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::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}
40
41pub struct TextInput {
60 input: InputProps,
61 common: Common,
62}
63
64impl TextInput {
65 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 pub fn placeholder(mut self, text: impl IntoProp<String>) -> TextInput {
83 self.input.placeholder = Some(text.into_prop());
84 self
85 }
86
87 pub fn password(mut self, password: impl IntoProp<bool>) -> TextInput {
90 self.input.password = Some(password.into_prop());
91 self
92 }
93
94 pub fn focus(mut self, focus: impl IntoProp<bool>) -> TextInput {
97 self.input.focus = Some(focus.into_prop());
98 self
99 }
100
101 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 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#[derive(Clone, Debug, PartialEq, Eq)]
132pub struct Preedit {
133 pub text: String,
135 pub cursor: Option<(usize, usize)>,
137}
138
139#[derive(Clone, Debug, PartialEq)]
141pub struct FieldState {
142 pub field: u64,
144 pub text: String,
146 pub cursor: usize,
148 pub anchor: usize,
150 pub caret: Rect,
152 pub multiline: bool,
154}
155
156impl Window {
157 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 pub fn commit_text(&self, text: &str) {
182 self.edit_field(|edit| edit.insert(text));
183 }
184
185 pub fn paste(&self, text: &str) {
190 if text.is_empty() {
192 return;
193 }
194 self.change_field(true, |edit| edit.insert(text));
195 }
196
197 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 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 fn edit_field(&self, change: impl FnOnce(&mut Edit)) {
246 self.change_field(false, change);
247 }
248
249 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 signal.try_set(text);
274 }
275 }
276}
277
278pub(crate) struct InputNode {
280 pub(crate) text: TextNode,
282 pub(crate) edit: Edit,
283 pub(crate) signal: Signal<String>,
285 pub(crate) placeholder: String,
286 pub(crate) password: bool,
287 pub(crate) focused: bool,
289 pub(crate) wants_focus: bool,
292 pub(crate) scroll: f32,
294 pub(crate) caret: Rect,
297 pub(crate) selection: Vec<Rect>,
299 pub(crate) area: Rect,
301 pub(crate) preedit: Option<Preedit>,
303 pub(crate) underline: Vec<Rect>,
305 pub(crate) goal: Option<(usize, f32)>,
308 pub(crate) upstream: Option<usize>,
311 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 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 pub(crate) fn showing_placeholder(&self) -> bool {
372 self.edit.text.is_empty() && self.preedit.is_none()
373 }
374
375 fn preedit_len(&self) -> usize {
377 self
378 .preedit
379 .as_ref()
380 .map_or(0, |preedit| preedit.text.len())
381 }
382
383 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 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 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 let after = at.saturating_sub(self.preedit_len()).max(self.edit.cursor);
425 after.min(self.edit.text.len())
426 }
427 }
428
429 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 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 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 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 (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 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 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 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 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}