Skip to main content

repose_core/
runtime.rs

1use std::any::Any;
2use std::cell::RefCell;
3use std::collections::HashSet;
4use std::panic::Location;
5use std::rc::Rc;
6use std::sync::atomic::{AtomicU64, Ordering};
7
8use rustc_hash::{FxHashMap, FxHashSet};
9
10use crate::effects::Dispose;
11use crate::scope::Scope;
12use crate::{
13    CursorGrabMode, CursorIcon, Rect, Scene, View,
14    input::{GamepadPad, PhysicalKey},
15    semantics::Role,
16};
17
18thread_local! {
19    pub static COMPOSER: RefCell<Composer> = RefCell::new(Composer::default());
20    static ROOT_SCOPE: RefCell<Option<Scope>> = const { RefCell::new(None) };
21    static INITIALIZER_STACK: RefCell<Vec<InitializerKind>> =
22        const { RefCell::new(Vec::new()) };
23    static PENDING_INITIALIZER_CURSOR: RefCell<Option<usize>> =
24        const { RefCell::new(None) };
25    static KEYED_DISPOSERS: RefCell<FxHashMap<String, KeyedDisposerEntry>> =
26        RefCell::new(FxHashMap::default());
27    static KEYED_DISPOSER_ORDER: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
28    static PENDING_KEYED_REGISTRATIONS: RefCell<Vec<(String, Dispose, String)>> =
29        const { RefCell::new(Vec::new()) };
30
31    /// Programmatic focus requests queued by `FocusRequester`. A queue (not a
32    /// single slot) so multiple requests in one frame are honored in order
33    /// instead of last-wins. `CLEAR_FOCUS_MARKER` entries clear focus.
34    static FOCUS_REQUESTS: RefCell<std::collections::VecDeque<u64>> =
35        const { RefCell::new(std::collections::VecDeque::new()) };
36
37    /// Captured-focus lock (`FocusRequester::capture_focus`). While set,
38    /// queued requests for other targets are denied and focus stays pinned.
39    static FOCUS_CAPTURED: RefCell<Option<u64>> = const { RefCell::new(None) };
40
41    /// Focusable view ids in declaration/layout order, captured by paint before
42    /// hit regions are reordered by z-index for hit testing.
43    static FOCUS_ORDER: RefCell<Option<Vec<u64>>> = const { RefCell::new(None) };
44
45    /// Programmatic bring-into-view requests queued by `BringIntoViewRequester`.
46    /// Ids are drained once per frame by the app runtime and resolved against
47    /// the previous frame's hit regions before the next frame is composed.
48    static BRING_INTO_VIEW_REQUESTS: RefCell<std::collections::VecDeque<u64>> =
49        const { RefCell::new(std::collections::VecDeque::new()) };
50}
51
52pub const CLEAR_FOCUS_MARKER: u64 = u64::MAX;
53
54const ROOT_OWNER: &str = "\0repose:root-owner";
55
56struct KeyedDisposerEntry {
57    disposer: Dispose,
58    owners: FxHashSet<String>,
59}
60
61enum InitializerKind {
62    Sequential,
63    Keyed,
64}
65
66pub(crate) fn scope_owner_token(scope: Option<&str>) -> String {
67    match scope {
68        Some(scope) if !scope.is_empty() => scope.to_string(),
69        _ => ROOT_OWNER.to_string(),
70    }
71}
72
73fn queue_keyed_registration(key: String, disposer: Dispose, owner: String) {
74    let queued = PENDING_KEYED_REGISTRATIONS.try_with(|pending| {
75        pending.try_borrow_mut().ok().map(|mut pending| {
76            pending.push((key, disposer, owner));
77            true
78        })
79    });
80    if !matches!(queued, Ok(Some(true))) {
81        crate::request_frame();
82    }
83}
84
85pub(crate) fn flush_keyed_disposer_registrations() {
86    let pending = PENDING_KEYED_REGISTRATIONS.try_with(|pending| {
87        pending
88            .try_borrow_mut()
89            .ok()
90            .map(|mut pending| std::mem::take(&mut *pending))
91    });
92    let Ok(Some(pending)) = pending else {
93        crate::request_frame();
94        return;
95    };
96    for (key, disposer, owner) in pending {
97        register_keyed_disposer_for_owner(key, disposer, owner);
98    }
99}
100
101pub(crate) fn register_keyed_disposer(key: String, disposer: Dispose) {
102    let owner = scope_owner_token(crate::scope_cache::current_scope_key().as_deref());
103    register_keyed_disposer_for_owner(key, disposer, owner);
104}
105
106pub(crate) fn register_keyed_disposer_for_owner(key: String, disposer: Dispose, owner: String) {
107    let result = KEYED_DISPOSERS
108        .try_with(|registry| {
109            let mut registry = match registry.try_borrow_mut() {
110                Ok(registry) => registry,
111                Err(_) => return Err(()),
112            };
113            if let Some(entry) = registry.get_mut(&key) {
114                if entry.owners.contains(&owner) && !entry.disposer.ptr_eq(&disposer) {
115                    let previous = std::mem::replace(&mut entry.disposer, disposer.clone());
116                    return Ok((false, Some(previous)));
117                }
118                entry.owners.insert(owner.clone());
119                return Ok((false, None));
120            }
121            registry.insert(
122                key.clone(),
123                KeyedDisposerEntry {
124                    disposer: disposer.clone(),
125                    owners: FxHashSet::from_iter([owner.clone()]),
126                },
127            );
128            Ok((true, None))
129        })
130        .ok();
131    match result {
132        Some(Ok((true, previous))) => {
133            let _ = KEYED_DISPOSER_ORDER.try_with(|order| {
134                if let Ok(mut order) = order.try_borrow_mut()
135                    && !order.iter().any(|registered| registered == &key)
136                {
137                    order.push(key.clone());
138                }
139            });
140            drop(previous);
141        }
142        Some(Ok((false, previous))) => {
143            if let Some(previous) = previous {
144                run_keyed_disposer(previous);
145            }
146        }
147        Some(Err(())) | None => queue_keyed_registration(key, disposer, owner),
148    }
149}
150
151pub(crate) fn keyed_disposer_has_owner(key: &str, disposer: &Dispose, owner: &str) -> bool {
152    KEYED_DISPOSERS
153        .try_with(|registry| {
154            registry.try_borrow().ok().and_then(|registry| {
155                registry
156                    .get(key)
157                    .filter(|entry| entry.disposer.ptr_eq(disposer))
158                    .map(|entry| entry.owners.contains(owner))
159            })
160        })
161        .ok()
162        .flatten()
163        .unwrap_or(false)
164}
165
166pub(crate) fn remove_keyed_disposer_for_owner(key: &str, disposer: &Dispose, owner: &str) -> bool {
167    let mut to_run = None;
168    let mut owner_removed = false;
169    let mut registry_removed = false;
170    let result = KEYED_DISPOSERS.try_with(|registry| {
171        let mut registry = match registry.try_borrow_mut() {
172            Ok(registry) => registry,
173            Err(_) => return false,
174        };
175        let Some(entry) = registry.get_mut(key) else {
176            return true;
177        };
178        if !entry.disposer.ptr_eq(disposer) {
179            return true;
180        }
181        owner_removed = entry.owners.remove(owner);
182        if entry.owners.is_empty()
183            && let Some(entry) = registry.remove(key)
184        {
185            to_run = Some(entry.disposer);
186            registry_removed = true;
187        }
188        true
189    });
190    if !matches!(result, Ok(true)) {
191        queue_keyed_registration(key.to_string(), disposer.clone(), owner.to_string());
192        return false;
193    }
194    if registry_removed {
195        let _ = KEYED_DISPOSER_ORDER.try_with(|order| {
196            if let Ok(mut order) = order.try_borrow_mut() {
197                order.retain(|registered| registered != key);
198            }
199        });
200    }
201    if let Some(disposer) = to_run {
202        run_keyed_disposer(disposer);
203        true
204    } else {
205        owner_removed
206    }
207}
208
209pub(crate) fn take_keyed_disposer(key: &str) -> Option<Dispose> {
210    let disposer = KEYED_DISPOSERS
211        .try_with(|registry| {
212            registry
213                .try_borrow_mut()
214                .ok()?
215                .remove(key)
216                .map(|entry| entry.disposer)
217        })
218        .ok()
219        .flatten();
220    if disposer.is_some() {
221        let _ = KEYED_DISPOSER_ORDER.try_with(|order| {
222            if let Ok(mut order) = order.try_borrow_mut() {
223                order.retain(|registered| registered != key);
224            }
225        });
226    }
227    disposer
228}
229
230pub(crate) fn take_all_keyed_disposers() -> Vec<Dispose> {
231    flush_keyed_disposer_registrations();
232    let order = KEYED_DISPOSER_ORDER
233        .try_with(|order| {
234            order
235                .try_borrow_mut()
236                .ok()
237                .map(|mut order| std::mem::take(&mut *order))
238        })
239        .ok()
240        .flatten()
241        .unwrap_or_default();
242
243    KEYED_DISPOSERS
244        .try_with(|registry| {
245            registry.try_borrow_mut().ok().map(|mut registry| {
246                let mut result = Vec::with_capacity(registry.len());
247                for key in order.into_iter().rev() {
248                    if let Some(entry) = registry.remove(&key) {
249                        result.push(entry.disposer);
250                    }
251                }
252                result.extend(registry.drain().map(|(_, entry)| entry.disposer));
253                result
254            })
255        })
256        .ok()
257        .flatten()
258        .unwrap_or_default()
259}
260
261pub(crate) fn run_keyed_disposer(disposer: Dispose) {
262    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| disposer.run()));
263}
264
265/// Process-wide unique id for namespacing `remember_with_key` slots
266/// (dialogs, menus, sheets, tooltips, ...).
267static COMPONENT_ID: AtomicU64 = AtomicU64::new(1);
268
269/// Returns a fresh unique component id. See [`COMPONENT_ID`].
270pub fn unique_component_id() -> u64 {
271    COMPONENT_ID.fetch_add(1, Ordering::Relaxed)
272}
273
274pub fn take_focus_request() -> Option<u64> {
275    FOCUS_REQUESTS.with(|r| r.borrow_mut().pop_front())
276}
277
278/// Drain all queued focus requests in FIFO order.
279///
280/// While a capture lock is held, requests for other targets are denied and
281/// the captured id is returned instead, pinning focus.
282pub fn drain_focus_requests() -> Vec<u64> {
283    if let Some(captured) = FOCUS_CAPTURED.with(|c| *c.borrow()) {
284        FOCUS_REQUESTS.with(|r| r.borrow_mut().clear());
285        return vec![captured];
286    }
287    FOCUS_REQUESTS.with(|r| r.borrow_mut().drain(..).collect())
288}
289
290/// Enqueue a bring-into-view request for a view id. The request is consumed
291/// once, on the next frame, against the most recently painted hit regions.
292pub fn queue_bring_into_view(id: u64) {
293    BRING_INTO_VIEW_REQUESTS.with(|r| r.borrow_mut().push_back(id));
294}
295
296/// Drain all queued bring-into-view requests in FIFO order.
297pub fn drain_bring_into_view_requests() -> Vec<u64> {
298    BRING_INTO_VIEW_REQUESTS.with(|r| r.borrow_mut().drain(..).collect())
299}
300
301/// Currently captured focus target, if any.
302pub fn focus_capture() -> Option<u64> {
303    FOCUS_CAPTURED.with(|c| *c.borrow())
304}
305
306/// Record the focusable ids in declaration/layout order for the frame being
307/// painted. Called by the layout engine before hit regions are reordered for
308/// hit testing.
309pub fn set_focus_order(order: Vec<u64>) {
310    FOCUS_ORDER.with(|o| *o.borrow_mut() = Some(order));
311}
312
313/// Take the focus order captured by the last paint, if any.
314pub fn take_focus_order() -> Option<Vec<u64>> {
315    FOCUS_ORDER.with(|o| o.borrow_mut().take())
316}
317
318/// A handle that can programmatically request focus for a widget.
319///
320/// Similar to Compose's `FocusRequester`. Create one via `remember(FocusRequester::new)`,
321/// attach it via `.focus_requester(...)` on a modifier, and call `request_focus()` to
322/// move keyboard focus to the associated widget on the next frame.
323#[derive(Clone)]
324pub struct FocusRequester {
325    /// Target view ID, set during layout/paint by the modifier system.
326    pub target: Rc<RefCell<Option<u64>>>,
327}
328
329impl FocusRequester {
330    pub fn new() -> Self {
331        Self {
332            target: Rc::new(RefCell::new(None)),
333        }
334    }
335
336    /// Request focus for the associated widget on the next frame.
337    /// Queued; unlike the old single-slot behavior, multiple requests in one
338    /// frame are all honored in order. If the target is not laid out yet the
339    /// request is dropped (target assigned during layout/paint).
340    pub fn request_focus(&self) {
341        let _ = self.try_request_focus();
342    }
343
344    /// Enqueue a focus request, reporting whether it was accepted.
345    /// Returns `false` when the target is not laid out yet (request dropped)
346    /// or when another target holds the capture lock.
347    pub fn try_request_focus(&self) -> bool {
348        let Some(id) = *self.target.borrow() else {
349            return false;
350        };
351        if let Some(captured) = FOCUS_CAPTURED.with(|c| *c.borrow())
352            && captured != id
353        {
354            return false;
355        }
356        FOCUS_REQUESTS.with(|r| r.borrow_mut().push_back(id));
357        true
358    }
359
360    /// Request focus for the associated widget from a traversal direction.
361    /// Directional enter delegation is not implemented (focus targets are
362    /// flat, not containers), so this behaves like [`try_request_focus`](Self::try_request_focus)
363    /// and reports acceptance the same way.
364    pub fn request_focus_directed(&self, _direction: FocusDirection) -> bool {
365        self.try_request_focus()
366    }
367
368    /// Free/clear focus from the associated widget on the next frame.
369    /// If the associated widget currently has focus, focus is cleared entirely.
370    /// Corresponds to Compose's `freeFocus()`. Releases this target's capture
371    /// lock when held.
372    pub fn free_focus(&self) {
373        if let Some(id) = *self.target.borrow() {
374            FOCUS_CAPTURED.with(|c| {
375                if *c.borrow() == Some(id) {
376                    *c.borrow_mut() = None;
377                }
378            });
379        }
380        FOCUS_REQUESTS.with(|r| r.borrow_mut().push_back(CLEAR_FOCUS_MARKER));
381    }
382
383    /// Capture focus for the associated widget: focus moves to the target and
384    /// stays pinned there until [`free_focus`](Self::free_focus). Other
385    /// targets' requests are denied while the lock is held.
386    /// Returns `false` when the target is not laid out yet.
387    pub fn capture_focus(&self) -> bool {
388        let Some(id) = *self.target.borrow() else {
389            return false;
390        };
391        FOCUS_CAPTURED.with(|c| *c.borrow_mut() = Some(id));
392        FOCUS_REQUESTS.with(|r| r.borrow_mut().push_back(id));
393        true
394    }
395}
396
397impl Default for FocusRequester {
398    fn default() -> Self {
399        Self::new()
400    }
401}
402
403/// A handle that can programmatically scroll a widget into view.
404///
405/// Create one via `remember(BringIntoViewRequester::new)`, attach it with
406/// `Modifier::bring_into_view(requester)`, and call [`request`](Self::request)
407/// to scroll the attached widget into view on the next frame. The runtime
408/// resolves the target against the current frame and walks its ancestor scroll
409/// containers, dispatching the scroll deltas needed to reveal it.
410#[derive(Clone)]
411pub struct BringIntoViewRequester {
412    /// Target view id, assigned during layout/paint by the modifier system.
413    pub target: Rc<RefCell<Option<u64>>>,
414}
415
416impl BringIntoViewRequester {
417    pub fn new() -> Self {
418        Self {
419            target: Rc::new(RefCell::new(None)),
420        }
421    }
422
423    /// Request that the associated widget be scrolled into view.
424    ///
425    /// Queued: the request is resolved on the next frame. If the modifier has
426    /// not been laid out yet the request is dropped.
427    pub fn request(&self) {
428        let _ = self.try_request();
429    }
430
431    /// Enqueue the request, reporting whether a target was available.
432    pub fn try_request(&self) -> bool {
433        let Some(id) = *self.target.borrow() else {
434            return false;
435        };
436        queue_bring_into_view(id);
437        true
438    }
439
440    /// Assign the view id this requester is attached to. Called by layout.
441    pub fn set_target(&self, id: u64) {
442        *self.target.borrow_mut() = Some(id);
443    }
444
445    /// Drop the current target (e.g. when the widget leaves the tree).
446    pub fn clear_target(&self) {
447        *self.target.borrow_mut() = None;
448    }
449}
450
451impl Default for BringIntoViewRequester {
452    fn default() -> Self {
453        Self::new()
454    }
455}
456
457/// Direction for focus movement.
458#[derive(Clone, Copy, Debug, PartialEq, Eq)]
459pub enum FocusDirection {
460    Next,
461    Previous,
462    Left,
463    Right,
464    Up,
465    Down,
466}
467
468/// A manager for programmatic focus navigation.
469///
470/// Wraps a `&Scheduler` and provides methods to move focus.
471/// Can also be used standalone with a focus chain and focused element.
472#[derive(Clone)]
473pub struct FocusManager {
474    /// The ordered list of focusable element IDs.
475    pub chain: Vec<u64>,
476    /// The currently focused element (if any).
477    pub focused: Option<u64>,
478    /// Hit regions for focus group lookups.
479    pub hit_regions: Vec<HitRegion>,
480}
481
482impl FocusManager {
483    pub fn new(chain: Vec<u64>, focused: Option<u64>) -> Self {
484        Self {
485            chain,
486            focused,
487            hit_regions: Vec::new(),
488        }
489    }
490
491    /// Move focus in the given direction.
492    /// Returns the new focused element ID, or `None` if no movement is possible.
493    pub fn move_focus(&mut self, dir: FocusDirection) -> Option<u64> {
494        match dir {
495            FocusDirection::Next | FocusDirection::Previous => {
496                self.move_tab(dir == FocusDirection::Previous)
497            }
498            _ => None, // use move_focus_spatial when hit regions are available
499        }
500    }
501
502    /// Clears focus entirely on the next frame.
503    /// Corresponds to Compose's `FocusManager.clearFocus()`.
504    /// The `force` parameter is accepted for API compatibility. In repose
505    /// focus is always cleared immediately (no keep-focus mechanism).
506    pub fn clear_focus(&self, _force: bool) {
507        FOCUS_REQUESTS.with(|r| r.borrow_mut().push_back(CLEAR_FOCUS_MARKER));
508    }
509
510    /// Spatial focus navigation: find the closest focusable element in a given
511    /// direction using bounding rect geometry.
512    pub fn move_focus_spatial(
513        &mut self,
514        dir: FocusDirection,
515        hit_regions: &[HitRegion],
516    ) -> Option<u64> {
517        let next = spatial_focus_next(&self.chain, hit_regions, self.focused, dir)?;
518        self.focused = Some(next);
519        Some(next)
520    }
521
522    /// Tab forward or backward in the focus chain.
523    /// When the current focus belongs to a focus group, navigation is restricted
524    /// to elements within that group.
525    pub fn move_tab(&mut self, reverse: bool) -> Option<u64> {
526        if self.chain.is_empty() {
527            return None;
528        }
529        let next = if let Some(sub_chain) =
530            focus_group_chain(&self.chain, &self.hit_regions, self.focused)
531        {
532            if sub_chain.is_empty() {
533                return None;
534            }
535            if let Some(cur) = self.focused {
536                if let Some(idx) = sub_chain.iter().position(|&id| id == cur) {
537                    if reverse {
538                        if idx == 0 {
539                            sub_chain[sub_chain.len() - 1]
540                        } else {
541                            sub_chain[idx - 1]
542                        }
543                    } else {
544                        sub_chain[(idx + 1) % sub_chain.len()]
545                    }
546                } else {
547                    sub_chain[0]
548                }
549            } else if reverse {
550                sub_chain[sub_chain.len() - 1]
551            } else {
552                sub_chain[0]
553            }
554        } else {
555            if let Some(cur) = self.focused {
556                if let Some(idx) = self.chain.iter().position(|&id| id == cur) {
557                    if reverse {
558                        if idx == 0 {
559                            self.chain[self.chain.len() - 1]
560                        } else {
561                            self.chain[idx - 1]
562                        }
563                    } else {
564                        self.chain[(idx + 1) % self.chain.len()]
565                    }
566                } else {
567                    self.chain[0]
568                }
569            } else if reverse {
570                self.chain[self.chain.len() - 1]
571            } else {
572                self.chain[0]
573            }
574        };
575        self.focused = Some(next);
576        Some(next)
577    }
578
579    /// Set target ID on a FocusRequester (called during layout).
580    pub fn set_requester_target(requester: &FocusRequester, id: u64) {
581        *requester.target.borrow_mut() = Some(id);
582    }
583}
584
585/// Sub-chain of ids sharing the focused element's focus group.
586/// Returns `None` when focus is outside any group (full chain applies).
587/// Tab and spatial navigation both scope to this so modals trap focus.
588pub fn focus_group_chain(
589    chain: &[u64],
590    hit_regions: &[HitRegion],
591    current: Option<u64>,
592) -> Option<Vec<u64>> {
593    let cur = current?;
594    let group_id = hit_regions.iter().find(|h| h.id == cur)?.focus_group_id?;
595    Some(
596        chain
597            .iter()
598            .copied()
599            .filter(|&id| {
600                id == group_id
601                    || hit_regions
602                        .iter()
603                        .any(|h| h.id == id && h.focus_group_id == Some(group_id))
604            })
605            .collect(),
606    )
607}
608
609/// Find the next focusable element in a given spatial direction.
610///
611/// Uses the bounding rects from `hit_regions` to determine which element is
612/// "next" in the given direction from the currently focused element.
613pub fn spatial_focus_next(
614    chain: &[u64],
615    hit_regions: &[HitRegion],
616    current: Option<u64>,
617    dir: FocusDirection,
618) -> Option<u64> {
619    if chain.is_empty() {
620        return None;
621    }
622
623    let current_rect =
624        current.and_then(|id| hit_regions.iter().find(|h| h.id == id).map(|h| h.rect));
625
626    // For Next/Previous, use tab-order navigation
627    match dir {
628        FocusDirection::Next | FocusDirection::Previous => {
629            let mut fm = FocusManager {
630                chain: chain.to_vec(),
631                focused: current,
632                hit_regions: hit_regions.to_vec(),
633            };
634            return fm.move_tab(dir == FocusDirection::Previous);
635        }
636        _ => {}
637    }
638
639    let (cx, cy) = match current_rect {
640        Some(r) => (r.x + r.w / 2.0, r.y + r.h / 2.0),
641        None => {
642            // For games: Tab/Shift-Tab should establish initial focus, not arrows.
643            return None;
644        }
645    };
646
647    let mut best: Option<(u64, f32)> = None;
648
649    // Modal trap: arrows stay inside the focused element's focus group.
650    let scoped: Vec<u64>;
651    let chain: &[u64] = match focus_group_chain(chain, hit_regions, current) {
652        Some(sub) => {
653            scoped = sub;
654            &scoped
655        }
656        None => chain,
657    };
658
659    for &id in chain {
660        if Some(id) == current {
661            continue;
662        }
663        let Some(hr) = hit_regions.iter().find(|h| h.id == id) else {
664            continue;
665        };
666        let r = hr.rect;
667        let other_cx = r.x + r.w / 2.0;
668        let other_cy = r.y + r.h / 2.0;
669        let dx = other_cx - cx;
670        let dy = other_cy - cy;
671
672        let in_direction = match dir {
673            FocusDirection::Left => dx < 0.0 && dy.abs() <= r.h.max(1.0),
674            FocusDirection::Right => dx > 0.0 && dy.abs() <= r.h.max(1.0),
675            FocusDirection::Up => dy < 0.0 && dx.abs() <= r.w.max(1.0),
676            FocusDirection::Down => dy > 0.0 && dx.abs() <= r.w.max(1.0),
677            _ => false,
678        };
679
680        if !in_direction {
681            continue;
682        }
683
684        let dist = dx * dx + dy * dy;
685        let weight = dist / (r.w * r.h + 1.0).max(1.0);
686
687        match best {
688            Some((_, best_weight)) if weight >= best_weight => {}
689            _ => best = Some((id, weight)),
690        }
691    }
692
693    best.map(|(id, _)| id)
694}
695
696#[derive(Default)]
697pub struct Composer {
698    pub slots: Vec<Box<dyn Any>>,
699    pub slot_callers: Vec<&'static Location<'static>>,
700    pub cursor: usize,
701    pub auto_counts: FxHashMap<String, usize>,
702    pub keyed_slots: FxHashMap<String, Box<dyn Any>>,
703    pub keyed_owner: FxHashMap<String, String>,
704    pub keyed_owners: FxHashMap<String, rustc_hash::FxHashSet<String>>,
705    /// Owner tokens of registered scopes visited this frame, plus the root token.
706    pub live_keyed_owners: rustc_hash::FxHashSet<String>,
707    /// Raw keys read through `remember_with_key` this frame.
708    pub live_keyed_keys: rustc_hash::FxHashSet<String>,
709    /// Owner tokens of scopes served from cache this frame. Their bodies did not
710    /// re-run, so their keyed slots go unread and must not be collected.
711    pub cache_preserved_owners: rustc_hash::FxHashSet<String>,
712    pub scope_caches: FxHashMap<String, crate::scope_cache::ScopeCache>,
713    pub live_scope_keys: rustc_hash::FxHashSet<String>,
714}
715
716/// The position-dependent part of the composer, isolated for movable content.
717#[derive(Default)]
718pub(crate) struct ComposerSlots {
719    pub(crate) slots: Vec<Box<dyn Any>>,
720    pub(crate) slot_callers: Vec<&'static Location<'static>>,
721    pub(crate) cursor: usize,
722    pub(crate) auto_counts: FxHashMap<String, usize>,
723}
724
725pub(crate) fn replace_composer_slots(next: ComposerSlots) -> ComposerSlots {
726    COMPOSER.with(|composer| {
727        let mut composer = composer.borrow_mut();
728        ComposerSlots {
729            slots: std::mem::replace(&mut composer.slots, next.slots),
730            slot_callers: std::mem::replace(&mut composer.slot_callers, next.slot_callers),
731            cursor: std::mem::replace(&mut composer.cursor, next.cursor),
732            auto_counts: std::mem::replace(&mut composer.auto_counts, next.auto_counts),
733        }
734    })
735}
736
737pub struct ComposeGuard {
738    scope: Scope,
739}
740
741pub(crate) fn keyed_disposer_order(key: &str) -> usize {
742    KEYED_DISPOSER_ORDER
743        .try_with(|order| {
744            order
745                .try_borrow()
746                .ok()
747                .and_then(|order| order.iter().position(|registered| registered == key))
748        })
749        .ok()
750        .flatten()
751        .unwrap_or(usize::MAX)
752}
753
754pub(crate) fn release_keyed_owner(key: &str, owner: &str) -> (bool, Option<Box<dyn Any>>) {
755    let result = COMPOSER
756        .try_with(|composer| {
757            let mut composer = match composer.try_borrow_mut() {
758                Ok(composer) => composer,
759                Err(_) => return (false, None, None),
760            };
761            let owners = match composer.keyed_owners.get_mut(key) {
762                Some(owners) => owners,
763                None => return (false, None, None),
764            };
765            owners.remove(owner);
766            if !owners.is_empty() {
767                return (true, None, None);
768            }
769            composer.keyed_owners.remove(key);
770            let old_owner = composer.keyed_owner.remove(key);
771            (true, composer.keyed_slots.remove(key), old_owner)
772        })
773        .unwrap_or((false, None, None));
774    drop(result.2);
775    (result.0, result.1)
776}
777
778/// A keyed slot survives when both hold:
779///
780/// * an owning scope is live (registered and visited this frame, or root) —
781///   unchanged rule, so slots whose owner is not a real scope (a bare
782///   `with_scope_key`, as `produce_state` tests use) are still collected, and
783///   `ProduceHandle::drop` can strip the reactive observer; and
784/// * the key was read this frame, or an owning scope was served from cache and
785///   so legitimately never read it.
786///
787/// The second condition is the fix. A scope that re-runs but stops reading a
788/// key now drops it, so a slot abandoned inside a permanently mounted scope —
789/// an overlay guard held by a component the host stopped composing, releases
790/// its entry instead of pinning it for the life of the app.
791pub(crate) fn take_dead_keyed_slots(composer: &mut Composer) -> Vec<(String, Box<dyn Any>)> {
792    fn owners_of<'a>(composer: &'a Composer, key: &str) -> Vec<&'a String> {
793        match composer.keyed_owners.get(key) {
794            Some(owners) => owners.iter().collect(),
795            None => composer.keyed_owner.get(key).into_iter().collect(),
796        }
797    }
798    let dead: Vec<String> = composer
799        .keyed_slots
800        .keys()
801        .filter(|key| {
802            let owners = owners_of(composer, key);
803            let scope_live = owners
804                .iter()
805                .any(|owner| composer.live_keyed_owners.contains(*owner));
806            if !scope_live {
807                return true;
808            }
809            if composer.live_keyed_keys.contains(*key) {
810                return false;
811            }
812            !owners
813                .iter()
814                .any(|owner| composer.cache_preserved_owners.contains(*owner))
815        })
816        .cloned()
817        .collect();
818    let mut removed = Vec::with_capacity(dead.len());
819    for key in dead {
820        if let Some(value) = composer.keyed_slots.remove(&key) {
821            removed.push((key.clone(), value));
822        }
823        composer.keyed_owner.remove(&key);
824        composer.keyed_owners.remove(&key);
825    }
826    removed
827}
828
829pub(crate) fn current_scope_key_for_remember() -> Option<String> {
830    crate::scope_cache::current_scope_key()
831}
832
833fn flush_initializer_cursor() {
834    let pending = PENDING_INITIALIZER_CURSOR
835        .try_with(|pending| {
836            pending
837                .try_borrow_mut()
838                .ok()
839                .and_then(|mut pending| pending.take())
840        })
841        .ok()
842        .flatten();
843    let Some(cursor) = pending else {
844        return;
845    };
846    let restored = COMPOSER
847        .try_with(|composer| {
848            composer
849                .try_borrow_mut()
850                .ok()
851                .map(|mut composer| composer.cursor = cursor)
852        })
853        .ok()
854        .flatten();
855    if restored.is_none() {
856        let _ = PENDING_INITIALIZER_CURSOR.try_with(|pending| {
857            if let Ok(mut pending) = pending.try_borrow_mut() {
858                *pending = Some(cursor);
859            }
860        });
861    }
862}
863
864impl ComposeGuard {
865    pub fn begin() -> Self {
866        flush_initializer_cursor();
867        COMPOSER.with(|c| {
868            let mut c = c.borrow_mut();
869            c.cursor = 0;
870            c.auto_counts.clear();
871            c.live_scope_keys.clear();
872            c.live_keyed_owners.clear();
873            c.live_keyed_keys.clear();
874            c.cache_preserved_owners.clear();
875            c.live_scope_keys.insert(String::new());
876            c.live_keyed_owners.insert(scope_owner_token(None));
877        });
878
879        let scope = ROOT_SCOPE.with(|rs| {
880            if let Some(existing) = rs.borrow().clone() {
881                existing
882            } else {
883                let s = Scope::new();
884                *rs.borrow_mut() = Some(s.clone());
885                s
886            }
887        });
888
889        ComposeGuard { scope }
890    }
891
892    pub fn scope(&self) -> &Scope {
893        &self.scope
894    }
895
896    pub fn live_scope_keys(&self) -> rustc_hash::FxHashSet<String> {
897        COMPOSER.with(|c| c.borrow().live_scope_keys.clone())
898    }
899}
900
901impl Drop for ComposeGuard {
902    fn drop(&mut self) {
903        let removed = COMPOSER.with(|c| {
904            let mut c = c.borrow_mut();
905            let n = c.cursor;
906            let mut removed = Vec::new();
907            if c.slots.len() > n {
908                removed.extend(c.slots.drain(n..));
909            }
910            if c.slot_callers.len() > n {
911                c.slot_callers.truncate(n);
912            }
913            removed
914        });
915        drop(removed);
916        crate::scope_cache::gc_dead_scopes();
917    }
918}
919
920/// Dispose the root composition scope and clear all composer caches.
921///
922/// Call once on process exit (desktop `exiting`, tests). After this the next
923/// `ComposeGuard::begin` starts from a fresh root scope.
924pub fn shutdown_composition() {
925    let scope = ROOT_SCOPE.with(|rs| rs.borrow_mut().take());
926    if let Some(scope) = scope {
927        scope.dispose();
928    }
929    let removed = COMPOSER.with(|c| {
930        let mut c = c.borrow_mut();
931        let slots = std::mem::take(&mut c.slots);
932        let callers = std::mem::take(&mut c.slot_callers);
933        let keyed = std::mem::take(&mut c.keyed_slots);
934        let caches = std::mem::take(&mut c.scope_caches);
935        c.keyed_owner.clear();
936        c.keyed_owners.clear();
937        c.live_keyed_owners.clear();
938        c.live_keyed_keys.clear();
939        c.cache_preserved_owners.clear();
940        c.live_scope_keys.clear();
941        c.cursor = 0;
942        c.auto_counts.clear();
943        (slots, callers, keyed, caches)
944    });
945    drop(removed);
946    for disposer in take_all_keyed_disposers() {
947        run_keyed_disposer(disposer);
948    }
949    crate::animation_driver::shutdown();
950    crate::scope_cache::clear_all_scope_deps();
951    INITIALIZER_STACK.with(|stack| stack.borrow_mut().clear());
952    PENDING_INITIALIZER_CURSOR.with(|pending| {
953        let _ = pending.borrow_mut().take();
954    });
955}
956
957struct InitializerGuard {
958    active: bool,
959    cursor: Option<usize>,
960}
961
962impl InitializerGuard {
963    fn assert_sequential_allowed() {
964        assert!(
965            INITIALIZER_STACK.with(|stack| stack
966                .try_borrow()
967                .map(|stack| stack.is_empty())
968                .unwrap_or(false)),
969            "remember initializer re-entered composition; use an explicit keyed helper"
970        );
971    }
972
973    fn enter_sequential() -> (Self, usize) {
974        Self::assert_sequential_allowed();
975        let cursor = COMPOSER.with(|composer| {
976            let mut composer = composer.borrow_mut();
977            let cursor = composer.cursor;
978            composer.cursor = composer.cursor.wrapping_add(1);
979            cursor
980        });
981        let pushed = INITIALIZER_STACK
982            .try_with(|stack| {
983                stack.try_borrow_mut().ok().map(|mut stack| {
984                    stack.push(InitializerKind::Sequential);
985                    true
986                })
987            })
988            .ok()
989            .flatten();
990        if pushed != Some(true) {
991            let _ = COMPOSER.try_with(|composer| {
992                if let Ok(mut composer) = composer.try_borrow_mut() {
993                    composer.cursor = cursor;
994                }
995            });
996            panic!("initializer stack busy");
997        }
998        (
999            Self {
1000                active: true,
1001                cursor: Some(cursor),
1002            },
1003            cursor,
1004        )
1005    }
1006
1007    fn assert_keyed_allowed() {
1008        assert!(
1009            INITIALIZER_STACK.with(|stack| stack
1010                .try_borrow()
1011                .map(|stack| stack.is_empty())
1012                .unwrap_or(false)),
1013            "remember initializer re-entered composition; use an explicit keyed helper"
1014        );
1015    }
1016
1017    fn enter_keyed() -> Self {
1018        Self::assert_keyed_allowed();
1019        INITIALIZER_STACK.with(|stack| {
1020            stack
1021                .try_borrow_mut()
1022                .expect("initializer stack busy")
1023                .push(InitializerKind::Keyed)
1024        });
1025        Self {
1026            active: true,
1027            cursor: None,
1028        }
1029    }
1030
1031    fn commit(&mut self) {
1032        if !self.active {
1033            return;
1034        }
1035        let _ = INITIALIZER_STACK.try_with(|stack| {
1036            if let Ok(mut stack) = stack.try_borrow_mut() {
1037                stack.pop();
1038            }
1039        });
1040        self.active = false;
1041    }
1042}
1043
1044impl Drop for InitializerGuard {
1045    fn drop(&mut self) {
1046        if !self.active {
1047            return;
1048        }
1049        if let Some(cursor) = self.cursor {
1050            let restored = COMPOSER
1051                .try_with(|composer| {
1052                    composer
1053                        .try_borrow_mut()
1054                        .ok()
1055                        .map(|mut composer| composer.cursor = cursor)
1056                })
1057                .ok()
1058                .flatten();
1059            if restored.is_none() {
1060                let _ = PENDING_INITIALIZER_CURSOR.try_with(|pending| {
1061                    if let Ok(mut pending) = pending.try_borrow_mut() {
1062                        *pending = Some(cursor);
1063                    }
1064                });
1065            }
1066        }
1067        let _ = INITIALIZER_STACK.try_with(|stack| {
1068            if let Ok(mut stack) = stack.try_borrow_mut() {
1069                stack.pop();
1070            }
1071        });
1072    }
1073}
1074
1075/// Slot-based remember (sequential composition only).
1076/// This prevents state aliasing when the composition tree structure changes between frames
1077#[track_caller]
1078pub fn remember<T: 'static>(init: impl FnOnce() -> T) -> Rc<T> {
1079    flush_initializer_cursor();
1080    let caller = Location::caller();
1081    let (mut initializer, cursor) = InitializerGuard::enter_sequential();
1082
1083    let existing = COMPOSER.with(|c| {
1084        let c = c.borrow();
1085        if cursor >= c.slots.len() || c.slot_callers.get(cursor).copied() != Some(caller) {
1086            return None;
1087        }
1088        c.slots[cursor].downcast_ref::<Rc<T>>().cloned()
1089    });
1090    if let Some(rc) = existing {
1091        initializer.commit();
1092        return rc;
1093    }
1094
1095    if COMPOSER.with(|c| {
1096        let c = c.borrow();
1097        cursor < c.slots.len() && c.slot_callers.get(cursor).copied() == Some(caller)
1098    }) {
1099        log::warn!(
1100            "remember: slot {} type changed {}. \
1101             Use remember_with_key(key, || ...) for conditional branches.",
1102            cursor,
1103            std::any::type_name::<T>(),
1104        );
1105    }
1106
1107    let rc = Rc::new(init());
1108    let old = COMPOSER.with(|c| {
1109        let mut c = c.borrow_mut();
1110        let value: Box<dyn Any> = Box::new(rc.clone());
1111        let old = if cursor < c.slots.len() {
1112            Some(std::mem::replace(&mut c.slots[cursor], value))
1113        } else {
1114            c.slots.push(value);
1115            None
1116        };
1117        if cursor < c.slot_callers.len() {
1118            c.slot_callers[cursor] = caller;
1119        } else {
1120            c.slot_callers.push(caller);
1121        }
1122        old
1123    });
1124    initializer.commit();
1125    drop(old);
1126    rc
1127}
1128
1129fn push_key_part(key: &mut String, part: &str) {
1130    key.push_str(&part.len().to_string());
1131    key.push(':');
1132    key.push_str(part);
1133    key.push('|');
1134}
1135
1136/// Auto-keyed variant of [`remember`]: identity is the call site plus an
1137/// occurrence index, so state follows a composition *position*, not an item.
1138/// Only safe where the number of calls at this site is fixed across frames —
1139/// list items and conditional branches need [`remember_with_key`].
1140#[track_caller]
1141pub fn remember_auto<T: 'static>(slot: &str, init: impl FnOnce() -> T) -> Rc<T> {
1142    let caller = Location::caller();
1143    let scope = current_scope_key_for_remember().unwrap_or_default();
1144    let mut base = String::from("auto:v1|");
1145    push_key_part(&mut base, &scope);
1146    push_key_part(&mut base, caller.file());
1147    push_key_part(&mut base, &caller.line().to_string());
1148    push_key_part(&mut base, &caller.column().to_string());
1149    push_key_part(&mut base, slot);
1150    let occurrence = COMPOSER.with(|composer| {
1151        let mut composer = composer.borrow_mut();
1152        let count = composer.auto_counts.entry(base.clone()).or_insert(0);
1153        let occurrence = *count;
1154        *count += 1;
1155        occurrence
1156    });
1157    push_key_part(&mut base, &occurrence.to_string());
1158    remember_with_key(base, init)
1159}
1160
1161pub fn keyed<T>(key: impl Into<String>, f: impl FnOnce() -> T) -> T {
1162    let key = key.into();
1163    assert!(!key.is_empty(), "keyed scopes need non-empty keys");
1164    let parent = current_scope_key_for_remember().unwrap_or_default();
1165    let mut full_key = String::new();
1166    push_key_part(&mut full_key, &parent);
1167    push_key_part(&mut full_key, &key);
1168    crate::scope_cache::with_scope_key(&full_key, f)
1169}
1170
1171/// Key-based remember.
1172pub fn remember_with_key<T: 'static>(key: impl Into<String>, init: impl FnOnce() -> T) -> Rc<T> {
1173    flush_initializer_cursor();
1174    InitializerGuard::assert_keyed_allowed();
1175    let key = key.into();
1176    let scope = current_scope_key_for_remember();
1177    let owner = scope_owner_token(scope.as_deref());
1178    let existing = COMPOSER.with(|composer| {
1179        let composer = composer.borrow();
1180        composer
1181            .keyed_slots
1182            .get(&key)
1183            .and_then(|value| value.downcast_ref::<Rc<T>>().cloned())
1184    });
1185    if let Some(existing) = existing {
1186        let old_owner = COMPOSER.with(|composer| {
1187            let mut composer = composer.borrow_mut();
1188            composer.live_keyed_keys.insert(key.clone());
1189            let old_owner = composer.keyed_owner.insert(key.clone(), owner.clone());
1190            composer
1191                .keyed_owners
1192                .entry(key.clone())
1193                .or_default()
1194                .insert(owner.clone());
1195            composer.live_keyed_owners.insert(owner);
1196            old_owner
1197        });
1198        drop(old_owner);
1199        return existing;
1200    }
1201
1202    // Reaching here means the same-type early return above did not fire, so the
1203    // key is either absent or held under a different type. Keep the two signals
1204    // apart: fusing them made a type collision also log the "unbounded dynamic
1205    // keys" message, and left the real key-count check unable to fire outside
1206    // debug builds.
1207    let (wrong_type, key_count_high) = COMPOSER.with(|composer| {
1208        let composer = composer.borrow();
1209        (
1210            composer.keyed_slots.contains_key(&key),
1211            composer.keyed_slots.len() > 10_000,
1212        )
1213    });
1214    if wrong_type {
1215        log::warn!(
1216            "remember_with_key: key '{}' reused with a different type; replacing.",
1217            key
1218        );
1219    }
1220    if key_count_high {
1221        log::warn!(
1222            "remember_with_key: {} keys stored; are you generating unbounded dynamic keys?",
1223            COMPOSER.with(|composer| composer.borrow().keyed_slots.len())
1224        );
1225    }
1226
1227    let mut initializer = InitializerGuard::enter_keyed();
1228    let value = Rc::new(init());
1229    let (result, old) = COMPOSER.with(|composer| {
1230        let mut composer = composer.borrow_mut();
1231        if let Some(existing) = composer.keyed_slots.get(&key)
1232            && let Some(existing) = existing.downcast_ref::<Rc<T>>()
1233        {
1234            let existing = existing.clone();
1235            composer.live_keyed_keys.insert(key.clone());
1236            composer.keyed_owner.insert(key.clone(), owner.clone());
1237            composer
1238                .keyed_owners
1239                .entry(key.clone())
1240                .or_default()
1241                .insert(owner.clone());
1242            composer.live_keyed_owners.insert(owner);
1243            return (existing, None);
1244        }
1245        let old = composer
1246            .keyed_slots
1247            .insert(key.clone(), Box::new(value.clone()));
1248        composer.live_keyed_keys.insert(key.clone());
1249        composer.keyed_owner.insert(key.clone(), owner.clone());
1250        composer
1251            .keyed_owners
1252            .entry(key)
1253            .or_default()
1254            .insert(owner.clone());
1255        (value, old)
1256    });
1257    initializer.commit();
1258    drop(old);
1259    result
1260}
1261
1262/// Raw slot state (`Rc<RefCell<T>>`). Writes via `borrow_mut()` don't request a
1263/// frame - prefer [`remember_mutable`] if a write must always recompose.
1264#[track_caller]
1265pub fn remember_state<T: 'static>(init: impl FnOnce() -> T) -> Rc<RefCell<T>> {
1266    remember(|| RefCell::new(init()))
1267}
1268
1269/// Key-based variant of [`remember_state`]. Same no-frame-on-write caveat.
1270pub fn remember_state_with_key<T: 'static>(
1271    key: impl Into<String>,
1272    init: impl FnOnce() -> T,
1273) -> Rc<RefCell<T>> {
1274    remember_with_key(key, || RefCell::new(init()))
1275}
1276
1277/// Auto-keyed variant of [`remember_state`]. Same positional caveat as
1278/// [`remember_auto`] and the same no-frame-on-write caveat as [`remember_state`].
1279#[track_caller]
1280pub fn remember_state_auto<T: 'static>(slot: &str, init: impl FnOnce() -> T) -> Rc<RefCell<T>> {
1281    remember_auto(slot, || RefCell::new(init()))
1282}
1283
1284/// Frame - output of composition for a tick: scene + input/semantics.
1285#[derive(Clone)]
1286pub struct Frame {
1287    pub scene: Scene,
1288    pub hit_regions: Vec<HitRegion>,
1289    pub semantics_nodes: Vec<SemNode>,
1290    pub focus_chain: Vec<u64>,
1291}
1292
1293/// Hit-test region in physical pixels (`rect` carries px magnitudes,
1294/// like Compose `Rect`).
1295#[derive(Clone, Default)]
1296pub struct HitRegion {
1297    pub id: u64,
1298    pub rect: Rect,
1299    /// Tree depth: 0 = root, higher = deeper child. Used for three-pass
1300    /// pointer dispatch to determine ancestor/descendant ordering.
1301    pub depth: u32,
1302    pub parent: Option<u64>,
1303    pub on_click: Option<Rc<dyn Fn()>>,
1304    pub on_double_click: Option<Rc<dyn Fn()>>,
1305    pub on_long_click: Option<Rc<dyn Fn()>>,
1306    pub on_scroll: Option<Rc<dyn Fn(crate::Vec2) -> crate::Vec2>>,
1307    pub on_scroll_with_source:
1308        Option<Rc<dyn Fn(crate::Vec2, crate::input::ScrollSource) -> crate::Vec2>>,
1309    pub focusable: bool,
1310    pub on_pointer_down: Option<Rc<dyn Fn(crate::input::PointerEvent)>>,
1311    pub on_pointer_move: Option<Rc<dyn Fn(crate::input::PointerEvent)>>,
1312    pub on_pointer_up: Option<Rc<dyn Fn(crate::input::PointerEvent)>>,
1313    pub on_pointer_cancel: Option<Rc<dyn Fn(crate::input::PointerEvent)>>,
1314    pub on_pointer_enter: Option<Rc<dyn Fn(crate::input::PointerEvent)>>,
1315    pub on_pointer_leave: Option<Rc<dyn Fn(crate::input::PointerEvent)>>,
1316    /// True when an explicit `on_pointer_move` handler owns dragging (sliders,
1317    /// splitters, drag surfaces). Tap-only `pointer_input` does not set this.
1318    pub drag_owner: bool,
1319    pub z_index: f32,
1320    pub disabled: bool,
1321    /// Carried from [`Modifier::visible`](crate::Modifier::visible). `None` and
1322    /// `Some(true)` are visible; `Some(false)` must not receive pointer events.
1323    pub visible: Option<bool>,
1324    pub on_text_change: Option<Rc<dyn Fn(String)>>,
1325    pub on_text_submit: Option<Rc<dyn Fn(String)>>,
1326    /// If this hit region belongs to a TextField, this persistent key is used
1327    /// for looking up platform-managed TextFieldState. Falls back to `id` if None.
1328    pub tf_state_key: Option<u64>,
1329
1330    /// True if this hit region corresponds to a multiline text input (TextArea).
1331    pub tf_multiline: bool,
1332
1333    /// Unclipped top-left of the TextField *content* box (padding-inset).
1334    /// Used for pointer->grapheme mapping so parent scroll clipping of `rect`
1335    /// does not shift selection into the top of the content.
1336    /// `None` for non-textfields.
1337    pub tf_content_origin: Option<(f32, f32)>,
1338
1339    /// When false, the field rejects edits and is not focusable
1340    pub tf_enabled: bool,
1341
1342    /// When true, selection/focus/copy are allowed but mutations are rejected
1343    pub tf_read_only: bool,
1344
1345    pub tf_sensitive: bool,
1346
1347    /// Controlled text snapshot for this field (last compose).
1348    pub tf_value: String,
1349
1350    /// Font size for this text field in [`Sp`](crate::units::Sp)
1351    /// (for hit-test / caret mapping). `Sp::ZERO` means use `TF_FONT_SP` default.
1352    pub tf_font_size: crate::units::Sp,
1353
1354    // internal
1355    pub on_drag_start: Option<Rc<dyn Fn(crate::dnd::DragStart) -> Option<crate::dnd::DragPayload>>>,
1356    pub on_drag_end: Option<Rc<dyn Fn(crate::dnd::DragEnd)>>,
1357    pub on_drag_enter: Option<Rc<dyn Fn(crate::dnd::DragOver)>>,
1358    pub on_drag_over: Option<Rc<dyn Fn(crate::dnd::DragOver)>>,
1359    pub on_drag_leave: Option<Rc<dyn Fn(crate::dnd::DragOver)>>,
1360    pub on_drop: Option<Rc<dyn Fn(crate::dnd::DropEvent) -> bool>>,
1361    /// Copied onto the drag session when a drag starts from this region.
1362    pub drag_preview: Option<crate::dnd::DragPreview>,
1363
1364    pub on_action: Option<Rc<dyn Fn(crate::shortcuts::Action) -> bool>>,
1365
1366    pub on_set_progress: Option<Rc<dyn Fn(f32)>>,
1367    pub on_expand: Option<Rc<dyn Fn()>>,
1368    pub on_collapse: Option<Rc<dyn Fn()>>,
1369    pub on_dismiss: Option<Rc<dyn Fn()>>,
1370
1371    /// Called when a key event is received while this element is focused.
1372    /// Return `true` to consume the event.
1373    pub on_key_event: Option<Rc<dyn Fn(crate::input::KeyEvent) -> bool>>,
1374    /// Called before `on_key_event`. Return `true` to consume before normal dispatch.
1375    pub on_preview_key_event: Option<Rc<dyn Fn(crate::input::KeyEvent) -> bool>>,
1376    /// Called when an IME event (composition update/commit) is received
1377    /// while this element is focused. Return `true` to consume the event.
1378    pub on_ime: Option<Rc<dyn Fn(crate::input::ImeEvent) -> bool>>,
1379
1380    /// Cursor hint for desktop/web.
1381    pub cursor: Option<crate::CursorIcon>,
1382
1383    /// If `Some(group_id)`, this hit region belongs to a focus group with the
1384    /// given id. Tab navigation will cycle within the group instead of moving
1385    /// to elements outside it. Set automatically by the layout engine when the
1386    /// element is a descendant of a node with `focus_group: true`.
1387    pub focus_group_id: Option<u64>,
1388
1389    /// View id of a `BringIntoViewRequester` attached to this region. The
1390    /// runtime uses it to resolve which view to reveal when `request()` fires.
1391    pub bring_into_view_target: Option<u64>,
1392
1393    /// Called with the focused descendant's bounds (physical px) whenever
1394    /// focus or those bounds change. Scroll containers install this to implement
1395    /// focus-driven bring-into-view.
1396    pub on_focused_bounds_changed: Option<Rc<dyn Fn(Rect)>>,
1397
1398    /// IME keyboard hints, populated for text-field hit regions so the
1399    /// platform runner can configure the OS keyboard / IME on focus.
1400    pub keyboard_type: crate::text::KeyboardType,
1401    pub capitalization: crate::text::KeyboardCapitalization,
1402    pub ime_action: crate::text::ImeAction,
1403    /// Whether auto-correct is enabled. `None` = follow platform default;
1404    /// password keyboards always resolve to `false` in the layout engine.
1405    pub auto_correct: Option<bool>,
1406
1407    /// Shared interaction source auto-wired by the layout engine
1408    /// (press/hover/focus/drag). Used by keyboard activation and focus
1409    /// transitions so they stay in parity with pointer input.
1410    /// `None` when the component does not need one (no indication/state colors).
1411    pub interaction_source: Option<crate::modifier::InteractionSource>,
1412
1413    /// Test-only identifier copied from [`crate::Semantics::test_tag`].
1414    pub test_tag: Option<String>,
1415}
1416
1417fn with_pointer_input(
1418    original: Option<Rc<dyn Fn(crate::input::PointerEvent)>>,
1419    dispatch: &Option<crate::pointer::PointerInputDispatch>,
1420) -> Option<Rc<dyn Fn(crate::input::PointerEvent)>> {
1421    let Some(dispatch) = dispatch.clone() else {
1422        return original;
1423    };
1424    Some(Rc::new(move |event: crate::input::PointerEvent| {
1425        if let Some(original) = &original {
1426            original(event.clone());
1427        }
1428        if !event.is_consumed() && dispatch.on_event(&event) {
1429            event.consume();
1430        }
1431    }))
1432}
1433
1434impl HitRegion {
1435    /// Seed a HitRegion with all the modifier's event handlers + dnd + cursor.
1436    /// Call‑sites should only override the fields that differ (on_click, focusable, etc.)
1437    /// via struct‑update syntax: `HitRegion { focusable: true, ..from_modifier(..) }`.
1438    pub fn from_modifier(id: u64, rect: Rect, m: &crate::modifier::Modifier) -> Self {
1439        let dispatch = m.pointer_dispatch();
1440        Self {
1441            id,
1442            rect,
1443            z_index: m.z_index,
1444            on_click: m.on_click.clone(),
1445            on_double_click: m.on_double_click.clone(),
1446            on_long_click: m.on_long_click.clone(),
1447            on_pointer_down: with_pointer_input(m.on_pointer_down.clone(), &dispatch),
1448            on_pointer_move: with_pointer_input(m.on_pointer_move.clone(), &dispatch),
1449            on_pointer_up: with_pointer_input(m.on_pointer_up.clone(), &dispatch),
1450            on_pointer_cancel: with_pointer_input(m.on_pointer_cancel.clone(), &dispatch),
1451            on_pointer_enter: m.on_pointer_enter.clone(),
1452            on_pointer_leave: m.on_pointer_leave.clone(),
1453            drag_owner: m.on_pointer_move.is_some() && m.pointer_dispatch().is_none(),
1454            on_action: m.on_action.clone(),
1455            on_set_progress: m.on_set_progress.clone(),
1456            on_expand: m.on_expand.clone(),
1457            on_collapse: m.on_collapse.clone(),
1458            on_dismiss: m.on_dismiss.clone(),
1459            on_key_event: m.on_key_event.clone(),
1460            on_preview_key_event: m.on_preview_key_event.clone(),
1461            on_ime: m.on_ime.clone(),
1462            cursor: m.cursor.clone(),
1463            on_drag_start: m.on_drag_start.clone(),
1464            on_drag_end: m.on_drag_end.clone(),
1465            on_drag_enter: m.on_drag_enter.clone(),
1466            on_drag_over: m.on_drag_over.clone(),
1467            on_drag_leave: m.on_drag_leave.clone(),
1468            on_scroll: m.on_scroll.clone(),
1469            on_scroll_with_source: m.on_scroll_with_source.clone(),
1470            on_drop: m.on_drop.clone(),
1471            drag_preview: m.drag_preview.clone(),
1472            disabled: m.disabled,
1473            visible: m.visible,
1474            bring_into_view_target: m.bring_into_view.as_ref().map(|requester| {
1475                requester.set_target(id);
1476                id
1477            }),
1478            on_focused_bounds_changed: m.on_focused_bounds_changed.clone(),
1479            tf_enabled: true,
1480            tf_read_only: false,
1481            test_tag: m.semantics.as_ref().and_then(|s| s.test_tag.clone()),
1482            ..Default::default()
1483        }
1484    }
1485}
1486
1487/// Route a gesture action to the topmost hit region under `center`,
1488/// walking up ancestors until one consumes it. Fallback for gestures that
1489/// miss the focused widget, matching Compose routing to the node under the
1490/// pointer. Coordinates are physical px, like [`HitRegion::rect`].
1491pub fn route_action_to_point(
1492    hits: &[HitRegion],
1493    action: &crate::shortcuts::Action,
1494    center: crate::Vec2,
1495) -> bool {
1496    let mut best: Option<&HitRegion> = None;
1497    for h in hits {
1498        if h.disabled || h.visible == Some(false) || h.on_action.is_none() {
1499            continue;
1500        }
1501        let r = h.rect;
1502        if center.x < r.x || center.x > r.x + r.w || center.y < r.y || center.y > r.y + r.h {
1503            continue;
1504        }
1505        let better = match best {
1506            None => true,
1507            Some(b) => (h.z_index, h.depth) >= (b.z_index, b.depth),
1508        };
1509        if better {
1510            best = Some(h);
1511        }
1512    }
1513    let mut current = best.map(|h| h.id);
1514    while let Some(id) = current {
1515        let Some(h) = hits.iter().find(|h| h.id == id) else {
1516            break;
1517        };
1518        if !h.disabled
1519            && h.visible != Some(false)
1520            && let Some(cb) = &h.on_action
1521            && cb(action.clone())
1522        {
1523            return true;
1524        }
1525        current = h.parent;
1526    }
1527    false
1528}
1529
1530/// Flattened semantics node produced by `layout_and_paint`.
1531///
1532/// This is the source of truth for accessibility backends: it contains the
1533/// resolved screen rect, role, label, and focus/enabled state.
1534///
1535/// The platform runner should convert this into OS‑specific accessibility trees (when implemented)
1536/// (AT‑SPI on Linux, TalkBack on Android, etc.).
1537#[derive(Clone)]
1538pub struct SemNode {
1539    /// Stable id, shared with the associated `HitRegion` / `ViewId`.
1540    pub id: u64,
1541
1542    /// `None` means direct child of the window root.
1543    pub parent: Option<u64>,
1544
1545    pub role: Role,
1546    pub label: Option<String>,
1547    pub rect: Rect,
1548    pub focused: bool,
1549    pub enabled: bool,
1550    /// Marks this node as a collection of selectable children (e.g., Tabs).
1551    pub selectable_group: bool,
1552    pub checked: Option<bool>,
1553    pub selected: Option<bool>,
1554    pub value: Option<String>,
1555    pub heading: bool,
1556    pub live_region: Option<crate::semantics::LiveRegion>,
1557    pub state_description: Option<String>,
1558    pub traversal_index: Option<f32>,
1559    pub is_traversal_group: bool,
1560    pub hidden: bool,
1561    pub collection_rows: Option<usize>,
1562    pub collection_columns: Option<usize>,
1563    pub row_index: Option<usize>,
1564    pub column_index: Option<usize>,
1565    pub progress: Option<crate::semantics::ProgressRangeInfo>,
1566    pub error: Option<String>,
1567    pub expanded: Option<bool>,
1568    pub scrollable: bool,
1569    pub can_expand: bool,
1570    pub can_collapse: bool,
1571    pub can_dismiss: bool,
1572    pub test_tag: Option<String>,
1573}
1574
1575impl Default for SemNode {
1576    fn default() -> Self {
1577        Self {
1578            id: 0,
1579            parent: None,
1580            role: Role::default(),
1581            label: None,
1582            rect: Rect::default(),
1583            focused: false,
1584            enabled: true,
1585            selectable_group: false,
1586            checked: None,
1587            selected: None,
1588            value: None,
1589            heading: false,
1590            live_region: None,
1591            state_description: None,
1592            traversal_index: None,
1593            is_traversal_group: false,
1594            hidden: false,
1595            collection_rows: None,
1596            collection_columns: None,
1597            row_index: None,
1598            column_index: None,
1599            progress: None,
1600            error: None,
1601            expanded: None,
1602            scrollable: false,
1603            can_expand: false,
1604            can_collapse: false,
1605            can_dismiss: false,
1606            test_tag: None,
1607        }
1608    }
1609}
1610
1611pub struct Scheduler {
1612    next_id: u64,
1613    /// Per-scope unique IDs, assigned lazily when a scope first executes.
1614    /// Keyed by the scope key string from `scope!`.
1615    scope_key_to_id: FxHashMap<String, u32>,
1616    next_scope_id: u32,
1617    /// Stack of active scope keys. `id()` allocates from the innermost scope
1618    /// so nested `scope!` bodies get stable packed IDs and the outer scope
1619    /// resumes correctly after the inner exits (previously `exit_scope` reset
1620    /// to `None`, leaking outer IDs into the global sequence).
1621    current_scope: Vec<String>,
1622    /// Per-scope local ID counters. Reset to 0 when a scope re-executes.
1623    scope_local_counters: FxHashMap<String, u32>,
1624    pub focused: Option<u64>,
1625    pub size: (u32, u32),
1626    /// Last known mouse pointer position in physical px, updated on
1627    /// mouse move/press/release without passing through focus dispatch.
1628    pub pointer_pos_px: Option<(f32, f32)>,
1629    /// Polled physical keys currently down, layout-independent
1630    /// positions (see [`PhysicalKey`]). The platform runner maintains
1631    /// this from raw `KeyboardInput` events without passing through
1632    /// focus dispatch; games reconcile their event-staged held sets
1633    /// against it every frame (GML `keyboard_check` parity). Cleared
1634    /// on window focus loss (no key-ups arrive across an alt-tab).
1635    pub held_keys: HashSet<PhysicalKey>,
1636    /// Window focus as of the last platform event. `false` drops every
1637    /// held key on the game side.
1638    pub window_focused: bool,
1639    /// Live touch contacts in physical px: `(touch id, x, y)` per
1640    /// finger currently down. Written by the platform runners from
1641    /// raw `WindowEvent::Touch` (Started/Moved/Ended-Cancelled), read
1642    /// by games through `feed_polled`-style staging snapshots
1643    /// (GML `device_mouse_x_to_gui(i)` parity: stable per-finger slot
1644    /// ids, positions sampled every tick while held).
1645    pub touch_points: Vec<(u64, f32, f32)>,
1646    /// Polled mouse-button levels, same source as `held_keys`
1647    /// (GML `mouse_check_button` parity; repairs a missed button-up
1648    /// when the release lands outside the window).
1649    pub mouse_primary: bool,
1650    pub mouse_secondary: bool,
1651    pub mouse_middle: bool,
1652    /// The connected gamepads, polled like the keys and the mouse levels: the
1653    /// buttons that are down and the live axis values, one entry per pad.
1654    pub gamepads: Vec<GamepadPad>,
1655    /// The window's DPI scale factor: physical px per logical px. `1.0` on
1656    /// a display that reports no scaling. The pointer's positions are physical
1657    /// px, so a game that maps them into its own space divides by this.
1658    pub scale: f32,
1659    /// App-requested cursor override. When `Some`, the platform
1660    /// applies it instead of the hover-derived icon: games hide the
1661    /// OS pointer here (`CursorIcon::Hidden`) while drawing their own
1662    /// crosshair, GML `window_set_cursor(cr_none)` parity. `None`
1663    /// restores hover behavior. Set during composition (any view can
1664    /// write it; last write per frame wins), consumed by the runner
1665    /// after `frame()`.
1666    pub cursor_override: Option<CursorIcon>,
1667    /// App-requested pointer confinement, declared per frame like
1668    /// `cursor_override`: a game steering with the mouse sets
1669    /// [`CursorGrabMode::Confined`](crate::CursorGrabMode::Confined)
1670    /// while the pointer is its input, so the mouse stops at the
1671    /// window edge instead of escaping and freezing the control. The
1672    /// field is reset to `None` after every `frame()`, so a game that
1673    /// stops asking - a paused match, a closed editor - releases the
1674    /// pointer the same frame.
1675    pub cursor_grab: CursorGrabMode,
1676    /// App-requested borderless fullscreen, taken by the runner when it next
1677    /// looks rather than declared per frame like `cursor_grab`.
1678    ///
1679    /// A switch rather than a state, and the difference matters: the game asks
1680    /// on the frame the player flips the setting, so a window the player
1681    /// resized themselves is left alone by the next frame re-asserting it. The
1682    /// runner consumes the request, so it is `None` again once it has been
1683    /// applied. Games ask through [`Scheduler::request_fullscreen`]; shells
1684    /// read it back with `repose_app::Runtime::take_fullscreen_request`.
1685    pub fullscreen_request: Option<bool>,
1686}
1687
1688impl Default for Scheduler {
1689    fn default() -> Self {
1690        Self::new()
1691    }
1692}
1693
1694impl Scheduler {
1695    pub fn new() -> Self {
1696        Self {
1697            next_id: 1,
1698            scope_key_to_id: FxHashMap::default(),
1699            next_scope_id: 1,
1700            current_scope: Vec::new(),
1701            scope_local_counters: FxHashMap::default(),
1702            focused: None,
1703            size: (1280, 800),
1704            pointer_pos_px: None,
1705            held_keys: HashSet::new(),
1706            window_focused: true,
1707            touch_points: Vec::new(),
1708            mouse_primary: false,
1709            mouse_secondary: false,
1710            mouse_middle: false,
1711            gamepads: Vec::new(),
1712            scale: 1.0,
1713            cursor_override: None,
1714            cursor_grab: CursorGrabMode::None,
1715            fullscreen_request: None,
1716        }
1717    }
1718
1719    /// Ask the runner for borderless fullscreen on or off.
1720    ///
1721    /// The app's side of the request: the runner consumes it when it next
1722    /// looks, so this is asked once, on the frame the player changes their
1723    /// mind, rather than asserted every frame. A game has no other way to
1724    /// reach the window — the closure the shell calls is handed a scheduler
1725    /// and a render context, and neither is the window.
1726    pub fn request_fullscreen(&mut self, fullscreen: bool) {
1727        self.fullscreen_request = Some(fullscreen);
1728    }
1729
1730    /// Enter a named scope. Subsequent `id()` calls within this scope
1731    /// will allocate from the scope's local counter, producing packed
1732    /// `(scope_id << 32) | local_id` values that are stable across sibling
1733    /// recompositions. Nested scopes push; `exit_scope` pops.
1734    pub fn enter_scope(&mut self, key: &str) {
1735        if !self.current_scope.iter().any(|k| k == key) {
1736            self.scope_local_counters.insert(key.to_string(), 0);
1737        }
1738        self.current_scope.push(key.to_string());
1739        self.get_or_create_scope_id(key);
1740    }
1741
1742    /// Exit the innermost scope. No-op if the stack is empty or the top does
1743    /// not match (defensive: never corrupt an outer scope).
1744    pub fn exit_scope(&mut self) {
1745        self.current_scope.pop();
1746    }
1747
1748    /// RAII scope entry: pops on drop, so a panicking scope body cannot leave
1749    /// the scheduler stuck in the wrong scope (which previously leaked outer
1750    /// IDs into the global sequence).
1751    pub fn scope_guard<'a>(&'a mut self, key: &str) -> SchedulerScopeGuard<'a> {
1752        self.enter_scope(key);
1753        SchedulerScopeGuard { sched: self }
1754    }
1755
1756    /// Panic-safe scope entry that does NOT hold a borrow: the guarded body
1757    /// (including nested `scope!`) can keep using the `Scheduler`. Used by
1758    /// the `scope!` macro.
1759    pub fn scope_guard_raw(&mut self, key: &str) -> SchedulerScopeGuardRaw {
1760        let ptr = self as *mut Scheduler;
1761        unsafe { SchedulerScopeGuardRaw::enter(ptr, key) }
1762    }
1763
1764    fn get_or_create_scope_id(&mut self, key: &str) -> u32 {
1765        if let Some(&id) = self.scope_key_to_id.get(key) {
1766            id
1767        } else {
1768            let id = self.next_scope_id;
1769            self.next_scope_id += 1;
1770            self.scope_key_to_id.insert(key.to_string(), id);
1771            id
1772        }
1773    }
1774
1775    pub fn id(&mut self) -> u64 {
1776        if let Some(key) = self.current_scope.last().cloned() {
1777            let scope_id = self.scope_key_to_id.get(&key).copied().unwrap_or(0);
1778            let local = self.scope_local_counters.get_mut(&key).unwrap();
1779            let id = *local;
1780            *local += 1;
1781            (scope_id as u64) << 32 | id as u64
1782        } else {
1783            // Global sequential ID (for non-scoped views)
1784            let id = self.next_id;
1785            self.next_id += 1;
1786            id
1787        }
1788    }
1789
1790    pub fn id_count(&self) -> u64 {
1791        self.next_id - 1
1792    }
1793
1794    /// True while the named physical key is in the polled snapshot.
1795    pub fn is_held(&self, key: PhysicalKey) -> bool {
1796        self.held_keys.contains(&key)
1797    }
1798
1799    /// Snapshot the current ID counter (before executing a scope body) so the
1800    /// delta can be computed after the body returns.
1801    pub fn snapshot_id(&self) -> u64 {
1802        self.next_id
1803    }
1804
1805    /// Advance the ID counter by `count` without assigning IDs.
1806    /// Used by the scope! macro to reserve IDs for a cached scope subtree.
1807    pub fn advance_id(&mut self, count: u32) {
1808        self.next_id += count as u64;
1809    }
1810
1811    /// Number of IDs assigned since `prev_id` (the value returned by
1812    /// `snapshot_id()` before executing a scope body).
1813    pub fn ids_used_since(&self, prev_id: u64) -> u32 {
1814        (self.next_id - prev_id) as u32
1815    }
1816
1817    pub fn gc_scope_state(&mut self, live_keys: &rustc_hash::FxHashSet<String>) {
1818        self.scope_key_to_id
1819            .retain(|key, _| live_keys.contains(key));
1820        self.scope_local_counters
1821            .retain(|key, _| live_keys.contains(key));
1822    }
1823}
1824
1825/// RAII guard from [`Scheduler::scope_guard`]. Pops the scope on drop.
1826pub struct SchedulerScopeGuard<'a> {
1827    sched: &'a mut Scheduler,
1828}
1829
1830impl Drop for SchedulerScopeGuard<'_> {
1831    fn drop(&mut self) {
1832        self.sched.exit_scope();
1833    }
1834}
1835
1836/// Panic-safe scope guard that does NOT hold a borrow across the body.
1837///
1838/// The `scope!` macro uses this (not [`SchedulerScopeGuard`]) so the guarded
1839/// body, including nested `scope!` invocations, can keep using the
1840/// `Scheduler` normally. At drop time (normal or unwind) no other borrows of
1841/// the scheduler are live, since the body has ended.
1842pub struct SchedulerScopeGuardRaw {
1843    sched: *mut Scheduler,
1844}
1845
1846impl SchedulerScopeGuardRaw {
1847    /// # Safety
1848    /// `sched` must point to a valid `Scheduler` for the guard's lifetime,
1849    /// and the scheduler must not be used while the guard is being dropped
1850    /// (guaranteed when the guard outlives the body it protects).
1851    pub unsafe fn enter(sched: *mut Scheduler, key: &str) -> Self {
1852        unsafe {
1853            (*sched).enter_scope(key);
1854        }
1855        Self { sched }
1856    }
1857}
1858
1859impl Drop for SchedulerScopeGuardRaw {
1860    fn drop(&mut self) {
1861        unsafe {
1862            (*self.sched).exit_scope();
1863        }
1864    }
1865}
1866
1867impl Scheduler {
1868    pub fn repose<F>(
1869        &mut self,
1870        mut build_root: F,
1871        layout_paint: impl Fn(&View, (u32, u32)) -> (Scene, Vec<HitRegion>, Vec<SemNode>),
1872    ) -> Frame
1873    where
1874        F: FnMut(&mut Scheduler) -> View,
1875    {
1876        let guard = ComposeGuard::begin();
1877        let root = guard.scope.run(|| build_root(self));
1878        let (scene, hits, sem) = layout_paint(&root, self.size);
1879
1880        let focusable: FxHashSet<u64> = hits.iter().filter(|h| h.focusable).map(|h| h.id).collect();
1881        let mut focus_chain: Vec<u64> = match take_focus_order() {
1882            Some(order) => order
1883                .into_iter()
1884                .filter(|id| focusable.contains(id))
1885                .collect(),
1886            None => Vec::new(),
1887        };
1888        // A focusable view painted through a path that did not contribute to the
1889        // captured order (overlay, deferred subtree, repaint-boundary replay)
1890        // must still be reachable. Otherwise the focused id is pruned from the
1891        // chain on the next frame, which drops focus and hides the IME.
1892        for hit in &hits {
1893            if hit.focusable && !focus_chain.contains(&hit.id) {
1894                focus_chain.push(hit.id);
1895            }
1896        }
1897
1898        let live_scope_keys = guard.live_scope_keys();
1899        let frame = Frame {
1900            scene,
1901            hit_regions: hits,
1902            semantics_nodes: sem,
1903            focus_chain,
1904        };
1905        drop(guard);
1906        self.gc_scope_state(&live_scope_keys);
1907        frame
1908    }
1909}
1910
1911/// Test helper: full composer reset. Production shutdown should call
1912/// `shutdown_composition`.
1913#[cfg(test)]
1914pub fn clear_composer() {
1915    shutdown_composition();
1916}
1917
1918#[cfg(test)]
1919mod focus_trap_tests {
1920    use super::*;
1921
1922    fn region(id: u64, x: f32, group: Option<u64>) -> HitRegion {
1923        HitRegion {
1924            id,
1925            rect: Rect {
1926                x,
1927                y: 0.0,
1928                w: 10.0,
1929                h: 10.0,
1930            },
1931            focus_group_id: group,
1932            ..Default::default()
1933        }
1934    }
1935
1936    #[test]
1937    fn arrows_stay_inside_group() {
1938        // Dialog buttons 2,3 in group 9; background button 4 outside;
1939        // outsider 1 sits left of button 2 and would win unconstrained.
1940        let chain = vec![1, 2, 3, 4];
1941        let regions = vec![
1942            region(1, 0.0, None),
1943            region(2, 20.0, Some(9)),
1944            region(3, 40.0, Some(9)),
1945            region(4, 60.0, None),
1946        ];
1947        assert_eq!(
1948            spatial_focus_next(&chain, &regions, Some(2), FocusDirection::Left),
1949            None,
1950            "outsider 1 is left of 2 but outside the group: trapped"
1951        );
1952        assert_eq!(
1953            spatial_focus_next(&chain, &regions, Some(2), FocusDirection::Right),
1954            Some(3)
1955        );
1956        assert_eq!(
1957            spatial_focus_next(&chain, &regions, Some(3), FocusDirection::Left),
1958            Some(2)
1959        );
1960        assert_eq!(
1961            spatial_focus_next(&chain, &regions, Some(1), FocusDirection::Right),
1962            Some(2),
1963            "ungrouped focus still sees the full chain"
1964        );
1965    }
1966
1967    #[test]
1968    fn tab_cycles_inside_group() {
1969        let chain = vec![1, 2, 3, 4];
1970        let regions = vec![
1971            region(1, 0.0, None),
1972            region(2, 20.0, Some(9)),
1973            region(3, 40.0, Some(9)),
1974            region(4, 60.0, None),
1975        ];
1976        let mut fm = FocusManager::new(chain, Some(2));
1977        fm.hit_regions = regions;
1978        assert_eq!(fm.move_tab(false), Some(3));
1979        assert_eq!(fm.move_tab(false), Some(2));
1980        assert_eq!(fm.move_tab(true), Some(3));
1981    }
1982
1983    #[test]
1984    fn tab_from_outside_can_enter_group() {
1985        let chain = vec![1, 2, 3, 4];
1986        let regions = vec![
1987            region(1, 0.0, None),
1988            region(2, 20.0, Some(9)),
1989            region(3, 40.0, Some(9)),
1990            region(4, 60.0, None),
1991        ];
1992        let mut fm = FocusManager::new(chain, Some(1));
1993        fm.hit_regions = regions;
1994        assert_eq!(fm.move_tab(false), Some(2));
1995        let mut fm = FocusManager::new(vec![1, 2, 3, 4], Some(1));
1996        fm.hit_regions = vec![
1997            region(1, 0.0, None),
1998            region(2, 20.0, Some(9)),
1999            region(3, 40.0, Some(9)),
2000            region(4, 60.0, None),
2001        ];
2002        assert_eq!(fm.move_tab(true), Some(4));
2003    }
2004
2005    #[test]
2006    fn empty_group_never_moves() {
2007        let chain = vec![1, 4];
2008        let regions = vec![region(1, 0.0, None), region(4, 60.0, None)];
2009        let mut fm = FocusManager::new(chain, Some(1));
2010        fm.hit_regions = regions.clone();
2011        assert_eq!(fm.move_tab(false), Some(4));
2012        let chain = vec![1, 2, 4];
2013        let regions = vec![
2014            region(1, 0.0, None),
2015            region(2, 20.0, Some(77)),
2016            region(4, 60.0, None),
2017        ];
2018        let mut fm = FocusManager::new(chain, Some(2));
2019        fm.hit_regions = regions;
2020        assert_eq!(fm.move_tab(false), Some(2));
2021        assert_eq!(
2022            spatial_focus_next(&fm.chain, &fm.hit_regions, Some(2), FocusDirection::Right),
2023            None
2024        );
2025    }
2026}