Skip to content

Theming

A Theme holds the values that determine the look of an app: colors, font sizes, corner radii, spacing and transition durations. Every built-in widget takes its look from the theme. When your own styles also read from the theme, appearance switches and theme changes apply to the whole interface.

CPUI ships two themes, Theme::light() and Theme::dark(). Options::appearance selects the one a window uses:

Value Behavior
Appearance::System (default) Follows the system, and switches when the system switches
Appearance::Light Always light
Appearance::Dark Always dark

The window title bar follows the appearance. To switch at runtime, call ui.set_appearance (see section 5.3).

use cpui::{App, Appearance, Options, Ui};
struct Reader;
impl App for Reader {
fn ui(&mut self, ui: &mut Ui<'_>) {
ui.text("Always uses the dark theme.");
}
}
fn main() -> Result<(), cpui::Error> {
cpui::run(Options::new("Reader").appearance(Appearance::Dark), Reader)
}

Colors are named by role, not by hue. A background color and the color of text drawn on it form a pair, x and x_foreground:

Field Used for
background, foreground Window background; body text
surface Background of cards, inputs and anything else that sits above the window background
muted, muted_foreground Subtle background (hover, groups, panels); secondary text and placeholders
border, border_strong Dividers and borders; a stronger border on hover
accent, accent_hover, accent_active, accent_foreground The accent color, its hover and pressed states, and text on it
secondary, secondary_foreground Neutral buttons and their text
danger, danger_hover, danger_active, danger_foreground Destructive actions, their hover and pressed states, and text on them
success, success_foreground, warning, warning_foreground Success and warning states, for badges and alerts
ring Focus ring
shadow, scrim Shadows; the dimmed layer behind a dialog
tooltip, tooltip_foreground Tooltip background and text
selection Background of selected text

Other values:

Field Used for
font_size, font_size_sm, font_size_heading, font_size_title Font sizes of body text, notes, headings and titles: 13, 11, 17 and 22 on macOS, as in its own interface, and 14, 12, 18 and 24 elsewhere
radius_sm, radius, radius_lg Corner radii: rows, checkboxes and tags; buttons, inputs, menus and dropdowns; cards, dialogs and toasts
control_height_sm, control_height, control_height_lg Heights of small, regular and large buttons, inputs and selects (24, 32 and 40 by default). Tab bars use control_height
row_height Height of a row in a menu, dropdown, list, table, tree, sidebar or accordion (28 by default). Rows grow with larger text
spacing The base spacing. Other spacings are multiples of it
motion Duration of hover, toggle and other transitions, in seconds (0.12 by default). Expanding or collapsing a section and opening or closing a dialog take 5/3 of it. 0 disables transitions
disabled_opacity Opacity of disabled widgets, 0.5 by default

The horizontal padding inside a control is derived from spacing. Controls of the same size therefore have the same height and keep their proportions when the theme changes. Rows have 8 pixels of horizontal padding on each side.

Every widget that accepts keyboard focus shows the same 3-pixel ring, following the widget’s corners. On a checkbox, radio button or switch, the ring surrounds the box, not the label.

ui.theme() returns a copy of the current theme. Call it before starting a chain of settings, because the chain borrows ui:

use cpui::Ui;
fn notice(ui: &mut Ui<'_>, text: &str) {
let t = ui.theme();
let tint = t.background.mix(t.accent, 0.12);
let notice = ui.row().w_fill().p(t.spacing * 1.5).gap(t.spacing).bg(tint);
notice.border(1, t.accent).rounded_md().children(|ui| {
ui.text(text).text_color(t.accent);
});
}

For a color between two theme colors, blend them with Color::mix instead of writing a literal color. The background above then adapts to the theme: in the dark theme it becomes a faint accent over the dark background.

The following methods read the theme directly:

  • Text: .muted() uses the secondary text color and .text_sm() the note size. ui.heading and ui.title use the heading and title sizes.
  • Shape: .rounded_md() and .shadow_md() use the theme’s radius and shadow.
  • Badges and alerts: .success(), .warning() and .danger().
  • Containers: .bordered() adds the standard border; .bg_muted() and .bg_surface() set the muted and surface backgrounds.

On a canvas, read the theme with Painter::theme:

