teksilo-core 0.11.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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! The tree-owned long-press route.
//!
//! A finger has no hover, so every affordance a mouse reaches by resting on it
//! needs a second way in. For two of them — a context menu and a tooltip — the
//! way in is a hold, and neither can be delivered by the widget that owns the
//! affordance:
//!
//! * a **context menu** is mounted from a factory the router walks up to
//!   (`WidgetTree::show_context_menu_for`), not from a handler, so no widget
//!   is in a position to open one from its own `on_long_press`;
//! * a **tooltip** is attached to a node the router keeps in its own table, and
//!   the anchor may be **disabled** — a disabled node is dropped from focus
//!   traversal and never reaches `dispatch_to_widget`, so it has no gesture
//!   arena and cannot recognise anything at all. Hover is today the only way to
//!   ask "why is this greyed out?", which is precisely the question a touch user
//!   has no way to ask.
//!
//! So the route is the tree's: a deadline hung off the press, resolved in the
//! same pass as the press-feedback delay and a standing hold's expiry
//! (`tick_gestures_with_ops`), reached from `advance_time` like every other
//! input deadline and folded into the one `WaitUntil` through
//! [`WidgetTree::next_input_deadline`].
//!
//! # Precedence
//!
//! Three rules, in order:
//!
//! 1. **A widget's own `on_long_press` wins.** If any *enabled* node on the
//!    press's frozen path carries one, no tree route is armed. The widget said
//!    what its hold means.
//! 2. **A hold that is a grab is spent.** Where the hold is the mechanism that
//!    arms a drag — a reorderable row under a finger, whose drag member is
//!    deferred to the long-press deadline — the hold belongs to the grab, and
//!    long-press *recognition* on that path is suppressed as well (see
//!    `WidgetTree::long_press_is_a_grab`). [`LongPressRole::DragHandle`]
//!    declares the same thing for a node whose grab the deferral cannot see.
//! 3. Otherwise the resolved [`LongPressRole`] selects the route, and
//!    [`LongPressRole::Auto`] — the default — resolves to the context menu if
//!    one is reachable, else the tooltip, else nothing.
//!
//! # What it is not
//!
//! Not a mouse path. The route is armed only for a **coarse** pointer
//! ([`PointerKind::is_coarse`](teksilo_tokens::PointerKind::is_coarse)), which
//! is touch and touch only — a pen has a barrel button and a genuine hover, so
//! giving it a hold-to-menu would take away a press it already uses, and an
//! unclassified pointer is tuned as a mouse (see `arm_touch_route` for why
//! "cannot hover" is the wrong predicate here, even though it reads like the
//! right one).

use teksilo_canvas::Point;

use crate::pointer::{EventTime, PointerId};
use crate::widget_id::WidgetId;

use super::WidgetTree;

/// How long a tooltip a hold summoned stays up.
///
/// There is no pointer to leave and no focus to move, so the two routes that
/// retire a hovered or a focused tip both do nothing here. The tip owns its own
/// expiry instead — long enough to read a sentence, short enough that it is
/// gone before it is in the way. Escape and a press anywhere else still retire
/// it sooner.
pub const TOUCH_TOOLTIP_DISMISS: std::time::Duration = std::time::Duration::from_secs(5);

/// What a hold on a node means, when the node itself does not say.
///
/// Selects the tree-owned fallback described in the
/// [module documentation](self); a widget's own `on_long_press` always takes
/// precedence over every variant of this.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LongPressRole {
    /// Resolve from what the node offers: a context menu if a factory is
    /// reachable on the path, else a tooltip if one is attached, else nothing.
    /// The default, and what every node that never mentions the property gets.
    #[default]
    Auto,
    /// No tree-owned route, and none for anything below this node either. A
    /// subtree that wants its hold left alone without having to install a
    /// handler to swallow it.
    None,
    /// The hold opens the context menu, and does not fall back to a tooltip
    /// when no factory answers.
    ContextMenu,
    /// The hold shows the tooltip, even where a context-menu factory is also
    /// reachable.
    Tooltip,
    /// The hold **is** the grab: it arms this node's drag, so it is not
    /// available for a menu or a tip, and long-press recognition is suppressed
    /// on this node and everything below it. Declare it on a node whose grab
    /// the framework's own deferral cannot see — one that takes the pointer by
    /// an explicit `capture_pointer` rather than through a drag recognizer.
    DragHandle,
}

/// The route a resolved hold will take.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Route {
    ContextMenu,
    /// The index into `WidgetTree::tooltips` of the entry to show.
    Tooltip(usize),
}

/// A hold the tree is waiting out.
pub(super) struct PendingTouchRoute {
    pointer: PointerId,
    /// The node the press landed on. The context menu walks up from here and
    /// the announcement is checked against it.
    target: WidgetId,
    /// **Window** space, not node-local: `show_context_menu_for` places the
    /// menu against the window and a gesture's own `TapEvent` has already been
    /// localized by the time it is dispatched.
    position: Point,
    deadline: EventTime,
    route: Route,
}

