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::draw lends Draw for immediate-mode drawing (also passed to a canvas node's closure via Host::set_canvas_draw).
  • Host::tree / Host::tree_mut expose the retained Tree (ui/src/tree.rs).
  • Host::set_cursor_visible, decode_pixels / decode_image, Host::window_size / set_window_size, display_interval_ms, and Waker (waking a window from any thread).
  • Each window owns its own Host on the main thread; polling routes SDL events to the owning window and wakes the shared event loop.
  • InputState (ui/src/input.rs) folds events into keys and pointer buttons (Buttons tracking held, just pressed, and just released since end_frame), pointer position, and touch fingers using SDL keycodes in input::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 — Calling Host::engine_draw_begin switches that frame through engine-gfx so embedded 2D/3D engine views composite cleanly between canvas layers.
  • HUD over stage passes — Host::tree_frame_over takes a Passes closure that records host render passes (such as StageRenderer::record) into the canvas's window-sized texture, then loads and draws the toolkit tree on top in one presentation. Host::capture reads back the composed image without re-recording. See ui/examples/stage_hud.rs.
  • Linear-light blending — Default on new hosts (HostOptions::default(), toggleable via Host::set_linear_blending / Canvas::set_linear_blending). Draws through kitFragmentLinear into an Rgba8UnormSrgb view (Device::create_srgb_view) so hardware decodes on blend and encodes on write with zero extra copy passes. Hosts requiring legacy encoded blending open with HostOptions::encoded().
  • Headless & captures — Host::open_headless renders offscreen without showing a window. Host::capture_pixels returns 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_flex adds CSS-style margins (Auto included), min/max sizes, grow, shrink (default 0), basis, align_self, aspect_ratio, absolute insets, hidden, and z_index.
  • Box model — Fixed(n) is always the outer box (like CSS border-box). Borders default to BoxSizing::Overlaid (painted inside without affecting layout); set Flex::box_sizing = BoxSizing::BorderBox for CSS border-box inset behaviour.
  • Visuals — Tree::set_decor adds per-side borders, multi-stop linear/radial gradients, and offset shadows. set_transform applies draw-time scale, rotation, and translation around a pivot (layout stays untransformed; children hit-test through it). set_image_mode selects 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 Draw commands 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_again after 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::work counts it); memoized children that leave a list are detached and parked, and come back without new nodes.
  • Input — press(nodes, hit) and hover(nodes, hit) walk up from the node the tree hit to the nearest element with a message and send it to the update; message_at asks without sending. Hover and press fills stay the tree's own.
  • The tree — Nodes is the tree calls a mount makes; Tree and &mut Tree implement 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 bare Tree laid out by Tree::layout answers bounds and presses without a host or GPU (ui/view/tests).
  • Kit — kit holds behaviours without a look: place_at / place_within keep a popup inside the window, step / first move through enabled items, Typeahead selects 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 — harfrust shapes each line face-run by face-run with automatic system fallback (CJK, symbols, colour emoji, Arial Unicode). Colour emoji read sbix / CBDT strikes 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 font gvar deltas); CFF outlines use skrifa's PostScript hinter; engine_gfx::raster renders 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_runs shapes single-font coloured spans together to preserve kerning. Tree::set_text_style configures 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::stats reports instances, draws, layers, shaped lines, cache hits, and rasterized glyphs per frame.