teksilo_core/widget/layout_context.rs
1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4use crate::widget_id::WidgetId;
5
6use super::LayoutResponse;
7
8/// The main (distribution) axis of the linear stack currently negotiating a
9/// child's layout, if any. Set by `HStack`/`VStack` while they query children
10/// so an orientation-agnostic flexible child (notably `Spacer`) can place its
11/// minimum length on the *main* axis only and report `0` on the cross axis —
12/// otherwise it imposes a spurious cross-axis floor on the stack. `None` when
13/// the parent is not a linear stack (or in test contexts).
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum StackAxis {
16 Horizontal,
17 Vertical,
18}
19
20/// Context available during layout.
21pub struct LayoutContext<'a> {
22 /// The enclosing linear stack's main axis, when a stack is querying this
23 /// child (see [`StackAxis`]). `None` otherwise.
24 pub stack_main_axis: Option<StackAxis>,
25 pub theme: &'a crate::styles::Theme,
26 pub layout_direction: crate::environment::LayoutDirection,
27 /// Host window HiDPI device scale (physical px per logical px). The layout
28 /// pass is otherwise fully logical, and the renderer applies this scale at
29 /// the vertex stage — so **ordinary widgets must ignore this**. It exists
30 /// only as the escape hatch for widgets that bridge to a device-pixel OS
31 /// resource (e.g. a `WebView` sizing its native subview, which on some
32 /// toolkits — WebKitGTK on X11 — ignores fractional scaling and needs
33 /// device pixels). 1.0 in headless / test contexts.
34 pub scale_factor: f32,
35 /// Combined user×OS text-scale factor (`1.0` = 100 %). Distinct from
36 /// `scale_factor` (HiDPI device pixels): this is the *logical* accessibility
37 /// magnification. Widgets that size text from `Theme.typography` already
38 /// scale via the effective theme and should ignore this; it exists for
39 /// widgets that size from another source (`IconWidget`, the rich-text engine
40 /// default size, scene text) and need the raw factor. `1.0` in test contexts.
41 pub text_scale: f32,
42 /// Text backend for accurate text measurement during layout.
43 pub text_backend: Option<&'a std::rc::Rc<std::cell::RefCell<dyn teksilo_canvas::TextBackend>>>,
44 /// Arena reference for querying child widget sizes.
45 pub(crate) arena: Option<&'a crate::arena::WidgetArena>,
46 /// Optional bundle of read-only tree state (focus, shortcuts,
47 /// overlays). Carried through layout for debug-tooling consumers
48 /// like the inspector's Focus / Shortcuts / Overlays tabs. `None`
49 /// in test contexts.
50 pub(crate) extras: Option<LayoutExtras<'a>>,
51}
52
53/// Read-only handles to tree-level state that some widgets (notably
54/// the debug inspector) want to query from `layout_response`. Threaded
55/// through the recursive layout pass alongside the arena.
56#[derive(Clone, Copy)]
57pub(crate) struct LayoutExtras<'a> {
58 pub focused: Option<WidgetId>,
59 /// Every widget that currently owns live interaction state the framework
60 /// would destroy if its subtree were parked dormant: the focused node,
61 /// each pointer's captor, and the source of an in-flight drag. Collected
62 /// once per layout pass; empty on an idle tree.
63 pub interaction_anchors: &'a [WidgetId],
64 pub shortcut_registry: Option<&'a crate::shortcut::ShortcutRegistry>,
65 pub overlay_manager: Option<&'a crate::overlay::OverlayManager>,
66}
67
68impl<'a> LayoutContext<'a> {
69 /// Create a LayoutContext for testing (no arena access).
70 pub fn for_testing(theme: &'a crate::styles::Theme) -> Self {
71 Self {
72 theme,
73 layout_direction: crate::environment::LayoutDirection::LeftToRight,
74 scale_factor: 1.0,
75 text_scale: 1.0,
76 text_backend: None,
77 arena: None,
78 extras: None,
79 stack_main_axis: None,
80 }
81 }
82
83 /// The enclosing linear stack's main axis, if a stack is currently
84 /// querying this child. See [`StackAxis`].
85 pub fn stack_main_axis(&self) -> Option<StackAxis> {
86 self.stack_main_axis
87 }
88
89 /// Derive a context that advertises `axis` as the enclosing stack's main
90 /// axis. Used by `HStack`/`VStack` when querying children so a `Spacer`
91 /// (and any other orientation-agnostic flexible leaf) can size correctly
92 /// per axis. All other fields are shared with `self`.
93 pub fn with_stack_main_axis(&self, axis: StackAxis) -> LayoutContext<'a> {
94 LayoutContext {
95 stack_main_axis: Some(axis),
96 ..*self
97 }
98 }
99
100 /// The currently focused widget id, if any. Returns `None` when
101 /// the layout pass is unrelated to a tree (test contexts).
102 pub fn focused(&self) -> Option<WidgetId> {
103 self.extras.as_ref().and_then(|e| e.focused)
104 }
105
106 /// Call `f` with every widget that holds live interaction state, and with
107 /// each of its ancestors up to a root.
108 ///
109 /// "Live interaction state" is what the framework destroys when it parks a
110 /// subtree dormant: the keyboard focus (cleared by
111 /// `WidgetTree::revalidate_interaction_state`), a captured pointer and an
112 /// in-flight drag source (both cancelled with
113 /// [`CancelReason::SubtreeParked`](crate::pointer::CancelReason)). Losing any
114 /// of them is fine when the *user* navigated away and wrong when the
115 /// *container* moved.
116 ///
117 /// So a container that culls by viewport intersects this with its own
118 /// children and pins whichever of them the user is in the middle of: a
119 /// card being typed in, or drag-selected inside, stays live wherever the
120 /// camera goes.
121 ///
122 /// Reported from the anchors *upward* rather than tested per child on
123 /// purpose — that makes the pin cost proportional to the number of live
124 /// interactions (almost always zero or one, times the tree depth) instead
125 /// of to the number of children, which is the quantity a culling container
126 /// exists to stop paying. Nothing is reported outside a real layout pass.
127 pub fn for_each_interaction_ancestor(&self, mut f: impl FnMut(WidgetId)) {
128 let (Some(arena), Some(extras)) = (self.arena, self.extras.as_ref()) else {
129 return;
130 };
131 for &anchor in extras.interaction_anchors {
132 let mut cur = Some(anchor);
133 while let Some(id) = cur {
134 f(id);
135 cur = arena.parent(id);
136 }
137 }
138 }
139
140 /// Borrow the tree's shortcut registry. Returns `None` outside a
141 /// real layout pass. Intended for read-only inspection by the
142 /// debug inspector.
143 pub fn shortcut_registry(&self) -> Option<&crate::shortcut::ShortcutRegistry> {
144 self.extras.as_ref().and_then(|e| e.shortcut_registry)
145 }
146
147 /// Borrow the tree's overlay manager. Returns `None` outside a
148 /// real layout pass. Intended for read-only inspection by the
149 /// debug inspector.
150 pub fn overlay_manager(&self) -> Option<&crate::overlay::OverlayManager> {
151 self.extras.as_ref().and_then(|e| e.overlay_manager)
152 }
153
154 /// Query a child widget's full layout response (wanted size + flex weight).
155 /// Returns None if the child doesn't exist, is dormant, or the arena is not available.
156 pub fn child_layout_response(
157 &self,
158 child_id: WidgetId,
159 proposal: teksilo_canvas::SizeProposal,
160 ) -> Option<LayoutResponse> {
161 // Routed through the arena's per-pass memoization cache so the
162 // main-then-cross queries that height-for-width negotiation issues do
163 // not recompute the same `(child, proposal)` repeatedly. The cache
164 // handles the active-state check and the `cacheable_layout()` opt-out.
165 let arena = self.arena?;
166 arena.cached_layout_response(child_id, proposal, self)
167 }
168
169 /// Measure a widget's intrinsic size for `proposal`, **regardless of
170 /// activation** — works even for dormant/collapsed widgets (and their
171 /// dormant subtrees), unlike [`child_size`](Self::child_size) /
172 /// [`child_layout_response`](Self::child_layout_response), which return
173 /// `None` for inactive widgets.
174 ///
175 /// Intended for adaptive layouts that hide some children but still need
176 /// their size to decide when to reveal them — e.g. an overflow `Toolbar`
177 /// collapsing actions into a chevron menu. Runs uncached and re-entrant-
178 /// safe; calls `layout_response`, which must be idempotent.
179 pub fn measure_intrinsic(
180 &self,
181 id: WidgetId,
182 proposal: teksilo_canvas::SizeProposal,
183 ) -> Option<teksilo_canvas::Size> {
184 self.arena?.measure_intrinsic(id, proposal, self)
185 }
186
187 /// Query a child widget's wanted size only (drops the flex weight).
188 /// Convenience over [`child_layout_response`](Self::child_layout_response).
189 pub fn child_size(
190 &self,
191 child_id: WidgetId,
192 proposal: teksilo_canvas::SizeProposal,
193 ) -> Option<teksilo_canvas::Size> {
194 self.child_layout_response(child_id, proposal)
195 .map(|r| r.size)
196 }
197
198 /// Query the laid-out bounds of any active widget. Returns `None`
199 /// when the arena is not available (test contexts) — otherwise
200 /// returns the widget's current bounds (`Rect::ZERO` if unknown).
201 /// Useful for inspector-style widgets that need to mirror another
202 /// widget's geometry into a `Signal` during the layout pass.
203 pub fn widget_bounds(&self, id: WidgetId) -> Option<teksilo_canvas::Rect> {
204 let arena = self.arena?;
205 if !arena.is_active(id) {
206 return None;
207 }
208 Some(arena.bounds(id))
209 }
210
211 /// Hit-test the active widget tree at `point` and return the
212 /// deepest widget under it. Honors `event_pass_through`. The
213 /// `exclude` argument lets the caller skip a specific subtree
214 /// (e.g. the inspector's picker overlay so it doesn't pick
215 /// itself). Returns `None` outside layout (no arena available).
216 pub fn widget_at_point(
217 &self,
218 point: teksilo_canvas::Point,
219 exclude: Option<WidgetId>,
220 ) -> Option<WidgetId> {
221 let arena = self.arena?;
222 arena.hit_test_at(point, exclude)
223 }
224
225 /// Borrow the underlying arena. Returns `None` outside a layout
226 /// pass (test contexts). Intended for read-only introspection by
227 /// debug tooling (the inspector's tree view) — use the typed
228 /// accessors above when possible.
229 pub fn arena(&self) -> Option<&crate::arena::WidgetArena> {
230 self.arena
231 }
232
233 /// Query a child's per-widget alignment override, if any.
234 pub fn child_alignment(&self, child_id: WidgetId) -> Option<teksilo_tokens::Alignment> {
235 let arena = self.arena?;
236 arena.alignment_override(child_id)
237 }
238
239 /// Whether the layout direction is right-to-left.
240 pub fn is_rtl(&self) -> bool {
241 self.layout_direction == crate::environment::LayoutDirection::RightToLeft
242 }
243}