Skip to content
Development

Porting a display and input backend ​

mirui separates the scene graph, layout engine, and reactive models from platform hardware through four orthogonal boundaries:

  • Surface: reports display metrics (DisplayInfo), drains input events (InputEvent), and flushes damaged physical-pixel rectangles (PhysicalRect);
  • FramebufferAccess & RendererFactory: exposes single or rotating CPU framebuffers to SwRendererFactory (with automatic scroll pixel-copy and dirty-region mirroring) or binds a custom GPU renderer;
  • RenderEngine & compose_backend!: routes supported operations to 2D DMA blitters (STM32 DMA2D, NXP PXP) or 2.5D vector GPUs (VeriSilicon VG-Lite, with runtime vg_lite_query_feature capability checks) while falling back to the software rasterizer only for unsupported features;
  • set_clock, Storage, and AudioSink: connects bare-metal timers, flash key-value stores, and I2S/DMA audio buffers on no_std.
Surface & Dirty Window
recipes.rs143 lines
2208#[model]
2209pub struct SurfaceProbe {
2210 #[observe]
2211 pub rgb565: bool,
2212 #[observe]
2213 pub zone: u8,
2214 #[observe]
2215 pub rotary: i16,
2216}
2217
2218impl Default for SurfaceProbe {
2219 fn default() -> Self {
2220 Self {
2221 rgb565: true,
2222 zone: 0,
2223 rotary: 0,
2224 }
2225 }
2226}
2227
2228#[model]
2229impl SurfaceProbe {
2230 pub fn tap_touch(&mut self) {
2231 self.zone = (self.zone + 1) % 3;
2232 }
2233
2234 pub fn turn_rotary(&mut self) {
2235 self.rotary = self.rotary.wrapping_add(1);
2236 self.zone = (self.zone + 1) % 3;
2237 }
2238
2239 pub fn toggle_format(&mut self) {
2240 self.rgb565 = !self.rgb565;
2241 }
2242
2243 #[observe]
2244 pub fn rect(&self) -> (u16, u16, u16, u16) {
2245 match self.zone {
2246 0 => (16, 14, 108, 34),
2247 1 => (88, 30, 124, 38),
2248 _ => (12, 10, 216, 58),
2249 }
2250 }
2251
2252 #[observe]
2253 pub fn transfer_bytes(&self) -> u32 {
2254 let (_, _, w, h) = self.rect();
2255 let bpp = if self.rgb565 { 2_u32 } else { 4_u32 };
2256 u32::from(w) * u32::from(h) * bpp
2257 }
2258}
2259
2260#[compose]
2261fn porting_inspector_scene(probe: model!(SurfaceProbe)) {
2262 ui! {
2263 Column (
2264 grow: 1.0,
2265 padding: Padding::all(16),
2266 justify: JustifyContent::SpaceBetween,
2267 text_color: ColorToken::OnSurface
2268 ) {
2269 Row (height: 30, column_gap: 6, align: AlignItems::Center) {
2270 Button (
2271 "Touch Tap",
2272 grow: 1.0,
2273 height: 28,
2274 font_size: 12,
2275 border_radius: 7,
2276 normal_color: ColorToken::Primary,
2277 pressed_color: ColorToken::Secondary,
2278 text_color: ColorToken::OnPrimary
2279 ) on Tap { probe.tap_touch(); }
2280 Button (
2281 "Rotary +1",
2282 grow: 1.0,
2283 height: 28,
2284 font_size: 12,
2285 border_radius: 7,
2286 normal_color: ColorToken::SurfaceVariant,
2287 pressed_color: ColorToken::Outline,
2288 text_color: ColorToken::OnSurface
2289 ) on Tap { probe.turn_rotary(); }
2290 Button (
2291 text: ${ if probe.rgb565() { "RGB565 (2B)" } else { "RGBA8 (4B)" } },
2292 grow: 1.0,
2293 height: 28,
2294 font_size: 12,
2295 border_radius: 7,
2296 normal_color: ColorToken::SurfaceVariant,
2297 pressed_color: ColorToken::Outline,
2298 text_color: ColorToken::OnSurface
2299 ) on Tap { probe.toggle_format(); }
2300 }
2301 View (
2302 height: 82,
2303 bg_color: ColorToken::SurfaceVariant,
2304 border_radius: 10,
2305 clip_children: true
2306 ) {
2307 View (
2308 position: Position::Absolute,
2309 left: ${ i32::from(probe.rect().0) },
2310 top: ${ i32::from(probe.rect().1) },
2311 width: ${ Dimension::px(i32::from(probe.rect().2)) },
2312 height: ${ Dimension::px(i32::from(probe.rect().3)) },
2313 padding: Padding::all(6),
2314 bg_color: ColorToken::Secondary,
2315 border_width: 2,
2316 border_color: ColorToken::Primary,
2317 border_radius: 6
2318 ) {
2319 Text (
2320 text: ${
2321 let (x, y, w, h) = probe.rect();
2322 format_args!("flush({x},{y} {w}x{h})")
2323 },
2324 capacity: 32,
2325 height: 18,
2326 font_size: 12,
2327 text_color: ColorToken::OnSecondary
2328 )
2329 }
2330 }
2331 Text (
2332 text: ${
2333 let (x, y, w, h) = probe.rect();
2334 format_args!(
2335 "CASET {x}..{} · RASET {y}..{} · {} B · rotary #{}",
2336 x + w - 1,
2337 y + h - 1,
2338 probe.transfer_bytes(),
2339 probe.rotary()
2340 )
2341 },
2342 capacity: 64,
2343 height: 18,
2344 font_size: 12,
2345 text_color: ColorToken::OnSurfaceVariant,
2346 paragraph: ParagraphStyle::label().with_align(TextAlign::Start)
2347 )
2348 }
2349 };
2350}
Loading preview…

