Skip to main content

xrack_runtime/
focus.rs

1use crate::Property;
2use std::{cell::RefCell, fmt, rc::Rc};
3
4/// Identity of a focus target in one component instance.
5#[derive(Clone, Default)]
6pub struct FocusHandle(Rc<FocusSignals>);
7
8#[derive(Default)]
9struct FocusSignals {
10    direct: Property<bool>,
11    within: Property<bool>,
12}
13
14impl fmt::Debug for FocusHandle {
15    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
16        f.debug_struct("FocusHandle").finish_non_exhaustive()
17    }
18}
19
20impl PartialEq for FocusHandle {
21    fn eq(&self, other: &Self) -> bool {
22        Rc::ptr_eq(&self.0, &other.0)
23    }
24}
25
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub enum FocusAction {
28    Focus,
29    Clear,
30    Text(TextCommand),
31}
32
33/// A programmatic edit using the same selection, validation and history as keyboard input.
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35pub enum TextCommand {
36    SelectAll,
37    ClearSelection,
38    SetSelection { anchor: i64, focus: i64 },
39    Undo,
40    Redo,
41    Cut,
42    Copy,
43    Paste,
44}
45
46#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
47pub enum FocusReason {
48    #[default]
49    Programmatic,
50    TabNavigation,
51    PointerClick,
52    PopupActivation,
53    WindowActivation,
54    Accessibility,
55    LayoutChange,
56    KeyboardNavigation,
57}
58
59#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60pub enum FocusEvent {
61    Gained(FocusReason),
62    Lost(FocusReason),
63    Within { focused: bool, reason: FocusReason },
64}
65
66impl FocusEvent {
67    #[doc(hidden)]
68    pub fn is_loss(self) -> bool {
69        matches!(self, Self::Lost(_) | Self::Within { focused: false, .. })
70    }
71}
72
73pub struct FocusRequest {
74    pub target: FocusHandle,
75    pub action: FocusAction,
76}
77
78/// A window's commands, drained against the scene prepared after the callback.
79#[derive(Clone, Default)]
80pub struct FocusRequests(Rc<RefCell<Vec<FocusRequest>>>);
81
82thread_local! {
83    static ACTIVE: RefCell<Option<FocusRequests>> = const { RefCell::new(None) };
84}
85
86pub struct FocusContext(Option<FocusRequests>);
87
88impl FocusRequests {
89    pub fn enter(&self) -> FocusContext {
90        FocusContext(ACTIVE.with(|active| active.replace(Some(self.clone()))))
91    }
92
93    pub fn drain(&self) -> Vec<FocusRequest> {
94        std::mem::take(&mut *self.0.borrow_mut())
95    }
96
97    pub fn is_empty(&self) -> bool {
98        self.0.borrow().is_empty()
99    }
100}
101
102impl Drop for FocusContext {
103    fn drop(&mut self) {
104        ACTIVE.with(|active| active.replace(self.0.take()));
105    }
106}
107
108impl FocusHandle {
109    pub fn has_focus(&self) -> bool {
110        self.0.direct.get(|| false)
111    }
112
113    pub fn focus_within(&self) -> bool {
114        self.0.within.get(|| false)
115    }
116
117    #[doc(hidden)]
118    pub fn publish(&self, direct: bool, within: bool) {
119        self.0.direct.set_if_changed(direct);
120        self.0.within.set_if_changed(within);
121    }
122
123    pub fn request(&self, action: FocusAction) {
124        ACTIVE.with(|active| {
125            if let Some(requests) = &*active.borrow() {
126                requests.0.borrow_mut().push(FocusRequest {
127                    target: self.clone(),
128                    action,
129                });
130            }
131        });
132    }
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138
139    #[test]
140    fn direct_and_within_focus_have_independent_dependencies() {
141        let handle = FocusHandle::default();
142        let direct = Property::default();
143        let within = Property::default();
144        assert!(!direct.get(|| handle.has_focus()));
145        assert!(!within.get(|| handle.focus_within()));
146        handle.publish(false, true);
147        assert!(!direct.is_dirty());
148        assert!(within.is_dirty());
149        assert!(within.get(|| handle.focus_within()));
150        handle.publish(true, true);
151        assert!(direct.is_dirty());
152        assert!(!within.is_dirty());
153    }
154}