impl WidgetTree {
    /// Whether a hold on `id` is already spoken for as a grab, for the pointer
    /// whose sequence is `pointer`.
    ///
    /// Two ways it can be:
    ///
    /// * a live member of the sequence has had its activation **deferred to the
    ///   long-press deadline** — which is what `DragActivation::Auto` resolves
    ///   to for a direct pointer with a pan competitor, i.e. a reorderable row
    ///   under a finger. The deferral *is* the mechanism, so a node whose grab
    ///   it arms cannot also fire a long press;
    /// * a node at or above `id` on the frozen path declared
    ///   [`LongPressRole::DragHandle`].
    ///
    /// A mouse is unaffected by construction: it enrols no pan claimant, so
    /// `resolve_activation` never returns `AfterLongPress` and nothing is
    /// deferred.
    pub(super) fn long_press_is_a_grab(&self, pointer: PointerId, id: WidgetId) -> bool {
        let Some(sequence) = self
            .pointers
            .get(pointer)
            .and_then(|entry| entry.sequence.as_ref())
        else {
            return false;
        };
        if sequence.has_deferred_grab() {
            return true;
        }
        let path = sequence.path();
        let Some(cut) = path.iter().position(|&n| n == id) else {
            return false;
        };
        // The path runs target → root, so everything from `cut` onward is `id`
        // itself or an ancestor of it.
        path[cut..]
            .iter()
            .any(|&n| self.long_press_role_of(n) == LongPressRole::DragHandle)
    }

    fn long_press_role_of(&self, id: WidgetId) -> LongPressRole {
        self.arena
            .get(id)
            .map(|node| node.long_press_role)
            .unwrap_or_default()
    }

    /// Arm the tree-owned hold for the press that has just been opened.
    ///
    /// Called from the `PointerDown` arm once the sequence exists (the frozen
    /// path is what the resolution walks) and the press record is open.
    pub(super) fn arm_touch_route(&mut self, target: WidgetId, position: Point) {
        self.pending_touch_route = None;
        let pointer = self.current_input.pointer;
        // Touch and touch only, which is `is_coarse` and not `!hovers`: a pen
        // hovers, so it already reaches both affordances the way a mouse does
        // and has a barrel button for the menu — but an *unclassified* pointer
        // hovers no more than a finger does, and `InputTokens::profile` hands it
        // the MOUSE profile ("treated as Mouse for gesture tuning, the
        // conservative choice"). Arming a route here for it would time a hold
        // against a profile whose `long_press` was never meant to arm one.
        if !pointer.kind.is_coarse() {
            return;
        }
        // The kill switch means the framework is not handling touch at all;
        // a route armed here would be the one touch behaviour that survived it.
        if !self.effective_theme.input.touch_enabled {
            return;
        }
        let Some(path) = self
            .pointers
            .get(pointer.id)
            .and_then(|entry| entry.sequence.as_ref())
            .map(|sequence| sequence.path().to_vec())
        else {
            return;
        };
        // Rule 1: a widget said what its own hold means.
        if path.iter().any(|&id| {
            self.arena.is_enabled(id)
                && self
                    .arena
                    .get(id)
                    .is_some_and(|node| node.any_handler(|h| h.on_long_press.is_some()))
        }) {
            return;
        }
        // Rule 2: the hold is a grab.
        if self.long_press_is_a_grab(pointer.id, target) {
            return;
        }
        let Some(route) = self.resolve_touch_route(&path) else {
            return;
        };
        let profile = self.effective_theme.input.profile(pointer.kind);
        let started = self
            .pointers
            .get(pointer.id)
            .and_then(|entry| entry.sequence.as_ref())
            .map(|sequence| sequence.started_at());
        let Some(started) = started else {
            return;
        };
        self.pending_touch_route = Some(PendingTouchRoute {
            pointer: pointer.id,
            target,
            position,
            deadline: started + profile.long_press,
            route,
        });
    }

    /// Rule 3: what the innermost node that has an opinion says, else the
    /// `Auto` fallback order.
    fn resolve_touch_route(&self, path: &[WidgetId]) -> Option<Route> {
        // The path runs target → root, so this walk is innermost-first: a row
        // inside a menu-owning list decides for itself.
        for &id in path {
            match self.long_press_role_of(id) {
                LongPressRole::Auto => continue,
                LongPressRole::None | LongPressRole::DragHandle => return None,
                LongPressRole::ContextMenu => return self.context_menu_route(path),
                LongPressRole::Tooltip => return self.tooltip_route(path),
            }
        }
        self.context_menu_route(path)
            .or_else(|| self.tooltip_route(path))
    }

