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::cx::Cx;
16use crate::edit::Keyed;
17use crate::input::{Handler, run_isolated};
18use crate::select::copy_key;
19use crate::text_input::AcceptHandler;
20use crate::tree::{Change, NodeId, NodeKind, Tree, borrow};
21use crate::window::Window;
22
23/// A key press, or a repeat of a key held down.
24#[derive(Clone, Debug, PartialEq, Eq)]
25pub struct KeyEvent {
26  /// Which key, as the keyboard layout names it.
27  pub key: Key,
28  /// The text it types, if any, with Shift and the layout applied:
29  /// `"A"` for Shift+a. Keys like Enter and Ctrl combinations type none.
30  pub text: Option<String>,
31  /// The modifiers held.
32  pub modifiers: Modifiers,
33  /// Whether this is a repeat of a key held down.
34  pub repeat: bool,
35}
36
37/// A key, as the keyboard layout names it.
38#[derive(Clone, Debug, PartialEq, Eq)]
39pub enum Key {
40  /// Enter or Return, on the main keys or the keypad.
41  Enter,
42  /// Escape.
43  Escape,
44  /// Tab, with or without Shift.
45  Tab,
46  /// Backspace.
47  Backspace,
48  /// Delete.
49  Delete,
50  /// The left arrow.
51  Left,
52  /// The right arrow.
53  Right,
54  /// The up arrow.
55  Up,
56  /// The down arrow.
57  Down,
58  /// Home.
59  Home,
60  /// End.
61  End,
62  /// Page Up.
63  PageUp,
64  /// Page Down.
65  PageDown,
66  /// A function key, from F1.
67  Function(u8),
68  /// A key that stands for a character, such as `'a'`, `'A'` with Shift,
69  /// or `' '` for the space bar.
70  Character(char),
71  /// Any other key, by its XKB keysym, such as `0xffe1` for the left
72  /// Shift.
73  Other(u32),
74}
75
76/// What a key asks of the clipboard.
77#[derive(Clone, Debug, PartialEq, Eq)]
78pub enum Clipboard {
79  /// Offer this text as the clipboard's.
80  Copy(String),
81  /// Read the clipboard and [`paste`](Window::paste) it into the focused
82  /// field.
83  Paste,
84}
85
86/// The modifier keys held.
87#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
88pub struct Modifiers {
89  /// Control.
90  pub ctrl: bool,
91  /// Alt.
92  pub alt: bool,
93  /// Shift.
94  pub shift: bool,
95  /// The logo key, also called Super or the Windows key.
96  pub logo: bool,
97}
98
99/// How many lines PageUp and PageDown move in a text area outside a
100/// scroll view.
101const PAGE_LINES: f32 = 10.0;
102
103pub(crate) type KeyHandler = Rc<Handler<dyn Fn(&Cx, &KeyEvent) -> bool>>;
104
105/// Who has the keyboard in a window.
106#[derive(Default)]
107pub(crate) struct Keyboard {
108  /// The window has the keyboard.
109  pub(crate) entered: bool,
110  /// The focused button or field, kept while the keyboard is elsewhere.
111  pub(crate) focused: Option<NodeId>,
112  /// The link span of the focused text that Tab stopped on.
113  pub(crate) link: Option<usize>,
114  /// The window's own `on_key`.
115  pub(crate) handler: Option<KeyHandler>,
116  /// The modifiers held as the platform last said, which a press reads.
117  pub(crate) modifiers: Modifiers,
118}
119
120impl Keyboard {
121  /// Forgets nodes that were removed from the tree.
122  pub(crate) fn forget(&mut self, removed: &[NodeId]) {
123    if self.focused.is_some_and(|id| removed.contains(&id)) {
124      self.focused = None;
125      self.link = None;
126    }
127  }
128}
129
130impl Window {
131  /// The keyboard entered the window: its focused button shows its focus
132  /// style again.
133  pub fn keyboard_enter(&self) {
134    let mut tree = borrow(&self.tree);
135    tree.keyboard.entered = true;
136    let focused = tree.keyboard.focused;
137    tree.show_focus(focused, true);
138  }
139
140  /// The keyboard left the window. The focused button stays focused for
141  /// when it comes back.
142  pub fn keyboard_leave(&self) {
143    let mut tree = borrow(&self.tree);
144    tree.keyboard.entered = false;
145    let focused = tree.keyboard.focused;
146    tree.show_focus(focused, false);
147  }
148
149  /// The modifiers held on the seat, which the platform tells before a
150  /// pointer button goes down: Shift and a press extend a selection.
151  pub fn set_modifiers(&self, modifiers: Modifiers) {
152    borrow(&self.tree).keyboard.modifiers = modifiers;
153  }
154
155  /// A key was pressed or repeated. A focused text field edits with it
156  /// first. Then the focused button's `on_key` gets it, then the
157  /// window's; a handler returns `true` when it used the key. Otherwise
158  /// Tab and Shift+Tab move the focus between buttons and fields, and
159  /// Enter or Space clicks the focused button.
160  ///
161  /// Returns what the platform should do with the clipboard: copy a
162  /// field's selection on Ctrl+C or Ctrl+X, or paste into the focused
163  /// field with [`paste`](Self::paste) on Ctrl+V.
164  pub fn key(&self, event: &KeyEvent) -> Option<Clipboard> {
165    let typed = borrow(&self.tree).input_key(event);
166    match typed {
167      Some(Typed::Edited(signal, text, clipboard)) => {
168        // A signal whose owner is gone just isn't written.
169        signal.try_set(text);
170        return clipboard;
171      }
172      Some(Typed::Clipboard(clipboard)) => return Some(clipboard),
173      Some(Typed::Moved) => return None,
174      Some(Typed::Accept(call)) => {
175        call.run();
176        return None;
177      }
178      None => {}
179    }
180    let (button, window) = {
181      let tree = self.tree.borrow();
182      (tree.focused_key_call(), tree.window_key_call())
183    };
184    for call in [button, window].into_iter().flatten() {
185      if call.run(event) {
186        return None;
187      }
188    }
189    let click = borrow(&self.tree).default_key(event);
190    if let Some(click) = click {
191      click.run();
192    }
193    None
194  }
195
196  /// The path of the focused button, for tests and logs.
197  pub fn focused(&self) -> Option<String> {
198    let tree = self.tree.borrow();
199    let id = tree.keyboard.focused?;
200    tree.node(id).map(|node| node.path.to_string())
201  }
202}
203
204impl Tree {
205  /// Marks `id`, a button or field, as showing focus or not. Unlike a
206  /// hover change, a layout this causes checks the hover again: buttons
207  /// may have moved under the pointer.
208  fn show_focus(&mut self, id: Option<NodeId>, shown: bool) {
209    let Some(id) = id else {
210      return;
211    };
212    // A focused link draws lit; text fields show no ring either.
213    if let Some(NodeKind::Text(_)) = self.node(id).map(|node| &node.kind) {
214      let link = self.keyboard.link.filter(|_| shown);
215      self.light_link(id, true, link);
216      return;
217    }
218    if matches!(
219      self.node(id).map(|node| &node.kind),
220      Some(NodeKind::Input(_))
221    ) {
222      self.update(id, |node| match &mut node.kind {
223        NodeKind::Input(input) if input.focused != shown => {
224          input.focused = shown;
225          Change::Paint
226        }
227        _ => Change::None,
228      });
229    } else {
230      self.update_button_style(id, |button| button.focused = shown);
231    }
232  }
233
234  /// Moves the focus to `id`. It shows once the window has the keyboard.
235  /// A hidden node, or one inside a hidden widget, is refused.
236  pub(crate) fn focus(&mut self, id: Option<NodeId>) {
237    self.focus_link(id, None);
238  }
239
240  /// Drops the focus from text `id` if the link span it is on is no
241  /// longer a link, so Tab starts again from the first stop.
242  pub(crate) fn drop_stale_link_focus(&mut self, id: NodeId) {
243    let (Some(focused), Some(link)) = (self.keyboard.focused, self.keyboard.link) else {
244      return;
245    };
246    let still = match self.node(id).map(|node| &node.kind) {
247      Some(NodeKind::Text(text)) => text.spans.get(link).is_some_and(|span| span.link.is_some()),
248      _ => false,
249    };
250    if focused == id && !still {
251      self.focus(None);
252    }
253  }
254
255  /// Moves the focus to `id`, on its link span `link` if it is a text.
256  fn focus_link(&mut self, id: Option<NodeId>, link: Option<usize>) {
257    if id.is_some_and(|id| !self.shown(id)) {
258      return;
259    }
260    if self.keyboard.focused == id {
261      if self.keyboard.link != link {
262        self.keyboard.link = link;
263        let entered = self.keyboard.entered;
264        self.show_focus(id, entered);
265      }
266      return;
267    }
268    let old = std::mem::replace(&mut self.keyboard.focused, id);
269    // What an input method was composing there is dropped with it.
270    if let Some(old) = old
271      && matches!(self.node(old).map(|node| &node.kind), Some(NodeKind::Input(input)) if input.preedit.is_some())
272    {
273      self.update_input(old, |input| {
274        input.preedit = None;
275        input.refresh();
276      });
277    }
278    if let Some(old) = old {
279      self.drop_selection(old);
280    }
281    self.show_focus(old, false);
282    self.keyboard.link = link;
283    let entered = self.keyboard.entered;
284    self.show_focus(id, entered);
285    // The next layout scrolls a newly focused field's caret into view.
286    if let Some(id) = id {
287      self.update_input(id, |_| {});
288    }
289  }
290
291  /// What `event` does to the focused text field, if one is focused and
292  /// uses the key.
293  fn input_key(&mut self, event: &KeyEvent) -> Option<Typed> {
294    let id = self.keyboard.focused?;
295    let view = self.page_height(id);
296    let input = match &mut self.node_mut(id)?.kind {
297      NodeKind::Input(input) => input,
298      NodeKind::Text(text) => return copy_key(text, event).map(Typed::Clipboard),
299      _ => return None,
300    };
301    let page = view.unwrap_or(PAGE_LINES * input.text.buffer.metrics().line_height);
302    let keyed = match input.edit.multiline {
303      true => input.line_key(event, page),
304      false => None,
305    };
306    let keyed = keyed.unwrap_or_else(|| {
307      // Any other move forgets the line's end and the place across.
308      input.upstream = None;
309      input.goal = None;
310      input.edit.key(event, !input.password)
311    });
312    let accept = keyed == Keyed::Accept;
313    let typed = match keyed {
314      Keyed::Unused => return None,
315      Keyed::Moved => Typed::Moved,
316      Keyed::Edited => Typed::Edited(input.signal, input.edit.text.clone(), None),
317      Keyed::Copy(text) => Typed::Clipboard(Clipboard::Copy(text)),
318      Keyed::Cut(text) => Typed::Edited(
319        input.signal,
320        input.edit.text.clone(),
321        Some(Clipboard::Copy(text)),
322      ),
323      Keyed::Paste => Typed::Clipboard(Clipboard::Paste),
324      Keyed::Accept => {
325        let handler = untrack(|| input.on_accept.try_with(Option::clone)).flatten();
326        let text = input.edit.text.clone();
327        let node = self.node(id)?;
328        // Without its own `on_accept`, Enter goes on to the window.
329        Typed::Accept(AcceptCall {
330          cx: node.cx.clone(),
331          path: Rc::clone(&node.path),
332          handler: handler?,
333          text,
334        })
335      }
336    };
337    if !accept {
338      self.update_input(id, |input| {
339        input.refresh();
340      });
341    }
342    Some(typed)
343  }
344
345  /// How far PageUp and PageDown move in node `id`: the height of the
346  /// innermost scroll view around it that scrolls up and down, if any.
347  fn page_height(&self, id: NodeId) -> Option<f32> {
348    self
349      .path_to(id)
350      .into_iter()
351      .rev()
352      .find_map(|at| match &self.node(at)?.kind {
353        NodeKind::Scroll(scroll) => scroll
354          .active()
355          .iter()
356          .find(|axis| !axis.horizontal)
357          .map(|axis| axis.length),
358        _ => None,
359      })
360  }
361
362  /// The enabled buttons, the fields and the links of texts with an
363  /// `on_link`, in the order they are laid out: depth first, in child
364  /// order, a text's links in text order.
365  fn focusable(&self) -> Vec<(NodeId, Option<usize>)> {
366    let mut found = Vec::new();
367    let mut pending = vec![self.root];
368    while let Some(id) = pending.pop() {
369      // A hidden widget is skipped with everything in it.
370      if self.node(id).is_some_and(|node| !node.visible) {
371        continue;
372      }
373      match self.node(id).map(|node| &node.kind) {
374        Some(NodeKind::Button(button)) if button.enabled => found.push((id, None)),
375        Some(NodeKind::Input(_)) => found.push((id, None)),
376        Some(NodeKind::Text(text)) => {
377          found.extend(text.link_stops().into_iter().map(|link| (id, Some(link))));
378        }
379        _ => {}
380      }
381      let mut children = self.taffy.children(id).unwrap_or_default();
382      children.reverse();
383      pending.extend(children);
384    }
385    found
386  }
387
388  fn focused_key_call(&self) -> Option<KeyCall> {
389    let id = self.keyboard.focused?;
390    let node = self.node(id)?;
391    let NodeKind::Button(button) = &node.kind else {
392      return None;
393    };
394    // Reading the handlers doesn't make anything depend on them.
395    let handler = untrack(|| button.handlers.try_with(|handlers| handlers.key.clone()))??;
396    Some(KeyCall {
397      cx: node.cx.clone(),
398      path: Rc::clone(&node.path),
399      handler,
400    })
401  }
402
403  fn window_key_call(&self) -> Option<KeyCall> {
404    let node = self.node(self.root)?;
405    Some(KeyCall {
406      cx: node.cx.clone(),
407      path: Rc::clone(&node.path),
408      handler: self.keyboard.handler.clone()?,
409    })
410  }
411
412  /// What a key nobody handled does: Tab moves the focus, Enter and Space
413  /// click the focused button.
414  fn default_key(&mut self, event: &KeyEvent) -> Option<crate::input::Call> {
415    match event.key {
416      Key::Tab => {
417        let buttons = self.focusable();
418        let at = self.keyboard.focused.and_then(|id| {
419          let link = self.keyboard.link;
420          buttons.iter().position(|&stop| stop == (id, link))
421        });
422        let count = buttons.len();
423        let next = match (at, event.modifiers.shift) {
424          _ if count == 0 => None,
425          (None, false) => Some(0),
426          (None, true) => Some(count - 1),
427          (Some(at), false) => Some((at + 1) % count),
428          (Some(at), true) => Some((at + count - 1) % count),
429        };
430        let (id, link) = next.map_or((None, None), |next| {
431          (Some(buttons[next].0), buttons[next].1)
432        });
433        self.focus_link(id, link);
434        None
435      }
436      Key::Enter | Key::Character(' ') => {
437        let id = self.keyboard.focused?;
438        match self.keyboard.link {
439          Some(link) => self.link_call(id, link),
440          None => self.click(id),
441        }
442      }
443      _ => None,
444    }
445  }
446}
447
448/// What a key did in a text field, once the tree is released.
449enum Typed {
450  /// The text changed; the signal gets it. A cut also copies.
451  Edited(Signal<String>, String, Option<Clipboard>),
452  /// The platform should copy or paste.
453  Clipboard(Clipboard),
454  /// Only the caret or selection moved, already in the tree.
455  Moved,
456  /// Enter: the field's `on_accept` runs.
457  Accept(AcceptCall),
458}
459
460/// A field's `on_accept`, to run once the tree is released.
461struct AcceptCall {
462  cx: Cx,
463  path: Rc<str>,
464  handler: AcceptHandler,
465  text: String,
466}
467
468impl AcceptCall {
469  fn run(self) {
470    run_isolated(&self.path, "on_accept", self.handler, |f| {
471      f(&self.cx, &self.text)
472    });
473  }
474}
475
476/// A key handler to run once the tree is released.
477struct KeyCall {
478  cx: Cx,
479  path: Rc<str>,
480  handler: KeyHandler,
481}
482
483impl KeyCall {
484  /// Whether the handler used the key. One that panicked didn't.
485  fn run(self, event: &KeyEvent) -> bool {
486    run_isolated(&self.path, "on_key", self.handler, |f| f(&self.cx, event)).unwrap_or(false)
487  }
488}