Skip to main content

vizia_core/views/
textbox.rs

1use std::cell::RefCell;
2use std::ops::Range;
3use std::rc::Rc;
4
5use crate::prelude::*;
6
7use crate::text::{
8    Direction, EditableText, Movement, PreeditBackup, Selection, VerticalMovement, apply_movement,
9    enforce_text_bounds, ensure_visible, offset_for_delete_backwards, resolved_text_direction,
10};
11use accesskit::{ActionData, ActionRequest, TextDirection, TextPosition, TextSelection};
12use skia_safe::textlayout::{RectHeightStyle, RectWidthStyle};
13use skia_safe::{ClipOp, Paint, PaintStyle, Point, Rect};
14use unicode_segmentation::UnicodeSegmentation;
15
16/// Events for modifying a textbox.
17pub enum TextEvent {
18    /// Insert a string of text into the textbox.
19    InsertText(String),
20    /// Update the preedit text of the textbox (for IME input).
21    UpdatePreedit(String, Option<(usize, usize)>),
22    /// Clear the preedit text of the textbox.
23    ClearPreedit,
24    /// Reset the text of the textbox to the bound data.
25    Clear,
26    /// Delete a section of text, determined by the `Movement`.
27    DeleteText(Movement),
28    /// Move the cursor and selection.
29    MoveCursor(Movement, bool),
30    /// Select all text.
31    SelectAll,
32    /// Select the word at the current cursor position.
33    SelectWord,
34    /// Select the paragraph at the current cursor position.
35    SelectParagraph,
36    /// Toggle the textbox to allow text input.
37    StartEdit,
38    /// Toggle the textbox to *not* allow text input.
39    EndEdit,
40    /// Trigger the `on_submit` callback with the current text.
41    Submit(bool),
42    /// Specify the 'hit' position of the mouse cursor.
43    Hit(f32, f32, bool),
44    /// Specify the 'drag' position of the mouse cursor.
45    Drag(f32, f32),
46    /// Specify the scroll offset of the textbox.
47    Scroll(f32, f32),
48    /// Copy the textbox buffer to the clipboard.
49    Copy,
50    /// Paste the clipboard buffer into the textbox.
51    Paste,
52    /// Cut the textbox text and place it in the clipboard.
53    Cut,
54    /// Set the placeholder text of the textbox.
55    SetPlaceholder(String),
56    /// Trigger the `on_blur` callback.
57    Blur,
58    /// Set whether masked text should be visible.
59    SetMaskVisible(bool),
60    /// Toggle whether masked text should be visible.
61    ToggleMaskVisible,
62    /// Toggle the visibility of the text Caret.
63    ToggleCaret,
64}
65
66/// The `Textbox` view provides an input control for editing a value as a string.
67///
68/// The textbox takes a lens to some value, which must be a type which can convert to and from a `String`,
69/// as determined by the `ToString` and `FromStr` traits. The value type is used for validation and returned by
70/// the `on_submit` callback, which is triggered when the textbox is submitted with the enter key or when the textbox
71/// loses keyboard focus.
72pub struct Textbox<R, T> {
73    value: R,
74    kind: TextboxKind,
75    edit: bool,
76    transform: Rc<RefCell<(f32, f32)>>,
77    on_edit: Option<Box<dyn Fn(&mut EventContext, String) + Send + Sync>>,
78    on_submit: Option<Box<dyn Fn(&mut EventContext, T, bool) + Send + Sync>>,
79    on_blur: Option<Box<dyn Fn(&mut EventContext) + Send + Sync>>,
80    on_cancel: Option<Box<dyn Fn(&mut EventContext) + Send + Sync>>,
81    validate: Option<Box<dyn Fn(&T) -> bool>>,
82    placeholder: Signal<String>,
83    show_placeholder: Signal<bool>,
84    show_caret: Signal<bool>,
85    mask_char: Signal<Option<char>>,
86    max_length: Signal<Option<usize>>,
87    can_copy: Signal<bool>,
88    can_paste: Signal<bool>,
89    mask_visible: bool,
90    real_text: String,
91    caret_timer: Timer,
92    selection: Selection,
93    preedit_backup: Option<PreeditBackup>,
94    text_overflow: Option<TextOverflow>,
95    edited_since_focus: bool,
96    edited_once: bool,
97}
98
99// Determines whether the enter key submits the text or inserts a new line.
100#[derive(Copy, Clone, PartialEq, Eq)]
101enum TextboxKind {
102    SingleLine,
103    MultiLineUnwrapped,
104    MultiLineWrapped,
105}
106
107impl<R, T> Textbox<R, T>
108where
109    R: Res<T> + 'static,
110    T: Clone + ToStringLocalized + std::str::FromStr + 'static,
111{
112    /// Creates a new single-line textbox.
113    ///
114    /// # Example
115    /// ```rust
116    /// # use vizia_core::prelude::*;
117    /// #
118    /// # #[derive(Lens)]
119    /// # struct AppData {
120    /// #     text: String,
121    /// # }
122    /// #
123    /// # impl Model for AppData {}
124    /// #
125    /// # let cx = &mut Context::default();
126    /// #
127    /// # AppData { text: String::from("Hello World") }.build(cx);
128    /// #
129    /// Textbox::new(cx, AppData::text);
130    /// ```
131    pub fn new(cx: &mut Context, value: R) -> Handle<Self>
132    where
133        R: Clone,
134    {
135        Self::new_core(cx, value, TextboxKind::SingleLine)
136    }
137
138    /// Creates a new multi-line textbox.
139    ///
140    /// The `wrap` parameter determines whether text which is too long for the textbox
141    /// should soft-wrap onto multiple lines. If false, then only hard-wraps from line breaks
142    /// will cause the text to span multiple lines.
143    ///
144    /// # Example
145    /// ```rust
146    /// # use vizia_core::prelude::*;
147    /// #
148    /// # #[derive(Lens)]
149    /// # struct AppData {
150    /// #     text: String,
151    /// # }
152    /// #
153    /// # impl Model for AppData {}
154    /// #
155    /// # let cx = &mut Context::default();
156    /// #
157    /// # AppData { text: String::from("Hello World") }.build(cx);
158    /// #
159    /// Textbox::new_multiline(cx, AppData::text, true);
160    /// ```
161    pub fn new_multiline(cx: &mut Context, value: R, wrap: bool) -> Handle<Self>
162    where
163        R: Clone,
164    {
165        Self::new_core(
166            cx,
167            value,
168            if wrap { TextboxKind::MultiLineWrapped } else { TextboxKind::MultiLineUnwrapped },
169        )
170    }
171
172    fn new_core(cx: &mut Context, value: R, kind: TextboxKind) -> Handle<Self>
173    where
174        R: Clone,
175    {
176        let value_text = value.clone().to_signal(cx);
177        let caret_timer = cx.environment().caret_timer;
178        let initial_text = value.get_value(cx).to_string_local(cx);
179        let show_caret = Signal::new(false);
180        let mask_char = Signal::new(None);
181        let max_length = Signal::new(None);
182        let can_copy = Signal::new(true);
183        let can_paste = Signal::new(true);
184        let placeholder = Signal::new(String::from(""));
185        let show_placeholder = Signal::new(initial_text.is_empty());
186
187        Self {
188            value: value.clone(),
189            kind,
190            edit: false,
191            transform: Rc::new(RefCell::new((0.0, 0.0))),
192            on_edit: None,
193            on_submit: None,
194            on_blur: None,
195            on_cancel: None,
196            validate: None,
197            placeholder,
198            show_placeholder,
199            show_caret,
200            mask_char,
201            max_length,
202            can_copy,
203            can_paste,
204            mask_visible: false,
205            real_text: initial_text.clone(),
206            caret_timer,
207            selection: Selection::new(0, 0),
208            preedit_backup: None,
209            text_overflow: None,
210            edited_since_focus: false,
211            edited_once: false,
212        }
213        .build(cx, move |cx| {
214            cx.add_listener(move |textbox: &mut Self, cx, event| {
215                let flag: bool = textbox.edit;
216                event.map(|window_event, meta| match window_event {
217                    WindowEvent::MouseDown(_) => {
218                        if flag && meta.origin != cx.current() && cx.hovered() != cx.current() {
219                            cx.emit(TextEvent::Blur);
220                        }
221                    }
222
223                    _ => {}
224                });
225            });
226        })
227        .toggle_class("multiline", kind == TextboxKind::MultiLineWrapped)
228        .text_wrap(kind == TextboxKind::MultiLineWrapped)
229        .navigable(true)
230        .role(if kind == TextboxKind::SingleLine {
231            Role::TextInput
232        } else {
233            Role::MultilineTextInput
234        })
235        .text_value(value.clone())
236        .toggle_class("caret", show_caret)
237        .placeholder_shown(show_placeholder)
238        .bind(value_text, move |handle| {
239            handle.bind(placeholder, move |handle| {
240                let text = value_text.get();
241                let txt = text.to_string_local(&handle);
242                let mut display_text = String::new();
243                let handle = handle.modify(|textbox| {
244                    textbox.real_text = txt.clone();
245                    textbox.show_placeholder.set_if_changed(txt.is_empty());
246                    display_text = textbox.display_text_from_real();
247                });
248                handle.text(display_text);
249            });
250        })
251    }
252
253    fn display_text_from_real(&self) -> String {
254        if self.show_placeholder.get() {
255            return self.placeholder.get().clone();
256        }
257
258        if self.mask_visible {
259            return self.real_text.clone();
260        }
261
262        let Some(mask) = self.mask_char.get() else {
263            return self.real_text.clone();
264        };
265
266        let mut masked = String::with_capacity(self.real_text.len());
267        for grapheme in self.real_text.graphemes(true) {
268            if grapheme == "\n" {
269                masked.push('\n');
270            } else {
271                masked.push(mask);
272            }
273        }
274
275        masked
276    }
277
278    fn sync_display_text(&self, cx: &mut EventContext) {
279        cx.style.set_text(cx.tree, cx.current, self.display_text_from_real());
280        cx.style.needs_text_update(cx.current);
281    }
282
283    fn grapheme_index_to_byte(text: &str, idx: usize) -> usize {
284        if idx == 0 {
285            return 0;
286        }
287
288        for (i, (byte, _)) in text.grapheme_indices(true).enumerate() {
289            if i == idx {
290                return byte;
291            }
292        }
293
294        text.len()
295    }
296
297    fn byte_to_grapheme_index(text: &str, byte_offset: usize) -> usize {
298        let mut idx = 0;
299        for (byte, _) in text.grapheme_indices(true) {
300            if byte >= byte_offset {
301                break;
302            }
303            idx += 1;
304        }
305        idx
306    }
307
308    fn selection_display_to_real(
309        display_text: &str,
310        real_text: &str,
311        selection: Selection,
312    ) -> Selection {
313        let anchor_g = Self::byte_to_grapheme_index(display_text, selection.anchor);
314        let active_g = Self::byte_to_grapheme_index(display_text, selection.active);
315        let anchor = Self::grapheme_index_to_byte(real_text, anchor_g);
316        let active = Self::grapheme_index_to_byte(real_text, active_g);
317        Selection::new(anchor, active).with_h_pos(selection.h_pos)
318    }
319
320    fn remap_selection_for_display_change(&mut self, old_display: &str, new_display: &str) {
321        let anchor_g = Self::byte_to_grapheme_index(old_display, self.selection.anchor);
322        let active_g = Self::byte_to_grapheme_index(old_display, self.selection.active);
323        self.selection.anchor = Self::grapheme_index_to_byte(new_display, anchor_g);
324        self.selection.active = Self::grapheme_index_to_byte(new_display, active_g);
325    }
326
327    fn insert_text(&mut self, cx: &mut EventContext, txt: &str) {
328        if let Some(text) = cx.style.text.get_mut(cx.current) {
329            let old_display = text.clone();
330            if self.show_placeholder.get() && !txt.is_empty() {
331                text.clear();
332                self.show_placeholder.set(false);
333            }
334
335            let real_selection =
336                Self::selection_display_to_real(&old_display, &self.real_text, self.selection);
337
338            let clamped = self.clamp_insert_text(txt, real_selection.range());
339
340            text.edit(self.selection.range(), &clamped);
341            self.real_text.edit(real_selection.range(), &clamped);
342
343            // Track the caret in grapheme space so we can remap it safely after
344            // display text is regenerated (for example when masking is enabled).
345            let new_caret_grapheme =
346                Self::byte_to_grapheme_index(text, self.selection.min() + clamped.len());
347
348            self.show_placeholder.set(self.real_text.is_empty());
349            self.sync_display_text(cx);
350            if let Some(new_display) = cx.style.text.get(cx.current) {
351                let new_caret = Self::grapheme_index_to_byte(new_display, new_caret_grapheme);
352                self.selection = Selection::caret(new_caret);
353            }
354            cx.style.needs_access_update(cx.current);
355        }
356    }
357
358    fn update_preedit(
359        &mut self,
360        cx: &mut EventContext,
361        preedit_txt: &str,
362        cursor: Option<(usize, usize)>,
363    ) {
364        if preedit_txt.is_empty() || cursor.is_none() {
365            return;
366        }
367
368        if let Some(text) = cx.style.text.get_mut(cx.current) {
369            let old_display = text.clone();
370            if self.show_placeholder.get() {
371                text.clear();
372                self.show_placeholder.set(false);
373            }
374
375            if !self.selection.is_caret() {
376                let start = self.selection.min();
377                let end = self.selection.max();
378                let real_selection =
379                    Self::selection_display_to_real(&old_display, &self.real_text, self.selection);
380
381                if end > start && end <= text.len() {
382                    text.replace_range(start..end, "");
383                }
384                if real_selection.max() <= self.real_text.len() {
385                    self.real_text.replace_range(real_selection.range(), "");
386                }
387                self.selection = Selection::caret(start);
388            }
389
390            let (original_selection, prev_preedit_text) = {
391                let preedit_backup = self
392                    .preedit_backup
393                    .get_or_insert_with(|| PreeditBackup::new(String::new(), self.selection));
394                (preedit_backup.original_selection, preedit_backup.prev_preedit.clone())
395            };
396
397            let new_caret_grapheme;
398
399            if prev_preedit_text == preedit_txt {
400                // Move the cursor only
401                let caret = original_selection.min() + cursor.unwrap().0;
402                new_caret_grapheme = Self::byte_to_grapheme_index(text, caret);
403            } else {
404                // Bytes index
405                let start = original_selection.min();
406                let end = start + prev_preedit_text.chars().map(|c| c.len_utf8()).sum::<usize>();
407
408                // Delete old preedit text
409                if end > start && end <= text.len() {
410                    text.replace_range(start..end, "");
411                }
412
413                let original_real_selection = Self::selection_display_to_real(
414                    &old_display,
415                    &self.real_text,
416                    original_selection,
417                );
418                let real_start = original_real_selection.min();
419                let real_end =
420                    real_start + prev_preedit_text.chars().map(|c| c.len_utf8()).sum::<usize>();
421                let clamped_preedit = self.clamp_insert_text(preedit_txt, real_start..real_end);
422                if real_end > real_start && real_end <= self.real_text.len() {
423                    self.real_text.replace_range(real_start..real_end, "");
424                }
425                self.real_text.insert_str(real_start, &clamped_preedit);
426
427                text.insert_str(start, &clamped_preedit);
428
429                if let Some((cursor_index, _)) = cursor {
430                    let new_caret =
431                        original_selection.min() + cursor_index.min(clamped_preedit.len());
432                    new_caret_grapheme = Self::byte_to_grapheme_index(text, new_caret);
433                } else {
434                    // If there is no valid cursor, the default behavior is to move to the end of the text.
435                    let new_caret = original_selection.min() + clamped_preedit.chars().count();
436                    new_caret_grapheme = Self::byte_to_grapheme_index(text, new_caret);
437                }
438
439                self.preedit_backup.as_mut().unwrap().set_prev_preedit(clamped_preedit);
440            }
441
442            self.show_placeholder.set(self.real_text.is_empty());
443            self.sync_display_text(cx);
444            if let Some(new_display) = cx.style.text.get(cx.current) {
445                let new_caret = Self::grapheme_index_to_byte(new_display, new_caret_grapheme);
446                self.selection = Selection::caret(new_caret);
447            }
448        }
449    }
450
451    fn clear_preedit(&mut self, cx: &mut EventContext) {
452        if let Some(text) = cx.style.text.get_mut(cx.current)
453            && let Some(preedit_backup) = self.preedit_backup.as_ref()
454        {
455            let old_display = text.clone();
456            let original_selection = preedit_backup.original_selection;
457            let prev_preedit_text = preedit_backup.prev_preedit.clone();
458
459            let start = original_selection.min();
460            let end = start + prev_preedit_text.chars().map(|c| c.len_utf8()).sum::<usize>();
461
462            text.replace_range(start..end, "");
463
464            let original_real_selection =
465                Self::selection_display_to_real(&old_display, &self.real_text, original_selection);
466            let real_start = original_real_selection.min();
467            let real_end =
468                real_start + prev_preedit_text.chars().map(|c| c.len_utf8()).sum::<usize>();
469            if real_end <= self.real_text.len() {
470                self.real_text.replace_range(real_start..real_end, "");
471            }
472
473            self.selection = original_selection;
474
475            self.preedit_backup = None;
476            self.show_placeholder.set(self.real_text.is_empty());
477            self.sync_display_text(cx);
478        }
479    }
480
481    fn delete_text(&mut self, cx: &mut EventContext, movement: Movement) {
482        if self.show_placeholder.get() {
483            return;
484        }
485
486        if self.preedit_backup.is_some() {
487            return;
488        }
489
490        if self.selection.is_caret() {
491            if movement == Movement::Grapheme(Direction::Upstream) {
492                if self.selection.active == 0 {
493                    return;
494                }
495                if let Some(text) = cx.style.text.get_mut(cx.current) {
496                    let old_display = text.clone();
497                    let del_offset = offset_for_delete_backwards(&self.selection, text);
498                    let del_range = del_offset..self.selection.active;
499                    let real_del_range = Self::selection_display_to_real(
500                        &old_display,
501                        &self.real_text,
502                        Selection::new(del_range.start, del_range.end),
503                    )
504                    .range();
505
506                    self.selection = Selection::caret(del_range.start);
507
508                    text.edit(del_range, "");
509                    self.real_text.edit(real_del_range, "");
510
511                    self.sync_display_text(cx);
512                    cx.style.needs_access_update(cx.current);
513                }
514            } else if let Some(text) = cx.style.text.get_mut(cx.current)
515                && let Some(paragraph) = cx.text_context.text_paragraphs.get(cx.current)
516            {
517                let old_display = text.clone();
518                let to_delete = apply_movement(movement, self.selection, text, paragraph, true);
519                let real_to_delete =
520                    Self::selection_display_to_real(&old_display, &self.real_text, to_delete);
521                self.selection = to_delete;
522                let new_cursor_pos = self.selection.min();
523
524                text.edit(to_delete.range(), "");
525                self.real_text.edit(real_to_delete.range(), "");
526                self.selection = Selection::caret(new_cursor_pos);
527
528                self.sync_display_text(cx);
529                cx.style.needs_access_update(cx.current);
530            }
531        } else if let Some(text) = cx.style.text.get_mut(cx.current) {
532            let old_display = text.clone();
533            let del_range = self.selection.range();
534            let real_del_range =
535                Self::selection_display_to_real(&old_display, &self.real_text, self.selection)
536                    .range();
537
538            self.selection = Selection::caret(del_range.start);
539
540            text.edit(del_range, "");
541            self.real_text.edit(real_del_range, "");
542
543            self.sync_display_text(cx);
544            cx.style.needs_access_update(cx.current);
545        }
546
547        self.show_placeholder.set(self.real_text.is_empty());
548    }
549
550    fn reset_text(&mut self, cx: &mut EventContext) {
551        if let Some(text) = cx.style.text.get_mut(cx.current) {
552            text.clear();
553            self.real_text.clear();
554            self.selection = Selection::caret(0);
555            self.show_placeholder.set(true);
556            self.sync_display_text(cx);
557            cx.style.needs_access_update(cx.current);
558        }
559    }
560
561    /// When IME is enabled, the cursor movement logic will be controlled by [`update_preedit`].
562    ///
563    /// [`update_preedit`]: Textbox::update_preedit
564    fn move_cursor(&mut self, cx: &mut EventContext, movement: Movement, selection: bool) {
565        if let Some(text) = cx.style.text.get_mut(cx.current)
566            && let Some(paragraph) = cx.text_context.text_paragraphs.get(cx.current)
567        {
568            let new_selection =
569                apply_movement(movement, self.selection, text, paragraph, selection);
570            self.selection = new_selection;
571            cx.needs_redraw();
572            cx.style.needs_access_update(cx.current);
573        }
574    }
575
576    fn select_all(&mut self, cx: &mut EventContext) {
577        if self.show_placeholder.get() {
578            return;
579        }
580        if let Some(text) = cx.style.text.get(cx.current) {
581            self.selection.anchor = 0;
582            self.selection.active = text.len();
583            cx.needs_redraw();
584            cx.style.needs_access_update(cx.current);
585        }
586    }
587
588    fn select_word(&mut self, cx: &mut EventContext) {
589        if self.show_placeholder.get() {
590            return;
591        }
592        self.move_cursor(cx, Movement::Word(Direction::Upstream), false);
593        self.move_cursor(cx, Movement::Word(Direction::Downstream), true);
594    }
595
596    fn select_paragraph(&mut self, cx: &mut EventContext) {
597        if self.show_placeholder.get() {
598            return;
599        }
600        self.move_cursor(cx, Movement::ParagraphStart, false);
601        self.move_cursor(cx, Movement::ParagraphEnd, true);
602    }
603
604    fn deselect(&mut self) {
605        self.selection = Selection::caret(self.selection.active);
606    }
607
608    /// These input coordinates should be physical coordinates, i.e. what the mouse events provide.
609    /// The output text coordinates will also be physical, but relative to the top of the text
610    /// glyphs, appropriate for passage to cosmic.
611    fn coordinates_global_to_text(&self, cx: &EventContext, x: f32, y: f32) -> (f32, f32) {
612        let bounds = cx.bounds();
613
614        if let Some(paragraph) = cx.text_context.text_paragraphs.get(cx.current) {
615            let padding_left = cx
616                .style
617                .padding_left
618                .get_resolved(cx.current, &cx.style.custom_units_props)
619                .unwrap_or_default();
620            let padding_top = cx
621                .style
622                .padding_top
623                .get_resolved(cx.current, &cx.style.custom_units_props)
624                .unwrap_or_default();
625            let padding_right = cx
626                .style
627                .padding_right
628                .get_resolved(cx.current, &cx.style.custom_units_props)
629                .unwrap_or_default();
630            let padding_bottom = cx
631                .style
632                .padding_bottom
633                .get_resolved(cx.current, &cx.style.custom_units_props)
634                .unwrap_or_default();
635
636            let logical_parent_width = cx.physical_to_logical(bounds.w);
637            let logical_parent_height = cx.physical_to_logical(bounds.h);
638
639            let mut padding_left =
640                padding_left.to_px(logical_parent_width, 0.0) * cx.scale_factor();
641            let mut padding_right =
642                padding_right.to_px(logical_parent_width, 0.0) * cx.scale_factor();
643            let padding_top = padding_top.to_px(logical_parent_height, 0.0) * cx.scale_factor();
644            let padding_bottom =
645                padding_bottom.to_px(logical_parent_height, 0.0) * cx.scale_factor();
646
647            if resolved_text_direction(cx.style, cx.current) == crate::style::Direction::RightToLeft
648            {
649                std::mem::swap(&mut padding_left, &mut padding_right);
650            }
651
652            let (mut top, _) = match cx.style.alignment.get(cx.current).copied().unwrap_or_default()
653            {
654                Alignment::TopLeft => (0.0, 0.0),
655                Alignment::TopCenter => (0.0, 0.5),
656                Alignment::TopRight => (0.0, 1.0),
657                Alignment::Left => (0.5, 0.0),
658                Alignment::Center => (0.5, 0.5),
659                Alignment::Right => (0.5, 1.0),
660                Alignment::BottomLeft => (1.0, 0.0),
661                Alignment::BottomCenter => (1.0, 0.5),
662                Alignment::BottomRight => (1.0, 1.0),
663            };
664
665            top *= bounds.height() - padding_top - padding_bottom - paragraph.height();
666
667            let x = x - bounds.x - padding_left;
668            let y = y - bounds.y - padding_top - top;
669
670            (x, y)
671        } else {
672            (x, y)
673        }
674    }
675
676    /// This function takes window-global physical coordinates.
677    fn hit(&mut self, cx: &mut EventContext, x: f32, y: f32, selection: bool) {
678        if let Some(text) = cx.style.text.get(cx.current)
679            && let Some(paragraph) = cx.text_context.text_paragraphs.get(cx.current)
680        {
681            let (mut x, mut y) = (x, y);
682
683            if let Some(inv_transform) = cx.transform().invert() {
684                let point = inv_transform.map_point(Point::new(x, y));
685                x = point.x;
686                y = point.y;
687            }
688
689            x -= self.transform.borrow().0;
690            y -= self.transform.borrow().1;
691
692            let gp = paragraph
693                .get_glyph_position_at_coordinate(self.coordinates_global_to_text(cx, x, y));
694            let num_graphemes = text.graphemes(true).count();
695            let pos = (gp.position as usize).min(num_graphemes);
696            let mut cursor = text.len();
697            for (i, (j, _)) in text.grapheme_indices(true).enumerate() {
698                if pos == i {
699                    cursor = j;
700                    break;
701                }
702            }
703
704            if selection {
705                self.selection.active = cursor;
706            } else {
707                self.selection = Selection::caret(cursor);
708            }
709
710            cx.needs_redraw();
711            cx.style.needs_access_update(cx.current);
712        }
713    }
714
715    /// This function takes window-global physical coordinates.
716    fn drag(&mut self, cx: &mut EventContext, x: f32, y: f32) {
717        if let Some(text) = cx.style.text.get(cx.current)
718            && let Some(paragraph) = cx.text_context.text_paragraphs.get(cx.current)
719        {
720            let (mut x, mut y) = (x, y);
721
722            if let Some(inv_transform) = cx.transform().invert() {
723                let point = inv_transform.map_point(Point::new(x, y));
724                x = point.x;
725                y = point.y;
726            }
727
728            x -= self.transform.borrow().0;
729            y -= self.transform.borrow().1;
730
731            let gp = paragraph
732                .get_glyph_position_at_coordinate(self.coordinates_global_to_text(cx, x, y));
733            let num_graphemes = text.graphemes(true).count();
734            let pos = (gp.position as usize).min(num_graphemes);
735
736            let mut cursor = text.len();
737            for (i, (j, _)) in text.grapheme_indices(true).enumerate() {
738                if pos == i {
739                    cursor = j;
740                    break;
741                }
742            }
743
744            self.selection.active = cursor;
745
746            cx.needs_redraw();
747            cx.style.needs_access_update(cx.current);
748        }
749    }
750
751    // /// This function takes window-global physical dimensions.
752    // fn scroll(&mut self, cx: &mut EventContext, x: f32, y: f32) {}
753
754    #[cfg(feature = "clipboard")]
755    fn clone_selected(&self, cx: &mut EventContext) -> Option<String> {
756        if let Some(text) = cx.style.text.get(cx.current) {
757            let real_selection =
758                Self::selection_display_to_real(text, &self.real_text, self.selection);
759            let substring = &self.real_text[real_selection.range()];
760            return Some(substring.to_string());
761        }
762
763        None
764    }
765
766    fn clone_text(&self, _cx: &mut EventContext) -> String {
767        if self.show_placeholder.get() {
768            return String::new();
769        }
770
771        self.real_text.clone()
772    }
773
774    fn clamp_insert_text(&self, txt: &str, replace_range: Range<usize>) -> String {
775        let Some(max_length) = self.max_length.get() else {
776            return txt.to_string();
777        };
778
779        let current_len = self.real_text.graphemes(true).count();
780        let replaced_len = self.real_text[replace_range].graphemes(true).count();
781        let preserved_len = current_len.saturating_sub(replaced_len);
782        let remaining = max_length.saturating_sub(preserved_len);
783
784        if remaining == 0 {
785            return String::new();
786        }
787
788        txt.graphemes(true).take(remaining).collect()
789    }
790
791    fn is_text_valid(&self, text: &str) -> bool {
792        if let Ok(value) = text.parse::<T>() {
793            if let Some(validate) = &self.validate { validate(&value) } else { true }
794        } else {
795            false
796        }
797    }
798
799    fn reset_caret_timer(&mut self, cx: &mut EventContext) {
800        cx.stop_timer(self.caret_timer);
801        if !cx.is_read_only() {
802            self.show_caret.set(true);
803            cx.start_timer(self.caret_timer);
804        }
805    }
806
807    fn reset_ime_position(&mut self, cx: &mut EventContext) {
808        // TODO: Make the position of IME follow the cursor.
809        cx.send_event(
810            Event::new(WindowEvent::SetImeCursorArea(
811                (cx.bounds().x as u32, cx.bounds().y as u32),
812                ((cx.bounds().width()) as u32, cx.bounds().height() as u32),
813            ))
814            .target(cx.current),
815        );
816    }
817
818    fn draw_selection(&self, cx: &mut DrawContext, canvas: &Canvas) {
819        if !self.selection.is_caret()
820            && let Some(paragraph) = cx.text_context.text_paragraphs.get(cx.current)
821            && let Some(text) = cx.style.text.get(cx.current)
822        {
823            let min = text.current_grapheme_offset(self.selection.min());
824            let max = text.current_grapheme_offset(self.selection.max());
825
826            let cursor_rects = paragraph.get_rects_for_range(
827                min..max,
828                RectHeightStyle::Tight,
829                RectWidthStyle::Tight,
830            );
831
832            for cursor_rect in cursor_rects {
833                let bounds = cx.bounds();
834
835                let alignment = cx.alignment();
836
837                let (mut top, left) = match alignment {
838                    Alignment::TopLeft => (0.0, 0.0),
839                    Alignment::TopCenter => (0.0, 0.5),
840                    Alignment::TopRight => (0.0, 1.0),
841                    Alignment::Left => (0.5, 0.0),
842                    Alignment::Center => (0.5, 0.5),
843                    Alignment::Right => (0.5, 1.0),
844                    Alignment::BottomLeft => (1.0, 0.0),
845                    Alignment::BottomCenter => (1.0, 0.5),
846                    Alignment::BottomRight => (1.0, 1.0),
847                };
848
849                let padding_top = match cx.padding_top() {
850                    Units::Pixels(val) => val,
851                    _ => 0.0,
852                };
853
854                let padding_bottom = match cx.padding_bottom() {
855                    Units::Pixels(val) => val,
856                    _ => 0.0,
857                };
858
859                top *= bounds.height() - padding_top - padding_bottom - paragraph.height();
860
861                let mut padding_left = match cx.padding_left() {
862                    Units::Pixels(val) => val,
863                    _ => 0.0,
864                };
865
866                let mut padding_right = match cx.padding_right() {
867                    Units::Pixels(val) => val,
868                    _ => 0.0,
869                };
870
871                if resolved_text_direction(cx.style, cx.current)
872                    == crate::style::Direction::RightToLeft
873                {
874                    std::mem::swap(&mut padding_left, &mut padding_right);
875                }
876
877                let x = bounds.x + padding_left + cursor_rect.rect.left + left;
878                let y = bounds.y + padding_top + cursor_rect.rect.top + top;
879
880                let x2 = x + (cursor_rect.rect.right - cursor_rect.rect.left);
881                let y2 = y + (cursor_rect.rect.bottom - cursor_rect.rect.top);
882
883                let mut paint = Paint::default();
884                paint.set_anti_alias(true);
885                paint.set_style(PaintStyle::Fill);
886                paint.set_color(cx.selection_color());
887
888                canvas.draw_rect(Rect::new(x, y, x2, y2), &paint);
889            }
890        }
891    }
892
893    /// Draw text caret for the current view.
894    pub fn draw_text_caret(&self, cx: &mut DrawContext, canvas: &Canvas) {
895        if let Some(paragraph) = cx.text_context.text_paragraphs.get(cx.current)
896            && let Some(text) = cx.style.text.get(cx.current)
897        {
898            let bounds = cx.bounds();
899
900            let current = text.current_grapheme_offset(self.selection.active);
901
902            let grapheme_count = text.graphemes(true).count();
903            let (range_start, range_end, use_trailing_edge) = if current < grapheme_count {
904                (current, current + 1, false)
905            } else if current > 0 {
906                // At end-of-text, use the previous grapheme box and place the caret on its trailing edge.
907                (current - 1, current, true)
908            } else {
909                // Empty text: anchor caret to the paragraph's first position.
910                (0, 1, false)
911            };
912
913            let rects = paragraph.get_rects_for_range(
914                range_start..range_end,
915                RectHeightStyle::Tight,
916                RectWidthStyle::Tight,
917            );
918
919            let Some(cursor_rect) = rects.first() else {
920                return;
921            };
922
923            let alignment = cx.alignment();
924
925            let (mut top, _) = match alignment {
926                Alignment::TopLeft => (0.0, 0.0),
927                Alignment::TopCenter => (0.0, 0.5),
928                Alignment::TopRight => (0.0, 1.0),
929                Alignment::Left => (0.5, 0.0),
930                Alignment::Center => (0.5, 0.5),
931                Alignment::Right => (0.5, 1.0),
932                Alignment::BottomLeft => (1.0, 0.0),
933                Alignment::BottomCenter => (1.0, 0.5),
934                Alignment::BottomRight => (1.0, 1.0),
935            };
936
937            let padding_top = match cx.padding_top() {
938                Units::Pixels(val) => val,
939                _ => 0.0,
940            };
941
942            let padding_bottom = match cx.padding_bottom() {
943                Units::Pixels(val) => val,
944                _ => 0.0,
945            };
946
947            top *= bounds.height() - padding_top - padding_bottom - paragraph.height();
948
949            let mut padding_left = match cx.padding_left() {
950                Units::Pixels(val) => val,
951                _ => 0.0,
952            };
953
954            let mut padding_right = match cx.padding_right() {
955                Units::Pixels(val) => val,
956                _ => 0.0,
957            };
958
959            if resolved_text_direction(cx.style, cx.current) == crate::style::Direction::RightToLeft
960            {
961                std::mem::swap(&mut padding_left, &mut padding_right);
962            }
963
964            let caret_x =
965                if use_trailing_edge { cursor_rect.rect.right } else { cursor_rect.rect.left };
966
967            let x = (bounds.x + padding_left + caret_x).round();
968            let y = (bounds.y + padding_top + cursor_rect.rect.top + top).round();
969
970            let x2 = x + 1.0;
971            let y2 = y + (cursor_rect.rect.bottom - cursor_rect.rect.top);
972
973            let mut paint = Paint::default();
974            paint.set_anti_alias(true);
975            paint.set_style(PaintStyle::Fill);
976            paint.set_color(cx.caret_color());
977
978            canvas.draw_rect(Rect::new(x, y, x2, y2), &paint);
979
980            let mut transform = self.transform.borrow_mut();
981
982            let text_bounds = BoundingBox::from_min_max(
983                bounds.x + padding_left,
984                bounds.y + padding_top + top,
985                bounds.x + padding_left + paragraph.max_intrinsic_width(),
986                bounds.y + padding_top + top + paragraph.height(),
987            );
988
989            let mut bounds = bounds;
990
991            bounds = bounds.shrink_sides(padding_left, padding_top, padding_right, padding_bottom);
992
993            let (tx, ty) = enforce_text_bounds(&text_bounds, &bounds, (transform.0, transform.1));
994
995            let caret_box = BoundingBox::from_min_max(x, y, x2, y2);
996
997            let (new_tx, new_ty) = ensure_visible(&caret_box, &bounds, (tx, ty));
998
999            if new_tx != transform.0 || new_ty != transform.1 {
1000                *transform = (new_tx, new_ty);
1001                cx.needs_redraw();
1002            }
1003        }
1004    }
1005}
1006
1007impl<R, T> Handle<'_, Textbox<R, T>>
1008where
1009    R: Res<T> + 'static,
1010    T: Clone + ToStringLocalized + std::str::FromStr + 'static,
1011{
1012    /// Sets the callback triggered when a textbox is edited, i.e. text is inserted/deleted.
1013    ///
1014    /// Callback provides the current text of the textbox.
1015    pub fn on_edit<F>(self, callback: F) -> Self
1016    where
1017        F: 'static + Fn(&mut EventContext, String) + Send + Sync,
1018    {
1019        self.modify(|textbox| textbox.on_edit = Some(Box::new(callback)))
1020    }
1021
1022    /// Sets the callback triggered when a textbox is submitted,
1023    /// i.e. when the enter key is pressed with a single-line textbox or the textbox loses focus.
1024    ///
1025    /// Callback provides the text of the textbox and a flag to indicate if the submit was due to a key press or a loss of focus.
1026    pub fn on_submit<F>(self, callback: F) -> Self
1027    where
1028        F: 'static + Fn(&mut EventContext, T, bool) + Send + Sync,
1029    {
1030        self.modify(|textbox| textbox.on_submit = Some(Box::new(callback)))
1031    }
1032
1033    /// Sets the callback triggered when a textbox is blurred, i.e. the mouse is pressed outside of the textbox.
1034    pub fn on_blur<F>(self, callback: F) -> Self
1035    where
1036        F: 'static + Fn(&mut EventContext) + Send + Sync,
1037    {
1038        self.modify(|textbox| textbox.on_blur = Some(Box::new(callback)))
1039    }
1040
1041    /// Sets the callback triggered when a textbox edit is cancelled, i.e. the escape key is pressed while editing.
1042    pub fn on_cancel<F>(self, callback: F) -> Self
1043    where
1044        F: 'static + Fn(&mut EventContext) + Send + Sync,
1045    {
1046        self.modify(|textbox| textbox.on_cancel = Some(Box::new(callback)))
1047    }
1048
1049    /// Sets a validation closure which is called when the textbox is edited and sets the validity attribute to the output of the closure.
1050    ///
1051    /// If a textbox is modified with the validate modifier then the `on_submit` will not be called if the text is invalid.
1052    pub fn validate<F>(self, is_valid: F) -> Self
1053    where
1054        F: 'static + Fn(&T) -> bool + Send + Sync,
1055    {
1056        self.modify(|textbox| textbox.validate = Some(Box::new(is_valid)))
1057    }
1058
1059    /// Sets the placeholder text that appears when the textbox has no value.
1060    pub fn placeholder<P: ToStringLocalized + Clone + 'static>(
1061        self,
1062        text: impl Res<P> + 'static,
1063    ) -> Self {
1064        let text = text.to_signal(self.cx);
1065        self.bind(text, move |mut handle| {
1066            let text = text.get();
1067            let txt = text.to_string_local(&handle);
1068            let entity = handle.entity();
1069            handle = handle.modify(|textbox| textbox.placeholder.set(txt));
1070            handle.context().style.needs_access_update(entity);
1071        })
1072    }
1073
1074    /// Sets an optional character used to visually mask textbox text.
1075    ///
1076    /// Use `Some('*')` (or any character) to enable masking and `None` to disable it.
1077    pub fn mask_char<U: Into<Option<char>> + Clone + 'static>(
1078        self,
1079        mask: impl Res<U> + 'static,
1080    ) -> Self {
1081        let mask = mask.to_signal(self.cx);
1082        self.bind(mask, move |mut handle| {
1083            let entity = handle.entity();
1084            let new_mask = mask.get().into();
1085            let mut display_text = String::new();
1086            handle = handle.modify(|textbox| {
1087                let old_display = textbox.display_text_from_real();
1088                textbox.mask_char.set_if_changed(new_mask);
1089                let new_display = textbox.display_text_from_real();
1090                textbox.remap_selection_for_display_change(&old_display, &new_display);
1091                display_text = new_display;
1092            });
1093            handle = handle.text(display_text);
1094            handle.context().style.needs_text_update(entity);
1095            handle.context().needs_redraw(entity);
1096        })
1097    }
1098
1099    /// Sets whether masked text should be visible.
1100    pub fn mask_visible<U: Into<bool> + Clone + 'static>(
1101        self,
1102        visible: impl Res<U> + 'static,
1103    ) -> Self {
1104        let visible = visible.to_signal(self.cx);
1105        self.bind(visible, move |mut handle| {
1106            let entity = handle.entity();
1107            let new_visible = visible.get().into();
1108            let mut display_text = String::new();
1109            let mut changed = false;
1110
1111            handle = handle.modify(|textbox| {
1112                if textbox.mask_visible != new_visible {
1113                    let old_display = textbox.display_text_from_real();
1114                    textbox.mask_visible = new_visible;
1115                    let new_display = textbox.display_text_from_real();
1116                    textbox.remap_selection_for_display_change(&old_display, &new_display);
1117                    display_text = new_display;
1118                    changed = true;
1119                }
1120            });
1121
1122            if changed {
1123                handle = handle.text(display_text);
1124                handle.context().style.needs_text_update(entity);
1125                handle.context().needs_redraw(entity);
1126            }
1127        })
1128    }
1129
1130    /// Sets an optional maximum number of graphemes for textbox input.
1131    ///
1132    /// Use `Some(n)` to limit input length and `None` to remove the limit.
1133    pub fn max_length<U: Into<Option<usize>> + Clone + 'static>(
1134        self,
1135        max_length: impl Res<U> + 'static,
1136    ) -> Self {
1137        let max_length = max_length.to_signal(self.cx);
1138        self.bind(max_length, move |handle| {
1139            let value = max_length.get().into();
1140            handle.modify(|textbox| textbox.max_length.set_if_changed(value));
1141        })
1142    }
1143
1144    /// Sets whether text in this textbox can be copied to the clipboard.
1145    pub fn can_copy<U: Into<bool> + Clone + 'static>(self, state: impl Res<U> + 'static) -> Self {
1146        let state = state.to_signal(self.cx);
1147        self.bind(state, move |handle| {
1148            let value = state.get().into();
1149            handle.modify(|textbox| textbox.can_copy.set_if_changed(value));
1150        })
1151    }
1152
1153    /// Sets whether text can be pasted into this textbox from the clipboard.
1154    pub fn can_paste<U: Into<bool> + Clone + 'static>(self, state: impl Res<U> + 'static) -> Self {
1155        let state = state.to_signal(self.cx);
1156        self.bind(state, move |handle| {
1157            let value = state.get().into();
1158            handle.modify(|textbox| textbox.can_paste.set_if_changed(value));
1159        })
1160    }
1161}
1162
1163/// Converts a byte offset (relative to line start) into a character index
1164/// within the `character_lengths` array for AccessKit text positioning.
1165fn byte_offset_to_char_index(character_lengths: &[u8], byte_offset: usize) -> usize {
1166    let mut cumulative = 0;
1167    for (i, &len) in character_lengths.iter().enumerate() {
1168        cumulative += len as usize;
1169        if byte_offset < cumulative {
1170            return i;
1171        }
1172    }
1173    character_lengths.len()
1174}
1175
1176impl<R, T> View for Textbox<R, T>
1177where
1178    R: Res<T> + 'static,
1179    T: Clone + ToStringLocalized + std::str::FromStr + 'static,
1180{
1181    fn element(&self) -> Option<&'static str> {
1182        Some("textbox")
1183    }
1184
1185    fn accessibility(&self, cx: &mut AccessContext, node: &mut AccessNode) {
1186        if !self.placeholder.get().is_empty() {
1187            node.set_placeholder(self.placeholder.get().clone());
1188        }
1189
1190        let node_id = node.node_id();
1191
1192        let selection = self.selection;
1193
1194        let mut selection_active_line = None;
1195        let mut selection_anchor_line = None;
1196        let mut selection_active_cursor = 0;
1197        let mut selection_anchor_cursor = 0;
1198        let mut first_line_node_id = None;
1199
1200        let text = if self.show_placeholder.get() {
1201            ""
1202        } else {
1203            cx.style.text.get(cx.current).map(|t| t.as_str()).unwrap_or("")
1204        };
1205        // build_paragraph() appends a zero-width space (\u{200B}, 3 UTF-8 bytes)
1206        // to every paragraph, so skia's line metrics include indices beyond the
1207        // actual text. We use text.len() as the upper bound for all slicing.
1208        let text_len = text.len();
1209
1210        if let Some(paragraph) = cx.text_context.text_paragraphs.get(cx.current) {
1211            let text_direction = if resolved_text_direction(cx.style, cx.current)
1212                == crate::style::Direction::RightToLeft
1213            {
1214                TextDirection::RightToLeft
1215            } else {
1216                TextDirection::LeftToRight
1217            };
1218
1219            let line_metrics = paragraph.get_line_metrics();
1220            for line in line_metrics.iter() {
1221                // Skip lines that start beyond the actual text (i.e., the ZWS-only line)
1222                if line.start_index >= text_len && text_len > 0 {
1223                    continue;
1224                }
1225
1226                // We need a child node per line
1227                let mut line_node = AccessNode::new_from_parent(node_id, line.line_number);
1228                line_node.set_role(Role::TextRun);
1229                line_node.set_text_direction(text_direction);
1230                line_node.set_bounds(BoundingBox {
1231                    x: line.left as f32,
1232                    y: (line.baseline - line.ascent) as f32,
1233                    w: line.width as f32,
1234                    h: line.height as f32,
1235                });
1236
1237                // Only iterate over glyphs within the actual text range
1238                let glyph_end = line.end_index.min(text_len);
1239                if line.start_index > glyph_end {
1240                    continue;
1241                }
1242                let estimated_chars = glyph_end.saturating_sub(line.start_index);
1243                let mut character_lengths: Vec<u8> = Vec::with_capacity(estimated_chars);
1244                let mut character_positions: Vec<f32> = Vec::with_capacity(estimated_chars);
1245                let mut character_widths: Vec<f32> = Vec::with_capacity(estimated_chars);
1246                let mut glyph_pos = line.start_index;
1247
1248                while glyph_pos < glyph_end {
1249                    if let Some(cluster_info) = paragraph.get_glyph_cluster_at(glyph_pos) {
1250                        let length = cluster_info.text_range.end - cluster_info.text_range.start;
1251                        if length == 0 {
1252                            break;
1253                        }
1254
1255                        character_lengths.push(length as u8);
1256                        character_positions.push(cluster_info.bounds.left());
1257                        character_widths.push(cluster_info.bounds.width());
1258
1259                        glyph_pos += length;
1260                    } else {
1261                        break;
1262                    }
1263                }
1264
1265                // Include the newline character for hard breaks, as AccessKit needs it
1266                let mut line_end = if line.hard_break {
1267                    line.end_including_newline.min(text_len)
1268                } else {
1269                    glyph_end
1270                };
1271                if line_end < line.start_index {
1272                    line_end = line.start_index;
1273                }
1274                let line_text = text.get(line.start_index..line_end).unwrap_or("").to_owned();
1275
1276                if line.hard_break && line.end_including_newline <= text_len {
1277                    character_lengths.push(1);
1278                    character_positions.push(line.width as f32);
1279                    character_widths.push(0.0);
1280                }
1281
1282                let mut word_starts = Vec::new();
1283                let mut previous_is_alphanumeric = text
1284                    .get(..line.start_index)
1285                    .and_then(|prefix| prefix.graphemes(true).next_back())
1286                    .and_then(|grapheme| grapheme.chars().next())
1287                    .is_some_and(|ch| ch.is_alphanumeric());
1288
1289                for (character_index, grapheme) in line_text.graphemes(true).enumerate() {
1290                    let current_is_alphanumeric =
1291                        grapheme.chars().next().is_some_and(|ch| ch.is_alphanumeric());
1292
1293                    if current_is_alphanumeric
1294                        && !previous_is_alphanumeric
1295                        && let Ok(character_index) = u8::try_from(character_index)
1296                    {
1297                        word_starts.push(character_index);
1298                    }
1299
1300                    previous_is_alphanumeric = current_is_alphanumeric;
1301                }
1302
1303                if first_line_node_id.is_none() {
1304                    first_line_node_id = Some(line_node.node_id());
1305                }
1306
1307                // Check if this line contains the selection active (focus) position
1308                if selection.active >= line.start_index && selection.active <= line_end {
1309                    selection_active_line = Some(line_node.node_id());
1310                    selection_active_cursor = byte_offset_to_char_index(
1311                        &character_lengths,
1312                        selection.active - line.start_index,
1313                    );
1314                }
1315
1316                // Check if this line contains the selection anchor position
1317                if selection.anchor >= line.start_index && selection.anchor <= line_end {
1318                    selection_anchor_line = Some(line_node.node_id());
1319                    selection_anchor_cursor = byte_offset_to_char_index(
1320                        &character_lengths,
1321                        selection.anchor - line.start_index,
1322                    );
1323                }
1324
1325                line_node.set_value(line_text.into_boxed_str());
1326                line_node.set_character_lengths(character_lengths.into_boxed_slice());
1327                line_node.set_character_positions(character_positions.into_boxed_slice());
1328                line_node.set_character_widths(character_widths.into_boxed_slice());
1329                line_node.set_word_starts(word_starts.into_boxed_slice());
1330
1331                node.add_child(line_node);
1332            }
1333        }
1334
1335        if let Some(fallback) = first_line_node_id {
1336            node.set_text_selection(TextSelection {
1337                anchor: TextPosition {
1338                    node: selection_anchor_line.unwrap_or(fallback),
1339                    character_index: selection_anchor_cursor,
1340                },
1341                focus: TextPosition {
1342                    node: selection_active_line.unwrap_or(fallback),
1343                    character_index: selection_active_cursor,
1344                },
1345            });
1346        }
1347    }
1348
1349    fn event(&mut self, cx: &mut EventContext, event: &mut Event) {
1350        // Window Events
1351        event.map(|window_event, meta| match window_event {
1352            WindowEvent::MouseDown(MouseButton::Left) => {
1353                if meta.origin == cx.current {
1354                    return;
1355                }
1356
1357                if cx.is_over() {
1358                    if !cx.is_disabled() {
1359                        cx.focus_with_visibility(true);
1360                        cx.capture();
1361                        cx.lock_cursor_icon();
1362
1363                        if !self.edit {
1364                            cx.emit(TextEvent::StartEdit);
1365                        }
1366                        self.reset_caret_timer(cx);
1367                        cx.emit(TextEvent::Hit(
1368                            cx.mouse.cursor_x,
1369                            cx.mouse.cursor_y,
1370                            cx.modifiers.shift(),
1371                        ));
1372                    }
1373                } else {
1374                    cx.release();
1375
1376                    // Forward event to hovered
1377                    cx.send_event(
1378                        Event::new(WindowEvent::MouseDown(MouseButton::Left)).target(cx.hovered()),
1379                    );
1380                    cx.send_event(
1381                        Event::new(WindowEvent::PressDown { mouse: true }).target(cx.hovered()),
1382                    );
1383                }
1384            }
1385
1386            WindowEvent::FocusIn => {
1387                if cx.mouse.left.pressed != cx.current()
1388                    || cx.mouse.left.state == MouseButtonState::Released
1389                {
1390                    cx.emit(TextEvent::StartEdit);
1391                }
1392            }
1393
1394            WindowEvent::FocusOut => {
1395                cx.emit(TextEvent::EndEdit);
1396            }
1397
1398            WindowEvent::MouseDoubleClick(MouseButton::Left) => {
1399                cx.emit(TextEvent::SelectWord);
1400            }
1401
1402            WindowEvent::MouseTripleClick(MouseButton::Left) => {
1403                cx.emit(TextEvent::SelectParagraph);
1404            }
1405
1406            WindowEvent::MouseUp(MouseButton::Left) => {
1407                self.reset_caret_timer(cx);
1408                cx.unlock_cursor_icon();
1409                cx.release();
1410            }
1411
1412            WindowEvent::MouseMove(x, y) => {
1413                if cx.mouse.left.state == MouseButtonState::Pressed
1414                    && cx.mouse.left.pressed == cx.current
1415                {
1416                    if self.edit {
1417                        self.reset_caret_timer(cx);
1418                    }
1419                    if cx.mouse.left.pos_down.0 != *x || cx.mouse.left.pos_down.1 != *y {
1420                        cx.emit(TextEvent::Drag(*x, *y));
1421                    }
1422                }
1423            }
1424
1425            WindowEvent::MouseScroll(x, y) => {
1426                cx.emit(TextEvent::Scroll(*x, *y));
1427            }
1428
1429            WindowEvent::CharInput(c) => {
1430                if *c != '\u{1b}' && // Escape
1431                    *c != '\u{8}' && // Backspace
1432                    *c != '\u{9}' && // Tab
1433                    *c != '\u{7f}' && // Delete
1434                    *c != '\u{0d}' && // Carriage return
1435                    !cx.modifiers.ctrl() &&
1436                    !cx.modifiers.logo() &&
1437                    self.edit &&
1438                    !cx.is_read_only()
1439                {
1440                    self.reset_caret_timer(cx);
1441                    cx.emit(TextEvent::InsertText(String::from(*c)));
1442                }
1443            }
1444
1445            WindowEvent::ImeCommit(text) => {
1446                if !cx.modifiers.ctrl() && !cx.modifiers.logo() && self.edit && !cx.is_read_only() {
1447                    self.reset_caret_timer(cx);
1448                    cx.emit(TextEvent::ClearPreedit);
1449                    cx.emit(TextEvent::InsertText(text.to_string()));
1450
1451                    self.reset_ime_position(cx);
1452                }
1453            }
1454
1455            WindowEvent::ImePreedit(text, cursor) => {
1456                if !cx.modifiers.ctrl() && !cx.modifiers.logo() && self.edit && !cx.is_read_only() {
1457                    self.reset_caret_timer(cx);
1458                    cx.emit(TextEvent::UpdatePreedit(text.to_string(), *cursor));
1459                }
1460            }
1461
1462            WindowEvent::KeyDown(code, _) => match code {
1463                Code::Enter => {
1464                    if matches!(self.kind, TextboxKind::SingleLine) {
1465                        cx.emit(TextEvent::Submit(true));
1466                    } else if !cx.is_read_only() {
1467                        self.reset_caret_timer(cx);
1468                        cx.emit(TextEvent::InsertText("\n".to_owned()));
1469                    }
1470                }
1471
1472                // Note: no `Code::Space` arm — the space character arrives
1473                // through `WindowEvent::CharInput(' ')` above, which already
1474                // inserts it (and correctly suppresses insertion when Ctrl
1475                // or Cmd is held). Handling it here as well produced double
1476                // insertion on platforms that emit both events for a plain
1477                // spacebar press.
1478                Code::ArrowLeft => {
1479                    self.reset_caret_timer(cx);
1480                    // macOS convention: Option (alt) for word movement,
1481                    // Cmd (logo) for line-boundary movement.
1482                    // Other platforms: Ctrl for word movement.
1483                    #[cfg(target_os = "macos")]
1484                    let movement = if cx.modifiers.logo() {
1485                        Movement::LineStart
1486                    } else if cx.modifiers.alt() {
1487                        Movement::Word(Direction::Left)
1488                    } else {
1489                        Movement::Grapheme(Direction::Left)
1490                    };
1491                    #[cfg(not(target_os = "macos"))]
1492                    let movement = if cx.modifiers.ctrl() {
1493                        Movement::Word(Direction::Left)
1494                    } else {
1495                        Movement::Grapheme(Direction::Left)
1496                    };
1497
1498                    cx.emit(TextEvent::MoveCursor(movement, cx.modifiers.shift()));
1499                }
1500
1501                Code::ArrowRight => {
1502                    self.reset_caret_timer(cx);
1503
1504                    #[cfg(target_os = "macos")]
1505                    let movement = if cx.modifiers.logo() {
1506                        Movement::LineEnd
1507                    } else if cx.modifiers.alt() {
1508                        Movement::Word(Direction::Right)
1509                    } else {
1510                        Movement::Grapheme(Direction::Right)
1511                    };
1512                    #[cfg(not(target_os = "macos"))]
1513                    let movement = if cx.modifiers.ctrl() {
1514                        Movement::Word(Direction::Right)
1515                    } else {
1516                        Movement::Grapheme(Direction::Right)
1517                    };
1518
1519                    cx.emit(TextEvent::MoveCursor(movement, cx.modifiers.shift()));
1520                }
1521
1522                Code::ArrowUp => {
1523                    self.reset_caret_timer(cx);
1524                    if self.kind != TextboxKind::SingleLine {
1525                        cx.emit(TextEvent::MoveCursor(
1526                            Movement::Vertical(VerticalMovement::LineUp),
1527                            cx.modifiers.shift(),
1528                        ));
1529                    }
1530                }
1531
1532                Code::ArrowDown => {
1533                    self.reset_caret_timer(cx);
1534                    if self.kind != TextboxKind::SingleLine {
1535                        cx.emit(TextEvent::MoveCursor(
1536                            Movement::Vertical(VerticalMovement::LineDown),
1537                            cx.modifiers.shift(),
1538                        ));
1539                    }
1540                }
1541
1542                Code::Backspace => {
1543                    self.reset_caret_timer(cx);
1544                    if !cx.is_read_only() {
1545                        #[cfg(target_os = "macos")]
1546                        let movement = if cx.modifiers.logo() {
1547                            // Cmd+Backspace deletes from caret to the visual
1548                            // line start on macOS, matching Cmd+Left cursor
1549                            // movement (which uses `Movement::LineStart`).
1550                            Movement::LineStart
1551                        } else if cx.modifiers.alt() {
1552                            Movement::Word(Direction::Upstream)
1553                        } else {
1554                            Movement::Grapheme(Direction::Upstream)
1555                        };
1556                        #[cfg(not(target_os = "macos"))]
1557                        let movement = if cx.modifiers.ctrl() {
1558                            Movement::Word(Direction::Upstream)
1559                        } else {
1560                            Movement::Grapheme(Direction::Upstream)
1561                        };
1562
1563                        cx.emit(TextEvent::DeleteText(movement));
1564                    }
1565                }
1566
1567                Code::Delete => {
1568                    self.reset_caret_timer(cx);
1569                    if !cx.is_read_only() {
1570                        #[cfg(target_os = "macos")]
1571                        let movement = if cx.modifiers.alt() {
1572                            Movement::Word(Direction::Downstream)
1573                        } else {
1574                            Movement::Grapheme(Direction::Downstream)
1575                        };
1576                        #[cfg(not(target_os = "macos"))]
1577                        let movement = if cx.modifiers.ctrl() {
1578                            Movement::Word(Direction::Downstream)
1579                        } else {
1580                            Movement::Grapheme(Direction::Downstream)
1581                        };
1582
1583                        cx.emit(TextEvent::DeleteText(movement));
1584                    }
1585                }
1586
1587                Code::Escape => {
1588                    if let Some(callback) = &self.on_cancel {
1589                        (callback)(cx);
1590                    } else {
1591                        cx.emit(TextEvent::EndEdit);
1592                    }
1593                }
1594
1595                Code::Home => {
1596                    self.reset_caret_timer(cx);
1597                    cx.emit(TextEvent::MoveCursor(Movement::LineStart, cx.modifiers.shift()));
1598                }
1599
1600                Code::End => {
1601                    self.reset_caret_timer(cx);
1602                    cx.emit(TextEvent::MoveCursor(Movement::LineEnd, cx.modifiers.shift()));
1603                }
1604
1605                Code::PageUp | Code::PageDown => {
1606                    self.reset_caret_timer(cx);
1607                    let direction = if *code == Code::PageUp {
1608                        Direction::Upstream
1609                    } else {
1610                        Direction::Downstream
1611                    };
1612                    cx.emit(TextEvent::MoveCursor(
1613                        if cx.modifiers.ctrl() {
1614                            Movement::Body(direction)
1615                        } else {
1616                            Movement::Page(direction)
1617                        },
1618                        cx.modifiers.shift(),
1619                    ));
1620                }
1621
1622                Code::KeyA => {
1623                    #[cfg(target_os = "macos")]
1624                    let modifier = Modifiers::SUPER;
1625                    #[cfg(not(target_os = "macos"))]
1626                    let modifier = Modifiers::CTRL;
1627
1628                    if cx.modifiers == &modifier {
1629                        cx.emit(TextEvent::SelectAll);
1630                    }
1631                }
1632
1633                Code::KeyC => {
1634                    #[cfg(target_os = "macos")]
1635                    let modifier = Modifiers::SUPER;
1636                    #[cfg(not(target_os = "macos"))]
1637                    let modifier = Modifiers::CTRL;
1638
1639                    if cx.modifiers == &modifier && self.can_copy.get() {
1640                        cx.emit(TextEvent::Copy);
1641                    }
1642                }
1643
1644                Code::KeyV => {
1645                    #[cfg(target_os = "macos")]
1646                    let modifier = Modifiers::SUPER;
1647                    #[cfg(not(target_os = "macos"))]
1648                    let modifier = Modifiers::CTRL;
1649
1650                    if cx.modifiers == &modifier && self.can_paste.get() {
1651                        cx.emit(TextEvent::Paste);
1652                    }
1653                }
1654
1655                Code::KeyX => {
1656                    #[cfg(target_os = "macos")]
1657                    let modifier = Modifiers::SUPER;
1658                    #[cfg(not(target_os = "macos"))]
1659                    let modifier = Modifiers::CTRL;
1660
1661                    if cx.modifiers == &modifier && !cx.is_read_only() {
1662                        cx.emit(TextEvent::Cut);
1663                    }
1664                }
1665
1666                _ => {}
1667            },
1668
1669            WindowEvent::ActionRequest(ActionRequest {
1670                action: accesskit::Action::SetTextSelection,
1671                target_tree: _,
1672                target_node: _,
1673                data: Some(ActionData::SetTextSelection(_selection)),
1674            }) => {
1675                // TODO: Implement SetTextSelection action for screen reader support.
1676            }
1677
1678            _ => {}
1679        });
1680
1681        // Textbox Events
1682        event.map(|text_event, _| match text_event {
1683            TextEvent::InsertText(text) => {
1684                if self.preedit_backup.is_some() {
1685                    return;
1686                }
1687
1688                self.edited_since_focus = true;
1689                self.edited_once = true;
1690
1691                if self.show_placeholder.get() {
1692                    self.reset_text(cx);
1693                }
1694
1695                self.insert_text(cx, text);
1696
1697                let text = self.clone_text(cx);
1698
1699                cx.set_valid(self.is_text_valid(&text));
1700
1701                if self.edit
1702                    && let Some(callback) = &self.on_edit
1703                {
1704                    (callback)(cx, text);
1705                }
1706            }
1707
1708            TextEvent::UpdatePreedit(preedit, cursor) => {
1709                self.update_preedit(cx, preedit, *cursor);
1710            }
1711
1712            TextEvent::ClearPreedit => {
1713                self.clear_preedit(cx);
1714            }
1715
1716            TextEvent::Clear => {
1717                self.reset_text(cx);
1718                // self.scroll(cx, 0.0, 0.0); // ensure_visible
1719                cx.needs_relayout();
1720                cx.needs_redraw();
1721            }
1722
1723            TextEvent::DeleteText(movement) => {
1724                if self.edit {
1725                    self.edited_since_focus = true;
1726                    self.edited_once = true;
1727                    self.delete_text(cx, *movement);
1728
1729                    let text = self.clone_text(cx);
1730
1731                    cx.set_valid(self.is_text_valid(&text));
1732
1733                    if let Some(callback) = &self.on_edit {
1734                        (callback)(cx, text);
1735                    }
1736                }
1737            }
1738
1739            TextEvent::MoveCursor(movement, selection) => {
1740                if self.edit && !self.show_placeholder.get() && self.preedit_backup.is_none() {
1741                    self.move_cursor(cx, *movement, *selection);
1742                }
1743            }
1744
1745            TextEvent::SetPlaceholder(text) => {
1746                self.placeholder.set(text.clone());
1747                cx.style.needs_access_update(cx.current);
1748            }
1749
1750            TextEvent::StartEdit => {
1751                if !cx.is_disabled() && !self.edit {
1752                    self.edit = true;
1753                    self.edited_since_focus = false;
1754                    cx.focus_with_visibility(true);
1755                    cx.capture();
1756                    self.reset_caret_timer(cx);
1757                    self.reset_ime_position(cx);
1758
1759                    self.text_overflow = cx.style.text_overflow.get_inline(cx.current).copied();
1760                    cx.style.text_overflow.remove(cx.current);
1761
1762                    let text = self.value.get_value(cx);
1763                    let text = text.to_string_local(cx);
1764                    self.real_text = text.clone();
1765
1766                    if text.is_empty() {
1767                        self.show_placeholder.set(true);
1768                        self.selection = Selection::caret(0);
1769                        cx.style.needs_access_update(cx.current);
1770                    } else {
1771                        self.show_placeholder.set(false);
1772                        self.select_all(cx);
1773                    }
1774
1775                    // Keep textbox pristine only until first user edit; once edited,
1776                    // preserve validation across blur/focus cycles.
1777                    if self.edited_once || !text.is_empty() {
1778                        cx.set_valid(self.is_text_valid(&text));
1779                    } else {
1780                        cx.set_valid(true);
1781                    }
1782                }
1783
1784                self.sync_display_text(cx);
1785            }
1786
1787            TextEvent::EndEdit => {
1788                self.deselect();
1789                self.edit = false;
1790                cx.release();
1791                cx.stop_timer(self.caret_timer);
1792
1793                let text = self.clone_text(cx);
1794                self.show_placeholder.set(text.is_empty());
1795
1796                if let Some(text_overflow) = self.text_overflow {
1797                    cx.style.text_overflow.insert(cx.current, text_overflow);
1798                } else {
1799                    cx.style.text_overflow.remove(cx.current);
1800                }
1801
1802                self.select_all(cx);
1803
1804                if self.edited_since_focus {
1805                    cx.set_valid(self.is_text_valid(&text));
1806                }
1807
1808                // Reset transform to 0,0
1809                let mut transform = self.transform.borrow_mut();
1810                *transform = (0.0, 0.0);
1811
1812                // Reset cursor position
1813                self.selection = Selection::caret(0);
1814
1815                self.sync_display_text(cx);
1816                cx.style.needs_access_update(cx.current);
1817            }
1818
1819            TextEvent::Blur => {
1820                // Clicking outside a textbox can end editing while retaining keyboard focus
1821                // (for example when clicking non-focusable chrome). Keep focus but remove
1822                // the visible focus indicator for pointer-driven blur.
1823                if cx.focused() == cx.current() {
1824                    cx.focus_with_visibility(false);
1825                }
1826
1827                if let Some(callback) = &self.on_blur {
1828                    (callback)(cx);
1829                } else {
1830                    cx.emit(TextEvent::Submit(false));
1831                    cx.emit(TextEvent::EndEdit);
1832                }
1833            }
1834
1835            TextEvent::SetMaskVisible(visible) => {
1836                if self.mask_visible != *visible {
1837                    let old_display = self.display_text_from_real();
1838                    self.mask_visible = *visible;
1839                    let new_display = self.display_text_from_real();
1840                    self.remap_selection_for_display_change(&old_display, &new_display);
1841                    self.sync_display_text(cx);
1842                    cx.needs_redraw();
1843                }
1844            }
1845
1846            TextEvent::ToggleMaskVisible => {
1847                let old_display = self.display_text_from_real();
1848                self.mask_visible = !self.mask_visible;
1849                let new_display = self.display_text_from_real();
1850                self.remap_selection_for_display_change(&old_display, &new_display);
1851                self.sync_display_text(cx);
1852                cx.needs_redraw();
1853            }
1854
1855            TextEvent::Submit(reason) => {
1856                if let Some(callback) = &self.on_submit {
1857                    let text = self.clone_text(cx);
1858                    let is_valid = self.is_text_valid(&text);
1859                    cx.set_valid(is_valid);
1860                    if is_valid && let Ok(value) = text.parse::<T>() {
1861                        (callback)(cx, value, *reason);
1862                    }
1863                }
1864            }
1865
1866            TextEvent::SelectAll => {
1867                self.select_all(cx);
1868            }
1869
1870            TextEvent::SelectWord => {
1871                self.select_word(cx);
1872            }
1873
1874            TextEvent::SelectParagraph => {
1875                self.select_paragraph(cx);
1876            }
1877
1878            TextEvent::Hit(posx, posy, selection) => {
1879                if !self.show_placeholder.get() {
1880                    self.hit(cx, *posx, *posy, *selection);
1881                }
1882            }
1883
1884            TextEvent::Drag(posx, posy) => {
1885                if !self.show_placeholder.get() {
1886                    self.drag(cx, *posx, *posy);
1887                }
1888            }
1889
1890            TextEvent::Scroll(_x, _y) => {
1891                //self.scroll(cx, *x, *y);
1892            }
1893
1894            TextEvent::Copy => {
1895                #[cfg(feature = "clipboard")]
1896                if self.edit
1897                    && self.can_copy.get()
1898                    && let Some(selected_text) = self.clone_selected(cx)
1899                    && !selected_text.is_empty()
1900                {
1901                    cx.set_clipboard(selected_text).expect("Failed to add text to clipboard");
1902                }
1903            }
1904
1905            TextEvent::Paste => {
1906                #[cfg(feature = "clipboard")]
1907                if self.edit
1908                    && self.can_paste.get()
1909                    && let Ok(text) = cx.get_clipboard()
1910                {
1911                    cx.emit(TextEvent::InsertText(text));
1912                }
1913            }
1914
1915            TextEvent::Cut => {
1916                #[cfg(feature = "clipboard")]
1917                if self.edit
1918                    && let Some(selected_text) = self.clone_selected(cx)
1919                    && !selected_text.is_empty()
1920                {
1921                    self.edited_since_focus = true;
1922                    self.edited_once = true;
1923                    cx.set_clipboard(selected_text).expect("Failed to add text to clipboard");
1924                    self.delete_text(cx, Movement::Grapheme(Direction::Upstream));
1925
1926                    let text = self.clone_text(cx);
1927
1928                    cx.set_valid(self.is_text_valid(&text));
1929
1930                    if let Some(callback) = &self.on_edit {
1931                        (callback)(cx, text);
1932                    }
1933                }
1934            }
1935
1936            TextEvent::ToggleCaret => {
1937                self.show_caret ^= true;
1938            }
1939        });
1940    }
1941
1942    // Use custom drawing for the textbox so a transform can be applied to just the text.
1943    fn draw(&self, cx: &mut DrawContext, canvas: &Canvas) {
1944        cx.draw_shadows(canvas);
1945        cx.draw_background(canvas);
1946        cx.draw_border(canvas);
1947        cx.draw_outline(canvas);
1948
1949        // Clip only the text content to the textbox shape so long text is contained
1950        // without clipping outside effects such as outlines.
1951        canvas.save();
1952        let path = cx.path();
1953        canvas.clip_path(&path, ClipOp::Intersect, true);
1954
1955        let bounds = cx.bounds();
1956        let padding_left = match cx.padding_left() {
1957            Units::Pixels(val) => val,
1958            _ => 0.0,
1959        };
1960        let padding_right = match cx.padding_right() {
1961            Units::Pixels(val) => val,
1962            _ => 0.0,
1963        };
1964        let padding_top = match cx.padding_top() {
1965            Units::Pixels(val) => val,
1966            _ => 0.0,
1967        };
1968        let padding_bottom = match cx.padding_bottom() {
1969            Units::Pixels(val) => val,
1970            _ => 0.0,
1971        };
1972
1973        let content_left = bounds.x + padding_left;
1974        let content_top = bounds.y + padding_top;
1975        let content_right = (bounds.x + bounds.w - padding_right).max(content_left);
1976        let content_bottom = (bounds.y + bounds.h - padding_bottom).max(content_top);
1977        canvas.clip_rect(
1978            Rect::new(content_left, content_top, content_right, content_bottom),
1979            ClipOp::Intersect,
1980            true,
1981        );
1982
1983        let transform = *self.transform.borrow();
1984        canvas.translate((transform.0, transform.1));
1985        cx.draw_text(canvas);
1986
1987        if self.edit {
1988            self.draw_selection(cx, canvas);
1989            self.draw_text_caret(cx, canvas);
1990        }
1991
1992        canvas.restore();
1993    }
1994}