    fn context_menu_route(&self, path: &[WidgetId]) -> Option<Route> {
        path.iter()
            .any(|&id| {
                self.arena
                    .get(id)
                    .is_some_and(|node| node.context_menu_factory.is_some())
            })
            .then_some(Route::ContextMenu)
    }

    /// The innermost tooltip anchored at or above the pressed node — the same
    /// choice `tooltip_pointer_enter` makes for a hover, and made the same way,
    /// so a hold and a hover surface the same tip.
    fn tooltip_route(&self, path: &[WidgetId]) -> Option<Route> {
        let target = *path.first()?;
        self.tooltip_index_for(target).map(Route::Tooltip)
    }

    /// Disarm the hold: the press ended, was revoked, or travelled far enough
    /// to be something else.
    pub(super) fn cancel_touch_route(&mut self, pointer: PointerId) {
        if self
            .pending_touch_route
            .as_ref()
            .is_some_and(|pending| pending.pointer == pointer)
        {
            self.pending_touch_route = None;
        }
    }

    /// A move: the hold survives only while the contact stays inside the
    /// profile's tap boundary. Past it the gesture is a pan or a drag and the
    /// route has nothing to say.
    pub(super) fn touch_route_moved(&mut self, pointer: PointerId) {
        let Some(pending) = self.pending_touch_route.as_ref() else {
            return;
        };
        if pending.pointer != pointer {
            return;
        }
        let Some(entry) = self.pointers.get(pointer) else {
            return;
        };
        let Some(sequence) = entry.sequence.as_ref() else {
            // No sequence left to measure against — the press is over.
            self.pending_touch_route = None;
            return;
        };
        let slop = self.effective_theme.input.profile(entry.info.kind).tap_slop;
        if sequence.travel() > slop {
            self.pending_touch_route = None;
        }
    }

    /// The instant the pending hold wants the loop back, if there is one.
    pub(super) fn next_touch_route_deadline(&self) -> Option<EventTime> {
        self.pending_touch_route
            .as_ref()
            .map(|pending| pending.deadline)
    }

    /// Fire a hold whose deadline has come. Runs in `tick_gestures_with_ops`
    /// beside the other three tree-owned input deadlines.
    pub(super) fn resolve_touch_routes(
        &mut self,
        now: EventTime,
        ops: &mut dyn crate::window::WindowOps,
    ) {
        let Some(pending) = self.pending_touch_route.as_ref() else {
            return;
        };
        if now < pending.deadline {
            return;
        }
        let Some(pending) = self.pending_touch_route.take() else {
            return;
        };
        // The target may have gone away under the finger.
        if !self.arena.is_active(pending.target) {
            return;
        }
        let fired = match pending.route {
            Route::ContextMenu => self.fire_context_menu_route(&pending, ops),
            Route::Tooltip(index) => self.fire_tooltip_route(&pending, index),
        };
        if fired {
            // The hold has been answered; the release must not also actuate the
            // control the menu or the tip is about.
            if let Some(sequence) = self
                .pointers
                .get_mut(pending.pointer)
                .and_then(|entry| entry.sequence.as_mut())
            {
                sequence.set_taps_cancelled();
            }
        }
    }

    fn fire_context_menu_route(
        &mut self,
        pending: &PendingTouchRoute,
        ops: &mut dyn crate::window::WindowOps,
    ) -> bool {
        if !self.show_context_menu_for(pending.target, pending.position, ops) {
            return false;
        }
        if let Some(wording) = self.context_menu_announcement.clone() {
            self.announce_unless_widget_speaks(pending.target, wording());
        }
        true
    }

    fn fire_tooltip_route(&mut self, pending: &PendingTouchRoute, index: usize) -> bool {
        // The table may have been rebuilt since the press; re-resolve rather
        // than trusting the index across a rebuild.
        let index = match self.tooltip_index_for(pending.target) {
            Some(fresh) => fresh,
            None => index,
        };
        let Some(entry) = self.tooltips.get_mut(index) else {
            return false;
        };
        if entry.overlay_id.is_some() {
            // Already up — nothing to do, and nothing to cancel a tap for.
            return false;
        }
        // Backdate the dwell instead of duplicating the show: the hold has
        // already paid the delay, so the ordinary tooltip pass shows it inside
        // this same virtual frame, having run its content and blank-body checks
        // exactly as it would for a hover.
        let delay = entry.delay;
        entry.hover_start = Some(sub_or(self.sim_clock, delay));
        entry.real_hover_start = Some(sub_or(std::time::Instant::now(), delay));
        entry.hover_origin = Some(pending.position);
        entry.armed_by_focus = false;
        entry.armed_by_hold = true;
        let anchor = entry.anchor_id;
        self.arena.mark_needs_paint(anchor);
        true
    }
}

