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. A widget that reads
34 /// it binds `BuildContext::device_scale_signal` at `Relayout`: a scale
35 /// change with an unchanged logical size relayouts nothing on its own.
36 pub scale_factor: f32,
37 /// Combined user×OS text-scale factor (`1.0` = 100 %). Distinct from
38 /// `scale_factor` (HiDPI device pixels): this is the *logical* accessibility
39 /// magnification. Widgets that size text from `Theme.typography` already
40 /// scale via the effective theme and should ignore this; it exists for
41 /// widgets that size from another source (`IconWidget`, the rich-text engine
42 /// default size, scene text) and need the raw factor. `1.0` in test contexts.
43 pub text_scale: f32,
44 /// Text backend for accurate text measurement during layout.
45 pub text_backend: Option<&'a std::rc::Rc<std::cell::RefCell<dyn teksilo_canvas::TextBackend>>>,
46 /// Arena reference for querying child widget sizes.
47 pub(crate) arena: Option<&'a crate::arena::WidgetArena>,
48 /// Optional bundle of read-only tree state (focus, shortcuts,
49 /// overlays). Carried through layout for debug-tooling consumers
50 /// like the inspector's Focus / Shortcuts / Overlays tabs. `None`
51 /// in test contexts.
52 pub(crate) extras: Option<LayoutExtras<'a>>,
53 /// The language of the content of the widget this context was resolved
54 /// for (see [`content_language`](Self::content_language)). `None` both
55 /// when nothing declares one and while no node in the tree declares a
56 /// language at all.
57 pub(crate) content_language: Option<crate::language::LanguageTag>,
58 /// The widget `content_language` was resolved for. A widget asking a
59 /// child for its size hands it its own context, so the arena re-resolves
60 /// the language for the child: in O(1) from this when the child's parent
61 /// is this widget, with a walk otherwise. `None` outside a tree.
62 pub(crate) language_for: Option<WidgetId>,
63}
64
65/// Read-only handles to tree-level state that some widgets (notably
66/// the debug inspector) want to query from `layout_response`. Threaded
67/// through the recursive layout pass alongside the arena.
68#[derive(Clone, Copy)]
69pub(crate) struct LayoutExtras<'a> {
70 pub focused: Option<WidgetId>,
71 /// Every widget that currently owns live interaction state the framework
72 /// would destroy if its subtree were parked dormant: the focused node,
73 /// each pointer's captor, and the source of an in-flight drag. Collected
74 /// once per layout pass; empty on an idle tree.
75 pub interaction_anchors: &'a [WidgetId],
76 pub shortcut_registry: Option<&'a crate::shortcut::ShortcutRegistry>,
77 pub overlay_manager: Option<&'a crate::overlay::OverlayManager>,
78}
79
80impl<'a> LayoutContext<'a> {
81 /// Create a LayoutContext for testing (no arena access).
82 pub fn for_testing(theme: &'a crate::styles::Theme) -> Self {
83 Self {
84 theme,
85 layout_direction: crate::environment::LayoutDirection::LeftToRight,
86 scale_factor: 1.0,
87 text_scale: 1.0,
88 text_backend: None,
89 arena: None,
90 extras: None,
91 stack_main_axis: None,
92 content_language: None,
93 language_for: None,
94 }
95 }
96
97 /// The language of the content of the widget being laid out: its own
98 /// [`content_language`](crate::widget_builder::WidgetBuilder::content_language)
99 /// declaration, else its nearest ancestor's, else, inside an overlay, that
100 /// of the widget the overlay is attached to. `None` when nothing
101 /// declares one, which means the content is in the application's locale.
102 ///
103 /// A change to a declaration lays the tree out again.
104 pub fn content_language(&self) -> Option<&crate::language::LanguageTag> {
105 self.content_language.as_ref()
106 }
107
108 /// The same context, resolved for `id` with `language`.
109 pub(crate) fn with_content_language(
110 &self,
111 id: WidgetId,
112 language: Option<crate::language::LanguageTag>,
113 ) -> LayoutContext<'a> {
114 LayoutContext {
115 stack_main_axis: self.stack_main_axis,
116 theme: self.theme,
117 layout_direction: self.layout_direction,
118 scale_factor: self.scale_factor,
119 text_scale: self.text_scale,
120 text_backend: self.text_backend,
121 arena: self.arena,
122 extras: self.extras,
123 content_language: language,
124 language_for: Some(id),
125 }
126 }
127
128 /// The enclosing linear stack's main axis, if a stack is currently
129 /// querying this child. See [`StackAxis`].
130 pub fn stack_main_axis(&self) -> Option<StackAxis> {
131 self.stack_main_axis
132 }
133
134 /// Derive a context that advertises `axis` as the enclosing stack's main
135 /// axis. Used by `HStack`/`VStack` when querying children so a `Spacer`
136 /// (and any other orientation-agnostic flexible leaf) can size correctly
137 /// per axis. All other fields are shared with `self`.
138 pub fn with_stack_main_axis(&self, axis: StackAxis) -> LayoutContext<'a> {
139 LayoutContext {
140 stack_main_axis: Some(axis),
141 theme: self.theme,
142 layout_direction: self.layout_direction,
143 scale_factor: self.scale_factor,
144 text_scale: self.text_scale,
145 text_backend: self.text_backend,
146 arena: self.arena,
147 extras: self.extras,
148 content_language: self.content_language.clone(),
149 language_for: self.language_for,
150 }
151 }
152
153 /// The currently focused widget id, if any. Returns `None` when
154 /// the layout pass is unrelated to a tree (test contexts).
155 pub fn focused(&self) -> Option<WidgetId> {
156 self.extras.as_ref().and_then(|e| e.focused)
157 }
158
159 /// Call `f` with every widget that holds live interaction state, and with
160 /// each of its ancestors up to a root.
161 ///
162 /// "Live interaction state" is what the framework destroys when it parks a
163 /// subtree dormant: the keyboard focus (cleared by
164 /// `WidgetTree::revalidate_interaction_state`), a captured pointer and an
165 /// in-flight drag source (both cancelled with
166 /// [`CancelReason::SubtreeParked`](crate::pointer::CancelReason)). Losing any
167 /// of them is fine when the *user* navigated away and wrong when the
168 /// *container* moved.
169 ///
170 /// So a container that culls by viewport intersects this with its own
171 /// children and pins whichever of them the user is in the middle of: a
172 /// card being typed in, or drag-selected inside, stays live wherever the
173 /// camera goes.
174 ///
175 /// Reported from the anchors *upward* rather than tested per child on
176 /// purpose — that makes the pin cost proportional to the number of live
177 /// interactions (almost always zero or one, times the tree depth) instead
178 /// of to the number of children, which is the quantity a culling container
179 /// exists to stop paying. Nothing is reported outside a real layout pass.
180 pub fn for_each_interaction_ancestor(&self, mut f: impl FnMut(WidgetId)) {
181 let (Some(arena), Some(extras)) = (self.arena, self.extras.as_ref()) else {
182 return;
183 };
184 for &anchor in extras.interaction_anchors {
185 let mut cur = Some(anchor);
186 while let Some(id) = cur {
187 f(id);
188 cur = arena.parent(id);
189 }
190 }
191 }
192
193 /// Borrow the tree's shortcut registry. Returns `None` outside a
194 /// real layout pass. Intended for read-only inspection by the
195 /// debug inspector.
196 pub fn shortcut_registry(&self) -> Option<&crate::shortcut::ShortcutRegistry> {
197 self.extras.as_ref().and_then(|e| e.shortcut_registry)
198 }
199
200 /// Borrow the tree's overlay manager. Returns `None` outside a
201 /// real layout pass. Intended for read-only inspection by the
202 /// debug inspector.
203 pub fn overlay_manager(&self) -> Option<&crate::overlay::OverlayManager> {
204 self.extras.as_ref().and_then(|e| e.overlay_manager)
205 }
206
207 /// Query a child widget's full layout response (wanted size + flex weight).
208 /// Returns None if the child doesn't exist, is dormant, or the arena is not available.
209 pub fn child_layout_response(
210 &self,
211 child_id: WidgetId,
212 proposal: teksilo_canvas::SizeProposal,
213 ) -> Option<LayoutResponse> {
214 // Routed through the arena's per-pass memoization cache so the
215 // main-then-cross queries that height-for-width negotiation issues do
216 // not recompute the same `(child, proposal)` repeatedly. The cache
217 // handles the active-state check and the `cacheable_layout()` opt-out.
218 let arena = self.arena?;
219 arena.cached_layout_response(child_id, proposal, self)
220 }
221
222 /// Measure a widget's intrinsic size for `proposal`, **regardless of
223 /// activation** — works even for dormant/collapsed widgets (and their
224 /// dormant subtrees), unlike [`child_size`](Self::child_size) /
225 /// [`child_layout_response`](Self::child_layout_response), which return
226 /// `None` for inactive widgets.
227 ///
228 /// Intended for adaptive layouts that hide some children but still need
229 /// their size to decide when to reveal them — e.g. an overflow `Toolbar`
230 /// collapsing actions into a chevron menu. Runs uncached and re-entrant-
231 /// safe; calls `layout_response`, which must be idempotent.
232 pub fn measure_intrinsic(
233 &self,
234 id: WidgetId,
235 proposal: teksilo_canvas::SizeProposal,
236 ) -> Option<teksilo_canvas::Size> {
237 self.arena?.measure_intrinsic(id, proposal, self)
238 }
239
240 /// Query a child widget's wanted size only (drops the flex weight).
241 /// Convenience over [`child_layout_response`](Self::child_layout_response).
242 pub fn child_size(
243 &self,
244 child_id: WidgetId,
245 proposal: teksilo_canvas::SizeProposal,
246 ) -> Option<teksilo_canvas::Size> {
247 self.child_layout_response(child_id, proposal)
248 .map(|r| r.size)
249 }
250
251 /// Query the laid-out bounds of any active widget. Returns `None`
252 /// when the arena is not available (test contexts) — otherwise
253 /// returns the widget's current bounds (`Rect::ZERO` if unknown).
254 /// Useful for inspector-style widgets that need to mirror another
255 /// widget's geometry into a `Signal` during the layout pass.
256 pub fn widget_bounds(&self, id: WidgetId) -> Option<teksilo_canvas::Rect> {
257 let arena = self.arena?;
258 if !arena.is_active(id) {
259 return None;
260 }
261 Some(arena.bounds(id))
262 }
263
264 /// Hit-test the active widget tree at `point` and return the
265 /// deepest widget under it. Honors `event_pass_through`. The
266 /// `exclude` argument lets the caller skip a specific subtree
267 /// (e.g. the inspector's picker overlay so it doesn't pick
268 /// itself). Returns `None` outside layout (no arena available).
269 pub fn widget_at_point(
270 &self,
271 point: teksilo_canvas::Point,
272 exclude: Option<WidgetId>,
273 ) -> Option<WidgetId> {
274 let arena = self.arena?;
275 arena.hit_test_at(point, exclude)
276 }
277
278 /// Borrow the underlying arena. Returns `None` outside a layout
279 /// pass (test contexts). Intended for read-only introspection by
280 /// debug tooling (the inspector's tree view) — use the typed
281 /// accessors above when possible.
282 pub fn arena(&self) -> Option<&crate::arena::WidgetArena> {
283 self.arena
284 }
285
286 /// Query a child's per-widget alignment override, if any.
287 pub fn child_alignment(&self, child_id: WidgetId) -> Option<teksilo_tokens::Alignment> {
288 let arena = self.arena?;
289 arena.alignment_override(child_id)
290 }
291
292 /// Whether the layout direction is right-to-left.
293 pub fn is_rtl(&self) -> bool {
294 self.layout_direction == crate::environment::LayoutDirection::RightToLeft
295 }
296}