UI Toolkit
engine-ui (ui/) is Xodó's hardware-accelerated UI toolkit for desktop tools and game HUDs. A host that does not draw through it links none of it.
Host (ui/src/host.rs) owns the window, canvas, fonts, and retained tree:
Host::drawlendsDrawfor immediate-mode drawing (also passed to a canvas node's closure viaHost::set_canvas_draw).Host::tree/Host::tree_mutexpose the retainedTree(ui/src/tree.rs).Host::set_cursor_visible,decode_pixels/decode_image,Host::window_size/set_window_size,display_interval_ms, andWaker(waking a window from any thread).- Each window owns its own
Hoston the main thread; polling routes SDL events to the owning window and wakes the shared event loop. InputState(ui/src/input.rs) folds events intokeysand pointerbuttons(Buttonstracking held, just pressed, and just released sinceend_frame), pointer position, and touch fingers using SDL keycodes ininput::keys.
Drawing (shaders/kit.slang)
ui/src/canvas.rs draws every primitive as an instance of one Slang shader (shaders/kit.slang), pulling six vertices per rectangle from a storage buffer by vertex index (no hardware instancing required). Each instance is 112 bytes: rectangle, per-corner radii, texture coordinates, rounded clip rect, three colours (fill, gradient end, border), and kind:
- Shape — Signed-distance rounded rectangle with anti-aliased edges, inner border, and angled linear gradient.
- Shadow — Gaussian-integrated rounded box shadow reaching three standard deviations past the rectangle.
- Glyph — Coverage sampled from the glyph atlas in the text colour.
- Image — Texels multiplied by a tint.
- Per-side border — Independent width and colour per side with clean diagonal miters at corners.
- Gradients — Linear (up to 4 stops per instance, splitting automatically for more) and radial gradients with straight-alpha interpolation.
An instance's kind word also encodes an optional 2D transform index (Canvas::push_transform), reading transform rows appended to the frame buffer without growing the 112-byte instance. Instances cull on the CPU against the damaged region and clip; consecutive instances sharing a texture and sampler merge into one draw.
Frames & Compositing
- Direct toolkit frames — Draw into the canvas's window-sized texture and present via the device layer, paced by display sync. Small dirty regions (under half the window) load and redraw only the scissored damage rect; larger changes clear the texture for free on tile-based GPUs.
- Interleaving with
engine-gfx— CallingHost::engine_draw_beginswitches that frame throughengine-gfxso embedded 2D/3D engine views composite cleanly between canvas layers. - HUD over stage passes —
Host::tree_frame_overtakes aPassesclosure that records host render passes (such asStageRenderer::record) into the canvas's window-sized texture, then loads and draws the toolkit tree on top in one presentation.Host::capturereads back the composed image without re-recording. Seeui/examples/stage_hud.rs. - Linear-light blending — Default on new hosts (
HostOptions::default(), toggleable viaHost::set_linear_blending/Canvas::set_linear_blending). Draws throughkitFragmentLinearinto anRgba8UnormSrgbview (Device::create_srgb_view) so hardware decodes on blend and encodes on write with zero extra copy passes. Hosts requiring legacy encoded blending open withHostOptions::encoded(). - Headless & captures —
Host::open_headlessrenders offscreen without showing a window.Host::capture_pixelsreturns RGBA8 rows directly;capture_with(path, CaptureCompression::Fast)encodes fast PNGs (~7× faster).
The Retained Tree (ui/src/tree.rs)
Holds stable-ID nodes: boxes, text, images, text fields, and custom canvas nodes.
- Layout & Flexbox — Rows and columns with
Fixed,Auto,Fill(weight),Percent, and viewport units (Vw,Vh,Vmin,Vmax).Tree::set_flexadds CSS-style margins (Autoincluded), min/max sizes,grow,shrink(default0),basis,align_self,aspect_ratio, absolute insets,hidden, andz_index. - Box model —
Fixed(n)is always the outer box (like CSSborder-box). Borders default toBoxSizing::Overlaid(painted inside without affecting layout); setFlex::box_sizing = BoxSizing::BorderBoxfor CSS border-box inset behaviour. - Visuals —
Tree::set_decoradds per-side borders, multi-stop linear/radial gradients, and offset shadows.set_transformapplies draw-time scale, rotation, and translation around a pivot (layout stays untransformed; children hit-test through it).set_image_modeselects stretch, contain, cover, or natural sizing with optional mirroring. - Incremental updates — Setting an unchanged value is a no-op. Resizes relayout only from the nearest size-isolated ancestor, and frames redraw only the damaged region.
- Retained canvas nodes — Record immediate
Drawcommands and replay them across damaged regions until invalidated or resized. - Interaction & animation — Hit testing respects clipping, visibility, and
Tree::set_hit_through(pointer-events: none). Focus traversal draws a focus ring; scroll containers ease mouse wheel deltas with a spring while applying trackpad deltas directly. Spring animations step opacity and offset natively without host callbacks. - Headless layout & accessibility —
Tree::layout(fonts, width, height)lays out and hit-tests trees in unit tests without a GPU or window. Nodes carry accessibility roles/labels for platform adapters (such as VoiceOver via AccessKit) and text tree dumps.
Components (ui/view)
engine-ui-view (ui/view/) runs Elm-style components on the retained tree, after Effect UI's: a Component has Props, a Model, Messages and an Output, a pure update(model, message) that may hand one output to whoever holds it, and a view(props, model) that returns an Element.
- Elements — Built by chained calls (
row().px(8.0).gap(5.0).bg(colour).on_press(message).child(text(font, "Save", colour))): flex layout, paint, text (with runs and eliding), images, keys, press and hover messages, roles, focus and hit-through.memo(key, props, build)builds a subtree only when its props change. - Mounting —
Mount::new(parent, before, model)places a component under a node.render(nodes, props)renders when the props differ or a message reached the model (otherwise one comparison);render_againafter a message. Each render reconciles the view with the nodes made last time, by key or by position among unkeyed elements of a kind, and sets only what changed (Mount::workcounts it); memoized children that leave a list are detached and parked, and come back without new nodes. - Input —
press(nodes, hit)andhover(nodes, hit)walk up from the node the tree hit to the nearest element with a message and send it to the update;message_atasks without sending. Hover and press fills stay the tree's own. - The tree —
Nodesis the tree calls a mount makes;Treeand&mut Treeimplement it, and a host that reaches its tree through a handle implements it for that handle. - Tests —
Story::given(model).send(message)drives an update with no nodes; a mount on a bareTreelaid out byTree::layoutanswers bounds and presses without a host or GPU (ui/view/tests). - Kit —
kitholds behaviours without a look:place_at/place_withinkeep a popup inside the window,step/firstmove through enabled items,Typeaheadselects by typed prefix.
examples/counter.rs is a counter as a component (cargo run -p engine-ui-view --example counter).
Text & Fonts (ui/src/fonts.rs)
- Shaping & fallback —
harfrustshapes each line face-run by face-run with automatic system fallback (CJK, symbols, colour emoji, Arial Unicode). Colour emoji readsbix/CBDTstrikes and rasterize as RGBA into the glyph atlas. - Hinting & rasterization — TrueType outlines use
engine_gfx::autofit(a port of FreeType 2.14's automatic hinter, including variable fontgvardeltas); CFF outlines useskrifa's PostScript hinter;engine_gfx::rasterrenders smooth coverage bitmaps into a 2048×2048 atlas at quarter-pixel horizontal phase. Fractional font sizes (font_sized,font_file_sized,font_variable_sized) key by 1/64th pixel. - Rich text & wrapping —
Tree::set_text_runsshapes single-font coloured spans together to preserve kerning.Tree::set_text_styleconfigures wrapping (spaces and UAX #14 slashes), alignment (left, centre, right, justify), line height, and text shadows. - Caching — Shaped lines cache up to 16,384 entries per font.
Host::statsreports instances, draws, layers, shaped lines, cache hits, and rasterized glyphs per frame.