blit-ui 0.1.0

an experimental immediate-mode ui library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
//! a small immediate-mode library for building user interfaces
//!
//! # frame lifecycle
//!
//! every frame builds the [`Tree`] from scratch, then lays it out and paints it
//!
//! 1. [`Tree::build`] runs your [`Widget`]s. they add and describe nodes, but nothing is sized
//!    or drawn yet. a node defers its own content to closures from [`Ui::measure`] and
//!    [`Ui::paint`]
//! 2. [`Tree::layout`] sizes and positions every node, running each layout and measure closure
//! 3. [`Tree::paint`] runs each paint closure with its node's solved area
//!
//! # layout
//!
//! a node arranges its children with the [`Layout`] from [`Ui::layout`]. each child can pass
//! the layout a [`Layout::Item`] through [`Ui::item`]
//!
//! a layout works one axis at a time
//!
//! - [`Layout::fit`] reports the smallest and natural extents of the content
//! - [`Layout::distribute`] splits the final extent and positions the children
//!
//! [`Ui::place`] positions a node outside its parent's flow, relative to a target node, with a
//! [`Place`]. popovers use this
//!
//! # interaction
//!
//! [`Ui::interact`] adds an [`Interact`] to a node and returns its latest response.
//! interactions run before each build using the last build's layout, so a widget sees this
//! frame's input while it builds
//!
//! # identity
//!
//! every node receives a stable [`Id`] matched across frames without hashing
//!
//! - [`Ui::child`] matches by parent and call site
//! - [`Ui::child_in`] matches by an integer [`Key`] in a [`Scope`] (from [`Ui::scope`] or [`Scope::ROOT`])
//! - [`Ui::resolve`] turns a scope and key into its [`Id`] before the node is built
//! - [`Ui::node`] queries a node's previous area or attaches interactions by [`Id`]
//!
//! an [`Id`] stops resolving once its node is absent for a full build, so resolve from a scope
//! and key each frame rather than storing [`Id`]s across frames
//!
//! ```
//! # use blit::{Context, Ui};
//! fn list<C: Context>(mut ui: Ui<'_, C>, rows: &[u32]) {
//!     let scope = ui.scope();
//!     let mut column = ui.layout(());
//!     for &row in rows {
//!         // keyed by row, so each keeps its state when the list reorders
//!         column.child_in(scope, row).insert(());
//!     }
//! }
//! ```
//!
//! # context
//!
//! everything is generic over a [`Context`], which carries frame wide resources such as a
//! renderer, theme, or asset cache into every widget, layout and paint closure. keep application
//! state in your app and pass it down explicitly. a context opts into capabilities:
//!
//! - [`Paint<T>`](Paint) draws command `T`. paint callbacks send commands through it
//! - [`HasFrameStore`] provides a [`FrameStore`] for data that lasts the whole frame
//!
//! # storage
//!
//! blit provides two ways to store temporary data without allocating:
//!
//! - [`Scratch`] lasts until the current scope ends
//!   - [`Ui::scratch`]
//!   - [`LayoutCx::scratch`]
//!   - [`PaintCx::scratch`]
//! - [`FrameSlice`] lasts the whole frame. use it for data a draw command reads later
//!   - [`HasFrameStore`]

#![no_std]

extern crate alloc;

pub use self::{
    animation::{Animation, AnimationOptions, Easing, Motion, MotionProps, Spring, Tween},
    frame_store::{FrameSlice, FrameSliceBuilder, FrameStore, FrameStoreMut, HasFrameStore},
    geometry::{
        Constraints, Corners, LogicalPoint, LogicalRect, LogicalSize, PhysicalPoint, PhysicalRect, PhysicalSize, Point,
        Rect, Scalar, Scale2, Sides, Size,
    },
    interact::{Contact, ContactId, ContactSource, Contacts, Interact, InteractCx, KeyboardEvent, Phase, ScrollEvent},
    layout::{Axis, Children, Fit, Layout, LayoutCx, Place, PlaceCx},
    node::NodeId,
    paint::PaintCx,
    scratch::{Scratch, ScratchBuffer, ScratchStr, StrSource},
    timer::Timer,
    ui::{Ui, state},
};

mod animation;
mod arena;
mod frame_store;
mod geometry;
mod interact;
mod layout;
mod macros;
mod math;
mod node;
mod paint;
mod scratch;
mod timer;
mod ui;

pub mod input;

#[doc(hidden)]
pub mod internal;

use alloc::vec::Vec;
use core::{
    any::TypeId,
    marker::PhantomData,
    num::NonZeroU32,
    ops::{BitOr, BitOrAssign},
    panic::Location,
    time::Duration,
};