Click Touch Tap or Rotary +1 to move the damaged PhysicalRect window, or toggle RGB565 (2B) / RGBA8 (4B) to see how flush(area) computes the exact CASET / RASET column/row bounds and transfer byte count.

EMBEDDED ISR · DMA · VSYNC TIMELINEHardware interrupts, D-Cache barriers, DMA transfer & VSync flip
01Touch / Rotary ISR & Peripherals
02UI Main Thread (mirui App)
03DMA Engine & Panel Scanout

Touch IC pulls INT low or rotary encoder steps. ISR pushes raw sample into a lock-free SPSC ring buffer and wakes the UI thread (`sev` / RTOS semaphore).

IRQ_RING.push_from_isr(RawIrqEvent::RotaryStep(1)); cortex_m::asm::sev();ISR never touches App or World directly

Choosing a porting tier ​

Pick the lightest tier that matches your display controller and memory architecture:

TierTypical TargetWhat You ImplementFramebuffer OwnershipInput & Hardware Acceleration
Tier 1 · Callback FramebufferSPI / QSPI / I2C LCD (ST7789, ST7735, GC9A01, ILI9341)Pass one |buf, area: PhysicalRect| closure to FramebufSurfaceFramebufSurface allocates one Vec<u8> (W × H × bpp)Feed events directly or upgrade to Tier 2 when adding a touch IC
Tier 2 · Custom Surface + FramebufferAccessStatic BSS DMA buffers, RTOS (NuttX, Vela, Zephyr, FreeRTOS), Linux fbdev / DRMSurface + FramebufferAccess (framebuffer & optional all_buffers)Caller-owned static array, mmap region, or DMA scanout ringFull poll_event() queue (Pointer, Rotary, Key, Wheel) + automatic multi-buffer dirty mirroring
Tier 3 · 2D Blitter / VG-Lite Vector GPU2D DMA blitters (STM32 DMA2D, NXP PXP) or 2.5D vector GPUs (VG-Lite with vg_lite_query_feature)RenderEngine<SwRenderer> + compose_backend! + RendererFactory (or full Renderer)Shared with SwRenderer or device-owned BackendTargetHardware-accelerated rects, blits, or Bézier paths (vg_lite_draw) with per-command software fallback

Tier 1: Bring up an SPI panel with FramebufSurface ​

If your board has an allocator (extern crate alloc) and pushes pixels to an external display controller over SPI or 8080 parallel bus, FramebufSurface gets a panel running without implementing any traits.

Pixel formats and SPI byte order ​

Most SPI LCD controllers (ST7789, ST7735, GC9A01, ILI9341) expect 16-bit RGB565 pixels transmitted MSB first (big-endian), whereas ARM Cortex-M and RISC-V MCUs are little-endian. Choose ColorFormat::RGB565Swapped so SwRenderer writes byte-swapped RGB565 directly during rasterization—your SPI DMA transfer can then stream the slice without a byte-swapping loop:

ColorFormatBytes / PixelMemory LayoutTypical Panel / Bus
RGB565Swapped2[msb, lsb] (big-endian RGB565)SPI / QSPI panels (ST7789, GC9A01, ILI9341) on little-endian MCUs
RGB5652[lsb, msb] (native little-endian)Parallel RGB / LTDC / MIPI DSI / Linux fbdev 16-bpp
RGB8883[r, g, b] packed24-bit parallel RGB or MIPI DSI
RGBA88884[r, g, b, a]Desktop / Web Canvas / GPU upload targets
BGRA88884[b, g, r, a]DRM / X11 / Windows native scanout buffers

Slicing the dirty rectangle for CASET / RASET ​

During app.render_dirty() (or app.tick()), FramebufSurface invokes your callback once per damaged physical rectangle (area: PhysicalRect). Note that buf is the full W × H framebuffer with row stride W * bpp bytes; when area.width() < W, copy or DMA each row slice of the sub-window:

rust
use mirui::prelude::*;
use mirui::render::texture::ColorFormat;
use mirui::surface::{RedrawStrategy, framebuf::FramebufSurface};
use mirui::types::PhysicalRect;

const W: u16 = 240;
const H: u16 = 240;
const BPP: usize = ColorFormat::RGB565Swapped.bytes_per_pixel(); // 2
const STRIDE: usize = W as usize * BPP;

let surface = FramebufSurface::with_format(
    W,
    H,
    ColorFormat::RGB565Swapped,
    |buf: &[u8], area: PhysicalRect| {
        if area.is_empty() {
            return;
        }
        let x0 = area.x();
        let y0 = area.y();
        let w = area.width();
        let h = area.height();
        let x1 = x0 + w - 1;
        let y1 = y0 + h - 1;

        // 1. Send CASET (0x2A): [(x0 >> 8) as u8, x0 as u8, (x1 >> 8) as u8, x1 as u8]
        // 2. Send RASET (0x2B): [(y0 >> 8) as u8, y0 as u8, (y1 >> 8) as u8, y1 as u8]
        // 3. Send RAMWR (0x2C) and stream the window bytes:
        if x0 == 0 && w == W {
            // Full-width dirty band: stream one contiguous slice over SPI DMA.
            let start = y0 as usize * STRIDE;
            let end = (y0 + h) as usize * STRIDE;
            let _contiguous = &buf[start..end];
        } else {
            // Sub-width dirty box: advance by STRIDE for each row.
            for row in y0..(y0 + h) {
                let offset = row as usize * STRIDE + x0 as usize * BPP;
                let _slice = &buf[offset..offset + w as usize * BPP];
            }
        }
        let _ = (x1, y1);
    },
)
// Coalesce sparse dirty rects into one bounding box when SPI CS/command overhead is high:
.with_redraw_strategy(RedrawStrategy::BoundingBox);

