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