1#![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
138pub trait Context {
140 type Scalar: Scalar;
142
143 fn duplicate_key(&mut self, _scope: Scope, _key: u64, _location: &'static Location<'static>) {}
145}
146
147impl Context for () {
148 type Scalar = f32;
149}
150
151pub trait Paint<T>: Context {
153 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
164pub trait Widget<C: Context, S = state::Build> {
170 type Response;
171
172 fn build(self, ui: Ui<'_, C, S>) -> Self::Response;
173}
174
175#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
180pub struct Id {
181 slot: u32,
182 generation: NonZeroU32,
183}
184
185impl Id {
186 pub const ROOT: Self = Self {
188 slot: 0,
189 generation: NonZeroU32::MIN,
190 };
191}
192
193#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
197pub struct Scope(Id);
198
199impl Scope {
200 pub const ROOT: Self = Self(Id::ROOT);
202}
203
204pub 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 nodes: Vec<StoredNode>,
243 marks: Vec<Mark>,
245 placements: Vec<Rect<C::Scalar>>,
246 z_indices: Vec<i16>,
248 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 paint_order: Vec<NodeId>,
257 sites: Vec<Site>,
259 bump: BumpArena,
260 scratch: ScratchBuffer,
261 has_custom_order: bool,
262 has_clips: bool,
263
264 old_nodes: Vec<StoredNode>,
268 old_marks: Vec<Mark>,
269 old_placements: Vec<Rect<C::Scalar>>,
270
271 slots: Slots,
275 interaction: InteractionState<C::Scalar>,
276 animations: Vec<AnimationState>,
277 scopes: Vec<CallScope>,
279 motions: Vec<MotionState<C::Scalar>>,
280 timers: Vec<TimerState>,
281 focus: FocusRequest,
283
284 layout_kinds: Vec<LayoutKind<C>>,
288
289 input: Input<C::Scalar>,
293 time: Duration,
294 screen: Rect<C::Scalar>,
295 resized: bool,
296 frame_requested: bool,
297 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 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 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 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 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 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 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 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 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 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 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 pub fn find(&self, scope: Scope, key: impl Key) -> Option<Id> {
517 self.slots.find(scope.0, key.value())
518 }
519}
520
521impl<C: Context> Tree<C> {
526 #[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 {}