let mut app = App::new(surface);
app.with_default_widgets().with_default_systems();
let _root = app.spawn_root().id();
app.render().unwrap();

Tier 2: Implement Surface and FramebufferAccess ​

When you need to:

  1. Place the framebuffer in a static BSS / SRAM / PSRAM section (32-byte aligned for DMA & cache lines, with zero heap allocation);
  2. Deliver touch, rotary encoder, or keypad events from poll_event();
  3. Coordinate begin / flush / end transactions with an asynchronous DMA channel or VSync interrupt; or
  4. Rotate across double or triple scanout buffers,

implement Surface and FramebufferAccess directly on your board struct. Because SwRendererFactory provides a blanket implementation for every B: FramebufferAccess, App::new(your_surface) works out of the box.

rust
use mirui::core::cache::InspectCaches;
use mirui::prelude::*;
use mirui::render::RenderError;
use mirui::render::texture::{ColorFormat, Texture};
use mirui::surface::{
    BackbufferPersistence, DisplayInfo, FramebufferAccess, InputEvent, RedrawStrategy,
    SafeAreaInsets, Surface,
};
use mirui::types::{Fixed, PhysicalRect};

const PHYS_W: u16 = 240;
const PHYS_H: u16 = 280;
const FB_LEN: usize = PHYS_W as usize * PHYS_H as usize * 2;

#[repr(C, align(32))]
pub struct AlignedFb(pub [u8; FB_LEN]);

pub struct BoardSurface {
    fb: AlignedFb,
    pending_events: [Option<InputEvent>; 8],
    event_head: usize,
    event_len: usize,
    dirty_count: u32,
}

impl BoardSurface {
    pub const fn new() -> Self {
        Self {
            fb: AlignedFb([0; FB_LEN]),
            pending_events: [const { None }; 8],
            event_head: 0,
            event_len: 0,
            dirty_count: 0,
        }
    }

    pub fn push_input(&mut self, event: InputEvent) {
        if self.event_len < self.pending_events.len() {
            let slot = (self.event_head + self.event_len) % self.pending_events.len();
            self.pending_events[slot] = Some(event);
            self.event_len += 1;
        }
    }
}

impl InspectCaches for BoardSurface {}

impl Surface for BoardSurface {
    fn display_info(&self) -> DisplayInfo {
        DisplayInfo {
            width: PHYS_W,
            height: PHYS_H,
            scale: Fixed::ONE,
            format: ColorFormat::RGB565Swapped,
        }
    }

    fn physical_size(&self) -> (u32, u32) {
        (u32::from(PHYS_W), u32::from(PHYS_H))
    }

    fn safe_area_insets(&self) -> SafeAreaInsets {
        // Keep root UI clear of rounded watch corners or camera cutouts:
        SafeAreaInsets {
            top: Fixed::from_int(12),
            right: Fixed::ZERO,
            bottom: Fixed::from_int(12),
            left: Fixed::ZERO,
        }
    }

    fn begin_flush(&mut self) -> Result<(), RenderError> {
        // Wait for any previous async SPI DMA transfer to finish before mutating or flushing.
        Ok(())
    }

    fn flush(&mut self, area: PhysicalRect) -> Result<(), RenderError> {
        if !area.is_empty() {
            self.dirty_count += 1;
            // Clean D-Cache for `area` rows and start SPI/QSPI DMA transfer.
        }
        Ok(())
    }

    fn end_flush(&mut self) -> Result<(), RenderError> {
        // Commit the frame (e.g. deassert CS or trigger panel refresh).
        Ok(())
    }

    fn abort_flush(&mut self) {
        // Called if rendering fails mid-frame; pending damage is retained by App.
    }

    fn poll_event(&mut self) -> Option<InputEvent> {
        if self.event_len == 0 {
            return None;
        }
        let event = self.pending_events[self.event_head].take();
        self.event_head = (self.event_head + 1) % self.pending_events.len();
        self.event_len -= 1;
        event
    }

    fn persistence(&self) -> BackbufferPersistence {
        BackbufferPersistence::Persistent
    }

    fn redraw_strategy(&self) -> RedrawStrategy {
        RedrawStrategy::Adaptive
    }
}

impl FramebufferAccess for BoardSurface {
    fn framebuffer(&mut self) -> Texture<'_> {
        Texture::new(
            &mut self.fb.0,
            PHYS_W,
            PHYS_H,
            ColorFormat::RGB565Swapped,
        )
        .expect("static buffer matches PHYS_W * PHYS_H * 2")
    }
}

let mut app = App::new(BoardSurface::new());
app.with_default_widgets().with_default_systems();
let _root = app.spawn_root().id();
app.render().unwrap();

Double-buffered scanout and automatic mirroring ​

When driving a parallel RGB / LTDC / MIPI DSI / Linux DRM controller that scans out directly from RAM, writing into the currently scanned buffer causes tearing. With two buffers (front being scanned by the display controller and back being drawn by mirui), partial redraws require keeping both buffers in sync.