use cpui::{Rect, Ui};
fn meter(ui: &mut Ui<'_>, fraction: f32) {
ui.canvas(160, 8).paint(|p| {
let (w, h) = p.size();
let (track, fill) = (p.theme().muted, p.theme().accent);
p.rounded(Rect::new(0.0, 0.0, w, h), h / 2.0, track);
p.rounded(Rect::new(0.0, 0.0, w * fraction, h), h / 2.0, fill);
});
}
Widget Theme values
Button (default) secondary, secondary_foreground, radius
Primary button accent, accent_hover, accent_active, accent_foreground
Outline and ghost buttons surface, muted, border_strong, foreground
Danger button danger, danger_hover, danger_active, danger_foreground
Text input surface, border, border_strong (hover), accent (caret), selection
Checkbox, switch accent, accent_foreground, border_strong, radius_sm
Slider, progress bar accent, muted, surface
Badge, alert muted and foreground, or a faint tint of accent, success, warning or danger with that color as text
Card surface, border, radius_lg, shadow
Popover, dialog surface, border, radius_lg, shadow; dialogs also use scrim
Tooltip tooltip, tooltip_foreground
Text, icon foreground by default, or the color set on their container
Focus ring (all widgets) ring

A disabled widget is faded as a whole and has no colors of its own.

An app provides a light theme and a dark theme. CPUI uses the one that matches the current appearance.

5.1 Accent color, font size, radius and density

Section titled “5.1 Accent color, font size, radius and density”

Each common adjustment has a dedicated method:

  • with_base_color(BaseColor::Slate) changes the gray palette: backgrounds, text, borders and muted fills. The options are Neutral, Stone, Zinc (default), Gray and Slate; a dark theme uses the dark shades of the chosen palette.
  • with_accent(color) changes the accent color. The hover, pressed, focus ring and selection colors are derived from it. Text on the accent is black or white, depending on the accent’s brightness.
  • with_font_size(size) sets the body font size, the same on every platform. The note, heading and title sizes scale by the same ratio, to whole pixels. Control and row heights are made for text up to 14 px: they grow with larger text and stay with smaller.
  • with_radius(radius) sets the control radius and derives the small and large radii from it. 0 gives square corners.
  • compact() reduces control and row heights by about an eighth and spacing by a quarter. Font sizes are unchanged. It is intended for tools that display dense content.

Text is a size smaller on macOS, so a layout that only just fits there can wrap or truncate on Windows and Linux. Try it at 14 px, or set with_font_size to use one size everywhere.

use cpui::{App, Color, Options, Theme, Ui};
struct Notes;
impl App for Notes {
fn ui(&mut self, ui: &mut Ui<'_>) {
ui.button("New");
}
}
fn main() -> Result<(), cpui::Error> {
let accent = Color::hex(0x16a34a);
let tune = |t: Theme| t.with_accent(accent).with_font_size(15.0).with_radius(8.0).compact();
let (light, dark) = (tune(Theme::light()), tune(Theme::dark()));
cpui::run(Options::new("Notes").themes(light, dark), Notes)
}

For an app with a single look, use Options::theme(theme). That theme is used for both appearances, and the appearance setting has no effect on the interface.

A theme is a plain struct; set any other value through its fields:

use cpui::{Color, Theme};
let rounded = Theme {
radius: 10.0,
radius_lg: 16.0,
muted: Color::hex(0xeef2ff),
motion: 0.0,
..Theme::light().with_accent(Color::hex(0x4f46e5))
};
assert_eq!(rounded.spacing, Theme::light().spacing);
assert!(!rounded.is_dark());

If you set the accent field directly, also set accent_hover, accent_active, ring and selection; otherwise hover and focus keep the old color. with_accent updates all of them.

An app can change the appearance and the theme at runtime. The current frame is rebuilt with the new theme before it is displayed, and colors fade over twice the motion duration (sizes change immediately). The change applies to every window of the app.

use cpui::{Appearance, Color, Theme, Ui};
struct Look {
appearance: Appearance,
green: bool,
}
fn look(ui: &mut Ui<'_>, look: &mut Look) {
let options = [
(Appearance::System, "System"),
(Appearance::Light, "Light"),
(Appearance::Dark, "Dark"),
];
if ui.select(&mut look.appearance, &options).changed() {
ui.set_appearance(look.appearance);
}
if ui.switch(&mut look.green, "Green accent").changed() {
let accent = Color::hex(if look.green { 0x16a34a } else { 0x2563eb });
let light = Theme::light().with_accent(accent);
let dark = Theme::dark().with_accent(accent);
ui.set_themes(light, dark);
}
}

