Skip to main content

blit/
lib.rs

1//! a small immediate-mode library for building user interfaces
2//!
3//! # frame lifecycle
4//!
5//! every frame builds the [`Tree`] from scratch, then lays it out and paints it
6//!
7//! 1. [`Tree::build`] runs your [`Widget`]s. they add and describe nodes, but nothing is sized
8//!    or drawn yet. a node defers its own content to closures from [`Ui::measure`] and
9//!    [`Ui::paint`]
10//! 2. [`Tree::layout`] sizes and positions every node, running each layout and measure closure
11//! 3. [`Tree::paint`] runs each paint closure with its node's solved area
12//!
13//! # layout
14//!
15//! a node arranges its children with the [`Layout`] from [`Ui::layout`]. each child can pass
16//! the layout a [`Layout::Item`] through [`Ui::item`]
17//!
18//! a layout works one axis at a time
19//!
20//! - [`Layout::fit`] reports the smallest and natural extents of the content
21//! - [`Layout::distribute`] splits the final extent and positions the children
22//!
23//! [`Ui::place`] positions a node outside its parent's flow, relative to a target node, with a
24//! [`Place`]. popovers use this
25//!
26//! # interaction
27//!
28//! [`Ui::interact`] adds an [`Interact`] to a node and returns its latest response.
29//! interactions run before each build using the last build's layout, so a widget sees this
30//! frame's input while it builds
31//!
32//! # identity
33//!
34//! every node receives a stable [`Id`] matched across frames without hashing
35//!
36//! - [`Ui::child`] matches by parent and call site
37//! - [`Ui::child_in`] matches by an integer [`Key`] in a [`Scope`] (from [`Ui::scope`] or [`Scope::ROOT`])
38//! - [`Ui::resolve`] turns a scope and key into its [`Id`] before the node is built
39//! - [`Ui::node`] queries a node's previous area or attaches interactions by [`Id`]
40//!
41//! an [`Id`] stops resolving once its node is absent for a full build, so resolve from a scope
42//! and key each frame rather than storing [`Id`]s across frames
43//!
44//! ```
45//! # use blit::{Context, Ui};
46//! fn list<C: Context>(mut ui: Ui<'_, C>, rows: &[u32]) {
47//!     let scope = ui.scope();
48//!     let mut column = ui.layout(());
49//!     for &row in rows {
50//!         // keyed by row, so each keeps its state when the list reorders
51//!         column.child_in(scope, row).insert(());
52//!     }
53//! }
54//! ```
55//!
56//! # context
57//!
58//! everything is generic over a [`Context`], which carries frame wide resources such as a
59//! renderer, theme, or asset cache into every widget, layout and paint closure. keep application
60//! state in your app and pass it down explicitly. a context opts into capabilities:
61//!
62//! - [`Paint<T>`](Paint) draws command `T`. paint callbacks send commands through it
63//! - [`HasFrameStore`] provides a [`FrameStore`] for data that lasts the whole frame
64//!
65//! # storage
66//!
67//! blit provides two ways to store temporary data without allocating:
68//!
69//! - [`Scratch`] lasts until the current scope ends
70//!   - [`Ui::scratch`]
71//!   - [`LayoutCx::scratch`]
72//!   - [`PaintCx::scratch`]
73//! - [`FrameSlice`] lasts the whole frame. use it for data a draw command reads later
74//!   - [`HasFrameStore`]
75
76#![no_std]
77
78extern crate alloc;
79
80pub use self::{
81    animation::{Animation, AnimationOptions, Easing, Motion, MotionProps, Spring, Tween},
82    frame_store::{FrameSlice, FrameSliceBuilder, FrameStore, FrameStoreMut, HasFrameStore},
83    geometry::{
84        Constraints, Corners, LogicalPoint, LogicalRect, LogicalSize, PhysicalPoint, PhysicalRect, PhysicalSize, Point,
85        Rect, Scalar, Scale2, Sides, Size,
86    },
87    interact::{Contact, ContactId, ContactSource, Contacts, Interact, InteractCx, KeyboardEvent, Phase, ScrollEvent},
88    layout::{Axis, Children, Fit, Layout, LayoutCx, Place, PlaceCx},
89    node::NodeId,
90    paint::PaintCx,
91    scratch::{Scratch, ScratchBuffer, ScratchStr, StrSource},
92    timer::Timer,
93    ui::{Ui, state},
94};
95
96mod animation;
97mod arena;
98mod frame_store;
99mod geometry;
100mod interact;
101mod layout;
102mod macros;
103mod math;
104mod node;
105mod paint;
106mod scratch;
107mod timer;
108mod ui;
109
110pub mod input;
111
112#[doc(hidden)]
113pub mod internal;
114
115use alloc::vec::Vec;
116use core::{
117    any::TypeId,
118    marker::PhantomData,
119    num::NonZeroU32,
120    ops::{BitOr, BitOrAssign},
121    panic::Location,
122    time::Duration,
123};
124
125use self::{
126    animation::{AnimationState, MotionState, Playback},
127    arena::{BumpArena, BumpId},
128    input::{Input, KeyInput, MouseButton, ScrollPhase, TouchPhase},
129    interact::InteractionState,
130    internal::{
131        animator::Animator,
132        bump::{Bump, Offset},
133    },
134    node::*,
135    timer::TimerState,
136};
137
138/// resources shared by every widget, layout and painter in a frame
139pub trait Context {
140    /// coordinate type for all frame geometry
141    type Scalar: Scalar;
142
143    /// the node built at `location` repeats `key` in `scope` and takes a fresh id instead
144    fn duplicate_key(&mut self, _scope: Scope, _key: u64, _location: &'static Location<'static>) {}
145}
146
147impl Context for () {
148    type Scalar = f32;
149}
150
151/// accepts one kind of drawing operation in frame coordinates
152pub trait Paint<T>: Context {
153    /// area supplies placement and dimensions while the operation defines any outsets
154    fn paint(&mut self, area: Rect<Self::Scalar>, command: &T);
155}
156
157builder! {
158    #[derive(Clone, Copy, Debug, PartialEq)]
159    pub struct FrameInfo<T> {
160        new(size: Size<T>),
161    }
162}
163
164/// builds part of the ui each frame and returns a response such as whether it was clicked
165///
166/// - by default a widget owns a node it can lay out
167/// - [`state::Insert`] widgets add content like text or backgrounds to the node through [`Ui::insert`]
168///   without changing the node itself
169pub trait Widget<C: Context, S = state::Build> {
170    type Response;
171
172    fn build(self, ui: Ui<'_, C, S>) -> Self::Response;
173}
174
175/// stable identity for widgets, animations and timers, handed out by [`Tree`]
176///
177/// each build matches a node to the previous build by its parent and call site, or by its key
178/// in a scope, and the node keeps the id it matched. an id stops resolving once its node is gone.
179#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
180pub struct Id {
181    slot: u32,
182    generation: NonZeroU32,
183}
184
185impl Id {
186    /// the tree root
187    pub const ROOT: Self = Self {
188        slot: 0,
189        generation: NonZeroU32::MIN,
190    };
191}
192
193/// a space of keys, so keys from unrelated code never meet
194///
195/// [`Ui::scope`] makes one owned by a node and a call site, and [`Scope::ROOT`] belongs to the app
196#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
197pub struct Scope(Id);
198
199impl Scope {
200    /// the app's own scope, which widgets leave alone
201    pub const ROOT: Self = Self(Id::ROOT);
202}
203
204/// a key in a [`Scope`], any integer widened so one value names one node whatever its type
205pub trait Key: Copy {
206    fn value(self) -> u64;
207}
208
209macro_rules! key {
210    ($($integer:ty),*) => {$(
211        impl Key for $integer {
212            fn value(self) -> u64 {
213                self as u64
214            }
215        }
216    )*};
217}
218
219key!(u8, u16, u32, u64, usize, i8, i16, i32, i64, isize);
220
221impl<C: Context, F, O> Widget<C> for F
222where
223    F: FnOnce(Ui<'_, C>) -> O,
224{
225    type Response = O;
226
227    fn build(self, ui: Ui<'_, C>) -> Self::Response {
228        self(ui)
229    }
230}
231
232impl<C: Context> Widget<C, state::Insert> for () {
233    type Response = ();
234
235    fn build(self, _: Ui<'_, C, state::Insert>) {}
236}
237
238pub struct Tree<C: Context> {
239    //
240    // current build
241    //
242    nodes: Vec<StoredNode>,
243    // how each node was told apart from its siblings, kept apart so nodes fit one cache line
244    marks: Vec<Mark>,
245    placements: Vec<Rect<C::Scalar>>,
246    // sparse paint order offsets, empty when all zero
247    z_indices: Vec<i16>,
248    // each node's clip, resolved after layout, empty when no clips
249    resolved_clips: Vec<ResolvedClipId>,
250    measures: Vec<StoredMeasure<C>>,
251    paints: Vec<StoredPaint<C>>,
252    aux: Vec<Aux<C::Scalar>>,
253    places: Vec<StoredPlace<C>>,
254    node_motions: Vec<NodeMotion>,
255    /// nodes in paint order, empty when tree order
256    paint_order: Vec<NodeId>,
257    /// call sites of children under the open nodes
258    sites: Vec<Site>,
259    bump: BumpArena,
260    scratch: ScratchBuffer,
261    has_custom_order: bool,
262    has_clips: bool,
263
264    //
265    // latest layout
266    //
267    old_nodes: Vec<StoredNode>,
268    old_marks: Vec<Mark>,
269    old_placements: Vec<Rect<C::Scalar>>,
270
271    //
272    // retained state
273    //
274    slots: Slots,
275    interaction: InteractionState<C::Scalar>,
276    animations: Vec<AnimationState>,
277    // the scopes made by call sites, sorted by call
278    scopes: Vec<CallScope>,
279    motions: Vec<MotionState<C::Scalar>>,
280    timers: Vec<TimerState>,
281    /// focus requested during this build, applied once it resolves
282    focus: FocusRequest,
283
284    //
285    // node kinds
286    //
287    layout_kinds: Vec<LayoutKind<C>>,
288
289    //
290    // frame inputs
291    //
292    input: Input<C::Scalar>,
293    time: Duration,
294    screen: Rect<C::Scalar>,
295    resized: bool,
296    frame_requested: bool,
297    /// the next frame updates interactions against this layout
298    settle: bool,
299}
300
301impl<C: Context> Default for Tree<C> {
302    fn default() -> Self {
303        Self {
304            nodes: Vec::new(),
305            marks: Vec::new(),
306            placements: Vec::new(),
307            z_indices: Vec::new(),
308            resolved_clips: Vec::new(),
309            measures: Vec::new(),
310            paints: Vec::new(),
311            aux: Vec::new(),
312            places: Vec::new(),
313            node_motions: Vec::new(),
314            paint_order: Vec::new(),
315            sites: Vec::new(),
316            bump: BumpArena::default(),
317            scratch: ScratchBuffer::default(),
318            has_custom_order: false,
319            has_clips: false,
320
321            old_nodes: Vec::new(),
322            old_marks: Vec::new(),
323            old_placements: Vec::new(),
324
325            slots: Slots::default(),
326            interaction: InteractionState::default(),
327            animations: Vec::new(),
328            scopes: Vec::new(),
329            motions: Vec::new(),
330            timers: Vec::new(),
331            focus: FocusRequest::Keep,
332
333            layout_kinds: Vec::new(),
334
335            input: Input::None,
336            time: Duration::ZERO,
337            screen: Rect::default(),
338            resized: false,
339            frame_requested: true,
340            settle: false,
341        }
342    }
343}
344
345impl<C: Context> Tree<C> {
346    /// rebuilds the tree for one input
347    ///
348    /// call [`Self::layout`] after every build, as the next build reads that layout
349    pub fn build<W: Widget<C>>(
350        &mut self,
351        context: &mut C,
352        info: FrameInfo<C::Scalar>,
353        time: Duration,
354        input: Input<C::Scalar>,
355        widget: W,
356    ) -> W::Response {
357        // interactions update against the previous layout, so every frame settles in one more
358        // unless nothing but settling built it
359        let settling = match input {
360            Input::None => {
361                core::mem::take(&mut self.settle)
362                    && !self.has_pending_redraw()
363                    && self.screen.size() == info.size
364                    && self.next_timer_deadline().is_none_or(|deadline| deadline > time)
365            }
366            _ => false,
367        };
368        self.settle = !settling;
369        self.frame_requested = false;
370        // interactions update against the previous build's nodes
371        self.interaction.begin(&input, time, &self.nodes);
372        core::mem::swap(&mut self.nodes, &mut self.old_nodes);
373        core::mem::swap(&mut self.marks, &mut self.old_marks);
374        core::mem::swap(&mut self.placements, &mut self.old_placements);
375        self.nodes.clear();
376        self.marks.clear();
377        self.placements.clear();
378        self.z_indices.clear();
379        self.has_custom_order = false;
380        self.has_clips = false;
381        self.slots.begin();
382        self.focus = FocusRequest::Keep;
383        self.measures.clear();
384        self.paints.clear();
385        self.aux.clear();
386        self.places.clear();
387        self.node_motions.clear();
388        self.sites.clear();
389        self.bump.clear();
390        for kind in &mut self.layout_kinds {
391            kind.default_item = BumpId::NONE;
392        }
393        self.paint_order.clear();
394        self.input = input;
395        self.time = time;
396        let size = info.size;
397        self.resized = self.screen.size() != size;
398        self.screen = Rect::new(C::Scalar::ZERO, C::Scalar::ZERO, size.width, size.height);
399        for animation in &mut self.animations {
400            animation.seen = false;
401        }
402        for state in &mut self.motions {
403            state.seen = false;
404        }
405        for timer in &mut self.timers {
406            timer.seen = false;
407        }
408
409        let root = self.push_node(None, Id::ROOT, Mark::Named);
410        let mut scratch = core::mem::take(&mut self.scratch);
411        scratch.prepare();
412        let old = self.slots.old(Id::ROOT).map_or(Slots::NONE, |node| node as u32);
413        let output = widget.build(Ui::new(self, context, &scratch, root, old));
414        scratch.prepare();
415        self.scratch = scratch;
416        // a scope this build did not make dies with the next one
417        let slots = &self.slots;
418        self.scopes.retain(|scope| slots.is_kept(scope.id));
419        assert_eq!(
420            self.nodes[0].subtree_end as usize,
421            self.nodes.len() - 1,
422            "a frame must have exactly one root"
423        );
424        output
425    }
426
427    /// resolves layout, positioning, clipping and interaction for the built tree
428    pub fn layout(&mut self, context: &mut C) {
429        let mut bump = core::mem::take(&mut self.bump);
430        bump.storage.prepare();
431        layout::resolve(
432            self,
433            &bump,
434            context,
435            NodeId::new(0),
436            Constraints::tight(self.screen.size()),
437            true,
438        );
439        layout::position(self);
440        for state in &mut self.motions {
441            state.flying &= state.is_active();
442        }
443        // a lifted node paints above everything under its lift target while it flies to a new reference
444        for index in 0..self.node_motions.len() {
445            let NodeMotion {
446                node,
447                motion: Motion { lift: Some(lift), .. },
448            } = self.node_motions[index]
449            else {
450                continue;
451            };
452            let id = self.nodes[node.index()].id;
453            let flying = self
454                .motions
455                .binary_search_by_key(&id, |state| state.id)
456                .is_ok_and(|state| self.motions[state].flying);
457            // a target that was not built before the node leaves it with its own parent
458            if flying && let Some(parent) = ui::resolve_target(self, node, lift) {
459                self.aux_mut(node).visual_parent = parent;
460                self.set_z_index(node, i16::MAX);
461                self.has_custom_order = true;
462            }
463        }
464        paint::resolve_order(self, &bump);
465        paint::resolve_clips(self);
466        // interactions bind against this build
467        interact::resolve(self);
468        self.animations.retain(|animation| animation.seen);
469        self.motions.retain(|state| state.seen);
470        self.timers.retain(|timer| timer.seen);
471        bump.storage.prepare();
472        self.bump = bump;
473    }
474
475    /// paints the resolved tree and releases its retained values
476    pub fn paint(
477        &mut self,
478        context: &mut C,
479        push_clip: impl FnMut(&mut C, Rect<C::Scalar>, Corners<C::Scalar>),
480        pop_clip: impl FnMut(&mut C),
481    ) {
482        let mut bump = core::mem::take(&mut self.bump);
483        paint::paint(self, &bump, context, push_clip, pop_clip);
484        bump.clear();
485        self.bump = bump;
486    }
487
488    pub fn has_pending_redraw(&self) -> bool {
489        self.frame_requested
490            || self.settle
491            || self.animations.iter().any(AnimationState::is_active)
492            || self.motions.iter().any(MotionState::is_active)
493    }
494
495    pub fn next_timer_deadline(&self) -> Option<Duration> {
496        self.timers
497            .iter()
498            .filter_map(TimerState::deadline)
499            .chain(self.interaction.deadline)
500            .min()
501    }
502
503    pub fn request_frame(&mut self) {
504        self.frame_requested = true;
505    }
506
507    /// returns the area of the node with `id` in the latest layout
508    ///
509    /// valid after [`Self::layout`]
510    pub fn area(&self, id: Id) -> Option<Rect<C::Scalar>> {
511        let node = self.slots.node(id)?;
512        self.placements.get(node.index()).copied()
513    }
514
515    /// the id keyed `key` in `scope`, if anything holds it
516    pub fn find(&self, scope: Scope, key: impl Key) -> Option<Id> {
517        self.slots.find(scope.0, key.value())
518    }
519}
520
521//
522// internals
523//
524
525impl<C: Context> Tree<C> {
526    /// pushes a node and assigns `id` to it
527    #[inline(always)]
528    fn push_node(&mut self, parent: Option<NodeId>, id: Id, mark: Mark) -> NodeId {
529        let node = NodeId::new(self.nodes.len());
530        let place_scope = parent.map_or(node, |parent| self.nodes[parent.index()].place_scope);
531        self.slots.set(id, node);
532        self.marks.push(mark);
533        self.nodes.push(StoredNode {
534            id,
535            parent: parent.unwrap_or(node),
536            subtree_end: node.index() as u32,
537            first_measure: StoredMeasureId::NONE,
538            last_paint: StoredPaintId::NONE,
539            layout: BumpId::NONE,
540            layout_kind: 0,
541            aux: AuxId::NONE,
542            place: PlaceId::NONE,
543            place_scope,
544            item: BumpId::NONE,
545            target: parent.unwrap_or(node),
546            interactive: false,
547        });
548        node
549    }
550
551    fn set_z_index(&mut self, node: NodeId, z_index: i16) {
552        if z_index != 0 {
553            self.has_custom_order = true;
554        } else if self.z_indices.is_empty() {
555            return;
556        }
557        let index = node.index();
558        if self.z_indices.len() <= index {
559            self.z_indices.resize(index + 1, 0);
560        }
561        self.z_indices[index] = z_index;
562    }
563
564    fn aux_mut(&mut self, node: NodeId) -> &mut Aux<C::Scalar> {
565        let stored = &mut self.nodes[node.index()];
566        let index = match stored.aux.index() {
567            Some(index) => index,
568            None => {
569                stored.aux = AuxId::new(self.aux.len());
570                self.aux.push(Aux {
571                    visual_parent: stored.parent,
572                    clip: None,
573                    limits: Constraints::loose(Size::uniform(C::Scalar::UNBOUNDED)),
574                    padding: Sides::all(C::Scalar::ZERO),
575                    hit: Sides::all(C::Scalar::ZERO),
576                    motion: NodeMotionId::NONE,
577                });
578                self.aux.len() - 1
579            }
580        };
581        &mut self.aux[index]
582    }
583}
584
585#[cfg(doctest)]
586#[doc = include_str!("../tests/compile_fail.md")]
587mod compile_fail {}