You do not need to copy the entire screen on every frame or manually track dirty rectangles. Override Surface::buffer_count to return 2 and FramebufferAccess::all_buffers to return [completed_draw_buffer, inactive_mirror_buffer] after end_flush() swaps the buffers. SwRendererFactory::mirror_buffers will automatically:

  1. Apply any in-place scroll pixel shifts (plan.shifts) to the inactive buffer first;
  2. Copy only the redrawn physical rectangles (redraw) from the just-completed buffer into the inactive buffer.
DOUBLE-BUFFER MIRRORING ORDERWhy scroll shifts must run before dirty-rect blits on multi-buffer surfaces

When a scroll container moves by `dy = -24`, `App` shifts existing pixels inside `buffers[draw_index]` in place and repaints only the newly exposed 24 px strip at the bottom.

plan.shifts = [ScrollShift { area, dx: 0, dy: -24 }]; redraw = [bottom_strip];Rasterized pixels: ~10% of scroll viewport
rust
use alloc::{vec, vec::Vec};
use mirui::core::cache::InspectCaches;
use mirui::render::RenderError;
use mirui::render::texture::{ColorFormat, Texture};
use mirui::surface::{DisplayInfo, FramebufferAccess, InputEvent, Surface};
use mirui::types::{Fixed, PhysicalRect};

const W: u16 = 320;
const H: u16 = 240;
const LEN: usize = W as usize * H as usize * 2;

pub struct DoubleBufferedSurface {
    buffers: [[u8; LEN]; 2],
    draw_index: usize,
    last_presented: usize,
}

impl InspectCaches for DoubleBufferedSurface {}

impl Surface for DoubleBufferedSurface {
    fn display_info(&self) -> DisplayInfo {
        DisplayInfo {
            width: W,
            height: H,
            scale: Fixed::ONE,
            format: ColorFormat::RGB565,
        }
    }

    fn flush(&mut self, _area: PhysicalRect) -> Result<(), RenderError> {
        Ok(())
    }

    fn end_flush(&mut self) -> Result<(), RenderError> {
        // Flip scanout to `self.draw_index` at VSync, then switch the writable slot:
        self.last_presented = self.draw_index;
        self.draw_index ^= 1;
        Ok(())
    }

    fn poll_event(&mut self) -> Option<InputEvent> {
        None
    }

    fn buffer_count(&self) -> usize {
        2
    }
}

impl FramebufferAccess for DoubleBufferedSurface {
    fn framebuffer(&mut self) -> Texture<'_> {
        Texture::new(
            &mut self.buffers[self.draw_index],
            W,
            H,
            ColorFormat::RGB565,
        )
        .unwrap()
    }

    fn all_buffers(&mut self) -> Vec<Texture<'_>> {
        // Called right after `end_flush()` succeeds:
        // The completed frame (`last_presented`) MUST come first, followed by writable inactive buffers.
        let (first, second) = self.buffers.split_at_mut(1);
        let (completed, inactive) = if self.last_presented == 0 {
            (&mut first[0], &mut second[0])
        } else {
            (&mut second[0], &mut first[0])
        };
        vec![
            Texture::new(completed, W, H, ColorFormat::RGB565).unwrap(),
            Texture::new(inactive, W, H, ColorFormat::RGB565).unwrap(),
        ]
    }
}

D-Cache coherency and DMA tearing prevention ​

On MCUs with a data cache (such as ARM Cortex-M7, Cortex-A, or cached RISC-V cores), CPU software rasterization writes into the CPU's D-Cache, while SPI DMA, LTDC, and DMA2D access physical SRAM/PSRAM directly over the bus matrix. Follow these three cache-maintenance rules to prevent stale horizontal lines or corrupted blends:

TransitionRequired BarrierWhy
CPU SwRenderer → SPI / LTDC DMA readClean D-Cache (SCB_CleanDCache_by_Addr) over the dirty PhysicalRect span before starting DMAFlushes dirty cache lines out to SRAM so the DMA controller does not transmit stale bytes
CPU SwRenderer → 2D Accelerator (DMA2D / PXP)Clean & Invalidate D-Cache (SCB_CleanInvalidateDCache_by_Addr) in RenderEngine::beginEnsures hardware sees previous CPU pixels AND discards CPU cache lines that hardware is about to overwrite
2D Accelerator (DMA2D) → CPU SwRendererWait for hardware transfer-complete IRQ/flag in RenderEngine::end + memory barrier (dmb)Prevents the CPU from reading or writing the same pixel rows while the 2D engine is still active

Wiring touch, rotary encoders, and hardware keys ​

Surface::poll_event(&mut self) drains one InputEvent at a time until it returns None. All spatial coordinates (PointerDown, PointerMove, PointerUp, Wheel) are in logical pixels (0..display_info().width, 0..display_info().height) represented as Fixed:

  • If display_info().scale is Fixed::ONE (1.0), convert raw touch controller integers directly with Fixed::from_int(raw_x);
  • If scale is 2.0 (for example, a 480×480 physical panel configured as a 240×240 logical viewport), divide physical touch coordinates by scale: Fixed::from_int(raw_x) / scale.

Panel rotation (MADCTL) and touch coordinate transforms ​

When a panel is rotated in hardware via its MADCTL (0x36) register (MV, MX, MY bits), the touch controller often still reports coordinates in the sensor's native portrait orientation. Transform (raw_x, raw_y) into logical (x, y) before constructing InputEvent:

RotationMADCTL BitsLogical (W, H)Touch Coordinate Transform (raw_x, raw_y) -> (x, y)
0° (Portrait)0x00(PHYS_W, PHYS_H)(raw_x, raw_y)
90° ClockwiseMV | MX (0x60)(PHYS_H, PHYS_W)(raw_y, PHYS_W - 1 - raw_x)
180° InvertedMX | MY (0xC0)(PHYS_W, PHYS_H)(PHYS_W - 1 - raw_x, PHYS_H - 1 - raw_y)
270° ClockwiseMV | MY (0xA0)(PHYS_H, PHYS_W)(PHYS_H - 1 - raw_y, raw_x)
rust
use mirui::input::event::input::{
    InputEvent, KEY_HW_BUTTON_0, KEY_RETURN, KEY_ROTARY_PRESS, Key, PointerKind, Rotary,
};
use mirui::types::Fixed;

/// Capacitive touch sample (e.g. FT6336 / CST816 / GT911).
pub fn map_touch_sample(touching: bool, was_touching: bool, x: i32, y: i32) -> Option<InputEvent> {
    let x = Fixed::from_int(x);
    let y = Fixed::from_int(y);
    match (was_touching, touching) {
        (false, true) => Some(InputEvent::PointerDown {
            kind: PointerKind::Touch,
            id: 0,
            x,
            y,
        }),
        (true, true) => Some(InputEvent::PointerMove {
            kind: PointerKind::Touch,
            id: 0,
            x,
            y,
        }),
        (true, false) => Some(InputEvent::PointerUp {
            kind: PointerKind::Touch,
            id: 0,
            x,
            y,
        }),
        (false, false) => None,
    }
}

/// Detent delta from a quadrature encoder or smart-watch crown (+1 clockwise, -1 counter-clockwise).
pub fn map_rotary_detent(delta: i16) -> InputEvent {
    Rotary { id: 0, delta }.into()
}

/// Crown push button or side GPIO hardware button (`0..N`).
pub fn map_hw_button(button_index: u32, pressed: bool) -> InputEvent {
    let code = if button_index == 0 {
        KEY_ROTARY_PRESS
    } else {
        KEY_HW_BUTTON_0 + (button_index - 1)
    };
    Key {
        code,
        physical: None,
        pressed,
        modifiers: None,
        repeat: Some(false),
    }
    .into()
}

/// Standard navigation / confirm key for keypad-driven UIs.
pub fn map_enter_key(pressed: bool) -> InputEvent {
    Key {
        code: KEY_RETURN,
        physical: None,
        pressed,
        modifiers: None,
        repeat: Some(false),
    }
    .into()
}

Lock-free ISR-to-UI event queue ​

Never call App methods inside a hardware interrupt service routine (ISR). Instead, push compact raw samples from your GPIO / I2C / timer ISR into a single-producer single-consumer (SPSC) ring buffer (or critical_section-guarded queue), wake the main thread, and drain them inside Surface::poll_event():

rust
use core::sync::atomic::{AtomicUsize, Ordering};
use mirui::input::event::input::{InputEvent, KEY_ROTARY_PRESS, Key, Rotary};

#[derive(Clone, Copy)]
pub enum RawIrqEvent {
    RotaryStep(i16),
    CrownPress(bool),
}

pub struct IsrRing<const N: usize> {
    slots: [core::cell::UnsafeCell<Option<RawIrqEvent>>; N],
    head: AtomicUsize,
    tail: AtomicUsize,
}

unsafe impl<const N: usize> Sync for IsrRing<N> {}

impl<const N: usize> IsrRing<N> {
    pub const fn new() -> Self {
        Self {
            slots: [const { core::cell::UnsafeCell::new(None) }; N],
            head: AtomicUsize::new(0),
            tail: AtomicUsize::new(0),
        }
    }

    /// Called from GPIO / quadrature encoder ISR (single producer):
    pub fn push_from_isr(&self, ev: RawIrqEvent) -> bool {
        let tail = self.tail.load(Ordering::Relaxed);
        let next = (tail + 1) % N;
        if next == self.head.load(Ordering::Acquire) {
            return false; // Queue full
        }
        unsafe { *self.slots[tail].get() = Some(ev) };
        self.tail.store(next, Ordering::Release);
        true
    }

    /// Called inside `Surface::poll_event(&mut self)` on the UI thread (single consumer):
    pub fn pop_for_surface(&self) -> Option<InputEvent> {
        let head = self.head.load(Ordering::Relaxed);
        if head == self.tail.load(Ordering::Acquire) {
            return None;
        }
        let raw = unsafe { (*self.slots[head].get()).take() }?;
        self.head.store((head + 1) % N, Ordering::Release);
        Some(match raw {
            RawIrqEvent::RotaryStep(delta) => Rotary { id: 0, delta }.into(),
            RawIrqEvent::CrownPress(pressed) => Key {
                code: KEY_ROTARY_PRESS,
                physical: None,
                pressed,
                modifiers: None,
                repeat: Some(false),
            }
            .into(),
        })
    }
}

Lifecycle and memory-pressure hooks ​

  • Suspend & Resume: Enqueue InputEvent::AppSuspend before powering down the display or entering deep sleep, and InputEvent::AppResume after waking up. App automatically cancels in-flight pointer drags/gestures and triggers PersistencePlugin save hooks on suspend.
  • Memory warnings: When heap headroom runs low, call app.memory_warning() to trim reconstructible text-shaping, path-placement, and offscreen caches without losing application state.

Tier 3: 2D blitters and 2.5D vector GPUs (compose_backend!) ​

Embedded graphics accelerators fall into two distinct capability classes, and RenderEngine<T> + compose_backend! handles both without forcing you to reimplement unsupported operations:

