#![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,
};
pub trait Context {
type Scalar: Scalar;
fn duplicate_key(&mut self, _scope: Scope, _key: u64, _location: &'static Location<'static>) {}
}
impl Context for () {
type Scalar = f32;
}
pub trait Paint<T>: Context {
fn paint(&mut self, area: Rect<Self::Scalar>, command: &T);
}
builder! {
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FrameInfo<T> {
new(size: Size<T>),
}
}
pub trait Widget<C: Context, S = state::Build> {
type Response;
fn build(self, ui: Ui<'_, C, S>) -> Self::Response;
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Id {
slot: u32,
generation: NonZeroU32,
}
impl Id {
pub const ROOT: Self = Self {
slot: 0,
generation: NonZeroU32::MIN,
};
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Scope(Id);
impl Scope {
pub const ROOT: Self = Self(Id::ROOT);
}
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> {
nodes: Vec<StoredNode>,
marks: Vec<Mark>,
placements: Vec<Rect<C::Scalar>>,
z_indices: Vec<i16>,
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>,
paint_order: Vec<NodeId>,
sites: Vec<Site>,
bump: BumpArena,
scratch: ScratchBuffer,
has_custom_order: bool,
has_clips: bool,
old_nodes: Vec<StoredNode>,
old_marks: Vec<Mark>,
old_placements: Vec<Rect<C::Scalar>>,
slots: Slots,
interaction: InteractionState<C::Scalar>,
animations: Vec<AnimationState>,
scopes: Vec<CallScope>,
motions: Vec<MotionState<C::Scalar>>,
timers: Vec<TimerState>,
focus: FocusRequest,
layout_kinds: Vec<LayoutKind<C>>,
input: Input<C::Scalar>,
time: Duration,
screen: Rect<C::Scalar>,
resized: bool,
frame_requested: bool,
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> {
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 {
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;
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;
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
}
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();
}
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);
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);
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;
}
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;
}
pub fn area(&self, id: Id) -> Option<Rect<C::Scalar>> {
let node = self.slots.node(id)?;
self.placements.get(node.index()).copied()
}
pub fn find(&self, scope: Scope, key: impl Key) -> Option<Id> {
self.slots.find(scope.0, key.value())
}
}
impl<C: Context> Tree<C> {
#[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 {}