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 static FOCUS_REQUESTS: RefCell<std::collections::VecDeque<u64>> =
35 const { RefCell::new(std::collections::VecDeque::new()) };
36
37 static FOCUS_CAPTURED: RefCell<Option<u64>> = const { RefCell::new(None) };
40
41 static FOCUS_ORDER: RefCell<Option<Vec<u64>>> = const { RefCell::new(None) };
44
45 static BRING_INTO_VIEW_REQUESTS: RefCell<std::collections::VecDeque<u64>> =
49 const { RefCell::new(std::collections::VecDeque::new()) };
50
51 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
272static COMPONENT_ID: AtomicU64 = AtomicU64::new(1);
275
276pub 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
285pub 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
297pub fn queue_bring_into_view(id: u64) {
300 BRING_INTO_VIEW_REQUESTS.with(|r| r.borrow_mut().push_back(id));
301}
302
303pub fn drain_bring_into_view_requests() -> Vec<u64> {
305 BRING_INTO_VIEW_REQUESTS.with(|r| r.borrow_mut().drain(..).collect())
306}
307
308pub fn focus_capture() -> Option<u64> {
310 FOCUS_CAPTURED.with(|c| *c.borrow())
311}
312
313pub fn set_focus_order(order: Vec<u64>) {
317 FOCUS_ORDER.with(|o| *o.borrow_mut() = Some(order));
318}
319
320pub fn take_focus_order() -> Option<Vec<u64>> {
322 FOCUS_ORDER.with(|o| o.borrow_mut().take())
323}
324
325#[derive(Clone)]
331pub struct FocusRequester {
332 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 pub fn request_focus(&self) {
348 let _ = self.try_request_focus();
349 }
350
351 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 pub fn request_focus_directed(&self, _direction: FocusDirection) -> bool {
372 self.try_request_focus()
373 }
374
375 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 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#[derive(Clone)]
418pub struct BringIntoViewRequester {
419 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 pub fn request(&self) {
435 let _ = self.try_request();
436 }
437
438 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 pub fn set_target(&self, id: u64) {
449 *self.target.borrow_mut() = Some(id);
450 }
451
452 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
466pub enum FocusDirection {
467 Next,
468 Previous,
469 Left,
470 Right,
471 Up,
472 Down,
473}
474
475#[derive(Clone)]
480pub struct FocusManager {
481 pub chain: Vec<u64>,
483 pub focused: Option<u64>,
485 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 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, }
507 }
508
509 pub fn clear_focus(&self, _force: bool) {
514 FOCUS_REQUESTS.with(|r| r.borrow_mut().push_back(CLEAR_FOCUS_MARKER));
515 }
516
517 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 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 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}
596pub fn take_focus_target_remaps() -> Vec<(u64, u64)> {
598 FOCUS_TARGET_REMAPS.with(|remaps| std::mem::take(&mut *remaps.borrow_mut()))
599}
600
601pub 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
625pub 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 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 return None;
660 }
661 };
662
663 let mut best: Option<(u64, f32)> = None;
664
665 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 pub live_keyed_owners: rustc_hash::FxHashSet<String>,
723 pub live_keyed_keys: rustc_hash::FxHashSet<String>,
725 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#[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
794pub(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
936pub 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#[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#[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
1187pub 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 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#[track_caller]
1281pub fn remember_state<T: 'static>(init: impl FnOnce() -> T) -> Rc<RefCell<T>> {
1282 remember(|| RefCell::new(init()))
1283}
1284
1285pub 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#[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#[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#[derive(Clone, Default)]
1312pub struct HitRegion {
1313 pub id: u64,
1314 pub rect: Rect,
1315 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 pub drag_owner: bool,
1335 pub z_index: f32,
1336 pub disabled: bool,
1337 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 pub tf_state_key: Option<u64>,
1345
1346 pub tf_multiline: bool,
1348
1349 pub tf_content_origin: Option<(f32, f32)>,
1354
1355 pub tf_enabled: bool,
1357
1358 pub tf_read_only: bool,
1360
1361 pub tf_sensitive: bool,
1362
1363 pub tf_value: String,
1365
1366 pub tf_font_size: crate::units::Sp,
1369
1370 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 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 pub on_key_event: Option<Rc<dyn Fn(crate::input::KeyEvent) -> bool>>,
1390 pub on_preview_key_event: Option<Rc<dyn Fn(crate::input::KeyEvent) -> bool>>,
1392 pub on_ime: Option<Rc<dyn Fn(crate::input::ImeEvent) -> bool>>,
1395
1396 pub cursor: Option<crate::CursorIcon>,
1398
1399 pub focus_group_id: Option<u64>,
1404
1405 pub bring_into_view_target: Option<u64>,
1408
1409 pub on_focused_bounds_changed: Option<Rc<dyn Fn(Rect)>>,
1413
1414 pub keyboard_type: crate::text::KeyboardType,
1417 pub capitalization: crate::text::KeyboardCapitalization,
1418 pub ime_action: crate::text::ImeAction,
1419 pub auto_correct: Option<bool>,
1422
1423 pub interaction_source: Option<crate::modifier::InteractionSource>,
1428
1429 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 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
1503pub 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#[derive(Clone)]
1554pub struct SemNode {
1555 pub id: u64,
1557
1558 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 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 scope_key_to_id: FxHashMap<String, u32>,
1632 next_scope_id: u32,
1633 current_scope: Vec<String>,
1638 scope_local_counters: FxHashMap<String, u32>,
1640 pub focused: Option<u64>,
1641 pub size: (u32, u32),
1642 pub pointer_pos_px: Option<(f32, f32)>,
1645 pub held_keys: HashSet<PhysicalKey>,
1652 pub window_focused: bool,
1655 pub touch_points: Vec<(u64, f32, f32)>,
1662 pub mouse_primary: bool,
1666 pub mouse_secondary: bool,
1667 pub mouse_middle: bool,
1668 pub gamepads: Vec<GamepadPad>,
1671 pub scale: f32,
1675 pub cursor_override: Option<CursorIcon>,
1683 pub cursor_grab: CursorGrabMode,
1692 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 pub fn request_fullscreen(&mut self, fullscreen: bool) {
1743 self.fullscreen_request = Some(fullscreen);
1744 }
1745
1746 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 pub fn exit_scope(&mut self) {
1761 self.current_scope.pop();
1762 }
1763
1764 pub fn scope_guard<'a>(&'a mut self, key: &str) -> SchedulerScopeGuard<'a> {
1768 self.enter_scope(key);
1769 SchedulerScopeGuard { sched: self }
1770 }
1771
1772 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 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 pub fn is_held(&self, key: PhysicalKey) -> bool {
1812 self.held_keys.contains(&key)
1813 }
1814
1815 pub fn snapshot_id(&self) -> u64 {
1818 self.next_id
1819 }
1820
1821 pub fn advance_id(&mut self, count: u32) {
1824 self.next_id += count as u64;
1825 }
1826
1827 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
1841pub 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
1852pub struct SchedulerScopeGuardRaw {
1859 sched: *mut Scheduler,
1860}
1861
1862impl SchedulerScopeGuardRaw {
1863 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 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#[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 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, ®ions, 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, ®ions, Some(2), FocusDirection::Right),
1970 Some(3)
1971 );
1972 assert_eq!(
1973 spatial_focus_next(&chain, ®ions, Some(3), FocusDirection::Left),
1974 Some(2)
1975 );
1976 assert_eq!(
1977 spatial_focus_next(&chain, ®ions, 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}