blit: immediate (yet deferred) mode UI
I started working on blit as an experiment 5 months ago. a few rewrites later, it has a zero-dependency core, a terminal & gpu backend, and a very fast software renderer.
at Foundation our device runs KeyOS, a custom microkernel OS, on a single core 500 MHz Cortex-A5 with 128 MB of RAM and no GPU. we picked Slint because it’s one of the few rust UI frameworks with a real software renderer. it topped out at 30 fps on our 480×800 LCD. I felt like the hardware could do more, so I started tinkering.
to understand where blit ended up, it helps to look at how most UI frameworks work and where they fall short.
retained mode
most UI frameworks operate in retained mode. the code you write can look simple. here’s a button that shows a panel in Dioxus[1]:
fn app() -> Element {
let mut show_details = use_signal(|| false);
rsx! {
button {
onclick: move |_| show_details.toggle(),
"toggle"
}
if show_details() {
p { "some details" }
}
}
}
it looks like rust, but rsx! is a procedural macro with its own DSL.
also note how app() doesn’t ‘run’ your UI. it returns your UI as a value, and the runtime interprets that value. and show_details isn’t a bool. it’s a Signal<bool> that tracks who reads it, so the runtime knows which parts of the UI to update when it changes.
here’s what an Element actually is:
type Element = Result<VNode, RenderError>;
struct VNode {
vnode: Rc<VNodeInner>,
}
struct VNodeInner {
template: Template,
dynamic_nodes: Vec<DynamicNode>,
dynamic_attrs: Vec<Box<[Attribute]>>,
}
enum DynamicNode {
Component(VComponent),
Text(VText),
Fragment(Vec<VNode>),
}
struct VComponent {
driver: Rc<dyn RenderDriver>,
props: Box<dyn AnyProps>,
}
enum AttributeValue {
Listener(Rc<RefCell<dyn FnMut(Event<dyn Any>)>>),
...
}
it’s a tree of Rc and Box scattered on the heap. everything the runtime does means chasing those pointers:
React, Flutter, SwiftUI, and Slint all kinda look like this.
now why does this hurt? CPUs don’t read one byte at a time. they grab memory in small chunks (usually 64 bytes) and keep recent chunks close by in cache.
here’s how long a memory load takes on my pc[2]:
| memory | latency | cpu cycles |
|---|---|---|
| L1 | ~1 ns | ~5 |
| L2 | ~4 ns | ~20 |
| L3 | ~18 ns | ~100 |
| RAM | ~92 ns | ~500 |
modern CPUs spend a lot of effort trying to guess what memory your program will read next so it can already be waiting in cache before you ask for it. if you’re walking through an array, that pattern is easy to spot, so upcoming chunks get pulled in ahead of time.
following pointers scattered across a heap breaks that. to know where a child lives, you first have to read the pointer inside its parent, and the CPU can’t fetch the child ahead of time when it doesn’t even know its address yet. worse, every time you jump to a random spot in memory, the CPU still grabs a whole chunk of whatever unrelated data happens to sit next to it, pushing useful things out of cache. if what you need isn’t in cache, the CPU has to sit around for ~500 cycles waiting on RAM, which is a couple thousand operations it could have done instead.
immediate mode
immediate mode makes a different bet:
rebuilding the UI every frame costs less than the bookkeeping to avoid it.
here’s the same panel in egui:
struct App {
show_details: bool,
}
impl App {
fn build(&mut self, ui: &mut egui::Ui) {
if ui.button("toggle").clicked() {
self.show_details = !self.show_details;
}
if self.show_details {
ui.label("some details");
}
}
}
this code runs each frame. ui.button measures and positions the button, records drawing commands, and returns whether it was clicked.
there is a beauty in this simplicity:
you own your state
it’s a plain bool in a struct you own. the widget borrows it for one call.
ui.checkbox(&mut self.dark_mode, "dark mode");
in retained mode the same bool moves into the framework. you read it in one place and write it back in a callback.
let mut dark_mode = use_signal(|| false);
input {
r#type: "checkbox",
checked: dark_mode(),
onchange: move |e| dark_mode.set(e.checked()),
}
your app ends up built around the framework instead of the other way around.
your program’s execution is already a tree
running functions that branch and loop already traces out a tree on the call stack. retained mode has to capture your UI as a data structure first, which means encoding control flow into that structure too.
in immediate mode, a for loop is a list, an if is a conditional widget, and a component is just a function. when the call stack is the UI tree, a normal debugger or profiler actually shows you your own code instead of a framework runtime.
built to be embedded
egui and Dear ImGui don’t own your window, event loop or renderer. each frame you hand them input and they hand back draw commands.
that’s why games can embed them for debug tools and editors. the whole UI is one function call inside a frame the game was already drawing.
the trade-off
widgets are laid out immediately as they’re built, and you can’t go back to resize the row or move an earlier widget.
say I have a row with two rectangles, where B takes up the remaining width. I want the row to be as tall as its tallest child, with all children centered along the cross axis.
ui.horizontal(|ui| {
ui.add_sized([40.0, 20.0], egui::Button::new("A"));
ui.add_sized([ui.available_width(), 60.0], egui::Button::new("B"));
});
A is placed before B even exists, so it’s stuck at the top instead of centered.
blit: immediate mode, deferred layout
blit is a portable no_std UI library with zero dependencies. your code stays immediate mode, while blit retains a little state to avoid immediate mode’s shortcomings.
deferred layout
immediate mode doesn’t require immediate layout. each frame, blit runs three passes: build, layout, then paint. and yes, it’s still very fast.
here’s the same row in blit:
let mut row = ui.layout(flex::row().gap(4.0).align(Align::Center));
row.child()
.item(flex::item().width(40.0).height(20.0))
.insert(Rectangle::new().background(Color::BLACK));
row.child()
.item(flex::item().width(Sizing::grow()).height(60.0))
.insert(Rectangle::new().background(Color::GRAY));
build records the tree. nothing is placed yet.
| node | position | size |
|---|---|---|
| row | ? | ? |
| A | ? | 40 × 20 |
| B | ? | ? × 60 |
layout gives B the leftover width, sizes the row to fit, then centers A.
paint walks the tree with the solved areas and records draw commands.
| node | command | x | y | size |
|---|---|---|---|---|
| A | rectangle | 0 | 20 | 40 × 20 |
| B | rectangle | 44 | 0 | 156 × 60 |
layouts aren’t built in. the flex::row() above is just ordinary code implementing Layout:
trait Layout<C: Context>: 'static {
type Item: Default + 'static;
fn fit(
&self,
cx: &mut LayoutCx<'_, C, Self::Item>,
axis: Axis,
) -> Fit<C::Scalar>;
fn distribute(
&self,
cx: &mut LayoutCx<'_, C, Self::Item>,
axis: Axis,
extent: C::Scalar,
);
}
struct Fit<T> {
min: T,
natural: T,
}
blit solves each axis (width, then height) in two passes over the node array:
fitwalks up from the leaves. each leaf reports itsminandnaturalsize, each parent sizes itself from its children, and every result lands in afitsarray.distributewalks down from the root. with every node’s fit already sitting infits, each parent takes the space it got and hands out final sizes and positions.
example: a centering layout
struct Center;
impl<C: Context<Scalar = f32>> Layout<C> for Center {
type Item = ();
fn fit(&self, cx: &mut LayoutCx<'_, C, ()>, axis: Axis) -> Fit<f32> {
cx.children().map(|c| cx.fit(c, axis)).fold(Fit::ZERO, Fit::max)
}
fn distribute(&self, cx: &mut LayoutCx<'_, C, ()>, axis: Axis, extent: f32) {
for child in cx.children() {
let size = cx.set_extent(child, cx.fit(child, axis).natural.min(extent));
cx.set_offset(child, (extent - size) / 2.0);
}
}
}most retained engines work top down via recursion instead: a parent calls into its children to measure them, then lays them out again once it knows their final bounds. in a nested tree, revisiting children blows up fast, so engines either bolt on a second measurement API just to ask preferred sizes (Flutter, Jetpack Compose) or keep per-node caches to absorb the repeat work (SwiftUI, Taffy).
that machinery adds up. Taffy retains over 1 KB per node just to solve layout, while blit needs under 100 bytes[3].
to be fair, blit doesn’t implement all of CSS, and that itself is a feature. CSS has to cram every possible layout rule, and how they all interact, into one giant static set of flags. in blit you pay for what you use, and when your UI needs something unusual, you just write the rules in code.
it’s easy to assume layout is just inherently this complicated. layout caches, duplicate measurement APIs, kilobytes per node: these aren’t fundamental problems of the universe. they’re artifacts of the constraints we’ve inflicted upon ourselves.
animation is (kinda) just interpolation
to animate a widget moving or resizing, you need to know where it was last frame. in immediate mode, nothing remembers that for you.
with deferred layout, blit already solves every node’s position and size. by keeping last frame’s around too, it has everything it needs to interpolate between them. you don’t manage animation state, you just tell blit which nodes should animate.
take that row. suppose we want A to widen on click, and B to shrink to make room:
let spring = Spring::new(0.3, 0.3);
let width = if self.wide { 120.0 } else { 40.0 };
row.child()
.item(flex::item().width(width).height(20.0))
.motion(Motion::new(spring).layout())
.insert(Rectangle::new().background(Color::BLACK));
row.child()
.item(flex::item().width(Sizing::grow()).height(60.0))
.motion(Motion::new(spring).layout())
.insert(Rectangle::new().background(Color::GRAY));
self.wide is just a bool, and B is still Sizing::grow(). layout solves the target rects as usual, and blit springs both nodes there from where they were last frame.
how does blit know which node is A?
Dear ImGui hashes label strings on an ID stack, so duplicate labels collide unless you disambiguate them:
ImGui::Button("delete##1");
ImGui::Button("delete##2");
egui hashes a sequential counter per container, so toggling an if shifts the IDs of widgets after it unless you scope them:
if show_banner { ui.label("heads up"); }
ui.push_id("notes", |ui| ui.text_edit_singleline(&mut notes));
blit doesn’t hash[4] at all. each child() uses rust’s #[track_caller] to record its source location, and blit walks a cursor alongside the previous frame’s children to match them by call site (and iteration count in a loop). duplicate labels and if branches just work:
if show_banner { col.child().insert(Text::new("heads up")); }
col.child().build(Button::new("delete"));
col.child().build(Button::new("delete"));
when the same widget can be built from a different call site or parent across frames, you pass an explicit key with Ui::child_in(scope, key).
bump arena
retained-mode frameworks allocate each node individually on the heap because any widget might live for two frames or two hours. they can’t assume anything about when that memory dies.
in blit, everything built for a frame dies together. frame state sits in a few arrays, and when the frame ends their lengths just reset to zero.
for things that don’t have a fixed type, like layouts and paint closures, blit uses a bump arena. it’s a single byte array that packs values of any type back to back, addressed by u32 offsets.
after the first few frames settle, building the UI doesn’t touch the system allocator at all, and everything the layout and paint passes need sits side by side in memory.
here’s the toggle demo from earlier in blit:
the C context generic
deep inside a UI, widgets often need access to ambient things like a theme or a renderer. normally you either pass those arguments down through every function along the way (prop drilling), or stash them in globals and runtime context lookups.
instead, everything in blit is generic over a context C, which acts like a typed global threaded through the entire frame. in your own app, you just use your concrete context struct directly and read off ui.context().
when you want a widget to work across different contexts, bound it with a trait:
trait HasTheme {
fn theme(&self) -> &Theme;
}
impl<C: Context + HasTheme> Widget<C> for Button<'_> {
type Response = bool;
fn build(self, mut ui: Ui<'_, C>) -> bool {
let theme = ui.context().theme();
let press = ui.interact(interact::press());
let background = if press.active { theme.active } else { theme.surface };
ui.insert(Rectangle::new().background(background));
ui.insert(Text::new(self.label));
press.clicked
}
}
you can test Button by passing a tiny Test(Theme) struct with no window needed. blit’s own widgets work the same way, which is how the same layouts and widgets run on both a terminal and a GPU.
performance
blit started as a software rendered UI framework for KeyOS, hence the name. on KeyOS, every app renders directly into a framebuffer and hands it to our compositor, which puts it on an LCDC hardware layer at the next vsync. most UI frameworks lean heavily on the GPU. if they support software rendering at all, it’s basically a GPU triangle pipeline emulated on the CPU (not very fast!). in blit, software rendering is a first class use case. moving KeyOS from Slint to blit took us from 30 (best case) to 60 fps, and cut build times and binary sizes by 60-70%.
for the mandatory vanity benchmarks, I built a dashboard running on both the terminal and desktop backends:
here’s the frame time breakdown[2]:
build & layout
building and laying out the dashboard takes ~50 µs with zero allocations.
the renderers
-
the software renderer is an aggressively SIMD’d scanline renderer that skips anything hidden behind an opaque shape. a full 5K repaint takes ~6 ms on a single thread. if only part of the screen changes a frame takes ~2 ms
-
the GPU renderer uses wgpu, and usually draws the whole frame in one instanced draw call. well under 1 ms at 5K
-
the terminal renderer repaints 230×70 in ~280 µs
blit is for you
somewhere along the way, UI got big. big runtimes, big dependency trees, big DSLs, all built to serve everyone at once.
blit is small, FAST, and modular on purpose. it doesn’t treat you like a child or hand you someone else’s compromises.
it’s still experimental and rough around the edges, but it already runs on Wayland, macOS, terminals, KeyOS, and even a Kindle.
-
slint has its own language, compiler, and build step. dioxus is plain rust so it’s simpler to compare against. ↩
-
rough numbers from my machine: Ryzen 9 7900 at 5.4 GHz, Radeon RX 9070, NixOS. ymmv ↩ ↩2
-
measured on a 1,000-node flex tree: ↩
- Taffy v0.16.1: ~1.28 KB/node (
NodeDataholds a 560 BStyle, 408 BCache, two 92 BLayouts, plus tree storage). - blit: ~98 B/node for layout state, or ~253 B/node for the full double-buffered
Tree(previous-frame state, identity, hit testing, paint).
- Taffy v0.16.1: ~1.28 KB/node (
-
inspired by hashless imgui talk. ↩