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    EditTableCell { row: i64, column: i64 },
32    CancelTableEdit,
33}
34
35/// A programmatic edit using the same selection, validation and history as keyboard input.
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub enum TextCommand {
38    SelectAll,
39    ClearSelection,
40    SetSelection { anchor: i64, focus: i64 },
41    Undo,
42    Redo,
43    Cut,
44    Copy,
45    Paste,
46}
47
48/// Commands lowered from XR focus and editor methods.
49#[doc(hidden)]
50#[derive(Clone, Copy, Debug)]
51pub enum FocusCommandMethod {
52    Focus,
53    Clear,
54    SelectAll,
55    ClearSelection,
56    SetSelection,
57    Undo,
58    Redo,
59    Cut,
60    Copy,
61    Paste,
62    EditTableCell,
63    CancelTableEdit,
64}
65
66impl FocusCommandMethod {
67    pub fn parse(name: &str) -> Option<Self> {
68        Some(match name {
69            "focus" => Self::Focus,
70            "clear" => Self::Clear,
71            "select-all" => Self::SelectAll,
72            "clear-selection" => Self::ClearSelection,
73            "set-selection-offsets" => Self::SetSelection,
74            "undo" => Self::Undo,
75            "redo" => Self::Redo,
76            "cut" => Self::Cut,
77            "copy" => Self::Copy,
78            "paste" => Self::Paste,
79            "edit-cell" => Self::EditTableCell,
80            "cancel-edit" => Self::CancelTableEdit,
81            _ => return None,
82        })
83    }
84
85    pub fn action(self, operands: &[i64]) -> Option<FocusAction> {
86        let text = match (self, operands) {
87            (Self::Focus, []) => return Some(FocusAction::Focus),
88            (Self::Clear, []) => return Some(FocusAction::Clear),
89            (Self::SelectAll, []) => TextCommand::SelectAll,
90            (Self::ClearSelection, []) => TextCommand::ClearSelection,
91            (Self::SetSelection, &[anchor, focus]) => TextCommand::SetSelection { anchor, focus },
92            (Self::Undo, []) => TextCommand::Undo,
93            (Self::Redo, []) => TextCommand::Redo,
94            (Self::Cut, []) => TextCommand::Cut,
95            (Self::Copy, []) => TextCommand::Copy,
96            (Self::Paste, []) => TextCommand::Paste,
97            (Self::EditTableCell, &[row, column]) => {
98                return Some(FocusAction::EditTableCell { row, column });
99            }
100            (Self::CancelTableEdit, []) => return Some(FocusAction::CancelTableEdit),
101            _ => return None,
102        };
103        Some(FocusAction::Text(text))
104    }
105}
106
107#[doc(hidden)]
108pub fn is_focus_handler(name: &str) -> bool {
109    matches!(
110        name,
111        "focus-gained" | "focus-lost" | "focus-changed-event" | "focus-within-changed"
112    )
113}
114
115#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
116pub enum FocusReason {
117    #[default]
118    Programmatic,
119    TabNavigation,
120    PointerClick,
121    PopupActivation,
122    WindowActivation,
123    Accessibility,
124    LayoutChange,
125    KeyboardNavigation,
126}
127
128#[derive(Clone, Copy, Debug, PartialEq, Eq)]
129pub enum FocusEvent {
130    Gained(FocusReason),
131    Lost(FocusReason),
132    Within { focused: bool, reason: FocusReason },
133}
134
135impl FocusEvent {
136    #[doc(hidden)]
137    pub fn is_loss(self) -> bool {
138        matches!(self, Self::Lost(_) | Self::Within { focused: false, .. })
139    }
140}
141
142pub struct FocusRequest {
143    pub target: FocusHandle,
144    pub action: FocusAction,
145}
146
147/// A window's commands, drained against the scene prepared after the callback.
148#[derive(Clone, Default)]
149pub struct FocusRequests(Rc<RefCell<Vec<FocusRequest>>>);
150
151thread_local! {
152    static ACTIVE: RefCell<Option<FocusRequests>> = const { RefCell::new(None) };
153}
154
155pub struct FocusContext(Option<FocusRequests>);
156
157impl FocusRequests {
158    pub fn enter(&self) -> FocusContext {
159        FocusContext(ACTIVE.with(|active| active.replace(Some(self.clone()))))
160    }
161
162    pub fn drain(&self) -> Vec<FocusRequest> {
163        std::mem::take(&mut *self.0.borrow_mut())
164    }
165
166    pub fn is_empty(&self) -> bool {
167        self.0.borrow().is_empty()
168    }
169}
170
171impl Drop for FocusContext {
172    fn drop(&mut self) {
173        ACTIVE.with(|active| active.replace(self.0.take()));
174    }
175}
176
177impl FocusHandle {
178    pub fn has_focus(&self) -> bool {
179        self.0.direct.get(|| false)
180    }
181
182    pub fn focus_within(&self) -> bool {
183        self.0.within.get(|| false)
184    }
185
186    #[doc(hidden)]
187    pub fn publish(&self, direct: bool, within: bool) {
188        self.0.direct.set_if_changed(direct);
189        self.0.within.set_if_changed(within);
190    }
191
192    pub fn request(&self, action: FocusAction) {
193        ACTIVE.with(|active| {
194            if let Some(requests) = &*active.borrow() {
195                requests.0.borrow_mut().push(FocusRequest {
196                    target: self.clone(),
197                    action,
198                });
199            }
200        });
201    }
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207
208    #[test]
209    fn direct_and_within_focus_have_independent_dependencies() {
210        let handle = FocusHandle::default();
211        let direct = Property::default();
212        let within = Property::default();
213        assert!(!direct.get(|| handle.has_focus()));
214        assert!(!within.get(|| handle.focus_within()));
215        handle.publish(false, true);
216        assert!(!direct.is_dirty());
217        assert!(within.is_dirty());
218        assert!(within.get(|| handle.focus_within()));
219        handle.publish(true, true);
220        assert!(direct.is_dirty());
221        assert!(!within.is_dirty());
222    }
223}