Skip to main content

xrack_runtime/
focus.rs

1use crate::Property;
2use std::{cell::RefCell, fmt, ops::Range, rc::Rc};
3
4/// Identity of a focus target in one component instance.
5#[derive(Clone, Default)]
6pub struct FocusHandle(Rc<FocusSignals>);
7
8/// Reactive physical press state for one observed push button.
9#[derive(Clone, Default)]
10#[doc(hidden)]
11pub struct ButtonPressHandle(Rc<Property<bool>>);
12
13impl fmt::Debug for ButtonPressHandle {
14    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
15        f.debug_struct("ButtonPressHandle").finish_non_exhaustive()
16    }
17}
18
19impl PartialEq for ButtonPressHandle {
20    fn eq(&self, other: &Self) -> bool {
21        Rc::ptr_eq(&self.0, &other.0)
22    }
23}
24
25impl ButtonPressHandle {
26    pub fn pressed(&self) -> bool {
27        self.0.get(|| false)
28    }
29
30    pub fn publish(&self, pressed: bool) {
31        self.0.set_if_changed(pressed);
32    }
33}
34
35#[derive(Default)]
36struct FocusSignals {
37    direct: Property<bool>,
38    within: Property<bool>,
39    text: Option<Box<TextSelectionSignals>>,
40    commands: Option<Box<TextCommandSignals>>,
41}
42
43#[derive(Default)]
44struct TextSelectionSignals {
45    offsets: [Property<i64>; 3],
46    selected: Property<Rc<str>>,
47}
48
49#[derive(Default)]
50struct TextCommandSignals {
51    undo: Property<bool>,
52    redo: Property<bool>,
53    cut: Property<bool>,
54    copy: Property<bool>,
55}
56
57/// Availability of commands on the active text editor.
58#[doc(hidden)]
59#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
60pub struct TextCommandAvailability {
61    pub undo: bool,
62    pub redo: bool,
63    pub cut: bool,
64    pub copy: bool,
65}
66
67impl fmt::Debug for FocusHandle {
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        f.debug_struct("FocusHandle").finish_non_exhaustive()
70    }
71}
72
73impl PartialEq for FocusHandle {
74    fn eq(&self, other: &Self) -> bool {
75        Rc::ptr_eq(&self.0, &other.0)
76    }
77}
78
79#[derive(Clone, Copy, Debug, PartialEq, Eq)]
80pub enum FocusAction {
81    Focus,
82    Clear,
83    Text(TextCommand),
84    EditTableCell { row: i64, column: i64 },
85    CancelTableEdit,
86}
87
88/// A programmatic edit using the same selection, validation and history as keyboard input.
89#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub enum TextCommand {
91    SelectAll,
92    ClearSelection,
93    SetSelection { anchor: i64, focus: i64 },
94    Undo,
95    Redo,
96    Cut,
97    Copy,
98    Paste,
99}
100
101/// Commands lowered from XR focus and editor methods.
102#[doc(hidden)]
103#[derive(Clone, Copy, Debug)]
104pub enum FocusCommandMethod {
105    Focus,
106    Clear,
107    SelectAll,
108    ClearSelection,
109    SetSelection,
110    Undo,
111    Redo,
112    Cut,
113    Copy,
114    Paste,
115    EditTableCell,
116    CancelTableEdit,
117}
118
119impl FocusCommandMethod {
120    pub fn parse(name: &str) -> Option<Self> {
121        Some(match name {
122            "focus" => Self::Focus,
123            "clear" => Self::Clear,
124            "select-all" => Self::SelectAll,
125            "clear-selection" => Self::ClearSelection,
126            "set-selection-offsets" => Self::SetSelection,
127            "undo" => Self::Undo,
128            "redo" => Self::Redo,
129            "cut" => Self::Cut,
130            "copy" => Self::Copy,
131            "paste" => Self::Paste,
132            "edit-cell" => Self::EditTableCell,
133            "cancel-edit" => Self::CancelTableEdit,
134            _ => return None,
135        })
136    }
137
138    pub fn action(self, operands: &[i64]) -> Option<FocusAction> {
139        let text = match (self, operands) {
140            (Self::Focus, []) => return Some(FocusAction::Focus),
141            (Self::Clear, []) => return Some(FocusAction::Clear),
142            (Self::SelectAll, []) => TextCommand::SelectAll,
143            (Self::ClearSelection, []) => TextCommand::ClearSelection,
144            (Self::SetSelection, &[anchor, focus]) => TextCommand::SetSelection { anchor, focus },
145            (Self::Undo, []) => TextCommand::Undo,
146            (Self::Redo, []) => TextCommand::Redo,
147            (Self::Cut, []) => TextCommand::Cut,
148            (Self::Copy, []) => TextCommand::Copy,
149            (Self::Paste, []) => TextCommand::Paste,
150            (Self::EditTableCell, &[row, column]) => {
151                return Some(FocusAction::EditTableCell { row, column });
152            }
153            (Self::CancelTableEdit, []) => return Some(FocusAction::CancelTableEdit),
154            _ => return None,
155        };
156        Some(FocusAction::Text(text))
157    }
158}
159
160#[doc(hidden)]
161pub fn is_focus_handler(name: &str) -> bool {
162    FocusHandler::ALL
163        .iter()
164        .any(|handler| handler.name() == name)
165}
166
167#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
168pub enum FocusReason {
169    #[default]
170    Programmatic,
171    TabNavigation,
172    PointerClick,
173    PopupActivation,
174    WindowActivation,
175    Accessibility,
176    LayoutChange,
177    KeyboardNavigation,
178}
179
180#[derive(Clone, Copy, Debug, PartialEq, Eq)]
181pub enum FocusEvent {
182    Gained(FocusReason),
183    Lost(FocusReason),
184    Within { focused: bool, reason: FocusReason },
185}
186
187#[derive(Clone, Copy, Debug)]
188#[doc(hidden)]
189pub enum FocusHandler {
190    Gained,
191    Lost,
192    Changed,
193    Within,
194}
195
196impl FocusHandler {
197    pub const ALL: [Self; 4] = [Self::Gained, Self::Lost, Self::Changed, Self::Within];
198
199    pub fn name(self) -> &'static str {
200        match self {
201            Self::Gained => "focus-gained",
202            Self::Lost => "focus-lost",
203            Self::Changed => "focus-changed-event",
204            Self::Within => "focus-within-changed",
205        }
206    }
207}
208
209impl FocusEvent {
210    #[doc(hidden)]
211    pub fn is_loss(self) -> bool {
212        matches!(self, Self::Lost(_) | Self::Within { focused: false, .. })
213    }
214
215    #[doc(hidden)]
216    pub fn try_deliver<E>(
217        self,
218        mut notify: impl FnMut(FocusHandler, bool, FocusReason) -> Result<bool, E>,
219    ) -> Result<bool, E> {
220        let (handler, focused, reason) = match self {
221            Self::Gained(reason) => (FocusHandler::Gained, true, reason),
222            Self::Lost(reason) => (FocusHandler::Lost, false, reason),
223            Self::Within { focused, reason } => {
224                return notify(FocusHandler::Within, focused, reason);
225            }
226        };
227        let handled = notify(handler, focused, reason)?;
228        Ok(notify(FocusHandler::Changed, focused, reason)? || handled)
229    }
230
231    #[doc(hidden)]
232    pub fn deliver(self, mut notify: impl FnMut(FocusHandler, bool, FocusReason) -> bool) -> bool {
233        self.try_deliver(|handler, focused, reason| {
234            Ok::<_, std::convert::Infallible>(notify(handler, focused, reason))
235        })
236        .unwrap_or_else(|error| match error {})
237    }
238}
239
240pub struct FocusRequest {
241    pub target: FocusHandle,
242    pub action: FocusAction,
243}
244
245/// A window's commands, drained against the scene prepared after the callback.
246#[derive(Clone, Default)]
247pub struct FocusRequests(Rc<RefCell<Vec<FocusRequest>>>);
248
249thread_local! {
250    static ACTIVE: RefCell<Option<FocusRequests>> = const { RefCell::new(None) };
251}
252
253pub struct FocusContext(Option<FocusRequests>);
254
255impl FocusRequests {
256    pub fn enter(&self) -> FocusContext {
257        FocusContext(ACTIVE.with(|active| active.replace(Some(self.clone()))))
258    }
259
260    pub fn drain(&self) -> Vec<FocusRequest> {
261        std::mem::take(&mut *self.0.borrow_mut())
262    }
263
264    pub fn is_empty(&self) -> bool {
265        self.0.borrow().is_empty()
266    }
267}
268
269impl Drop for FocusContext {
270    fn drop(&mut self) {
271        ACTIVE.with(|active| active.replace(self.0.take()));
272    }
273}
274
275impl FocusHandle {
276    #[doc(hidden)]
277    pub fn with_text_selection() -> Self {
278        Self::with_text_state(true, false)
279    }
280
281    #[doc(hidden)]
282    pub fn with_text_state(selection: bool, commands: bool) -> Self {
283        Self(Rc::new(FocusSignals {
284            text: selection.then(Box::default),
285            commands: commands.then(Box::default),
286            ..FocusSignals::default()
287        }))
288    }
289
290    #[doc(hidden)]
291    pub fn observes_text_commands(&self) -> bool {
292        self.0.commands.is_some()
293    }
294
295    #[doc(hidden)]
296    pub fn publish_text_commands(&self, commands: TextCommandAvailability) {
297        if let Some(signals) = &self.0.commands {
298            signals.undo.set_if_changed(commands.undo);
299            signals.redo.set_if_changed(commands.redo);
300            signals.cut.set_if_changed(commands.cut);
301            signals.copy.set_if_changed(commands.copy);
302        }
303    }
304
305    #[doc(hidden)]
306    pub fn clear_text_state(&self) {
307        self.publish_text_selection(0, 0..0, "");
308        self.publish_text_commands(TextCommandAvailability::default());
309    }
310
311    pub fn can_undo(&self) -> bool {
312        self.0
313            .commands
314            .as_ref()
315            .is_some_and(|signals| signals.undo.get(|| false))
316    }
317
318    pub fn can_redo(&self) -> bool {
319        self.0
320            .commands
321            .as_ref()
322            .is_some_and(|signals| signals.redo.get(|| false))
323    }
324
325    pub fn can_cut(&self) -> bool {
326        self.0
327            .commands
328            .as_ref()
329            .is_some_and(|signals| signals.cut.get(|| false))
330    }
331
332    pub fn can_copy(&self) -> bool {
333        self.0
334            .commands
335            .as_ref()
336            .is_some_and(|signals| signals.copy.get(|| false))
337    }
338
339    #[doc(hidden)]
340    pub fn observes_text_selection(&self) -> bool {
341        self.0.text.is_some()
342    }
343
344    #[doc(hidden)]
345    pub fn publish_text_selection(&self, caret: usize, selection: Range<usize>, text: &str) {
346        if let Some(signals) = &self.0.text {
347            for (offset, value) in
348                signals
349                    .offsets
350                    .iter()
351                    .zip([caret, selection.start, selection.end])
352            {
353                offset.set_if_changed(value as i64);
354            }
355            if signals.selected.explicit_value().as_deref() != Some(text) {
356                signals.selected.set(Rc::from(text));
357            }
358        }
359    }
360
361    fn text_offset(&self, index: usize) -> i64 {
362        self.0
363            .text
364            .as_ref()
365            .map_or(0, |signals| signals.offsets[index].get(|| 0))
366    }
367
368    pub fn cursor_offset(&self) -> i64 {
369        self.text_offset(0)
370    }
371
372    pub fn selection_start_offset(&self) -> i64 {
373        self.text_offset(1)
374    }
375
376    pub fn selection_end_offset(&self) -> i64 {
377        self.text_offset(2)
378    }
379
380    pub fn selected_text(&self) -> String {
381        self.0.text.as_ref().map_or_else(String::new, |signals| {
382            signals.selected.get(|| Rc::from("")).to_string()
383        })
384    }
385
386    pub fn has_focus(&self) -> bool {
387        self.0.direct.get(|| false)
388    }
389
390    pub fn focus_within(&self) -> bool {
391        self.0.within.get(|| false)
392    }
393
394    #[doc(hidden)]
395    pub fn publish(&self, direct: bool, within: bool) {
396        self.0.direct.set_if_changed(direct);
397        self.0.within.set_if_changed(within);
398    }
399
400    pub fn request(&self, action: FocusAction) {
401        ACTIVE.with(|active| {
402            if let Some(requests) = &*active.borrow() {
403                requests.0.borrow_mut().push(FocusRequest {
404                    target: self.clone(),
405                    action,
406                });
407            }
408        });
409    }
410}
411
412#[cfg(test)]
413mod tests {
414    use super::*;
415
416    #[test]
417    fn selection_start_and_selected_text_track_independently() {
418        let handle = FocusHandle::with_text_selection();
419        let start = Property::default();
420        let selected = Property::default();
421        handle.publish_text_selection(3, 1..3, "bc");
422        assert_eq!(start.get(|| handle.selection_start_offset()), 1);
423        assert_eq!(selected.get(|| handle.selected_text()), "bc");
424
425        handle.publish_text_selection(4, 1..4, "bcd");
426        assert!(!start.is_dirty());
427        assert!(selected.is_dirty());
428        assert_eq!(selected.get(|| handle.selected_text()), "bcd");
429
430        handle.publish_text_selection(1, 1..4, "bcd");
431        assert!(!start.is_dirty());
432        assert!(!selected.is_dirty());
433    }
434
435    #[test]
436    fn direct_and_within_focus_have_independent_dependencies() {
437        let handle = FocusHandle::default();
438        let direct = Property::default();
439        let within = Property::default();
440        assert!(!direct.get(|| handle.has_focus()));
441        assert!(!within.get(|| handle.focus_within()));
442        handle.publish(false, true);
443        assert!(!direct.is_dirty());
444        assert!(within.is_dirty());
445        assert!(within.get(|| handle.focus_within()));
446        handle.publish(true, true);
447        assert!(direct.is_dirty());
448        assert!(!within.is_dirty());
449    }
450}