teksilo-core 0.9.0

Core of the Teksilo GUI framework — widget trait, arena, layout engine, event dispatch, focus, signals and theming.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

use super::*;

impl WidgetTree {
    /// Get an immutable reference to a widget node (for internal use).
    #[allow(dead_code)]
    pub(crate) fn arena_get(&self, id: WidgetId) -> Option<&crate::arena::WidgetNode> {
        self.arena.get(id)
    }

    pub fn bounds(&self, id: WidgetId) -> Rect {
        self.arena.bounds(id)
    }

    /// Last known pointer position from a `PointerMove` event. Used
    /// by the safe-triangle submenu hover gate to compare the
    /// cursor trajectory against the open submenu's bounds without
    /// requiring the gate's evaluation site to receive a fresh
    /// `PointerMove` itself.
    pub fn last_pointer_position(&self) -> Option<teksilo_canvas::Point> {
        self.last_pointer_position
    }

    /// Borrow the widget at `id` as `&dyn Any` for concrete-type
    /// introspection. Uses the `Widget::as_any` hook — widgets that
    /// haven't opted in return `None`. Primarily for tests that need
    /// to inspect a widget's private Signal state.
    pub fn widget_as_any(&self, id: WidgetId) -> Option<&dyn std::any::Any> {
        self.arena.get(id).and_then(|node| node.widget.as_any())
    }

    /// Mutable variant of [`widget_as_any`](Self::widget_as_any).
    /// Widgets opt in by overriding `Widget::as_any_mut`. Used by
    /// tests that need to mutate widget state post-layout (e.g.
    /// declaring a logical AT parent on a `SceneView` after the
    /// arena allocated the inner widget's `WidgetId`).
    pub fn widget_as_any_mut(&mut self, id: WidgetId) -> Option<&mut dyn std::any::Any> {
        self.arena
            .get_mut(id)
            .and_then(|node| node.widget.as_any_mut())
    }

    pub fn children(&self, id: WidgetId) -> Vec<WidgetId> {
        self.arena.children(id).to_vec()
    }

    /// Root widget ids of the arena (the entry points for a full widget-tree
    /// walk). Mirrors what the debug inspector starts its tree view from.
    pub fn roots(&self) -> Vec<WidgetId> {
        self.arena.roots()
    }

