1use std::rc::Rc;
12
13use crabshell_reactive::{Signal, untrack};
14
15use crate::cx::Cx;
16use crate::edit::Keyed;
17use crate::input::{Handler, run_isolated};
18use crate::text_input::AcceptHandler;
19use crate::tree::{Change, NodeId, NodeKind, Tree, borrow};
20use crate::window::Window;
21
22#[derive(Clone, Debug, PartialEq, Eq)]
24pub struct KeyEvent {
25 pub key: Key,
27 pub text: Option<String>,
30 pub modifiers: Modifiers,
32 pub repeat: bool,
34}
35
36#[derive(Clone, Debug, PartialEq, Eq)]
38pub enum Key {
39 Enter,
41 Escape,
43 Tab,
45 Backspace,
47 Delete,
49 Left,
51 Right,
53 Up,
55 Down,
57 Home,
59 End,
61 PageUp,
63 PageDown,
65 Function(u8),
67 Character(char),
70 Other(u32),
73}
74
75#[derive(Clone, Debug, PartialEq, Eq)]
77pub enum Clipboard {
78 Copy(String),
80 Paste,
83}
84
85#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
87pub struct Modifiers {
88 pub ctrl: bool,
90 pub alt: bool,
92 pub shift: bool,
94 pub logo: bool,
96}
97
98pub(crate) type KeyHandler = Rc<Handler<dyn Fn(&Cx, &KeyEvent) -> bool>>;
99
100#[derive(Default)]
102pub(crate) struct Keyboard {
103 pub(crate) entered: bool,
105 pub(crate) focused: Option<NodeId>,
107 pub(crate) handler: Option<KeyHandler>,
109}
110
111impl Keyboard {
112 pub(crate) fn forget(&mut self, removed: &[NodeId]) {
114 if self.focused.is_some_and(|id| removed.contains(&id)) {
115 self.focused = None;
116 }
117 }
118}
119
120impl Window {
121 pub fn keyboard_enter(&self) {
124 let mut tree = borrow(&self.tree);
125 tree.keyboard.entered = true;
126 let focused = tree.keyboard.focused;
127 tree.show_focus(focused, true);
128 }
129
130 pub fn keyboard_leave(&self) {
133 let mut tree = borrow(&self.tree);
134 tree.keyboard.entered = false;
135 let focused = tree.keyboard.focused;
136 tree.show_focus(focused, false);
137 }
138
139 pub fn key(&self, event: &KeyEvent) -> Option<Clipboard> {
149 let typed = borrow(&self.tree).input_key(event);
150 match typed {
151 Some(Typed::Edited(signal, text, clipboard)) => {
152 signal.try_set(text);
154 return clipboard;
155 }
156 Some(Typed::Clipboard(clipboard)) => return Some(clipboard),
157 Some(Typed::Moved) => return None,
158 Some(Typed::Accept(call)) => {
159 call.run();
160 return None;
161 }
162 None => {}
163 }
164 let (button, window) = {
165 let tree = self.tree.borrow();
166 (tree.focused_key_call(), tree.window_key_call())
167 };
168 for call in [button, window].into_iter().flatten() {
169 if call.run(event) {
170 return None;
171 }
172 }
173 let click = borrow(&self.tree).default_key(event);
174 if let Some(click) = click {
175 click.run();
176 }
177 None
178 }
179
180 pub fn focused(&self) -> Option<String> {
182 let tree = self.tree.borrow();
183 let id = tree.keyboard.focused?;
184 tree.node(id).map(|node| node.path.to_string())
185 }
186}
187
188impl Tree {
189 fn show_focus(&mut self, id: Option<NodeId>, shown: bool) {
193 let Some(id) = id else {
194 return;
195 };
196 if matches!(
197 self.node(id).map(|node| &node.kind),
198 Some(NodeKind::Input(_))
199 ) {
200 self.update(id, |node| match &mut node.kind {
201 NodeKind::Input(input) if input.focused != shown => {
202 input.focused = shown;
203 Change::Paint
204 }
205 _ => Change::None,
206 });
207 } else {
208 self.update_button_style(id, |button| button.focused = shown);
209 }
210 }
211
212 pub(crate) fn focus(&mut self, id: Option<NodeId>) {
215 if id.is_some_and(|id| !self.shown(id)) {
216 return;
217 }
218 let old = std::mem::replace(&mut self.keyboard.focused, id);
219 if old != id {
220 if let Some(old) = old
222 && matches!(self.node(old).map(|node| &node.kind), Some(NodeKind::Input(input)) if input.preedit.is_some())
223 {
224 self.update_input(old, |input| {
225 input.preedit = None;
226 input.refresh();
227 });
228 }
229 self.show_focus(old, false);
230 let entered = self.keyboard.entered;
231 self.show_focus(id, entered);
232 }
233 }
234
235 fn input_key(&mut self, event: &KeyEvent) -> Option<Typed> {
238 let id = self.keyboard.focused?;
239 let NodeKind::Input(input) = &mut self.node_mut(id)?.kind else {
240 return None;
241 };
242 let keyed = input.edit.key(event, !input.password);
243 let accept = keyed == Keyed::Accept;
244 let typed = match keyed {
245 Keyed::Unused => return None,
246 Keyed::Moved => Typed::Moved,
247 Keyed::Edited => Typed::Edited(input.signal, input.edit.text.clone(), None),
248 Keyed::Copy(text) => Typed::Clipboard(Clipboard::Copy(text)),
249 Keyed::Cut(text) => Typed::Edited(
250 input.signal,
251 input.edit.text.clone(),
252 Some(Clipboard::Copy(text)),
253 ),
254 Keyed::Paste => Typed::Clipboard(Clipboard::Paste),
255 Keyed::Accept => {
256 let handler = untrack(|| input.on_accept.try_with(Option::clone)).flatten();
257 let text = input.edit.text.clone();
258 let node = self.node(id)?;
259 Typed::Accept(AcceptCall {
261 cx: node.cx.clone(),
262 path: Rc::clone(&node.path),
263 handler: handler?,
264 text,
265 })
266 }
267 };
268 if !accept {
269 self.update_input(id, |input| {
270 input.refresh();
271 });
272 }
273 Some(typed)
274 }
275
276 fn focusable(&self) -> Vec<NodeId> {
279 let mut found = Vec::new();
280 let mut pending = vec![self.root];
281 while let Some(id) = pending.pop() {
282 if self.node(id).is_some_and(|node| !node.visible) {
284 continue;
285 }
286 if let Some(node) = self.node(id)
287 && match &node.kind {
288 NodeKind::Button(button) => button.enabled,
289 NodeKind::Input(_) => true,
290 _ => false,
291 }
292 {
293 found.push(id);
294 }
295 let mut children = self.taffy.children(id).unwrap_or_default();
296 children.reverse();
297 pending.extend(children);
298 }
299 found
300 }
301
302 fn focused_key_call(&self) -> Option<KeyCall> {
303 let id = self.keyboard.focused?;
304 let node = self.node(id)?;
305 let NodeKind::Button(button) = &node.kind else {
306 return None;
307 };
308 let handler = untrack(|| button.handlers.try_with(|handlers| handlers.key.clone()))??;
310 Some(KeyCall {
311 cx: node.cx.clone(),
312 path: Rc::clone(&node.path),
313 handler,
314 })
315 }
316
317 fn window_key_call(&self) -> Option<KeyCall> {
318 let node = self.node(self.root)?;
319 Some(KeyCall {
320 cx: node.cx.clone(),
321 path: Rc::clone(&node.path),
322 handler: self.keyboard.handler.clone()?,
323 })
324 }
325
326 fn default_key(&mut self, event: &KeyEvent) -> Option<crate::input::Call> {
329 match event.key {
330 Key::Tab => {
331 let buttons = self.focusable();
332 let at = self
333 .keyboard
334 .focused
335 .and_then(|id| buttons.iter().position(|button| *button == id));
336 let count = buttons.len();
337 let next = match (at, event.modifiers.shift) {
338 _ if count == 0 => None,
339 (None, false) => Some(0),
340 (None, true) => Some(count - 1),
341 (Some(at), false) => Some((at + 1) % count),
342 (Some(at), true) => Some((at + count - 1) % count),
343 };
344 self.focus(next.map(|next| buttons[next]));
345 None
346 }
347 Key::Enter | Key::Character(' ') => self.click(self.keyboard.focused?),
348 _ => None,
349 }
350 }
351}
352
353enum Typed {
355 Edited(Signal<String>, String, Option<Clipboard>),
357 Clipboard(Clipboard),
359 Moved,
361 Accept(AcceptCall),
363}
364
365struct AcceptCall {
367 cx: Cx,
368 path: Rc<str>,
369 handler: AcceptHandler,
370 text: String,
371}
372
373impl AcceptCall {
374 fn run(self) {
375 run_isolated(&self.path, "on_accept", self.handler, |f| {
376 f(&self.cx, &self.text)
377 });
378 }
379}
380
381struct KeyCall {
383 cx: Cx,
384 path: Rc<str>,
385 handler: KeyHandler,
386}
387
388impl KeyCall {
389 fn run(self, event: &KeyEvent) -> bool {
391 run_isolated(&self.path, "on_key", self.handler, |f| f(&self.cx, event)).unwrap_or(false)
392 }
393}