Skip to main content

teksilo_core/widget_tree/
overlay_impl.rs

1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4use super::*;
5
6use crate::accessibility::AccessNodeBuilder;
7
8impl WidgetTree {
9    /// Attach a tooltip to a widget. The tooltip content widget must already
10    /// be in the tree (typically added as a dormant widget during build).
11    pub fn attach_tooltip(
12        &mut self,
13        anchor_id: WidgetId,
14        content_id: WidgetId,
15        delay: std::time::Duration,
16    ) {
17        self.attach_tooltip_inner(
18            anchor_id,
19            content_id,
20            delay,
21            None,
22            None,
23            crate::overlay::TooltipPlacement::Below,
24        );
25    }
26
27    /// Variant of [`attach_tooltip`](Self::attach_tooltip) that opens the
28    /// tooltip at the given [`TooltipPlacement`](crate::overlay::TooltipPlacement)
29    /// — `Side` for anchors stacked vertically (menu items, a vertical tab
30    /// strip, list/tree rows) where `Below` would cover the next sibling.
31    pub fn attach_tooltip_with_placement(
32        &mut self,
33        anchor_id: WidgetId,
34        content_id: WidgetId,
35        delay: std::time::Duration,
36        placement: crate::overlay::TooltipPlacement,
37    ) {
38        self.attach_tooltip_inner(anchor_id, content_id, delay, None, None, placement);
39    }
40
41    /// Attach a tooltip that auto-promotes to "sticky" after
42    /// `sticky_after` elapses post-show. Used by rich tooltips
43    /// implementing the sticky-on-dwell UX (typically 2 seconds).
44    ///
45    /// The tooltip is shown normally after `delay`, then each
46    /// subsequent layout pass checks whether `sticky_after` has
47    /// elapsed since the overlay was shown. When it has, the tree
48    /// calls [`promote_tooltip_to_sticky`](Self::promote_tooltip_to_sticky)
49    /// — the entry is flagged sticky (so pointer-leave no longer
50    /// auto-dismisses) and the overlay's dismiss behavior is
51    /// swapped to `EscapeOrClickOutside`.
52    pub fn attach_tooltip_with_sticky(
53        &mut self,
54        anchor_id: WidgetId,
55        content_id: WidgetId,
56        delay: std::time::Duration,
57        sticky_after: Option<std::time::Duration>,
58    ) {
59        self.attach_tooltip_inner(
60            anchor_id,
61            content_id,
62            delay,
63            sticky_after,
64            None,
65            crate::overlay::TooltipPlacement::Below,
66        );
67    }
68
69    /// Variant of [`attach_tooltip_with_sticky`](Self::attach_tooltip_with_sticky)
70    /// that also takes a shared `Rc<Cell<Option<Instant>>>` "sink"
71    /// the tree updates whenever the tooltip is shown or dismissed.
72    /// The rich tooltip widget reads from this sink to drive its
73    /// dwell indicator without needing a paint-gap heuristic.
74    pub fn attach_tooltip_with_sticky_sink(
75        &mut self,
76        anchor_id: WidgetId,
77        content_id: WidgetId,
78        delay: std::time::Duration,
79        sticky_after: Option<std::time::Duration>,
80        shown_at_sink: std::rc::Rc<std::cell::Cell<Option<std::time::Instant>>>,
81    ) {
82        self.attach_tooltip_inner(
83            anchor_id,
84            content_id,
85            delay,
86            sticky_after,
87            Some(shown_at_sink),
88            crate::overlay::TooltipPlacement::Below,
89        );
90    }
91
92    /// Variant of [`attach_tooltip_with_sticky_sink`](Self::attach_tooltip_with_sticky_sink)
93    /// that also carries a [`TooltipPlacement`](crate::overlay::TooltipPlacement)
94    /// — the full-featured path used by `MenuItem` / `TabHeader` /
95    /// `StandardItem` rich + composite tooltips that want `Side` placement.
96    pub fn attach_tooltip_with_sticky_sink_placement(
97        &mut self,
98        anchor_id: WidgetId,
99        content_id: WidgetId,
100        delay: std::time::Duration,
101        sticky_after: Option<std::time::Duration>,
102        shown_at_sink: std::rc::Rc<std::cell::Cell<Option<std::time::Instant>>>,
103        placement: crate::overlay::TooltipPlacement,
104    ) {
105        self.attach_tooltip_inner(
106            anchor_id,
107            content_id,
108            delay,
109            sticky_after,
110            Some(shown_at_sink),
111            placement,
112        );
113    }
114
115    /// Drop every tooltip previously attached to `anchor_id` whose content is
116    /// not `keep_content_id`: dismiss a live overlay, destroy the orphaned
117    /// content subtree, and remove the entry.
118    ///
119    /// **An anchor owns at most one tooltip.** `attach_tooltip*` is called from
120    /// `build()`, which re-runs on every rebuild with a freshly-`ctx.add`ed
121    /// content widget — and `ctx.add` creates a *parentless* node, so the
122    /// rebuild teardown (which walks `old_children`) never reaches it. Without
123    /// this retirement the entry table would gain one dead row plus one
124    /// orphaned arena node per rebuild, forever. That table is not cold
125    /// storage: it is scanned on every pointer move, four times per layout
126    /// pass, on every event-loop wake (`next_timer_deadline`) and — worst —
127    /// once *per widget* during the accessibility walk, so the leak is O(n)
128    /// on the hottest paths in the tree.
129    fn retire_tooltips_for_anchor(&mut self, anchor_id: WidgetId, keep_content_id: WidgetId) {
130        let stale: Vec<(WidgetId, Option<crate::overlay::OverlayId>)> = self
131            .tooltips
132            .iter()
133            .filter(|entry| entry.anchor_id == anchor_id && entry.content_id != keep_content_id)
134            .map(|entry| (entry.content_id, entry.overlay_id))
135            .collect();
136        if stale.is_empty() {
137            return;
138        }
139        self.tooltips
140            .retain(|entry| entry.anchor_id != anchor_id || entry.content_id == keep_content_id);
141        for (content_id, overlay_id) in stale {
142            // Retire the overlay before the widget: `dismiss_overlay` walks the
143            // content subtree for focus/hover restoration, which needs the
144            // nodes to still exist.
145            if let Some(overlay_id) = overlay_id {
146                self.dismiss_overlay(overlay_id);
147            }
148            self.destroy_subtree(content_id);
149        }
150    }
151
152    /// Reap the tooltip owned by a widget that is being destroyed.
153    ///
154    /// The anchor's own teardown never reaches the tooltip content — it is a
155    /// parentless node (see [`Self::retire_tooltips_for_anchor`]) — so a destroyed
156    /// widget would otherwise leave its entry and content node behind for the
157    /// lifetime of the tree. Called from `destroy_subtree_inner`.
158    pub(super) fn retire_tooltips_of_destroyed_anchor(&mut self, anchor_id: WidgetId) {
159        let stale: Vec<(WidgetId, Option<crate::overlay::OverlayId>)> = self
160            .tooltips
161            .iter()
162            .filter(|entry| entry.anchor_id == anchor_id)
163            .map(|entry| (entry.content_id, entry.overlay_id))
164            .collect();
165        if stale.is_empty() {
166            return;
167        }
168        self.tooltips.retain(|entry| entry.anchor_id != anchor_id);
169        for (content_id, overlay_id) in stale {
170            if let Some(overlay_id) = overlay_id {
171                self.dismiss_overlay(overlay_id);
172            }
173            self.destroy_subtree(content_id);
174        }
175    }
176
177    fn attach_tooltip_inner(
178        &mut self,
179        anchor_id: WidgetId,
180        content_id: WidgetId,
181        delay: std::time::Duration,
182        sticky_after: Option<std::time::Duration>,
183        shown_at_sink: Option<std::rc::Rc<std::cell::Cell<Option<std::time::Instant>>>>,
184        placement: crate::overlay::TooltipPlacement,
185    ) {
186        self.retire_tooltips_for_anchor(anchor_id, content_id);
187        // A re-attach with the *same* content id (a widget whose build reuses
188        // its tooltip node) updates in place rather than stacking a duplicate.
189        if let Some(entry) = self
190            .tooltips
191            .iter_mut()
192            .find(|entry| entry.anchor_id == anchor_id && entry.content_id == content_id)
193        {
194            entry.delay = delay;
195            entry.sticky_after = sticky_after;
196            entry.placement = placement;
197            if shown_at_sink.is_some() {
198                entry.shown_at_sink = shown_at_sink;
199            }
200            return;
201        }
202        self.arena.set_dormant(content_id);
203        self.tooltips.push(TooltipEntry {
204            anchor_id,
205            content_id,
206            // The historic placement, and the right one for a widget that
207            // anchors its tooltip on itself. `BuildContext` overwrites it
208            // immediately after for everything else.
209            description_owner_id: anchor_id,
210            delay,
211            hover_start: None,
212            real_hover_start: None,
213            hover_origin: None,
214            overlay_id: None,
215            sticky_after,
216            is_sticky: false,
217            shown_at_sim: None,
218            shown_at_real: None,
219            shown_at_sink,
220            promoted_by_focus: false,
221            dwell_promotes: false,
222            armed_by_focus: false,
223            armed_by_hold: false,
224            suppressed_until_focus_leaves: false,
225            placement,
226        });
227    }
228
229    /// Record which widget's accessibility node should carry a tooltip's
230    /// description, when that is not the node the overlay hangs off.
231    ///
232    /// Called by every `BuildContext::attach_tooltip*` wrapper with the widget
233    /// that was building, so a composing control gets the right node without a
234    /// line in `button.rs`, `toggle.rs` or the two dozen others like them.
235    ///
236    /// **A claim, not an instruction.** One `build()` can attach many tooltips
237    /// -- a list body pane attaches one per visible row -- and `self_id()` is
238    /// the same for all of them, so an owner naming itself here may be naming
239    /// itself for a dozen rows at once. Which of those claims is honoured is
240    /// settled where the whole set can be seen at once, in the accessibility
241    /// walk; nothing is resolved at attach time, because at attach time the
242    /// second row has not been attached yet.
243    ///
244    /// Only the accessibility walk reads this. Overlay placement, hover
245    /// hit-testing, dwell, focus promotion and retirement all go on reading
246    /// `anchor_id`, which is still where the tooltip actually opens.
247    pub(crate) fn set_tooltip_description_owner(
248        &mut self,
249        anchor_id: WidgetId,
250        owner_id: WidgetId,
251    ) {
252        if let Some(entry) = self
253            .tooltips
254            .iter_mut()
255            .find(|entry| entry.anchor_id == anchor_id)
256        {
257            entry.description_owner_id = owner_id;
258        }
259    }
260
261    /// Resolve a [`TooltipPlacement`](crate::overlay::TooltipPlacement) to
262    /// the concrete [`OverlayPlacement`](crate::overlay::OverlayPlacement) used to position the tooltip
263    /// overlay. `Below` keeps the historic tooltip offset; `Side` reuses
264    /// the submenu-style `TrailingEdge` (RTL-aware, leading fallback,
265    /// viewport-clamped) so the tooltip opens beside — not over — the next
266    /// vertically-stacked sibling.
267    fn tooltip_overlay_placement(
268        placement: crate::overlay::TooltipPlacement,
269    ) -> crate::overlay::OverlayPlacement {
270        match placement {
271            crate::overlay::TooltipPlacement::Below => {
272                crate::overlay::OverlayPlacement::NearAnchor {
273                    offset: teksilo_canvas::Vec2::new(0.0, 8.0),
274                }
275            }
276            crate::overlay::TooltipPlacement::Side => {
277                crate::overlay::OverlayPlacement::TrailingEdge
278            }
279        }
280    }
281
282    pub(super) fn process_tooltips(&mut self) {
283        let sim_now = self.sim_clock;
284        let session_active = self.tooltip_session_active_sim(sim_now);
285        self.process_tooltips_impl(
286            |entry| {
287                entry
288                    .hover_start
289                    .map(|start| sim_now.saturating_duration_since(start))
290            },
291            session_active,
292            true,
293        );
294    }
295
296    pub(super) fn process_tooltips_real(&mut self) {
297        let real_now = std::time::Instant::now();
298        let session_active = self.tooltip_session_active_real(real_now);
299        self.process_tooltips_impl(
300            |entry| {
301                entry
302                    .real_hover_start
303                    .map(|start| real_now.saturating_duration_since(start))
304            },
305            session_active,
306            false,
307        );
308    }
309
310    /// Whether any tooltip is visible *and still part of an active hover
311    /// session*.
312    ///
313    /// A pointer-dwelled **sticky** tooltip is deliberately excluded. It
314    /// survives pointer-leave and stays up until Escape or a click outside, so
315    /// counting it would keep the reshow session warm for as long as it is
316    /// pinned — every other anchor in the window would then fire on the 100 ms
317    /// path indefinitely, which is not a "session", it is a stuck state.
318    fn any_tooltip_in_session(&self) -> bool {
319        self.tooltips
320            .iter()
321            .any(|e| e.overlay_id.is_some() && !e.is_sticky)
322    }
323
324    /// Whether the shortened reshow delay applies right now (sim clock).
325    fn tooltip_session_active_sim(&self, now: std::time::Instant) -> bool {
326        self.any_tooltip_in_session()
327            || self
328                .tooltip_session_until_sim
329                .is_some_and(|until| now < until)
330    }
331
332    /// Whether the shortened reshow delay applies right now (real clock).
333    fn tooltip_session_active_real(&self, now: std::time::Instant) -> bool {
334        self.any_tooltip_in_session()
335            || self
336                .tooltip_session_until_real
337                .is_some_and(|until| now < until)
338    }
339
340    /// Resolve the delay for a pending tooltip: full initial delay, or the
341    /// shortened reshow delay while a tooltip session is active.
342    ///
343    /// The shortening is **proportional**, not a flat floor. Windows derives
344    /// `TTDT_RESHOW` as `TTDT_INITIAL / 5` rather than pinning an absolute
345    /// number, and that ratio is what the two theme tokens encode (100 ms of
346    /// 500 ms). Clamping every entry to the absolute `tooltip_reshow_delay`
347    /// instead collapsed `tooltip_delay_heavy` to the light tier's 100 ms
348    /// whenever a session happened to be warm — so a composite surface or a
349    /// scene-item tip, which exists precisely because heavier content needs a
350    /// longer statement of intent, popped after an incidental 100 ms brush.
351    /// Scaling keeps the light tier at exactly 100 ms while a 700 ms heavy
352    /// entry reshows at 140 ms.
353    fn effective_tooltip_delay(
354        &self,
355        entry_delay: std::time::Duration,
356        session_active: bool,
357    ) -> std::time::Duration {
358        if !session_active {
359            return entry_delay;
360        }
361        let motion = &self.theme.motion;
362        let base = motion.tooltip_delay.as_secs_f64();
363        if base <= 0.0 {
364            // Degenerate theme (no initial delay to take a ratio of) — fall
365            // back to the absolute token.
366            return entry_delay.min(motion.tooltip_reshow_delay);
367        }
368        let ratio = motion.tooltip_reshow_delay.as_secs_f64() / base;
369        // Never *lengthen* a delay on the warm path, whatever the theme says.
370        entry_delay.mul_f64(ratio).min(entry_delay)
371    }
372
373    fn process_tooltips_impl(
374        &mut self,
375        elapsed_fn: impl Fn(&TooltipEntry) -> Option<std::time::Duration>,
376        session_active: bool,
377        use_sim_clock: bool,
378    ) {
379        // Reconcile externally-dismissed overlays (audit G12): a shown tooltip's
380        // overlay may have been removed by the overlay stack's PointerLeave
381        // machinery (pointer left BOTH anchor and tooltip for 100ms). Clear the
382        // now-stale overlay_id + shown state so the tooltip can re-show on the
383        // next dwell, and reset its "shown at" sink.
384        let dismissed_indices: Vec<usize> = self
385            .tooltips
386            .iter()
387            .enumerate()
388            .filter_map(|(i, e)| match e.overlay_id {
389                Some(oid) if !self.overlay_manager.stack.iter().any(|o| o.id == oid) => Some(i),
390                _ => None,
391            })
392            .collect();
393        let any_dismissed = !dismissed_indices.is_empty();
394        for i in dismissed_indices {
395            let e = &mut self.tooltips[i];
396            e.overlay_id = None;
397            e.is_sticky = false;
398            e.promoted_by_focus = false;
399            e.armed_by_hold = false;
400            e.shown_at_sim = None;
401            e.shown_at_real = None;
402            e.hover_origin = None;
403            if let Some(sink) = e.shown_at_sink.as_ref() {
404                sink.set(None);
405            }
406        }
407        // Keep the reshow session warm for a short grace after dismiss so
408        // moving to the next toolbar icon does not pay the full initial delay.
409        if any_dismissed {
410            let grace = super::TOOLTIP_SESSION_GRACE;
411            if use_sim_clock {
412                self.tooltip_session_until_sim = Some(self.sim_clock + grace);
413            } else {
414                self.tooltip_session_until_real = Some(std::time::Instant::now() + grace);
415            }
416        }
417
418        // Re-evaluate session after dismiss bookkeeping: a still-visible
419        // sibling tip, or the grace we just opened, both count. Uses the same
420        // sticky-excluding predicate as the two `tooltip_session_active_*`
421        // helpers — a pinned tip is not an active session.
422        let session_active = session_active
423            || self.any_tooltip_in_session()
424            || if use_sim_clock {
425                self.tooltip_session_active_sim(self.sim_clock)
426            } else {
427                self.tooltip_session_active_real(std::time::Instant::now())
428            };
429
430        let mut to_show = Vec::new();
431        // Collect show candidates first so we don't hold a mutable borrow
432        // across `arena.is_active` (which needs `&self`).
433        let pending: Vec<usize> = self
434            .tooltips
435            .iter()
436            .enumerate()
437            .filter(|(_, entry)| entry.overlay_id.is_none())
438            .filter(|(_, entry)| self.arena.is_active(entry.anchor_id))
439            .filter_map(|(i, entry)| {
440                let delay = self.effective_tooltip_delay(entry.delay, session_active);
441                let elapsed = elapsed_fn(entry)?;
442                (elapsed >= delay).then_some(i)
443            })
444            .collect();
445        for index in pending {
446            // Tooltip bodies are built lazily (`add_detached_deferred_on_demand`),
447            // so materialize this one before anything asks it a question — the
448            // `tooltip_has_content` check below reads the content widget, and an
449            // unbuilt host would answer for a body that does not exist yet.
450            let content_id = self.tooltips[index].content_id;
451            self.materialize_deferred(content_id);
452            // A tooltip with nothing to say must not open. An unresolved or
453            // blank i18n key would otherwise pop an empty chromed bubble,
454            // which reads as a rendering fault rather than as "no tip here".
455            // The content widget decides — see `Widget::tooltip_has_content`,
456            // which defaults to `true` so arbitrary bodies are never
457            // suppressed by a check they did not opt into.
458            // …and ask the *body*, not the host: once materialized the deferred
459            // host has handed its widget value to a real child, so probing the
460            // host would consult the default `true` and let an empty bubble
461            // through on exactly the second hover.
462            let body_id = self.tooltip_content_node(content_id);
463            if !self
464                .arena
465                .get(body_id)
466                .is_none_or(|node| node.widget.tooltip_has_content())
467            {
468                let entry = &mut self.tooltips[index];
469                entry.hover_start = None;
470                entry.real_hover_start = None;
471                entry.hover_origin = None;
472                continue;
473            }
474            let entry = &mut self.tooltips[index];
475            to_show.push((
476                entry.anchor_id,
477                entry.content_id,
478                entry.placement,
479                entry.armed_by_focus,
480                entry.armed_by_hold,
481            ));
482            entry.hover_start = None;
483            entry.real_hover_start = None;
484            entry.hover_origin = None;
485        }
486        let sim_now = self.sim_clock;
487        let real_now = std::time::Instant::now();
488        // Tooltips fade in over `duration_fast` (~120 ms) — matches the
489        // MotionTokens recommendation for "tooltip fade, popup fade".
490        // Reduced-motion users get an instant snap, and so does the warm
491        // reshow path: on a toolbar sweep the whole point of the ~100 ms
492        // reshow is that the next tip is *already there*, and a 120 ms fade
493        // on top of it costs more than the delay it just saved.
494        let fade_duration = if self.prefers_reduced_motion || session_active {
495            None
496        } else {
497            Some(self.theme.motion.duration_fast)
498        };
499        for (anchor_id, content_id, placement, by_focus, by_hold) in to_show {
500            self.arena.activate(content_id);
501            // A tip the keyboard summoned has no pointer to leave, so the
502            // pointer-leave grace would never fire and it would hang on screen.
503            // It ends the way a keyboard user ends things: Escape, a click
504            // outside, or focus moving off the anchor. A tip a **hold**
505            // summoned is in the same position — the finger has lifted by the
506            // time it appears — with one difference: nothing moves focus off it
507            // either, so it also carries its own expiry (see
508            // `super::touch_route::TOUCH_TOOLTIP_DISMISS`).
509            let dismiss = if by_focus || by_hold {
510                crate::overlay::DismissBehavior::EscapeOrClickOutside
511            } else {
512                crate::overlay::DismissBehavior::PointerLeave {
513                    delay: std::time::Duration::from_millis(100),
514                }
515            };
516            let mut request = crate::overlay::OverlayRequest::new(
517                content_id,
518                anchor_id,
519                Self::tooltip_overlay_placement(placement),
520                dismiss,
521            );
522            request.fade_duration = fade_duration;
523            let oid = if by_hold {
524                self.show_overlay_for(request, super::touch_route::TOUCH_TOOLTIP_DISMISS)
525            } else {
526                self.show_overlay(request)
527            };
528            if by_focus && let Some(focused) = self.focused {
529                self.record_top_focus_restore(focused);
530            }
531            if let Some(entry) = self
532                .tooltips
533                .iter_mut()
534                .find(|e| e.content_id == content_id)
535            {
536                entry.overlay_id = Some(oid);
537                entry.shown_at_sim = Some(sim_now);
538                entry.shown_at_real = Some(real_now);
539                entry.promoted_by_focus = by_focus;
540                // A focus rest shows the tip but never pins it, so its dwell
541                // indicator has no countdown to show.
542                entry.dwell_promotes = !by_focus;
543                if let Some(sink) = entry.shown_at_sink.as_ref() {
544                    sink.set((!by_focus).then_some(real_now));
545                }
546            }
547        }
548
549        // Sticky-on-dwell sweep:
550        //   1. Mark every shown rich tooltip's **subtree** needs_paint
551        //      so its `paint()` re-runs each layout pass during the
552        //      dwell window AND its children (notably the
553        //      `DwellIndicator`) repaint with the freshly-set step.
554        //      Marking only the root would leave the indicator's
555        //      cached_paint in place and the visible wedge stale.
556        //   2. Auto-promote any tooltip whose dwell window has
557        //      elapsed: flag the entry sticky and swap the overlay's
558        //      dismiss behavior to `EscapeOrClickOutside`. Marking
559        //      runs even on the promoting frame so `tick_dwell` can
560        //      observe `elapsed >= sticky_after` and flip the
561        //      indicator to its pin variant.
562        let mut to_mark_paint: Vec<WidgetId> = Vec::new();
563        let mut to_promote: Vec<WidgetId> = Vec::new();
564        for entry in &self.tooltips {
565            let Some(sticky_after) = entry.sticky_after else {
566                continue;
567            };
568            if entry.overlay_id.is_none() || entry.is_sticky || !entry.dwell_promotes {
569                continue;
570            }
571            let elapsed = entry
572                .shown_at_real
573                .map(|t| real_now.saturating_duration_since(t));
574            let elapsed = match elapsed {
575                Some(e) => e,
576                None => continue,
577            };
578            // Always mark needs_paint on the dwell window — the
579            // promoting frame still needs the widget to repaint so
580            // tick_dwell can flip the indicator to its pin variant.
581            to_mark_paint.push(entry.content_id);
582            if elapsed >= sticky_after {
583                to_promote.push(entry.content_id);
584            }
585        }
586        for id in to_mark_paint {
587            self.arena.mark_subtree_needs_paint(id);
588        }
589        for content_id in to_promote {
590            self.promote_tooltip_to_sticky(content_id);
591        }
592    }
593
594    pub(super) fn process_delayed_overlays(&mut self) {
595        let sim_now = self.sim_clock;
596        let mut noop = crate::window::NoopWindowOps;
597        self.process_delayed_overlays_impl(
598            |p| sim_now.saturating_duration_since(p.sim_requested_at),
599            &mut noop,
600        );
601    }
602
603    pub(super) fn process_delayed_overlays_real(&mut self, ops: &mut dyn crate::window::WindowOps) {
604        let real_now = std::time::Instant::now();
605        self.process_delayed_overlays_impl(
606            |p| real_now.saturating_duration_since(p.real_requested_at),
607            &mut *ops,
608        );
609    }
610
611    fn process_delayed_overlays_impl(
612        &mut self,
613        elapsed_fn: impl Fn(&PendingDelayedOverlay) -> std::time::Duration,
614        ops: &mut dyn crate::window::WindowOps,
615    ) {
616        let mut ready_indices = Vec::new();
617        for (index, pending) in self.pending_delayed_overlays.iter().enumerate() {
618            if elapsed_fn(pending) >= pending.delay {
619                ready_indices.push(index);
620            }
621        }
622
623        let mut ready = Vec::new();
624        for &index in ready_indices.iter().rev() {
625            ready.push(self.pending_delayed_overlays.remove(index));
626        }
627        ready.reverse();
628
629        let any_shown = !ready.is_empty();
630        for pending in ready {
631            let content_id = pending.request.content_id;
632            // Deferred hover-switch: the sibling submenu that was open
633            // while this one was merely pending goes now, not when the
634            // pointer first touched the trigger. `preserve` finds
635            // nothing yet (this overlay is not on the stack), which is
636            // exactly right — everything below the anchor's own overlay
637            // goes, and this one is pushed immediately after.
638            if pending.replace_siblings {
639                let anchor = pending.request.anchor;
640                self.dismiss_child_overlays_for_source(anchor, Some(content_id), &mut *ops);
641            }
642            self.arena.activate(content_id);
643            let current_focus = self.focused;
644            self.overlay_manager.show(pending.request);
645            if let Some(focus_id) = current_focus {
646                self.record_top_focus_restore(focus_id);
647            }
648            self.arena.mark_needs_paint(content_id);
649            // The target is named outright, like `WidgetTree::focus`, so it
650            // follows the same rule: a composite that cannot take focus hands
651            // it to its first Tab stop.
652            if let Some(focus_target) = pending.focus_target
653                && self.arena.is_active(focus_target)
654            {
655                let target = self.exact_focus_target(focus_target);
656                self.focus_ops(target, &mut *ops);
657            }
658        }
659        if any_shown {
660            self.a11y_dirty = true;
661        }
662    }
663
664    pub(super) fn overlay_ancestor_for_widget(
665        &self,
666        widget_id: WidgetId,
667    ) -> Option<crate::overlay::OverlayId> {
668        self.overlay_manager
669            .stack
670            .iter()
671            .rev()
672            .find(|overlay| self.is_descendant_of(widget_id, overlay.content_id))
673            .map(|overlay| overlay.id)
674    }
675
676    pub(super) fn modal_overlay_for_widget(
677        &self,
678        widget_id: WidgetId,
679    ) -> Option<crate::overlay::OverlayId> {
680        let mut current = self.overlay_ancestor_for_widget(widget_id);
681
682        while let Some(overlay_id) = current {
683            let overlay = self.overlay_manager.overlay(overlay_id)?;
684            if overlay.placement.is_modal() {
685                return Some(overlay_id);
686            }
687            current = overlay.parent_overlay;
688        }
689
690        None
691    }
692
693    /// Whether a modal is up and `widget_id` is behind it.
694    ///
695    /// A modal leaves reachable its own content, the content of every overlay
696    /// above it (a drop-down or a menu opened from inside it) and of any
697    /// overlay in a lower band that is anchored in those (the selection
698    /// handles of a field inside it). Everything else, the page and whatever
699    /// it had open, is behind its scrim: the pointer cannot reach it and the
700    /// Tab cycle does not go there. A modal is a `Centered` overlay, the
701    /// discriminator the Tab trap and the pointer's hit test already use, and
702    /// it stays modal while it fades out, as focus stays in it until it has
703    /// gone.
704    ///
705    /// An assistive technology's request is the one input nothing else stops.
706    /// AccessKit's only word for a modal is `Node::set_modal`, a state every
707    /// adapter reports and none acts on (`accesskit_atspi_common`
708    /// `node.rs:342-344`, `accesskit_windows` `node.rs:735-741`,
709    /// `accesskit_macos` `node.rs:1194-1197`): each goes on routing a request
710    /// to any node in the tree, and the page stays in it. Leaving the page out
711    /// of the walk, as a browser leaves out what a modal dialog makes inert,
712    /// is not an option while a node id outlives its removal: AT-SPI declares
713    /// a removed node defunct, libatspi keeps that for its path, and
714    /// `tools/reader/` measured Orca 46.1 dropping the focus event of the
715    /// opener the page came back with ("Ignoring defunct object").
716    ///
717    /// A menu bar's window-level keys are the other: F10 and Alt+letter reach
718    /// the bar wherever focus is, so `teksilo-app` asks this before acting on
719    /// one.
720    pub fn is_behind_modal(&self, widget_id: WidgetId) -> bool {
721        let Some(modal) = self.overlay_manager.topmost_modal() else {
722            return false;
723        };
724        let stack = &self.overlay_manager.stack;
725        let Some(at) = stack.iter().position(|overlay| overlay.id == modal.id) else {
726            return false;
727        };
728        let (below, above) = stack.split_at(at);
729        let in_modal = |id: WidgetId| {
730            above
731                .iter()
732                .any(|overlay| self.is_descendant_of(id, overlay.content_id))
733        };
734        !(in_modal(widget_id)
735            || below.iter().any(|overlay| {
736                self.is_descendant_of(widget_id, overlay.content_id) && in_modal(overlay.anchor)
737            }))
738    }
739
740    fn menu_ancestor_for_widget(&self, widget_id: WidgetId) -> Option<WidgetId> {
741        let mut current = Some(widget_id);
742        while let Some(id) = current {
743            if let Some(node) = self.arena.get(id) {
744                let mut builder = AccessNodeBuilder::new();
745                node.widget.accessibility(&mut builder);
746                if builder.role() == accesskit::Role::Menu {
747                    return Some(id);
748                }
749            }
750            current = self.arena.parent(id);
751        }
752        None
753    }
754
755    pub(super) fn dismiss_child_overlays_for_source(
756        &mut self,
757        source_widget: WidgetId,
758        preserve_content: Option<WidgetId>,
759        ops: &mut dyn crate::window::WindowOps,
760    ) {
761        if let Some(parent_overlay) = self.overlay_ancestor_for_widget(source_widget) {
762            let preserve_overlay = preserve_content
763                .and_then(|content_id| self.overlay_manager.find_by_content(content_id));
764            let mark = self.dismissal_mark();
765            let (dismissed, focus_restore) = self
766                .overlay_manager
767                .dismiss_descendants_of(parent_overlay, preserve_overlay);
768            self.dormant_dismissed_content(&dismissed, &mut *ops);
769            self.return_focus_after_dismissal(focus_restore, mark, &mut *ops);
770            return;
771        }
772
773        let Some(menu_root) = self.menu_ancestor_for_widget(source_widget) else {
774            return;
775        };
776        let preserve_overlay = preserve_content
777            .and_then(|content_id| self.overlay_manager.find_by_content(content_id));
778        let overlay_ids: Vec<crate::overlay::OverlayId> = self
779            .overlay_manager
780            .stack
781            .iter()
782            .filter(|overlay| {
783                overlay.parent_overlay.is_none()
784                    && self.is_descendant_of(overlay.anchor, menu_root)
785                    && !preserve_overlay.is_some_and(|keep| {
786                        overlay.id == keep
787                            || self.overlay_manager.is_descendant_of(overlay.id, keep)
788                    })
789            })
790            .map(|overlay| overlay.id)
791            .collect();
792
793        for overlay_id in overlay_ids {
794            let mark = self.dismissal_mark();
795            let (dismissed, focus_restore) =
796                self.overlay_manager.dismiss_with_focus_restore(overlay_id);
797            self.dormant_dismissed_content(&dismissed, &mut *ops);
798            self.return_focus_after_dismissal(focus_restore, mark, &mut *ops);
799        }
800    }
801
802    /// Dismiss the menu chain anchored to `source_widget`. Walks from
803    /// the source's containing overlay up the `parent_overlay` chain,
804    /// collecting every overlay whose content role is *not* a "stop"
805    /// role (`Tooltip`, `Dialog`, `AlertDialog`). Dismisses the
806    /// topmost collected overlay — `OverlayManager::dismiss` cascades
807    /// to descendants, so the entire menu/popover cascade closes in
808    /// one go while a hosting tooltip / dialog is preserved.
809    ///
810    /// Replacement for `dismiss_all_overlays` in menu / dropdown item
811    /// activation handlers, where the popover may be hosted inside a
812    /// composite tooltip and "all overlays" is too broad.
813    pub(super) fn dismiss_self_overlay_chain_for_source(
814        &mut self,
815        source_widget: WidgetId,
816        ops: &mut dyn crate::window::WindowOps,
817    ) {
818        let Some(start) = self.overlay_ancestor_for_widget(source_widget) else {
819            return;
820        };
821
822        let mut topmost_to_dismiss: Option<crate::overlay::OverlayId> = None;
823        let mut current = Some(start);
824        while let Some(overlay_id) = current {
825            let Some(overlay) = self.overlay_manager.overlay(overlay_id) else {
826                break;
827            };
828            if self.overlay_is_host_surface(overlay_id) {
829                break;
830            }
831            topmost_to_dismiss = Some(overlay_id);
832            current = overlay.parent_overlay;
833        }
834
835        if let Some(target) = topmost_to_dismiss {
836            let mark = self.dismissal_mark();
837            let (dismissed, focus_restore) =
838                self.overlay_manager.dismiss_with_focus_restore(target);
839            self.dormant_dismissed_content(&dismissed, &mut *ops);
840            self.return_focus_after_dismissal(focus_restore, mark, &mut *ops);
841        }
842    }
843
844    /// Whether an overlay is **positioned relative to its anchor** — a panel
845    /// that belongs to a control, rather than to the window.
846    ///
847    /// This is the line between a disclosure and a notification. `Below`,
848    /// `Above`, `TrailingEdge`, `AtPointer`, `NearAnchor` and `BelowPreferred`
849    /// all place content *at* the widget that opened it: the anchor is a real
850    /// relationship, and "focus left that control" is a meaningful thing to say
851    /// about them. The viewport-placed variants are not that — `ViewportCorner`
852    /// and `FullViewport` say outright that anchor bounds are ignored,
853    /// `BottomCenter` is where a snackbar lives, and `Centered` is the modal.
854    /// Their `anchor` field is bookkeeping (whatever widget happened to ask),
855    /// not a disclosure they hang off.
856    ///
857    /// Written as an exhaustive `match` on purpose: a placement variant added
858    /// later must not quietly inherit whichever answer happened to be the
859    /// default, so the compiler makes it a decision.
860    fn overlay_is_anchor_positioned(placement: &crate::overlay::OverlayPlacement) -> bool {
861        use crate::overlay::OverlayPlacement as P;
862        match placement {
863            P::Below
864            | P::Above
865            | P::TrailingEdge
866            | P::AtPointer(_)
867            | P::AtPointerAvoiding { .. }
868            | P::NearAnchor { .. }
869            | P::BelowPreferred => true,
870            // `AboveSelection` joins the viewport-placed group: what it hangs
871            // off is a range of text, not the widget recorded as its anchor.
872            // Its lifetime belongs to the selection controller that raised it,
873            // which is also why it lives in the text-affordance band.
874            // `BelowSelection` is its mirror and answers the same.
875            P::Centered
876            | P::TopCenter { .. }
877            | P::BottomCenter
878            | P::ViewportCorner { .. }
879            | P::FullViewport
880            | P::AboveSelection { .. }
881            | P::BelowSelection { .. } => false,
882        }
883    }
884
885    /// Whether an overlay is one that keyboard focus leaving it should close.
886    ///
887    /// Four exclusions, all structural rather than declared:
888    ///
889    /// * Anything **not positioned at its anchor** (see
890    ///   [`Self::overlay_is_anchor_positioned`]). That covers the modal — the
891    ///   one surface that legitimately *contains* focus (ARIA's Dialog (Modal)
892    ///   pattern), which `cycle_focus` already roots Tab traversal at — its
893    ///   full-viewport scrim, and the notification surfaces. A snackbar is the
894    ///   sharp case: it is shown *from* a focused button and keeps that button
895    ///   focused, so an anchor-aware rule would otherwise tear it down on the
896    ///   user's very next keystroke, overriding both its timer and
897    ///   `.persistent()`. A toast's lifetime belongs to its timer, never to
898    ///   where the keyboard happens to be.
899    /// * An overlay **already fading out**. Dismissing it again collapses the
900    ///   tween it is mid-way through — and a dismissal is usually what moved
901    ///   focus here in the first place, so this is the common case, not a
902    ///   corner.
903    /// * A **tooltip**, owned end-to-end by `tooltip_focus_leave_outside`,
904    ///   which asks a deliberately wider question — it keeps a tip alive while
905    ///   focus rests on its *anchor*, which is the normal state of a
906    ///   focus-promoted tip. Judging it by content alone would kill it the
907    ///   moment it appeared.
908    /// * An [**inert**](crate::overlay::OverlayRequest::inert) overlay — a value
909    ///   readout over a slider, say. Nothing in it can hold focus or be worked
910    ///   from the keyboard, so it is not a disclosure focus can walk out of,
911    ///   and the widget that raised it decides when it goes, as a tooltip's
912    ///   machinery does for a tip.
913    ///
914    /// Note what is *not* consulted: [`DismissBehavior`](crate::overlay::DismissBehavior).
915    /// That enum picks which of Escape / click-outside / hover-out apply, which
916    /// is an orthogonal axis — a popover that opted out of click-outside did not
917    /// thereby ask to survive being tabbed away from.
918    ///
919    /// Deliberately *not* `overlay_is_host_surface` either: that matches
920    /// `Role::Dialog`, and `PopoverSurface` announces itself as exactly that,
921    /// so host-ness would exempt every popover in the framework — the one
922    /// surface this rule exists for. Host-ness still stops the walk *above*
923    /// the overlay focus left; see `dismiss_overlays_left_by_focus`.
924    fn overlay_follows_focus_out(&self, overlay_id: crate::overlay::OverlayId) -> bool {
925        let Some(overlay) = self.overlay_manager.overlay(overlay_id) else {
926            return false;
927        };
928        if !Self::overlay_is_anchor_positioned(&overlay.placement) {
929            return false;
930        }
931        if overlay.is_dismissing() {
932            return false;
933        }
934        if overlay.inert {
935            return false;
936        }
937        !self
938            .tooltips
939            .iter()
940            .any(|entry| entry.content_id == overlay.content_id)
941    }
942
943    /// The topmost overlay `widget_id` belongs to for focus purposes — either
944    /// because it sits *inside* that overlay's content, or because it is the
945    /// **anchor** the overlay hangs off.
946    ///
947    /// The anchor half is not a nicety. A non-searchable `ComboBox` keeps focus
948    /// on its own trigger the whole time its dropdown is open, and a
949    /// `SearchField` keeps it in the text input while the suggestion list
950    /// floats below — in both cases focus is never inside the overlay at all,
951    /// so a content-only test would decide nothing was ever open and leave the
952    /// panel behind when the user tabbed away. `tooltip_focus_leave_outside`
953    /// reached the same conclusion for tips, for the same reason.
954    ///
955    /// **One pass over the stack, top down, asking both questions at each
956    /// level** — not "by content, else by anchor". Those two orderings differ
957    /// exactly when a widget is inside one overlay and the anchor of another,
958    /// which is the ordinary shape of a dropdown opened inside a modal: a
959    /// content-first lookup answers with the *modal*, whose whole point is that
960    /// it does not follow focus out, and the dropdown anchored to the very
961    /// widget holding focus never gets considered at all. That left a
962    /// `ComboBox` panel open over the Settings dialog after Tab had moved on.
963    /// Scanning top down instead lets the nearer, more specific overlay win,
964    /// because the stack is already ordered by exactly that.
965    fn overlay_orbit_for_widget(&self, widget_id: WidgetId) -> Option<crate::overlay::OverlayId> {
966        self.overlay_manager
967            .stack
968            .iter()
969            .rev()
970            .find(|overlay| {
971                self.is_descendant_of(widget_id, overlay.content_id)
972                    || (self.overlay_follows_focus_out(overlay.id)
973                        && self.is_descendant_of(widget_id, overlay.anchor))
974            })
975            .map(|overlay| overlay.id)
976    }
977
978    /// Close whatever non-modal overlay the keyboard just walked out of.
979    ///
980    /// Non-modal overlays do not trap Tab — menus, popovers and dropdown
981    /// panels implement patterns (Menu, Disclosure, Combobox) that all treat
982    /// Tab as an *exit* gesture, not a navigation one. APG is unqualified
983    /// about menus in particular: Tab "moves focus out of the menu or menubar,
984    /// and closes all menus and submenus". So rather than contain focus, we
985    /// let it go and take the overlay down behind it — which is also what
986    /// keeps an open panel from hiding the focus ring that just left it
987    /// (WCAG 2.2 SC 2.4.11, Focus Not Obscured).
988    ///
989    /// **Ancestry here is two different questions, and they use two
990    /// identically-named helpers.** A submenu's content is `add_detached`, so
991    /// it is never an arena descendant of the menu that opened it — only
992    /// [`OverlayManager::is_descendant_of`](crate::overlay::OverlayManager::is_descendant_of),
993    /// which walks `parent_overlay`, relates the two. Asking
994    /// [`Self::is_descendant_of`] (the arena walk) instead would close a menu
995    /// the instant its own submenu took focus.
996    ///
997    /// Walking *up* the chain and dismissing the outermost eligible level is
998    /// what delivers APG's plural "all menus": `dismiss` already cascades back
999    /// down to every descendant, so one call closes the whole tree.
1000    ///
1001    /// Unlike every other dismissal path this one must **not** restore focus to
1002    /// the overlay's `focus_restore`. The caller has already installed the new
1003    /// focus target; re-focusing the trigger here would yank it straight back.
1004    pub(super) fn dismiss_overlays_left_by_focus(
1005        &mut self,
1006        old: Option<WidgetId>,
1007        new_focus: Option<WidgetId>,
1008        ops: &mut dyn crate::window::WindowOps,
1009    ) {
1010        let Some(old) = old else {
1011            return;
1012        };
1013        let Some(old_overlay) = self.overlay_orbit_for_widget(old) else {
1014            return;
1015        };
1016        // Deliberately the *content*-only lookup, not the orbit: arriving on an
1017        // overlay's own anchor is leaving it. That is the trigger — exactly
1018        // where Escape would have put you — so Shift+Tab off the front of a
1019        // popover closes it rather than parking an open panel under the focus
1020        // ring of the button that owns it.
1021        // `None` is focus cleared outright (`WidgetTree::clear_focus`), which
1022        // leaves every overlay it was in.
1023        let new_overlay = new_focus.and_then(|id| self.overlay_ancestor_for_widget(id));
1024
1025        // Focus went *deeper* into the same cascade — a submenu opening off its
1026        // parent, a picker inside a popover. Nothing was left behind.
1027        if let Some(new_overlay) = new_overlay
1028            && (new_overlay == old_overlay
1029                || self
1030                    .overlay_manager
1031                    .is_descendant_of(new_overlay, old_overlay))
1032        {
1033            return;
1034        }
1035
1036        if !self.overlay_follows_focus_out(old_overlay) {
1037            return;
1038        }
1039
1040        let mut topmost = old_overlay;
1041        let mut current = self
1042            .overlay_manager
1043            .overlay(old_overlay)
1044            .and_then(|overlay| overlay.parent_overlay);
1045        while let Some(overlay_id) = current {
1046            // Focus backed out to a shallower level of this same cascade (a
1047            // submenu handing back to the menu that owns it). That level stays;
1048            // only what sits below it goes.
1049            if Some(overlay_id) == new_overlay {
1050                break;
1051            }
1052            // Never let a menu take its hosting dialog, composite tooltip or
1053            // revealed menubar down with it.
1054            if self.overlay_is_host_surface(overlay_id) {
1055                break;
1056            }
1057            if !self.overlay_follows_focus_out(overlay_id) {
1058                break;
1059            }
1060            topmost = overlay_id;
1061            current = self
1062                .overlay_manager
1063                .overlay(overlay_id)
1064                .and_then(|overlay| overlay.parent_overlay);
1065        }
1066
1067        let dismissed = self.overlay_manager.dismiss(topmost);
1068        self.dormant_dismissed_content(&dismissed, &mut *ops);
1069    }
1070
1071    /// Dismiss every overlay whose content's role is *not* a host
1072    /// surface (`Tooltip` / `Dialog` / `AlertDialog`). Targets stay
1073    /// stable across the loop because we resolve ids first, then
1074    /// dismiss — `OverlayManager::dismiss` cascades to descendants,
1075    /// so an already-cascaded id is a no-op.
1076    ///
1077    /// Replacement for `dismiss_all_overlays` in popover triggers and
1078    /// pre-show cleanup paths, where the broad "dismiss everything"
1079    /// semantics also closed an outer composite tooltip or modal
1080    /// hosting the trigger.
1081    ///
1082    /// Focus held inside one of them goes back where it was when the
1083    /// lowest of them opened.
1084    pub(super) fn dismiss_all_overlays_except_hosts(
1085        &mut self,
1086        ops: &mut dyn crate::window::WindowOps,
1087    ) {
1088        let to_dismiss: Vec<crate::overlay::OverlayId> = self
1089            .overlay_manager
1090            .stack
1091            .iter()
1092            .map(|overlay| overlay.id)
1093            .filter(|&id| !self.overlay_is_host_surface(id))
1094            .collect();
1095
1096        // Focus inside one of them is cleared with it. It goes back where it
1097        // was when the lowest of them opened (the stack runs bottom to top),
1098        // as Escape would give it back, rather than being left nowhere: a
1099        // menu bar's menu replaced by its neighbour, or closed from its
1100        // title, comes through here.
1101        // The fallback chain then belongs to that same lowest overlay: the
1102        // removed entry it reads is the first whose target is `restore`.
1103        let mark = self.dismissal_mark();
1104        let mut restore = None;
1105        for overlay_id in to_dismiss {
1106            let (dismissed, focus_restore) =
1107                self.overlay_manager.dismiss_with_focus_restore(overlay_id);
1108            self.dormant_dismissed_content(&dismissed, &mut *ops);
1109            restore = restore.or(focus_restore);
1110        }
1111        // As before this used the chain: only when something held focus
1112        // before the dismissal and nothing live holds it now.
1113        if mark.focused_before().is_some() && self.focus_left_nowhere() {
1114            self.return_focus_after_dismissal(restore, mark, &mut *ops);
1115        }
1116    }
1117
1118    /// Whether `overlay_id` is a "host" surface — a tooltip, dialog,
1119    /// or alert dialog. Host overlays survive `dismiss_all_except_hosts`
1120    /// and stop the upward walk in `dismiss_self_overlay_chain_for_source`,
1121    /// so a popover hosted inside a composite tooltip can dismiss
1122    /// itself (or its menu cascade) without taking the host with it.
1123    pub(super) fn overlay_is_host_surface(&self, overlay_id: crate::overlay::OverlayId) -> bool {
1124        let Some(overlay) = self.overlay_manager.overlay(overlay_id) else {
1125            return false;
1126        };
1127        // A modal (an overlay whose placement `is_modal`, see `modal_overlay_for_widget`) is
1128        // always a host surface: a dropdown / popover / menu opened *inside* a
1129        // modal must dismiss only its own cascade, never tear down the hosting
1130        // modal. Without this, a `ComboBox`/menu inside a modal that closes via
1131        // `dismiss_all_except_hosts` / `dismiss_self_overlay_chain_for_source`
1132        // walks past the modal (whose content is not a `Dialog`-role widget) and
1133        // dismisses it too. Same fix that stopped a `TabWidget` overflow menu
1134        // from closing its hosting composite tooltip, extended to modals.
1135        if overlay.placement.is_modal() {
1136            return true;
1137        }
1138        let Some(node) = self.arena.get(overlay.content_id) else {
1139            return false;
1140        };
1141        // Prefer an `.access_role(...)` override (e.g. a collapsible
1142        // `MenuBar`'s bar-content node marked `Role::MenuBar`) over the
1143        // widget's own role — the override is what the AccessKit walker
1144        // surfaces, so it must also decide host-ness here. Without this,
1145        // the revealed bar would not be recognised as a host and
1146        // `dismiss_all_except_hosts` (called when a menu opens) would
1147        // tear it down mid-navigation.
1148        let role = node
1149            .access_overrides
1150            .as_ref()
1151            .and_then(|o| o.role)
1152            .unwrap_or_else(|| {
1153                let mut builder = AccessNodeBuilder::new();
1154                node.widget.accessibility(&mut builder);
1155                builder.role()
1156            });
1157        matches!(
1158            role,
1159            accesskit::Role::Tooltip
1160                | accesskit::Role::Dialog
1161                | accesskit::Role::AlertDialog
1162                | accesskit::Role::MenuBar
1163        )
1164    }
1165
1166    pub(super) fn dismiss_modal_for_source(
1167        &mut self,
1168        source_widget: WidgetId,
1169        ops: &mut dyn crate::window::WindowOps,
1170    ) -> bool {
1171        let Some(modal_overlay) = self.modal_overlay_for_widget(source_widget) else {
1172            return false;
1173        };
1174
1175        let mark = self.dismissal_mark();
1176        let (dismissed, focus_restore) = self
1177            .overlay_manager
1178            .dismiss_with_focus_restore(modal_overlay);
1179        self.dormant_dismissed_content(&dismissed, &mut *ops);
1180        self.return_focus_after_dismissal(focus_restore, mark, &mut *ops);
1181        true
1182    }
1183
1184    pub fn is_descendant_of(&self, widget_id: WidgetId, ancestor: WidgetId) -> bool {
1185        if widget_id == ancestor {
1186            return true;
1187        }
1188        let mut current = self.arena.parent(widget_id);
1189        while let Some(parent_id) = current {
1190            if parent_id == ancestor {
1191                return true;
1192            }
1193            current = self.arena.parent(parent_id);
1194        }
1195        false
1196    }
1197
1198    /// Whether `widget_id` is the root content node of an active overlay
1199    /// (an open menu, popover, dialog, …). Menus and popovers move keyboard
1200    /// focus onto their whole content container while navigating items via
1201    /// an internal highlight index, so the focus-tooltip path must not treat
1202    /// that container's focus as a per-item trigger (it would surface every
1203    /// descendant's rich tooltip at once).
1204    fn is_overlay_content_root(&self, widget_id: WidgetId) -> bool {
1205        self.overlay_manager.find_by_content(widget_id).is_some()
1206    }
1207
1208    /// Called when a widget gains keyboard focus. For any *rich* tooltip (one
1209    /// with `sticky_after` set) whose anchor contains `widget_id`, **arm** the
1210    /// tooltip's ordinary show delay: it appears only if focus comes to rest,
1211    /// and it is never promoted by that rest. Only a pointer resting on the
1212    /// anchor (or a hold) makes it sticky, through the dwell sweep, and the
1213    /// explicit routes (the tip's Focus action, its keys) stay.
1214    ///
1215    /// Both halves mirror the pointer deliberately. A tip that appeared the
1216    /// instant focus arrived strobed across a row of tooltipped buttons as the
1217    /// user Tabbed through, the same way a tip on pointer-*enter* (rather than
1218    /// pointer-*pause*) would flicker across a toolbar.
1219    ///
1220    /// Focus arriving, or resting, is not a statement of intent to enter the
1221    /// tip: Tab passes through controls constantly, and a reader resting on
1222    /// one to hear it is listening, not asking for a panel. A tip promoted by
1223    /// a focus rest turned that into a persistent `Role::Dialog` that took the
1224    /// next Tab stop. The surface stays an ephemeral `Role::Tooltip`,
1225    /// reachable to screen readers through the anchor's own description, and
1226    /// out of the Tab order (see `cycle_focus`).
1227    ///
1228    /// Plain tooltips (no `sticky_after`) are deliberately NOT
1229    /// auto-shown on focus: their text reaches assistive tech as the
1230    /// anchor's description, copied onto it by the a11y tree pass while
1231    /// the tooltip is hidden and written from its `described_by`
1232    /// relation while it is shown (no AccessKit adapter reads the
1233    /// relation itself). That is the W3C-recommended pattern for
1234    /// supplementary hints.
1235    pub(super) fn tooltip_focus_enter(&mut self, widget_id: WidgetId) {
1236        // Two ways a registered rich/composite tooltip can relate to the
1237        // focus target:
1238        //   • direct  — focus landed ON the anchor or somewhere inside it
1239        //     (an ordinary focusable control, a self-anchored focusable
1240        //     widget, and composites whose focus sinks into an inner field).
1241        //     Always show.
1242        //   • reverse — the anchor sits strictly *inside* the focused widget.
1243        //     This exists for composing controls (e.g. `Button`) that keep
1244        //     focus on their outer node but anchor the tooltip on an inner
1245        //     body root. Show ONLY when the focused widget is a single
1246        //     such control — never when it is a *container* that merely
1247        //     happens to be focusable and owns many tooltip-bearing
1248        //     descendants (an open `MenuList`, whose whole panel receives
1249        //     focus while items are navigated by an internal highlight
1250        //     index), or every descendant's rich tooltip fires at once — the
1251        //     "wall of tooltips".
1252        //
1253        // The two arms are mutually exclusive (`if` / `else if`): a widget
1254        // that anchors its own tooltip to its `self_id` (`TabHeader`,
1255        // `ColorSwatch`) satisfies BOTH predicates because `is_descendant_of`
1256        // is reflexive — routing it to `direct` only avoids a duplicate
1257        // `show_overlay` (which would leak the first overlay).
1258        type ToShow = (WidgetId, WidgetId, crate::overlay::TooltipPlacement);
1259        let mut direct: Vec<ToShow> = Vec::new();
1260        let mut reverse: Vec<ToShow> = Vec::new();
1261        for e in &self.tooltips {
1262            if e.sticky_after.is_none() || e.overlay_id.is_some() || e.suppressed_until_focus_leaves
1263            {
1264                continue;
1265            }
1266            if self.is_descendant_of(widget_id, e.anchor_id) {
1267                direct.push((e.anchor_id, e.content_id, e.placement));
1268            } else if self.is_descendant_of(e.anchor_id, widget_id) {
1269                reverse.push((e.anchor_id, e.content_id, e.placement));
1270            }
1271        }
1272        let mut to_show = direct;
1273        // A reverse match is a single composing control only when it resolves
1274        // to exactly one anchor and the focused node is not itself a menu /
1275        // popover content root. Otherwise it is a container fan-out — skip it.
1276        if reverse.len() == 1 && !self.is_overlay_content_root(widget_id) {
1277            to_show.extend(reverse);
1278        }
1279
1280        // Arm the same pending-delay timer the pointer path arms — do not show
1281        // now. Focus arriving is not intent, and Tab moves fast: showing on
1282        // arrival made a sweep across a row of tooltipped buttons strobe a tip
1283        // at every stop. The pointer has always required a *pause* before a tip
1284        // appears; the keyboard equivalent is focus coming to rest, so it waits
1285        // out the same `delay` (and gets the same warm-reshow discount inside a
1286        // session). `hover_origin` stays `None`: there is no pointer to apply
1287        // the stationary-slop filter to.
1288        let sim_now = self.sim_clock;
1289        let real_now = std::time::Instant::now();
1290        for (_anchor_id, content_id, _placement) in to_show {
1291            if let Some(entry) = self
1292                .tooltips
1293                .iter_mut()
1294                .find(|e| e.content_id == content_id)
1295            {
1296                entry.hover_start = Some(sim_now);
1297                entry.real_hover_start = Some(real_now);
1298                entry.hover_origin = None;
1299                entry.armed_by_focus = true;
1300                entry.armed_by_hold = false;
1301            }
1302        }
1303    }
1304
1305    /// Surface the tooltip of a keyboard-highlighted menu item immediately
1306    /// (no dwell), positioned per its own `TooltipPlacement`, and dismiss the
1307    /// previously-highlighted item's tooltip. Real keyboard focus stays on the
1308    /// enclosing `MenuList` (for key handling); this is keyed on `item_id`.
1309    ///
1310    /// The tooltip is shown as a `Manual`-dismiss **child overlay of the
1311    /// enclosing menu**, so closing the menu (Escape / click-outside / the
1312    /// opener) cascades the tooltip away automatically, and a single Escape
1313    /// reaches the menu rather than only clearing the tooltip.
1314    pub(super) fn show_highlight_tooltip(
1315        &mut self,
1316        item_id: WidgetId,
1317        ops: &mut dyn crate::window::WindowOps,
1318    ) {
1319        // Clear (and reconcile) any currently-shown highlight tooltip first —
1320        // moving the highlight replaces it; a tooltip-less target clears it.
1321        self.clear_highlight_tooltip(&mut *ops);
1322
1323        // Find the single tooltip anchored within the highlighted item's
1324        // subtree (a `MenuItem` anchors to its inner body root). Skip if it is
1325        // already shown or the item carries no tooltip.
1326        let found = self.tooltips.iter().find_map(|e| {
1327            if e.overlay_id.is_none() && self.is_descendant_of(e.anchor_id, item_id) {
1328                Some((e.anchor_id, e.content_id, e.placement))
1329            } else {
1330                None
1331            }
1332        });
1333        let Some((anchor_id, content_id, placement)) = found else {
1334            return;
1335        };
1336
1337        let parent_overlay = self.overlay_ancestor_for_widget(item_id);
1338        self.arena.activate(content_id);
1339        let fade_duration = if self.prefers_reduced_motion {
1340            None
1341        } else {
1342            Some(self.theme.motion.duration_fast)
1343        };
1344        let mut request = crate::overlay::OverlayRequest::new(
1345            content_id,
1346            anchor_id,
1347            Self::tooltip_overlay_placement(placement),
1348            crate::overlay::DismissBehavior::Manual,
1349        );
1350        request.parent_overlay = parent_overlay;
1351        request.fade_duration = fade_duration;
1352        let oid = self.show_overlay(request);
1353        let real_now = std::time::Instant::now();
1354        let sim_now = self.sim_clock;
1355        if let Some(entry) = self
1356            .tooltips
1357            .iter_mut()
1358            .find(|e| e.content_id == content_id)
1359        {
1360            entry.overlay_id = Some(oid);
1361            entry.shown_at_sim = Some(sim_now);
1362            entry.shown_at_real = Some(real_now);
1363            if let Some(sink) = entry.shown_at_sink.as_ref() {
1364                sink.set(Some(real_now));
1365            }
1366        }
1367        self.highlight_tooltip = Some((oid, content_id));
1368    }
1369
1370    /// Dismiss the keyboard-highlight tooltip if one is showing, resetting its
1371    /// entry so it can re-show later. Safe to call when none is active or when
1372    /// the overlay was already cascade-dismissed by a menu close (the tracked
1373    /// id is simply no longer in the stack).
1374    pub(super) fn clear_highlight_tooltip(&mut self, ops: &mut dyn crate::window::WindowOps) {
1375        let Some((oid, content_id)) = self.highlight_tooltip.take() else {
1376            return;
1377        };
1378        if self.overlay_manager.stack.iter().any(|o| o.id == oid) {
1379            let dismissed = self.overlay_manager.dismiss(oid);
1380            self.dormant_dismissed_content(&dismissed, &mut *ops);
1381        }
1382        if let Some(entry) = self
1383            .tooltips
1384            .iter_mut()
1385            .find(|e| e.content_id == content_id)
1386        {
1387            entry.overlay_id = None;
1388            entry.shown_at_sim = None;
1389            entry.shown_at_real = None;
1390            if let Some(sink) = entry.shown_at_sink.as_ref() {
1391                sink.set(None);
1392            }
1393        }
1394    }
1395
1396    /// Called when focus moves to a new widget. Dismisses every
1397    /// focus-promoted rich tooltip whose anchor- and tooltip-content
1398    /// subtrees both fail to contain the new focus — so Tab'ing INTO
1399    /// a sticky tooltip to click a link keeps it up, but Tab'ing
1400    /// past it onto unrelated controls closes it (preventing sticky
1401    /// accumulation as the user navigates through a form).
1402    ///
1403    /// Pointer-dwelled stickies (`promoted_by_focus == false`)
1404    /// survive focus changes intact — they're dismissed only via
1405    /// Escape or click-outside, matching the existing mouse UX.
1406    pub(super) fn tooltip_focus_leave_outside(
1407        &mut self,
1408        new_focus: Option<WidgetId>,
1409        ops: &mut dyn crate::window::WindowOps,
1410    ) {
1411        let to_dismiss: Vec<crate::overlay::OverlayId> = self
1412            .tooltips
1413            .iter()
1414            .filter(|e| e.promoted_by_focus && e.overlay_id.is_some())
1415            .filter(|e| {
1416                let in_scope = new_focus
1417                    .map(|nf| {
1418                        // In scope when the new focus lands in either
1419                        // the anchor's subtree or the tooltip content's
1420                        // subtree — covers Tab-to-anchor, Tab-deeper-
1421                        // inside-anchor, and Tab-into-tooltip.
1422                        self.is_descendant_of(nf, e.anchor_id)
1423                            || self.is_descendant_of(e.anchor_id, nf)
1424                            || self.is_descendant_of(nf, e.content_id)
1425                    })
1426                    .unwrap_or(false);
1427                !in_scope
1428            })
1429            .filter_map(|e| e.overlay_id)
1430            .collect();
1431
1432        for oid in to_dismiss {
1433            let dismissed = self.overlay_manager.dismiss(oid);
1434            self.dormant_dismissed_content(&dismissed, &mut *ops);
1435        }
1436
1437        // Focus moved on before the delay ripened: disarm, or the tip would
1438        // still open a beat later, over a control the user has already left.
1439        for e in &mut self.tooltips {
1440            if e.armed_by_focus && e.overlay_id.is_none() {
1441                e.hover_start = None;
1442                e.real_hover_start = None;
1443                e.armed_by_focus = false;
1444            }
1445        }
1446
1447        // Focus has landed somewhere new: any entry it is now outside of has
1448        // had its Escape-suppression served. Tabbing away and back must
1449        // re-summon the tip, or one Escape would mute that anchor forever.
1450        let served: Vec<usize> = self
1451            .tooltips
1452            .iter()
1453            .enumerate()
1454            .filter(|(_, e)| e.suppressed_until_focus_leaves)
1455            .filter(|(_, e)| {
1456                let still_inside = new_focus
1457                    .map(|nf| {
1458                        self.is_descendant_of(nf, e.anchor_id)
1459                            || self.is_descendant_of(nf, e.content_id)
1460                    })
1461                    .unwrap_or(false);
1462                !still_inside
1463            })
1464            .map(|(i, _)| i)
1465            .collect();
1466        for i in served {
1467            self.tooltips[i].suppressed_until_focus_leaves = false;
1468        }
1469    }
1470
1471    /// Whether a pointer hover over `widget_id` should count as a hover
1472    /// of `anchor_id` for tooltip purposes.
1473    ///
1474    /// `widget_id` must be a descendant-or-self of `anchor_id`, AND no
1475    /// active-overlay boundary may separate them. The second clause is
1476    /// what stops a tooltip leaking onto overlay content that merely
1477    /// *remains* an arena child of its anchor: a `ComboBox`'s dropdown
1478    /// panel, a `PopoverButton`'s popover, a menu — all are kept under
1479    /// their trigger in the arena (for hit-test / a11y / teardown) but
1480    /// are shown as overlays. Hovering one of their rows is a hover of
1481    /// the *overlay*, not of the anchor's own chrome, so the anchor's
1482    /// (or any ancestor's) tooltip must not fire.
1483    ///
1484    /// Concretely: if the hovered widget lives inside an active overlay
1485    /// whose content subtree does **not** contain the anchor, the hover
1486    /// is on the overlay and we return `false`. A tooltip attached to a
1487    /// widget *inside* the overlay (e.g. a dropdown row's own tooltip)
1488    /// still fires, because that anchor is itself within the overlay's
1489    /// content subtree.
1490    fn tooltip_hover_targets_anchor(&self, widget_id: WidgetId, anchor_id: WidgetId) -> bool {
1491        if !self.is_descendant_of(widget_id, anchor_id) {
1492            return false;
1493        }
1494        if let Some(overlay_id) = self.overlay_ancestor_for_widget(widget_id)
1495            && let Some(content_id) = self
1496                .overlay_manager
1497                .overlay(overlay_id)
1498                .map(|o| o.content_id)
1499            && !self.is_descendant_of(anchor_id, content_id)
1500        {
1501            return false;
1502        }
1503        true
1504    }
1505
1506    /// Arm the dwell for the tooltip that owns this hover.
1507    ///
1508    /// A hover target can sit inside several tooltip anchors at once (a row
1509    /// with its own tip inside a panel with a tip). Only the **innermost**
1510    /// anchor arms: it is the most specific description of what the pointer is
1511    /// actually over, and arming the outer ones too would let two tooltips
1512    /// mature and open simultaneously, one on top of the other.
1513    ///
1514    /// "Innermost" is measured by arena depth from the hovered widget, so
1515    /// nesting order — not the order the anchors happened to be attached in —
1516    /// decides the winner.
1517    /// The tooltip entry a pointer over `widget_id` should surface: the
1518    /// **innermost** one whose anchor is `widget_id` or an ancestor of it.
1519    ///
1520    /// Shared by the hover arm and by the tree-owned hold route
1521    /// ([`super::touch_route`]) so a hold and a hover cannot pick different
1522    /// tips for the same node.
1523    pub(super) fn tooltip_index_for(&self, widget_id: WidgetId) -> Option<usize> {
1524        self.tooltips
1525            .iter()
1526            .enumerate()
1527            .filter(|(_, entry)| self.tooltip_hover_targets_anchor(widget_id, entry.anchor_id))
1528            .filter_map(|(index, entry)| {
1529                self.ancestor_distance(widget_id, entry.anchor_id)
1530                    .map(|depth| (depth, index))
1531            })
1532            .min()
1533            .map(|(_, index)| index)
1534    }
1535
1536    pub(super) fn tooltip_pointer_enter(&mut self, widget_id: WidgetId) {
1537        let Some(index) = self.tooltip_index_for(widget_id) else {
1538            return;
1539        };
1540        // Don't restart a timer for a tip that is already showing. A tip focus
1541        // showed does become a pointer dwell, though: the pointer resting on
1542        // its anchor earns stickiness over the usual window, from now.
1543        if self.tooltips[index].overlay_id.is_some() {
1544            let entry = &mut self.tooltips[index];
1545            if entry.promoted_by_focus && !entry.is_sticky && !entry.dwell_promotes {
1546                let real_now = std::time::Instant::now();
1547                entry.dwell_promotes = true;
1548                entry.shown_at_sim = Some(self.sim_clock);
1549                entry.shown_at_real = Some(real_now);
1550                if let Some(sink) = entry.shown_at_sink.as_ref() {
1551                    sink.set(Some(real_now));
1552                }
1553            }
1554            return;
1555        }
1556        self.tooltips[index].hover_start = Some(self.sim_clock);
1557        self.tooltips[index].real_hover_start = Some(std::time::Instant::now());
1558        self.tooltips[index].hover_origin = self.hover_owner_position();
1559        self.tooltips[index].armed_by_focus = false;
1560        self.tooltips[index].armed_by_hold = false;
1561        self.arena.mark_needs_paint(self.tooltips[index].anchor_id);
1562    }
1563
1564    /// Number of parent hops from `widget_id` up to `ancestor`, or `None` if
1565    /// `ancestor` is not on the chain. `0` when they are the same widget.
1566    fn ancestor_distance(&self, widget_id: WidgetId, ancestor: WidgetId) -> Option<usize> {
1567        let mut current = widget_id;
1568        let mut depth = 0usize;
1569        loop {
1570            if current == ancestor {
1571                return Some(depth);
1572            }
1573            current = self.arena.parent(current)?;
1574            depth += 1;
1575        }
1576    }
1577
1578    /// Cancel tooltip activity on a pointer press.
1579    ///
1580    /// A press is a statement that the user already knows what the control
1581    /// does: a pending dwell is cancelled (so a tooltip does not pop *after*
1582    /// the click that answered it), and a shown non-sticky tooltip is
1583    /// dismissed (so it stops covering what was just clicked). Re-hovering
1584    /// restarts the delay from scratch, matching Windows and GTK.
1585    ///
1586    /// Pointer-dwelled **sticky** tooltips are left alone — they are an
1587    /// interactive surface the user deliberately pinned, and they own their
1588    /// own Escape / click-outside dismissal.
1589    /// `at` is the press position, when there is one. A press landing *inside*
1590    /// a tooltip's own surface is the user reaching into it (a rich tooltip's
1591    /// inline link), not dismissing it, so that tooltip is spared.
1592    pub(super) fn tooltip_pointer_press(&mut self, at: Option<teksilo_canvas::Point>) {
1593        // Only a press holds the dwell back: a window deactivation or Escape
1594        // (no position) retires the tips but says nothing about the hover.
1595        if at.is_some() {
1596            self.tooltip_dwell_held = true;
1597        }
1598        let mut to_dismiss = Vec::new();
1599        let candidates: Vec<(usize, Option<crate::overlay::OverlayId>)> = self
1600            .tooltips
1601            .iter()
1602            .enumerate()
1603            .map(|(i, e)| (i, if e.is_sticky { None } else { e.overlay_id }))
1604            .collect();
1605        for (index, overlay_id) in candidates {
1606            // Content rect only — deliberately NOT `pointer_inside_overlay_region`,
1607            // which also counts the anchor (it exists to keep the tip alive
1608            // while the pointer crosses the gap). A press on the *anchor* is
1609            // exactly the case that must dismiss.
1610            // A tip that takes no hits (a plain one) has no inside: the press
1611            // was the covered control's, and the tip it covers must go.
1612            let body = self.tooltip_content_node(self.tooltips[index].content_id);
1613            let takes_hits = !self
1614                .arena
1615                .get(body)
1616                .is_some_and(|node| node.hit_transparent);
1617            let inside = match (overlay_id, at) {
1618                (Some(oid), Some(pos)) => {
1619                    takes_hits
1620                        && self
1621                            .overlay_content_bounds(oid)
1622                            .is_some_and(|rect| rect.contains(pos))
1623                }
1624                _ => false,
1625            };
1626            if inside {
1627                continue;
1628            }
1629            let entry = &mut self.tooltips[index];
1630            entry.hover_start = None;
1631            entry.real_hover_start = None;
1632            entry.hover_origin = None;
1633            if let Some(oid) = overlay_id {
1634                to_dismiss.push(oid);
1635            }
1636        }
1637        for overlay_id in to_dismiss {
1638            self.dismiss_overlay(overlay_id);
1639        }
1640    }
1641
1642    /// Retire shown tooltips on **Escape**, without consuming the key.
1643    ///
1644    /// WCAG 1.4.13 (Content on Hover or Focus) requires that hover content can
1645    /// be dismissed without moving the pointer or focus, and Escape is the
1646    /// mechanism everyone expects. What it does **not** require is that the
1647    /// keystroke stop there — and stopping there is a bug with real teeth,
1648    /// because a tooltip is up far more often than anyone realises. A writer
1649    /// renaming a table cell, pointer resting where they clicked, presses
1650    /// Escape to abandon the rename: the tip they were not looking at silently
1651    /// goes away and the editor stays open. Press it again and it works. It
1652    /// reads as "Escape does nothing", and it is why an Escape-cancels
1653    /// affordance anywhere in an app is unreliable rather than plainly broken.
1654    ///
1655    /// So this runs *before* the overlay stack's own Escape walk and returns no
1656    /// verdict: the tips go, and the key carries on to whatever the user
1657    /// actually meant it for — a menu, a popover, or the focused widget.
1658    /// Retiring them first also means that walk can no longer pick a tooltip as
1659    /// its target, which is what used to swallow the press.
1660    ///
1661    /// Sticky tooltips are untouched, exactly as on a pointer press: the user
1662    /// deliberately pinned those, and they own their own Escape handling.
1663    pub(super) fn tooltip_escape_pressed(&mut self) {
1664        // No position — the same "every non-sticky tip goes" case as a window
1665        // deactivation. A key press has nowhere to be "inside".
1666        self.tooltip_pointer_press(None);
1667    }
1668
1669    /// Retire every [inert](crate::overlay::OverlayRequest::inert) overlay Escape may close, without consuming the key
1670    /// and without moving focus.
1671    ///
1672    /// [`tooltip_escape_pressed`](Self::tooltip_escape_pressed)'s rule for
1673    /// what is not a registered tooltip: a value readout raised by a hovered
1674    /// control is up while the user types in a field elsewhere, and an Escape
1675    /// spent on it is an Escape the field never sees. Content shown on hover or
1676    /// focus still has to be dismissible without moving either (WCAG 2.2 SC
1677    /// 1.4.13), and this is what dismisses it. Runs ahead of the stack's own
1678    /// Escape walk, which steps over inert overlays.
1679    pub(super) fn inert_overlays_escape_pressed(&mut self, ops: &mut dyn crate::window::WindowOps) {
1680        let dismissed = self.overlay_manager.dismiss_inert_on_escape();
1681        if !dismissed.is_empty() {
1682            self.dormant_dismissed_content(&dismissed, &mut *ops);
1683            self.a11y_dirty = true;
1684        }
1685    }
1686
1687    /// Retire hover tooltips when the window stops being active.
1688    ///
1689    /// Same shape as [`tooltip_pointer_press`](Self::tooltip_pointer_press) —
1690    /// pending dwells cancelled, shown non-sticky tips dismissed, pinned
1691    /// stickies preserved — but triggered by the window losing focus rather
1692    /// than by a click.
1693    pub(super) fn tooltip_window_deactivated(&mut self) {
1694        // No position: the window is going away, so every non-sticky tip goes
1695        // with it regardless of where the pointer happened to be.
1696        self.tooltip_pointer_press(None);
1697    }
1698
1699    /// Cancel every pending (not-yet-shown) tooltip dwell.
1700    ///
1701    /// Called when a drag session starts: the pointer is now carrying
1702    /// something, and a tooltip that pops mid-drag is a stray overlay in the
1703    /// user's way. `process_tooltips_real` runs from the layout pass, which a
1704    /// drag keeps driving, so the dwell would otherwise mature and show even
1705    /// though the pointer-move path is short-circuited for the drag.
1706    pub(crate) fn tooltip_cancel_pending_dwell(&mut self) {
1707        for entry in &mut self.tooltips {
1708            if entry.overlay_id.is_none() {
1709                entry.hover_start = None;
1710                entry.real_hover_start = None;
1711                entry.hover_origin = None;
1712            }
1713        }
1714    }
1715
1716    /// Restart a pending tooltip's delay when the pointer keeps moving
1717    /// inside the same anchor beyond the stationary slop. Called from
1718    /// pointer-move when the hover target has not changed.
1719    pub(super) fn tooltip_pointer_moved(
1720        &mut self,
1721        widget_id: WidgetId,
1722        position: teksilo_canvas::Point,
1723    ) {
1724        let matching: Vec<usize> = self
1725            .tooltips
1726            .iter()
1727            .enumerate()
1728            .filter(|(_, entry)| {
1729                entry.overlay_id.is_none()
1730                    && entry.hover_start.is_some()
1731                    && !entry.armed_by_focus
1732                    && self.tooltip_hover_targets_anchor(widget_id, entry.anchor_id)
1733            })
1734            .map(|(index, _)| index)
1735            .collect();
1736        if matching.is_empty() {
1737            return;
1738        }
1739        let now = self.sim_clock;
1740        let real_now = std::time::Instant::now();
1741        let slop = super::TOOLTIP_STATIONARY_SLOP;
1742        let slop_sq = slop * slop;
1743        for index in matching {
1744            let origin = match self.tooltips[index].hover_origin {
1745                Some(o) => o,
1746                None => {
1747                    // Enter happened without a recorded position (tests that
1748                    // call `tooltip_pointer_enter` directly) — adopt this
1749                    // position as the origin without restarting the timer.
1750                    self.tooltips[index].hover_origin = Some(position);
1751                    continue;
1752                }
1753            };
1754            let dx = position.x - origin.x;
1755            let dy = position.y - origin.y;
1756            if dx * dx + dy * dy <= slop_sq {
1757                continue;
1758            }
1759            // Pointer has moved meaningfully since hover began — restart.
1760            self.tooltips[index].hover_start = Some(now);
1761            self.tooltips[index].real_hover_start = Some(real_now);
1762            self.tooltips[index].hover_origin = Some(position);
1763        }
1764    }
1765
1766    /// Promote a shown tooltip from "ephemeral hover" to "sticky".
1767    ///
1768    /// - Flags the tooltip entry as sticky so
1769    ///   `tooltip_pointer_press`
1770    ///   no longer auto-dismisses it,
1771    /// - Swaps the overlay's dismiss behavior to
1772    ///   `EscapeOrClickOutside` so clicking anywhere off the tooltip
1773    ///   (or pressing Escape) closes it.
1774    ///
1775    /// The entry is **not** removed: when the user later dismisses
1776    /// the sticky overlay, `dormant_dismissed_content` resets the
1777    /// entry back to its initial state so a future hover re-shows
1778    /// the tooltip from scratch.
1779    ///
1780    /// Called by the auto-promote sweep in `process_tooltips_impl` once the
1781    /// dwell timer reaches its threshold, and reachable from a widget through
1782    /// `BuildContext::promote_tooltip_to_sticky`.
1783    pub fn promote_tooltip_to_sticky(&mut self, content_id: WidgetId) {
1784        let Some(entry) = self
1785            .tooltips
1786            .iter_mut()
1787            .find(|entry| entry.content_id == content_id)
1788        else {
1789            return;
1790        };
1791        if entry.is_sticky {
1792            return;
1793        }
1794        entry.is_sticky = true;
1795        let overlay_id = entry.overlay_id;
1796        if let Some(overlay_id) = overlay_id {
1797            self.overlay_manager.set_dismiss(
1798                overlay_id,
1799                crate::overlay::DismissBehavior::EscapeOrClickOutside,
1800            );
1801        }
1802    }
1803
1804    pub(super) fn tooltip_pointer_leave(
1805        &mut self,
1806        widget_id: WidgetId,
1807        _ops: &mut dyn crate::window::WindowOps,
1808    ) {
1809        let matching: Vec<usize> = self
1810            .tooltips
1811            .iter()
1812            .enumerate()
1813            .filter(|(_, entry)| self.is_descendant_of(widget_id, entry.anchor_id))
1814            .map(|(index, _)| index)
1815            .collect();
1816        for index in matching {
1817            // A pointer that only passed over the anchor of a tip focus showed
1818            // does not leave it to ripen into a sticky one: the tip goes back
1819            // to not promoting.
1820            let entry = &mut self.tooltips[index];
1821            if entry.promoted_by_focus && !entry.is_sticky && entry.dwell_promotes {
1822                entry.dwell_promotes = false;
1823                if let Some(sink) = entry.shown_at_sink.as_ref() {
1824                    sink.set(None);
1825                }
1826            }
1827            // Cancel any pending (not-yet-shown) dwell so re-hovering restarts
1828            // the delay timer.
1829            self.tooltips[index].hover_start = None;
1830            self.tooltips[index].real_hover_start = None;
1831            self.tooltips[index].hover_origin = None;
1832            // Audit G12 (WCAG 1.4.13 Hoverable): do NOT dismiss a *shown*
1833            // tooltip here on anchor-leave — that killed it the instant the
1834            // pointer crossed the 8px gap toward the tooltip. Dismissal of a
1835            // shown (non-sticky) tooltip is owned by the overlay stack's
1836            // `PointerLeave { 100ms }` machinery (process_pointer_leave_overlays_real,
1837            // run every frame), whose `pointer_inside_overlay_region` keeps the
1838            // overlay alive while the pointer is over EITHER the anchor or the
1839            // tooltip and dismisses only after 100ms outside both. Sticky
1840            // tooltips are dismissed via Escape / click-outside. The stale
1841            // overlay_id left when that machinery dismisses the overlay is
1842            // reconciled at the top of `process_tooltips_impl`.
1843        }
1844    }
1845
1846    /// Returns the earliest of every deadline the tree owes the event loop —
1847    /// pending tooltips and their dwell steps, delayed overlays, overlay
1848    /// auto-dismiss / pointer-leave / fade removal, animations, animated
1849    /// quads, input gestures, an explicit wake-at and the per-frame tick
1850    /// (if any).
1851    pub fn next_timer_deadline(&self) -> Option<std::time::Instant> {
1852        self.next_timer_deadline_source().map(|(at, _)| at)
1853    }
1854
1855    /// [`next_timer_deadline`](Self::next_timer_deadline), with the name of
1856    /// the timer that sets it: `tooltip`, `tooltip_dwell`,
1857    /// `delayed_overlay`, `overlay_auto_dismiss`, `overlay_pointer_leave`,
1858    /// `overlay_fade`, `animation`, `animated_quad`, `gesture`, `wake_at` (a
1859    /// caret blink, a held-back accessibility delivery, a toast timer) or
1860    /// `frame_tick`. The first named when several are due at once. Read by
1861    /// `TEKSILO_IDLE_TRACE`'s `woken_by` counts.
1862    #[doc(hidden)]
1863    pub fn next_timer_deadline_source(&self) -> Option<(std::time::Instant, &'static str)> {
1864        let now = std::time::Instant::now();
1865        let session_active = self.tooltip_session_active_real(now);
1866        let tooltip_deadline = self
1867            .tooltips
1868            .iter()
1869            .filter(|entry| entry.overlay_id.is_none())
1870            .filter_map(|entry| {
1871                let start = entry.real_hover_start?;
1872                let delay = self.effective_tooltip_delay(entry.delay, session_active);
1873                Some(start + delay)
1874            })
1875            .min();
1876
1877        // Sticky-on-dwell wake-ups: once a rich tooltip is shown, wake once per
1878        // indicator step (500 ms for the default 2 s promotion) so the step
1879        // indicator advances and the promotion fires, even with the pointer
1880        // held still. Without these deadlines the loop would only wake on user
1881        // input, freezing the dwell counter. The step is derived per entry from
1882        // its own `sticky_after` rather than hardcoded, so a caller with a
1883        // non-default promotion window still gets evenly-spaced wake-ups.
1884        //
1885        // The step boundary is rounded off `last_frame_time` (the last rendered
1886        // frame) — NOT `Instant::now()`. The app's `request_redraw_due`
1887        // re-derives this deadline at each timer wake and only redraws windows
1888        // whose `deadline <= now`. If we rounded off `now`, then at the instant
1889        // a 500 ms boundary's wake fires, `elapsed` has just crossed it and the
1890        // boundary would already have rolled forward to the NEXT step (a future
1891        // instant) — so `deadline <= now` would never hold and the window would
1892        // never redraw. The dwell then only advanced when some unrelated input
1893        // event happened to redraw the window (the "only updates on mouse move"
1894        // bug). Pinning the boundary to `last_frame_time` keeps the deadline
1895        // `<= now` at its own wake until a render actually advances the frame
1896        // time to the next step — one redraw per 500 ms boundary, no free-run.
1897        let ref_time = self.last_frame_time.unwrap_or_else(std::time::Instant::now);
1898        let dwell_tooltip_deadline = self
1899            .tooltips
1900            .iter()
1901            .filter_map(|entry| {
1902                let sticky_after = entry.sticky_after?;
1903                let shown_at = entry.shown_at_real?;
1904                if entry.overlay_id.is_none() || entry.is_sticky || !entry.dwell_promotes {
1905                    return None;
1906                }
1907                let dwell_step = sticky_after / super::TOOLTIP_DWELL_STEPS;
1908                if dwell_step.is_zero() {
1909                    return None;
1910                }
1911                let elapsed = ref_time.saturating_duration_since(shown_at);
1912                if elapsed >= sticky_after {
1913                    return None;
1914                }
1915                // Round up to the next step boundary so each wake-up lands on a
1916                // 500 ms / 1 s / 1.5 s / 2 s mark (measured at the last frame).
1917                let steps_passed = (elapsed.as_millis() / dwell_step.as_millis()) as u32;
1918                let next_step_at = shown_at + dwell_step * (steps_passed + 1);
1919                Some(next_step_at.min(shown_at + sticky_after))
1920            })
1921            .min();
1922        let delayed_overlay_deadline = self
1923            .pending_delayed_overlays
1924            .iter()
1925            .map(|pending| pending.real_requested_at + pending.delay)
1926            .min();
1927        let auto_dismiss_deadline = self.overlay_manager.next_auto_dismiss_deadline();
1928        // Hover-opened overlays (every shown tooltip, hover submenus) dismiss
1929        // on a `PointerLeave { delay }` grace that only advances when a frame
1930        // runs. The pointer's last motion event is the *start* of that grace,
1931        // not a reason to wake at its end — so without this term a tooltip the
1932        // user has walked away from stays on screen for as long as the app
1933        // stays idle.
1934        let pointer_leave_deadline = self.overlay_manager.next_pointer_leave_deadline();
1935        // A fade-out defers the overlay's removal by the tween's duration, and
1936        // that removal is what parks the content. The tween's own scheduler
1937        // deadline usually wakes the loop at the same instant, but only while
1938        // the tween is registered — a fade that is cancelled, completed early
1939        // or never scheduled (reduced motion) leaves nothing else to wake for,
1940        // and the surface stays on screen until unrelated input arrives.
1941        let fade_dismiss_deadline = self.overlay_manager.next_fade_dismiss_deadline();
1942        let animation_deadline = self
1943            .animation_scheduler
1944            .next_deadline(&self.arena, self.paint_epoch);
1945        // Same pattern for the shader-driven animated-quad registry —
1946        // without this the event loop sleeps between frame intervals
1947        // and shader-driven animations only advance on unrelated
1948        // wakes (mouse move, scroll), producing a visible staircase.
1949        let animated_quad_deadline = self
1950            .animated_quads
1951            .next_deadline(&self.arena, self.paint_epoch);
1952        // Every deadline the input layer owns — a pending long press, a
1953        // press-feedback delay, a live fling simulation — folded into the one
1954        // `WaitUntil` over the one clock. Without the fling term a coast would
1955        // only advance on unrelated wakes, which is a list that scrolls when
1956        // the mouse happens to move.
1957        let gesture_deadline = self.next_input_deadline();
1958        let wake_at_deadline = self.pending_wake_at.get();
1959        // Per-frame-effect path (Pulse / Cycle / caret blink / drag
1960        // auto-scroll): a fixed 60 Hz deadline instead of the old
1961        // `ControlFlow::Poll` free-run, so continuous animations render
1962        // at 60 Hz regardless of the display's refresh rate. See
1963        // `frame_tick_deadline`.
1964        let frame_tick_deadline = self.frame_tick_deadline();
1965
1966        [
1967            (tooltip_deadline, "tooltip"),
1968            (dwell_tooltip_deadline, "tooltip_dwell"),
1969            (delayed_overlay_deadline, "delayed_overlay"),
1970            (auto_dismiss_deadline, "overlay_auto_dismiss"),
1971            (pointer_leave_deadline, "overlay_pointer_leave"),
1972            (fade_dismiss_deadline, "overlay_fade"),
1973            (animation_deadline, "animation"),
1974            (animated_quad_deadline, "animated_quad"),
1975            (gesture_deadline, "gesture"),
1976            (wake_at_deadline, "wake_at"),
1977            (frame_tick_deadline, "frame_tick"),
1978        ]
1979        .into_iter()
1980        .filter_map(|(at, source)| Some((at?, source)))
1981        .min_by_key(|&(at, _)| at)
1982    }
1983
1984    /// When a tree that is never painted must next be laid out: the part
1985    /// of [`next_timer_deadline`](Self::next_timer_deadline) that layout
1986    /// alone moves forward. That is a wake requested with `request_wake_at`,
1987    /// a running tween (a looping one counts only while its widget is
1988    /// painted, so never here), and the frame tick, paced from the last
1989    /// layout.
1990    ///
1991    /// Left out: animated quads, which advance only in render and would be
1992    /// due forever, and the tooltip, overlay and gesture timers, which
1993    /// pointer input and a window's overlays start, and a tree no window
1994    /// hosts has neither.
1995    pub fn next_unpainted_deadline(&self) -> Option<std::time::Instant> {
1996        let animation_deadline = self
1997            .animation_scheduler
1998            .next_deadline(&self.arena, self.paint_epoch);
1999        [
2000            self.pending_wake_at.get(),
2001            animation_deadline,
2002            self.frame_tick_deadline(),
2003        ]
2004        .into_iter()
2005        .flatten()
2006        .min()
2007    }
2008
2009    pub fn overlay_manager(&self) -> &crate::overlay::OverlayManager {
2010        &self.overlay_manager
2011    }
2012
2013    /// Mutable access to the overlay manager. Used by the
2014    /// modal-presentation pipeline to wire up cascade-dismissal
2015    /// between paired overlays (e.g. the dialog scrim and the modal
2016    /// panel) via `OverlayManager::set_parent_overlay`.
2017    pub fn overlay_manager_mut(&mut self) -> &mut crate::overlay::OverlayManager {
2018        &mut self.overlay_manager
2019    }
2020
2021    pub fn active_overlays(&self) -> Vec<crate::overlay::OverlayId> {
2022        self.overlay_manager.active_ids()
2023    }
2024
2025    /// Laid-out bounds of an open overlay's content surface.
2026    ///
2027    /// This is the rectangle the overlay pass placed the content at: its
2028    /// width measured with an *unbounded* proposal, independent of the host
2029    /// tree's own proposal, then narrowed or widened by the placement. Its
2030    /// height is then measured again at that width (a placed width of zero
2031    /// is left alone), and when that height differs from the open-width one
2032    /// by more than half a pixel the overlay is placed again with it;
2033    /// otherwise the open-width height stands. A placement may still shrink
2034    /// the height to the room it finds, as it does an `Above` panel against
2035    /// the top of the window. So it is the right thing to assert against for
2036    /// content that must cap or wrap itself (tooltips against
2037    /// `TOOLTIP_MAX_WIDTH`, popovers against their max height).
2038    /// Reading `bounds(content_id)` instead would report whatever the
2039    /// surrounding layout handed the widget.
2040    pub fn overlay_content_bounds(
2041        &self,
2042        id: crate::overlay::OverlayId,
2043    ) -> Option<teksilo_canvas::Rect> {
2044        self.overlay_manager
2045            .stack
2046            .iter()
2047            .find(|o| o.id == id)
2048            .map(|o| o.bounds)
2049    }
2050
2051    pub fn show_overlay(
2052        &mut self,
2053        request: crate::overlay::OverlayRequest,
2054    ) -> crate::overlay::OverlayId {
2055        let fade_duration = request.fade_duration;
2056        let content_id = request.content_id;
2057        let is_modal = request.placement.is_modal();
2058        let id = self.overlay_manager.show(request);
2059        self.cancel_pointers_for_modal(is_modal);
2060        // The overlay's content subtree just entered the active set;
2061        // the AT tree shape changed and the cached snapshot must be
2062        // rebuilt. The dismiss path already flips this; we must mirror
2063        // it here, otherwise a popup show + read AT sequence returns
2064        // the pre-popup snapshot. The unconditional `a11y_dirty = true`
2065        // in `layout()` previously masked this gap; now this explicit
2066        // set is required.
2067        self.a11y_dirty = true;
2068        if let Some(duration) = fade_duration {
2069            self.attach_overlay_fade(id, content_id, duration);
2070        }
2071        id
2072    }
2073
2074    /// Show an overlay in an explicit z-band.
2075    ///
2076    /// [`show_overlay`](Self::show_overlay) is this with
2077    /// [`OverlayBand::Standard`](crate::overlay::OverlayBand::Standard). The
2078    /// other band is for the touch text affordances — selection handles, the
2079    /// magnifier, the selection toolbar — which must render above the editor's
2080    /// `clips_children` ancestor, below every menu, and outside the
2081    /// outside-press dismissal that every caret-moving tap would otherwise
2082    /// trigger. See [`crate::overlay::text_affordance`].
2083    pub fn show_overlay_in_band(
2084        &mut self,
2085        request: crate::overlay::OverlayRequest,
2086        band: crate::overlay::OverlayBand,
2087    ) -> crate::overlay::OverlayId {
2088        let fade_duration = request.fade_duration;
2089        let content_id = request.content_id;
2090        let is_modal = request.placement.is_modal();
2091        let id = self.overlay_manager.show_in_band(request, band);
2092        self.cancel_pointers_for_modal(is_modal);
2093        self.a11y_dirty = true;
2094        if let Some(duration) = fade_duration {
2095            self.attach_overlay_fade(id, content_id, duration);
2096        }
2097        id
2098    }
2099
2100    /// Show an overlay relative to a source widget, inheriting the source
2101    /// overlay ancestry and focus-restore behavior used during event dispatch.
2102    pub fn show_overlay_from_source(
2103        &mut self,
2104        source_widget: WidgetId,
2105        mut request: crate::overlay::OverlayRequest,
2106    ) -> crate::overlay::OverlayId {
2107        if request.parent_overlay.is_none() {
2108            request.parent_overlay = self.overlay_ancestor_for_widget(source_widget);
2109        }
2110        if let Some(existing) = self.overlay_manager.find_by_content(request.content_id) {
2111            return existing;
2112        }
2113
2114        let fade_duration = request.fade_duration;
2115        let content_id = request.content_id;
2116        let is_modal = request.placement.is_modal();
2117        let current_focus = self.focused;
2118        let id = self.overlay_manager.show(request);
2119        self.cancel_pointers_for_modal(is_modal);
2120        self.a11y_dirty = true;
2121        if let Some(focus_id) = current_focus {
2122            self.record_top_focus_restore(focus_id);
2123        }
2124        if let Some(duration) = fade_duration {
2125            self.attach_overlay_fade(id, content_id, duration);
2126        }
2127        id
2128    }
2129
2130    pub fn show_overlay_for(
2131        &mut self,
2132        request: crate::overlay::OverlayRequest,
2133        duration: std::time::Duration,
2134    ) -> crate::overlay::OverlayId {
2135        let fade_duration = request.fade_duration;
2136        let content_id = request.content_id;
2137        let is_modal = request.placement.is_modal();
2138        let id = self.overlay_manager.show_for(request, duration);
2139        self.cancel_pointers_for_modal(is_modal);
2140        self.overlay_manager.set_shown_at_sim(id, self.sim_clock);
2141        self.a11y_dirty = true;
2142        if let Some(fade) = fade_duration {
2143            self.attach_overlay_fade(id, content_id, fade);
2144        }
2145        id
2146    }
2147
2148    /// Internal: install an animated opacity scope on `content_id`,
2149    /// kick off the 0→1 fade-in tween, and register the signal with
2150    /// the overlay manager so the matching fade-out plays on
2151    /// dismiss. Owner of the animated signal is `content_id` itself
2152    /// — the visibility-gate fix from the scheduler ensures the
2153    /// fade-in still ticks even when the content is freshly inserted
2154    /// and not yet stamped with a paint epoch.
2155    fn attach_overlay_fade(
2156        &mut self,
2157        overlay_id: crate::overlay::OverlayId,
2158        content_id: WidgetId,
2159        duration: std::time::Duration,
2160    ) {
2161        let opacity = crate::signal::Signal::<f32>::new_animated(0.0);
2162        self.register_animated_signal(&opacity, content_id);
2163        self.set_opacity(content_id, opacity.clone());
2164        // Audit G16 (WCAG 2.3.3 / EN 301 549 11.7): honour reduced motion —
2165        // snap the overlay to fully visible with no fade-in tween, and register
2166        // a zero-duration fade so dismissal snaps to 0 as well.
2167        if self.prefers_reduced_motion() {
2168            opacity.set(1.0);
2169            self.overlay_manager
2170                .attach_fade(overlay_id, opacity, std::time::Duration::ZERO);
2171            return;
2172        }
2173        let _ = opacity.try_animate_with_options(crate::animation::AnimationRequest {
2174            target: 1.0,
2175            duration,
2176            easing: teksilo_tokens::Easing::EaseOut,
2177            frame_interval: None,
2178            looping: false,
2179            epsilon: 0.0,
2180            max_duration: None,
2181        });
2182        self.overlay_manager
2183            .attach_fade(overlay_id, opacity, duration);
2184    }
2185
2186    /// Dismiss an overlay programmatically. Uses
2187    /// [`NoopWindowOps`](crate::window::NoopWindowOps) for any
2188    /// focus-loss handlers it triggers — user code fires these from
2189    /// outside a dispatch.
2190    pub fn dismiss_overlay(&mut self, id: crate::overlay::OverlayId) {
2191        let mut noop = crate::window::NoopWindowOps;
2192        self.dismiss_overlay_with_ops(id, &mut noop);
2193    }
2194
2195    /// Dismiss every overlay, running each one's dismissal callback with
2196    /// `reason` and `ops`: a dialog in the tree answers as dismissed (a
2197    /// `MessageBox` reports its escape button). Used by the application
2198    /// before it closes the window, so a dialog still up answers through
2199    /// its own Cancel path rather than going with the window unanswered.
2200    #[doc(hidden)]
2201    pub fn dismiss_all_overlays_with_ops(
2202        &mut self,
2203        reason: crate::overlay::DismissReason,
2204        ops: &mut dyn crate::window::WindowOps,
2205    ) {
2206        let mark = self.dismissal_mark();
2207        let dismissed = self.overlay_manager.dismiss_all_because(reason);
2208        self.dormant_dismissed_content(&dismissed, &mut *ops);
2209        self.return_focus_after_dismissal(None, mark, &mut *ops);
2210    }
2211
2212    /// Dispatch-path variant that threads `ops` through to the
2213    /// focus-loss handler fired during dismissal.
2214    pub fn dismiss_overlay_with_ops(
2215        &mut self,
2216        id: crate::overlay::OverlayId,
2217        ops: &mut dyn crate::window::WindowOps,
2218    ) {
2219        let mark = self.dismissal_mark();
2220        let dismissed = self.overlay_manager.dismiss(id);
2221        self.dormant_dismissed_content(&dismissed, &mut *ops);
2222        self.return_focus_after_dismissal(None, mark, &mut *ops);
2223    }
2224
2225    /// A modal just opened. Every live pointer loses its interaction: the
2226    /// surface it was working on is now behind a scrim it cannot reach, and
2227    /// the `Up` that would have completed the press lands on the modal
2228    /// instead.
2229    ///
2230    /// A modal is a `Centered` overlay — the same discriminator
2231    /// [`modal_overlay_for_widget`](Self::modal_overlay_for_widget) uses, so
2232    /// the two cannot drift. Every other placement (a menu, a popover, a
2233    /// tooltip, a drag preview) opens *over* an interaction that legitimately
2234    /// continues, and must not cancel anything.
2235    fn cancel_pointers_for_modal(&mut self, is_modal: bool) {
2236        if !is_modal {
2237            return;
2238        }
2239        let mut noop = crate::window::NoopWindowOps;
2240        self.cancel_all_pointers(crate::pointer::CancelReason::ModalOpened, &mut noop);
2241    }
2242
2243    /// Run the dismissal callbacks the overlay manager parked.
2244    ///
2245    /// The manager cannot run them itself: they take an `EventContext` and it
2246    /// has no tree. It is called from `dormant_dismissed_content`, which every
2247    /// dismissal path reaches while still holding `ops` and *before* focus
2248    /// returns to the trigger — so `on_dismiss` keeps the ordering its callers
2249    /// document and depend on (`present_in_tree_modal_request` restores the
2250    /// pre-modal `:focus-visible` modality in one, and the trigger must paint
2251    /// with the restored value).
2252    pub(super) fn run_pending_dismiss_callbacks(&mut self, ops: &mut dyn crate::window::WindowOps) {
2253        // A callback is allowed to dismiss another overlay, which parks more
2254        // and re-enters here through that overlay's own teardown. Bail on the
2255        // inner call and let the outer loop collect them: one level deep by
2256        // construction, not by luck.
2257        if self.draining_dismiss.replace(true) {
2258            return;
2259        }
2260        // Bounded rather than `while`: a pair of callbacks that dismiss each
2261        // other's overlay would otherwise spin. Eight is far above any real
2262        // cascade and the excess stays parked rather than being lost.
2263        for _ in 0..8 {
2264            let pending = self.overlay_manager.take_pending_dismiss();
2265            if pending.is_empty() {
2266                break;
2267            }
2268            for (cb, reason) in pending {
2269                self.run_with_event_context(&mut *ops, |ctx| cb(reason, ctx));
2270            }
2271        }
2272        self.draining_dismiss.set(false);
2273    }
2274
2275    pub(super) fn dormant_dismissed_content(
2276        &mut self,
2277        content_ids: &[WidgetId],
2278        ops: &mut dyn crate::window::WindowOps,
2279    ) {
2280        // Before anything is parked: the callback may still want to read the
2281        // content it is being told about, and its documented position is
2282        // during dismissal, ahead of the focus restore below.
2283        self.run_pending_dismiss_callbacks(&mut *ops);
2284        // Reset any tooltip entries that match a dismissed content
2285        // id so the next hover starts fresh — without this, sticky
2286        // tooltips dismissed via Escape/click-outside would keep
2287        // their `is_sticky` flag and stale `overlay_id`, and the
2288        // next hover would never re-show them.
2289        let mut any_tooltip_dismissed = false;
2290        for &id in content_ids {
2291            if let Some(entry) = self.tooltips.iter_mut().find(|e| e.content_id == id) {
2292                // A focus-promoted tip is dismissed while the focus that
2293                // summoned it is still in scope, and the restore below hands
2294                // that focus straight back to the anchor — which re-enters
2295                // `tooltip_focus_enter` on an entry whose `overlay_id` this
2296                // very line has just cleared. Mute it until focus genuinely
2297                // leaves, or Escape would close and reopen in one keystroke.
2298                entry.suppressed_until_focus_leaves = entry.promoted_by_focus;
2299                entry.overlay_id = None;
2300                entry.is_sticky = false;
2301                entry.hover_start = None;
2302                entry.real_hover_start = None;
2303                entry.hover_origin = None;
2304                entry.shown_at_sim = None;
2305                entry.shown_at_real = None;
2306                entry.promoted_by_focus = false;
2307                entry.armed_by_focus = false;
2308                entry.armed_by_hold = false;
2309                if let Some(sink) = entry.shown_at_sink.as_ref() {
2310                    sink.set(None);
2311                }
2312                any_tooltip_dismissed = true;
2313            }
2314        }
2315        if any_tooltip_dismissed {
2316            let grace = super::TOOLTIP_SESSION_GRACE;
2317            self.tooltip_session_until_sim = Some(self.sim_clock + grace);
2318            self.tooltip_session_until_real = Some(std::time::Instant::now() + grace);
2319        }
2320        for &id in content_ids {
2321            let focused_in_subtree = self
2322                .focused
2323                .filter(|focused| self.is_descendant_of(*focused, id));
2324            let hovered_in_subtree = self
2325                .hovered_id()
2326                .filter(|hovered| self.is_descendant_of(*hovered, id));
2327
2328            if let Some(focused) = focused_in_subtree {
2329                self.dispatch_to_widget(focused, &WidgetEvent::FocusLost, &mut *ops);
2330                if self
2331                    .focused
2332                    .is_some_and(|current| self.is_descendant_of(current, id))
2333                {
2334                    let old = self.focused;
2335                    self.set_focused(None);
2336                    self.focus_origin = None;
2337                    self.update_focus_within_signals(old, None);
2338                    self.update_view_focus_signals(old, None);
2339                }
2340            }
2341
2342            // A pointer anchored inside the overlay about to be parked would
2343            // be stranded on a widget that no longer takes events. Cancel it —
2344            // but only if there is still a press to revoke, which is what lets
2345            // a tap on a menu item whose own handler closes that menu complete
2346            // instead of cancelling itself. See `press_is_revocable`.
2347            self.cancel_pointers_in_subtree(
2348                id,
2349                crate::pointer::CancelReason::OverlayDismissed,
2350                &mut *ops,
2351            );
2352            let _parked = self.arena.set_dormant(id);
2353
2354            if hovered_in_subtree.is_some() {
2355                let old = self.hovered_id();
2356                self.set_hovered(None);
2357                self.update_hover_within_signals(old, None);
2358            }
2359        }
2360        if !content_ids.is_empty() {
2361            self.cached_frame = None;
2362            self.a11y_dirty = true;
2363            // Tell the parked content now, not at the next layout pass: a
2364            // menu reopened in the same batch of input (Escape, then Down)
2365            // would otherwise never see itself parked and keep its old row.
2366            self.flush_activation_signals();
2367        }
2368    }
2369
2370    pub fn is_visible(&self, id: WidgetId) -> bool {
2371        self.arena.is_active(id)
2372    }
2373}
2374
2375#[cfg(test)]
2376mod tests {
2377    use super::*;
2378    use crate::test_widgets::FillWidget;
2379    use crate::test_widgets::StackWidget;
2380
2381    /// The idle trace names what wakes the loop from this, so the name must
2382    /// be the earliest timer's.
2383    #[test]
2384    fn the_next_timer_deadline_is_named_for_its_timer() {
2385        let mut tree = WidgetTree::new();
2386        tree.add(FillWidget::new());
2387        tree.layout(SizeProposal::exact(100.0, 50.0));
2388        assert_eq!(tree.next_timer_deadline_source(), None, "an idle tree");
2389
2390        let blink = std::time::Instant::now() + std::time::Duration::from_millis(500);
2391        tree.request_wake_at(blink);
2392        assert_eq!(tree.next_timer_deadline_source(), Some((blink, "wake_at")));
2393        assert_eq!(tree.next_timer_deadline(), Some(blink));
2394
2395        tree.request_frame();
2396        let (at, source) = tree.next_timer_deadline_source().expect("a frame is due");
2397        assert_eq!(source, "frame_tick", "the frame is due before the blink");
2398        assert!(at < blink);
2399    }
2400
2401    #[test]
2402    fn is_visible_reflects_dormancy() {
2403        let mut tree = WidgetTree::new();
2404        let widget = tree.add(FillWidget::new());
2405        tree.layout(SizeProposal::exact(100.0, 50.0));
2406
2407        assert!(tree.is_visible(widget));
2408        tree.set_dormant(widget);
2409        assert!(!tree.is_visible(widget));
2410        tree.activate(widget);
2411        assert!(tree.is_visible(widget));
2412    }
2413
2414    #[test]
2415    fn frame_tick_deadline_caps_per_frame_effects_at_60hz() {
2416        let mut tree = WidgetTree::new();
2417        // Not armed → no per-frame-effect deadline.
2418        assert!(tree.frame_tick_deadline().is_none());
2419
2420        // Arm the per-frame-effect path (what Pulse / Cycle / caret blink
2421        // / drag auto-scroll do via `request_frame` or the render re-arm).
2422        tree.request_frame();
2423        // Pace from a known frame time so the interval is assertable.
2424        let t0 = std::time::Instant::now();
2425        tree.last_frame_time = Some(t0);
2426
2427        let deadline = tree
2428            .frame_tick_deadline()
2429            .expect("an armed per-frame effect must publish a deadline");
2430        let interval = deadline.saturating_duration_since(t0);
2431        // 60 Hz == 16.667 ms; the cap replaces the old ControlFlow::Poll
2432        // free-run (which rendered at the display's full refresh rate).
2433        assert!(
2434            interval >= std::time::Duration::from_micros(16_000)
2435                && interval <= std::time::Duration::from_micros(17_500),
2436            "per-frame effects must pace at ~60 Hz (got {interval:?})"
2437        );
2438
2439        // It must flow through next_timer_deadline so the event loop uses
2440        // WaitUntil rather than the removed Poll free-run.
2441        assert_eq!(
2442            tree.next_timer_deadline(),
2443            Some(deadline),
2444            "frame-tick deadline must be surfaced by next_timer_deadline"
2445        );
2446    }
2447
2448    #[test]
2449    fn throttled_subscriber_stretches_deadline_but_per_frame_wins_min() {
2450        use crate::test_widgets::{FillWidget, StackWidget};
2451        let mut tree = WidgetTree::new();
2452        let w = tree.add(FillWidget::new());
2453        let w2 = tree.add(FillWidget::new());
2454        tree.add(StackWidget::new().child(w).child(w2));
2455        // Cycle-style throttled subscription: wake at most once per 1.5 s.
2456        let _throttled =
2457            tree.subscribe_frame_tick_throttled(w, std::time::Duration::from_millis(1500));
2458        // Armed the way a subscription is, by a render that painted its
2459        // owner. Not by `request_frame`: that is due at 60 Hz whatever is
2460        // subscribed (`a_raw_frame_request_is_not_paced_by_a_throttled_subscriber`).
2461        tree.layout(SizeProposal::exact(200.0, 100.0));
2462        let _ = tree.render();
2463        assert!(
2464            !tree.frame_tick_requested.get(),
2465            "precondition: nothing but the subscriber wants this frame"
2466        );
2467        let t0 = tree.last_frame_time.expect("a frame has run");
2468
2469        // The render painted the subscriber, so its throttled interval governs.
2470        let d = tree.frame_tick_deadline().expect("armed");
2471        let dt = d.saturating_duration_since(t0);
2472        assert!(
2473            dt >= std::time::Duration::from_millis(1490)
2474                && dt <= std::time::Duration::from_millis(1510),
2475            "a lone throttled subscriber must pace at its interval (~1.5 s), got {dt:?}"
2476        );
2477
2478        // A per-frame subscriber pulls the subscribers' deadline back to
2479        // 60 Hz: it is the minimum interval across visible subscribers, so a
2480        // Cycle sharing a tree with a Pulse rides the Pulse's cadence. `w2`
2481        // was painted by the same render, so it counts as visible.
2482        let _per_frame = tree.subscribe_frame_tick(w2);
2483        let d2 = tree.frame_tick_deadline().expect("armed");
2484        let dt2 = d2.saturating_duration_since(t0);
2485        assert!(
2486            dt2 <= std::time::Duration::from_millis(20),
2487            "a per-frame subscriber must pull the shared deadline to 60 Hz, got {dt2:?}"
2488        );
2489    }
2490
2491    /// A throttled subscriber stretches its own wake and nothing else's. A
2492    /// caret, a drag auto-scroll or the announcer asking for one more frame
2493    /// is due at the normal 60 Hz pace even while a once-a-minute clock is on
2494    /// screen, and when that request has been served the clock is back to
2495    /// pacing alone.
2496    #[test]
2497    fn a_raw_frame_request_is_not_paced_by_a_throttled_subscriber() {
2498        use crate::test_widgets::FillWidget;
2499        const NORMAL_FRAME: std::time::Duration = std::time::Duration::from_micros(17_500);
2500        const CLOCK: std::time::Duration = std::time::Duration::from_secs(60);
2501        fn frame(tree: &mut WidgetTree) {
2502            tree.layout(SizeProposal::exact(200.0, 100.0));
2503            let _ = tree.render();
2504        }
2505        fn wait(tree: &WidgetTree) -> std::time::Duration {
2506            let deadline = tree.frame_tick_deadline().expect("armed");
2507            deadline.saturating_duration_since(tree.last_frame_time.expect("a frame has run"))
2508        }
2509
2510        let mut tree = WidgetTree::new();
2511        let clock = tree.add(FillWidget::new());
2512        let _tick = tree.subscribe_frame_tick_throttled(clock, CLOCK);
2513        frame(&mut tree);
2514        assert!(
2515            wait(&tree) >= CLOCK - NORMAL_FRAME,
2516            "precondition: the painted clock paces the loop at its own interval"
2517        );
2518
2519        // Both doors a widget reaches the flag by: the tree method, and the
2520        // shared handle stashed for use inside a tick effect.
2521        for request in [
2522            (|tree: &WidgetTree| tree.request_frame()) as fn(&WidgetTree),
2523            |tree: &WidgetTree| tree.frame_request_handle().set(true),
2524        ] {
2525            request(&tree);
2526            assert!(
2527                wait(&tree) <= NORMAL_FRAME,
2528                "a requested frame must not wait on the clock (waited {:?})",
2529                wait(&tree)
2530            );
2531            assert_eq!(tree.next_timer_deadline(), tree.frame_tick_deadline());
2532
2533            frame(&mut tree);
2534            assert!(
2535                wait(&tree) >= CLOCK - NORMAL_FRAME,
2536                "once the request is served the clock paces alone again, rather than the loop \
2537                 free-running at 60 Hz (waited {:?})",
2538                wait(&tree)
2539            );
2540        }
2541    }
2542
2543    /// The render-end re-arm has a flag of its own, so it needs what the raw
2544    /// request flag always had: `frame_requested` reports it, and each door
2545    /// that fires the tick (`layout`, and `advance_time` for a tree on
2546    /// simulated time) spends it. An arm nothing spends outlives its owner: a
2547    /// subscriber parked in a hidden `Switcher` branch would go on waking the
2548    /// loop at 60 Hz, which is the bug the scheduler exists to prevent. No
2549    /// test in the workspace failed when the arm was left unspent, when
2550    /// `frame_requested` ignored it, or when `advance_time` skipped it.
2551    #[test]
2552    fn the_subscriber_arm_is_spent_by_its_tick_and_ends_with_its_owner() {
2553        use crate::test_widgets::StackWidget;
2554        fn frame(tree: &mut WidgetTree) {
2555            tree.layout(SizeProposal::exact(200.0, 100.0));
2556            let _ = tree.render();
2557        }
2558
2559        let mut tree = WidgetTree::new();
2560        let owner = tree.add(FillWidget::new());
2561        let sibling = tree.add(FillWidget::new());
2562        tree.add(StackWidget::new().child(owner).child(sibling));
2563        let ticks = std::rc::Rc::new(std::cell::Cell::new(0_u32));
2564        let _count = tree.frame_tick().observe({
2565            let ticks = ticks.clone();
2566            move |_| ticks.set(ticks.get() + 1)
2567        });
2568        let _sub = tree.subscribe_frame_tick(owner);
2569
2570        frame(&mut tree);
2571        assert!(
2572            tree.frame_requested(),
2573            "a render that painted the subscriber arms the next tick"
2574        );
2575        assert!(
2576            !tree.frame_tick_requested.get(),
2577            "precondition: armed by the subscribers' flag, not by a raw request"
2578        );
2579
2580        // The layout door.
2581        let before = ticks.get();
2582        tree.layout(SizeProposal::exact(200.0, 100.0));
2583        assert_eq!(
2584            ticks.get(),
2585            before + 1,
2586            "the armed tick fires on the next layout"
2587        );
2588        assert!(
2589            !tree.frame_requested(),
2590            "the layout that fired the tick has spent the arm"
2591        );
2592        let _ = tree.render();
2593        assert!(
2594            tree.frame_requested(),
2595            "the owner painted again and re-armed"
2596        );
2597
2598        // The simulated-time door the automation bridge drives.
2599        let before = ticks.get();
2600        tree.advance_time(std::time::Duration::from_millis(16));
2601        assert_eq!(ticks.get(), before + 1, "advance_time fires an armed tick");
2602        assert!(
2603            !tree.frame_requested(),
2604            "advance_time spends the arm as layout does"
2605        );
2606        tree.resume_real_time();
2607
2608        // Parked, the owner stops painting. The tick it armed while visible
2609        // still runs, once, and then nothing is left to wake the loop.
2610        frame(&mut tree);
2611        tree.set_dormant(owner);
2612        assert!(
2613            tree.frame_tick_deadline().is_some(),
2614            "the tick armed before the owner was parked is still due"
2615        );
2616        let before = ticks.get();
2617        frame(&mut tree);
2618        assert_eq!(ticks.get(), before + 1);
2619        assert!(
2620            !tree.frame_requested(),
2621            "a parked subscriber must not re-arm the tick"
2622        );
2623        assert_eq!(
2624            tree.next_timer_deadline(),
2625            None,
2626            "with its only subscriber parked the loop sleeps"
2627        );
2628    }
2629
2630    #[test]
2631    fn show_and_dismiss_overlay() {
2632        let mut tree = WidgetTree::new();
2633        let anchor = tree.add(FillWidget::new());
2634        let content = tree.add(FillWidget::new().label("Overlay"));
2635        tree.layout(SizeProposal::exact(200.0, 100.0));
2636
2637        assert!(tree.active_overlays().is_empty());
2638
2639        let id = tree.show_overlay(crate::overlay::OverlayRequest::new(
2640            content,
2641            anchor,
2642            crate::overlay::OverlayPlacement::Below,
2643            crate::overlay::DismissBehavior::Manual,
2644        ));
2645
2646        assert_eq!(tree.active_overlays().len(), 1);
2647
2648        tree.dismiss_overlay(id);
2649        assert!(tree.active_overlays().is_empty());
2650        assert!(!tree.is_visible(content));
2651    }
2652
2653    /// A modal (an overlay whose placement `is_modal`) must count as a host surface so a
2654    /// `ComboBox` / menu / popover opened *inside* it — which closes via
2655    /// `dismiss_all_except_hosts` / `dismiss_self_overlay_chain_for_source` —
2656    /// dismisses only its own cascade and never tears down the hosting modal.
2657    #[test]
2658    fn modal_centered_overlay_is_a_host_surface() {
2659        let mut tree = WidgetTree::new();
2660        let anchor = tree.add(FillWidget::new());
2661        let modal_content = tree.add(FillWidget::new().label("Modal"));
2662        let dropdown_content = tree.add(FillWidget::new().label("Dropdown"));
2663        tree.layout(SizeProposal::exact(200.0, 100.0));
2664
2665        let modal = tree.show_overlay(crate::overlay::OverlayRequest::new(
2666            modal_content,
2667            anchor,
2668            crate::overlay::OverlayPlacement::Centered,
2669            crate::overlay::DismissBehavior::EscapeOrClickOutside,
2670        ));
2671        let dropdown = tree.show_overlay(
2672            crate::overlay::OverlayRequest::new(
2673                dropdown_content,
2674                anchor,
2675                crate::overlay::OverlayPlacement::Below,
2676                crate::overlay::DismissBehavior::EscapeOrClickOutside,
2677            )
2678            .parent_overlay(modal),
2679        );
2680
2681        assert!(
2682            tree.overlay_is_host_surface(modal),
2683            "a Centered modal overlay must be treated as a host surface"
2684        );
2685        assert!(
2686            !tree.overlay_is_host_surface(dropdown),
2687            "a plain dropdown overlay is not a host surface"
2688        );
2689    }
2690
2691    /// A field, and an overlay opened over it with a focusable `inside`.
2692    fn overlay_over_a_field(tree: &mut WidgetTree) -> (WidgetId, WidgetId, WidgetId) {
2693        let field = tree.add(FillWidget::new().focusable());
2694        let inside = tree.add(FillWidget::new().focusable());
2695        let content = tree.add(StackWidget::new().child(inside));
2696        tree.layout(SizeProposal::exact(200.0, 100.0));
2697        tree.focus(field);
2698        tree.show_overlay_from_source(
2699            field,
2700            crate::overlay::OverlayRequest::new(
2701                content,
2702                field,
2703                crate::overlay::OverlayPlacement::Below,
2704                crate::overlay::DismissBehavior::EscapeOrClickOutside,
2705            ),
2706        );
2707        tree.layout(SizeProposal::exact(200.0, 100.0));
2708        (field, content, inside)
2709    }
2710
2711    fn dismiss_all_except_hosts(tree: &mut WidgetTree) {
2712        tree.run_with_event_context(&mut crate::window::NoopWindowOps, |ctx| {
2713            ctx.dismiss_all_except_hosts();
2714        });
2715    }
2716
2717    /// Closing the overlays with `dismiss_all_except_hosts` while focus is in
2718    /// one gives focus back to where it was when the first of them opened, as
2719    /// Escape does, rather than leaving the window with nothing focused. A
2720    /// menu bar's menu replaced by its neighbour, or closed by a click on its
2721    /// title, goes through here.
2722    #[test]
2723    fn dismissing_all_except_hosts_gives_back_the_focus_it_took_away() {
2724        let mut tree = WidgetTree::new();
2725        let (field, content, inside) = overlay_over_a_field(&mut tree);
2726        let nested = tree.add(FillWidget::new().focusable());
2727        tree.layout(SizeProposal::exact(200.0, 100.0));
2728        tree.focus(inside);
2729        tree.show_overlay_from_source(
2730            inside,
2731            crate::overlay::OverlayRequest::new(
2732                nested,
2733                inside,
2734                crate::overlay::OverlayPlacement::Below,
2735                crate::overlay::DismissBehavior::EscapeOrClickOutside,
2736            ),
2737        );
2738        tree.focus(nested);
2739        assert!(tree.is_active(content), "precondition");
2740        dismiss_all_except_hosts(&mut tree);
2741        assert!(tree.active_overlays().is_empty());
2742        assert_eq!(tree.focused(), Some(field));
2743    }
2744
2745    /// Of several unrelated overlays, focus goes back where it was when the
2746    /// lowest opened, not where the one holding it would give it back: the
2747    /// window as it was before any of them, as closing them one by one with
2748    /// Escape would leave it.
2749    #[test]
2750    fn dismissing_all_except_hosts_gives_focus_back_as_the_lowest_overlay_found_it() {
2751        let mut tree = WidgetTree::new();
2752        let first_field = tree.add(FillWidget::new().focusable());
2753        let second_field = tree.add(FillWidget::new().focusable());
2754        let open_over = |tree: &mut WidgetTree, field: WidgetId| {
2755            let inside = tree.add(FillWidget::new().focusable());
2756            let content = tree.add(StackWidget::new().child(inside));
2757            tree.layout(SizeProposal::exact(200.0, 100.0));
2758            tree.focus(field);
2759            // Placed in the viewport, so focus leaving it does not close it.
2760            tree.show_overlay_from_source(
2761                field,
2762                crate::overlay::OverlayRequest::new(
2763                    content,
2764                    field,
2765                    crate::overlay::OverlayPlacement::BottomCenter,
2766                    crate::overlay::DismissBehavior::Manual,
2767                ),
2768            );
2769            tree.layout(SizeProposal::exact(200.0, 100.0));
2770            inside
2771        };
2772        open_over(&mut tree, first_field);
2773        let second_inside = open_over(&mut tree, second_field);
2774        tree.focus(second_inside);
2775        assert_eq!(tree.active_overlays().len(), 2, "two overlays, unrelated");
2776        dismiss_all_except_hosts(&mut tree);
2777        assert!(tree.active_overlays().is_empty());
2778        assert_eq!(
2779            tree.focused(),
2780            Some(first_field),
2781            "the lowest overlay's focus, not the top one's"
2782        );
2783    }
2784
2785    /// With focus outside the overlays they close, it stays where it is.
2786    #[test]
2787    fn dismissing_all_except_hosts_leaves_focus_outside_them_alone() {
2788        let mut tree = WidgetTree::new();
2789        let (_field, _content, _inside) = overlay_over_a_field(&mut tree);
2790        let other = tree.add(FillWidget::new().focusable());
2791        tree.layout(SizeProposal::exact(200.0, 100.0));
2792        tree.focus(other);
2793        dismiss_all_except_hosts(&mut tree);
2794        assert_eq!(tree.focused(), Some(other));
2795    }
2796
2797    #[test]
2798    fn escape_dismisses_topmost_overlay() {
2799        let mut tree = WidgetTree::new();
2800        let anchor = tree.add(FillWidget::new().focusable());
2801        let content = tree.add(FillWidget::new());
2802        tree.layout(SizeProposal::exact(200.0, 100.0));
2803        tree.focus(anchor);
2804
2805        tree.show_overlay(crate::overlay::OverlayRequest::new(
2806            content,
2807            anchor,
2808            crate::overlay::OverlayPlacement::Below,
2809            crate::overlay::DismissBehavior::EscapeOrClickOutside,
2810        ));
2811
2812        assert_eq!(tree.active_overlays().len(), 1);
2813
2814        tree.press_key(Key::Escape, Modifiers::NONE);
2815        assert!(tree.active_overlays().is_empty());
2816        assert!(!tree.is_visible(content));
2817    }
2818
2819    /// A dialog holding a field inside a container that previews Escape,
2820    /// shown with `dismiss`. Returns the dialog's content and the field, and
2821    /// counts the container's Escapes in `seen`.
2822    fn show_dialog_with_escape_preview(
2823        tree: &mut WidgetTree,
2824        takes: bool,
2825        seen: std::rc::Rc<std::cell::Cell<u32>>,
2826    ) -> (WidgetId, WidgetId) {
2827        let anchor = tree.add(FillWidget::new().focusable());
2828        let field = tree.add(FillWidget::new().focusable());
2829        let row = tree.add(crate::widget_builder::WidgetBuilder::on_key_preview(
2830            StackWidget::new().child(field),
2831            move |event, _ctx| {
2832                if let WidgetEvent::KeyDown {
2833                    key: Key::Escape, ..
2834                } = event
2835                {
2836                    seen.set(seen.get() + 1);
2837                    if takes {
2838                        return EventResponse::Handled;
2839                    }
2840                }
2841                EventResponse::Ignored
2842            },
2843        ));
2844        let content = tree.add(StackWidget::new().child(row));
2845        tree.layout(SizeProposal::exact(200.0, 100.0));
2846        tree.focus(anchor);
2847        tree.show_overlay(crate::overlay::OverlayRequest::new(
2848            content,
2849            anchor,
2850            crate::overlay::OverlayPlacement::Below,
2851            crate::overlay::DismissBehavior::EscapeKey,
2852        ));
2853        tree.focus(field);
2854        (content, field)
2855    }
2856
2857    /// An Escape preview handler between the focus and the root of the
2858    /// overlay Escape would close takes the key first: the overlay stays.
2859    #[test]
2860    fn escape_taken_inside_an_overlay_keeps_it_open() {
2861        let mut tree = WidgetTree::new();
2862        let seen = std::rc::Rc::new(std::cell::Cell::new(0));
2863        let (content, _) = show_dialog_with_escape_preview(&mut tree, true, seen.clone());
2864
2865        tree.press_key(Key::Escape, Modifiers::NONE);
2866        assert_eq!(
2867            seen.get(),
2868            1,
2869            "the handler inside the dialog heard Escape once"
2870        );
2871        assert_eq!(tree.active_overlays().len(), 1, "the dialog stays open");
2872        assert!(tree.is_visible(content));
2873    }
2874
2875    /// A preview handler that lets Escape go hears it once, and the overlay
2876    /// closes as before.
2877    #[test]
2878    fn escape_declined_inside_an_overlay_closes_it_once() {
2879        let mut tree = WidgetTree::new();
2880        let seen = std::rc::Rc::new(std::cell::Cell::new(0));
2881        let (content, _) = show_dialog_with_escape_preview(&mut tree, false, seen.clone());
2882
2883        tree.press_key(Key::Escape, Modifiers::NONE);
2884        assert_eq!(seen.get(), 1, "heard once, not again after the dismissal");
2885        assert!(tree.active_overlays().is_empty());
2886        assert!(!tree.is_visible(content));
2887    }
2888
2889    /// A popup over the focused control is the overlay Escape closes, and
2890    /// the focus is not inside it: the handler around the control is not
2891    /// asked, and the popup goes first.
2892    #[test]
2893    fn escape_closes_a_popup_over_the_focus_before_its_dialog_handler() {
2894        let mut tree = WidgetTree::new();
2895        let seen = std::rc::Rc::new(std::cell::Cell::new(0));
2896        let (dialog, field) = show_dialog_with_escape_preview(&mut tree, true, seen.clone());
2897        let popup = tree.add(FillWidget::new());
2898        tree.layout(SizeProposal::exact(200.0, 100.0));
2899        tree.show_overlay(crate::overlay::OverlayRequest::new(
2900            popup,
2901            field,
2902            crate::overlay::OverlayPlacement::Below,
2903            crate::overlay::DismissBehavior::EscapeOrClickOutside,
2904        ));
2905        tree.focus(field);
2906
2907        tree.press_key(Key::Escape, Modifiers::NONE);
2908        assert_eq!(
2909            seen.get(),
2910            0,
2911            "the popup took Escape before the row was asked"
2912        );
2913        assert!(!tree.is_visible(popup));
2914        assert!(tree.is_visible(dialog));
2915    }
2916
2917    /// Build two stacked overlays (a submenu over its parent menu) so the
2918    /// nested-overlay "back" key path (`overlay_manager.len() > 1`) is live.
2919    fn show_two_nested_overlays(tree: &mut WidgetTree) -> (WidgetId, WidgetId) {
2920        let anchor = tree.add(FillWidget::new());
2921        let c1 = tree.add(FillWidget::new());
2922        let c2 = tree.add(FillWidget::new());
2923        tree.layout(SizeProposal::exact(200.0, 100.0));
2924        let o1 = tree.show_overlay(crate::overlay::OverlayRequest::new(
2925            c1,
2926            anchor,
2927            crate::overlay::OverlayPlacement::Below,
2928            crate::overlay::DismissBehavior::Manual,
2929        ));
2930        tree.show_overlay(
2931            crate::overlay::OverlayRequest::new(
2932                c2,
2933                c1,
2934                crate::overlay::OverlayPlacement::Below,
2935                crate::overlay::DismissBehavior::Manual,
2936            )
2937            .parent_overlay(o1),
2938        );
2939        (c1, c2)
2940    }
2941
2942    #[test]
2943    fn nested_overlay_back_key_dismisses_with_arrow_left_under_ltr() {
2944        let mut tree = WidgetTree::new();
2945        let _ = show_two_nested_overlays(&mut tree);
2946        assert_eq!(tree.active_overlays().len(), 2);
2947
2948        // Wrong-direction arrow under LTR leaves both overlays open.
2949        tree.press_key(Key::ArrowRight, Modifiers::NONE);
2950        assert_eq!(tree.active_overlays().len(), 2);
2951
2952        // ArrowLeft (inline-start under LTR) closes the top nested overlay.
2953        tree.press_key(Key::ArrowLeft, Modifiers::NONE);
2954        assert_eq!(tree.active_overlays().len(), 1);
2955    }
2956
2957    #[test]
2958    fn nested_overlay_back_key_flips_to_arrow_right_under_rtl() {
2959        let mut tree = WidgetTree::new();
2960        tree.set_layout_direction(crate::environment::LayoutDirection::RightToLeft);
2961        let _ = show_two_nested_overlays(&mut tree);
2962        assert_eq!(tree.active_overlays().len(), 2);
2963
2964        // Under RTL, ArrowLeft navigates *into* a submenu — it must NOT
2965        // dismiss the top overlay.
2966        tree.press_key(Key::ArrowLeft, Modifiers::NONE);
2967        assert_eq!(tree.active_overlays().len(), 2);
2968
2969        // ArrowRight is the inline-start ("back toward parent") key in RTL.
2970        tree.press_key(Key::ArrowRight, Modifiers::NONE);
2971        assert_eq!(tree.active_overlays().len(), 1);
2972    }
2973
2974    /// An inert overlay shown over `anchor`: a value readout, say.
2975    fn show_inert_overlay(tree: &mut WidgetTree, anchor: WidgetId) -> WidgetId {
2976        let content = tree.add(FillWidget::new());
2977        tree.layout(SizeProposal::exact(200.0, 100.0));
2978        tree.show_overlay(
2979            crate::overlay::OverlayRequest::new(
2980                content,
2981                anchor,
2982                crate::overlay::OverlayPlacement::Below,
2983                crate::overlay::DismissBehavior::EscapeKey,
2984            )
2985            .inert(),
2986        );
2987        content
2988    }
2989
2990    /// An inert overlay is no cascade level. Counted, one inert overlay made a
2991    /// single open menu read as a submenu over its parent, and the back key
2992    /// closed whichever of the two was on top: the menu when the inert overlay
2993    /// was shown first, the inert overlay when it was shown last.
2994    #[test]
2995    fn back_key_does_not_count_an_inert_overlay_as_a_menu_level() {
2996        for inert_first in [true, false] {
2997            let mut tree = WidgetTree::new();
2998            let anchor = tree.add(FillWidget::new());
2999            let menu = tree.add(FillWidget::new());
3000            tree.layout(SizeProposal::exact(200.0, 100.0));
3001            let show_menu = |tree: &mut WidgetTree| {
3002                tree.show_overlay(crate::overlay::OverlayRequest::new(
3003                    menu,
3004                    anchor,
3005                    crate::overlay::OverlayPlacement::Below,
3006                    crate::overlay::DismissBehavior::Manual,
3007                ));
3008            };
3009            let inert = if inert_first {
3010                let inert = show_inert_overlay(&mut tree, anchor);
3011                show_menu(&mut tree);
3012                inert
3013            } else {
3014                show_menu(&mut tree);
3015                show_inert_overlay(&mut tree, anchor)
3016            };
3017            assert_eq!(tree.active_overlays().len(), 2);
3018
3019            tree.press_key(Key::ArrowLeft, Modifiers::NONE);
3020            assert_eq!(
3021                tree.active_overlays().len(),
3022                2,
3023                "inert shown first: {inert_first}: one menu is not a cascade"
3024            );
3025            assert!(tree.is_visible(menu) && tree.is_visible(inert));
3026        }
3027    }
3028
3029    /// Over a submenu, the back key closes the submenu, not an inert overlay
3030    /// shown after it on top of the stack.
3031    #[test]
3032    fn back_key_closes_the_submenu_beneath_an_inert_overlay() {
3033        let mut tree = WidgetTree::new();
3034        let (parent, submenu) = show_two_nested_overlays(&mut tree);
3035        let inert = show_inert_overlay(&mut tree, parent);
3036        assert_eq!(tree.active_overlays().len(), 3);
3037
3038        tree.press_key(Key::ArrowLeft, Modifiers::NONE);
3039        assert!(!tree.is_visible(submenu), "the submenu closes");
3040        assert!(tree.is_visible(parent), "its parent stays open");
3041        assert!(
3042            tree.is_visible(inert),
3043            "the inert overlay is not what closes"
3044        );
3045    }
3046
3047    /// A focusable leaf that records the keys it is handed, so a test can ask
3048    /// the question the writer actually asks: did the keystroke reach me?
3049    #[derive(Debug)]
3050    struct KeyProbe {
3051        seen: std::rc::Rc<std::cell::RefCell<Vec<Key>>>,
3052    }
3053
3054    impl Widget for KeyProbe {
3055        fn layout_response(
3056            &self,
3057            proposal: SizeProposal,
3058            _ctx: &crate::widget::LayoutContext,
3059        ) -> crate::widget::LayoutResponse {
3060            proposal.resolve(0.0, 0.0).into()
3061        }
3062
3063        fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
3064            let seen = self.seen.clone();
3065            ctx.apply_self_handlers(
3066                crate::widget_builder::HandlerSet::new()
3067                    .focusable(true)
3068                    .on_key(move |event, _ctx| match event {
3069                        WidgetEvent::KeyDown { key, .. } => {
3070                            seen.borrow_mut().push(*key);
3071                            crate::event::EventResponse::Handled
3072                        }
3073                        _ => crate::event::EventResponse::Ignored,
3074                    }),
3075            );
3076            Vec::new()
3077        }
3078    }
3079
3080    /// ⚠ The regression this exists for. Every mounted text editor keeps one
3081    /// full-viewport affordance host alive in the `TextAffordance` band for its
3082    /// selection handles. Counting those alongside menus made **two editors on
3083    /// one page** — a manuscript column and the synopsis beside it — read as a
3084    /// submenu over its parent menu, so the back key dismissed an affordance
3085    /// host and returned: ArrowLeft stopped reaching any editor in the window,
3086    /// and the writer could no longer step the caret left at all.
3087    ///
3088    /// A text affordance is not a cascade level, which is exactly what its own
3089    /// band says — the same distinction `dismissed_by_outside_press` already
3090    /// makes for presses.
3091    #[test]
3092    fn back_key_ignores_text_affordance_overlays_and_reaches_the_editor() {
3093        let mut tree = WidgetTree::new();
3094        let seen = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
3095        let editor = tree.add(KeyProbe { seen: seen.clone() });
3096        let handles_a = tree.add(FillWidget::new());
3097        let handles_b = tree.add(FillWidget::new());
3098        tree.layout(SizeProposal::exact(200.0, 100.0));
3099        tree.focus(editor);
3100
3101        // Two editors on one page: one affordance host apiece.
3102        for content in [handles_a, handles_b] {
3103            tree.show_overlay_in_band(
3104                crate::overlay::OverlayRequest::new(
3105                    content,
3106                    editor,
3107                    crate::overlay::OverlayPlacement::FullViewport,
3108                    crate::overlay::DismissBehavior::Manual,
3109                ),
3110                crate::overlay::OverlayBand::TextAffordance,
3111            );
3112        }
3113        assert_eq!(tree.active_overlays().len(), 2);
3114
3115        tree.press_key(Key::ArrowLeft, Modifiers::NONE);
3116
3117        assert_eq!(
3118            tree.active_overlays().len(),
3119            2,
3120            "a text affordance is not a menu cascade level — the back key must \
3121             leave both hosts standing"
3122        );
3123        assert_eq!(
3124            seen.borrow().as_slice(),
3125            &[Key::ArrowLeft],
3126            "ArrowLeft must reach the focused editor; swallowing it is the bug \
3127             that left the caret unable to step left in any dual-pane tab"
3128        );
3129    }
3130
3131    /// The complement: a real menu cascade still navigates back, even while
3132    /// affordance hosts are mounted beneath it. The band filter must narrow the
3133    /// count, not disable the key.
3134    #[test]
3135    fn back_key_still_closes_a_submenu_over_a_mounted_text_affordance() {
3136        let mut tree = WidgetTree::new();
3137        let affordance = tree.add(FillWidget::new());
3138        let anchor = tree.add(FillWidget::new());
3139        let menu = tree.add(FillWidget::new());
3140        let submenu = tree.add(FillWidget::new());
3141        tree.layout(SizeProposal::exact(200.0, 100.0));
3142        tree.show_overlay_in_band(
3143            crate::overlay::OverlayRequest::new(
3144                affordance,
3145                anchor,
3146                crate::overlay::OverlayPlacement::FullViewport,
3147                crate::overlay::DismissBehavior::Manual,
3148            ),
3149            crate::overlay::OverlayBand::TextAffordance,
3150        );
3151        let parent = tree.show_overlay(crate::overlay::OverlayRequest::new(
3152            menu,
3153            anchor,
3154            crate::overlay::OverlayPlacement::Below,
3155            crate::overlay::DismissBehavior::Manual,
3156        ));
3157        tree.show_overlay(
3158            crate::overlay::OverlayRequest::new(
3159                submenu,
3160                menu,
3161                crate::overlay::OverlayPlacement::Below,
3162                crate::overlay::DismissBehavior::Manual,
3163            )
3164            .parent_overlay(parent),
3165        );
3166        assert_eq!(tree.active_overlays().len(), 3);
3167
3168        tree.press_key(Key::ArrowLeft, Modifiers::NONE);
3169        assert_eq!(
3170            tree.active_overlays().len(),
3171            2,
3172            "the submenu must still close: the affordance host narrows the \
3173             count, it does not disarm the back key"
3174        );
3175    }
3176
3177    /// The back key navigates *menu* cascades only — it must never close a
3178    /// dialog/alert/modal on top. A modal is a scrim+panel overlay pair, so two
3179    /// stacked modals put two (non-host) scrims in the stack, which inflates the
3180    /// "nested menu" count; guard on the *topmost* overlay being back-navigable.
3181    #[test]
3182    fn back_key_does_not_dismiss_a_dialog_on_top_of_a_modal() {
3183        let mut tree = WidgetTree::new();
3184        let anchor = tree.add(FillWidget::new());
3185        let scrim1 = tree.add(FillWidget::new());
3186        let scrim2 = tree.add(FillWidget::new());
3187        let dialog = tree.add(FillWidget::new());
3188        tree.layout(SizeProposal::exact(200.0, 100.0));
3189        // Two non-host "scrim" overlays (as the two modals' scrims would be)…
3190        for c in [scrim1, scrim2] {
3191            tree.show_overlay(crate::overlay::OverlayRequest::new(
3192                c,
3193                anchor,
3194                crate::overlay::OverlayPlacement::Below,
3195                crate::overlay::DismissBehavior::Manual,
3196            ));
3197        }
3198        // …with a Centered (host) dialog panel on top.
3199        tree.show_overlay(crate::overlay::OverlayRequest::new(
3200            dialog,
3201            anchor,
3202            crate::overlay::OverlayPlacement::Centered,
3203            crate::overlay::DismissBehavior::Manual,
3204        ));
3205        assert_eq!(tree.active_overlays().len(), 3);
3206
3207        // The nested-menu count is 2 (the scrims), but the top is a host dialog,
3208        // so the back key must leave it alone (Escape / its buttons dismiss it).
3209        tree.press_key(Key::ArrowLeft, Modifiers::NONE);
3210        assert_eq!(
3211            tree.active_overlays().len(),
3212            3,
3213            "the back key must not close a dialog sitting on top of a modal"
3214        );
3215    }
3216
3217    #[test]
3218    fn escape_does_not_dismiss_manual_overlay() {
3219        let mut tree = WidgetTree::new();
3220        let anchor = tree.add(FillWidget::new().focusable());
3221        let content = tree.add(FillWidget::new());
3222        tree.layout(SizeProposal::exact(200.0, 100.0));
3223        tree.focus(anchor);
3224
3225        tree.show_overlay(crate::overlay::OverlayRequest::new(
3226            content,
3227            anchor,
3228            crate::overlay::OverlayPlacement::Below,
3229            crate::overlay::DismissBehavior::Manual,
3230        ));
3231
3232        assert_eq!(tree.active_overlays().len(), 1);
3233
3234        tree.press_key(Key::Escape, Modifiers::NONE);
3235        // Manual overlays should NOT be dismissed by Escape
3236        assert_eq!(tree.active_overlays().len(), 1);
3237    }
3238
3239    #[test]
3240    fn click_outside_dismisses_overlay() {
3241        let mut tree = WidgetTree::new();
3242        let anchor = tree.add(FillWidget::new());
3243        let content = tree.add(FillWidget::new());
3244        tree.layout(SizeProposal::exact(200.0, 100.0));
3245
3246        let overlay = tree.show_overlay(crate::overlay::OverlayRequest::new(
3247            content,
3248            anchor,
3249            crate::overlay::OverlayPlacement::Below,
3250            crate::overlay::DismissBehavior::ClickOutside,
3251        ));
3252
3253        tree.overlay_manager
3254            .set_content_bounds(overlay, teksilo_canvas::Size::new(100.0, 50.0));
3255
3256        assert_eq!(tree.active_overlays().len(), 1);
3257
3258        tree.dispatch_event(WidgetEvent::pointer_down(
3259            Point::new(500.0, 500.0),
3260            PointerButton::Primary,
3261            Modifiers::NONE,
3262        ));
3263        assert!(tree.active_overlays().is_empty());
3264        assert!(!tree.is_visible(content));
3265    }
3266
3267    #[test]
3268    fn cascade_dismissal() {
3269        let mut tree = WidgetTree::new();
3270        let anchor = tree.add(FillWidget::new());
3271        let content_a = tree.add(FillWidget::new());
3272        let content_b = tree.add(FillWidget::new());
3273        tree.layout(SizeProposal::exact(200.0, 100.0));
3274
3275        let parent = tree.show_overlay(crate::overlay::OverlayRequest::new(
3276            content_a,
3277            anchor,
3278            crate::overlay::OverlayPlacement::Below,
3279            crate::overlay::DismissBehavior::Manual,
3280        ));
3281        tree.show_overlay(
3282            crate::overlay::OverlayRequest::new(
3283                content_b,
3284                content_a,
3285                crate::overlay::OverlayPlacement::TrailingEdge,
3286                crate::overlay::DismissBehavior::Manual,
3287            )
3288            .parent_overlay(parent),
3289        );
3290
3291        assert_eq!(tree.active_overlays().len(), 2);
3292
3293        tree.dismiss_overlay(parent);
3294        assert!(tree.active_overlays().is_empty());
3295        assert!(!tree.is_visible(content_a));
3296        assert!(!tree.is_visible(content_b));
3297    }
3298
3299    #[test]
3300    fn dismissed_overlay_content_is_dormant_and_invisible() {
3301        let mut tree = WidgetTree::new();
3302        let anchor = tree.add(FillWidget::new());
3303        let content = tree.add(FillWidget::new());
3304        tree.layout(SizeProposal::exact(800.0, 600.0));
3305
3306        let id = tree.show_overlay(crate::overlay::OverlayRequest::new(
3307            content,
3308            anchor,
3309            crate::overlay::OverlayPlacement::Below,
3310            crate::overlay::DismissBehavior::Manual,
3311        ));
3312
3313        tree.layout(SizeProposal::exact(800.0, 600.0));
3314
3315        tree.dismiss_overlay(id);
3316        assert!(!tree.is_visible(content));
3317
3318        tree.layout(SizeProposal::exact(800.0, 600.0));
3319
3320        let center = tree.bounds(content).center();
3321        let hit = tree.hit_test(center);
3322        assert_ne!(hit, Some(content));
3323
3324        let _frame = tree.render();
3325        assert!(!tree.is_visible(content));
3326    }
3327
3328    #[test]
3329    fn tooltip_appears_after_delay() {
3330        let mut tree = WidgetTree::new();
3331        let anchor = tree.add(FillWidget::new());
3332        let tooltip = tree.add(FillWidget::new().label("Tooltip text"));
3333        tree.layout(SizeProposal::exact(200.0, 100.0));
3334
3335        tree.attach_tooltip(anchor, tooltip, std::time::Duration::from_millis(500));
3336
3337        let center = tree.bounds(anchor).center();
3338        tree.pointer_move(center);
3339        assert!(tree.active_overlays().is_empty());
3340
3341        tree.advance_time(std::time::Duration::from_millis(600));
3342
3343        assert_eq!(tree.active_overlays().len(), 1);
3344        assert!(tree.find_by_label("Tooltip text").is_some());
3345    }
3346
3347    #[test]
3348    fn tooltip_survives_theme_switch() {
3349        // Regression: switching themes used to wipe the tooltip
3350        // registry, so subsequent hovers found nothing to show. Theme
3351        // changes don't rebuild widgets (they only update the theme
3352        // signal), so the registry must be preserved.
3353        let mut tree = WidgetTree::new().with_theme(crate::presets::intui::light());
3354        let anchor = tree.add(FillWidget::new());
3355        let tooltip = tree.add(FillWidget::new().label("Tip"));
3356        tree.layout(SizeProposal::exact(200.0, 100.0));
3357
3358        tree.attach_tooltip(anchor, tooltip, std::time::Duration::from_millis(500));
3359
3360        tree.set_theme(crate::presets::intui::dark());
3361
3362        tree.pointer_move(tree.bounds(anchor).center());
3363        tree.advance_time(std::time::Duration::from_millis(600));
3364
3365        assert_eq!(tree.active_overlays().len(), 1);
3366        assert!(tree.find_by_label("Tip").is_some());
3367    }
3368
3369    #[test]
3370    fn tooltip_suppressed_when_hovering_anchor_owned_overlay_content() {
3371        // Regression: a tooltip attached to an anchor (a ComboBox, a
3372        // PopoverButton, a menu trigger, …) must not re-trigger while
3373        // the pointer is over content the anchor opened as an overlay.
3374        // Those overlays keep their content as an arena child of the
3375        // anchor (for hit-test / a11y / teardown), so a plain
3376        // descendant walk would treat hovering a dropdown row as
3377        // hovering the anchor's own chrome.
3378        let mut tree = WidgetTree::new();
3379        let anchor = tree.add(FillWidget::new());
3380        // Overlay content + a row inside it, both arena children of the
3381        // anchor — exactly the ComboBox dropdown shape.
3382        let panel = tree.add_child(anchor, FillWidget::new());
3383        let row = tree.add_child(panel, FillWidget::new());
3384        let tip = tree.add(FillWidget::new().label("Tip"));
3385        tree.layout(SizeProposal::exact(200.0, 100.0));
3386
3387        let delay = std::time::Duration::from_millis(100);
3388        tree.attach_tooltip(anchor, tip, delay);
3389
3390        // Sanity: hovering the anchor's own chrome starts the timer and
3391        // the tooltip appears.
3392        tree.tooltip_pointer_enter(anchor);
3393        tree.advance_time(delay + std::time::Duration::from_millis(50));
3394        assert_eq!(
3395            tree.active_overlays().len(),
3396            1,
3397            "tooltip should appear when hovering the anchor itself"
3398        );
3399        // Dismiss the first tooltip before the next scenario: move the pointer
3400        // away and let the 100ms hoverable grace (audit G12) expire.
3401        tree.pointer_move(Point::new(500.0, 500.0));
3402        tree.advance_time(std::time::Duration::from_millis(150));
3403        assert!(tree.active_overlays().is_empty());
3404
3405        // Open the panel as an overlay anchored to the anchor.
3406        tree.show_overlay(crate::overlay::OverlayRequest::new(
3407            panel,
3408            anchor,
3409            crate::overlay::OverlayPlacement::Below,
3410            crate::overlay::DismissBehavior::Manual,
3411        ));
3412        assert_eq!(tree.active_overlays().len(), 1);
3413
3414        // Hovering a row inside the overlay must NOT start the anchor's
3415        // tooltip: the hover lands on overlay content, not anchor chrome.
3416        tree.tooltip_pointer_enter(row);
3417        tree.advance_time(delay + std::time::Duration::from_millis(50));
3418        assert_eq!(
3419            tree.active_overlays().len(),
3420            1,
3421            "anchor tooltip must not leak onto its own overlay's rows"
3422        );
3423    }
3424
3425    #[test]
3426    fn tooltip_inside_overlay_still_fires() {
3427        // The overlay gate must not over-reach: a tooltip whose anchor
3428        // is *itself* inside the overlay (a dropdown row with its own
3429        // tooltip) still fires when that row is hovered.
3430        let mut tree = WidgetTree::new();
3431        let host = tree.add(FillWidget::new());
3432        let panel = tree.add_child(host, FillWidget::new());
3433        let row = tree.add_child(panel, FillWidget::new());
3434        let tip = tree.add(FillWidget::new().label("Row tip"));
3435        tree.layout(SizeProposal::exact(200.0, 100.0));
3436
3437        let delay = std::time::Duration::from_millis(100);
3438        // Anchor is the row, which lives inside the overlay's content.
3439        tree.attach_tooltip(row, tip, delay);
3440
3441        tree.show_overlay(crate::overlay::OverlayRequest::new(
3442            panel,
3443            host,
3444            crate::overlay::OverlayPlacement::Below,
3445            crate::overlay::DismissBehavior::Manual,
3446        ));
3447        assert_eq!(tree.active_overlays().len(), 1);
3448
3449        tree.tooltip_pointer_enter(row);
3450        tree.advance_time(delay + std::time::Duration::from_millis(50));
3451        assert_eq!(
3452            tree.active_overlays().len(),
3453            2,
3454            "a row's own tooltip should still fire inside an overlay"
3455        );
3456    }
3457
3458    #[test]
3459    fn tooltip_dismissed_on_pointer_leave() {
3460        let mut tree = WidgetTree::new();
3461        let anchor = tree.add(FillWidget::new());
3462        let tooltip = tree.add(FillWidget::new().label("Tip"));
3463        tree.layout(SizeProposal::exact(200.0, 100.0));
3464
3465        tree.attach_tooltip(anchor, tooltip, std::time::Duration::from_millis(500));
3466
3467        tree.pointer_move(tree.bounds(anchor).center());
3468        tree.advance_time(std::time::Duration::from_millis(600));
3469        assert_eq!(tree.active_overlays().len(), 1);
3470
3471        // WCAG 1.4.13 (Hoverable, audit G12): leaving the anchor no longer
3472        // dismisses instantly — the pointer might be heading toward the
3473        // tooltip. The overlay stack's 100ms PointerLeave grace owns dismissal
3474        // once the pointer is outside BOTH the anchor and the tooltip.
3475        tree.pointer_move(Point::new(500.0, 500.0));
3476        assert_eq!(
3477            tree.active_overlays().len(),
3478            1,
3479            "tooltip persists briefly after anchor-leave (hoverable grace)"
3480        );
3481        tree.advance_time(std::time::Duration::from_millis(150));
3482        assert!(
3483            tree.active_overlays().is_empty(),
3484            "tooltip dismissed after the 100ms grace outside anchor+overlay"
3485        );
3486    }
3487
3488    #[test]
3489    fn tooltip_not_shown_if_pointer_leaves_before_delay() {
3490        let mut tree = WidgetTree::new();
3491        let anchor = tree.add(FillWidget::new());
3492        let tooltip = tree.add(FillWidget::new().label("Tip"));
3493        tree.layout(SizeProposal::exact(200.0, 100.0));
3494
3495        tree.attach_tooltip(anchor, tooltip, std::time::Duration::from_millis(500));
3496
3497        tree.pointer_move(tree.bounds(anchor).center());
3498        tree.advance_time(std::time::Duration::from_millis(200));
3499        tree.pointer_move(Point::new(500.0, 500.0));
3500
3501        tree.advance_time(std::time::Duration::from_millis(500));
3502        assert!(tree.active_overlays().is_empty());
3503    }
3504
3505    #[test]
3506    fn tooltip_reshow_uses_short_delay_after_prior_tip() {
3507        // Windows TTDT_RESHOW: while a tip is open (or just dismissed), the
3508        // next anchor pays the short reshow delay, not the full initial delay.
3509        let mut tree = WidgetTree::new();
3510        let a = tree.add(FillWidget::new());
3511        let b = tree.add(FillWidget::new());
3512        let tip_a = tree.add(FillWidget::new().label("Tip A"));
3513        let tip_b = tree.add(FillWidget::new().label("Tip B"));
3514        tree.layout(SizeProposal::exact(400.0, 200.0));
3515
3516        let delay = std::time::Duration::from_millis(500);
3517        tree.attach_tooltip(a, tip_a, delay);
3518        tree.attach_tooltip(b, tip_b, delay);
3519
3520        // First tip: full initial delay (drive via enter so anchors may
3521        // share layout bounds without hit-test ambiguity).
3522        tree.tooltip_pointer_enter(a);
3523        tree.advance_time(std::time::Duration::from_millis(150));
3524        assert!(
3525            tree.active_overlays().is_empty(),
3526            "must not appear before full initial delay"
3527        );
3528        tree.advance_time(std::time::Duration::from_millis(400));
3529        assert_eq!(
3530            tree.active_overlays().len(),
3531            1,
3532            "first tip after initial delay"
3533        );
3534        assert!(tree.find_by_label("Tip A").is_some());
3535
3536        // While A is still shown the reshow session is active — B uses 100 ms.
3537        let mut noop = crate::window::NoopWindowOps;
3538        tree.tooltip_pointer_leave(a, &mut noop);
3539        tree.tooltip_pointer_enter(b);
3540        tree.advance_time(std::time::Duration::from_millis(120));
3541        assert!(
3542            tree.find_by_label("Tip B").is_some(),
3543            "second tip should use the short reshow delay while session is warm"
3544        );
3545    }
3546
3547    #[test]
3548    fn reshow_delay_reverts_to_full_after_the_session_grace_expires() {
3549        // The reshow session is a *session*: once the last tip has been gone
3550        // for TOOLTIP_SESSION_GRACE, a fresh hover is a new deliberate act and
3551        // pays the full delay again. Regression guard for a grace that is
3552        // never cleared (permanent 100 ms flash on every control) or cleared
3553        // too eagerly (the toolbar sweep loses its snappiness).
3554        let mut tree = WidgetTree::new();
3555        // Reduced motion removes the fade-out, so the dismissal — and with it
3556        // the start of the grace window — lands on the pass that dismisses
3557        // rather than on the one that finishes the tween.
3558        tree.set_accessibility_preferences(false, true, 1.0);
3559        let a = tree.add(FillWidget::new());
3560        let b = tree.add(FillWidget::new());
3561        let tip_a = tree.add(FillWidget::new().label("Tip A"));
3562        let tip_b = tree.add(FillWidget::new().label("Tip B"));
3563        tree.layout(SizeProposal::exact(400.0, 200.0));
3564
3565        let delay = std::time::Duration::from_millis(500);
3566        tree.attach_tooltip(a, tip_a, delay);
3567        tree.attach_tooltip(b, tip_b, delay);
3568
3569        // Warm the session, then close A and let the grace run out.
3570        tree.tooltip_pointer_enter(a);
3571        tree.advance_time(std::time::Duration::from_millis(550));
3572        assert!(tree.find_by_label("Tip A").is_some(), "first tip shown");
3573
3574        tree.pointer_move(Point::new(900.0, 900.0));
3575        tree.advance_time(std::time::Duration::from_millis(150));
3576        assert!(tree.active_overlays().is_empty(), "A dismissed on leave");
3577
3578        // Past the 1 s grace with nothing shown, the session is cold.
3579        tree.advance_time(super::TOOLTIP_SESSION_GRACE + std::time::Duration::from_millis(50));
3580
3581        tree.tooltip_pointer_enter(b);
3582        tree.advance_time(std::time::Duration::from_millis(150));
3583        assert!(
3584            tree.active_overlays().is_empty(),
3585            "session went cold — B must pay the FULL delay, not the 100 ms reshow"
3586        );
3587        tree.advance_time(std::time::Duration::from_millis(400));
3588        assert!(
3589            tree.find_by_label("Tip B").is_some(),
3590            "B still appears once its full delay elapses"
3591        );
3592    }
3593
3594    #[test]
3595    fn warm_reshow_scales_the_delay_rather_than_flattening_every_tier() {
3596        // The reshow shortcut is proportional (Windows TTDT_RESHOW =
3597        // TTDT_INITIAL / 5), not an absolute floor. A *heavy* 700 ms entry
3598        // exists because its content needs a longer statement of intent, so on
3599        // the warm path it must reshow at 140 ms — not collapse to the light
3600        // tier's 100 ms.
3601        let mut tree = WidgetTree::new();
3602        let light = tree.add(FillWidget::new());
3603        let heavy = tree.add(FillWidget::new());
3604        let tip_light = tree.add(FillWidget::new().label("Light"));
3605        let tip_heavy = tree.add(FillWidget::new().label("Heavy"));
3606        tree.layout(SizeProposal::exact(400.0, 200.0));
3607
3608        tree.attach_tooltip(light, tip_light, std::time::Duration::from_millis(500));
3609        tree.attach_tooltip(heavy, tip_heavy, std::time::Duration::from_millis(700));
3610
3611        // Warm the session with the light tip and leave it open.
3612        tree.tooltip_pointer_enter(light);
3613        tree.advance_time(std::time::Duration::from_millis(550));
3614        assert!(tree.find_by_label("Light").is_some(), "session warm");
3615
3616        let mut noop = crate::window::NoopWindowOps;
3617        tree.tooltip_pointer_leave(light, &mut noop);
3618        tree.tooltip_pointer_enter(heavy);
3619
3620        // 120 ms would have been enough under the old flat 100 ms clamp.
3621        tree.advance_time(std::time::Duration::from_millis(120));
3622        assert!(
3623            tree.find_by_label("Heavy").is_none(),
3624            "a heavy tooltip must not fire at the light tier's reshow delay"
3625        );
3626        // 700 * (100/500) = 140 ms.
3627        tree.advance_time(std::time::Duration::from_millis(40));
3628        assert!(
3629            tree.find_by_label("Heavy").is_some(),
3630            "heavy reshow is the scaled 140 ms"
3631        );
3632    }
3633
3634    #[test]
3635    fn a_pinned_sticky_tooltip_does_not_hold_the_session_warm() {
3636        // A sticky tip survives pointer-leave and stays up until Escape or a
3637        // click outside. Counting it as an active session would put every
3638        // other anchor on the 100 ms path for as long as it is pinned.
3639        let mut tree = WidgetTree::new();
3640        tree.set_accessibility_preferences(false, true, 1.0); // no fade deferral
3641        let a = tree.add(FillWidget::new());
3642        let b = tree.add(FillWidget::new());
3643        let tip_a = tree.add(FillWidget::new().label("Pinned"));
3644        let tip_b = tree.add(FillWidget::new().label("Other"));
3645        tree.layout(SizeProposal::exact(400.0, 200.0));
3646
3647        tree.attach_tooltip_with_sticky(
3648            a,
3649            tip_a,
3650            std::time::Duration::from_millis(500),
3651            Some(std::time::Duration::from_millis(100)),
3652        );
3653        tree.attach_tooltip(b, tip_b, std::time::Duration::from_millis(500));
3654
3655        tree.tooltip_pointer_enter(a);
3656        tree.advance_time(std::time::Duration::from_millis(550));
3657        assert!(tree.find_by_label("Pinned").is_some());
3658        tree.promote_tooltip_to_sticky(tip_a);
3659
3660        // Let the dismiss-grace from nothing elapse, then hover B.
3661        tree.advance_time(super::TOOLTIP_SESSION_GRACE + std::time::Duration::from_millis(50));
3662        tree.tooltip_pointer_enter(b);
3663        tree.advance_time(std::time::Duration::from_millis(150));
3664        assert!(
3665            tree.find_by_label("Other").is_none(),
3666            "a pinned sticky must not keep every other anchor on the reshow path"
3667        );
3668    }
3669
3670    #[test]
3671    fn reattaching_a_tooltip_does_not_grow_the_entry_table() {
3672        // `attach_tooltip*` is called from `build()`, so it re-runs on every
3673        // rebuild. An anchor owns at most one tooltip: without retirement the
3674        // table gains a dead row (and an orphaned, parentless content node) per
3675        // rebuild, forever — and it is scanned on every pointer move, four
3676        // times per layout pass, and once per widget in the a11y walk.
3677        let mut tree = WidgetTree::new();
3678        let anchor = tree.add(FillWidget::new());
3679        tree.layout(SizeProposal::exact(200.0, 100.0));
3680
3681        let delay = std::time::Duration::from_millis(100);
3682        for _ in 0..25 {
3683            // Each "rebuild" mints a fresh content widget, as `ctx.add` does.
3684            let tip = tree.add(FillWidget::new().label("Tip"));
3685            tree.attach_tooltip(anchor, tip, delay);
3686            assert_eq!(
3687                tree.tooltip_entry_count(),
3688                1,
3689                "an anchor must own exactly one tooltip entry across rebuilds"
3690            );
3691        }
3692
3693        // The surviving entry is the newest one and still works.
3694        tree.tooltip_pointer_enter(anchor);
3695        tree.advance_time(delay + std::time::Duration::from_millis(50));
3696        assert_eq!(
3697            tree.active_overlays().len(),
3698            1,
3699            "latest tooltip still shows"
3700        );
3701    }
3702
3703    #[test]
3704    fn destroying_an_anchor_reaps_its_tooltip_entry() {
3705        // The content widget is parentless (`ctx.add`), so the anchor's own
3706        // subtree teardown never reaches it.
3707        let mut tree = WidgetTree::new();
3708        let host = tree.add(FillWidget::new());
3709        let anchor = tree.add_child(host, FillWidget::new());
3710        let tip = tree.add(FillWidget::new().label("Tip"));
3711        tree.layout(SizeProposal::exact(200.0, 100.0));
3712
3713        tree.attach_tooltip(anchor, tip, std::time::Duration::from_millis(100));
3714        assert_eq!(tree.tooltip_entry_count(), 1);
3715
3716        tree.destroy_subtree(anchor);
3717        assert_eq!(
3718            tree.tooltip_entry_count(),
3719            0,
3720            "destroying the anchor must reap its entry and content node"
3721        );
3722    }
3723
3724    #[test]
3725    fn a_leaving_tooltip_schedules_a_wake_for_its_dismissal() {
3726        // The pointer's last motion event only *starts* the PointerLeave
3727        // grace. Without a deadline for its end the loop parks in
3728        // `ControlFlow::Wait` and the tooltip hangs on screen until unrelated
3729        // input redraws the window.
3730        let mut tree = WidgetTree::new();
3731        tree.set_accessibility_preferences(false, true, 1.0); // no fade deadline
3732        let anchor = tree.add(FillWidget::new());
3733        let tip = tree.add(FillWidget::new().label("Tip"));
3734        tree.layout(SizeProposal::exact(400.0, 200.0));
3735
3736        tree.attach_tooltip(anchor, tip, std::time::Duration::from_millis(100));
3737        tree.pointer_move(tree.bounds(anchor).center());
3738        tree.advance_time(std::time::Duration::from_millis(150));
3739        assert_eq!(tree.active_overlays().len(), 1, "tooltip shown");
3740
3741        // Shown, pointer still inside: nothing pending, so no deadline.
3742        assert!(
3743            tree.next_timer_deadline().is_none(),
3744            "a settled tooltip under the pointer schedules nothing"
3745        );
3746
3747        // Pointer leaves — now the 100 ms grace is running and MUST be a wake
3748        // source, or nothing will ever dismiss the tooltip on an idle app.
3749        tree.pointer_move(Point::new(900.0, 900.0));
3750        assert!(
3751            tree.next_timer_deadline().is_some(),
3752            "the PointerLeave grace must contribute a wake deadline"
3753        );
3754    }
3755
3756    /// A fading-out overlay must be a wake source in its own right.
3757    ///
3758    /// Its removal is deferred by the tween's duration and fires from
3759    /// `process_overlay_fade_dismissals_*`, which only runs when something
3760    /// wakes the loop. The tween's own scheduler deadline usually is that
3761    /// something — but the scheduler withholds a deadline for an animation
3762    /// whose owner is not being painted, and an overlay dismissed before it was
3763    /// ever rendered is exactly that. Without a term of its own the surface
3764    /// then stays on the stack, its content held active, until unrelated input
3765    /// happens to redraw the window.
3766    #[test]
3767    fn a_fading_out_overlay_schedules_a_wake_for_its_deferred_removal() {
3768        let mut tree = WidgetTree::new();
3769        let anchor = tree.add(FillWidget::new());
3770        let content = tree.add(FillWidget::new().label("Faded"));
3771        tree.layout(SizeProposal::exact(200.0, 100.0));
3772
3773        let id = tree.show_overlay(
3774            crate::overlay::OverlayRequest::new(
3775                content,
3776                anchor,
3777                crate::overlay::OverlayPlacement::Below,
3778                crate::overlay::DismissBehavior::Manual,
3779            )
3780            .with_fade(std::time::Duration::from_millis(200)),
3781        );
3782        tree.dismiss_overlay(id);
3783        assert!(
3784            tree.is_visible(content),
3785            "precondition: the removal is deferred, so there is something to wake for"
3786        );
3787
3788        // `is_some()` would pass on any of the eleven terms the fold carries,
3789        // so assert the *value*: the deadline the loop will sleep to is this
3790        // overlay's, at its fade start plus its duration. The tween's own
3791        // scheduler term is absent here — the content has never been painted,
3792        // which is the case this term exists for.
3793        let expected = tree.overlay_manager.next_fade_dismiss_deadline();
3794        assert!(
3795            expected.is_some(),
3796            "precondition: the fade start was stamped, so there is a deadline to compare against"
3797        );
3798        assert_eq!(
3799            tree.next_timer_deadline(),
3800            expected,
3801            "the wake deadline must be the deferred removal's own, not merely some deadline"
3802        );
3803    }
3804
3805    #[test]
3806    fn pressing_cancels_a_pending_dwell_and_dismisses_a_shown_tooltip() {
3807        let mut tree = WidgetTree::new();
3808        let anchor = tree.add(FillWidget::new());
3809        let tip = tree.add(FillWidget::new().label("Tip"));
3810        tree.layout(SizeProposal::exact(400.0, 200.0));
3811
3812        let delay = std::time::Duration::from_millis(500);
3813        tree.attach_tooltip(anchor, tip, delay);
3814
3815        // Press partway through the dwell: the user has answered their own
3816        // question, so the tip must not arrive afterwards.
3817        tree.pointer_move(tree.bounds(anchor).center());
3818        tree.advance_time(std::time::Duration::from_millis(300));
3819        tree.tooltip_pointer_press(None);
3820        tree.advance_time(std::time::Duration::from_millis(400));
3821        assert!(
3822            tree.active_overlays().is_empty(),
3823            "a press must cancel the pending dwell, not merely delay it"
3824        );
3825
3826        // And a press while one is shown retires it rather than leaving it
3827        // covering the control that was just clicked.
3828        tree.tooltip_pointer_enter(anchor);
3829        tree.advance_time(delay + std::time::Duration::from_millis(50));
3830        assert_eq!(tree.active_overlays().len(), 1, "tooltip shown again");
3831        tree.tooltip_pointer_press(Some(tree.bounds(anchor).center()));
3832        assert!(
3833            tree.active_overlays().is_empty(),
3834            "a press must dismiss the shown tooltip"
3835        );
3836    }
3837
3838    #[test]
3839    fn a_pointer_that_left_the_window_by_a_jump_arms_no_tooltip() {
3840        // A click on the anchor, then the pointer leaves the window with no
3841        // move inside it on the way (a fast flick, an injected jump). The next
3842        // layout pass must not re-derive hover from the last position inside
3843        // the window and start the dwell again: the tooltip would open under a
3844        // pointer that is no longer there and nothing would ever dismiss it.
3845        let mut tree = WidgetTree::new();
3846        let anchor = tree.add(FillWidget::new());
3847        let tip = tree.add(FillWidget::new().label("Tip"));
3848        tree.layout(SizeProposal::exact(400.0, 200.0));
3849        let delay = std::time::Duration::from_millis(300);
3850        tree.attach_tooltip(anchor, tip, delay);
3851
3852        let centre = tree.bounds(anchor).center();
3853        tree.pointer_move(centre);
3854        tree.dispatch_event(WidgetEvent::pointer_down(
3855            centre,
3856            PointerButton::Primary,
3857            Modifiers::NONE,
3858        ));
3859        tree.dispatch_event(WidgetEvent::pointer_up(
3860            centre,
3861            PointerButton::Primary,
3862            Modifiers::NONE,
3863        ));
3864
3865        let mut noop = crate::window::NoopWindowOps;
3866        tree.pointer_left_window(&mut noop);
3867        tree.arena.mark_needs_layout(anchor);
3868        tree.arena.mark_ancestors_need_layout(anchor);
3869        tree.layout(SizeProposal::exact(400.0, 200.0));
3870        tree.advance_time(delay * 3);
3871        assert!(
3872            tree.active_overlays().is_empty(),
3873            "no tooltip may open once the pointer has left the window"
3874        );
3875        assert_eq!(
3876            tree.pending_tooltip_count(),
3877            0,
3878            "no dwell may be left running either"
3879        );
3880
3881        // Coming back inside restores the ordinary behaviour.
3882        tree.pointer_move(Point::new(centre.x + 1.0, centre.y));
3883        tree.advance_time(delay * 2);
3884        assert_eq!(tree.active_overlays().len(), 1, "a pointer inside arms it");
3885    }
3886
3887    #[test]
3888    fn a_click_that_rebuilds_the_anchor_does_not_start_its_dwell_again() {
3889        // The click changed something and the toolbar was rebuilt under the
3890        // stationary pointer: the layout pass recovers hover for the new
3891        // button, and must not start the tooltip dwell the press just
3892        // cancelled. A tooltip that opens right after the click is the one
3893        // that then sits over the button.
3894        let mut tree = WidgetTree::new();
3895        let anchor = tree.add(FillWidget::new());
3896        let tip = tree.add(FillWidget::new().label("Tip"));
3897        tree.layout(SizeProposal::exact(400.0, 200.0));
3898        let delay = std::time::Duration::from_millis(300);
3899        tree.attach_tooltip(anchor, tip, delay);
3900
3901        let centre = tree.bounds(anchor).center();
3902        tree.pointer_move(centre);
3903        tree.dispatch_event(WidgetEvent::pointer_down(
3904            centre,
3905            PointerButton::Primary,
3906            Modifiers::NONE,
3907        ));
3908        tree.dispatch_event(WidgetEvent::pointer_up(
3909            centre,
3910            PointerButton::Primary,
3911            Modifiers::NONE,
3912        ));
3913
3914        // What a rebuild of the anchor leaves behind: no hover, a fresh entry.
3915        tree.set_hovered(None);
3916        tree.arena.mark_needs_layout(anchor);
3917        tree.arena.mark_ancestors_need_layout(anchor);
3918        tree.layout(SizeProposal::exact(400.0, 200.0));
3919        assert!(tree.hovered_id().is_some(), "hover is recovered");
3920        tree.advance_time(delay * 3);
3921        assert!(
3922            tree.active_overlays().is_empty(),
3923            "no tooltip right after a click on its anchor"
3924        );
3925
3926        // Leaving and coming back is a new hover, and it arms the dwell.
3927        tree.pointer_left_window(&mut crate::window::NoopWindowOps);
3928        tree.pointer_move(centre);
3929        tree.advance_time(delay * 2);
3930        assert_eq!(tree.active_overlays().len(), 1);
3931    }
3932
3933    #[test]
3934    fn window_deactivation_retires_hover_tooltips() {
3935        let mut tree = WidgetTree::new();
3936        let anchor = tree.add(FillWidget::new());
3937        let tip = tree.add(FillWidget::new().label("Tip"));
3938        tree.layout(SizeProposal::exact(400.0, 200.0));
3939
3940        tree.attach_tooltip(anchor, tip, std::time::Duration::from_millis(100));
3941        tree.pointer_move(tree.bounds(anchor).center());
3942        tree.advance_time(std::time::Duration::from_millis(150));
3943        assert_eq!(tree.active_overlays().len(), 1);
3944
3945        tree.set_window_active(false);
3946        assert!(
3947            tree.active_overlays().is_empty(),
3948            "a tooltip must not float over another window's chrome"
3949        );
3950    }
3951
3952    #[test]
3953    fn only_the_innermost_anchor_arms_its_dwell() {
3954        // A row inside a panel, both with tooltips. Arming both would mature
3955        // two tips and stack them on top of each other.
3956        let mut tree = WidgetTree::new();
3957        let panel = tree.add(FillWidget::new());
3958        let row = tree.add_child(panel, FillWidget::new());
3959        let panel_tip = tree.add(FillWidget::new().label("Panel"));
3960        let row_tip = tree.add(FillWidget::new().label("Row"));
3961        tree.layout(SizeProposal::exact(400.0, 200.0));
3962
3963        let delay = std::time::Duration::from_millis(100);
3964        tree.attach_tooltip(panel, panel_tip, delay);
3965        tree.attach_tooltip(row, row_tip, delay);
3966
3967        tree.tooltip_pointer_enter(row);
3968        tree.advance_time(delay + std::time::Duration::from_millis(50));
3969
3970        assert_eq!(
3971            tree.active_overlays().len(),
3972            1,
3973            "exactly one tooltip may open for a hover"
3974        );
3975        assert!(
3976            tree.find_by_label("Row").is_some(),
3977            "the innermost anchor wins"
3978        );
3979    }
3980
3981    #[test]
3982    fn escape_dismisses_a_hover_tooltip_and_falls_through_to_the_menu_below() {
3983        // WCAG 2.2 SC 1.4.13(a): hover content must be dismissible without
3984        // moving the pointer. And a tooltip raised over an open menu must not
3985        // swallow the Escape meant for the menu underneath.
3986        let mut tree = WidgetTree::new();
3987        tree.set_accessibility_preferences(false, true, 1.0); // no fade deferral
3988        let anchor = tree.add(FillWidget::new());
3989        let menu = tree.add(FillWidget::new());
3990        let tip = tree.add(FillWidget::new().label("Tip"));
3991        tree.layout(SizeProposal::exact(400.0, 200.0));
3992
3993        let menu_overlay = tree.show_overlay(crate::overlay::OverlayRequest::new(
3994            menu,
3995            anchor,
3996            crate::overlay::OverlayPlacement::Below,
3997            crate::overlay::DismissBehavior::EscapeOrClickOutside,
3998        ));
3999        assert_eq!(tree.active_overlays().len(), 1);
4000
4001        // Raise a tooltip on top of the menu.
4002        tree.attach_tooltip(anchor, tip, std::time::Duration::from_millis(100));
4003        tree.tooltip_pointer_enter(anchor);
4004        tree.advance_time(std::time::Duration::from_millis(150));
4005        assert_eq!(
4006            tree.active_overlays().len(),
4007            2,
4008            "tooltip sits above the menu"
4009        );
4010
4011        // First Escape takes the tooltip...
4012        let dismissed = tree.overlay_manager.try_dismiss_top_on_escape();
4013        assert!(dismissed.is_some(), "Escape must dismiss the hover tooltip");
4014        assert_eq!(tree.active_overlays().len(), 1);
4015
4016        // ...the second reaches the menu, which was previously unreachable.
4017        let dismissed = tree.overlay_manager.try_dismiss_top_on_escape();
4018        assert_eq!(
4019            dismissed.map(|(id, _, _)| id),
4020            Some(menu_overlay),
4021            "Escape must then reach the menu underneath"
4022        );
4023        assert!(tree.active_overlays().is_empty());
4024    }
4025
4026    #[test]
4027    fn tooltip_timer_restarts_when_pointer_keeps_moving() {
4028        // Stationary-pointer filter: travel beyond ~4 px from hover origin
4029        // restarts the delay so a sweeping cursor does not pop tips.
4030        let mut tree = WidgetTree::new();
4031        let anchor = tree.add(FillWidget::new());
4032        let tooltip = tree.add(FillWidget::new().label("Tip"));
4033        tree.layout(SizeProposal::exact(200.0, 100.0));
4034
4035        tree.attach_tooltip(anchor, tooltip, std::time::Duration::from_millis(500));
4036
4037        let start = tree.bounds(anchor).center();
4038        tree.pointer_move(start);
4039        tree.advance_time(std::time::Duration::from_millis(300));
4040        // Still pending; move well past the 4 px slop inside the same anchor.
4041        tree.pointer_move(Point::new(start.x + 20.0, start.y));
4042        // Another 300 ms would have completed the *original* 500 ms timer,
4043        // but the restart means we need a full 500 ms from the move.
4044        tree.advance_time(std::time::Duration::from_millis(300));
4045        assert!(
4046            tree.active_overlays().is_empty(),
4047            "moving past stationary slop must restart the delay"
4048        );
4049        tree.advance_time(std::time::Duration::from_millis(250));
4050        assert_eq!(
4051            tree.active_overlays().len(),
4052            1,
4053            "tooltip appears after a full delay of stillness"
4054        );
4055    }
4056
4057    #[test]
4058    fn timed_overlay_auto_dismisses_after_duration() {
4059        let mut tree = WidgetTree::new();
4060        let anchor = tree.add(FillWidget::new());
4061        let content = tree.add(FillWidget::new().label("Toast"));
4062        tree.layout(SizeProposal::exact(200.0, 100.0));
4063
4064        tree.show_overlay_for(
4065            crate::overlay::OverlayRequest::new(
4066                content,
4067                anchor,
4068                crate::overlay::OverlayPlacement::Below,
4069                crate::overlay::DismissBehavior::Manual,
4070            ),
4071            std::time::Duration::from_millis(300),
4072        );
4073
4074        assert_eq!(tree.active_overlays().len(), 1);
4075
4076        tree.advance_time(std::time::Duration::from_millis(200));
4077        assert_eq!(tree.active_overlays().len(), 1);
4078
4079        tree.advance_time(std::time::Duration::from_millis(150));
4080        assert!(tree.active_overlays().is_empty());
4081        assert!(!tree.is_visible(content));
4082    }
4083
4084    #[test]
4085    fn fade_dismiss_keeps_overlay_off_active_list_immediately() {
4086        // The user-facing `active_overlays()` accessor reports a
4087        // dismissing-with-fade overlay as gone the moment dismiss is
4088        // requested — even though the fade-out tween is still
4089        // playing under the hood. Caller code asking "is this
4090        // overlay still up?" gets the expected answer; the framework
4091        // reaps the actual content on the next layout pass past the
4092        // tween deadline.
4093        let mut tree = WidgetTree::new();
4094        let anchor = tree.add(FillWidget::new());
4095        let content = tree.add(FillWidget::new().label("Faded"));
4096        tree.layout(SizeProposal::exact(200.0, 100.0));
4097
4098        let id = tree.show_overlay(
4099            crate::overlay::OverlayRequest::new(
4100                content,
4101                anchor,
4102                crate::overlay::OverlayPlacement::Below,
4103                crate::overlay::DismissBehavior::Manual,
4104            )
4105            .with_fade(std::time::Duration::from_millis(100)),
4106        );
4107        assert_eq!(tree.active_overlays().len(), 1);
4108
4109        tree.dismiss_overlay(id);
4110        // Reported as gone immediately, even though the content
4111        // widget is still active and painting the fade-out tween —
4112        // the deferred removal happens later in
4113        // process_overlay_fade_dismissals_real.
4114        assert!(tree.active_overlays().is_empty());
4115    }
4116
4117    #[test]
4118    fn fade_dismiss_defers_content_dormancy_until_sim_tween_completes() {
4119        // Sim-clock variant of the fade-defer contract: dismiss kicks
4120        // off the fade-out tween and stamps both real- and sim-time
4121        // start markers. `advance_time` (sim-clock) past the tween
4122        // duration flushes the deferred removal via
4123        // `process_overlay_fade_dismissals_sim`.
4124        let mut tree = WidgetTree::new();
4125        let anchor = tree.add(FillWidget::new());
4126        let content = tree.add(FillWidget::new().label("Faded"));
4127        tree.layout(SizeProposal::exact(200.0, 100.0));
4128
4129        let id = tree.show_overlay(
4130            crate::overlay::OverlayRequest::new(
4131                content,
4132                anchor,
4133                crate::overlay::OverlayPlacement::Below,
4134                crate::overlay::DismissBehavior::Manual,
4135            )
4136            .with_fade(std::time::Duration::from_millis(100)),
4137        );
4138        // Move the simulated clock **before** the dismiss. Without this the
4139        // manager's mirror — seeded with `Instant::now()` at construction —
4140        // happens to agree with the tree's sim clock, and the fade start is
4141        // stamped correctly whether or not `advance_time` ever mirrors it.
4142        // A second of virtual time is what makes the mirror load-bearing.
4143        tree.advance_time(std::time::Duration::from_secs(1));
4144
4145        tree.dismiss_overlay(id);
4146        assert!(
4147            tree.is_visible(content),
4148            "content stays active during fade-out"
4149        );
4150
4151        // Less than the tween: a stale mirror would have stamped the start a
4152        // whole second in the past, and this advance would reap the content
4153        // instead of leaving it up.
4154        tree.advance_time(std::time::Duration::from_millis(60));
4155        assert!(
4156            tree.is_visible(content),
4157            "60 ms into a 100 ms tween the content is still up"
4158        );
4159
4160        tree.advance_time(std::time::Duration::from_millis(90));
4161        assert!(
4162            !tree.is_visible(content),
4163            "after sim-time past the tween window, deferred removal fires"
4164        );
4165    }
4166
4167    /// The sim-clock mirror is refreshed **before** the dismissing passes run,
4168    /// not after them.
4169    ///
4170    /// The test above pins that `advance_time` mirrors the clock at all; this
4171    /// one pins *where in the call* it does it. An overlay dismissed from
4172    /// inside `advance_time` — by its own auto-dismiss timer — reads the
4173    /// mirror as it stands at that moment. Refresh it after the dismissing
4174    /// passes and the fade start is stamped one whole advance in the past, so
4175    /// a fade longer than nothing is over before it began: the surface is
4176    /// reaped in the same virtual frame that started fading it, and the tween
4177    /// the caller asked for never plays.
4178    #[test]
4179    fn an_auto_dismissed_fade_starts_at_the_instant_the_dismiss_ran() {
4180        let mut tree = WidgetTree::new();
4181        let anchor = tree.add(FillWidget::new());
4182        let content = tree.add(FillWidget::new().label("Toast"));
4183        tree.layout(SizeProposal::exact(200.0, 100.0));
4184
4185        tree.show_overlay_for(
4186            crate::overlay::OverlayRequest::new(
4187                content,
4188                anchor,
4189                crate::overlay::OverlayPlacement::Below,
4190                crate::overlay::DismissBehavior::Manual,
4191            )
4192            .with_fade(std::time::Duration::from_millis(100)),
4193            std::time::Duration::from_millis(500),
4194        );
4195        assert_eq!(tree.active_overlays().len(), 1);
4196
4197        // One advance, well past the auto-dismiss deadline: the auto-dismiss
4198        // pass fires the dismiss, and the fade pass right after it must find a
4199        // tween that started *this* instant and has 100 ms to run.
4200        tree.advance_time(std::time::Duration::from_millis(600));
4201        assert!(
4202            tree.active_overlays().is_empty(),
4203            "precondition: the auto-dismiss fired inside this advance"
4204        );
4205        assert!(
4206            tree.is_visible(content),
4207            "the fade must start at the instant the dismiss ran, so the \
4208             content survives the frame that dismissed it"
4209        );
4210
4211        tree.advance_time(std::time::Duration::from_millis(150));
4212        assert!(
4213            !tree.is_visible(content),
4214            "and is reaped once the tween's own window has passed"
4215        );
4216    }
4217
4218    // -----------------------------------------------------------------
4219    // Inert overlays
4220    // -----------------------------------------------------------------
4221
4222    /// A leaf of a fixed size, so an overlay showing it has bounds to hit.
4223    #[derive(Debug)]
4224    struct Block(f32, f32);
4225
4226    impl Widget for Block {
4227        fn layout_response(
4228            &self,
4229            _proposal: SizeProposal,
4230            _ctx: &LayoutContext,
4231        ) -> crate::widget::LayoutResponse {
4232            teksilo_canvas::Size::new(self.0, self.1).into()
4233        }
4234    }
4235
4236    /// A 100 x 60 panel at (20, 20), and above it on the stack a 60 x 40
4237    /// overlay of `top` at `top_at`, shown [inert](crate::overlay::OverlayRequest::inert)
4238    /// when `inert` says so. Returns the tree, the panel's content and `top`.
4239    fn panel_and_an_overlay_above(
4240        panel_dismiss: crate::overlay::DismissBehavior,
4241        top: impl Widget + 'static,
4242        top_dismiss: crate::overlay::DismissBehavior,
4243        top_at: Point,
4244        inert: bool,
4245    ) -> (WidgetTree, WidgetId, WidgetId) {
4246        let mut tree = WidgetTree::new();
4247        let panel = tree.add(Block(100.0, 60.0));
4248        let top = tree.add(top);
4249        // Added last, so a walk of the arena's roots, back to front, reaches
4250        // the window before either overlay's content: only the stack can say
4251        // the panel is above it.
4252        let beneath = tree.add(FillWidget::new());
4253        tree.show_overlay(crate::overlay::OverlayRequest::new(
4254            panel,
4255            beneath,
4256            crate::overlay::OverlayPlacement::AtPointer(Point::new(20.0, 20.0)),
4257            panel_dismiss,
4258        ));
4259        let request = crate::overlay::OverlayRequest::new(
4260            top,
4261            beneath,
4262            crate::overlay::OverlayPlacement::AtPointer(top_at),
4263            top_dismiss,
4264        );
4265        tree.show_overlay(if inert { request.inert() } else { request });
4266        tree.layout(SizeProposal::exact(400.0, 200.0));
4267        (tree, panel, top)
4268    }
4269
4270    /// [`panel_and_an_overlay_above`] with a plain block shown inert: nothing
4271    /// but the request makes it so.
4272    fn panel_and_an_inert_overlay(
4273        panel_dismiss: crate::overlay::DismissBehavior,
4274        inert_dismiss: crate::overlay::DismissBehavior,
4275        inert_at: Point,
4276    ) -> (WidgetTree, WidgetId, WidgetId) {
4277        panel_and_an_overlay_above(
4278            panel_dismiss,
4279            Block(60.0, 40.0),
4280            inert_dismiss,
4281            inert_at,
4282            true,
4283        )
4284    }
4285
4286    #[test]
4287    fn an_inert_overlay_hands_the_point_to_the_overlay_beneath_it() {
4288        let (tree, panel, inert) = panel_and_an_inert_overlay(
4289            crate::overlay::DismissBehavior::Manual,
4290            crate::overlay::DismissBehavior::EscapeKey,
4291            Point::new(30.0, 30.0),
4292        );
4293        let at = Point::new(40.0, 40.0);
4294        let over = tree.overlay_manager.find_by_content(inert).unwrap();
4295        assert!(
4296            tree.overlay_content_bounds(over).unwrap().contains(at),
4297            "fixture: the inert overlay covers the point"
4298        );
4299        assert_eq!(
4300            tree.hit_test(at),
4301            Some(panel),
4302            "the panel under it takes the point, not the window under both"
4303        );
4304    }
4305
4306    #[test]
4307    fn a_press_on_an_inert_overlay_is_outside_the_overlays_it_is_outside_of() {
4308        let (mut tree, panel, inert) = panel_and_an_inert_overlay(
4309            crate::overlay::DismissBehavior::ClickOutside,
4310            crate::overlay::DismissBehavior::EscapeKey,
4311            Point::new(200.0, 100.0),
4312        );
4313        let at = Point::new(220.0, 110.0);
4314        let over = tree.overlay_manager.find_by_content(inert).unwrap();
4315        assert!(
4316            tree.overlay_content_bounds(over).unwrap().contains(at),
4317            "fixture: the press lands on the inert overlay"
4318        );
4319        tree.pointer_down_button(at, crate::event::PointerButton::Primary);
4320        assert_eq!(
4321            tree.overlay_manager.find_by_content(panel),
4322            None,
4323            "the press was outside the panel, whatever floats over that spot",
4324        );
4325    }
4326
4327    #[test]
4328    fn an_inert_overlay_is_not_an_interactive_rect() {
4329        // What a title bar carves out of the OS caption: a press there must
4330        // drag the window, bubble or not.
4331        let (tree, panel, _inert) = panel_and_an_inert_overlay(
4332            crate::overlay::DismissBehavior::Manual,
4333            crate::overlay::DismissBehavior::EscapeKey,
4334            Point::new(200.0, 100.0),
4335        );
4336        let panel_bounds = tree
4337            .overlay_content_bounds(tree.overlay_manager.find_by_content(panel).unwrap())
4338            .unwrap();
4339        assert_eq!(tree.overlay_manager.interactive_rects(), vec![panel_bounds]);
4340    }
4341
4342    #[test]
4343    fn escape_steps_over_an_inert_overlay_to_the_one_beneath() {
4344        // A `Manual` overlay stops the Escape walk, but an inert one, even a
4345        // `Manual` one, owns no key: nothing in it can be what the user meant.
4346        let (mut tree, panel, inert) = panel_and_an_inert_overlay(
4347            crate::overlay::DismissBehavior::EscapeKey,
4348            crate::overlay::DismissBehavior::Manual,
4349            Point::new(200.0, 100.0),
4350        );
4351        tree.press_key(Key::Escape, Modifiers::NONE);
4352        assert_eq!(
4353            tree.overlay_manager.find_by_content(panel),
4354            None,
4355            "the panel beneath took the Escape"
4356        );
4357        assert!(
4358            tree.overlay_manager.find_by_content(inert).is_some(),
4359            "and the inert one, which Escape may not close, is still up"
4360        );
4361    }
4362
4363    #[test]
4364    fn an_inert_overlay_over_the_window_hands_the_point_to_the_window() {
4365        // No overlay beneath to take the point, so it goes to the walk of the
4366        // arena's roots, and the inert content is a root that walk reaches
4367        // first: added after the page, it is walked before it.
4368        let mut tree = WidgetTree::new();
4369        let page = tree.add(FillWidget::new());
4370        let inert = tree.add(Block(60.0, 40.0));
4371        tree.show_overlay(
4372            crate::overlay::OverlayRequest::new(
4373                inert,
4374                page,
4375                crate::overlay::OverlayPlacement::AtPointer(Point::new(200.0, 100.0)),
4376                crate::overlay::DismissBehavior::EscapeKey,
4377            )
4378            .inert(),
4379        );
4380        tree.layout(SizeProposal::exact(400.0, 200.0));
4381        let at = Point::new(220.0, 110.0);
4382        assert!(
4383            tree.overlay_content_bounds(tree.overlay_manager.find_by_content(inert).unwrap())
4384                .unwrap()
4385                .contains(at),
4386            "fixture: the inert overlay covers the point"
4387        );
4388        assert_eq!(tree.hit_test(at), Some(page));
4389        tree.pointer_move(at);
4390        assert_eq!(tree.hovered(), Some(page), "and so does a hover");
4391    }
4392
4393    #[test]
4394    fn a_root_that_is_hit_transparent_and_pass_through_is_not_inert() {
4395        use crate::widget_builder::WidgetBuilder;
4396
4397        // The two node flags keep their own meanings, and an overlay is inert
4398        // only when its request says so. Each assertion is the counterpart of
4399        // one of the inert tests above.
4400        let flagged = || {
4401            Block(60.0, 40.0)
4402                .hit_transparent(true)
4403                .event_pass_through(true)
4404        };
4405        let at = Point::new(220.0, 110.0);
4406
4407        let (mut tree, panel, top) = panel_and_an_overlay_above(
4408            crate::overlay::DismissBehavior::ClickOutside,
4409            flagged(),
4410            crate::overlay::DismissBehavior::Manual,
4411            Point::new(200.0, 100.0),
4412            false,
4413        );
4414        let over = tree.overlay_manager.find_by_content(top).unwrap();
4415        assert!(
4416            tree.overlay_content_bounds(over).unwrap().contains(at),
4417            "fixture: the press lands on the flagged overlay"
4418        );
4419        assert_eq!(
4420            tree.overlay_manager.hit_test(at),
4421            Some(over),
4422            "the stack still answers with the overlay"
4423        );
4424        assert_eq!(
4425            tree.overlay_manager.interactive_rects().len(),
4426            2,
4427            "which is an interactive rect"
4428        );
4429        tree.pointer_down_button(at, crate::event::PointerButton::Primary);
4430        tree.pointer_up_button(at, crate::event::PointerButton::Primary);
4431        assert!(
4432            tree.overlay_manager.find_by_content(panel).is_some(),
4433            "a press on it is inside the stack, so the panel beneath stays"
4434        );
4435
4436        let (mut tree, panel, top) = panel_and_an_overlay_above(
4437            crate::overlay::DismissBehavior::EscapeKey,
4438            flagged(),
4439            crate::overlay::DismissBehavior::Manual,
4440            Point::new(200.0, 100.0),
4441            false,
4442        );
4443        tree.press_key(Key::Escape, Modifiers::NONE);
4444        assert!(
4445            tree.overlay_manager.find_by_content(panel).is_some()
4446                && tree.overlay_manager.find_by_content(top).is_some(),
4447            "a `Manual` overlay owns the Escape: nothing beneath it closes"
4448        );
4449
4450        let (mut tree, panel, top) = panel_and_an_overlay_above(
4451            crate::overlay::DismissBehavior::EscapeKey,
4452            flagged(),
4453            crate::overlay::DismissBehavior::EscapeKey,
4454            Point::new(200.0, 100.0),
4455            false,
4456        );
4457        tree.press_key(Key::Escape, Modifiers::NONE);
4458        assert_eq!(
4459            tree.overlay_manager.find_by_content(top),
4460            None,
4461            "an `EscapeKey` one is what the Escape closes"
4462        );
4463        assert!(
4464            tree.overlay_manager.find_by_content(panel).is_some(),
4465            "and it is spent there"
4466        );
4467    }
4468
4469    #[test]
4470    fn an_inert_overlay_records_no_focus_to_give_back_on_any_show_path() {
4471        type Show = fn(&mut WidgetTree, crate::overlay::OverlayRequest, WidgetId);
4472        fn from_a_handler(
4473            tree: &mut WidgetTree,
4474            show: impl FnOnce(&mut crate::widget::EventContext),
4475        ) {
4476            tree.run_with_event_context(&mut crate::window::NoopWindowOps, show);
4477        }
4478        let paths: [(&str, Show); 5] = [
4479            ("show_overlay", |tree, request, _| {
4480                from_a_handler(tree, |ctx| ctx.show_overlay(request))
4481            }),
4482            ("show_overlay_for", |tree, request, _| {
4483                from_a_handler(tree, |ctx| {
4484                    ctx.show_overlay_for(request, std::time::Duration::from_secs(60))
4485                })
4486            }),
4487            ("show_overlay_with_reveal", |tree, request, _| {
4488                from_a_handler(tree, |ctx| {
4489                    ctx.show_overlay_with_reveal(
4490                        request,
4491                        crate::signal::Signal::new(0.0),
4492                        std::time::Duration::from_millis(100),
4493                    )
4494                })
4495            }),
4496            ("show_overlay_after", |tree, request, _| {
4497                from_a_handler(tree, |ctx| {
4498                    ctx.show_overlay_after(request, std::time::Duration::ZERO)
4499                });
4500                tree.layout(SizeProposal::exact(400.0, 200.0));
4501            }),
4502            ("show_overlay_from_source", |tree, request, field| {
4503                tree.show_overlay_from_source(field, request);
4504            }),
4505        ];
4506        for (path, show) in paths {
4507            let mut tree = WidgetTree::new();
4508            let field = tree.add(FillWidget::new().focusable());
4509            let inert = tree.add(Block(60.0, 40.0));
4510            let ordinary = tree.add(Block(60.0, 40.0));
4511            tree.layout(SizeProposal::exact(400.0, 200.0));
4512            tree.focus(field);
4513            for (content, inert) in [(inert, true), (ordinary, false)] {
4514                let request = crate::overlay::OverlayRequest::new(
4515                    content,
4516                    field,
4517                    crate::overlay::OverlayPlacement::AtPointer(Point::new(20.0, 20.0)),
4518                    crate::overlay::DismissBehavior::EscapeKey,
4519                );
4520                show(
4521                    &mut tree,
4522                    if inert { request.inert() } else { request },
4523                    field,
4524                );
4525            }
4526            let restore = |content: WidgetId| {
4527                tree.overlay_manager
4528                    .stack
4529                    .iter()
4530                    .find(|o| o.content_id == content)
4531                    .map(|o| o.focus_restore)
4532            };
4533            assert_eq!(
4534                restore(ordinary),
4535                Some(Some(field)),
4536                "{path}: an ordinary one does"
4537            );
4538            assert_eq!(
4539                restore(inert),
4540                Some(None),
4541                "{path}: an inert one took no focus"
4542            );
4543        }
4544    }
4545}