Skip to main content

crabshell_ui/
text_input.rs

1//! [`TextInput`], a one-line text field.
2
3use std::rc::Rc;
4
5use cosmic_text::Cursor;
6use crabshell_reactive::Signal;
7
8use crate::cx::Cx;
9use crate::edit::{Edit, grapheme_start, graphemes_before};
10use crate::geometry::{Point, Rect};
11use crate::input::Handler;
12use crate::prop::{IntoProp, Prop};
13use crate::style::Style;
14use crate::text::TextNode;
15use crate::tree::{NodeKind, borrow};
16use crate::widgets::{Common, Element, ElementKind, Widget, visibility_methods};
17use crate::window::Window;
18
19/// What a password shows for each character.
20const DOT: char = '•';
21
22/// The width a field takes when nothing else sets one, in logical pixels.
23pub(crate) const DEFAULT_WIDTH: f32 = 200.0;
24
25pub(crate) type AcceptHandler = Rc<Handler<dyn Fn(&Cx, &str)>>;
26
27pub(crate) struct InputProps {
28  pub(crate) text: Signal<String>,
29  pub(crate) placeholder: Option<Prop<String>>,
30  pub(crate) password: Option<Prop<bool>>,
31  pub(crate) focus: Option<Prop<bool>>,
32  pub(crate) on_accept: Option<AcceptHandler>,
33}
34
35/// A one-line text field. It takes the keyboard focus when clicked, when
36/// Tab reaches it, or when [`focus`](Self::focus) says so, and edits the
37/// text in a shared signal: typing writes it, and setting it changes what
38/// the field shows. Arrows, Home and End move the caret, Shift selects,
39/// Ctrl moves and deletes by word, and Ctrl+A selects everything. Keys it
40/// doesn't use, such as Up, Down and Escape, go on to the window's
41/// `on_key`.
42///
43/// ```
44/// use crabshell_ui::{Cx, TextInput};
45///
46/// fn search(cx: &Cx) -> TextInput {
47///     let query = cx.signal(String::new());
48///     TextInput::new(query)
49///         .placeholder("Search")
50///         .on_accept(|_cx, text| println!("run {text}"))
51/// }
52/// ```
53pub struct TextInput {
54  input: InputProps,
55  common: Common,
56}
57
58impl TextInput {
59  /// A field editing `text`.
60  pub fn new(text: Signal<String>) -> TextInput {
61    TextInput {
62      input: InputProps {
63        text,
64        placeholder: None,
65        password: None,
66        focus: None,
67        on_accept: None,
68      },
69      common: Common::default(),
70    }
71  }
72
73  /// Sets the text shown, dimmed, while the field is empty.
74  pub fn placeholder(mut self, text: impl IntoProp<String>) -> TextInput {
75    self.input.placeholder = Some(text.into_prop());
76    self
77  }
78
79  /// Sets whether the field shows a dot for each character instead of
80  /// the text.
81  pub fn password(mut self, password: impl IntoProp<bool>) -> TextInput {
82    self.input.password = Some(password.into_prop());
83    self
84  }
85
86  /// Takes the keyboard focus whenever this turns true, as when a
87  /// launcher opens.
88  pub fn focus(mut self, focus: impl IntoProp<bool>) -> TextInput {
89    self.input.focus = Some(focus.into_prop());
90    self
91  }
92
93  /// Runs `handler` with the text when Enter is pressed in the field.
94  pub fn on_accept(mut self, handler: impl Fn(&Cx, &str) + 'static) -> TextInput {
95    self.input.on_accept = Some(Rc::new(Handler::new(handler)));
96    self
97  }
98
99  /// Sets the style. A field cuts its text to the inside of its border.
100  pub fn style(mut self, style: impl IntoProp<Style>) -> TextInput {
101    self.common.style = Some(style.into_prop());
102    self
103  }
104
105  visibility_methods!();
106}
107
108impl Widget for TextInput {
109  fn into_element(self: Box<Self>) -> Element {
110    Element {
111      name: "TextInput",
112      common: self.common,
113      kind: ElementKind::Input(Box::new(self.input)),
114      children: Vec::new(),
115    }
116  }
117}
118
119/// Text an input method is composing, shown at the caret, underlined,
120/// until it commits or drops it.
121#[derive(Clone, Debug, PartialEq, Eq)]
122pub struct Preedit {
123  /// The text.
124  pub text: String,
125  /// Where in `text`, in bytes, its own caret or selection is, if shown.
126  pub cursor: Option<(usize, usize)>,
127}
128
129/// The focused text field, as an input method needs it.
130#[derive(Clone, Debug, PartialEq)]
131pub struct FieldState {
132  /// Which field it is: another number when the focus moves to another.
133  pub field: u64,
134  /// The field's text.
135  pub text: String,
136  /// The caret, in bytes.
137  pub cursor: usize,
138  /// The other end of the selection, or the caret without one.
139  pub anchor: usize,
140  /// Where the caret is drawn, in window coordinates.
141  pub caret: Rect,
142}
143
144impl Window {
145  /// The focused text field, while the window has the keyboard, for an
146  /// input method. Never a password: input methods learn what is typed.
147  pub fn field(&self) -> Option<FieldState> {
148    let tree = self.tree.borrow();
149    if !tree.keyboard.entered {
150      return None;
151    }
152    let id = tree.keyboard.focused?;
153    let NodeKind::Input(input) = &tree.node(id)?.kind else {
154      return None;
155    };
156    (!input.password).then(|| FieldState {
157      field: u64::from(id),
158      text: input.edit.text.clone(),
159      cursor: input.edit.cursor,
160      anchor: input.edit.anchor.unwrap_or(input.edit.cursor),
161      caret: tree.window_rect(id, input.caret),
162    })
163  }
164
165  /// Inserts `text` from an input method at the focused field's caret,
166  /// replacing its selection. A password field takes nothing.
167  pub fn commit_text(&self, text: &str) {
168    let text = text.replace(['\n', '\r'], " ");
169    self.edit_field(|edit| edit.insert(&text));
170  }
171
172  /// Pastes `text` from the clipboard into the focused field, replacing
173  /// its selection; line breaks become spaces. Unlike an input method's
174  /// text, a paste goes into a password field too.
175  pub fn paste(&self, text: &str) {
176    // An empty clipboard pastes nothing, not even over the selection.
177    if text.is_empty() {
178      return;
179    }
180    let text = text.replace(['\n', '\r'], " ");
181    self.change_field(true, |edit| edit.insert(&text));
182  }
183
184  /// Deletes `before` bytes before the focused field's selection, or its
185  /// caret, and `after` bytes after it, for an input method; the
186  /// selection itself stays. Lengths that would split a character are
187  /// ignored.
188  pub fn delete_around(&self, before: usize, after: usize) {
189    self.edit_field(|edit| {
190      let selected = edit.selection().unwrap_or(edit.cursor..edit.cursor);
191      let start = selected.start.saturating_sub(before);
192      let end = selected.end.saturating_add(after).min(edit.text.len());
193      if !(edit.text.is_char_boundary(start) && edit.text.is_char_boundary(end)) {
194        return;
195      }
196      edit.text.replace_range(selected.end..end, "");
197      edit.text.replace_range(start..selected.start, "");
198      let removed = selected.start - start;
199      edit.cursor -= removed;
200      edit.anchor = edit.anchor.map(|anchor| anchor - removed);
201    });
202  }
203
204  /// Shows `preedit` at the focused field's caret, replacing its
205  /// selection, or clears it. A password field shows none.
206  pub fn set_preedit(&self, preedit: Option<Preedit>) {
207    let preedit = preedit.filter(|preedit| !preedit.text.is_empty());
208    if preedit.is_some() {
209      self.edit_field(|edit| {
210        if edit.selection().is_some() {
211          edit.insert("");
212        }
213      });
214    }
215    let mut tree = borrow(&self.tree);
216    let Some(id) = tree.keyboard.focused else {
217      return;
218    };
219    if matches!(tree.node(id).map(|node| &node.kind), Some(NodeKind::Input(input)) if input.password)
220    {
221      return;
222    }
223    tree.update_input(id, |input| {
224      input.preedit = preedit;
225      input.refresh();
226    });
227  }
228
229  /// Changes the focused field's text with `change`, then writes it to
230  /// the field's signal once the tree is released. A password field is
231  /// left alone: input methods don't type in one.
232  fn edit_field(&self, change: impl FnOnce(&mut Edit)) {
233    self.change_field(false, change);
234  }
235
236  /// As [`edit_field`](Self::edit_field), into a password field too when
237  /// `passwords`.
238  fn change_field(&self, passwords: bool, change: impl FnOnce(&mut Edit)) {
239    let write = {
240      let mut tree = borrow(&self.tree);
241      let Some(id) = tree.keyboard.focused else {
242        return;
243      };
244      let before = match tree.node(id).map(|node| &node.kind) {
245        Some(NodeKind::Input(input)) if passwords || !input.password => input.edit.text.clone(),
246        _ => return,
247      };
248      let mut write = None;
249      tree.update_input(id, |input| {
250        change(&mut input.edit);
251        input.refresh();
252        if input.edit.text != before {
253          write = Some((input.signal, input.edit.text.clone()));
254        }
255      });
256      write
257    };
258    if let Some((signal, text)) = write {
259      // A signal whose owner is gone just isn't written.
260      signal.try_set(text);
261    }
262  }
263}
264
265/// A field in the tree.
266pub(crate) struct InputNode {
267  /// What is shown: the text, its dots, or the placeholder.
268  pub(crate) text: TextNode,
269  pub(crate) edit: Edit,
270  /// Written as the text is edited.
271  pub(crate) signal: Signal<String>,
272  pub(crate) placeholder: String,
273  pub(crate) password: bool,
274  /// The field has the keyboard, so it shows its caret.
275  pub(crate) focused: bool,
276  /// The last value of its `focus` binding, which it takes the focus by
277  /// whenever it is shown.
278  pub(crate) wants_focus: bool,
279  /// How far the text is scrolled left to keep the caret in view.
280  pub(crate) scroll: f32,
281  /// Where the caret and the selection are, from the last layout, in
282  /// window coordinates.
283  pub(crate) caret: Rect,
284  /// More than one span when right-to-left and left-to-right text mix.
285  pub(crate) selection: Vec<Rect>,
286  /// The content box the text is cut to, from the last layout.
287  pub(crate) area: Rect,
288  /// What an input method is composing, shown at the caret.
289  pub(crate) preedit: Option<Preedit>,
290  /// The line under the preedit, from the last layout.
291  pub(crate) underline: Vec<Rect>,
292  /// Kept in the reactive runtime, which drops the user's closure when the
293  /// field's owner goes.
294  pub(crate) on_accept: Signal<Option<AcceptHandler>>,
295}
296
297impl InputNode {
298  pub(crate) fn new(signal: Signal<String>, on_accept: Signal<Option<AcceptHandler>>) -> InputNode {
299    InputNode {
300      text: TextNode::new(),
301      edit: Edit::default(),
302      signal,
303      placeholder: String::new(),
304      password: false,
305      focused: false,
306      wants_focus: false,
307      scroll: 0.0,
308      caret: Rect::default(),
309      selection: Vec::new(),
310      area: Rect::default(),
311      preedit: None,
312      underline: Vec::new(),
313      on_accept,
314    }
315  }
316
317  /// Whether the placeholder is what shows.
318  pub(crate) fn showing_placeholder(&self) -> bool {
319    self.edit.text.is_empty() && self.preedit.is_none()
320  }
321
322  /// The preedit's length in bytes, 0 without one.
323  fn preedit_len(&self) -> usize {
324    self
325      .preedit
326      .as_ref()
327      .map_or(0, |preedit| preedit.text.len())
328  }
329
330  /// Puts what should show into the text node. Returns whether that
331  /// changed, which needs a layout.
332  pub(crate) fn refresh(&mut self) -> bool {
333    let shown = if self.showing_placeholder() {
334      self.placeholder.clone()
335    } else if self.password {
336      DOT
337        .to_string()
338        .repeat(graphemes_before(&self.edit.text, self.edit.text.len()))
339    } else if let Some(preedit) = &self.preedit {
340      let (before, after) = self.edit.text.split_at(self.edit.cursor);
341      format!("{before}{}{after}", preedit.text)
342    } else {
343      self.edit.text.clone()
344    };
345    self.text.set_content(shown)
346  }
347
348  /// The byte in what is shown that matches byte `at` of the text.
349  fn shown_index(&self, at: usize) -> usize {
350    if self.showing_placeholder() {
351      0
352    } else if self.password {
353      graphemes_before(&self.edit.text, at) * DOT.len_utf8()
354    } else if at > self.edit.cursor {
355      at + self.preedit_len()
356    } else {
357      at
358    }
359  }
360
361  /// The byte of the text that matches byte `at` of what is shown.
362  fn text_index(&self, at: usize) -> usize {
363    if self.showing_placeholder() {
364      0
365    } else if self.password {
366      grapheme_start(&self.edit.text, at / DOT.len_utf8())
367    } else if at <= self.edit.cursor {
368      at
369    } else {
370      // Inside the preedit is at the caret; past it, shifted back.
371      let after = at.saturating_sub(self.preedit_len()).max(self.edit.cursor);
372      after.min(self.edit.text.len())
373    }
374  }
375
376  /// How far from the line's left edge the caret before byte `at` of
377  /// what is shown sits. In right-to-left text, the start is on the right.
378  fn x_at(&self, at: usize) -> f32 {
379    self
380      .text
381      .runs()
382      .next()
383      .and_then(|run| run.cursor_position(&Cursor::new(0, at)))
384      .unwrap_or(0.0)
385  }
386
387  /// Scrolls the text to keep the caret inside `content`, then places the
388  /// caret and the selection. Called after the text node's own layout.
389  pub(crate) fn place(&mut self, content: Rect) {
390    let at = self.shown_index(self.edit.cursor);
391    let caret = match &self.preedit {
392      Some(preedit) => {
393        at + preedit
394          .cursor
395          .map_or(preedit.text.len(), |(start, _)| start)
396      }
397      None => at,
398    };
399    let caret = self.x_at(caret);
400    let width = self.text.runs().next().map_or(0.0, |run| run.line_w);
401    // The caret's own pixel counts as text, so it shows at the end.
402    let room = (content.width - 1.0).max(0.0);
403    let mut scroll = self.scroll.min((width - room).max(0.0));
404    if caret - scroll > room {
405      scroll = caret - room;
406    }
407    if caret < scroll {
408      scroll = caret;
409    }
410    self.scroll = scroll.max(0.0);
411    self.text.origin.x = content.x - self.scroll;
412    let origin = self.text.origin;
413    let height = self
414      .text
415      .runs()
416      .next()
417      .map_or(content.height, |run| run.line_height);
418    self.caret = Rect::new(origin.x + caret, origin.y, 1.0, height);
419    self.area = content;
420    self.selection = match (self.edit.selection(), self.text.runs().next()) {
421      (Some(range), Some(run)) => {
422        let start = Cursor::new(0, self.shown_index(range.start));
423        let end = Cursor::new(0, self.shown_index(range.end));
424        run
425          .highlight(start, end)
426          .map(|(x, width)| Rect::new(origin.x + x, origin.y, width, height))
427          .collect()
428      }
429      _ => Vec::new(),
430    };
431    self.underline = match (&self.preedit, self.text.runs().next()) {
432      (Some(preedit), Some(run)) => run
433        .highlight(Cursor::new(0, at), Cursor::new(0, at + preedit.text.len()))
434        .map(|(x, width)| Rect::new(origin.x + x, origin.y + height - 1.0, width, 1.0))
435        .collect(),
436      _ => Vec::new(),
437    };
438  }
439
440  /// The text position nearest `point`, in window coordinates.
441  pub(crate) fn hit(&self, point: Point) -> usize {
442    let origin = self.text.origin;
443    let at = self
444      .text
445      .buffer
446      .hit(point.x - origin.x, point.y - origin.y)
447      .map_or(0, |cursor| cursor.index);
448    self.text_index(at)
449  }
450}