Quickstart
How to go from zero to a running mirui application on desktop, mobile, WebAssembly, or embedded hardware while sharing the same UI model.
This guide is the long-form companion to the README and the docs.rs crate-level introduction. It expects familiarity with cargo and basic Rust, plus an SPI datasheet reading habit if you target an MCU.
Toolchain prerequisites
Stable Rust (1.85 or newer) is enough for the desktop path:
rustup default stable
rustup updateThe ESP32-C3 path also wants a riscv32imc target and the espflash flasher. Both work on stable:
rustup target add riscv32imc-unknown-none-elf
cargo install espflashThe desktop and ESP32-C3 targets in the workspace template use stable Rust; browser and mobile targets need their respective toolchains.
Desktop SDL
The SDL backend links SDL2 dynamically; install the runtime and headers with the platform package manager:
brew install sdl2-compat sdl3 # macOS
apt-get install libsdl2-dev # Debian / UbuntumacOS desktop builds require macOS 11 or newer. Use sdl2-compat with SDL 3.4.14 or newer for high-resolution trackpad scrolling. Mirui enables native momentum on this runtime; the original SDL2 runtime does not support that setting. The Rust sdl2 crate version is independent of the native library version. After upgrading the native libraries, restart the application.
Both SDL backends enable renderer command batching by default. An explicit SDL_RENDER_BATCHING environment variable or SDL hint overrides this default. Readback synchronizes queued rendering; exclude snapshots from normal frame-time measurements.
The sdl-gpu backend exposes driver, multisampling, presentation and window options:
use mirui::surface::sdl_gpu::{SdlGpuConfig, SdlGpuDriver, SdlGpuSurface, SdlWindowMode};
let surface = SdlGpuSurface::with_config("Demo", 640, 480, SdlGpuConfig {
driver: SdlGpuDriver::OpenGl { samples: 4 },
window: SdlWindowMode::Windowed { resizable: true },
vsync: true,
})?;
println!("Renderer: {}", surface.renderer_name());
# Ok::<(), mirui::surface::sdl_gpu::SdlGpuError>(())SdlGpuSurface::new(title, width, height) uses windowed OpenGL with 4× MSAA and vsync. Both constructors return Result. Explicit OpenGl and OpenGles2 selections do not fall back to another renderer; Auto lets SDL select an accelerated driver without a GL multisampling request. GL samples: 0 disables MSAA, 1 is invalid, and larger values request at least that sample count. Unsupported settings return an error rather than silently reducing quality. FullscreenDesktop uses the desktop display mode; requested window dimensions do not override its actual size. Window geometry and pointer coordinates follow the current logical size, including resize and display changes.
Single-sample windows with render-target support retain their GPU pixels for partial redraws. Multisampled windows keep window MSAA and redraw the full frame when damaged; both paths remain idle when unchanged. Retained target memory and composite fallback requirements are described in backend behavior.
SdlGpuFactory::new().with_texture_cache_budget(bytes) and WgpuRendererFactory::new().with_texture_cache_budget(bytes) configure retained image uploads, separately from glyph caches and target-edit buffers. Both default to 16 MiB, allocated on demand; zero disables retention and oversized textures still draw without being cached. The SDL budget estimates four pixel bytes per texel, including formats that the driver may expand; driver allocation overhead is not included. Static textures and explicitly revised contents can be reused. Borrowed or mutable textures remain transient unless the producer supplies a content revision; reusing a buffer with changed pixels requires a new revision.
Create a fresh project:
cargo new hello-mirui
cd hello-miruiCargo.toml:
[package]
name = "hello-mirui"
version = "0.1.0"
edition = "2024"
[dependencies]
mirui = { version = "0.57", features = ["sdl"] }src/main.rs:
use mirui::prelude::*;
use mirui::surface::sdl::SdlSurface;
use mirui::ui::widgets::{ParagraphStyle, Text};
#[compose]
fn build_ui() {
ui! {
Column (grow: 1.0) {
View (
bg_color: ColorToken::Primary,
text_color: ColorToken::OnPrimary,
height: 40,
border_radius: 8,
padding: Padding::all(10)
) {
Text ("Hello mirui!")
}
View (bg_color: ColorToken::SurfaceVariant, grow: 1.0)
Text ("ECS + DSL", height: 30, paragraph: ParagraphStyle::label())
}
};
}
fn main() {
let backend = SdlSurface::new("hello mirui", 480, 320);
let mut app = App::new(backend);
app.with_default_widgets().with_default_systems();
let root = app.spawn_root().id();
app.compose(root, build_ui());
app.run();
}Run it:
cargo runA 480x320 window appears with a blue header, a darker content area, and a footer strip — three widgets stacked inside a column container.
If cargo run fails to find libSDL2.dylib on macOS (Apple Silicon), add the Homebrew lib path:
export LIBRARY_PATH="/opt/homebrew/lib:$LIBRARY_PATH"Optional audio
Use sdl-audio on desktop or web-audio in the browser. AudioPlugin owns one fixed-capacity command bus and exposes AudioHandle through app.audio(). Bare-metal applications can fill a caller-owned PCM buffer with AudioMixer or implement AudioSink for an I2S/DMA driver.
use mirui::app::plugins::AudioPlugin;
use mirui::audio::{AudioBank, AudioTone, SdlAudioSink, Waveform};
static AUDIO: AudioBank = AudioBank::new(&[]);
app.add_plugin(AudioPlugin::new(SdlAudioSink::new(), &AUDIO));
if let Some(audio) = app.audio() {
audio.tone(AudioTone::new(72, Waveform::Sine, 240, 190));
}audio.state() returns a snapshot. audio.state_signal() returns the same read-only state as a reactive source; call get() inside a ui! property to follow mute and output changes. Cloned handles stop accepting commands after the app is dropped. AudioBus<N> remains available for standalone use.
ESP32-C3 embedded
The embedded path takes a hardware kit, an SPI display, and a USB cable. The shape of an mirui ESP project is small — no_std main, esp-hal peripherals, and a FramebufSurface whose flush closure speaks SPI to the panel — but the BSP wiring (clock setup, SPI mode + DMA buffers, ST7735/ST7789/GC9A01 init sequence, panel reset) is dozens of lines and moves with each esp-hal release.
Rather than reproduce that wiring here and let it bit-rot, the canonical reference is the mirui-examples project, which this guide tracks. Start there:
git clone https://github.com/W-Mai/mirui-examples
cd mirui-examples/examples/esp32c3-animation
cargo build --release --no-default-features --features=demo-threebodyThe esp32c3-animation crate's src/board.rs carries the SPI + ST7735 driver, src/main.rs ties it into App::new(FramebufSurface::…), and Cargo.toml pins compatible esp-hal / esp-alloc / esp-bootloader-esp-idf versions. Copy that repository, point board.rs at the target panel's pinout, and replace the demo widgets with an application ui! tree.
Once it builds, flash with:
espflash flash --monitor target/riscv32imc-unknown-none-elf/release/mirui-esp32c3The piece that's universal across boards is the mirui side:
let backend = FramebufSurface::with_format(
W, H,
mirui::render::texture::ColorFormat::RGB565Swapped, // or RGB565
|bytes: &[u8], area: mirui::types::PhysicalRect| {
// Push `bytes` to the LCD over SPI for the window described by `area`.
},
);
let mut app = App::new(backend);
app.with_default_widgets().with_default_systems();
// app.spawn_root(), build the ui! tree, app.run() — same as the desktop hello.ColorFormat::RGB565Swapped is the byte order most ST7735/ST7789 panels expect when the host MCU is little-endian; use RGB565 if the panel takes the bytes the other way around. mirui's Surface trait docs cover the rest of the contract — display_info, flush, poll_event, persistence — and which to override for a custom backend.
Cargo workspace
When the same UI code should drive both a desktop window and an MCU panel, put the UI in a shared library crate and let one binary crate per target consume it. mirui ships a Cargo workspace template that sets this up; you can also build it by hand. The layout below shows the desktop and ESP32-C3 targets only. The generated workspace also includes WebAssembly, Android, and iOS targets.
Layout:
my-app/
├── Cargo.toml # [workspace] members = ["app", "targets/*"]
├── app/ # shared UI library, std/no_std dual
│ ├── Cargo.toml
│ └── src/lib.rs
└── targets/ # one crate per target, glob-matched
├── desktop/ # SDL bin
│ ├── Cargo.toml
│ └── src/main.rs
└── esp32c3/ # ESP32-C3 bin
├── Cargo.toml
├── .cargo/config.toml
├── rust-toolchain.toml
└── src/main.rsRoot Cargo.toml:
[workspace]
resolver = "2"
members = ["app", "targets/*"]
default-members = ["app", "targets/desktop"]The targets/* glob means a new target crate dropped into targets/<name>/ is picked up without editing the workspace manifest. Plain cargo check at the root checks the shared app and desktop target; build each other target with its own platform toolchain and target triple.
app/Cargo.toml:
[package]
name = "app"
version = "0.1.0"
edition = "2024"
[features]
default = []
std = ["mirui/std"]
[dependencies]
mirui = { version = "0.57", default-features = false, features = ["quad-aa"] }app/src/lib.rs:
#![cfg_attr(not(feature = "std"), no_std)]
extern crate alloc;
use mirui::prelude::*;
use mirui::ui::widgets::Text;
#[compose]
pub fn build_ui() -> Entity {
ui! {
View (bg_color: ColorToken::Surface) {
Text ("Hello mirui!", text_color: ColorToken::OnSurface)
}
}
}targets/desktop/Cargo.toml enables sdl on mirui and std on app; targets/esp32c3/Cargo.toml keeps both at default-features = false and adds the esp-hal stack. Each target's main.rs opens a Surface, constructs App, then registers the shared composition with app.compose(root, app::build_ui()).
Adding a new target
The workspace is meant to grow. To add ESP32-S3, RP2040, STM32, or any other MCU:
- Copy an existing target as a starting point:
cp -r targets/esp32c3 targets/esp32s3. - Update the new crate's
Cargo.tomlwith the right[package].nameand BSP dependencies. - Update
.cargo/config.tomlandrust-toolchain.tomlfor the new target triple and linker script. - Adjust
src/main.rsto talk to the new chip's clocks, SPI, and panel.
Build it with cargo build -p esp32s3. Workspace membership is automatic — the glob picks the new directory up on the next cargo invocation.
WGPU configuration
WgpuSurface::new and MobileWgpuSurface::new return initialization errors. Their with_config constructors accept the same device and presentation settings:
use mirui::surface::wgpu_surface::{WgpuConfig, WgpuSurface, PresentMode, PowerPreference};
let surface = WgpuSurface::with_config("Demo", 640, 480, WgpuConfig {
present_mode: Some(PresentMode::Fifo),
power_preference: PowerPreference::LowPower,
maximum_frame_latency: 2,
samples: 4,
})?;The default presentation preference is Mailbox, Immediate, then Fifo; explicit modes must be supported, while AutoVsync and AutoNoVsync retain WGPU's fallback behavior. Frame latency must be nonzero and is a platform-clamped hint, not a guaranteed queue depth. MSAA defaults to 4 samples on desktop and 1 on mobile; 1 disables it, and unsupported counts return an error. Window restoration reuses the selected device and configuration. Render pipelines use the actual attachment sample count.
For a configured mobile host, use MobileHost::new(title, move |window| MobileWgpuSurface::with_config(window, config), build_app). The existing wgpu_mobile_host(title, build_app) uses defaults. SoftwareUploadConfig::gpu exposes the same device and presentation configuration for software-upload hosts; it requires one sample because the uploaded image has already been rasterized. Its existing render_scale and framebuffer_budget_bytes control CPU pixels independently.
Presentation pacing is separate from logical updates: install FrameRateCapPlugin with a clock plugin to cap ticks, including idle or failed frames. Without it, native hosts remain uncapped. SDL uses SdlGpuConfig::vsync or SdlSurface::new_with_vsync; Web uses browser animation frames. Neither presentation mode nor a frame cap reduces rendering resolution. with_texture_cache_budget on either GPU factory limits retained image uploads, not the window target or glyph cache. Capture and readback can synchronize GPU work and should be excluded from ordinary frame-time measurements.
Android and iOS
The android and ios generator templates ask for a rendering path. wgpu submits mirui draw commands directly to the platform WGPU surface. sw retains one caller-budgeted RGBA framebuffer, rasterizes with the software backend, uploads dirty regions, and uses WGPU only for presentation. Both paths keep the App, ECS world, and reactive state alive across native suspend and resume while recreating the platform surface.
cargo generate --git https://github.com/W-Mai/mirui-templates.git templates/android --name hello-mirui-android
cargo generate --git https://github.com/W-Mai/mirui-templates.git templates/ios --name hello-mirui-iosAndroid uses a NativeActivity entry point, builds Rust through cargo-ndk, and packages the application with the included Gradle wrapper. iOS generates a Rust static library plus a minimal Xcode application host for simulator and device targets. The generated READMEs contain the required Rust targets and launch commands.
iOS builds require iOS 14 or newer. Set the application's deployment target accordingly; standalone Cargo builds can use IPHONEOS_DEPLOYMENT_TARGET=14.0.
The iOS application's Info.plist declares one application scene. MobileHost attaches the Winit window to that scene before creating or resuming either rendering path. No custom scene delegate or additional application loop is required.
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
<false/>
<key>UISceneConfigurations</key>
<dict>
<key>UIWindowSceneSessionRoleApplication</key>
<array>
<dict>
<key>UISceneConfigurationName</key>
<string>Default Configuration</string>
</dict>
</array>
</dict>
</dict>Mobile applications retain their world and renderer state across suspend and resume. Touch contacts are mapped to stable compact pointer IDs for their full lifetime, and a focused TextInput opens the native software keyboard while preserving UTF-8 text delivered by native input events. Custom editors attach TextEditing and register its View to share editing, focus, and native keyboard behavior.
Software-rendered hosts use native device density within an explicit framebuffer budget. Resize admission is transactional: an allocation or budget failure leaves the last valid framebuffer active. WGPU acquisition recovers once from outdated or lost surfaces and skips transient timeout or occlusion frames. Native memory warnings release reconstructible text, path-placement, offscreen, software-raster, and GPU caches while preserving application state; plugins can release their own caches through Plugin::on_memory_warning.
app.spawn_root() keeps children inside the current safe area by default; fullscreen content can opt out with app.spawn_root().ignore_safe_area().id(). iOS renders against the full drawable while publishing logical safe-area insets separately, so edge-to-edge backgrounds and inset content share one coordinate space.
Skip the boilerplate
The same templates this guide walks through by hand are published as a cargo-generate template repository. After installing the tool:
cargo install cargo-generateGenerate a project from any of the templates:
# Desktop; choose WGPU or SDL when prompted
cargo generate --git https://github.com/W-Mai/mirui-templates.git templates/desktop --name hello-mirui
# Single-target ESP32-C3
cargo generate --git https://github.com/W-Mai/mirui-templates.git templates/esp32c3 --name hello-mirui-esp32c3
# Multi-target Cargo workspace (shared app + desktop, WebAssembly, ESP32-C3, Android, and iOS targets)
cargo generate --git https://github.com/W-Mai/mirui-templates.git templates/workspace --name my-app
# Browser Canvas 2D
cargo generate --git https://github.com/W-Mai/mirui-templates.git templates/wasm --name hello-mirui-web
# Android NativeActivity; choose WGPU or software rendering when prompted
cargo generate --git https://github.com/W-Mai/mirui-templates.git templates/android --name hello-mirui-android
# iPhone and iPad Xcode project; choose WGPU or software rendering when prompted
cargo generate --git https://github.com/W-Mai/mirui-templates.git templates/ios --name hello-mirui-ios--name supplies the generated package name. The generator asks for the mirui version and, where applicable, the rendering backend, then fills the Cargo manifests and source files. The wasm template uses the shipped web-canvas Surface and runs through trunk.
Where to go next
You have a running mirui app. The next steps depend on what you want to build:
- Add a custom widget — inspect the built-in widgets and Gallery compositions for rendering, theme integration, typed properties, and animation contracts.
- Compose a text editor —
text-editing.mdcombines a custom Component, TextEditing, TextInput, and a shared document owned by an application Model. - Drive an LCD, touch IC, or 2D DMA engine —
porting.mdwalks throughFramebufSurfaceSPI windows, customSurface+FramebufferAccessdouble buffering, touch/rotary/key events, andcompose_backend!hardware acceleration. - React to state changes declaratively —
state-management.mdcovers registered models, model-backed components, typed Views,Signal<T>,Computed<T>,Effect, and DSL bindings. - Handle input and notifications —
events.mdcovers typed callbacks, delivery order, and event capacity;widget-events.mdlists widget input and notifications. - Persist user state across runs — the
persistence_settingsGallery demo saves Model preferences while keeping preview expansion local to the session. See Persistence for field declarations and storage configuration.
The working examples in gallery/examples/ and mirui-examples exercise the same public APIs across desktop, browser, and embedded targets.