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  /// Whether the placeholder is what shows.
350  pub(crate) fn showing_placeholder(&self) -> bool {
351    self.edit.text.is_empty() && self.preedit.is_none()
352  }
353
354  /// The preedit's length in bytes, 0 without one.
355  fn preedit_len(&self) -> usize {
356    self
357      .preedit
358      .as_ref()
359      .map_or(0, |preedit| preedit.text.len())
360  }
361
362  /// Puts what should show into the text node. Returns whether that
363  /// changed, which needs a layout.
364  pub(crate) fn refresh(&mut self) -> bool {
365    let shown = if self.showing_placeholder() {
366      self.placeholder.clone()
367    } else if self.password {
368      DOT
369        .to_string()
370        .repeat(graphemes_before(&self.edit.text, self.edit.text.len()))
371    } else if let Some(preedit) = &self.preedit {
372      let (before, after) = self.edit.text.split_at(self.edit.cursor);
373      format!("{before}{}{after}", preedit.text)
374    } else {
375      self.edit.text.clone()
376    };
377    self.text.set_content(shown)
378  }
379
380  /// The byte in what is shown that matches byte `at` of the text.
381  fn shown_index(&self, at: usize) -> usize {
382    if self.showing_placeholder() {
383      0
384    } else if self.password {
385      graphemes_before(&self.edit.text, at) * DOT.len_utf8()
386    } else if at > self.edit.cursor {
387      at + self.preedit_len()
388    } else {
389      at
390    }
391  }
392
393  /// The byte of the text that matches byte `at` of what is shown.
394  fn text_index(&self, at: usize) -> usize {
395    if self.showing_placeholder() {
396      0
397    } else if self.password {
398      grapheme_start(&self.edit.text, at / DOT.len_utf8())
399    } else if at <= self.edit.cursor {
400      at
401    } else {
402      // Inside the preedit is at the caret; past it, shifted back.
403      let after = at.saturating_sub(self.preedit_len()).max(self.edit.cursor);
404      after.min(self.edit.text.len())
405    }
406  }
407
408  /// The line the caret before byte `at` of what is shown is drawn on:
409  /// the first of two that meet there when `upstream`, else the last.
410  fn caret_run(&self, at: usize, upstream: bool) -> Option<TextRun<'_>> {
411    let cursor = cursor_at(&self.text.buffer, at);
412    let mut runs = self.text.runs().filter(|run| {
413      run.line_i == cursor.line
414        && (run.glyphs.is_empty() || {
415          let start = run.glyphs.iter().map(|glyph| glyph.start).min();
416          let end = run.glyphs.iter().map(|glyph| glyph.end).max();
417          start.is_some_and(|start| start <= cursor.index)
418            && end.is_some_and(|end| cursor.index <= end)
419        })
420    });
421    if upstream { runs.next() } else { runs.last() }
422  }
423
424  /// Where the caret before byte `at` of what is shown is, from the
425  /// text's corner: across, the top of its line and the line's height.
426  /// In right-to-left text, the start is on the right. On an empty line,
427  /// or over the placeholder, it is where typed text would start.
428  fn caret_spot(&self, at: usize, upstream: bool) -> Option<(f32, f32, f32)> {
429    let run = self
430      .caret_run(at, upstream)
431      .or_else(|| self.text.runs().next())?;
432    let x = if run.glyphs.is_empty() || self.showing_placeholder() {
433      self.text.empty_line_place(run.rtl) * self.text.layout_width()
434    } else {
435      run
436        .layout()
437        .cursor_position(&cursor_at(&self.text.buffer, at))
438        .unwrap_or(0.0)
439    };
440    Some((x, run.line_top, run.line_height))
441  }
442
443  /// The part of a line `height` tall from `top` that its glyphs fill,
444  /// as top and height: the default line height's, centered as
445  /// cosmic-text centers the glyphs, when the style's is taller.
446  fn glyph_box(&self, top: f32, height: f32) -> (f32, f32) {
447    let natural = (1.2 * self.text.buffer.metrics().font_size).round();
448    let glyphs = natural.min(height);
449    (top + ((height - glyphs) / 2.0).round(), glyphs)
450  }
451
452  /// Lays the text out in the field's `content` box. Aligned text sits
453  /// in the room left of the caret's last pixel; a line too long for it
454  /// starts at the start, as unaligned text does, and scrolls.
455  pub(crate) fn finish(&mut self, content: Rect, fonts: &mut FontSystem) {
456    let room = (content.width - 1.0).max(0.0);
457    let width = match (self.text.aligned(), self.text.wraps()) {
458      (false, wraps) => wraps.then_some(content.width),
459      (true, true) => Some(room),
460      // A long placeholder is cut, but typed text starts where it should.
461      (true, false) if self.showing_placeholder() => Some(room),
462      (true, false) => Some(self.text.width().max(room)),
463    };
464    self.text.finish_at(content, width, fonts);
465  }
466
467  /// Scrolls the text sideways to keep the caret inside `content`, then
468  /// places the caret and the selection. Called after the text node's own
469  /// layout.
470  pub(crate) fn place(&mut self, content: Rect) {
471    let at = self.shown_index(self.edit.cursor);
472    let caret = match &self.preedit {
473      Some(preedit) => {
474        at + preedit
475          .cursor
476          .map_or(preedit.text.len(), |(start, _)| start)
477      }
478      None => at,
479    };
480    let upstream = self.upstream == Some(self.edit.cursor) && self.preedit.is_none();
481    let (x, top, height) = self
482      .caret_spot(caret, upstream)
483      .unwrap_or((0.0, 0.0, content.height));
484    let width = self.text.runs().map(|run| run.line_w).fold(0.0, f32::max);
485    // The caret's own pixel counts as text, so it shows at the end.
486    let room = (content.width - 1.0).max(0.0);
487    let mut scroll = self.scroll.min((width - room).max(0.0));
488    if x - scroll > room {
489      scroll = x - room;
490    }
491    if x < scroll {
492      scroll = x;
493    }
494    self.scroll = scroll.max(0.0);
495    self.text.origin.x = content.x - self.scroll;
496    let origin = self.text.origin;
497    let (top, height) = self.glyph_box(top, height);
498    self.caret = Rect::new(origin.x + x, origin.y + top, 1.0, height);
499    self.area = content;
500    self.selection = match self.edit.selection() {
501      Some(range) => highlights(
502        &self.text,
503        self.shown_index(range.start)..self.shown_index(range.end),
504      ),
505      None => Vec::new(),
506    };
507    self.underline = match &self.preedit {
508      Some(preedit) => highlights(&self.text, at..at + preedit.text.len())
509        .into_iter()
510        .map(|span| {
511          let (top, height) = self.glyph_box(span.y, span.height);
512          Rect::new(span.x, top + height - 1.0, span.width, 1.0)
513        })
514        .collect(),
515      None => Vec::new(),
516    };
517  }
518
519  /// The text position nearest `point`, in window coordinates, and
520  /// whether it is the end of a wrapped line rather than the start of the
521  /// next.
522  pub(crate) fn hit(&self, point: Point) -> (usize, bool) {
523    let origin = self.text.origin;
524    let Some(cursor) = self.text.buffer.hit(point.x - origin.x, point.y - origin.y) else {
525      return (0, false);
526    };
527    let at = self.text_index(index_of(&self.text.buffer, cursor));
528    (at, cursor.affinity == Affinity::Before)
529  }
530
531  /// What a key that moves by line does in a text area: Up and Down to
532  /// the line above or below, keeping the caret's place across, PageUp
533  /// and PageDown by `page` logical pixels, and Home and End to the ends
534  /// of the line as it is wrapped. Shift extends the selection. `None`
535  /// for any other key.
536  pub(crate) fn line_key(&mut self, event: &KeyEvent, page: f32) -> Option<Keyed> {
537    let ctrl = event.modifiers.ctrl;
538    let lines = match event.key {
539      Key::Up => -1.0,
540      Key::Down => 1.0,
541      Key::PageUp => -page,
542      Key::PageDown => page,
543      Key::Home | Key::End if !ctrl => 0.0,
544      _ => return None,
545    };
546    let at = self.shown_index(self.edit.cursor);
547    let upstream = self.upstream == Some(self.edit.cursor);
548    let (target, upstream, goal) = if lines == 0.0 {
549      let run = self.caret_run(at, upstream)?;
550      let ends = run.glyphs.iter().map(|glyph| (glyph.start, glyph.end));
551      let index = if event.key == Key::Home {
552        ends.map(|(start, _)| start).min()
553      } else {
554        ends.map(|(_, end)| end).max()
555      };
556      let line = cosmic_text::Cursor::new(run.line_i, index.unwrap_or(0));
557      (
558        index_of(&self.text.buffer, line),
559        event.key == Key::End,
560        None,
561      )
562    } else {
563      let (x, top, height) = self.caret_spot(at, upstream)?;
564      let x = self
565        .goal
566        .filter(|&(cursor, _)| cursor == self.edit.cursor)
567        .map_or(x, |(_, x)| x);
568      let step = if matches!(event.key, Key::Up | Key::Down) {
569        lines * height
570      } else {
571        lines
572      };
573      let cursor = self.text.buffer.hit(x, top + height / 2.0 + step)?;
574      (
575        index_of(&self.text.buffer, cursor),
576        cursor.affinity == Affinity::Before,
577        Some(x),
578      )
579    };
580    let target = self.text_index(target);
581    self.edit.move_to(event.modifiers.shift, target);
582    self.upstream = upstream.then_some(target);
583    self.goal = goal.map(|x| (target, x));
584    Some(Keyed::Moved)
585  }
586}