Skip to main content

frust_core/
lib.rs

1//! Layer 1+2 of Frust: the declarative view API, the retained widget tree,
2//! box-constraint layout, and the rebuild/layout/paint pass skeleton.
3//!
4//! The design mirrors `xilem_core`'s proven `View` lifecycle and Masonry's
5//! `tree_arena`-backed widget tree, but owns its implementation — there is **no
6//! xilem/masonry dependency and no `unsafe`** in this crate.
7//!
8//! # Layers
9//!
10//! * [`view`] — layer 1: the [`View`](view::View) trait, [`ChangeFlags`], and
11//!   [`BuildCtx`](view::BuildCtx). Views are cheap descriptors produced by
12//!   `fn build(&mut State) -> impl View<State>`. [`ViewSeq`] is
13//!   the child-sequence trait container child lists take (a view, a tuple, a
14//!   `Vec`/array/`Option`, or [`views`] over an iterator).
15//! * [`widget`] — layer 2: the [`Widget`](widget::Widget) trait and its
16//!   layout/paint/event contexts, the [`PaintScene`](widget::PaintScene) paint
17//!   boundary, and container-owned [`ChildPod`](widget::ChildPod) children.
18//! * [`event`] — layer 2 input: [`InputEvent`](event::InputEvent)/
19//!   [`PointerEvent`](event::PointerEvent) and the [`EventCtx`](event::EventCtx)
20//!   handlers mutate state through.
21//! * [`input`] — pure gesture helpers: slop/wheel constants, a
22//!   [`VelocityTracker`](input::VelocityTracker), and the fling-decay math the
23//!   interactive widgets build on.
24//! * [`layout`] — the [`BoxConstraints`](layout::BoxConstraints) box model.
25//! * [`tree`] — the [`WidgetTree`](tree::WidgetTree) arena wrapper,
26//!   [`WidgetPod`](tree::WidgetPod), and the read-only
27//!   [`InspectNode`](tree::InspectNode) walk tooling reads the tree through.
28//! * [`app`] — the [`RenderRoot`](app::RenderRoot) that drives rebuild → layout
29//!   → paint. This is what each platform shell owns.
30//! * [`component`] — [`Component`](component::Component), Flutter's
31//!   `StatefulWidget` analog: a subtree with retained local state, a
32//!   per-component reactive `Owner`, and a state boundary the outer view tree
33//!   never sees.
34//! * [`overlay`] — the overlay portal: an owner-hosted, root-painted,
35//!   root-routed pod a widget floats above the whole app (menus, popovers,
36//!   tooltips, selection toolbars).
37//! * [`selection_toolbar`] — what a text field publishes when it has a
38//!   selection, plus the process-global policy/builder slots that decide who
39//!   draws the toolbar.
40//! * [`hit`] — hit-testing helpers for content drawn under an arbitrary
41//!   [`kurbo::Affine`]: the test [`ChildPod`](widget::ChildPod) uses for a
42//!   transformed pod, exposed for canvas hit closures and pan/zoom containers.
43
44pub mod anim;
45pub mod app;
46pub mod component;
47pub mod event;
48#[cfg(feature = "hotpatch")]
49pub mod hotpatch;
50pub mod input;
51pub mod insets;
52pub mod layout;
53pub mod overlay;
54pub mod selection_toolbar;
55pub mod semantics;
56pub mod tree;
57pub mod view;
58pub mod widget;
59
60/// Hit-testing under an arbitrary [`kurbo::Affine`].
61///
62/// [`ChildPod::set_transform`](widget::ChildPod::set_transform) places a child
63/// under a transform; these are the helpers it hit-tests with, exposed so a
64/// canvas hit closure or a pan/zoom container answers "is this point on that
65/// shape" exactly the way the pod does.
66pub mod hit {
67    use kurbo::{Affine, Point, Rect};
68
69    /// `affine`'s inverse, or `None` when it has none — a singular (zero
70    /// determinant) or non-finite transform, or one whose inverse overflows.
71    ///
72    /// [`Affine::inverse`] on a singular matrix divides by zero and returns
73    /// non-finite coefficients rather than failing; this is the checked form
74    /// every caller that maps a point back through a transform should use.
75    pub fn checked_inverse(affine: &Affine) -> Option<Affine> {
76        let det = affine.determinant();
77        if det == 0.0 || !det.is_finite() || !affine.is_finite() {
78            return None;
79        }
80        let inverse = affine.inverse();
81        inverse.is_finite().then_some(inverse)
82    }
83
84    /// Whether `point` lands inside `rect` once `rect` is drawn under `affine`.
85    ///
86    /// `rect` is in the content's own (local) space and `affine` maps that space
87    /// into the space `point` is in, so this is the hit test for content painted
88    /// inside `push_transform(affine)`: `point` is mapped back through the
89    /// inverse and tested against `rect` with the same half-open convention as
90    /// [`ChildPod::contains`](crate::widget::ChildPod::contains) (`x0 <= x < x1`,
91    /// `y0 <= y < y1`). A rotated rect therefore hits along its rotated edges,
92    /// not its axis-aligned bounding box.
93    ///
94    /// A transform with no inverse ([`checked_inverse`]) collapses the rect to a
95    /// line or a point, which nothing can hit: the answer is `false`, never a
96    /// panic.
97    pub fn point_in_transformed_rect(point: Point, rect: Rect, affine: &Affine) -> bool {
98        let Some(inverse) = checked_inverse(affine) else {
99            return false;
100        };
101        let local = inverse * point;
102        local.x >= rect.x0 && local.x < rect.x1 && local.y >= rect.y0 && local.y < rect.y1
103    }
104
105    #[cfg(test)]
106    mod tests {
107        use super::*;
108        use kurbo::Vec2;
109        use std::f64::consts::FRAC_PI_4;
110
111        #[test]
112        fn identity_matches_the_half_open_rect_test() {
113            let rect = Rect::new(0.0, 0.0, 10.0, 10.0);
114            assert!(point_in_transformed_rect(
115                Point::ZERO,
116                rect,
117                &Affine::IDENTITY
118            ));
119            assert!(point_in_transformed_rect(
120                Point::new(9.99, 9.99),
121                rect,
122                &Affine::IDENTITY
123            ));
124            assert!(!point_in_transformed_rect(
125                Point::new(10.0, 5.0),
126                rect,
127                &Affine::IDENTITY
128            ));
129        }
130
131        #[test]
132        fn scale_and_translate_map_the_point_back() {
133            let rect = Rect::new(0.0, 0.0, 10.0, 10.0);
134            let affine = Affine::translate(Vec2::new(100.0, 50.0)) * Affine::scale(2.0);
135            // Drawn at (100..120, 50..70).
136            assert!(point_in_transformed_rect(
137                Point::new(119.0, 69.0),
138                rect,
139                &affine
140            ));
141            assert!(!point_in_transformed_rect(
142                Point::new(121.0, 60.0),
143                rect,
144                &affine
145            ));
146            assert!(!point_in_transformed_rect(
147                Point::new(105.0, 49.0),
148                rect,
149                &affine
150            ));
151        }
152
153        #[test]
154        fn rotation_hits_the_diamond_not_its_bounding_box() {
155            let rect = Rect::new(0.0, 0.0, 100.0, 100.0);
156            let affine = Affine::rotate_about(FRAC_PI_4, Point::new(50.0, 50.0));
157            // The box's own corner (1, 1) is outside the rotated diamond.
158            assert!(!point_in_transformed_rect(
159                Point::new(1.0, 1.0),
160                rect,
161                &affine
162            ));
163            // The diamond's top vertex sits at (50, 50 - 50·√2).
164            let top = affine * Point::new(0.0, 0.0);
165            assert!(point_in_transformed_rect(
166                top + Vec2::new(0.0, 1.0),
167                rect,
168                &affine
169            ));
170            assert!(!point_in_transformed_rect(
171                top - Vec2::new(0.0, 1.0),
172                rect,
173                &affine
174            ));
175        }
176
177        #[test]
178        fn a_singular_transform_hits_nothing() {
179            let rect = Rect::new(0.0, 0.0, 10.0, 10.0);
180            for affine in [
181                Affine::scale(0.0),
182                Affine::scale_non_uniform(1.0, 0.0),
183                Affine::new([1.0, 2.0, 2.0, 4.0, 0.0, 0.0]),
184                Affine::new([f64::NAN, 0.0, 0.0, 1.0, 0.0, 0.0]),
185            ] {
186                assert!(checked_inverse(&affine).is_none());
187                assert!(!point_in_transformed_rect(Point::ZERO, rect, &affine));
188            }
189        }
190    }
191}
192
193/// Re-export of the [`accesskit`] accessibility vocabulary (roles, node
194/// builders, toggle/value state) widgets use to populate a
195/// [`semantics::SemanticsCtx`]. Re-exported here — the sole crate that depends
196/// on accesskit — so `frust-widgets` (and app code) name the vocabulary
197/// through `frust_core::accesskit::*` without a direct dependency; the
198/// platform `accesskit_*` adapter crates live in the shells, not here.
199pub use accesskit;
200pub use anim::{
201    AnimationController, AnimationStatus, Curve, FrameTime, Lerp, Spring, SpringDesc, Tween,
202};
203pub use app::{Orientation, RenderRoot, WindowMetrics};
204pub use component::{Component, ComponentView, ComponentWidget, component};
205pub use event::{
206    CursorIcon, EditCommand, EditingState, EventCtx, EventOutcome, EventResult, ImeContentType,
207    ImeEvent, ImeState, InputEvent, Key, KeyEvent, Modifiers, NamedKey, OverlayEvent,
208    OverlayEventKind, PointerButton, PointerEvent, PointerPhase, ScrollDelta,
209    has_pending_result_flush, mark_focus_orphaned, mark_pending_result_flush, take_focus_orphaned,
210    take_pending_result_flush,
211};
212#[cfg(feature = "hotpatch")]
213pub use hotpatch::{LayoutMismatch, SeamWitness, build_erased, set_patch_listener};
214pub use input::{
215    FLING_DECAY, FLING_STOP, MOUSE_SLOP, TOUCH_SLOP, VELOCITY_WINDOW_MS, VelocityTracker,
216    WHEEL_LINE_PX, fling_decay, fling_displacement,
217};
218pub use insets::{CornerInset, CornerInsets, EdgeInsets as WindowEdgeInsets, WindowInsets};
219pub use layout::BoxConstraints;
220pub use overlay::{
221    OutsideTap, OverlayBand, OverlayEntry, OverlayHit, OverlayInput, OverlayKey, OverlayPod,
222};
223pub use selection_toolbar::{
224    SelectionToolbarActions, SelectionToolbarBuilder, SelectionToolbarPolicy,
225    SelectionToolbarRequest, install_selection_toolbar_builder_if_unset,
226    lock_selection_toolbar_policy, selection_toolbar_builder, selection_toolbar_policy,
227    set_selection_toolbar_builder, set_selection_toolbar_policy,
228};
229pub use semantics::{SemanticsCtx, SemanticsUpdate};
230pub use tree::{InspectNode, WidgetPod, WidgetTree};
231pub use view::{AnyView, BuildCtx, ChangeFlags, View, ViewSeq, WidgetId, any, views};
232pub use widget::{
233    ChildPod, CornerRadii, DashPattern, DiscardScene, HeroDirective, HeroFrames, LayoutCtx,
234    PaintCtx, PaintOutcome, PaintScene, TickClass, Widget,
235};