use self::{
    animation::{AnimationState, MotionState, Playback},
    arena::{BumpArena, BumpId},
    input::{Input, KeyInput, MouseButton, ScrollPhase, TouchPhase},
    interact::InteractionState,
    internal::{
        animator::Animator,
        bump::{Bump, Offset},
    },
    node::*,
    timer::TimerState,
};

/// resources shared by every widget, layout and painter in a frame
pub trait Context {
    /// coordinate type for all frame geometry
    type Scalar: Scalar;

    /// the node built at `location` repeats `key` in `scope` and takes a fresh id instead
    fn duplicate_key(&mut self, _scope: Scope, _key: u64, _location: &'static Location<'static>) {}
}

impl Context for () {
    type Scalar = f32;
}

/// accepts one kind of drawing operation in frame coordinates
pub trait Paint<T>: Context {
    /// area supplies placement and dimensions while the operation defines any outsets
    fn paint(&mut self, area: Rect<Self::Scalar>, command: &T);
}

builder! {
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct FrameInfo<T> {
        new(size: Size<T>),
    }
}

/// builds part of the ui each frame and returns a response such as whether it was clicked
///
/// - by default a widget owns a node it can lay out
/// - [`state::Insert`] widgets add content like text or backgrounds to the node through [`Ui::insert`]
///   without changing the node itself
pub trait Widget<C: Context, S = state::Build> {
    type Response;

    fn build(self, ui: Ui<'_, C, S>) -> Self::Response;
}

/// stable identity for widgets, animations and timers, handed out by [`Tree`]
///
/// each build matches a node to the previous build by its parent and call site, or by its key
/// in a scope, and the node keeps the id it matched. an id stops resolving once its node is gone.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Id {
    slot: u32,
    generation: NonZeroU32,
}

impl Id {
    /// the tree root
    pub const ROOT: Self = Self {
        slot: 0,
        generation: NonZeroU32::MIN,
    };
}

/// a space of keys, so keys from unrelated code never meet
///
/// [`Ui::scope`] makes one owned by a node and a call site, and [`Scope::ROOT`] belongs to the app
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Scope(Id);

impl Scope {
    /// the app's own scope, which widgets leave alone
    pub const ROOT: Self = Self(Id::ROOT);
}

/// a key in a [`Scope`], any integer widened so one value names one node whatever its type
pub trait Key: Copy {
    fn value(self) -> u64;
}

macro_rules! key {
    ($($integer:ty),*) => {$(
        impl Key for $integer {
            fn value(self) -> u64 {
                self as u64
            }
        }
    )*};
}

key!(u8, u16, u32, u64, usize, i8, i16, i32, i64, isize);