/// `instant - duration`, or `instant` where the platform's monotonic origin is
/// nearer than that. A tooltip whose dwell cannot be backdated ripens on the
/// next pass instead of this one — the same tip, one frame later.
fn sub_or(instant: std::time::Instant, duration: std::time::Duration) -> std::time::Instant {
    instant.checked_sub(duration).unwrap_or(instant)
}

#[cfg(test)]
mod tests {
    use std::cell::Cell;
    use std::rc::Rc;

    use teksilo_canvas::{Point, SizeProposal};

    use super::*;
    use crate::test_widgets::{FillWidget, InsetWidget, StackWidget};
    use crate::widget::Widget;
    use crate::widget_builder::WidgetBuilder;
    use crate::widget_tree::WidgetTree;

    /// The touch profile's hold, which is what the route's deadline is.
    fn hold() -> std::time::Duration {
        teksilo_tokens::GestureProfile::TOUCH.long_press
    }

    fn menu() -> Box<dyn Widget> {
        Box::new(FillWidget::new().label("menu"))
    }

    /// A tree whose single widget owns a context-menu factory, plus the count of
    /// times that factory has been asked.
    fn tree_with_menu() -> (WidgetTree, WidgetId, Rc<Cell<usize>>) {
        let opened = Rc::new(Cell::new(0usize));
        let counter = opened.clone();
        let mut tree = WidgetTree::new();
        let id = tree.add(FillWidget::new().context_menu(move |_pos, _ctx| {
            counter.set(counter.get() + 1);
            Some(menu())
        }));
        tree.layout(SizeProposal::exact(200.0, 100.0));
        (tree, id, opened)
    }

    #[test]
    fn a_hold_opens_the_context_menu_once_and_announces() {
        let (mut tree, id, opened) = tree_with_menu();
        let spoken = Rc::new(Cell::new(0usize));
        let counter = spoken.clone();
        tree.set_context_menu_announcement(Some(Rc::new(move || {
            counter.set(counter.get() + 1);
            "menu opened".to_string()
        })));

        let at = tree.bounds(id).center();
        let f = tree.new_contact();
        tree.touch_down(f, at);
        assert_eq!(opened.get(), 0, "the factory must not run on the press");

        tree.advance_input_time(hold() + std::time::Duration::from_millis(10));
        assert_eq!(opened.get(), 1, "the hold must open the menu");
        assert_eq!(spoken.get(), 1, "and announce it once");
        assert_eq!(tree.active_overlays().len(), 1);

        // Holding on does not open a second one.
        tree.advance_input_time(hold() * 3);
        assert_eq!(opened.get(), 1, "the hold opens exactly one menu");
        assert_eq!(spoken.get(), 1);
    }

    #[test]
    fn no_wording_registered_announces_nothing() {
        let (mut tree, id, opened) = tree_with_menu();
        let at = tree.bounds(id).center();
        let f = tree.new_contact();
        tree.touch_down(f, at);
        tree.advance_input_time(hold() + std::time::Duration::from_millis(10));
        assert_eq!(opened.get(), 1);
        assert!(
            tree.announcements_since(0).is_empty(),
            "silence is the default: the framework cannot word this itself",
        );
    }

    #[test]
    fn a_mouse_hold_opens_no_context_menu() {
        let (mut tree, id, opened) = tree_with_menu();
        let at = tree.bounds(id).center();
        tree.pointer_move(at);
        tree.pointer_down_button(at, crate::event::PointerButton::Primary);
        tree.advance_input_time(hold() * 4);
        assert_eq!(
            opened.get(),
            0,
            "a mouse has a secondary button; a held primary is not a menu request",
        );
    }

    #[test]
    fn a_pen_hold_opens_no_context_menu() {
        let (mut tree, id, opened) = tree_with_menu();
        let at = tree.bounds(id).center();
        tree.pen_down(at, 0.5, (0.0, 0.0));
        tree.advance_input_time(hold() * 4);
        assert_eq!(
            opened.get(),
            0,
            "a pen hovers and has a barrel button, so the hold stays its own",
        );
    }

    #[test]
    fn a_lift_before_the_deadline_opens_nothing() {
        let (mut tree, id, opened) = tree_with_menu();
        let at = tree.bounds(id).center();
        let f = tree.new_contact();
        tree.touch_down(f, at);
        tree.advance_input_time(hold() / 2);
        tree.touch_up(f, at);
        tree.advance_input_time(hold() * 2);
        assert_eq!(opened.get(), 0);
    }

    #[test]
    fn a_contact_that_travels_past_the_tap_slop_opens_nothing() {
        let (mut tree, id, opened) = tree_with_menu();
        let at = tree.bounds(id).center();
        let slop = teksilo_tokens::GestureProfile::TOUCH.tap_slop;
        let f = tree.new_contact();
        tree.touch_down(f, at);
        tree.touch_move(f, Point::new(at.x, at.y + slop + 2.0));
        tree.advance_input_time(hold() * 2);
        assert_eq!(
            opened.get(),
            0,
            "that travel is a pan, not a considered hold"
        );
    }

