1use 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::{Color, 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
22const DOT: char = '•';
24
25pub(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 pub(crate) multiline: bool,
38 pub(crate) wrap: Option<Prop<bool>>,
39 pub(crate) max_length: Option<Prop<Option<usize>>>,
40 pub(crate) read_only: Option<Prop<bool>>,
41 pub(crate) selection_color: Option<Prop<Option<Color>>>,
42 pub(crate) selected_text_color: Option<Prop<Option<Color>>>,
43}
44
45pub struct TextInput {
64 input: InputProps,
65 common: Common,
66}
67
68impl TextInput {
69 pub fn new(text: Signal<String>) -> TextInput {
71 TextInput {
72 input: InputProps {
73 text,
74 placeholder: None,
75 password: None,
76 focus: None,
77 on_accept: None,
78 multiline: false,
79 wrap: None,
80 max_length: None,
81 read_only: None,
82 selection_color: None,
83 selected_text_color: None,
84 },
85 common: Common::default(),
86 }
87 }
88
89 pub fn placeholder(mut self, text: impl IntoProp<String>) -> TextInput {
91 self.input.placeholder = Some(text.into_prop());
92 self
93 }
94
95 pub fn password(mut self, password: impl IntoProp<bool>) -> TextInput {
98 self.input.password = Some(password.into_prop());
99 self
100 }
101
102 pub fn max_length(mut self, max: impl IntoProp<Option<usize>>) -> TextInput {
108 self.input.max_length = Some(max.into_prop());
109 self
110 }
111
112 pub fn read_only(mut self, on: impl IntoProp<bool>) -> TextInput {
118 self.input.read_only = Some(on.into_prop());
119 self
120 }
121
122 pub fn selection_color(mut self, color: impl IntoProp<Option<Color>>) -> TextInput {
126 self.input.selection_color = Some(color.into_prop());
127 self
128 }
129
130 pub fn selected_text_color(mut self, color: impl IntoProp<Option<Color>>) -> TextInput {
134 self.input.selected_text_color = Some(color.into_prop());
135 self
136 }
137
138 pub fn focus(mut self, focus: impl IntoProp<bool>) -> TextInput {
141 self.input.focus = Some(focus.into_prop());
142 self
143 }
144
145 pub fn on_accept(mut self, handler: impl Fn(&Cx, &str) + 'static) -> TextInput {
147 self.input.on_accept = Some(Rc::new(Handler::new(handler)));
148 self
149 }
150
151 pub fn style(mut self, style: impl IntoProp<Style>) -> TextInput {
155 self.common.style = Some(style.into_prop());
156 self
157 }
158
159 visibility_methods!();
160}
161
162impl Widget for TextInput {
163 fn into_element(self: Box<Self>) -> Element {
164 Element {
165 name: "TextInput",
166 common: self.common,
167 kind: ElementKind::Input(Box::new(self.input)),
168 children: Vec::new(),
169 }
170 }
171}
172
173#[derive(Clone, Debug, PartialEq, Eq)]
176pub struct Preedit {
177 pub text: String,
179 pub cursor: Option<(usize, usize)>,
181}
182
183#[derive(Clone, Debug, PartialEq)]
185pub struct FieldState {
186 pub field: u64,
188 pub text: String,
190 pub cursor: usize,
192 pub anchor: usize,
194 pub caret: Rect,
196 pub multiline: bool,
198}
199
200impl Window {
201 pub fn field(&self) -> Option<FieldState> {
205 let tree = self.tree.borrow();
206 if !tree.keyboard.entered {
207 return None;
208 }
209 let id = tree.keyboard.focused?;
210 let NodeKind::Input(input) = &tree.node(id)?.kind else {
211 return None;
212 };
213 (!input.password && !input.edit.read_only).then(|| FieldState {
214 field: u64::from(id),
215 text: input.edit.text.clone(),
216 cursor: input.edit.cursor,
217 anchor: input.edit.anchor.unwrap_or(input.edit.cursor),
218 caret: tree.window_rect(id, input.caret),
219 multiline: input.edit.multiline,
220 })
221 }
222
223 pub fn commit_text(&self, text: &str) {
227 self.edit_field(|edit| edit.insert(text));
228 }
229
230 pub fn paste(&self, text: &str) {
235 if text.is_empty() {
237 return;
238 }
239 self.change_field(true, |edit| edit.insert(text));
240 }
241
242 pub fn delete_around(&self, before: usize, after: usize) {
247 self.edit_field(|edit| {
248 let selected = edit.selection().unwrap_or(edit.cursor..edit.cursor);
249 let start = selected.start.saturating_sub(before);
250 let end = selected.end.saturating_add(after).min(edit.text.len());
251 if !(edit.text.is_char_boundary(start) && edit.text.is_char_boundary(end)) {
252 return;
253 }
254 edit.text.replace_range(selected.end..end, "");
255 edit.text.replace_range(start..selected.start, "");
256 let removed = selected.start - start;
257 edit.cursor -= removed;
258 edit.anchor = edit.anchor.map(|anchor| anchor - removed);
259 });
260 }
261
262 pub fn set_preedit(&self, preedit: Option<Preedit>) {
265 let preedit = preedit.filter(|preedit| !preedit.text.is_empty());
266 if preedit.is_some() {
267 self.edit_field(|edit| {
268 if edit.selection().is_some() {
269 edit.insert("");
270 }
271 });
272 }
273 let mut tree = borrow(&self.tree);
274 let Some(id) = tree.keyboard.focused else {
275 return;
276 };
277 if matches!(tree.node(id).map(|node| &node.kind), Some(NodeKind::Input(input)) if input.password || input.edit.read_only)
278 {
279 return;
280 }
281 tree.update_input(id, |input| {
282 input.preedit = preedit;
283 input.refresh();
284 });
285 }
286
287 fn edit_field(&self, change: impl FnOnce(&mut Edit)) {
291 self.change_field(false, change);
292 }
293
294 fn change_field(&self, passwords: bool, change: impl FnOnce(&mut Edit)) {
297 let write = {
298 let mut tree = borrow(&self.tree);
299 let Some(id) = tree.keyboard.focused else {
300 return;
301 };
302 let before = match tree.node(id).map(|node| &node.kind) {
303 Some(NodeKind::Input(input)) if (passwords || !input.password) && !input.edit.read_only => {
304 input.edit.text.clone()
305 }
306 _ => return,
307 };
308 let mut write = None;
309 tree.update_input(id, |input| {
310 change(&mut input.edit);
311 input.refresh();
312 if input.edit.text != before {
313 write = Some((input.signal, input.edit.text.clone()));
314 }
315 });
316 write
317 };
318 if let Some((signal, text)) = write {
319 signal.try_set(text);
321 }
322 }
323}
324
325pub(crate) struct InputNode {
327 pub(crate) text: TextNode,
329 pub(crate) edit: Edit,
330 pub(crate) signal: Signal<String>,
332 pub(crate) placeholder: String,
333 pub(crate) password: bool,
334 pub(crate) focused: bool,
336 pub(crate) wants_focus: bool,
339 pub(crate) scroll: f32,
341 pub(crate) caret: Rect,
344 pub(crate) selection: Vec<Rect>,
346 pub(crate) area: Rect,
348 pub(crate) preedit: Option<Preedit>,
350 pub(crate) selection_color: Option<Color>,
352 pub(crate) selected_text_color: Option<Color>,
353 pub(crate) underline: Vec<Rect>,
355 pub(crate) goal: Option<(usize, f32)>,
358 pub(crate) upstream: Option<usize>,
361 pub(crate) on_accept: Signal<Option<AcceptHandler>>,
364}
365
366impl InputNode {
367 pub(crate) fn new(
368 signal: Signal<String>,
369 on_accept: Signal<Option<AcceptHandler>>,
370 multiline: bool,
371 ) -> InputNode {
372 let mut text = TextNode::new();
373 if multiline {
374 text.set_max_lines(u32::MAX);
375 }
376 InputNode {
377 text,
378 edit: Edit {
379 multiline,
380 ..Edit::default()
381 },
382 signal,
383 placeholder: String::new(),
384 password: false,
385 focused: false,
386 wants_focus: false,
387 scroll: 0.0,
388 caret: Rect::default(),
389 selection: Vec::new(),
390 area: Rect::default(),
391 preedit: None,
392 selection_color: None,
393 selected_text_color: None,
394 underline: Vec::new(),
395 goal: None,
396 upstream: None,
397 on_accept,
398 }
399 }
400
401 pub(crate) fn access_text(&self) -> crate::access::AccessText {
404 let text = &self.edit.text;
405 let at = |byte: usize| match self.password {
406 true => graphemes_before(text, byte),
407 false => text[..byte].chars().count(),
408 };
409 crate::access::AccessText {
410 text: match self.password {
411 true => DOT.to_string().repeat(at(text.len())),
412 false => text.clone(),
413 },
414 caret: at(self.edit.cursor),
415 selection: self
416 .edit
417 .selection()
418 .map(|range| (at(range.start), at(range.end))),
419 }
420 }
421
422 pub(crate) fn showing_placeholder(&self) -> bool {
424 self.edit.text.is_empty() && self.preedit.is_none()
425 }
426
427 fn preedit_len(&self) -> usize {
429 self
430 .preedit
431 .as_ref()
432 .map_or(0, |preedit| preedit.text.len())
433 }
434
435 pub(crate) fn refresh(&mut self) -> bool {
438 let shown = if self.showing_placeholder() {
439 self.placeholder.clone()
440 } else if self.password {
441 DOT
442 .to_string()
443 .repeat(graphemes_before(&self.edit.text, self.edit.text.len()))
444 } else if let Some(preedit) = &self.preedit {
445 let (before, after) = self.edit.text.split_at(self.edit.cursor);
446 format!("{before}{}{after}", preedit.text)
447 } else {
448 self.edit.text.clone()
449 };
450 self.text.set_content(shown)
451 }
452
453 pub(crate) fn shown_selection(&self) -> Option<std::ops::Range<usize>> {
455 let range = self.edit.selection()?;
456 Some(self.shown_index(range.start)..self.shown_index(range.end))
457 }
458
459 fn shown_index(&self, at: usize) -> usize {
461 if self.showing_placeholder() {
462 0
463 } else if self.password {
464 graphemes_before(&self.edit.text, at) * DOT.len_utf8()
465 } else if at > self.edit.cursor {
466 at + self.preedit_len()
467 } else {
468 at
469 }
470 }
471
472 fn text_index(&self, at: usize) -> usize {
474 if self.showing_placeholder() {
475 0
476 } else if self.password {
477 grapheme_start(&self.edit.text, at / DOT.len_utf8())
478 } else if at <= self.edit.cursor {
479 at
480 } else {
481 let after = at.saturating_sub(self.preedit_len()).max(self.edit.cursor);
483 after.min(self.edit.text.len())
484 }
485 }
486
487 fn caret_run(&self, at: usize, upstream: bool) -> Option<TextRun<'_>> {
490 let cursor = cursor_at(&self.text.buffer, at);
491 let mut runs = self.text.runs().filter(|run| {
492 run.line_i == cursor.line
493 && (run.glyphs.is_empty() || {
494 let start = run.glyphs.iter().map(|glyph| glyph.start).min();
495 let end = run.glyphs.iter().map(|glyph| glyph.end).max();
496 start.is_some_and(|start| start <= cursor.index)
497 && end.is_some_and(|end| cursor.index <= end)
498 })
499 });
500 if upstream { runs.next() } else { runs.last() }
501 }
502
503 fn caret_spot(&self, at: usize, upstream: bool) -> Option<(f32, f32, f32)> {
508 let run = self
509 .caret_run(at, upstream)
510 .or_else(|| self.text.runs().next())?;
511 let x = if run.glyphs.is_empty() || self.showing_placeholder() {
512 self.text.empty_line_place(run.rtl) * self.text.layout_width()
513 } else {
514 run
515 .layout()
516 .cursor_position(&cursor_at(&self.text.buffer, at))
517 .unwrap_or(0.0)
518 };
519 Some((x, run.line_top, run.line_height))
520 }
521
522 fn glyph_box(&self, top: f32, height: f32) -> (f32, f32) {
526 let natural = (1.2 * self.text.buffer.metrics().font_size).round();
527 let glyphs = natural.min(height);
528 (top + ((height - glyphs) / 2.0).round(), glyphs)
529 }
530
531 pub(crate) fn finish(&mut self, content: Rect, fonts: &mut FontSystem) {
535 let room = (content.width - 1.0).max(0.0);
536 let width = match (self.text.aligned(), self.text.wraps()) {
537 (false, wraps) => wraps.then_some(content.width),
538 (true, true) => Some(room),
539 (true, false) if self.showing_placeholder() => Some(room),
541 (true, false) => Some(self.text.width().max(room)),
542 };
543 self.text.finish_at(content, width, fonts);
544 }
545
546 pub(crate) fn place(&mut self, content: Rect) {
550 let at = self.shown_index(self.edit.cursor);
551 let caret = match &self.preedit {
552 Some(preedit) => {
553 at + preedit
554 .cursor
555 .map_or(preedit.text.len(), |(start, _)| start)
556 }
557 None => at,
558 };
559 let upstream = self.upstream == Some(self.edit.cursor) && self.preedit.is_none();
560 let (x, top, height) = self
561 .caret_spot(caret, upstream)
562 .unwrap_or((0.0, 0.0, content.height));
563 let width = self.text.runs().map(|run| run.line_w).fold(0.0, f32::max);
564 let room = (content.width - 1.0).max(0.0);
566 let mut scroll = self.scroll.min((width - room).max(0.0));
567 if x - scroll > room {
568 scroll = x - room;
569 }
570 if x < scroll {
571 scroll = x;
572 }
573 self.scroll = scroll.max(0.0);
574 self.text.origin.x = content.x - self.scroll;
575 let origin = self.text.origin;
576 let (top, height) = self.glyph_box(top, height);
577 self.caret = Rect::new(origin.x + x, origin.y + top, 1.0, height);
578 self.area = content;
579 self.selection = match self.shown_selection() {
580 Some(range) => highlights(&self.text, range),
581 None => Vec::new(),
582 };
583 self.underline = match &self.preedit {
584 Some(preedit) => highlights(&self.text, at..at + preedit.text.len())
585 .into_iter()
586 .map(|span| {
587 let (top, height) = self.glyph_box(span.y, span.height);
588 Rect::new(span.x, top + height - 1.0, span.width, 1.0)
589 })
590 .collect(),
591 None => Vec::new(),
592 };
593 }
594
595 pub(crate) fn hit(&self, point: Point) -> (usize, bool) {
599 let origin = self.text.origin;
600 let Some(cursor) = self.text.buffer.hit(point.x - origin.x, point.y - origin.y) else {
601 return (0, false);
602 };
603 let at = self.text_index(index_of(&self.text.buffer, cursor));
604 (at, cursor.affinity == Affinity::Before)
605 }
606
607 pub(crate) fn line_key(&mut self, event: &KeyEvent, page: f32) -> Option<Keyed> {
613 let ctrl = event.modifiers.ctrl;
614 let lines = match event.key {
615 Key::Up => -1.0,
616 Key::Down => 1.0,
617 Key::PageUp => -page,
618 Key::PageDown => page,
619 Key::Home | Key::End if !ctrl => 0.0,
620 _ => return None,
621 };
622 let at = self.shown_index(self.edit.cursor);
623 let upstream = self.upstream == Some(self.edit.cursor);
624 let (target, upstream, goal) = if lines == 0.0 {
625 let run = self.caret_run(at, upstream)?;
626 let ends = run.glyphs.iter().map(|glyph| (glyph.start, glyph.end));
627 let index = if event.key == Key::Home {
628 ends.map(|(start, _)| start).min()
629 } else {
630 ends.map(|(_, end)| end).max()
631 };
632 let line = cosmic_text::Cursor::new(run.line_i, index.unwrap_or(0));
633 (
634 index_of(&self.text.buffer, line),
635 event.key == Key::End,
636 None,
637 )
638 } else {
639 let (x, top, height) = self.caret_spot(at, upstream)?;
640 let x = self
641 .goal
642 .filter(|&(cursor, _)| cursor == self.edit.cursor)
643 .map_or(x, |(_, x)| x);
644 let step = if matches!(event.key, Key::Up | Key::Down) {
645 lines * height
646 } else {
647 lines
648 };
649 let cursor = self.text.buffer.hit(x, top + height / 2.0 + step)?;
650 (
651 index_of(&self.text.buffer, cursor),
652 cursor.affinity == Affinity::Before,
653 Some(x),
654 )
655 };
656 let target = self.text_index(target);
657 self.edit.move_to(event.modifiers.shift, target);
658 self.upstream = upstream.then_some(target);
659 self.goal = goal.map(|x| (target, x));
660 Some(Keyed::Moved)
661 }
662}