Skip to main content

crabshell_ui/
text_input.rs

1//! [`TextInput`], a one-line text field, and the field node it shares
2//! with [`TextArea`](crate::TextArea).
3
4use std::rc::Rc;
5
6use cosmic_text::{Affinity, FontSystem};
7use crabshell_reactive::Signal;
8
9use crate::cx::Cx;
10use crate::edit::{Edit, Keyed, grapheme_start, graphemes_before};
11use crate::geometry::{Point, Rect};
12use crate::input::Handler;
13use crate::keyboard::{Key, KeyEvent};
14use crate::prop::{IntoProp, Prop};
15use crate::select::{cursor_at, highlights, index_of};
16use crate::style::Style;
17use crate::text::{TextNode, TextRun};
18use crate::tree::{NodeKind, borrow};
19use crate::widgets::{Common, Element, ElementKind, Widget, visibility_methods};
20use crate::window::Window;
21
22/// What a password shows for each character.
23const DOT: char = '•';
24
25/// The width a field takes when nothing else sets one, in logical pixels.
26pub(crate) const DEFAULT_WIDTH: f32 = 200.0;
27
28pub(crate) type AcceptHandler = Rc<Handler<dyn Fn(&Cx, &str)>>;
29
30pub(crate) struct InputProps {
31  pub(crate) text: Signal<String>,
32  pub(crate) placeholder: Option<Prop<String>>,
33  pub(crate) password: Option<Prop<bool>>,
34  pub(crate) focus: Option<Prop<bool>>,
35  pub(crate) on_accept: Option<AcceptHandler>,
36  /// A text area: many lines.
37  pub(crate) multiline: bool,
38  pub(crate) wrap: Option<Prop<bool>>,
39}
40
41/// A one-line text field. It takes the keyboard focus when clicked, when
42/// Tab reaches it, or when [`focus`](Self::focus) says so, and edits the
43/// text in a shared signal: typing writes it, and setting it changes what
44/// the field shows. Arrows, Home and End move the caret, Shift selects,
45/// Ctrl moves and deletes by word, and Ctrl+A selects everything. Keys it
46/// doesn't use, such as Up, Down and Escape, go on to the window's
47/// `on_key`.
48///
49/// ```
50/// use crabshell_ui::{Cx, TextInput};
51///
52/// fn search(cx: &Cx) -> TextInput {
53///     let query = cx.signal(String::new());
54///     TextInput::new(query)
55///         .placeholder("Search")
56///         .on_accept(|_cx, text| println!("run {text}"))
57/// }
58/// ```
59pub struct TextInput {
60  input: InputProps,
61  common: Common,
62}
63
64impl TextInput {
65  /// A field editing `text`.
66  pub fn new(text: Signal<String>) -> TextInput {
67    TextInput {
68      input: InputProps {
69        text,
70        placeholder: None,
71        password: None,
72        focus: None,
73        on_accept: None,
74        multiline: false,
75        wrap: None,
76      },
77      common: Common::default(),
78    }
79  }
80
81  /// Sets the text shown, dimmed, while the field is empty.
82  pub fn placeholder(mut self, text: impl IntoProp<String>) -> TextInput {
83    self.input.placeholder = Some(text.into_prop());
84    self
85  }
86
87  /// Sets whether the field shows a dot for each character instead of
88  /// the text.
89  pub fn password(mut self, password: impl IntoProp<bool>) -> TextInput {
90    self.input.password = Some(password.into_prop());
91    self
92  }
93
94  /// Takes the keyboard focus whenever this turns true, as when a
95  /// launcher opens.
96  pub fn focus(mut self, focus: impl IntoProp<bool>) -> TextInput {
97    self.input.focus = Some(focus.into_prop());
98    self
99  }
100
101  /// Runs `handler` with the text when Enter is pressed in the field.
102  pub fn on_accept(mut self, handler: impl Fn(&Cx, &str) + 'static) -> TextInput {
103    self.input.on_accept = Some(Rc::new(Handler::new(handler)));
104    self
105  }
106
107  /// Sets the style. A field cuts its text to the inside of its border.
108  /// Its text takes the font, color, alignment, line height and
109  /// decorations it inherits or sets, as a [`Text`](crate::Text) does.
110  pub fn style(mut self, style: impl IntoProp<Style>) -> TextInput {
111    self.common.style = Some(style.into_prop());
112    self
113  }
114
115  visibility_methods!();
116}
117
118impl Widget for TextInput {
119  fn into_element(self: Box<Self>) -> Element {
120    Element {
121      name: "TextInput",
122      common: self.common,
123      kind: ElementKind::Input(Box::new(self.input)),
124      children: Vec::new(),
125    }
126  }
127}
128
129/// Text an input method is composing, shown at the caret, underlined,
130/// until it commits or drops it.
131#[derive(Clone, Debug, PartialEq, Eq)]
132pub struct Preedit {
133  /// The text.
134  pub text: String,
135  /// Where in `text`, in bytes, its own caret or selection is, if shown.
136  pub cursor: Option<(usize, usize)>,
137}
138
139/// The focused text field, as an input method needs it.
140#[derive(Clone, Debug, PartialEq)]
141pub struct FieldState {
142  /// Which field it is: another number when the focus moves to another.
143  pub field: u64,
144  /// The field's text.
145  pub text: String,
146  /// The caret, in bytes.
147  pub cursor: usize,
148  /// The other end of the selection, or the caret without one.
149  pub anchor: usize,
150  /// Where the caret is drawn, in window coordinates.
151  pub caret: Rect,
152  /// A [`TextArea`](crate::TextArea), whose text has line breaks.
153  pub multiline: bool,
154}
155
156impl Window {
157  /// The focused text field, while the window has the keyboard, for an
158  /// input method. Never a password: input methods learn what is typed.
159  pub fn field(&self) -> Option<FieldState> {
160    let tree = self.tree.borrow();
161    if !tree.keyboard.entered {
162      return None;
163    }
164    let id = tree.keyboard.focused?;
165    let NodeKind::Input(input) = &tree.node(id)?.kind else {
166      return None;
167    };
168    (!input.password).then(|| FieldState {
169      field: u64::from(id),
170      text: input.edit.text.clone(),
171      cursor: input.edit.cursor,
172      anchor: input.edit.anchor.unwrap_or(input.edit.cursor),
173      caret: tree.window_rect(id, input.caret),
174      multiline: input.edit.multiline,
175    })
176  }
177
178  /// Inserts `text` from an input method at the focused field's caret,
179  /// replacing its selection; in a one-line field, line breaks become
180  /// spaces. A password field takes nothing.
181  pub fn commit_text(&self, text: &str) {
182    self.edit_field(|edit| edit.insert(text));
183  }
184
185  /// Pastes `text` from the clipboard into the focused field, replacing
186  /// its selection; in a one-line field, line breaks become spaces.
187  /// Unlike an input method's text, a paste goes into a password field
188  /// too.
189  pub fn paste(&self, text: &str) {
190    // An empty clipboard pastes nothing, not even over the selection.
191    if text.is_empty() {
192      return;
193    }
194    self.change_field(true, |edit| edit.insert(text));
195  }
196
197  /// Deletes `before` bytes before the focused field's selection, or its
198  /// caret, and `after` bytes after it, for an input method; the
199  /// selection itself stays. Lengths that would split a character are
200  /// ignored.
201  pub fn delete_around(&self, before: usize, after: usize) {
202    self.edit_field(|edit| {
203      let selected = edit.selection().unwrap_or(edit.cursor..edit.cursor);
204      let start = selected.start.saturating_sub(before);
205      let end = selected.end.saturating_add(after).min(edit.text.len());
206      if !(edit.text.is_char_boundary(start) && edit.text.is_char_boundary(end)) {
207        return;
208      }
209      edit.text.replace_range(selected.end..end, "");
210      edit.text.replace_range(start..selected.start, "");
211      let removed = selected.start - start;
212      edit.cursor -= removed;
213      edit.anchor = edit.anchor.map(|anchor| anchor - removed);
214    });
215  }
216
217  /// Shows `preedit` at the focused field's caret, replacing its
218  /// selection, or clears it. A password field shows none.
219  pub fn set_preedit(&self, preedit: Option<Preedit>) {
220    let preedit = preedit.filter(|preedit| !preedit.text.is_empty());
221    if preedit.is_some() {
222      self.edit_field(|edit| {
223        if edit.selection().is_some() {
224          edit.insert("");
225        }
226      });
227    }
228    let mut tree = borrow(&self.tree);
229    let Some(id) = tree.keyboard.focused else {
230      return;
231    };
232    if matches!(tree.node(id).map(|node| &node.kind), Some(NodeKind::Input(input)) if input.password)
233    {
234      return;
235    }
236    tree.update_input(id, |input| {
237      input.preedit = preedit;
238      input.refresh();
239    });
240  }
241
242  /// Changes the focused field's text with `change`, then writes it to
243  /// the field's signal once the tree is released. A password field is
244  /// left alone: input methods don't type in one.
245  fn edit_field(&self, change: impl FnOnce(&mut Edit)) {
246    self.change_field(false, change);
247  }
248
249  /// As [`edit_field`](Self::edit_field), into a password field too when
250  /// `passwords`.
251  fn change_field(&self, passwords: bool, change: impl FnOnce(&mut Edit)) {
252    let write = {
253      let mut tree = borrow(&self.tree);
254      let Some(id) = tree.keyboard.focused else {
255        return;
256      };
257      let before = match tree.node(id).map(|node| &node.kind) {
258        Some(NodeKind::Input(input)) if passwords || !input.password => input.edit.text.clone(),
259        _ => return,
260      };
261      let mut write = None;
262      tree.update_input(id, |input| {
263        change(&mut input.edit);
264        input.refresh();
265        if input.edit.text != before {
266          write = Some((input.signal, input.edit.text.clone()));
267        }
268      });
269      write
270    };
271    if let Some((signal, text)) = write {
272      // A signal whose owner is gone just isn't written.
273      signal.try_set(text);
274    }
275  }
276}
277
278/// A field in the tree.
279pub(crate) struct InputNode {
280  /// What is shown: the text, its dots, or the placeholder.
281  pub(crate) text: TextNode,
282  pub(crate) edit: Edit,
283  /// Written as the text is edited.
284  pub(crate) signal: Signal<String>,
285  pub(crate) placeholder: String,
286  pub(crate) password: bool,
287  /// The field has the keyboard, so it shows its caret.
288  pub(crate) focused: bool,
289  /// The last value of its `focus` binding, which it takes the focus by
290  /// whenever it is shown.
291  pub(crate) wants_focus: bool,
292  /// How far the text is scrolled left to keep the caret in view.
293  pub(crate) scroll: f32,
294  /// Where the caret and the selection are, from the last layout, in
295  /// window coordinates.
296  pub(crate) caret: Rect,
297  /// More than one span when right-to-left and left-to-right text mix.
298  pub(crate) selection: Vec<Rect>,
299  /// The content box the text is cut to, from the last layout.
300  pub(crate) area: Rect,
301  /// What an input method is composing, shown at the caret.
302  pub(crate) preedit: Option<Preedit>,
303  /// The line under the preedit, from the last layout.
304  pub(crate) underline: Vec<Rect>,
305  /// Where across Up and Down keep the caret, and the caret position it
306  /// led to: a move that lands anywhere else forgets it.
307  pub(crate) goal: Option<(usize, f32)>,
308  /// A caret position shown at the end of a wrapped line rather than at
309  /// the start of the next, where both are the same byte.
310  pub(crate) upstream: Option<usize>,
311  /// Kept in the reactive runtime, which drops the user's closure when the
312  /// field's owner goes.
313  pub(crate) on_accept: Signal<Option<AcceptHandler>>,
314}
315
316impl InputNode {
317  pub(crate) fn new(
318    signal: Signal<String>,
319    on_accept: Signal<Option<AcceptHandler>>,
320    multiline: bool,
321  ) -> InputNode {
322    let mut text = TextNode::new();
323    if multiline {
324      text.set_max_lines(u32::MAX);
325    }
326    InputNode {
327      text,
328      edit: Edit {
329        multiline,
330        ..Edit::default()
331      },
332      signal,
333      placeholder: String::new(),
334      password: false,
335      focused: false,
336      wants_focus: false,
337      scroll: 0.0,
338      caret: Rect::default(),
339      selection: Vec::new(),
340      area: Rect::default(),
341      preedit: None,
342      underline: Vec::new(),
343      goal: None,
344      upstream: None,
345      on_accept,
346    }
347  }
348
349  /// What a screen reader reads of the field: its text, or a password's
350  /// dots, with the caret and selection in characters of that.
351  pub(crate) fn access_text(&self) -> crate::access::AccessText {
352    let text = &self.edit.text;
353    let at = |byte: usize| match self.password {
354      true => graphemes_before(text, byte),
355      false => text[..byte].chars().count(),
356    };
357    crate::access::AccessText {
358      text: match self.password {
359        true => DOT.to_string().repeat(at(text.len())),
360        false => text.clone(),
361      },
362      caret: at(self.edit.cursor),
363      selection: self
364        .edit
365        .selection()
366        .map(|range| (at(range.start), at(range.end))),
367    }
368  }
369
370  /// Whether the placeholder is what shows.
371  pub(crate) fn showing_placeholder(&self) -> bool {
372    self.edit.text.is_empty() && self.preedit.is_none()
373  }
374
375  /// The preedit's length in bytes, 0 without one.
376  fn preedit_len(&self) -> usize {
377    self
378      .preedit
379      .as_ref()
380      .map_or(0, |preedit| preedit.text.len())
381  }
382
383  /// Puts what should show into the text node. Returns whether that
384  /// changed, which needs a layout.
385  pub(crate) fn refresh(&mut self) -> bool {
386    let shown = if self.showing_placeholder() {
387      self.placeholder.clone()
388    } else if self.password {
389      DOT
390        .to_string()
391        .repeat(graphemes_before(&self.edit.text, self.edit.text.len()))
392    } else if let Some(preedit) = &self.preedit {
393      let (before, after) = self.edit.text.split_at(self.edit.cursor);
394      format!("{before}{}{after}", preedit.text)
395    } else {
396      self.edit.text.clone()
397    };
398    self.text.set_content(shown)
399  }
400
401  /// The byte in what is shown that matches byte `at` of the text.
402  fn shown_index(&self, at: usize) -> usize {
403    if self.showing_placeholder() {
404      0
405    } else if self.password {
406      graphemes_before(&self.edit.text, at) * DOT.len_utf8()
407    } else if at > self.edit.cursor {
408      at + self.preedit_len()
409    } else {
410      at
411    }
412  }
413
414  /// The byte of the text that matches byte `at` of what is shown.
415  fn text_index(&self, at: usize) -> usize {
416    if self.showing_placeholder() {
417      0
418    } else if self.password {
419      grapheme_start(&self.edit.text, at / DOT.len_utf8())
420    } else if at <= self.edit.cursor {
421      at
422    } else {
423      // Inside the preedit is at the caret; past it, shifted back.
424      let after = at.saturating_sub(self.preedit_len()).max(self.edit.cursor);
425      after.min(self.edit.text.len())
426    }
427  }
428
429  /// The line the caret before byte `at` of what is shown is drawn on:
430  /// the first of two that meet there when `upstream`, else the last.
431  fn caret_run(&self, at: usize, upstream: bool) -> Option<TextRun<'_>> {
432    let cursor = cursor_at(&self.text.buffer, at);
433    let mut runs = self.text.runs().filter(|run| {
434      run.line_i == cursor.line
435        && (run.glyphs.is_empty() || {
436          let start = run.glyphs.iter().map(|glyph| glyph.start).min();
437          let end = run.glyphs.iter().map(|glyph| glyph.end).max();
438          start.is_some_and(|start| start <= cursor.index)
439            && end.is_some_and(|end| cursor.index <= end)
440        })
441    });
442    if upstream { runs.next() } else { runs.last() }
443  }
444
445  /// Where the caret before byte `at` of what is shown is, from the
446  /// text's corner: across, the top of its line and the line's height.
447  /// In right-to-left text, the start is on the right. On an empty line,
448  /// or over the placeholder, it is where typed text would start.
449  fn caret_spot(&self, at: usize, upstream: bool) -> Option<(f32, f32, f32)> {
450    let run = self
451      .caret_run(at, upstream)
452      .or_else(|| self.text.runs().next())?;
453    let x = if run.glyphs.is_empty() || self.showing_placeholder() {
454      self.text.empty_line_place(run.rtl) * self.text.layout_width()
455    } else {
456      run
457        .layout()
458        .cursor_position(&cursor_at(&self.text.buffer, at))
459        .unwrap_or(0.0)
460    };
461    Some((x, run.line_top, run.line_height))
462  }
463
464  /// The part of a line `height` tall from `top` that its glyphs fill,
465  /// as top and height: the default line height's, centered as
466  /// cosmic-text centers the glyphs, when the style's is taller.
467  fn glyph_box(&self, top: f32, height: f32) -> (f32, f32) {
468    let natural = (1.2 * self.text.buffer.metrics().font_size).round();
469    let glyphs = natural.min(height);
470    (top + ((height - glyphs) / 2.0).round(), glyphs)
471  }
472
473  /// Lays the text out in the field's `content` box. Aligned text sits
474  /// in the room left of the caret's last pixel; a line too long for it
475  /// starts at the start, as unaligned text does, and scrolls.
476  pub(crate) fn finish(&mut self, content: Rect, fonts: &mut FontSystem) {
477    let room = (content.width - 1.0).max(0.0);
478    let width = match (self.text.aligned(), self.text.wraps()) {
479      (false, wraps) => wraps.then_some(content.width),
480      (true, true) => Some(room),
481      // A long placeholder is cut, but typed text starts where it should.
482      (true, false) if self.showing_placeholder() => Some(room),
483      (true, false) => Some(self.text.width().max(room)),
484    };
485    self.text.finish_at(content, width, fonts);
486  }
487
488  /// Scrolls the text sideways to keep the caret inside `content`, then
489  /// places the caret and the selection. Called after the text node's own
490  /// layout.
491  pub(crate) fn place(&mut self, content: Rect) {
492    let at = self.shown_index(self.edit.cursor);
493    let caret = match &self.preedit {
494      Some(preedit) => {
495        at + preedit
496          .cursor
497          .map_or(preedit.text.len(), |(start, _)| start)
498      }
499      None => at,
500    };
501    let upstream = self.upstream == Some(self.edit.cursor) && self.preedit.is_none();
502    let (x, top, height) = self
503      .caret_spot(caret, upstream)
504      .unwrap_or((0.0, 0.0, content.height));
505    let width = self.text.runs().map(|run| run.line_w).fold(0.0, f32::max);
506    // The caret's own pixel counts as text, so it shows at the end.
507    let room = (content.width - 1.0).max(0.0);
508    let mut scroll = self.scroll.min((width - room).max(0.0));
509    if x - scroll > room {
510      scroll = x - room;
511    }
512    if x < scroll {
513      scroll = x;
514    }
515    self.scroll = scroll.max(0.0);
516    self.text.origin.x = content.x - self.scroll;
517    let origin = self.text.origin;
518    let (top, height) = self.glyph_box(top, height);
519    self.caret = Rect::new(origin.x + x, origin.y + top, 1.0, height);
520    self.area = content;
521    self.selection = match self.edit.selection() {
522      Some(range) => highlights(
523        &self.text,
524        self.shown_index(range.start)..self.shown_index(range.end),
525      ),
526      None => Vec::new(),
527    };
528    self.underline = match &self.preedit {
529      Some(preedit) => highlights(&self.text, at..at + preedit.text.len())
530        .into_iter()
531        .map(|span| {
532          let (top, height) = self.glyph_box(span.y, span.height);
533          Rect::new(span.x, top + height - 1.0, span.width, 1.0)
534        })
535        .collect(),
536      None => Vec::new(),
537    };
538  }
539
540  /// The text position nearest `point`, in window coordinates, and
541  /// whether it is the end of a wrapped line rather than the start of the
542  /// next.
543  pub(crate) fn hit(&self, point: Point) -> (usize, bool) {
544    let origin = self.text.origin;
545    let Some(cursor) = self.text.buffer.hit(point.x - origin.x, point.y - origin.y) else {
546      return (0, false);
547    };
548    let at = self.text_index(index_of(&self.text.buffer, cursor));
549    (at, cursor.affinity == Affinity::Before)
550  }
551
552  /// What a key that moves by line does in a text area: Up and Down to
553  /// the line above or below, keeping the caret's place across, PageUp
554  /// and PageDown by `page` logical pixels, and Home and End to the ends
555  /// of the line as it is wrapped. Shift extends the selection. `None`
556  /// for any other key.
557  pub(crate) fn line_key(&mut self, event: &KeyEvent, page: f32) -> Option<Keyed> {
558    let ctrl = event.modifiers.ctrl;
559    let lines = match event.key {
560      Key::Up => -1.0,
561      Key::Down => 1.0,
562      Key::PageUp => -page,
563      Key::PageDown => page,
564      Key::Home | Key::End if !ctrl => 0.0,
565      _ => return None,
566    };
567    let at = self.shown_index(self.edit.cursor);
568    let upstream = self.upstream == Some(self.edit.cursor);
569    let (target, upstream, goal) = if lines == 0.0 {
570      let run = self.caret_run(at, upstream)?;
571      let ends = run.glyphs.iter().map(|glyph| (glyph.start, glyph.end));
572      let index = if event.key == Key::Home {
573        ends.map(|(start, _)| start).min()
574      } else {
575        ends.map(|(_, end)| end).max()
576      };
577      let line = cosmic_text::Cursor::new(run.line_i, index.unwrap_or(0));
578      (
579        index_of(&self.text.buffer, line),
580        event.key == Key::End,
581        None,
582      )
583    } else {
584      let (x, top, height) = self.caret_spot(at, upstream)?;
585      let x = self
586        .goal
587        .filter(|&(cursor, _)| cursor == self.edit.cursor)
588        .map_or(x, |(_, x)| x);
589      let step = if matches!(event.key, Key::Up | Key::Down) {
590        lines * height
591      } else {
592        lines
593      };
594      let cursor = self.text.buffer.hit(x, top + height / 2.0 + step)?;
595      (
596        index_of(&self.text.buffer, cursor),
597        cursor.affinity == Affinity::Before,
598        Some(x),
599      )
600    };
601    let target = self.text_index(target);
602    self.edit.move_to(event.modifiers.shift, target);
603    self.upstream = upstream.then_some(target);
604    self.goal = goal.map(|x| (target, x));
605    Some(Keyed::Moved)
606  }
607}