    #[test]
    fn a_cancelled_contact_opens_nothing() {
        let (mut tree, id, opened) = tree_with_menu();
        let at = tree.bounds(id).center();
        let f = tree.new_contact();
        tree.touch_down(f, at);
        tree.touch_cancel(f, at);
        tree.advance_input_time(hold() * 2);
        assert_eq!(opened.get(), 0);
    }

    #[test]
    fn the_hold_deadline_is_folded_into_the_one_input_deadline() {
        let (mut tree, id, _opened) = tree_with_menu();
        let at = tree.bounds(id).center();
        assert!(tree.next_input_deadline().is_none());
        let f = tree.new_contact();
        tree.touch_down(f, at);
        assert!(
            tree.next_input_deadline().is_some(),
            "the loop must be asked back, or a resting finger never ripens",
        );
    }

    #[test]
    fn a_widgets_own_long_press_takes_precedence_over_the_route() {
        let opened = Rc::new(Cell::new(0usize));
        let counter = opened.clone();
        let fired = Rc::new(Cell::new(0usize));
        let own = fired.clone();
        let mut tree = WidgetTree::new();
        let inner = tree.add(FillWidget::new().on_long_press(move |_e, _c| own.set(own.get() + 1)));
        let _outer = tree.add(
            StackWidget::new()
                .child(inner)
                .context_menu(move |_pos, _ctx| {
                    counter.set(counter.get() + 1);
                    Some(menu())
                }),
        );
        tree.layout(SizeProposal::exact(200.0, 100.0));

        let at = tree.bounds(inner).center();
        let f = tree.new_contact();
        tree.touch_down(f, at);
        tree.advance_input_time(hold() + std::time::Duration::from_millis(10));
        assert_eq!(fired.get(), 1, "the widget's own handler runs");
        assert_eq!(
            opened.get(),
            0,
            "and the tree route stands down: the widget said what its hold means",
        );
    }

    #[test]
    fn a_drag_handle_role_takes_the_hold() {
        let opened = Rc::new(Cell::new(0usize));
        let counter = opened.clone();
        let mut tree = WidgetTree::new();
        let inner = tree.add(FillWidget::new());
        let _outer = tree.add(
            StackWidget::new()
                .child(inner)
                .long_press_role(LongPressRole::DragHandle)
                .context_menu(move |_pos, _ctx| {
                    counter.set(counter.get() + 1);
                    Some(menu())
                }),
        );
        tree.layout(SizeProposal::exact(200.0, 100.0));

        let at = tree.bounds(inner).center();
        let f = tree.new_contact();
        tree.touch_down(f, at);
        tree.advance_input_time(hold() + std::time::Duration::from_millis(10));
        assert_eq!(opened.get(), 0, "the hold is the grab, so no menu opens");
    }

    /// What `DragHandle` is *for*, and the half `a_drag_handle_role_takes_the_hold`
    /// cannot see: the role suppresses long-press **recognition**, so the node's
    /// own `on_long_press` does not fire either. That is the distinctive job —
    /// standing the tree route down is what `None` already does — and it is
    /// reached through `long_press_is_a_grab`'s role walk rather than through
    /// `resolve_touch_route`, which is why a test asserting only "no menu
    /// opened" holds with that walk deleted.
    #[test]
    fn a_drag_handle_role_suppresses_the_nodes_own_long_press() {
        let fired = Rc::new(Cell::new(0usize));
        let counter = fired.clone();
        let mut tree = WidgetTree::new();
        let inner = tree.add(FillWidget::new());
        let _outer = tree.add(
            StackWidget::new()
                .child(inner)
                .long_press_role(LongPressRole::DragHandle)
                .on_long_press(move |_e, _ctx| counter.set(counter.get() + 1)),
        );
        tree.layout(SizeProposal::exact(200.0, 100.0));

        let at = tree.bounds(inner).center();
        let f = tree.new_contact();
        tree.touch_down(f, at);
        tree.advance_input_time(hold() + std::time::Duration::from_millis(10));
        assert_eq!(
            fired.get(),
            0,
            "the hold arms the grab, so the node's own long press must not also fire"
        );
    }