ui.set_theme(theme) uses one theme for both appearances. ui.theme().is_dark() reports whether the current theme is dark, for example to choose a matching image.

The theme example (cargo run --release -p cpui --example theme) is a complete program. It switches the appearance, accent color, font size, radius and density; its color swatches are a custom-drawn widget.

A Context driven directly (in tests, for screenshots or from a custom event loop) provides methods with the same names. It must also be told whether the system is in dark mode:

use cpui::{Appearance, Color, Context, Theme};
let accent = Color::hex(0x16a34a);
let mut ctx = Context::new(Theme::light());
ctx.set_themes(
Theme::light().with_accent(accent),
Theme::dark().with_accent(accent),
);
ctx.set_system_dark(true);
assert!(ctx.theme().is_dark());
ctx.set_appearance(Appearance::Light);
assert!(!ctx.theme().is_dark());

The interface uses the system font by default. Options::font adds a font to the fallback list. When a font lacks a character, the next font in the list is used:

use cpui::{FontSpec, Options};
let options = Options::new("Editor")
.font(FontSpec::Name("Menlo".into()))
.font(FontSpec::Path("fonts/Custom.ttf".into()));

A font is specified in one of four ways:

  • FontSpec::Name finds an installed font by its name or family name.
  • FontSpec::Path loads a font file.
  • FontSpec::Bytes uses a font embedded in the program.
  • FontSpec::Generic selects the system font of a generic family, such as GenericFamily::Serif.

Options::mono_font does the same for monospaced text, which is drawn with ui.text(…).mono().

Text has nine named weights, from .font_thin() to .font_black(). For any other weight, use .font_weight(FontWeight(650)):

use cpui::Ui;
fn weights(ui: &mut Ui<'_>) {
ui.text("Caption").font_light();
ui.text("Label").font_medium();
ui.text("Title").font_semibold();
ui.text("Total").font_bold();
}

CPUI takes weights from the font itself where possible: from the weight axis of a variable font, or from the closest face in the same family. If the font cannot reach the requested weight, CPUI thickens the strokes to make up the difference; it never thins them. Italic text uses the font’s italic face, or slants the glyphs if the font has none.

6.1 Weights, languages and fonts for other kinds of text

Section titled “6.1 Weights, languages and fonts for other kinds of text”

For settings the two methods above do not cover, pass a complete FontSet to Options::fonts:

use cpui::{FontSet, FontSpec, FontStack, FontWeight, FontWeights, Options, Ui};
let mut fonts = FontSet::default();
fonts.ui.push(FontSpec::Name("Inter".into()));
fonts.weights = FontWeights::uniform(FontWeight(450));
fonts.cjk_language = Some("ja".into());
let body = fonts.add(FontStack::proportional(vec![FontSpec::Name("Georgia".into())]));
let options = Options::new("Reader").fonts(fonts);
let article = move |ui: &mut Ui<'_>| {
ui.text("Set in the body font").font(body);
};
  • weights sets the weight of regular text, from 100 to 900, with separate values for the interface font and the monospaced font. Weights set on text are offsets from this value: with 450 as above, .font_bold() draws at 750.
  • cjk_language selects the glyph forms of Han characters, some of which differ between Chinese, Japanese and Korean. If unset, it follows the system language.
  • FontSet::add registers a FontStack, a list of fonts for an additional kind of text, such as the body of a document. It returns a FontKind that selects those fonts. FontKind::Math is built in and draws formulas.

A text widget selects its kind with .font(kind). A canvas draws and measures text with a Font, which combines the kind, size and style: p.text(Font::new(body, 16.0).bold(), at, text, color).

Hover, switch, checkbox and focus changes transition over the motion duration. During a transition, only the affected widget is redrawn. Set motion to 0 to disable all transitions.

In custom widgets, ui.animate(key, target) returns a value that moves toward the target at the same pace:

use cpui::{Rect, Ui};
fn reveal(ui: &mut Ui<'_>, open: &mut bool) {
ui.checkbox(open, "Show progress");
let t = ui.animate("reveal", if *open { 1.0 } else { 0.0 });
ui.canvas(200, 8).paint(|p| {
let accent = p.theme().accent;
p.rect(Rect::new(0.0, 0.0, 200.0 * t, 8.0), accent);
});
}