1use std::rc::Rc;
12
13use crabshell_reactive::{Signal, untrack};
14
15use crate::access::AccessEvent;
16use crate::cx::Cx;
17use crate::edit::Keyed;
18use crate::input::{Handler, run_isolated};
19use crate::select::copy_key;
20use crate::text_input::AcceptHandler;
21use crate::tree::{Change, NodeId, NodeKind, Tree, borrow};
22use crate::window::Window;
23
24#[derive(Clone, Debug, PartialEq, Eq)]
26pub struct KeyEvent {
27 pub key: Key,
29 pub text: Option<String>,
32 pub modifiers: Modifiers,
34 pub repeat: bool,
36}
37
38#[derive(Clone, Debug, PartialEq, Eq)]
40pub enum Key {
41 Enter,
43 Escape,
45 Tab,
47 Backspace,
49 Delete,
51 Left,
53 Right,
55 Up,
57 Down,
59 Home,
61 End,
63 PageUp,
65 PageDown,
67 Function(u8),
69 Character(char),
72 Other(u32),
75}
76
77#[derive(Clone, Debug, PartialEq, Eq)]
79pub enum Clipboard {
80 Copy(String),
82 Paste,
85}
86
87#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
89pub struct Modifiers {
90 pub ctrl: bool,
92 pub alt: bool,
94 pub shift: bool,
96 pub logo: bool,
98}
99
100const PAGE_LINES: f32 = 10.0;
103
104pub(crate) type KeyHandler = Rc<Handler<dyn Fn(&Cx, &KeyEvent) -> bool>>;
105
106#[derive(Default)]
108pub(crate) struct Keyboard {
109 pub(crate) entered: bool,
111 pub(crate) focused: Option<NodeId>,
113 pub(crate) link: Option<usize>,
115 pub(crate) handler: Option<KeyHandler>,
117 pub(crate) modifiers: Modifiers,
119}
120
121impl Keyboard {
122 pub(crate) fn forget(&mut self, removed: &[NodeId]) {
124 if self.focused.is_some_and(|id| removed.contains(&id)) {
125 self.focused = None;
126 self.link = None;
127 }
128 }
129}
130
131impl Window {
132 pub fn keyboard_enter(&self) {
135 let mut tree = borrow(&self.tree);
136 if !std::mem::replace(&mut tree.keyboard.entered, true) {
137 let root = tree.root;
138 tree.node_event(root, |id| AccessEvent::Active(id, true));
139 }
140 let focused = tree.keyboard.focused;
141 tree.show_focus(focused, true);
142 }
143
144 pub fn keyboard_leave(&self) {
147 let mut tree = borrow(&self.tree);
148 let was = std::mem::replace(&mut tree.keyboard.entered, false);
149 let focused = tree.keyboard.focused;
150 tree.show_focus(focused, false);
151 if was {
152 let root = tree.root;
153 tree.node_event(root, |id| AccessEvent::Active(id, false));
154 }
155 }
156
157 pub fn set_modifiers(&self, modifiers: Modifiers) {
160 borrow(&self.tree).keyboard.modifiers = modifiers;
161 }
162
163 pub fn key(&self, event: &KeyEvent) -> Option<Clipboard> {
173 let typed = borrow(&self.tree).input_key(event);
174 match typed {
175 Some(Typed::Edited(signal, text, clipboard)) => {
176 signal.try_set(text);
178 return clipboard;
179 }
180 Some(Typed::Clipboard(clipboard)) => return Some(clipboard),
181 Some(Typed::Moved) => return None,
182 Some(Typed::Accept(call)) => {
183 call.run();
184 return None;
185 }
186 None => {}
187 }
188 let (button, window) = {
189 let tree = self.tree.borrow();
190 (tree.focused_key_call(), tree.window_key_call())
191 };
192 for call in [button, window].into_iter().flatten() {
193 if call.run(event) {
194 return None;
195 }
196 }
197 let click = borrow(&self.tree).default_key(event);
198 if let Some(click) = click {
199 click.run();
200 }
201 None
202 }
203
204 pub fn focused(&self) -> Option<String> {
206 let tree = self.tree.borrow();
207 let id = tree.keyboard.focused?;
208 tree.node(id).map(|node| node.path.to_string())
209 }
210}
211
212impl Tree {
213 fn show_focus(&mut self, id: Option<NodeId>, shown: bool) {
217 let Some(id) = id else {
218 return;
219 };
220 if let Some(NodeKind::Text(_)) = self.node(id).map(|node| &node.kind) {
222 let link = self.keyboard.link.filter(|_| shown);
223 self.light_link(id, true, link);
224 return;
225 }
226 let was = match self.node(id).map(|node| &node.kind) {
227 Some(NodeKind::Input(input)) => input.focused,
228 Some(NodeKind::Button(button)) => button.focused,
229 _ => return,
230 };
231 if was == shown {
232 return;
233 }
234 if matches!(
235 self.node(id).map(|node| &node.kind),
236 Some(NodeKind::Input(_))
237 ) {
238 self.update(id, |node| match &mut node.kind {
239 NodeKind::Input(input) => {
240 input.focused = shown;
241 Change::Paint
242 }
243 _ => Change::None,
244 });
245 } else {
246 self.update_button_style(id, |button| button.focused = shown);
247 }
248 self.node_event(id, |id| AccessEvent::Focused(id, shown));
249 }
250
251 pub(crate) fn focus(&mut self, id: Option<NodeId>) {
254 self.focus_link(id, None);
255 }
256
257 pub(crate) fn drop_stale_link_focus(&mut self, id: NodeId) {
260 let (Some(focused), Some(link)) = (self.keyboard.focused, self.keyboard.link) else {
261 return;
262 };
263 let still = match self.node(id).map(|node| &node.kind) {
264 Some(NodeKind::Text(text)) => text.spans.get(link).is_some_and(|span| span.link.is_some()),
265 _ => false,
266 };
267 if focused == id && !still {
268 self.focus(None);
269 }
270 }
271
272 fn focus_link(&mut self, id: Option<NodeId>, link: Option<usize>) {
274 if id.is_some_and(|id| !self.shown(id)) {
275 return;
276 }
277 if self.keyboard.focused == id {
278 if self.keyboard.link != link {
279 self.keyboard.link = link;
280 let entered = self.keyboard.entered;
281 self.show_focus(id, entered);
282 }
283 return;
284 }
285 let old = std::mem::replace(&mut self.keyboard.focused, id);
286 if let Some(old) = old
288 && matches!(self.node(old).map(|node| &node.kind), Some(NodeKind::Input(input)) if input.preedit.is_some())
289 {
290 self.update_input(old, |input| {
291 input.preedit = None;
292 input.refresh();
293 });
294 }
295 if let Some(old) = old {
296 self.drop_selection(old);
297 }
298 self.show_focus(old, false);
299 self.keyboard.link = link;
300 let entered = self.keyboard.entered;
301 self.show_focus(id, entered);
302 if let Some(id) = id {
304 self.update_input(id, |_| {});
305 }
306 }
307
308 fn input_key(&mut self, event: &KeyEvent) -> Option<Typed> {
311 let id = self.keyboard.focused?;
312 let view = self.page_height(id);
313 let input = match &mut self.node_mut(id)?.kind {
314 NodeKind::Input(input) => input,
315 NodeKind::Text(text) => return copy_key(text, event).map(Typed::Clipboard),
316 _ => return None,
317 };
318 let page = view.unwrap_or(PAGE_LINES * input.text.buffer.metrics().line_height);
319 let keyed = match input.edit.multiline {
320 true => input.line_key(event, page),
321 false => None,
322 };
323 let was = input.edit.selection();
324 let keyed = keyed.unwrap_or_else(|| {
325 input.upstream = None;
327 input.goal = None;
328 input.edit.key(event, !input.password)
329 });
330 let selected = input
332 .edit
333 .selection()
334 .filter(|now| keyed == Keyed::Moved && Some(now) != was.as_ref() && !input.password);
335 let primary = selected.and_then(|range| input.edit.text.get(range).map(str::to_owned));
336 let accept = keyed == Keyed::Accept;
337 let typed = match keyed {
338 Keyed::Unused => return None,
339 Keyed::Moved => Typed::Moved,
340 Keyed::Edited => Typed::Edited(input.signal, input.edit.text.clone(), None),
341 Keyed::Copy(text) => Typed::Clipboard(Clipboard::Copy(text)),
342 Keyed::Cut(text) => Typed::Edited(
343 input.signal,
344 input.edit.text.clone(),
345 Some(Clipboard::Copy(text)),
346 ),
347 Keyed::Paste => Typed::Clipboard(Clipboard::Paste),
348 Keyed::Accept => {
349 let handler = untrack(|| input.on_accept.try_with(Option::clone)).flatten();
350 let text = input.edit.text.clone();
351 let node = self.node(id)?;
352 Typed::Accept(AcceptCall {
354 cx: node.cx.clone(),
355 path: Rc::clone(&node.path),
356 handler: handler?,
357 text,
358 })
359 }
360 };
361 if !accept {
362 self.update_input(id, |input| {
363 input.refresh();
364 });
365 }
366 if let Some(text) = primary {
367 self.primary = Some(Clipboard::Copy(text));
368 }
369 Some(typed)
370 }
371
372 fn page_height(&self, id: NodeId) -> Option<f32> {
375 self
376 .path_to(id)
377 .into_iter()
378 .rev()
379 .find_map(|at| match &self.node(at)?.kind {
380 NodeKind::Scroll(scroll) => scroll
381 .active()
382 .iter()
383 .find(|axis| !axis.horizontal)
384 .map(|axis| axis.length),
385 _ => None,
386 })
387 }
388
389 fn focusable(&self) -> Vec<(NodeId, Option<usize>)> {
393 let mut found = Vec::new();
394 let mut pending = vec![self.root];
395 while let Some(id) = pending.pop() {
396 if self.node(id).is_some_and(|node| !node.visible) {
398 continue;
399 }
400 match self.node(id).map(|node| &node.kind) {
401 Some(NodeKind::Button(button)) if button.enabled => found.push((id, None)),
402 Some(NodeKind::Input(_)) => found.push((id, None)),
403 Some(NodeKind::Text(text)) => {
404 found.extend(text.link_stops().into_iter().map(|link| (id, Some(link))));
405 }
406 _ => {}
407 }
408 let mut children = self.taffy.children(id).unwrap_or_default();
409 children.reverse();
410 pending.extend(children);
411 }
412 found
413 }
414
415 fn focused_key_call(&self) -> Option<KeyCall> {
416 let id = self.keyboard.focused?;
417 let node = self.node(id)?;
418 let NodeKind::Button(button) = &node.kind else {
419 return None;
420 };
421 let handler = untrack(|| button.handlers.try_with(|handlers| handlers.key.clone()))??;
423 Some(KeyCall {
424 cx: node.cx.clone(),
425 path: Rc::clone(&node.path),
426 handler,
427 })
428 }
429
430 fn window_key_call(&self) -> Option<KeyCall> {
431 let node = self.node(self.root)?;
432 Some(KeyCall {
433 cx: node.cx.clone(),
434 path: Rc::clone(&node.path),
435 handler: self.keyboard.handler.clone()?,
436 })
437 }
438
439 fn default_key(&mut self, event: &KeyEvent) -> Option<crate::input::Call> {
442 match event.key {
443 Key::Tab => {
444 let buttons = self.focusable();
445 let at = self.keyboard.focused.and_then(|id| {
446 let link = self.keyboard.link;
447 buttons.iter().position(|&stop| stop == (id, link))
448 });
449 let count = buttons.len();
450 let next = match (at, event.modifiers.shift) {
451 _ if count == 0 => None,
452 (None, false) => Some(0),
453 (None, true) => Some(count - 1),
454 (Some(at), false) => Some((at + 1) % count),
455 (Some(at), true) => Some((at + count - 1) % count),
456 };
457 let (id, link) = next.map_or((None, None), |next| {
458 (Some(buttons[next].0), buttons[next].1)
459 });
460 self.focus_link(id, link);
461 None
462 }
463 Key::Enter | Key::Character(' ') => {
464 let id = self.keyboard.focused?;
465 match self.keyboard.link {
466 Some(link) => self.link_call(id, link),
467 None => self.click(id),
468 }
469 }
470 _ => None,
471 }
472 }
473}
474
475enum Typed {
477 Edited(Signal<String>, String, Option<Clipboard>),
479 Clipboard(Clipboard),
481 Moved,
483 Accept(AcceptCall),
485}
486
487struct AcceptCall {
489 cx: Cx,
490 path: Rc<str>,
491 handler: AcceptHandler,
492 text: String,
493}
494
495impl AcceptCall {
496 fn run(self) {
497 run_isolated(&self.path, "on_accept", self.handler, |f| {
498 f(&self.cx, &self.text)
499 });
500 }
501}
502
503struct KeyCall {
505 cx: Cx,
506 path: Rc<str>,
507 handler: KeyHandler,
508}
509
510impl KeyCall {
511 fn run(self, event: &KeyEvent) -> bool {
513 run_isolated(&self.path, "on_key", self.handler, |f| f(&self.cx, event)).unwrap_or(false)
514 }
515}