Getting started with CPUI
This guide covers building a CPUI app from an empty project and the rules that govern how an
interface is written. The API documentation (cargo doc -p cpui --open) describes every widget
with an example. Layout is covered in layout.md, theming in
theming.md and custom widgets in widgets.md.
1. Setup
Section titled “1. Setup”CPUI requires Rust 1.89 or later. Add it to your project’s dependencies:
[dependencies]cpui = "0.1.1"Optional features add capabilities that not every application needs:
| Feature | Adds | Size |
|---|---|---|
png |
Bitmap::from_png for PNG images |
small |
jpeg |
Bitmap::from_jpeg for JPEG images |
small |
i18n |
Fluent translations with t!; see Internationalization |
about 0.1 MB |
word-break |
Line breaking between words in Thai, Lao, Khmer and Myanmar | about 1.1 MB |
[dependencies]cpui = { version = "0.1.1", features = ["png", "i18n"] }2. A first window
Section titled “2. A first window”An app is a type that implements App. Its fields hold the app’s data, and its ui method
describes the interface.
use cpui::{App, Options, Ui};
#[derive(Default)]struct Counter { count: u32,}
impl App for Counter { fn ui(&mut self, ui: &mut Ui<'_>) { ui.column().p(24).gap(12).children(|ui| { ui.heading(format_args!("Clicked {} times", self.count)); if ui.button("Add one").primary().clicked() { self.count += 1; } }); }}
fn main() -> Result<(), cpui::Error> { cpui::run(Options::new("Counter").size(360, 200), Counter::default())}cpui::run opens the window and runs until it closes. Options sets the window’s title,
size, minimum size, icon, appearance and fonts.
3. How the interface updates
Section titled “3. How the interface updates”CPUI has no widget objects to create, store and destroy. Each call to ui describes the entire
interface. The framework lays it out and redraws only the parts that differ from the previous
frame. This model is called immediate mode.
The following three rules apply:
- The app owns the state. The text of an input and the state of a switch are fields of your
struct, passed to widgets as
&mut. A changed field appears in the next frame. - Frames are drawn only when needed.
uiruns on input, on window resize, while a transition is running, and when a delayed tooltip is due. An idle app draws nothing. To request a frame from a background thread, use aWaker(section 8). For continuous animation, callui.request_repaint(). uimay run twice per frame. If a frame handles input or its layout changes, the framework runsuiagain before presenting the frame, so the frame reflects the latest state. Interaction results are reported only on the first run, so the code inif ui.button(…).clicked() { … }runs once. Other code inuimay run twice, so do not count or accumulate anything there that is unrelated to interaction.
4. Declaring widgets
Section titled “4. Declaring widgets”Each widget is created by a method on ui, followed by chained settings. The widget is placed in
the interface when a result is read from it or when the statement ends:
use cpui::{IconName, Ui};
fn toolbar(ui: &mut Ui<'_>, name: &mut String, saved: &mut bool) { ui.text("Name").muted(); ui.text_input(name).placeholder("Untitled"); let save = ui.button("Save").icon(IconName::Check).primary(); if save.disabled(name.is_empty()).clicked() { *saved = true; } ui.button("Help").ghost().tooltip("Opens the manual");}The following results are available on the widget and on its Response:
| Method | Meaning |
|---|---|
clicked() |
A click completed this frame, or Space or Enter activated the focused widget |
double_clicked() |
The click that completed this frame is a double click |
secondary_clicked() |
The secondary (right) button was pressed this frame; on touch screens, a long press |
hovered(), pressed() |
The pointer is over the widget; the primary button is held on it (pressed only on Response) |
changed() |
The widget’s value changed this frame (inputs, checkboxes, sliders and so on) |
submitted() |
Enter was pressed in a single-line text input |
response() |
Places the widget and returns its Response, for reading several results or rect(), the widget’s position after the previous frame’s layout |
This placement model has three consequences:
- A widget borrows
uiuntil it is placed, so declare it in a single statement. To use it afterwards, store.response()in a variable. - A closure that only declares widgets must have a block body:
|ui| { ui.text("…"); }. A closure cannot return a widget that borrows its own parameter. The same applies tomatcharms that declare widgets of different types. format_args!is accepted wherever text is expected. The text is copied when the widget is created.
5. Values and widgets
Section titled “5. Values and widgets”Form widgets take the value they edit as &mut. When the user changes it, the widget writes the
new value before returning. Use changed() to react to the change:
use cpui::{Appearance, Ui};
fn settings(ui: &mut Ui<'_>, volume: &mut f32, muted: &mut bool, look: &mut Appearance) { ui.checkbox(muted, "Mute"); if ui.slider(volume, 0.0..=1.0).disabled(*muted).changed() { // Hand the new volume to the player. } let looks = [ (Appearance::System, "System"), (Appearance::Light, "Light"), (Appearance::Dark, "Dark"), ]; if ui.select(look, &looks).changed() { ui.set_appearance(*look); }}| Widget | Method |
|---|---|
| Text | text, heading, title |
| Button | button, with primary, outline, ghost, danger, link, small, large, icon, loading |
| Checkbox, radio button, switch, toggle | checkbox(&mut bool, …), radio(&mut V, value, …), switch(&mut bool, …), toggle(&mut bool, …), toggle_group(&mut Option<V>) |
| Text input | text_input(&mut String), with placeholder, multiline, autofocus |
| Number input, slider | number_input(&mut N, range), slider(&mut N, range), range_slider(&mut N, &mut N, range), where N is any integer type, f32 or f64 |
| Select, tabs | select(&mut V, &[(value, text)]), combobox(&mut V, &[(value, text)]) that filters as you type, multi_combobox(&mut Vec<V>, &[(value, text)]) for multiple selection, tabs(&mut V, &[(value, text)]) |
| Dates | calendar(&mut Option<Date>), date_picker(&mut Option<Date>); for a range of days, calendar_range(&mut Option<(Date, Date)>), date_range_picker(&mut Option<(Date, Date)>) |
| Navigation | sidebar_item(&mut V, value, …), sidebar_label |
| Table | table(&columns, rows), with each row declared in show |
| Status | progress, badge, alert, spinner, kbd, empty, toast |
| Form | field with description, error and required; form |
| Popups | popover, dropdown_menu, context_menu, menu_item, dialog, drawer, alert_dialog |
| Menu bar | menu_bar, menu, with menu_item, menu_separator, menu_label |
| Groups | card, collapsible, accordion, separator |
| Image, icon | image, icon |
| Custom drawing | canvas, custom |
| Containers | row, column, flow, grid, scroll, container, overlay, list |
disabled(true) disables a widget. On a container, it disables all of its contents.
If the bound value is borrowed elsewhere at the same time, bind a local copy and write it back afterwards:
use cpui::{TableColumn, Ui};
struct Folder { names: Vec<String>, selected: Option<usize>,}
impl Folder { fn first(&self) -> Option<&String> { self.names.first() }
fn listing(&mut self, ui: &mut Ui<'_>) { let mut selected = self.selected; let first = self.first(); ui.text(format_args!("First: {}", first.map_or("none", String::as_str))); let columns = [TableColumn::new("Name")]; ui.table(&columns, self.names.len()).selected(&mut selected).show(|row, i| { row.text(&self.names[i]); }); self.selected = selected; }}To write a custom widget, implement Widget and place it with ui.add. Like built-in widgets,
it supports tooltips and the disabled state and provides the same results. See
widgets.md:
use cpui::{Response, Ui, Widget};
struct Tag(&'static str);
impl Widget for Tag { fn show(self, ui: &mut Ui<'_>) -> Response { ui.button(self.0).outline().small().response() }}
fn tags(ui: &mut Ui<'_>) { ui.flow().gap(8).children(|ui| { ui.add(Tag("Draft")).tooltip("Not published yet"); ui.add(Tag("Archived")); });}6. Lists and ids
Section titled “6. Lists and ids”Every widget has an id. The framework uses it to match a widget with the same widget in the previous frame, and stores focus, caret and scroll positions by id. An id is derived from the widget’s kind and its position among siblings of the same kind, so conditionally showing a text does not affect the input that follows it.
If list items can be added, removed or reordered, give each item a stable key with ui.key.
Without keys, deleting an item moves the focus and caret of the following items onto their
neighbors:
use cpui::Ui;
struct Todo { id: u64, text: String,}
fn todos(ui: &mut Ui<'_>, todos: &mut Vec<Todo>) { let mut removed = None; for todo in todos.iter_mut() { ui.key(todo.id, |ui| { ui.row().gap(8).children(|ui| { ui.text_input(&mut todo.text).placeholder("To do"); if ui.button("Delete").clicked() { removed = Some(todo.id); } }); }); } if let Some(id) = removed { todos.retain(|todo| todo.id != id); }}For many rows of equal height, use ui.list. It builds, lays out and draws only the visible
rows, so 100,000 rows cost the same as 100.
use cpui::Ui;
fn log(ui: &mut Ui<'_>, lines: &[String]) { ui.list(lines.len()).row_height(24).fill().show(|ui, row| { ui.text(&lines[row]).mono(); });}7. Popups
Section titled “7. Popups”The framework, not the app, tracks whether a popup is open, so the closure that declares a
popup’s content can use self freely. Popovers and context menus open from the widget they
belong to. Dialogs are opened by a key that the app chooses:
use cpui::Ui;
fn clear(ui: &mut Ui<'_>, items: &mut Vec<String>) { if ui.button("Clear").danger().clicked() { ui.open_dialog("clear"); } let confirmed = ui .alert_dialog("clear", "Clear the list?") .description("This cannot be undone.") .confirm("Clear") .danger() .confirmed(); if confirmed { items.clear(); }}| Popup | Opens | Closes |
|---|---|---|
popover(&trigger), placed with .side(Side::Top) and .align(Align::Center) |
A click on the trigger | A press outside, Escape, a chosen menu item, close_popover() |
dropdown_menu(&trigger) |
A click on the trigger | A chosen item, a click on the trigger, a press outside, Escape |
context_menu(&target) |
A secondary click on the target | A chosen item, a press outside, Escape |
dialog(key) |
open_dialog(key) |
close_dialog(key), Escape, a click on the scrim |
alert_dialog(key, title) |
open_dialog(key) |
Either button, Escape |
Popups are drawn in overlays above the rest of the interface, so their containers do not clip
them. ui.is_dialog_open(key) reports whether a dialog is open. A tooltip is a setting available
on every widget: .tooltip("…").
A toast is a message shown at an edge of the window. Call ui.toast once when an event occurs;
the framework keeps the message visible for a few seconds. A toast can carry a button that
triggers an action (see section 10):
use cpui::Ui;
cpui::actions! { enum Command { Undo = "undo", }}
fn delete(ui: &mut Ui<'_>, items: &mut Vec<String>, trash: &mut Vec<String>) { if ui.button("Delete").danger().clicked() { trash.extend(items.drain(..)); ui.toast("Deleted").action("Undo", Command::Undo); } if ui.action(Command::Undo) { items.extend(trash.drain(..)); }}To keep a toast visible until some work finishes, add .persistent(), give it a .key(…), and
close it with ui.close_toast(key) when the work is done.
Toasts appear at the bottom right, the newest in front, with the two previous toasts visible
behind it. When the pointer is over the stack, the stack expands to show each toast in full.
ui.set_toast_position(ToastPosition::TopCenter) moves toasts to another of the six positions.
8. Background work
Section titled “8. Background work”Run slow work on another thread and send the result back through a channel. When the work
finishes, call Waker::wake; the framework then runs ui for a new frame.
use std::sync::mpsc::{Receiver, channel};use std::time::Duration;
use cpui::{App, Ui};
#[derive(Default)]struct Loader { pending: Option<Receiver<String>>, text: Option<String>,}
impl App for Loader { fn ui(&mut self, ui: &mut Ui<'_>) { if let Some(text) = self.pending.as_ref().and_then(|r| r.try_recv().ok()) { self.text = Some(text); self.pending = None; } let loading = self.pending.is_some(); if ui.button("Load").loading(loading).clicked() { let (sender, receiver) = channel(); let waker = ui.waker(); std::thread::spawn(move || { std::thread::sleep(Duration::from_secs(1)); let _ = sender.send(String::from("Loaded")); waker.wake(); }); self.pending = Some(receiver); } match &self.text { Some(text) => ui.text(text), None => ui.text(if loading { "Loading…" } else { "Not loaded" }), }; }}9. Custom drawing
Section titled “9. Custom drawing”ui.canvas provides a Painter for drawing rectangles, lines, circles, icons and text. The
closure runs immediately and records the drawing commands. If they match the previous frame’s
commands, the canvas is not redrawn.
use cpui::{Sizing, Ui};
fn sparkline(ui: &mut Ui<'_>, values: &[f32]) { ui.canvas(Sizing::FILL, 48).paint(|p| { let (w, h) = p.size(); let accent = p.theme().accent; let step = w / (values.len().max(2) - 1) as f32; for (i, pair) in values.windows(2).enumerate() { let from = (i as f32 * step, h * (1.0 - pair[0])); let to = ((i + 1) as f32 * step, h * (1.0 - pair[1])); p.line(from, to, 2.0, accent); } });}Use ui.custom for the full drawing API (bitmaps, polygons, clipping) or for large content. Its
content is drawn directly by App::paint through a Frame. See Ui::custom for an example.
10. Windows
Section titled “10. Windows”ui.set_title(…)sets the title,ui.set_fullscreen(true)enters full screen, andui.quit()closes all windows and quits.ui.window_size()returns the size of the content area, which can be used to switch layouts in a narrow window.ui.dropped_files()returns the files dropped onto the window this frame.ui.files_hovering()reports whether files are being dragged over the window, for showing a drop hint.- File dialogs do not block the interface.
ui.show_file_dialog(key, dialog)opens a dialog after this frame. After the user chooses,ui.file_dialog_result(key)returns the paths in a later frame. A cancelled dialog produces no result.
use std::path::PathBuf;
use cpui::{FileDialog, Ui};
fn open_button(ui: &mut Ui<'_>, files: &mut Vec<PathBuf>) { if ui.button("Open…").clicked() { let dialog = FileDialog::open_files().filter("Images", &["png", "jpg"]); ui.show_file_dialog("open", dialog); } if let Some(paths) = ui.file_dialog_result("open") { files.extend_from_slice(paths); }}ui.key_pressed(Key::Escape)andui.shortcut_pressed(Shortcut::command('s'))detect keys. Keys handled by the focused widget or by an open popup are not reported. For example, Backspace in a text input deletes a character and does not also trigger the app’s own Backspace handling. For commands, prefer actions (below).ui.focus(&response)moves keyboard focus to a widget, such as a search box on Command + F.ui.copy_text(text)writes text to the system clipboard.- To keep a window open when the user closes it, for example to offer saving first, return false
from
App::close_requested(window). SeeAppfor an example.
Actions and key bindings
Section titled “Actions and key bindings”A command that has a key, a button and a menu item is declared once, as an action. A keymap
binds keys to actions. A button or menu item bound with .action(…) triggers the action, shows
its key, and is disabled when the action is disabled. ui.action(…) returns true once per
trigger, so the command is handled in one place.
use cpui::{App, Keymap, Options, Ui};
cpui::actions! { /// The editor's commands; the names are used in keymap text. enum Command { Save = "save", Rescan = "rescan", }}
struct Editor { busy: bool,}
impl App for Editor { fn ui(&mut self, ui: &mut Ui<'_>) { ui.set_action_enabled(Command::Rescan, !self.busy); if ui.action(Command::Save) { // Save. } if ui.action(Command::Rescan) { self.busy = true; } ui.row().gap(8).children(|ui| { ui.button("Save").primary().action(Command::Save); ui.button("Rescan").outline().action(Command::Rescan); }); }}
fn main() -> Result<(), cpui::Error> { let keymap = Keymap::new() .bind("mod-s", Command::Save) .bind("f5", Command::Rescan) .bind("mod-r", Command::Rescan); cpui::run(Options::new("Editor").keymap(keymap), Editor { busy: false })}- A key is written as modifiers and a key joined by
-.modis Command on macOS and iOS and Ctrl elsewhere.cmdexists only on Apple platforms, so one keymap can hold keys for each platform.ctrl,altandshifthave the same meaning on all platforms. SeeShortcut::parsefor key names. - Keys handled by the focused widget do not trigger actions, such as Command + A and character keys in a text input, or Enter on a focused button. While a modal dialog is open, keys trigger only actions queried inside it.
ui.trigger(a)triggers an action, for example from a command palette.ui.key_for(a)returns the action’s first key, for displaying hints.Command::all()lists all actions.- Users can reconfigure keys.
defaults.with_overrides::<Command>(&text)parses text such asrescan = f5, mod-r(one action per line,#for comments) and reports the lines it cannot use.keymap.to_text::<Command>()writes a keymap in the same format. The app decides where the file is stored.ui.set_keymap(keymap)applies a changed keymap immediately. - Text supplied by the framework, such as alert dialog buttons and the edit menu, comes from a
Locale, set withOptions::localeorui.set_locale. Internationalization covers the built-in languages and how to translate an application.
A menu bar lists the same actions. Each item shows its action’s key and is disabled when the action is disabled:
use cpui::Ui;
cpui::actions! { enum Command { Save = "save", Quit = "quit", }}
fn menus(ui: &mut Ui<'_>) { ui.menu_bar().children(|ui| { ui.menu("File").children(|ui| { ui.menu_label("Document"); ui.menu_item("Save").action(Command::Save); ui.menu_separator(); ui.menu_item("Quit").action(Command::Quit); }); });}Multiple windows
Section titled “Multiple windows”An app can open several windows, which share one App. Each window calls ui when it draws a
frame, and ui.window() identifies the window being built. Each window has its own focus, scroll
positions and transitions. After one window handles input, the others are rebuilt, so shared
state is consistent across windows. Themes and appearance apply to all windows.
use cpui::{App, Options, Ui, Window};
#[derive(Default)]struct Viewer { zoom: f64,}
impl App for Viewer { fn ui(&mut self, ui: &mut Ui<'_>) { let inspector = Window::named("inspector"); if ui.window() == inspector { ui.slider(&mut self.zoom, 0.5..=4.0); if ui.button("Close").clicked() { ui.close_window(); } return; } ui.text(format_args!("Zoom {:.0}%", self.zoom * 100.0)); if !ui.is_window_open(inspector) && ui.button("Inspector…").clicked() { ui.open_window(inspector, Options::new("Inspector").size(280, 160)); } }}ui.open_window(window, options)opens a window after this frame, or brings it to the front if it is already open.Window::named(key)identifies a window by name. For several windows of the same kind, useWindow::named(("document", number)).ui.close_window()closes the window being built. The program exits when the last window closes. The main window may close before the others.- Fonts and the glyph cache are shared by all windows, so the cost of an additional window is mainly its own presentation buffers.
- iOS and Android support a single window; requests to open more are ignored. The
windowsexample shows a complete program.
11. Testing
Section titled “11. Testing”An interface can be driven frame by frame without opening a window. Offscreen is the drawing
target, and Context holds the interface state and receives input.
use cpui::{App, Context, Offscreen, Theme, Ui};
struct Counter(u32);
impl App for Counter { fn ui(&mut self, ui: &mut Ui<'_>) { if ui.button("Add one").clicked() { self.0 += 1; } }}
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 = Counter(0); ctx.frame(&mut target, &mut app);
ctx.input.pointer = Some((10.0, 10.0)); ctx.input.pressed = true; ctx.frame(&mut target, &mut app); ctx.input.released = true; ctx.frame(&mut target, &mut app); assert_eq!(app.0, 1); Ok(())}target.snapshot() returns the pixels of the latest frame, for screenshot comparison.
ctx.accessibility() returns the accessibility tree, in which widgets can be found by role and
name.
12. Next steps
Section titled “12. Next steps”layout.md: sizing rules, alignment, wrapping, scrolling and overlays.theming.md: design tokens (a theme’s named values), light and dark appearance, and custom themes.widgets.md: three ways to write custom widgets.distribution.md: installers, code signing and notarization.- Examples:
cargo run --release -p cpui --example galleryshows every widget. Other examples arehello,list,canvas,themeandwindows. - API documentation:
cargo doc -p cpui --open. Every widget and type includes a runnable example.