    /// An unclassified pointer is not a finger. `!hovers()` admits both, which
    /// is why the gate reads `is_coarse()` instead: `InputTokens::profile` hands
    /// `Unknown` the *mouse* profile, so a hold armed for it would be timed
    /// against a `long_press` that was never meant to arm one. Deleting the
    /// gate, or widening it back to `!hovers()`, reddens this.
    #[test]
    fn an_unclassified_pointer_arms_no_hold_route() {
        let opened = Rc::new(Cell::new(0usize));
        let counter = opened.clone();
        let mut tree = WidgetTree::new();
        let inner = tree.add(FillWidget::new());
        let _outer = tree.add(
            StackWidget::new()
                .child(inner)
                .context_menu(move |_pos, _ctx| {
                    counter.set(counter.get() + 1);
                    Some(menu())
                }),
        );
        tree.layout(SizeProposal::exact(200.0, 100.0));

        let at = tree.bounds(inner).center();
        let p = tree.new_contact();
        let sample = tree.direct_sample(
            p,
            teksilo_tokens::PointerKind::Unknown,
            crate::pointer::PointerPhase::Down,
            at,
            true,
        );
        tree.dispatch_pointer(sample);
        tree.advance_input_time(hold() + std::time::Duration::from_millis(10));
        assert_eq!(
            opened.get(),
            0,
            "an unclassified pointer is tuned as a mouse, so its hold opens nothing"
        );
    }

    /// The discriminator between the two roles that share `resolve_touch_route`'s
    /// `None | DragHandle => return None` arm. `None` says "no tree route here";
    /// it does not say "no long press here", so a node that declares one still
    /// hears its own hold. Without this, the two variants are indistinguishable
    /// to the suite and either could be deleted for the other.
    #[test]
    fn a_none_role_leaves_the_nodes_own_long_press_alone() {
        let fired = Rc::new(Cell::new(0usize));
        let counter = fired.clone();
        let mut tree = WidgetTree::new();
        let inner = tree.add(FillWidget::new());
        let _outer = tree.add(
            StackWidget::new()
                .child(inner)
                .long_press_role(LongPressRole::None)
                .on_long_press(move |_e, _ctx| counter.set(counter.get() + 1)),
        );
        tree.layout(SizeProposal::exact(200.0, 100.0));

        let at = tree.bounds(inner).center();
        let f = tree.new_contact();
        tree.touch_down(f, at);
        tree.advance_input_time(hold() + std::time::Duration::from_millis(10));
        assert_eq!(
            fired.get(),
            1,
            "`None` stands the tree route down, not the widget's own handler"
        );
    }

    #[test]
    fn a_none_role_stands_the_route_down() {
        let opened = Rc::new(Cell::new(0usize));
        let counter = opened.clone();
        let mut tree = WidgetTree::new();
        let inner = tree.add(FillWidget::new().long_press_role(LongPressRole::None));
        let _outer = tree.add(
            StackWidget::new()
                .child(inner)
                .context_menu(move |_pos, _ctx| {
                    counter.set(counter.get() + 1);
                    Some(menu())
                }),
        );
        tree.layout(SizeProposal::exact(200.0, 100.0));

        let at = tree.bounds(inner).center();
        let f = tree.new_contact();
        tree.touch_down(f, at);
        tree.advance_input_time(hold() + std::time::Duration::from_millis(10));
        assert_eq!(opened.get(), 0);
    }

    #[test]
    fn a_tooltip_role_wins_over_a_reachable_menu() {
        let opened = Rc::new(Cell::new(0usize));
        let counter = opened.clone();
        let mut tree = WidgetTree::new();
        let anchor = tree.add(FillWidget::new().long_press_role(LongPressRole::Tooltip));
        let _outer = tree.add(
            StackWidget::new()
                .child(anchor)
                .context_menu(move |_pos, _ctx| {
                    counter.set(counter.get() + 1);
                    Some(menu())
                }),
        );
        let tip = tree.add(FillWidget::new().label("tip text"));
        tree.layout(SizeProposal::exact(200.0, 100.0));
        tree.attach_tooltip(anchor, tip, std::time::Duration::from_millis(500));

        let at = tree.bounds(anchor).center();
        let f = tree.new_contact();
        tree.touch_down(f, at);
        tree.advance_input_time(hold() + std::time::Duration::from_millis(10));
        assert_eq!(opened.get(), 0, "the role named the tooltip, not the menu");
        assert!(tree.find_by_label("tip text").is_some());
    }

    // ---------------------------------------------------------------
    // The tooltip route — including the one it exists for
    // ---------------------------------------------------------------

    #[test]
    fn a_hold_shows_the_tooltip_of_a_disabled_control() {
        let mut tree = WidgetTree::new();
        let anchor = tree.add(FillWidget::new());
        let tip = tree.add(FillWidget::new().label("why it is greyed out"));
        tree.layout(SizeProposal::exact(200.0, 100.0));
        tree.attach_tooltip(anchor, tip, std::time::Duration::from_millis(500));
        tree.enabled_when(anchor, false);

        let at = tree.bounds(anchor).center();
        let f = tree.new_contact();
        tree.touch_down(f, at);
        tree.advance_input_time(hold() + std::time::Duration::from_millis(10));
        assert!(
            tree.find_by_label("why it is greyed out").is_some(),
            "the disabled control's tip is hover-only with no other route; the hold is it",
        );
    }

