Skip to main content

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    pub shortcut_registry: Option<&'a crate::shortcut::ShortcutRegistry>,
60    pub overlay_manager: Option<&'a crate::overlay::OverlayManager>,
61}
62
63impl<'a> LayoutContext<'a> {
64    /// Create a LayoutContext for testing (no arena access).
65    pub fn for_testing(theme: &'a crate::styles::Theme) -> Self {
66        Self {
67            theme,
68            layout_direction: crate::environment::LayoutDirection::LeftToRight,
69            scale_factor: 1.0,
70            text_scale: 1.0,
71            text_backend: None,
72            arena: None,
73            extras: None,
74            stack_main_axis: None,
75        }
76    }
77
78    /// The enclosing linear stack's main axis, if a stack is currently
79    /// querying this child. See [`StackAxis`].
80    pub fn stack_main_axis(&self) -> Option<StackAxis> {
81        self.stack_main_axis
82    }
83
84    /// Derive a context that advertises `axis` as the enclosing stack's main
85    /// axis. Used by `HStack`/`VStack` when querying children so a `Spacer`
86    /// (and any other orientation-agnostic flexible leaf) can size correctly
87    /// per axis. All other fields are shared with `self`.
88    pub fn with_stack_main_axis(&self, axis: StackAxis) -> LayoutContext<'a> {
89        LayoutContext {
90            stack_main_axis: Some(axis),
91            ..*self
92        }
93    }
94
95    /// The currently focused widget id, if any. Returns `None` when
96    /// the layout pass is unrelated to a tree (test contexts).
97    pub fn focused(&self) -> Option<WidgetId> {
98        self.extras.as_ref().and_then(|e| e.focused)
99    }
100
101    /// Borrow the tree's shortcut registry. Returns `None` outside a
102    /// real layout pass. Intended for read-only inspection by the
103    /// debug inspector.
104    pub fn shortcut_registry(&self) -> Option<&crate::shortcut::ShortcutRegistry> {
105        self.extras.as_ref().and_then(|e| e.shortcut_registry)
106    }
107
108    /// Borrow the tree's overlay manager. Returns `None` outside a
109    /// real layout pass. Intended for read-only inspection by the
110    /// debug inspector.
111    pub fn overlay_manager(&self) -> Option<&crate::overlay::OverlayManager> {
112        self.extras.as_ref().and_then(|e| e.overlay_manager)
113    }
114
115    /// Query a child widget's full layout response (wanted size + flex weight).
116    /// Returns None if the child doesn't exist, is dormant, or the arena is not available.
117    pub fn child_layout_response(
118        &self,
119        child_id: WidgetId,
120        proposal: teksilo_canvas::SizeProposal,
121    ) -> Option<LayoutResponse> {
122        // Routed through the arena's per-pass memoization cache so the
123        // main-then-cross queries that height-for-width negotiation issues do
124        // not recompute the same `(child, proposal)` repeatedly. The cache
125        // handles the active-state check and the `cacheable_layout()` opt-out.
126        let arena = self.arena?;
127        arena.cached_layout_response(child_id, proposal, self)
128    }
129
130    /// Measure a widget's intrinsic size for `proposal`, **regardless of
131    /// activation** — works even for dormant/collapsed widgets (and their
132    /// dormant subtrees), unlike [`child_size`](Self::child_size) /
133    /// [`child_layout_response`](Self::child_layout_response), which return
134    /// `None` for inactive widgets.
135    ///
136    /// Intended for adaptive layouts that hide some children but still need
137    /// their size to decide when to reveal them — e.g. an overflow `Toolbar`
138    /// collapsing actions into a chevron menu. Runs uncached and re-entrant-
139    /// safe; calls `layout_response`, which must be idempotent.
140    pub fn measure_intrinsic(
141        &self,
142        id: WidgetId,
143        proposal: teksilo_canvas::SizeProposal,
144    ) -> Option<teksilo_canvas::Size> {
145        self.arena?.measure_intrinsic(id, proposal, self)
146    }
147
148    /// Query a child widget's wanted size only (drops the flex weight).
149    /// Convenience over [`child_layout_response`](Self::child_layout_response).
150    pub fn child_size(
151        &self,
152        child_id: WidgetId,
153        proposal: teksilo_canvas::SizeProposal,
154    ) -> Option<teksilo_canvas::Size> {
155        self.child_layout_response(child_id, proposal)
156            .map(|r| r.size)
157    }
158
159    /// Query the laid-out bounds of any active widget. Returns `None`
160    /// when the arena is not available (test contexts) — otherwise
161    /// returns the widget's current bounds (`Rect::ZERO` if unknown).
162    /// Useful for inspector-style widgets that need to mirror another
163    /// widget's geometry into a `Signal` during the layout pass.
164    pub fn widget_bounds(&self, id: WidgetId) -> Option<teksilo_canvas::Rect> {
165        let arena = self.arena?;
166        if !arena.is_active(id) {
167            return None;
168        }
169        Some(arena.bounds(id))
170    }
171
172    /// Hit-test the active widget tree at `point` and return the
173    /// deepest widget under it. Honors `event_pass_through`. The
174    /// `exclude` argument lets the caller skip a specific subtree
175    /// (e.g. the inspector's picker overlay so it doesn't pick
176    /// itself). Returns `None` outside layout (no arena available).
177    pub fn widget_at_point(
178        &self,
179        point: teksilo_canvas::Point,
180        exclude: Option<WidgetId>,
181    ) -> Option<WidgetId> {
182        let arena = self.arena?;
183        arena.hit_test_at(point, exclude)
184    }
185
186    /// Borrow the underlying arena. Returns `None` outside a layout
187    /// pass (test contexts). Intended for read-only introspection by
188    /// debug tooling (the inspector's tree view) — use the typed
189    /// accessors above when possible.
190    pub fn arena(&self) -> Option<&crate::arena::WidgetArena> {
191        self.arena
192    }
193
194    /// Query a child's per-widget alignment override, if any.
195    pub fn child_alignment(&self, child_id: WidgetId) -> Option<teksilo_tokens::Alignment> {
196        let arena = self.arena?;
197        arena.alignment_override(child_id)
198    }
199
200    /// Whether the layout direction is right-to-left.
201    pub fn is_rtl(&self) -> bool {
202        self.layout_direction == crate::environment::LayoutDirection::RightToLeft
203    }
204}