Accelerator ClassTypical IP / SoCsNative Hardware CapabilitiesDynamic Feature Query & Fallback Boundary
Fixed-Function 2D BlitterSTM32 Chrom-ART DMA2D, NXP PXP, Renesas DRW2D, ESP32-P4 PPAAxis-aligned rectangle fills (fill_rect), pixel-format conversion (RGB565 ↔ ARGB8888), and unrotated / scale-only texture blits (blit)No vector path rasterizer or 3D perspective—route fill_rect and blit to hardware, and delegate rounded corners, Bézier paths, and text to SwRenderer
2.5D Vector & Blit GPUVeriSilicon VG-Lite (NXP i.MX RT1170 / RT595, BES2700 / BES2800, Actions)Hardware cubic/quadratic Bézier path tessellation (vg_lite_draw with NonZero / EvenOdd), 3×3 perspective matrix blits (vg_lite_blit), linear/radial gradients (gcFEATURE_BIT_VG_LINEAR_GRADIENT_EXT), and path scissor/masking (gcFEATURE_BIT_VG_MASK)Query Silicon IP revision capabilities at runtime via vg_lite_query_feature(feature) inside RenderEngine::route: dispatch supported fill_path, stroke_path, projective blit, and gradients to vg_lite_*, and fall back to SwRenderer only when a specific chip revision lacks a feature (e.g. ApplyBlur or unimplemented radial gradient extensions)

With RenderEngine<T> and compose_backend!, you only write the fast path for the commands your peripheral supports. For every draw call:

  1. Your engine's route(&self, target, request) inspects the DrawRequest (and, on configurable IP like VG-Lite, checks cached vg_lite_query_feature(gcFEATURE_BIT_VG_*) flags);
  2. If the hardware supports the exact geometry, paint, and blend mode, route returns Ok(RenderRoute::Native) and submit drives the peripheral (DMA2D registers or vg_lite_draw / vg_lite_blit);
  3. For everything else, route delegates to target.route(request) or returns ExactFallback, and compose_backend! automatically runs end(&mut self, target) (e.g. polling DMA2D TCIF or calling vg_lite_finish()) before SwRenderer touches the shared framebuffer.
HYBRID ENGINE & EXACT FALLBACKPer-command routing across 2D blitters, VG-Lite vector GPUs & bounded fallback

`VgLiteEngine::route` checks `request.command` against the cached `vg_lite_query_feature(gcFEATURE_BIT_VG_*)` table: cubic/quadratic Bézier `FillPath`, `StrokePath`, and 3×3 projective `Blit` return `Ok(RenderRoute::Native)`.

if vg_lite_query_feature(gcFEATURE_BIT_VG_STROKE_PATH) != 0 { return Ok(RenderRoute::Native); }Hardware Bézier tessellation + 3×3 matrix blit

Example A: Fixed-function 2D blitter (DMA2D / PXP) ​

rust
use mirui::core::cache::InspectCaches;
use mirui::render::{
    DrawCommand, DrawRequest, PreparedDraw, RenderEngine, RenderError, RenderRoute, Renderer,
    RendererFactory, SwRenderer, SwRendererFactory,
};
use mirui::surface::FramebufferAccess;
use mirui::types::{Fixed, Viewport};
use mirui_macros::compose_backend;

#[derive(Default)]
pub struct Dma2dEngine {
    pub hw_fills: u32,
}

impl<'a> RenderEngine<SwRenderer<'a>> for Dma2dEngine {
    fn route(
        &self,
        target: &SwRenderer<'a>,
        request: &DrawRequest<'_, '_>,
    ) -> Result<RenderRoute, RenderError> {
        request.validate()?;
        // DMA2D only accelerates unrotated, non-projective, sharp-cornered opaque rectangle fills:
        if request.projective.is_identity()
            && request.command.transform().is_identity()
            && let DrawCommand::Fill {
                quad: None,
                radius,
                opa: 255,
                ..
            } = request.command
            && *radius == Fixed::ZERO
        {
            return Ok(RenderRoute::Native);
        }
        // Delegate rounded rects, paths, text, and blits to SwRenderer:
        target.route(request)
    }

    fn begin(&mut self, _target: &mut SwRenderer<'a>) -> Result<(), RenderError> {
        // Clean & invalidate D-Cache before DMA2D writes into shared SRAM/PSRAM.
        Ok(())
    }

    fn submit(
        &mut self,
        target: &mut SwRenderer<'a>,
        draw: &PreparedDraw<'_>,
    ) -> Result<(), RenderError> {
        let request = draw.request();
        if self.route(target, &request)? == RenderRoute::Native
            && let DrawCommand::Fill { area, color, .. } = request.command
        {
            self.hw_fills += 1;
            // In production, program DMA2D OMAR / OOR / NLR with `target.viewport.physical_rect(...)`.
            let _ = (area, color);
        }
        target.submit(draw)
    }

    fn end(&mut self, _target: &mut SwRenderer<'a>) {
        // Poll DMA2D TCIF (Transfer Complete Interrupt Flag) before CPU software rasterization resumes.
    }
}

compose_backend! {
    pub struct Dma2dHybrid<'a> {
        sw: SwRenderer<'a>,
        dma2d: Dma2dEngine,
    }
    route {
        default => sw,
        fill_rect => dma2d,
    }
}

#[derive(Default)]
pub struct Dma2dFactory {
    sw: SwRendererFactory,
}

impl InspectCaches for Dma2dFactory {}

impl<B: FramebufferAccess> RendererFactory<B> for Dma2dFactory {
    type Renderer<'a>
        = Dma2dHybrid<'a, SwRenderer<'a>, Dma2dEngine>
    where
        Self: 'a,
        B: 'a;

