1use crate::Property;
2use std::{cell::RefCell, fmt, rc::Rc};
3
4#[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#[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#[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 FocusHandler::ALL
110 .iter()
111 .any(|handler| handler.name() == name)
112}
113
114#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
115pub enum FocusReason {
116 #[default]
117 Programmatic,
118 TabNavigation,
119 PointerClick,
120 PopupActivation,
121 WindowActivation,
122 Accessibility,
123 LayoutChange,
124 KeyboardNavigation,
125}
126
127#[derive(Clone, Copy, Debug, PartialEq, Eq)]
128pub enum FocusEvent {
129 Gained(FocusReason),
130 Lost(FocusReason),
131 Within { focused: bool, reason: FocusReason },
132}
133
134#[derive(Clone, Copy, Debug)]
135#[doc(hidden)]
136pub enum FocusHandler {
137 Gained,
138 Lost,
139 Changed,
140 Within,
141}
142
143impl FocusHandler {
144 pub const ALL: [Self; 4] = [Self::Gained, Self::Lost, Self::Changed, Self::Within];
145
146 pub fn name(self) -> &'static str {
147 match self {
148 Self::Gained => "focus-gained",
149 Self::Lost => "focus-lost",
150 Self::Changed => "focus-changed-event",
151 Self::Within => "focus-within-changed",
152 }
153 }
154}
155
156impl FocusEvent {
157 #[doc(hidden)]
158 pub fn is_loss(self) -> bool {
159 matches!(self, Self::Lost(_) | Self::Within { focused: false, .. })
160 }
161
162 #[doc(hidden)]
163 pub fn try_deliver<E>(
164 self,
165 mut notify: impl FnMut(FocusHandler, bool, FocusReason) -> Result<bool, E>,
166 ) -> Result<bool, E> {
167 let (handler, focused, reason) = match self {
168 Self::Gained(reason) => (FocusHandler::Gained, true, reason),
169 Self::Lost(reason) => (FocusHandler::Lost, false, reason),
170 Self::Within { focused, reason } => {
171 return notify(FocusHandler::Within, focused, reason);
172 }
173 };
174 let handled = notify(handler, focused, reason)?;
175 Ok(notify(FocusHandler::Changed, focused, reason)? || handled)
176 }
177
178 #[doc(hidden)]
179 pub fn deliver(self, mut notify: impl FnMut(FocusHandler, bool, FocusReason) -> bool) -> bool {
180 self.try_deliver(|handler, focused, reason| {
181 Ok::<_, std::convert::Infallible>(notify(handler, focused, reason))
182 })
183 .unwrap_or_else(|error| match error {})
184 }
185}
186
187pub struct FocusRequest {
188 pub target: FocusHandle,
189 pub action: FocusAction,
190}
191
192#[derive(Clone, Default)]
194pub struct FocusRequests(Rc<RefCell<Vec<FocusRequest>>>);
195
196thread_local! {
197 static ACTIVE: RefCell<Option<FocusRequests>> = const { RefCell::new(None) };
198}
199
200pub struct FocusContext(Option<FocusRequests>);
201
202impl FocusRequests {
203 pub fn enter(&self) -> FocusContext {
204 FocusContext(ACTIVE.with(|active| active.replace(Some(self.clone()))))
205 }
206
207 pub fn drain(&self) -> Vec<FocusRequest> {
208 std::mem::take(&mut *self.0.borrow_mut())
209 }
210
211 pub fn is_empty(&self) -> bool {
212 self.0.borrow().is_empty()
213 }
214}
215
216impl Drop for FocusContext {
217 fn drop(&mut self) {
218 ACTIVE.with(|active| active.replace(self.0.take()));
219 }
220}
221
222impl FocusHandle {
223 pub fn has_focus(&self) -> bool {
224 self.0.direct.get(|| false)
225 }
226
227 pub fn focus_within(&self) -> bool {
228 self.0.within.get(|| false)
229 }
230
231 #[doc(hidden)]
232 pub fn publish(&self, direct: bool, within: bool) {
233 self.0.direct.set_if_changed(direct);
234 self.0.within.set_if_changed(within);
235 }
236
237 pub fn request(&self, action: FocusAction) {
238 ACTIVE.with(|active| {
239 if let Some(requests) = &*active.borrow() {
240 requests.0.borrow_mut().push(FocusRequest {
241 target: self.clone(),
242 action,
243 });
244 }
245 });
246 }
247}
248
249#[cfg(test)]
250mod tests {
251 use super::*;
252
253 #[test]
254 fn direct_and_within_focus_have_independent_dependencies() {
255 let handle = FocusHandle::default();
256 let direct = Property::default();
257 let within = Property::default();
258 assert!(!direct.get(|| handle.has_focus()));
259 assert!(!within.get(|| handle.focus_within()));
260 handle.publish(false, true);
261 assert!(!direct.is_dirty());
262 assert!(within.is_dirty());
263 assert!(within.get(|| handle.focus_within()));
264 handle.publish(true, true);
265 assert!(direct.is_dirty());
266 assert!(!within.is_dirty());
267 }
268}