Architecture
Goals
- Declarative API:
view() -> Elementrebuilt from state owned bystatefulwidgets, provided values and async sources. No messages, no signals, no retained widget objects owned by the user. - One rendering primitive: every pixel comes from one pipeline whose fragment shader evaluates a rounded-rect distance field, glyph coverage from Bézier outlines, or an app-provided bitmap. No texture atlases, no tessellation.
- Mobile first: Android via
android-activity, edge-to-edge with system bar insets, 60 fps on a mid-range Mali GPU (baseline numbers inTODO.md). - Small: few dependencies (wgpu, winit, taffy, read-fonts, harfrust), little code.
Frame loop
input event ──► dispatch ──► state updates ──┐
task wake ────► poll tasks ──► results ───────┴──► App::view ──► new Element tree
│
RedrawRequested ◄── request_redraw ◄── measure (taffy) + place ◄───────┘
│ ▲
│ └── place only: redraw without a rebuild
│ (hover, press, scroll, caret)
│
▼
paint every node ──► Scene (flat instance list) ──► Renderer (one pass) ──► surface
Runtime (src/runtime/mod.rs) owns the app, the current element tree,
per-widget state, the text system and the renderer. On desktop and the web
it is a winit ApplicationHandler. On Android, runtime/activity.rs drives
it from android-activity's poll_events instead, so the loop can return on
onDestroy and start again for a recreated activity; winit can't do either.
There, the renderer is dropped when the native window goes away
(backgrounded) and rebuilt when a new one arrives. The renderer only sees
the window through the Host trait.
Modules
| File | Role |
|---|---|
lib.rs | Public API: App, run, run_android, re-exports. |
widget.rs | Element, Widget trait, Event, State, PaintCx, EventCx. |
widgets/mod.rs | Widget infrastructure: the Styled flex modifiers, re-exports. |
widgets/*.rs | One file per built-in: container (row/column/container/spacer), label (text), button, icon (icon/icon_button), scroll, stateful, provide, builder (future_builder/stream_builder), text_input, toggle, slider, progress (progress/stacked_progress/wait_bar/spinner), radio, segmented (segmented/tabs), overlay (overlay/popup and the dialog, drawer, bottom_sheet, snackbar, tooltip, dropdown built on them). |
anim.rs | Animated<T> transitions, Lerp, ease curves; driven by PaintCx::now and request_frame. Morph between two Paths (e.g. glyphs): contours with as many corners pair corner to corner, and segments of the shorter side are cut into as many pieces as needed. |
kinetic.rs | Drag: drag slop, release velocity and fling decay for widgets that scroll themselves (scroll, app widgets). |
path.rs | Path: contours of quadratic segments, filled by PaintCx::path through the glyph renderer (per-frame shapes use a reserved region of the outline buffers). Shape: a Path stored once like a glyph and drawn into any rect by PaintCx::shape, for icons. |
layout.rs | Flattens the tree to pre-order nodes; measure runs taffy, place produces absolute rects, clips and scroll offsets. |
runtime/mod.rs | Runtime: input → Event translation, dispatch, pointer capture, focus, frame pacing and stats. |
runtime/winit_app.rs | Desktop and web event loop (winit ApplicationHandler). |
runtime/activity.rs | Android event loop on android-activity: lifecycle, touch, keys, soft keyboard, system bar icon color. |
runtime/android.rs | dfui::android: with_activity JNI helper, system bar insets and appearance. |
runtime/task.rs | Widget-owned futures/streams, polling, sleep timers, the event-loop waker. |
runtime/clipboard.rs | System clipboard on desktop, in-app elsewhere. |
runtime/bench.rs | Bench, GpuBench and snapshot, through the real runtime without a window. |
render/ | primitives (Color/Rect/Shadow/Bitmap), scene (Scene, damage), gpu (wgpu setup, the single render pass, GPU timestamp timing, offscreen rendering). |
shader.wgsl | Vertex expands instances to quads; fragment does SDF shapes (kind 0) and outline glyphs (kind 1). |
text.rs | Font handles (bundled DejaVu Sans as default and fallback), per-word shaping with harfrust, greedy word wrap, lazy glyph outline building. |
outline.rs | Converts glyph contours to monotonic quadratics and per-glyph band lists for the shader. |
Widgets and state
viewrebuilds the wholeElementtree after every state update or task result. Elements are cheap boxed descriptions.- Composite widgets are plain functions returning
Element. ImplementWidgetonly for new layout, paint or input behavior. - Framework-owned per-widget state (
State, a typedBox<dyn Any>slot) is keyed by a hash of the parent id plus child slot index, orElement::keywhen set. State for ids missing from the new tree is dropped after each update. Usekeyfor reorderable lists. - UI state lives in
stateful(|s: &S, h: Handle<S>| ...)widgets, including app-wide state in a rootstateful. Handlers capture theCopyhandle, never the state, and callcx.update(h, |s: &mut S| ...); the runtime lends the state during the call, so there are no borrow problems. statefulbuilds its subtree lazily inflattenviaWidget::expand, withSread from its state slot. Queued updates are applied after dispatch, then the tree is rebuilt.- External state stays outside the framework. The app owns it and hands it
down with
provide(value, child); descendants read the nearest one withScope::get::<T>()duringexpand.flattenkeeps the stack of provided values while it walks children. Button::on_click(|cx| ..)is the general handler.
Async
future_builder(deps, |scope| fut, build)andstream_builder(deps, |scope| stream, build)build their subtree from aSnapshot(data,done) that the source writes. Sources are any stdFutureorfutures_core::Stream, so they can come from any runtime. Streams collect intoS: Default + Extend<Item>(Vec,String, ...).- In
expanda builder starts its source as a task keyed by node id (src/runtime/task.rs), or keeps the running one when the hash ofdepsmatches. New deps reset the snapshot and replace the task. Tasks are dropped with their node in the same pass that drops state, which cancels them. - Tasks are polled on the UI thread, so sources need not be
Send. OneWakerposts a winit user event (deduplicated);user_eventpolls every task, draining up to 1024 ready items so a burst costs one rebuild, then gives tasks started by that rebuild their first poll. Running tasks wait for their next wake, so a fast source can't hold off painting. Without an event loop (tests, benches) the waker is a no-op anddriveis called directly.
Web
- Builds for
wasm32-unknown-unknown; WebGPU only.runuses winit'sspawn_app, and the window is a canvas appended to the page, sized by CSS. - GPU setup is async on every platform:
resumedstoresRenderer::newas a future and polls it with the task waker. Native adapters resolve on the first poll; in the browser the waker fires when the promises settle. dfui::sleepregisters deadlines on the UI thread;about_to_waitwakes due ones and sleeps the loop until the next (ControlFlow::WaitUntil), so timed async work needs no threads or runtime.- Time is
web_time::Instantthroughout (std's clock panics on wasm32); natively it is std's type. The clipboard is in-app on the web. site/builds each example as its own wasm;run.html?example=NAMEhosts one, embedded by its widget page in an iframe so its canvas and event loop don't take over the docs page.
Layout
flatten produces a pre-order Vec<Node>, once per rebuilt tree; other
passes re-walk it from cached ids (tree.md). measure builds a taffy tree from
each widget's style()/measure() and keeps each node's parent-relative box;
place turns those into absolute rects, applying scroll() offsets and
intersecting clip rects. The runtime keeps measure's result until the tree
is rebuilt or the viewport changes, so redraws without a rebuild only rerun
place. The taffy tree itself is kept across rebuilds, matched by node id:
only nodes whose style, children or measure_key() changed are marked
dirty, and taffy's cache recomputes just their path to the root. Widgets
whose measure depends on their own data must override measure_key. The root fills the
viewport, with insets added to its padding so backgrounds bleed under system
bars. Text layouts are cached in Text by (string, size, width) and evicted
after a frame that doesn't use them, so repeated measure calls and
per-frame rebuilds of the same strings are cheap.
Input
Events are offered in reverse paint order (deepest / topmost first). A widget can
stop() propagation or capture() the pointer; on capture every other widget
receives Event::Cancel and subsequent pointer events go only to the captor
until pointer up. Touch takes up to two fingers: a second finger moves the
one pointer with the fingers' midpoint (shifted so it doesn't jump when a
finger lands or lifts) and sends Event::Pinch with the spread's change. On
desktop, ctrl+wheel and touchpad pinch gestures send Event::Pinch too.
scroll captures the pointer once a drag passes a 6px slop. On release it
flings: the offset speed (from the last 100ms of pointer samples) decays as
e^(-t/0.35s) until it drops below 10 px/s or hits an edge. The offset is
computed in Widget::scroll from the frame time, and the scroll view's
paint calls request_placement so placement reruns every frame while the
fling lasts, without a relayout.
One widget at a time holds keyboard focus, claimed with cx.focus() on
pointer down; a tap no widget claims blurs it. Event::Text and Event::Key
go only to the focused widget, which sees cx.focused in event and paint,
and cx.shift for extending selections. Ctrl/Cmd+A, C and X arrive as
Key::SelectAll, Key::Copy and Key::Cut; a widget hands text to the
clipboard with cx.copy. Paste arrives as Event::Text with the
clipboard's contents. On
Android, focus shows the soft keyboard through runtime/editor.rs: a Java view
with an InputConnection, whose edits arrive as Event::Text and
Key::DeleteBefore. A field's Keyboard picks the keyboard type. Hardware
keys still arrive as key events.
Layers
A widget whose layer() returns Some floats over the tree instead of
taking part in its flow: measure makes it position: absolute over its
parent (Layer::Parent, which is made relative) or position: fixed over
the window inside the system bars (Layer::Window), using taffy's
containing blocks. place gives its subtree the viewport as clip, so it
escapes scroll views, and leaves it out of the parent's scrollable content.
Paint order is pre-order, except that each layer's subtree comes after
everything it covers (sorted by layer depth, computed once per tree in
Runtime::order); dispatch walks that order in reverse, so layers get input
first. Pointer events only reach the nodes under the pointer, the ones it
just left or pressed, and layers (docs/tree.md, "Pointer targets").
Overlay is the built-in layer. Its content sits in a Sink that stops
pointer events hitting it, so any press that reaches the overlay landed
outside: that is on_dismiss, and modal also stops everything else and
paints a scrim. Tooltips and snackbars hide themselves (hover, timeout) by
scrolling their content out of the overlay's clip, so showing and hiding
needs no rebuild. Dialogs, drawers, sheets and snackbars slide the same way:
scroll eases an Animated between closed and open and offsets the content
by that fraction of the overlay's rect, and the scrim fades with it.
A removed node can't animate out, so overlays(|ov| ..) hosts the ones
opened from handlers. It is a stateful holding a builder per entry;
ov.show(cx, build) adds one and Shown::close marks it closing, which
the overlay animates out. Each entry sits in a future_builder whose future
sleeps until the entry's removal time (dfui::sleep) and then builds
nothing, so removal is an ordinary task result and rebuild: the tree's shape
still only changes in set_root. The deps are (key, closing), so closing
restarts the timer while the overlay below keeps its state. Removed entries
are pruned from the list on the next show.
Rendering
Details and design decisions, including partial redraws: rendering.md.
- Painting appends instances to a
Scene: shapes (rect, radius, border, colors), shadows (shapes with blur), glyph quads and images. Each carries a clip rect evaluated in the fragment shader. - All instances go into one vertex buffer, drawn with one pipeline. Without images that's one draw call per frame; each image adds a draw with its own texture bound, splitting the list into runs in painter's order.
- Images: the app decodes into a
Bitmap(premultiplied RGBA8, any thread); the renderer uploads one texture per bitmap on first draw and frees it once the bitmap is dropped. - Shapes: rounded-box signed distance → antialiased fill, border and blurred shadow.
- Text: glyph outlines are stored in two storage buffers (curves, bands). The fragment shader casts horizontal and vertical rays through the band containing the pixel and counts antialiased winding crossings, giving resolution-independent text with no atlas. Curves are sorted by reach so the scan stops early. This requires fragment-stage storage buffers (Vulkan / GLES 3.1+).
- Colors are specified in sRGB and blended in sRGB (gamma) space.
Rendererreports CPU time (minus vsync wait) and GPU time via timestamp queries, logged every two seconds.
Testing
- Unit tests sit next to the code (
layout,outline,text,runtimedispatch). dfui::snapshot(app, size, scale)renders one frame offscreen toPixels.tests/golden.rscompares those against the PNGs intests/golden/.tests/patterns.rsdrives usual app patterns with input events.
Known limits
Tracked in TODO.md and as ponytail: comments in the code: no IME composition on desktop,
no bidi, fallback only to the default font, single pointer, full view rebuild and paint per change,
linear hit-testing.