    #[test]
    fn a_tooltip_a_hold_summoned_retires_on_its_own() {
        let mut tree = WidgetTree::new();
        let anchor = tree.add(FillWidget::new());
        let tip = tree.add(FillWidget::new().label("tip text"));
        tree.layout(SizeProposal::exact(200.0, 100.0));
        tree.attach_tooltip(anchor, tip, std::time::Duration::from_millis(500));

        let at = tree.bounds(anchor).center();
        let f = tree.new_contact();
        tree.touch_down(f, at);
        tree.advance_input_time(hold() + std::time::Duration::from_millis(10));
        tree.touch_up(f, at);
        assert_eq!(
            tree.active_overlays().len(),
            1,
            "the tip is up after the lift"
        );

        tree.advance_input_time(TOUCH_TOOLTIP_DISMISS / 2);
        assert_eq!(
            tree.active_overlays().len(),
            1,
            "and stays up long enough to read",
        );
        tree.advance_input_time(TOUCH_TOOLTIP_DISMISS);
        assert!(
            tree.active_overlays().is_empty(),
            "nothing else would ever retire it: no pointer left it and no focus moved",
        );
    }

    #[test]
    fn a_mouse_hold_shows_no_tooltip_before_its_dwell() {
        let mut tree = WidgetTree::new();
        let anchor = tree.add(FillWidget::new());
        let tip = tree.add(FillWidget::new().label("tip text"));
        tree.layout(SizeProposal::exact(200.0, 100.0));
        tree.attach_tooltip(anchor, tip, std::time::Duration::from_secs(5));

        let at = tree.bounds(anchor).center();
        tree.pointer_move(at);
        tree.pointer_down_button(at, crate::event::PointerButton::Primary);
        tree.advance_input_time(hold() * 4);
        assert!(
            tree.find_by_label("tip text").is_none(),
            "the mouse keeps its own dwell; a held button is not a summons",
        );
    }

    // ---------------------------------------------------------------
    // The hover-owner gate on the PointerLeave dismissal
    // ---------------------------------------------------------------

    /// A contact's move must not start a `DismissBehavior::PointerLeave` grace.
    ///
    /// No mouse test can see this: a mouse **is** the hover owner, so it takes
    /// the gated branch either way. Without the gate the frame pass closes a
    /// submenu a finger has just tapped open, with no further input at all.
    #[test]
    fn a_contacts_move_does_not_start_an_overlays_pointer_leave_grace() {
        let (mut tree, content, away) = leave_grace_fixture();

        // A finger lands **on** the overlay — so this is not an outside press,
        // which would dismiss it deliberately — and then travels off it.
        let inside = tree.bounds(content).center();
        let f = tree.new_contact();
        tree.touch_down(f, inside);
        tree.touch_move(f, away);
        tree.advance_input_time(std::time::Duration::from_millis(400));

        assert_eq!(
            tree.active_overlays().len(),
            1,
            "a contact cannot leave what it never hovered",
        );
    }

    /// The other half of the gate: it withholds the grace from a contact, and
    /// from nothing else. The identical journey under a mouse — which *is* the
    /// hover owner — must still close the overlay, or the gate has taken the
    /// mouse's dismissal away with it.
    #[test]
    fn a_mouses_move_off_the_same_overlay_still_starts_the_grace() {
        let (mut tree, content, away) = leave_grace_fixture();

        let inside = tree.bounds(content).center();
        tree.pointer_move(inside);
        tree.pointer_move(away);
        tree.advance_input_time(std::time::Duration::from_millis(400));

        assert_eq!(
            tree.active_overlays().len(),
            0,
            "the pointer that can leave still leaves",
        );
    }

    /// A widget that declares its own [`LongPressRole`] from `build`, through
    /// `apply_self_handlers` — the third of the three places a handler set is
    /// folded into a node, and the one a builder-method test never reaches.
    #[derive(Debug)]
    struct SelfDeclaring(LongPressRole);

    impl Widget for SelfDeclaring {
        fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
            ctx.apply_self_handlers(
                crate::widget_builder::HandlerSet::new().long_press_role(self.0),
            );
            vec![]
        }

