Skip to main content

crabshell_ui/
keyboard.rs

1//! Keyboard input: the focused button, Tab between buttons, and key
2//! handlers.
3//!
4//! The platform calls [`Window::keyboard_enter`], [`Window::key`] and
5//! [`Window::keyboard_leave`] for the window that has the keyboard. A key
6//! goes to the focused button's `on_key`, then to the window's, and if
7//! neither handled it, Tab moves the focus and Enter or Space clicks the
8//! focused button. Handlers run with the tree released, inside
9//! `catch_unwind`.
10
11use 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/// A key press, or a repeat of a key held down.
25#[derive(Clone, Debug, PartialEq, Eq)]
26pub struct KeyEvent {
27  /// Which key, as the keyboard layout names it.
28  pub key: Key,
29  /// The text it types, if any, with Shift and the layout applied:
30  /// `"A"` for Shift+a. Keys like Enter and Ctrl combinations type none.
31  pub text: Option<String>,
32  /// The modifiers held.
33  pub modifiers: Modifiers,
34  /// Whether this is a repeat of a key held down.
35  pub repeat: bool,
36}
37
38/// A key, as the keyboard layout names it.
39#[derive(Clone, Debug, PartialEq, Eq)]
40pub enum Key {
41  /// Enter or Return, on the main keys or the keypad.
42  Enter,
43  /// Escape.
44  Escape,
45  /// Tab, with or without Shift.
46  Tab,
47  /// Backspace.
48  Backspace,
49  /// Delete.
50  Delete,
51  /// The left arrow.
52  Left,
53  /// The right arrow.
54  Right,
55  /// The up arrow.
56  Up,
57  /// The down arrow.
58  Down,
59  /// Home.
60  Home,
61  /// End.
62  End,
63  /// Page Up.
64  PageUp,
65  /// Page Down.
66  PageDown,
67  /// A function key, from F1.
68  Function(u8),
69  /// A key that stands for a character, such as `'a'`, `'A'` with Shift,
70  /// or `' '` for the space bar.
71  Character(char),
72  /// Any other key, by its XKB keysym, such as `0xffe1` for the left
73  /// Shift.
74  Other(u32),
75}
76
77/// What a key asks of the clipboard.
78#[derive(Clone, Debug, PartialEq, Eq)]
79pub enum Clipboard {
80  /// Offer this text as the clipboard's.
81  Copy(String),
82  /// Read the clipboard and [`paste`](Window::paste) it into the focused
83  /// field.
84  Paste,
85}
86
87/// The modifier keys held.
88#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
89pub struct Modifiers {
90  /// Control.
91  pub ctrl: bool,
92  /// Alt.
93  pub alt: bool,
94  /// Shift.
95  pub shift: bool,
96  /// The logo key, also called Super or the Windows key.
97  pub logo: bool,
98}
99
100/// How many lines PageUp and PageDown move in a text area outside a
101/// scroll view.
102const PAGE_LINES: f32 = 10.0;
103
104pub(crate) type KeyHandler = Rc<Handler<dyn Fn(&Cx, &KeyEvent) -> bool>>;
105
106/// Who has the keyboard in a window.
107#[derive(Default)]
108pub(crate) struct Keyboard {
109  /// The window has the keyboard.
110  pub(crate) entered: bool,
111  /// The focused button or field, kept while the keyboard is elsewhere.
112  pub(crate) focused: Option<NodeId>,
113  /// The link span of the focused text that Tab stopped on.
114  pub(crate) link: Option<usize>,
115  /// The window's own `on_key`.
116  pub(crate) handler: Option<KeyHandler>,
117  /// The modifiers held as the platform last said, which a press reads.
118  pub(crate) modifiers: Modifiers,
119}
120
121impl Keyboard {
122  /// Forgets nodes that were removed from the tree.
123  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  /// The keyboard entered the window: its focused button shows its focus
133  /// style again.
134  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  /// The keyboard left the window. The focused button stays focused for
145  /// when it comes back.
146  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  /// The modifiers held on the seat, which the platform tells before a
158  /// pointer button goes down: Shift and a press extend a selection.
159  pub fn set_modifiers(&self, modifiers: Modifiers) {
160    borrow(&self.tree).keyboard.modifiers = modifiers;
161  }
162
163  /// A key was pressed or repeated. A focused text field edits with it
164  /// first. Then the focused button's `on_key` gets it, then the
165  /// window's; a handler returns `true` when it used the key. Otherwise
166  /// Tab and Shift+Tab move the focus between buttons and fields, and
167  /// Enter or Space clicks the focused button.
168  ///
169  /// Returns what the platform should do with the clipboard: copy a
170  /// field's selection on Ctrl+C or Ctrl+X, or paste into the focused
171  /// field with [`paste`](Self::paste) on Ctrl+V.
172  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        // A signal whose owner is gone just isn't written.
177        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  /// The path of the focused button, for tests and logs.
205  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  /// Marks `id`, a button or field, as showing focus or not. Unlike a
214  /// hover change, a layout this causes checks the hover again: buttons
215  /// may have moved under the pointer.
216  fn show_focus(&mut self, id: Option<NodeId>, shown: bool) {
217    let Some(id) = id else {
218      return;
219    };
220    // A focused link draws lit; text fields show no ring either.
221    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  /// Moves the focus to `id`. It shows once the window has the keyboard.
252  /// A hidden node, or one inside a hidden widget, is refused.
253  pub(crate) fn focus(&mut self, id: Option<NodeId>) {
254    self.focus_link(id, None);
255  }
256
257  /// Drops the focus from text `id` if the link span it is on is no
258  /// longer a link, so Tab starts again from the first stop.
259  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  /// Moves the focus to `id`, on its link span `link` if it is a text.
273  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    // What an input method was composing there is dropped with it.
287    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    // The next layout scrolls a newly focused field's caret into view.
303    if let Some(id) = id {
304      self.update_input(id, |_| {});
305    }
306  }
307
308  /// What `event` does to the focused text field, if one is focused and
309  /// uses the key.
310  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      // Any other move forgets the line's end and the place across.
326      input.upstream = None;
327      input.goal = None;
328      input.edit.key(event, !input.password)
329    });
330    // A selection made with the keys becomes the primary selection.
331    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        // Without its own `on_accept`, Enter goes on to the window.
353        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  /// How far PageUp and PageDown move in node `id`: the height of the
373  /// innermost scroll view around it that scrolls up and down, if any.
374  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  /// The enabled buttons, the fields and the links of texts with an
390  /// `on_link`, in the order they are laid out: depth first, in child
391  /// order, a text's links in text order.
392  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      // A hidden widget is skipped with everything in it.
397      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    // Reading the handlers doesn't make anything depend on them.
422    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  /// What a key nobody handled does: Tab moves the focus, Enter and Space
440  /// click the focused button.
441  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
475/// What a key did in a text field, once the tree is released.
476enum Typed {
477  /// The text changed; the signal gets it. A cut also copies.
478  Edited(Signal<String>, String, Option<Clipboard>),
479  /// The platform should copy or paste.
480  Clipboard(Clipboard),
481  /// Only the caret or selection moved, already in the tree.
482  Moved,
483  /// Enter: the field's `on_accept` runs.
484  Accept(AcceptCall),
485}
486
487/// A field's `on_accept`, to run once the tree is released.
488struct 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
503/// A key handler to run once the tree is released.
504struct KeyCall {
505  cx: Cx,
506  path: Rc<str>,
507  handler: KeyHandler,
508}
509
510impl KeyCall {
511  /// Whether the handler used the key. One that panicked didn't.
512  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}