    fn make<'a>(&'a mut self, backend: &'a mut B, transform: &Viewport) -> Self::Renderer<'a> {
        let sw = self.sw.make(backend, transform);
        Dma2dHybrid::new(sw, Dma2dEngine::default())
    }

    fn mirror_buffers(
        &mut self,
        backend: &mut B,
        plan: &mirui::ui::dirty::DirtyRegions,
        redraw: &[mirui::types::PhysicalRect],
        transform: &Viewport,
    ) -> Result<(), RenderError> {
        self.sw.mirror_buffers(backend, plan, redraw, transform)
    }

    fn trim_memory(&mut self) {
        self.sw.trim_memory();
    }
}

Example B: VeriSilicon VG-Lite vector GPU with vg_lite_query_feature ​

Unlike a simple DMA blitter, VG-Lite natively accelerates vector paths (M / L / Q / C / Z commands via vg_lite_path_t and vg_lite_draw), rounded rectangles, strokes (gcFEATURE_BIT_VG_STROKE_PATH), 3×3 perspective matrix blits (vg_lite_blit), and hardware gradients. Because different SoC vendors synthesize VG-Lite with different gcFEATURE_BIT_VG_* straps, query the hardware feature bits at initialization (or via vg_lite_query_feature) and route fill_path, stroke_path, fill_rect, and blit accordingly:

rust
use mirui::render::{
    Canvas, DrawCommand, DrawRequest, Paint, PreparedDraw, RenderEngine, RenderError, RenderRoute,
    SwRenderer,
};
use mirui_macros::compose_backend;

/// Cached result of `vg_lite_query_feature(gcFEATURE_BIT_VG_*)` probed at boot.
#[derive(Clone, Copy)]
pub struct VgLiteFeatures {
    pub stroke_path: bool,     // gcFEATURE_BIT_VG_STROKE_PATH
    pub linear_grad_ext: bool, // gcFEATURE_BIT_VG_LINEAR_GRADIENT_EXT
    pub radial_grad: bool,     // gcFEATURE_BIT_VG_RADIAL_GRADIENT
}

pub struct VgLiteEngine {
    pub features: VgLiteFeatures,
    pub hw_paths: u32,
}

impl<'a> RenderEngine<SwRenderer<'a>> for VgLiteEngine {
    fn route(
        &self,
        target: &SwRenderer<'a>,
        request: &DrawRequest<'_, '_>,
    ) -> Result<RenderRoute, RenderError> {
        request.validate()?;
        match request.command {
            // VG-Lite natively tessellates cubic/quadratic Bézier paths & rounded rects:
            DrawCommand::FillPath { paint, .. } => {
                let paint_ok = match paint {
                    Paint::Color(_) => true,
                    Paint::LinearGradient(_) => self.features.linear_grad_ext,
                    Paint::RadialGradient(_) => self.features.radial_grad,
                };
                if paint_ok {
                    Ok(RenderRoute::Native)
                } else {
                    target.route(request)
                }
            }
            DrawCommand::StrokePath { paint, .. } if self.features.stroke_path => match paint {
                Paint::Color(_) => Ok(RenderRoute::Native),
                _ => target.route(request),
            },
            // VG-Lite supports 3x3 homography matrices in vg_lite_blit / vg_lite_draw:
            DrawCommand::Fill { .. } | DrawCommand::Blit { .. } => Ok(RenderRoute::Native),
            // Gaussian blur or unsupported features fall back cleanly to SwRenderer:
            _ => target.route(request),
        }
    }

    fn submit(
        &mut self,
        target: &mut SwRenderer<'a>,
        draw: &PreparedDraw<'_>,
    ) -> Result<(), RenderError> {
        let request = draw.request();
        if self.route(target, &request)? == RenderRoute::Native {
            self.hw_paths += 1;
            // Encode mirui::render::PathCmd into VLC_OP_MOVE / LINE / QUAD / CUBIC / CLOSE
            // and submit via `vg_lite_draw(&vg_target, &vg_path, fill_rule, &matrix, blend, color)`.
        }
        target.submit(draw)
    }

    fn end(&mut self, _target: &mut SwRenderer<'a>) {
        // Call `vg_lite_finish()` so the command buffer completes before CPU accesses the buffer.
    }
}

compose_backend! {
    pub struct VgLiteHybrid<'a> {
        sw: SwRenderer<'a>,
        vglite: VgLiteEngine,
    }
    route {
        default => sw,
        fill_rect => vglite,
        fill_path => vglite,
        stroke_path => vglite,
        blit => vglite,
    }
}

Pass the custom factory to App::with_factory(surface, Dma2dFactory::default()). For full GPU backends that own device textures rather than a CPU framebuffer, implement Renderer + BackendTarget directly; see Backend target storage and Exact backend fallback.


Bare-metal clocks, flash storage, and audio ​

1. Monotonic clock (mirui::core::time::set_clock) ​

On std, mirui automatically anchors a monotonic clock on first read. On no_std, register a nanosecond clock function during board initialization and install a plugin that updates MonoClock so spring transitions, tweens, long-press gesture thresholds, and #[timer] schedules advance in real time:

rust
use mirui::app::{App, Plugin};
use mirui::core::time;
use mirui::ecs::MonoClock;

fn board_uptime_ns() -> u64 {
    // Read hardware timer / DWT cycle counter / RTOS tick converted to nanoseconds:
    16_666_667
}

pub struct BoardClockPlugin;

