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 showing_placeholder(&self) -> bool {
351 self.edit.text.is_empty() && self.preedit.is_none()
352 }
353
354 fn preedit_len(&self) -> usize {
356 self
357 .preedit
358 .as_ref()
359 .map_or(0, |preedit| preedit.text.len())
360 }
361
362 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 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 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 let after = at.saturating_sub(self.preedit_len()).max(self.edit.cursor);
404 after.min(self.edit.text.len())
405 }
406 }
407
408 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 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 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 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 (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 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 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 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 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}