    /// The concrete Rust type name of the widget at `id` (e.g.
    /// `"teksilo_widgets::button::Button"`), or `None` if the id isn't in the
    /// arena. The same `Widget::type_name()` the inspector's tree view labels
    /// rows with.
    pub fn widget_type_name(&self, id: WidgetId) -> Option<&'static str> {
        self.arena.get(id).map(|n| n.widget.type_name())
    }

    /// The widget at `id` formatted via its `Debug` impl — its constructor
    /// parameters / fields, the same "debug repr" the inspector's Properties
    /// tab shows. `None` if the id isn't in the arena.
    pub fn widget_debug_string(&self, id: WidgetId) -> Option<String> {
        self.arena.get(id).map(|n| format!("{:?}", n.widget))
    }

    /// Whether the widget at `id` clips its children (e.g. `ScrollArea`,
    /// `MaxSize`). `false` if the id isn't in the arena.
    pub fn widget_clips_children(&self, id: WidgetId) -> bool {
        self.arena
            .get(id)
            .map(|n| n.clips_children)
            .unwrap_or(false)
    }

    /// The most recent layout proposal applied to this tree (the size
    /// last passed to [`layout`](Self::layout) / `layout_with_ops`).
    /// Lets a settle pass re-run layout at the current size without
    /// recomputing it from a surface dimension. Returns
    /// `SizeProposal::exact(800.0, 600.0)` on a tree that was never
    /// laid out.
    pub fn last_proposal(&self) -> SizeProposal {
        self.last_proposal
    }

    /// Monotonic accessibility-tree version. Bumped in
    /// [`sync_accessibility`](Self::sync_accessibility) only when a rebuild
    /// produces a tree whose *content* actually differs from the cached one
    /// (cache hits don't bump, and a rebuild that reproduces an identical
    /// `TreeUpdate` — e.g. from a shortcut-rebind / locale invalidation —
    /// doesn't either). Saturating, so the monotonic contract holds past
    /// `u64::MAX`. Mirrors
    /// [`ShortcutRegistry::version`](crate::shortcut::ShortcutRegistry::version):
    /// poll it to detect AT-tree changes without diffing the whole
    /// `TreeUpdate`.
    pub fn at_version(&self) -> &crate::signal::Signal<u64> {
        &self.at_version
    }

    /// Drain the captured live-region announcements with `seq` strictly
    /// greater than `seq`. See [`crate::accessibility::Announcement`].
    /// The buffer is capped at 256 entries, so a caller that lags far
    /// behind sees only the retained tail. Read after a
    /// [`sync_accessibility`](Self::sync_accessibility) (or a settle that
    /// ends in one) to observe announcements raised by the latest
    /// rebuild.
    pub fn announcements_since(&self, seq: u64) -> Vec<crate::accessibility::Announcement> {
        self.automation_announcements
            .iter()
            .filter(|a| a.seq > seq)
            .cloned()
            .collect()
    }

    /// Parent widget id in the arena graph, or `None` for roots.
    pub fn parent(&self, id: WidgetId) -> Option<WidgetId> {
        self.arena.parent(id)
    }

    pub fn needs_layout(&self) -> bool {
        self.arena.any_needs_layout()
    }

    pub fn needs_paint(&self) -> bool {
        self.arena.any_needs_paint()
    }

    pub fn active_animation_count(&self) -> usize {
        self.animation_scheduler.active_count()
    }

    pub fn pending_tooltip_count(&self) -> usize {
        self.tooltips
            .iter()
            .filter(|entry| entry.overlay_id.is_none() && entry.real_hover_start.is_some())
            .count()
    }

    /// Whether there are pending idle callbacks to run.
    pub fn has_idle_work(&self) -> bool {
        !self.idle_queue.is_empty()
    }

    pub fn has_pending_modal_requests(&self) -> bool {
        !self.pending_modal_requests.is_empty()
    }

    pub fn has_pending_modal_dismissal(&self) -> bool {
        self.pending_modal_dismissal
    }

    pub fn current_cursor(&self) -> crate::widget::CursorIcon {
        self.current_cursor
    }

    /// The widget currently under the pointer, if any. The framework
    /// updates this on `PointerMove` / hover routing; widgets that have
    /// captured the pointer or that opt out via `event_pass_through`
    /// affect what shows up here. Mirrors the private `hovered` field
    /// for read-only consumers (debug inspector, layout introspection).
    pub fn hovered(&self) -> Option<WidgetId> {
        self.hovered
    }

    /// Reactive handle to the hovered widget id. Cheap clone — the
    /// underlying `Signal` is shared. Set whenever `hovered` changes
    /// during dispatch, post-layout hover recovery, widget destruction,
    /// or overlay subtree dormancy. Intended for debug tooling that
    /// wants to react to hover without polling (the inspector's hover
    /// tooltip).
    pub fn hovered_signal(&self) -> crate::signal::Signal<Option<WidgetId>> {
        self.hovered_signal.clone()
    }

    /// Reactive handle to the focused widget id. Mirror of
    /// [`hovered_signal`](Self::hovered_signal) for the focus chain;
    /// drives the inspector's Focus tab without polling.
    pub fn focused_signal(&self) -> crate::signal::Signal<Option<WidgetId>> {
        self.focused_signal.clone()
    }

    /// Drain and run all pending idle callbacks with the given time budget.
    /// Called by the event loop during idle periods between frames.
    pub fn run_idle_callbacks(&mut self, budget: std::time::Duration) {
        let callbacks = self.idle_queue.drain();
        for callback in callbacks {
            callback(crate::idle::IdleDeadline::new(budget));
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::overlay::{DismissBehavior, OverlayLayer, OverlayPlacement, OverlayRequest};
    use crate::test_widgets::FillWidget;
    use crate::widget_builder::WidgetBuilder;
    use crate::{ModalCloseBehavior, ModalContent, ModalPresentation, ModalRequest};
    use std::cell::Cell;
    use std::rc::Rc;
    use teksilo_canvas::Size;

    #[derive(Debug)]
    struct FixedWidget(f32, f32);

    impl Widget for FixedWidget {
        fn layout_response(
            &self,
            _proposal: SizeProposal,
            _ctx: &LayoutContext,
        ) -> crate::widget::LayoutResponse {
            Size::new(self.0, self.1).into()
        }
    }

    #[test]
    fn destroy_removes_from_arena() {
        let mut tree = WidgetTree::new();
        let widget = tree.add(FillWidget::new().label("Gone"));
        tree.layout(SizeProposal::exact(100.0, 50.0));
        assert!(tree.find_by_label("Gone").is_some());

        tree.arena.destroy(widget);
        assert!(tree.find_by_label("Gone").is_none());
    }

    #[test]
    fn idle_callback_requested_from_event_handler() {
        let called = Rc::new(Cell::new(false));
        let called_flag = called.clone();
        let mut tree = WidgetTree::new();
        let widget = tree.add(FillWidget::new().on_tap(move |_pos, ctx| {
            let called = called_flag.clone();
            ctx.request_idle_callback(move |_deadline| {
                called.set(true);
            });
        }));
        tree.layout(SizeProposal::exact(100.0, 50.0));

        assert!(!tree.has_idle_work());

        tree.click(widget);

        assert!(tree.has_idle_work());
        assert!(!called.get());

        tree.run_idle_callbacks(std::time::Duration::from_millis(16));

        assert!(called.get());
        assert!(!tree.has_idle_work());
    }

    #[test]
    fn set_locale_from_event_handler_is_parked_not_applied() {
        let mut tree = WidgetTree::new();
        let widget = tree.add(FillWidget::new().on_tap(|_pos, ctx| {
            ctx.set_locale("fr-FR");
        }));
        tree.layout(SizeProposal::exact(100.0, 50.0));
        assert!(tree.locale().is_none());

        tree.click(widget);

        // The tree's own locale signal must NOT have been flipped — the
        // app layer is responsible for routing the switch through
        // `WindowManager::set_locale` so the `I18nManager`'s active
        // locale, version signal, and RTL direction stay in sync.
        assert_eq!(tree.locale(), None);
        // The request is parked for the app layer to drain.
        assert_eq!(
            tree.take_pending_locale_request(),
            Some("fr-FR".to_string())
        );
        // Drained exactly once.
        assert_eq!(tree.take_pending_locale_request(), None);
    }

    #[test]
    fn set_theme_from_event_handler_is_parked_not_applied() {
        use crate::ThemeAppearance;

        let mut tree = WidgetTree::new();
        // `WidgetTree::new()` starts on the light preset.
        assert_eq!(tree.theme().appearance, ThemeAppearance::Light);

        let widget = tree.add(FillWidget::new().on_tap(|_pos, ctx| {
            ctx.set_theme(crate::presets::intui::dark());
        }));
        tree.layout(SizeProposal::exact(100.0, 50.0));

        tree.click(widget);

        // The tree's own theme must NOT have been flipped inline — the app
        // layer routes the switch through `WindowManager::set_theme` so it
        // fans out to *every* window, not just this one.
        assert_eq!(tree.theme().appearance, ThemeAppearance::Light);
        // The request is parked for the app layer to drain.
        let parked = tree.take_pending_theme_request();
        assert_eq!(parked.map(|t| t.appearance), Some(ThemeAppearance::Dark));
        // Drained exactly once.
        assert!(tree.take_pending_theme_request().is_none());
    }

    #[test]
    fn idle_deadline_provides_time_budget() {
        let deadline = crate::idle::IdleDeadline::new(std::time::Duration::from_millis(100));
        assert!(!deadline.did_timeout());
        assert!(deadline.time_remaining() > std::time::Duration::ZERO);
    }

    #[test]
    fn modal_request_requested_from_event_handler() {
        let mut tree = WidgetTree::new();
        let content = tree.add(FillWidget::new().label("Modal content"));
        let trigger = tree.add(FillWidget::new().on_tap(move |_pos, ctx| {
            ctx.present_modal(
                ModalRequest::in_tree(content)
                    .presentation(ModalPresentation::InTree)
                    .close_behavior(ModalCloseBehavior::Manual),
            );
        }));
        tree.layout(SizeProposal::exact(100.0, 50.0));

        assert!(!tree.has_pending_modal_requests());

        tree.click(trigger);

        assert!(tree.has_pending_modal_requests());
        let requests = tree.drain_pending_modal_requests();
        assert_eq!(requests.len(), 1);
        assert_eq!(requests[0].source_widget, trigger);
        assert_eq!(requests[0].request.presentation, ModalPresentation::InTree);
        assert_eq!(
            requests[0].request.close_behavior,
            ModalCloseBehavior::Manual
        );
        match requests[0].request.content {
            ModalContent::ExistingWidget(id) => assert_eq!(id, content),
            ModalContent::Deferred(_) => panic!("expected ExistingWidget content"),
        }
        assert!(!tree.has_pending_modal_requests());
    }

    #[test]
    fn draining_modal_requests_clears_queue() {
        let mut tree = WidgetTree::new();
        let content = tree.add(FillWidget::new());
        let trigger = tree.add(FillWidget::new().on_tap(move |_pos, ctx| {
            ctx.present_modal(ModalRequest::in_tree(content));
        }));
        tree.layout(SizeProposal::exact(100.0, 50.0));

        tree.click(trigger);
        assert_eq!(tree.drain_pending_modal_requests().len(), 1);
        assert!(tree.drain_pending_modal_requests().is_empty());
    }

    #[test]
    fn dismiss_modal_closes_centered_overlay_for_source_widget() {
        let mut tree = WidgetTree::new();
        let trigger = tree.add(FillWidget::new().label("Trigger"));
        let modal_content = tree.add(FixedWidget(120.0, 48.0).on_tap(|_pos, ctx| {
            ctx.dismiss_modal();
        }));
        tree.layout(SizeProposal::exact(320.0, 200.0));

        tree.show_overlay(OverlayRequest {
            content_id: modal_content,
            anchor: trigger,
            placement: OverlayPlacement::Centered,
            dismiss: DismissBehavior::Manual,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });
        tree.layout(SizeProposal::exact(320.0, 200.0));

        assert_eq!(tree.active_overlays().len(), 1);

        let center = tree
            .overlay_manager()
            .topmost_centered()
            .expect("expected centered modal overlay")
            .bounds
            .center();
        tree.pointer_down_button(center, PointerButton::Primary);
        tree.pointer_up_button(center, PointerButton::Primary);

        assert!(tree.active_overlays().is_empty());
        assert!(!tree.has_pending_modal_dismissal());
    }

    #[test]
    fn dismiss_modal_without_in_tree_modal_queues_window_dismissal() {
        let mut tree = WidgetTree::new();
        let trigger = tree.add(FillWidget::new().on_tap(|_pos, ctx| {
            ctx.dismiss_modal();
        }));
        tree.layout(SizeProposal::exact(100.0, 50.0));

        assert!(!tree.has_pending_modal_dismissal());

        tree.click(trigger);

        assert!(tree.has_pending_modal_dismissal());
        assert!(tree.drain_pending_modal_dismissal());
        assert!(!tree.has_pending_modal_dismissal());
    }
}