impl Plugin for BoardClockPlugin {
    fn build<B: mirui::surface::Surface, F: mirui::render::RendererFactory<B>>(
        &self,
        app: &mut App<B, F>,
    ) {
        time::set_clock(board_uptime_ns);
        app.world.insert_resource(MonoClock::new(0));
    }

    fn on_tick<B: mirui::surface::Surface, F: mirui::render::RendererFactory<B>>(
        &mut self,
        app: &mut App<B, F>,
    ) {
        let now_ms = time::clock_now_ns() / 1_000_000;
        if let Some(mut clock) = app.world.get_resource_mut::<MonoClock>() {
            clock.advance_to(now_ms);
        }
    }
}

2. Tick-less sleep and low-power main loop (wfi & RTOS pacing) ​

On battery-powered wearables and sensor nodes, spinning app.tick() in a busy loop wastes power. Check whether app.dirty_regions() is non-empty or an animation/spring is active; when the scene is quiescent, block on an RTOS semaphore or execute wfi (Wait For Interrupt) until the next touch interrupt or timer deadline:

rust
use mirui::prelude::*;
use mirui::surface::framebuf::FramebufSurface;

let surface = FramebufSurface::new(240, 240, |_buf, _area| {});
let mut app = App::new(surface);
app.with_default_widgets().with_default_systems();
let _root = app.spawn_root().id();
app.render().unwrap();

// Single iteration of a low-power embedded event loop:
let should_quit = app.tick();
if !should_quit {
    if !app.dirty_regions().unwrap().is_empty() {
        app.render_dirty().unwrap();
        // Active frame: pace to 60 Hz (16 ms) or wait for VSync / DMA completion.
    } else {
        // Idle frame: zero dirty pixels! Enter WFI or wait on IRQ semaphore.
    }
}

3. Flash / KV storage (mirui::core::storage::Storage) ​

To persist #[model(persistence)] state to SPI NorFlash, LittleFS, NVS, or EEPROM, implement the synchronous Storage trait and pass it to PersistencePlugin::new(storage). Return WriteOutcome::Unchanged when the stored bytes already match value to avoid redundant flash erase/program cycles:

rust
use alloc::vec::Vec;
use mirui::core::storage::{Storage, StorageError, WriteOutcome};

pub struct FlashKvStorage;

impl Storage for FlashKvStorage {
    fn read(&self, key: &str) -> Result<Option<Vec<u8>>, StorageError> {
        let _ = key;
        // Return Ok(None) only when the key does not exist; return Err(StorageError::Io) on CRC/bus errors.
        Ok(None)
    }

    fn write(&mut self, key: &str, value: &[u8]) -> Result<WriteOutcome, StorageError> {
        if self.read(key)?.as_deref() == Some(value) {
            return Ok(WriteOutcome::Unchanged);
        }
        // Write `value` to flash/KV sector for `key`:
        Ok(WriteOutcome::Written)
    }

    fn remove(&mut self, key: &str) -> Result<(), StorageError> {
        let _ = key;
        Ok(())
    }
}

4. I2S / DMA audio synthesis (AudioMixer & AudioSink) ​

When the audio feature is enabled, AudioMixer<V> synthesizes polyphonic waveforms and scores into caller-owned i16 PCM slices with zero heap allocation. Drive mixer.render_mono(&mut dma_half_buffer) from an I2S DMA interrupt or RTOS audio task, and implement AudioSink to forward AudioCommands from app.audio():

rust
use mirui::audio::{AudioBank, AudioCommand, AudioMixer, AudioSink, MixerError};

static BANK: AudioBank = AudioBank::new(&[]);

pub struct I2sAudioSink {
    mixer: AudioMixer<8>,
}

impl I2sAudioSink {
    pub fn new(sample_rate: u32) -> Result<Self, MixerError> {
        Ok(Self {
            mixer: AudioMixer::new(&BANK, sample_rate)?,
        })
    }

    /// Call from I2S DMA half-transfer / transfer-complete ISR or audio thread:
    pub fn fill_dma_buffer(&mut self, pcm_mono: &mut [i16]) {
        self.mixer.render_mono(pcm_mono);
    }
}

impl AudioSink for I2sAudioSink {
    type Error = MixerError;

    fn start(&mut self, _bank: &'static AudioBank) -> Result<(), Self::Error> {
        Ok(())
    }

    fn submit(&mut self, command: AudioCommand) -> Result<(), Self::Error> {
        self.mixer.apply(command)
    }
}

Porting verification checklist ​

StepVerification TargetSymptom if MisconfiguredFix
01 · Headless Smoke TestMount #[compose] tree on App::headless(W, H) in cargo testPanic or truncated text on deviceIncrease Text(capacity: N) or PathStore capacity before flashing hardware
02 · Colorbar & EndiannessDraw red, green, and blue View bars ((255,0,0), (0,255,0), (0,0,255))Red and blue swapped, or green bar has striped noiseSwap RGB565 ↔ RGB565Swapped (byte order) or toggle panel MADCTL BGR bit
03 · Sub-Window StrideTap a small button so flush(area) receives area.width() < WPartial update appears diagonal or shearedEnsure CASET/RASET end coords are inclusive (x+w-1, y+h-1) and row offset advances by W * bpp
04 · D-Cache & DMA SyncAnimate a fast-moving slider or scroll listHorizontal stale-pixel tearing bands inside dirty rectCall SCB_CleanDCache_by_Addr before DMA and wait for DMA completion in begin_flush()
05 · Touch & Idle SleepTap buttons in all 4 corners, then leave screen idleCorner taps inverted; high idle current drawApply the MADCTL touch transform table and enter wfi when dirty_regions().is_empty()