impl<C: Context, F, O> Widget<C> for F
where
    F: FnOnce(Ui<'_, C>) -> O,
{
    type Response = O;

    fn build(self, ui: Ui<'_, C>) -> Self::Response {
        self(ui)
    }
}

impl<C: Context> Widget<C, state::Insert> for () {
    type Response = ();

    fn build(self, _: Ui<'_, C, state::Insert>) {}
}

pub struct Tree<C: Context> {
    //
    // current build
    //
    nodes: Vec<StoredNode>,
    // how each node was told apart from its siblings, kept apart so nodes fit one cache line
    marks: Vec<Mark>,
    placements: Vec<Rect<C::Scalar>>,
    // sparse paint order offsets, empty when all zero
    z_indices: Vec<i16>,
    // each node's clip, resolved after layout, empty when no clips
    resolved_clips: Vec<ResolvedClipId>,
    measures: Vec<StoredMeasure<C>>,
    paints: Vec<StoredPaint<C>>,
    aux: Vec<Aux<C::Scalar>>,
    places: Vec<StoredPlace<C>>,
    node_motions: Vec<NodeMotion>,
    /// nodes in paint order, empty when tree order
    paint_order: Vec<NodeId>,
    /// call sites of children under the open nodes
    sites: Vec<Site>,
    bump: BumpArena,
    scratch: ScratchBuffer,
    has_custom_order: bool,
    has_clips: bool,

    //
    // latest layout
    //
    old_nodes: Vec<StoredNode>,
    old_marks: Vec<Mark>,
    old_placements: Vec<Rect<C::Scalar>>,

    //
    // retained state
    //
    slots: Slots,
    interaction: InteractionState<C::Scalar>,
    animations: Vec<AnimationState>,
    // the scopes made by call sites, sorted by call
    scopes: Vec<CallScope>,
    motions: Vec<MotionState<C::Scalar>>,
    timers: Vec<TimerState>,
    /// focus requested during this build, applied once it resolves
    focus: FocusRequest,

    //
    // node kinds
    //
    layout_kinds: Vec<LayoutKind<C>>,

    //
    // frame inputs
    //
    input: Input<C::Scalar>,
    time: Duration,
    screen: Rect<C::Scalar>,
    resized: bool,
    frame_requested: bool,
    /// the next frame updates interactions against this layout
    settle: bool,
}

impl<C: Context> Default for Tree<C> {
    fn default() -> Self {
        Self {
            nodes: Vec::new(),
            marks: Vec::new(),
            placements: Vec::new(),
            z_indices: Vec::new(),
            resolved_clips: Vec::new(),
            measures: Vec::new(),
            paints: Vec::new(),
            aux: Vec::new(),
            places: Vec::new(),
            node_motions: Vec::new(),
            paint_order: Vec::new(),
            sites: Vec::new(),
            bump: BumpArena::default(),
            scratch: ScratchBuffer::default(),
            has_custom_order: false,
            has_clips: false,

            old_nodes: Vec::new(),
            old_marks: Vec::new(),
            old_placements: Vec::new(),

            slots: Slots::default(),
            interaction: InteractionState::default(),
            animations: Vec::new(),
            scopes: Vec::new(),
            motions: Vec::new(),
            timers: Vec::new(),
            focus: FocusRequest::Keep,

            layout_kinds: Vec::new(),

            input: Input::None,
            time: Duration::ZERO,
            screen: Rect::default(),
            resized: false,
            frame_requested: true,
            settle: false,
        }
    }
}

impl<C: Context> Tree<C> {
    /// rebuilds the tree for one input
    ///
    /// call [`Self::layout`] after every build, as the next build reads that layout
    pub fn build<W: Widget<C>>(
        &mut self,
        context: &mut C,
        info: FrameInfo<C::Scalar>,
        time: Duration,
        input: Input<C::Scalar>,
        widget: W,
    ) -> W::Response {
        // interactions update against the previous layout, so every frame settles in one more
        // unless nothing but settling built it
        let settling = match input {
            Input::None => {
                core::mem::take(&mut self.settle)
                    && !self.has_pending_redraw()
                    && self.screen.size() == info.size
                    && self.next_timer_deadline().is_none_or(|deadline| deadline > time)
            }
            _ => false,
        };
        self.settle = !settling;
        self.frame_requested = false;
        // interactions update against the previous build's nodes
        self.interaction.begin(&input, time, &self.nodes);
        core::mem::swap(&mut self.nodes, &mut self.old_nodes);
        core::mem::swap(&mut self.marks, &mut self.old_marks);
        core::mem::swap(&mut self.placements, &mut self.old_placements);
        self.nodes.clear();
        self.marks.clear();
        self.placements.clear();
        self.z_indices.clear();
        self.has_custom_order = false;
        self.has_clips = false;
        self.slots.begin();
        self.focus = FocusRequest::Keep;
        self.measures.clear();
        self.paints.clear();
        self.aux.clear();
        self.places.clear();
        self.node_motions.clear();
        self.sites.clear();
        self.bump.clear();
        for kind in &mut self.layout_kinds {
            kind.default_item = BumpId::NONE;
        }
        self.paint_order.clear();
        self.input = input;
        self.time = time;
        let size = info.size;
        self.resized = self.screen.size() != size;
        self.screen = Rect::new(C::Scalar::ZERO, C::Scalar::ZERO, size.width, size.height);
        for animation in &mut self.animations {
            animation.seen = false;
        }
        for state in &mut self.motions {
            state.seen = false;
        }
        for timer in &mut self.timers {
            timer.seen = false;
        }

        let root = self.push_node(None, Id::ROOT, Mark::Named);
        let mut scratch = core::mem::take(&mut self.scratch);
        scratch.prepare();
        let old = self.slots.old(Id::ROOT).map_or(Slots::NONE, |node| node as u32);
        let output = widget.build(Ui::new(self, context, &scratch, root, old));
        scratch.prepare();
        self.scratch = scratch;
        // a scope this build did not make dies with the next one
        let slots = &self.slots;
        self.scopes.retain(|scope| slots.is_kept(scope.id));
        assert_eq!(
            self.nodes[0].subtree_end as usize,
            self.nodes.len() - 1,
            "a frame must have exactly one root"
        );
        output
    }

    /// resolves layout, positioning, clipping and interaction for the built tree
    pub fn layout(&mut self, context: &mut C) {
        let mut bump = core::mem::take(&mut self.bump);
        bump.storage.prepare();
        layout::resolve(
            self,
            &bump,
            context,
            NodeId::new(0),
            Constraints::tight(self.screen.size()),
            true,
        );
        layout::position(self);
        for state in &mut self.motions {
            state.flying &= state.is_active();
        }
        // a lifted node paints above everything under its lift target while it flies to a new reference
        for index in 0..self.node_motions.len() {
            let NodeMotion {
                node,
                motion: Motion { lift: Some(lift), .. },
            } = self.node_motions[index]
            else {
                continue;
            };
            let id = self.nodes[node.index()].id;
            let flying = self
                .motions
                .binary_search_by_key(&id, |state| state.id)
                .is_ok_and(|state| self.motions[state].flying);
            // a target that was not built before the node leaves it with its own parent
            if flying && let Some(parent) = ui::resolve_target(self, node, lift) {
                self.aux_mut(node).visual_parent = parent;
                self.set_z_index(node, i16::MAX);
                self.has_custom_order = true;
            }
        }
        paint::resolve_order(self, &bump);
        paint::resolve_clips(self);
        // interactions bind against this build
        interact::resolve(self);
        self.animations.retain(|animation| animation.seen);
        self.motions.retain(|state| state.seen);
        self.timers.retain(|timer| timer.seen);
        bump.storage.prepare();
        self.bump = bump;
    }

    /// paints the resolved tree and releases its retained values
    pub fn paint(
        &mut self,
        context: &mut C,
        push_clip: impl FnMut(&mut C, Rect<C::Scalar>, Corners<C::Scalar>),
        pop_clip: impl FnMut(&mut C),
    ) {
        let mut bump = core::mem::take(&mut self.bump);
        paint::paint(self, &bump, context, push_clip, pop_clip);
        bump.clear();
        self.bump = bump;
    }

    pub fn has_pending_redraw(&self) -> bool {
        self.frame_requested
            || self.settle
            || self.animations.iter().any(AnimationState::is_active)
            || self.motions.iter().any(MotionState::is_active)
    }

    pub fn next_timer_deadline(&self) -> Option<Duration> {
        self.timers
            .iter()
            .filter_map(TimerState::deadline)
            .chain(self.interaction.deadline)
            .min()
    }

    pub fn request_frame(&mut self) {
        self.frame_requested = true;
    }

    /// returns the area of the node with `id` in the latest layout
    ///
    /// valid after [`Self::layout`]
    pub fn area(&self, id: Id) -> Option<Rect<C::Scalar>> {
        let node = self.slots.node(id)?;
        self.placements.get(node.index()).copied()
    }

    /// the id keyed `key` in `scope`, if anything holds it
    pub fn find(&self, scope: Scope, key: impl Key) -> Option<Id> {
        self.slots.find(scope.0, key.value())
    }
}

//
// internals
//

impl<C: Context> Tree<C> {
    /// pushes a node and assigns `id` to it
    #[inline(always)]
    fn push_node(&mut self, parent: Option<NodeId>, id: Id, mark: Mark) -> NodeId {
        let node = NodeId::new(self.nodes.len());
        let place_scope = parent.map_or(node, |parent| self.nodes[parent.index()].place_scope);
        self.slots.set(id, node);
        self.marks.push(mark);
        self.nodes.push(StoredNode {
            id,
            parent: parent.unwrap_or(node),
            subtree_end: node.index() as u32,
            first_measure: StoredMeasureId::NONE,
            last_paint: StoredPaintId::NONE,
            layout: BumpId::NONE,
            layout_kind: 0,
            aux: AuxId::NONE,
            place: PlaceId::NONE,
            place_scope,
            item: BumpId::NONE,
            target: parent.unwrap_or(node),
            interactive: false,
        });
        node
    }

    fn set_z_index(&mut self, node: NodeId, z_index: i16) {
        if z_index != 0 {
            self.has_custom_order = true;
        } else if self.z_indices.is_empty() {
            return;
        }
        let index = node.index();
        if self.z_indices.len() <= index {
            self.z_indices.resize(index + 1, 0);
        }
        self.z_indices[index] = z_index;
    }

    fn aux_mut(&mut self, node: NodeId) -> &mut Aux<C::Scalar> {
        let stored = &mut self.nodes[node.index()];
        let index = match stored.aux.index() {
            Some(index) => index,
            None => {
                stored.aux = AuxId::new(self.aux.len());
                self.aux.push(Aux {
                    visual_parent: stored.parent,
                    clip: None,
                    limits: Constraints::loose(Size::uniform(C::Scalar::UNBOUNDED)),
                    padding: Sides::all(C::Scalar::ZERO),
                    hit: Sides::all(C::Scalar::ZERO),
                    motion: NodeMotionId::NONE,
                });
                self.aux.len() - 1
            }
        };
        &mut self.aux[index]
    }
}

#[cfg(doctest)]
#[doc = include_str!("../tests/compile_fail.md")]
mod compile_fail {}