use crate::*;
pub mod state {
use super::PhantomData;
pub struct Build;
pub struct Child<I>(PhantomData<I>);
pub struct Open<L>(PhantomData<L>);
pub struct Insert;
pub struct Ref;
pub trait Owned {}
impl Owned for Build {}
impl<I> Owned for Child<I> {}
impl<L> Owned for Open<L> {}
pub trait Local {}
impl Local for Build {}
impl<I> Local for Child<I> {}
impl<L> Local for Open<L> {}
impl Local for Insert {}
pub trait NoLayout: Owned + Local {}
impl NoLayout for Build {}
impl<I> NoLayout for Child<I> {}
}
pub struct Ui<'ui, C: Context, S = state::Build> {
inner: UiInner<'ui, C>,
marker: PhantomData<S>,
}
impl<'ui, C: Context, S> Ui<'ui, C, S> {
pub fn id(&self) -> Id {
self.inner.target
}
#[inline(always)]
pub fn area(&self) -> Option<Rect<C::Scalar>> {
self.inner.area()
}
#[inline(always)]
pub fn interact<K: Interact<C>>(&mut self, interaction: K) -> K::Response {
let tree = &mut *self.inner.tree;
tree.interaction
.interact::<C, K>(self.inner.target, interaction, tree.time)
}
#[inline(always)]
#[track_caller]
pub fn animate(&mut self, target: f32, animation: impl Into<Animation>, options: AnimationOptions) -> f32 {
self.inner
.animate(target, animation.into(), options, Location::caller())
}
#[inline(always)]
#[track_caller]
pub fn animate_loop(&mut self, tween: Tween) -> f32 {
self.inner.animate_loop(tween, Location::caller())
}
#[inline(always)]
#[track_caller]
pub fn timer(&mut self, duration: Duration) -> Timer<'_> {
self.inner.timer(duration, false, Location::caller())
}
#[inline(always)]
#[track_caller]
pub fn interval(&mut self, period: Duration) -> Timer<'_> {
self.inner.timer(period, true, Location::caller())
}
pub fn focus(&mut self) {
self.inner.tree.focus = FocusRequest::Focus(self.inner.target);
}
pub fn focused(&self) -> bool {
self.inner.tree.interaction.focused == Some(self.inner.target)
}
pub fn focus_moved(&self) -> bool {
let interaction = &self.inner.tree.interaction;
interaction.focused != interaction.focus_seen
}
pub fn clear_focus(&mut self) {
self.inner.tree.focus = FocusRequest::Clear;
}
pub fn context(&self) -> &C {
self.inner.context
}
pub fn context_mut(&mut self) -> &mut C {
self.inner.context
}
pub fn mouse_position(&self) -> Option<Point<C::Scalar>> {
self.inner.tree.interaction.mouse_position
}
pub fn contact_position(&self, id: ContactId) -> Option<Point<C::Scalar>> {
self.inner.tree.interaction.contact_position(id)
}
pub fn input(&self) -> &Input<C::Scalar> {
&self.inner.tree.input
}
pub fn screen(&self) -> Rect<C::Scalar> {
self.inner.tree.screen
}
pub fn time(&self) -> Duration {
self.inner.tree.time
}
pub fn request_frame(&mut self) {
self.inner.tree.request_frame();
}
}
impl<'ui, C: Context, S: state::Local> Ui<'ui, C, S> {
#[inline]
pub fn node(&mut self, id: Id) -> Ui<'_, C, state::Ref> {
self.inner.tree.slots.keep(id);
Ui {
inner: self.inner.borrow(id),
marker: PhantomData,
}
}
#[inline]
pub fn resolve(&mut self, scope: Scope, key: impl Key) -> Id {
let id = self.inner.tree.slots.name(scope.0, key.value());
self.inner.tree.slots.keep(id);
id
}
#[inline(always)]
#[track_caller]
pub fn scope(&mut self) -> Scope {
self.inner.scope(Location::caller())
}
#[inline]
pub fn insert<W: Widget<C, state::Insert>>(&mut self, widget: W) -> W::Response {
widget.build(Ui {
inner: self.inner.borrow(self.inner.target),
marker: PhantomData,
})
}
#[inline]
pub fn paint<F>(&mut self, paint: F)
where
F: Fn(&mut PaintCx<'_, C>, Rect<C::Scalar>) + 'static,
{
paint::insert_paint(self.inner.tree, self.inner.node, paint);
}
#[inline]
pub fn measure<R, F>(&mut self, measure: F)
where
R: Into<Fit<Size<C::Scalar>>>,
F: Fn(&mut C, Constraints<C::Scalar>) -> R + 'static,
{
paint::insert_measure(self.inner.tree, self.inner.node, measure);
}
#[inline(always)]
pub fn focus_within(&self) -> Option<Id> {
self.inner.focus_within()
}
pub fn parent_id(&self) -> Id {
let nodes = &self.inner.tree.nodes;
nodes[nodes[self.inner.node.index()].parent.index()].id
}
pub fn scratch(&self) -> &'ui ScratchBuffer {
self.inner.scratch
}
}
impl<'ui, C: Context, S: state::Owned> Ui<'ui, C, S> {
#[inline(always)]
pub fn constrain(mut self, limits: Constraints<C::Scalar>) -> Self {
self.inner.constrain(limits);
self
}
#[inline]
#[track_caller]
pub fn place<P: Place<C>>(&mut self, target: Id, place: P) -> Ui<'_, C, state::Build> {
let (node, old) = self.inner.child(Location::caller());
attach_place(self.inner.tree, node, target, place);
Ui::new(self.inner.tree, self.inner.context, self.inner.scratch, node, old)
}
#[inline]
#[track_caller]
pub fn place_in<P: Place<C>>(
&mut self,
scope: Scope,
key: impl Key,
target: Id,
place: P,
) -> Ui<'_, C, state::Build> {
let (node, old) = self.inner.child_in(scope.0, key.value(), Location::caller());
attach_place(self.inner.tree, node, target, place);
Ui::new(self.inner.tree, self.inner.context, self.inner.scratch, node, old)
}
#[inline(always)]
pub fn motion(mut self, motion: Motion) -> Self {
self.inner.motion(motion);
self
}
#[inline(always)]
pub fn parent(mut self, target: Id) -> Self {
self.inner.parent(target);
self
}
#[inline(always)]
pub fn clip(mut self, radius: impl Into<Corners<C::Scalar>>) -> Self {
self.inner.clip(radius.into());
self
}
#[inline(always)]
pub fn z_index(mut self, z_index: i16) -> Self {
self.inner.z_index(z_index);
self
}
#[inline(always)]
pub fn hit(mut self, hit: Sides<C::Scalar>) -> Self {
self.inner.hit(hit);
self
}
}
impl<'ui, C: Context, S: state::NoLayout> Ui<'ui, C, S> {
pub fn build<W: Widget<C>>(self, widget: W) -> W::Response {
widget.build(Ui {
inner: self.inner,
marker: PhantomData,
})
}
#[inline]
pub fn layout<L: Layout<C>>(self, layout: L) -> Ui<'ui, C, state::Open<L>> {
let Ui { mut inner, .. } = self;
let kind = inner.register_layout_kind(TypeId::of::<L>(), layout::fit::<C, L>, layout::distribute::<C, L>);
if inner.tree.layout_kinds[kind as usize].default_item.offset().is_none() {
inner.tree.layout_kinds[kind as usize].default_item = inner.tree.bump.store(L::Item::default());
}
let bump_id = inner.tree.bump.store(layout);
let node = &mut inner.tree.nodes[inner.node.index()];
node.layout = bump_id;
node.layout_kind = kind;
Ui {
inner,
marker: PhantomData,
}
}
}
impl<'ui, C: Context, I: 'static> Ui<'ui, C, state::Child<I>> {
#[inline]
pub fn item(self, item: I) -> Ui<'ui, C, state::Build> {
let Ui { inner, .. } = self;
inner.tree.nodes[inner.node.index()].item = inner.tree.bump.store(item);
Ui {
inner,
marker: PhantomData,
}
}
}
impl<'ui, C: Context, L: Layout<C>> Ui<'ui, C, state::Open<L>> {
#[inline]
#[track_caller]
pub fn child(&mut self) -> Ui<'_, C, state::Child<L::Item>> {
let (node, old) = self.inner.child(Location::caller());
Ui::new(self.inner.tree, self.inner.context, self.inner.scratch, node, old)
}
#[inline]
#[track_caller]
pub fn child_in(&mut self, scope: Scope, key: impl Key) -> Ui<'_, C, state::Child<L::Item>> {
let (node, old) = self.inner.child_in(scope.0, key.value(), Location::caller());
Ui::new(self.inner.tree, self.inner.context, self.inner.scratch, node, old)
}
#[inline(always)]
pub fn layout_child(&mut self, child: Id, bounds: Constraints<C::Scalar>) -> Size<C::Scalar> {
self.inner.layout_child(child, bounds)
}
#[inline(always)]
pub fn pad(mut self, padding: impl Into<Sides<C::Scalar>>) -> Self {
self.inner.pad(padding.into());
self
}
}
pub fn resolve_target<C: Context>(tree: &Tree<C>, node: NodeId, target: Id) -> Option<NodeId> {
let target = tree.slots.node(target)?;
(target.index() < node.index()).then_some(target)
}
fn attach_place<C: Context, P: Place<C>>(tree: &mut Tree<C>, node: NodeId, target: Id, place: P) {
let reference = resolve_target(tree, node, target);
let id = PlaceId::new(tree.places.len());
tree.places.push(StoredPlace {
bump_id: tree.bump.store(place),
run: layout::place::<C, P>,
});
let stored = &mut tree.nodes[node.index()];
stored.target = reference.unwrap_or(stored.target);
stored.place = id;
stored.place_scope = node;
}
struct UiInner<'ui, C: Context> {
tree: &'ui mut Tree<C>,
context: &'ui mut C,
scratch: &'ui ScratchBuffer,
node: NodeId,
target: Id,
sites: u32,
cursor: Cursor,
}
impl<'ui, C: Context> UiInner<'ui, C> {
fn new(tree: &'ui mut Tree<C>, context: &'ui mut C, scratch: &'ui ScratchBuffer, node: NodeId, old: u32) -> Self {
Self {
target: tree.nodes[node.index()].id,
sites: tree.sites.len() as u32,
cursor: Cursor {
old,
next: old.wrapping_add(1),
},
tree,
context,
scratch,
node,
}
}
#[inline]
fn borrow(&mut self, target: Id) -> UiInner<'_, C> {
UiInner {
tree: self.tree,
context: self.context,
scratch: self.scratch,
node: self.node,
target,
sites: Slots::NONE,
cursor: Cursor {
old: Slots::NONE,
next: 0,
},
}
}
fn area(&self) -> Option<Rect<C::Scalar>> {
let tree = &*self.tree;
let old = tree.slots.old(self.target)?;
tree.old_placements.get(old).copied()
}
#[inline(never)]
fn animate(
&mut self,
target: f32,
animation: Animation,
mut options: AnimationOptions,
location: &'static Location<'static>,
) -> f32 {
let call = Call::new(self.target, location);
let tree = &mut *self.tree;
let initial = options.initial.take().unwrap_or(target);
let state = AnimationState::update(&mut tree.animations, call, initial);
match &mut state.playback {
Playback::Target(animator) => {
animator
.advance([target], [true], animation, options, tree.time, true)
.0[0]
}
Playback::Loop { value, .. } => {
let mut animator = Animator::new([*value], Animation::default());
let value = animator
.advance([target], [true], animation, options, tree.time, true)
.0[0];
state.playback = Playback::Target(animator);
value
}
}
}
#[inline(never)]
fn animate_loop(&mut self, mut tween: Tween, location: &'static Location<'static>) -> f32 {
tween.duration = tween.duration.max(0.0);
if tween.duration == 0.0 {
return self.animate(0.0, Animation::default(), AnimationOptions::default(), location);
}
let call = Call::new(self.target, location);
let tree = &mut *self.tree;
let state = AnimationState::update(&mut tree.animations, call, 0.0);
let now = tree.time.as_secs_f64();
let time = match state.playback {
Playback::Loop {
tween: previous, time, ..
} if previous == tween => time,
_ => now,
};
let progress = (now - time).max(0.0) as f32 / tween.duration;
let value = tween.easing.sample(progress % 1.0).0;
state.playback = Playback::Loop { tween, time, value };
value
}
#[inline(never)]
fn timer(&mut self, period: Duration, repeat: bool, location: &'static Location<'static>) -> Timer<'_> {
if repeat {
assert!(!period.is_zero(), "an interval must be nonzero");
}
let call = Call::new(self.target, location);
let tree = &mut *self.tree;
TimerState::update(&mut tree.timers, call, period, repeat, tree.time)
}
#[inline(never)]
fn scope(&mut self, location: &'static Location<'static>) -> Scope {
let tree = &mut *self.tree;
let mut call = Call::new(self.target, location);
let index = loop {
match tree.scopes.binary_search_by_key(&call, |scope| scope.call) {
Ok(index) if tree.slots.is_kept(tree.scopes[index].id) => call.repeat += 1,
Ok(index) => break index,
Err(index) => {
let id = tree.slots.alloc();
tree.scopes.insert(index, CallScope { call, id });
break index;
}
}
};
let id = tree.scopes[index].id;
tree.slots.keep(id);
Scope(id)
}
fn focus_within(&self) -> Option<Id> {
let tree = &*self.tree;
let focused = tree.interaction.focused?;
let node = tree.slots.old(self.target)?;
let inside = tree.slots.old(focused)?;
(node < inside && inside <= tree.old_nodes[node].subtree_end as usize).then_some(focused)
}
#[inline(never)]
fn constrain(&mut self, limits: Constraints<C::Scalar>) {
assert!(
limits.min.width >= C::Scalar::ZERO
&& limits.min.height >= C::Scalar::ZERO
&& limits.min.width.is_finite()
&& limits.min.height.is_finite()
&& limits.max.width >= limits.min.width
&& limits.max.height >= limits.min.height,
"invalid local bounds"
);
self.tree.aux_mut(self.node).limits = limits;
}
fn motion(&mut self, motion: Motion) {
let tree = &mut *self.tree;
match tree.aux_mut(self.node).motion.index() {
Some(index) => tree.node_motions[index].motion = motion,
None => {
tree.aux_mut(self.node).motion = NodeMotionId::new(tree.node_motions.len());
tree.node_motions.push(NodeMotion {
node: self.node,
motion,
});
}
}
}
fn parent(&mut self, target: Id) {
if let Some(parent) = resolve_target(self.tree, self.node, target) {
self.tree.aux_mut(self.node).visual_parent = parent;
if parent != self.tree.nodes[self.node.index()].parent {
self.tree.has_custom_order = true;
}
}
}
fn clip(&mut self, radius: Corners<C::Scalar>) {
self.tree.aux_mut(self.node).clip = Some(radius);
self.tree.has_clips = true;
}
fn z_index(&mut self, z_index: i16) {
self.tree.set_z_index(self.node, z_index);
}
fn hit(&mut self, hit: Sides<C::Scalar>) {
self.tree.aux_mut(self.node).hit = hit;
}
#[inline(never)]
fn pad(&mut self, padding: Sides<C::Scalar>) {
assert!(
[padding.top, padding.right, padding.bottom, padding.left]
.iter()
.all(|side| *side >= C::Scalar::ZERO && side.is_finite()),
"invalid padding"
);
self.tree.aux_mut(self.node).padding = padding;
}
fn layout_child(&mut self, child: Id, bounds: Constraints<C::Scalar>) -> Size<C::Scalar> {
let tree = &mut *self.tree;
let child = tree.slots.node(child).expect("a laid out child must be built first");
assert!(
tree.nodes[child.index()].place.index().is_none(),
"measured widgets must stay in flow"
);
let mut bump = core::mem::take(&mut tree.bump);
bump.storage.prepare();
let size = layout::resolve(tree, &bump, self.context, child, bounds, false);
tree.bump = bump;
size
}
#[inline(never)]
fn register_layout_kind(
&mut self,
type_id: TypeId,
fit: fn(&mut LayoutCx<'_, C>, BumpId, Axis) -> Fit<C::Scalar>,
distribute: fn(&mut LayoutCx<'_, C>, BumpId, Axis, C::Scalar),
) -> u16 {
let tree = &mut *self.tree;
let kind = tree
.layout_kinds
.iter()
.position(|kind| kind.type_id == type_id)
.unwrap_or_else(|| {
tree.layout_kinds.push(LayoutKind {
type_id,
fit,
distribute,
default_item: BumpId::NONE,
});
tree.layout_kinds.len() - 1
});
u16::try_from(kind).expect("too many layout kinds")
}
fn child(&mut self, location: &'static Location<'static>) -> (NodeId, u32) {
#[cold]
fn search(
old_nodes: &[StoredNode],
old_marks: &[Mark],
cursor: Cursor,
end: u32,
location: &Location<'_>,
ordinal: u32,
) -> Option<u32> {
let mut index = if cursor.next <= end {
old_nodes[cursor.next as usize].subtree_end + 1
} else {
end + 1
};
while index <= end {
if old_marks[index as usize].is_site(location, ordinal) {
return Some(index);
}
index = old_nodes[index as usize].subtree_end + 1;
}
let mut index = cursor.old + 1;
while index < cursor.next {
if old_marks[index as usize].is_site(location, ordinal) {
return Some(index);
}
index = old_nodes[index as usize].subtree_end + 1;
}
None
}
let tree = &mut *self.tree;
let start = self.sites as usize;
let (site, ordinal, scan) = match tree.sites[start..]
.iter()
.rposition(|site| same_place(site.location, location))
{
Some(index) => {
let site = &mut tree.sites[start + index];
site.ordinal = site.ordinal.checked_add(1).expect("too many children from one place");
(start + index, site.ordinal, site.scan)
}
None => {
tree.sites.push(Site {
location,
ordinal: 0,
scan: true,
});
(tree.sites.len() - 1, 0, true)
}
};
let mut found = None;
if scan && self.cursor.old != Slots::NONE {
let end = tree.old_nodes[self.cursor.old as usize].subtree_end;
if self.cursor.next <= end && tree.old_marks[self.cursor.next as usize].is_site(location, ordinal) {
found = Some(self.cursor.next);
} else {
found = search(&tree.old_nodes, &tree.old_marks, self.cursor, end, location, ordinal);
tree.sites[site].scan = found.is_some();
}
}
let (id, old) = match found {
Some(index) => {
let stored = &tree.old_nodes[index as usize];
self.cursor.next = stored.subtree_end + 1;
(stored.id, index)
}
None => (tree.slots.alloc(), Slots::NONE),
};
(tree.push_node(Some(self.node), id, Mark::Site(location, ordinal)), old)
}
fn child_in(&mut self, scope: Id, key: u64, location: &'static Location<'static>) -> (NodeId, u32) {
let tree = &mut *self.tree;
let keyed = tree.slots.is_kept(scope);
let mut mark = if keyed { Mark::Key(scope.slot, key) } else { Mark::Named };
let (mut id, mut old) = if keyed
&& self.cursor.old != Slots::NONE
&& self.cursor.next <= tree.old_nodes[self.cursor.old as usize].subtree_end
&& matches!(tree.old_marks[self.cursor.next as usize], Mark::Key(slot, other) if slot == scope.slot && other == key)
{
let index = self.cursor.next;
let stored = &tree.old_nodes[index as usize];
self.cursor.next = stored.subtree_end + 1;
(stored.id, index)
} else {
let id = tree.slots.name(scope, key);
let old = tree.slots.old(id).map_or(Slots::NONE, |node| node as u32);
if old != Slots::NONE && tree.old_nodes[old as usize].parent.index() as u32 == self.cursor.old {
self.cursor.next = tree.old_nodes[old as usize].subtree_end + 1;
}
(id, old)
};
if tree.slots.claimed(id) {
self.context.duplicate_key(Scope(scope), key, location);
id = tree.slots.alloc();
old = Slots::NONE;
mark = Mark::Named;
}
(tree.push_node(Some(self.node), id, mark), old)
}
}
impl<'ui, C: Context, S> Ui<'ui, C, S> {
pub(crate) fn new(
tree: &'ui mut Tree<C>,
context: &'ui mut C,
scratch: &'ui ScratchBuffer,
node: NodeId,
old: u32,
) -> Self {
Self {
inner: UiInner::new(tree, context, scratch, node, old),
marker: PhantomData,
}
}
}
impl<C: Context> Drop for UiInner<'_, C> {
fn drop(&mut self) {
if self.sites == Slots::NONE {
return;
}
self.tree.nodes[self.node.index()].subtree_end = (self.tree.nodes.len() - 1) as u32;
self.tree.sites.truncate(self.sites as usize);
}
}