        fn layout_response(
            &self,
            proposal: SizeProposal,
            _ctx: &crate::widget::LayoutContext,
        ) -> crate::widget::LayoutResponse {
            proposal.resolve(0.0, 0.0).into()
        }
    }

    /// The role reaches the node from `apply_self_handlers` too, not only from
    /// the builder method.
    ///
    /// The property is folded into a node at **three** sites — the two rebuild
    /// paths in `widget_tree.rs` and `WidgetArena::apply_handler_set` — and they
    /// are a hand-maintained list, so a test that only ever uses
    /// `.long_press_role(..)` on a builder leaves the third one free to be
    /// wrong. This is the case that walks through it.
    #[test]
    fn a_widget_can_declare_its_own_role_from_build() {
        let opened = Rc::new(Cell::new(0usize));
        let counter = opened.clone();
        let mut tree = WidgetTree::new();
        let inner = tree.add(SelfDeclaring(LongPressRole::None));
        let _outer = tree.add(
            StackWidget::new()
                .child(inner)
                .context_menu(move |_pos, _ctx| {
                    counter.set(counter.get() + 1);
                    Some(menu())
                }),
        );
        tree.layout(SizeProposal::exact(200.0, 100.0));

        let at = tree.bounds(inner).center();
        let f = tree.new_contact();
        tree.touch_down(f, at);
        tree.advance_input_time(hold() + std::time::Duration::from_millis(10));
        assert_eq!(
            opened.get(),
            0,
            "the role the widget declared for itself stood the route down",
        );
    }

    /// A tip a hold summoned does not carry a pointer-leave dismissal, so a
    /// mouse moving afterwards does not take it away.
    ///
    /// This is what choosing the dismissal by *route* buys. The finger that
    /// summoned it has lifted; the only pointer that can still move is one that
    /// had nothing to do with it, and on a convertible there usually is one. A
    /// `PointerLeave` grace would let it close a tip it never opened, well
    /// inside the five seconds the tip was given to be read.
    #[test]
    fn a_mouse_moving_afterwards_does_not_take_away_a_tip_a_hold_summoned() {
        let mut tree = WidgetTree::new();
        let anchor = tree.add(FillWidget::new());
        let tip = tree.add(FillWidget::new().label("tip text"));
        let _root = tree.add(InsetWidget::new(60.0).set_child(anchor));
        tree.layout(SizeProposal::exact(400.0, 300.0));
        tree.attach_tooltip(anchor, tip, std::time::Duration::from_millis(500));

        let at = tree.bounds(anchor).center();
        let f = tree.new_contact();
        tree.touch_down(f, at);
        tree.advance_input_time(hold() + std::time::Duration::from_millis(10));
        tree.touch_up(f, at);
        assert_eq!(
            tree.active_overlays().len(),
            1,
            "the tip is up after the lift"
        );

        // A mouse, elsewhere, doing nothing in particular.
        tree.pointer_move(Point::new(395.0, 5.0));
        tree.advance_input_time(std::time::Duration::from_millis(300));
        assert_eq!(
            tree.active_overlays().len(),
            1,
            "a pointer that did not open it does not close it",
        );
    }

    /// A leaf of a fixed size. `FillWidget` fills whatever it is proposed, so
    /// an overlay built on one covers the window and no point is ever outside
    /// it — which is the trap the fixture below asserts its way out of.
    #[derive(Debug)]
    struct SizedWidget(teksilo_canvas::Size);

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

    /// A `PointerLeave`-dismissed overlay, its anchor, and a point far enough
    /// from both to be a leave.
    ///
    /// **The mouse case is this fixture's proof of reach**, and that is why it
    /// exists as a test rather than as a comment. An earlier version anchored
    /// the overlay on a widget that filled the window; every point was inside
    /// the anchor, `update_pointer_leave_overlays` returned early whatever it
    /// was handed, and the touch case passed with the gate deleted. Asserting
    /// the geometry does not fix that — the branch reads the overlay stack's
    /// own rectangles, not the arena's. A mouse making the identical journey
    /// and *dismissing* does: it can only have got there through the call the
    /// gate guards, so if it dismisses and the contact does not, the gate is
    /// the only thing that separated them.
    fn leave_grace_fixture() -> (WidgetTree, WidgetId, Point) {
        const WINDOW: (f32, f32) = (400.0, 300.0);
        const AWAY: Point = Point { x: 390.0, y: 10.0 };

        let mut tree = WidgetTree::new();
        let trigger = tree.add(FillWidget::new());
        // Inset, so the anchor does not cover the whole window and `AWAY` can
        // be outside it.
        let _root = tree.add(InsetWidget::new(100.0).set_child(trigger));
        let content = tree.add(SizedWidget(teksilo_canvas::Size::new(80.0, 60.0)));
        tree.layout(SizeProposal::exact(WINDOW.0, WINDOW.1));
        tree.show_overlay(crate::overlay::OverlayRequest {
            content_id: content,
            anchor: trigger,
            placement: crate::overlay::OverlayPlacement::AtPointer(Point::new(300.0, 200.0)),
            dismiss: crate::overlay::DismissBehavior::PointerLeave {
                delay: std::time::Duration::from_millis(150),
            },
            layer: crate::overlay::OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });
        tree.layout(SizeProposal::exact(WINDOW.0, WINDOW.1));

        assert_eq!(tree.active_overlays().len(), 1);
        (tree, content, AWAY)
    }
}