Skip to main content

euv_core/scene/kind/
impl.rs

1use super::*;
2
3/// Value equality for `ImageBuffer` with O(1) identity and shared-storage fast paths.
4impl PartialEq for ImageBuffer {
5    /// Compares two image buffers by dimensions and RGBA8 pixel content, short-circuiting on matching image ID or shared `Arc` storage.
6    ///
7    /// # Arguments
8    ///
9    /// - `&Self` - Left-hand image buffer.
10    /// - `&Self` - Right-hand image buffer.
11    ///
12    /// # Returns
13    ///
14    /// - `bool` - `true` when both buffers have identical dimensions and pixel bytes.
15    fn eq(&self, other: &Self) -> bool {
16        if self.get_width() != other.get_width() || self.get_height() != other.get_height() {
17            return false;
18        }
19        if self.get_id() != 0 && self.get_id() == other.get_id() {
20            return true;
21        }
22        Arc::ptr_eq(self.pixels_arc(), other.pixels_arc())
23            || self.pixels_slice() == other.pixels_slice()
24    }
25}
26
27/// Reflexive equality marker for `ImageBuffer`.
28impl Eq for ImageBuffer {}
29
30/// Helper operations for `ImageBuffer` and `InputNodeState`.
31impl ImageBuffer {
32    /// Constructs a zero-copy shared RGBA8 `ImageBuffer` and assigns a unique monotonic identifier.
33    ///
34    /// # Arguments
35    ///
36    /// - `u32` - Width in pixels.
37    /// - `u32` - Height in pixels.
38    /// - `P` - Packed RGBA8 pixel storage convertible into `Arc<[u8]>`.
39    ///
40    /// # Returns
41    ///
42    /// - `Self` - Populated zero-copy `ImageBuffer`.
43    #[must_use]
44    pub fn new<P>(width: u32, height: u32, pixels: P) -> Self
45    where
46        P: Into<Arc<[u8]>>,
47    {
48        let id: u64 = NEXT_IMAGE_ID.fetch_add(1, Ordering::Relaxed);
49        let shared: Arc<[u8]> = pixels.into();
50        Self {
51            id,
52            width,
53            height,
54            pixels: shared,
55        }
56    }
57
58    /// Returns a borrowed slice over the packed RGBA8 pixel bytes.
59    ///
60    /// # Arguments
61    ///
62    /// - `&Self` - Source image buffer.
63    ///
64    /// # Returns
65    ///
66    /// - `&[u8]` - Packed RGBA8 pixel slice.
67    #[must_use]
68    pub fn get_pixels(&self) -> &[u8] {
69        self.pixels.as_ref()
70    }
71
72    /// Returns a borrowed slice over the packed RGBA8 pixel bytes.
73    ///
74    /// # Arguments
75    ///
76    /// - `&Self` - Source image buffer.
77    ///
78    /// # Returns
79    ///
80    /// - `&[u8]` - Packed RGBA8 pixel slice.
81    #[must_use]
82    pub fn pixels_slice(&self) -> &[u8] {
83        self.get_pixels()
84    }
85
86    /// Returns a borrowed reference to the underlying shared `Arc<[u8]>` pixel storage.
87    ///
88    /// # Arguments
89    ///
90    /// - `&Self` - Source image buffer.
91    ///
92    /// # Returns
93    ///
94    /// - `&Arc<[u8]>` - Shared atomic reference-counted pixel slice.
95    #[must_use]
96    pub fn pixels_arc(&self) -> &Arc<[u8]> {
97        let Self { pixels, .. } = self;
98        pixels
99    }
100
101    /// Creates a solid-color RGBA8 image buffer for icons, placeholders, or tests.
102    ///
103    /// # Arguments
104    ///
105    /// - `u32` - Width in pixels.
106    /// - `u32` - Height in pixels.
107    /// - `Color` - Fill color.
108    ///
109    /// # Returns
110    ///
111    /// - `Self` - Populated `ImageBuffer`.
112    #[must_use]
113    pub fn solid(width: u32, height: u32, color: Color) -> Self {
114        let count: usize = (width as usize).saturating_mul(height as usize);
115        let rgba: [u8; 4] = color.to_rgba_bytes();
116        let mut pixels: Vec<u8> = Vec::with_capacity(count.saturating_mul(4));
117        for _ in 0..count {
118            pixels.extend_from_slice(&rgba);
119        }
120        Self::new(width, height, pixels)
121    }
122}
123
124/// Text editing and fluent construction helpers for `InputNodeState`.
125impl InputNodeState {
126    /// Constructs an `InputNodeState` with the given text, placeholder, caret byte offset, and flags.
127    ///
128    /// # Arguments
129    ///
130    /// - `String` - Initial UTF-8 input value.
131    /// - `String` - Placeholder text displayed when `value` is empty.
132    /// - `usize` - Initial caret byte offset (snapped to a valid UTF-8 char boundary).
133    /// - `bool` - Whether characters are masked as a password field.
134    /// - `bool` - Whether multi-line editing is enabled.
135    /// - `bool` - Whether user editing is disabled.
136    ///
137    /// # Returns
138    ///
139    /// - `Self` - Constructed `InputNodeState` with no active selection.
140    #[must_use]
141    pub fn new(
142        value: String,
143        placeholder: String,
144        caret: usize,
145        password: bool,
146        multiline: bool,
147        disabled: bool,
148    ) -> Self {
149        let clamped_caret: usize = Self::snap_utf8_boundary(value.as_str(), caret);
150        Self {
151            value,
152            placeholder,
153            caret: clamped_caret,
154            selection_anchor: None,
155            password,
156            multiline,
157            disabled,
158        }
159    }
160
161    /// Replaces the input value while preserving mid-string caret offsets (snapped to UTF-8 boundaries), advancing end-aligned carets, and clearing stale selections.
162    ///
163    /// # Arguments
164    ///
165    /// - `&Self` - Mutable input state.
166    /// - `String` - Replacement UTF-8 input value.
167    ///
168    /// # Returns
169    ///
170    /// - `&mut Self` - Mutable reference for fluent chaining.
171    pub fn set_value(&mut self, value: String) -> &mut Self {
172        let was_at_end: bool = self.caret >= self.value.len();
173        self.value = value;
174        if was_at_end {
175            self.caret = self.value.len();
176        } else {
177            self.caret = Self::snap_utf8_boundary(self.value.as_str(), self.caret);
178        }
179        self.selection_anchor = None;
180        self
181    }
182
183    /// Snaps an arbitrary byte index `idx` downward to the nearest valid UTF-8 char boundary in `s`.
184    ///
185    /// # Arguments
186    ///
187    /// - `&str` - Source UTF-8 string.
188    /// - `usize` - Candidate byte index.
189    ///
190    /// # Returns
191    ///
192    /// - `usize` - Valid UTF-8 char boundary `<= s.len()`.
193    #[must_use]
194    fn snap_utf8_boundary(s: &str, idx: usize) -> usize {
195        let mut pos: usize = idx.min(s.len());
196        while pos > 0 && !s.is_char_boundary(pos) {
197            pos -= 1;
198        }
199        pos
200    }
201
202    /// Returns `true` when `ch` is treated as part of a word for word-wise navigation and deletion.
203    ///
204    /// # Arguments
205    ///
206    /// - `char` - Unicode scalar value to classify.
207    ///
208    /// # Returns
209    ///
210    /// - `bool` - `true` for alphanumeric characters or underscores.
211    #[must_use]
212    fn is_word_char(ch: char) -> bool {
213        ch.is_alphanumeric() || ch == '_'
214    }
215
216    /// Returns the previous UTF-8 char boundary strictly before `pos` (or `0` when at start).
217    ///
218    /// # Arguments
219    ///
220    /// - `&str` - Source UTF-8 string.
221    /// - `usize` - Valid char boundary byte offset.
222    ///
223    /// # Returns
224    ///
225    /// - `usize` - Preceding UTF-8 char boundary byte offset.
226    #[must_use]
227    fn prev_char_boundary(s: &str, pos: usize) -> usize {
228        let safe_pos: usize = Self::snap_utf8_boundary(s, pos);
229        s[..safe_pos]
230            .char_indices()
231            .next_back()
232            .map(|(idx, _): (usize, char)| idx)
233            .unwrap_or(0)
234    }
235
236    /// Returns the next UTF-8 char boundary strictly after `pos` (or `s.len()` when at end).
237    ///
238    /// # Arguments
239    ///
240    /// - `&str` - Source UTF-8 string.
241    /// - `usize` - Valid char boundary byte offset.
242    ///
243    /// # Returns
244    ///
245    /// - `usize` - Following UTF-8 char boundary byte offset.
246    #[must_use]
247    fn next_char_boundary(s: &str, pos: usize) -> usize {
248        let safe_pos: usize = Self::snap_utf8_boundary(s, pos);
249        if safe_pos >= s.len() {
250            return s.len();
251        }
252        s[safe_pos..]
253            .chars()
254            .next()
255            .map(|ch: char| safe_pos + ch.len_utf8())
256            .unwrap_or(s.len())
257    }
258
259    /// Returns the byte offset of the previous word boundary before `pos`.
260    ///
261    /// # Arguments
262    ///
263    /// - `&str` - Source UTF-8 string.
264    /// - `usize` - Current caret byte offset.
265    ///
266    /// # Returns
267    ///
268    /// - `usize` - Target UTF-8 char boundary byte offset.
269    #[must_use]
270    fn prev_word_boundary(s: &str, pos: usize) -> usize {
271        let safe_pos: usize = Self::snap_utf8_boundary(s, pos);
272        let mut seen_non_ws: bool = false;
273        let mut target_is_word: bool = false;
274        let mut out: usize = 0;
275        for (idx, ch) in s[..safe_pos].char_indices().rev() {
276            if !seen_non_ws {
277                if ch.is_whitespace() {
278                    continue;
279                }
280                seen_non_ws = true;
281                target_is_word = Self::is_word_char(ch);
282                out = idx;
283                continue;
284            }
285            if ch.is_whitespace() || Self::is_word_char(ch) != target_is_word {
286                break;
287            }
288            out = idx;
289        }
290        out
291    }
292
293    /// Returns the byte offset of the next word boundary after `pos`.
294    ///
295    /// # Arguments
296    ///
297    /// - `&str` - Source UTF-8 string.
298    /// - `usize` - Current caret byte offset.
299    ///
300    /// # Returns
301    ///
302    /// - `usize` - Target UTF-8 char boundary byte offset.
303    #[must_use]
304    fn next_word_boundary(s: &str, pos: usize) -> usize {
305        let safe_pos: usize = Self::snap_utf8_boundary(s, pos);
306        let tail: &str = &s[safe_pos..];
307        let mut seen_non_ws: bool = false;
308        let mut target_is_word: bool = false;
309        for (rel_idx, ch) in tail.char_indices() {
310            if !seen_non_ws {
311                if ch.is_whitespace() {
312                    continue;
313                }
314                seen_non_ws = true;
315                target_is_word = Self::is_word_char(ch);
316                continue;
317            }
318            if ch.is_whitespace() || Self::is_word_char(ch) != target_is_word {
319                return safe_pos + rel_idx;
320            }
321        }
322        s.len()
323    }
324
325    /// Returns the byte offset of the start of the line containing `pos`.
326    ///
327    /// # Arguments
328    ///
329    /// - `&str` - Source UTF-8 string.
330    /// - `usize` - Current caret byte offset.
331    ///
332    /// # Returns
333    ///
334    /// - `usize` - Byte offset immediately after the preceding `'\n'`, or `0`.
335    #[must_use]
336    fn line_start_offset(s: &str, pos: usize) -> usize {
337        let safe_pos: usize = Self::snap_utf8_boundary(s, pos);
338        s[..safe_pos]
339            .rfind('\n')
340            .map(|idx: usize| idx + 1)
341            .unwrap_or(0)
342    }
343
344    /// Returns the byte offset of the end of the line containing `pos` (before `'\n'` or at `s.len()`).
345    ///
346    /// # Arguments
347    ///
348    /// - `&str` - Source UTF-8 string.
349    /// - `usize` - Current caret byte offset.
350    ///
351    /// # Returns
352    ///
353    /// - `usize` - Byte offset of the next `'\n'`, or `s.len()`.
354    #[must_use]
355    fn line_end_offset(s: &str, pos: usize) -> usize {
356        let safe_pos: usize = Self::snap_utf8_boundary(s, pos);
357        s[safe_pos..]
358            .find('\n')
359            .map(|rel: usize| safe_pos + rel)
360            .unwrap_or(s.len())
361    }
362
363    /// Converts a Unicode scalar index `char_idx` inside `s` into its UTF-8 byte offset.
364    ///
365    /// # Arguments
366    ///
367    /// - `&str` - Source UTF-8 string.
368    /// - `usize` - 0-based character index.
369    ///
370    /// # Returns
371    ///
372    /// - `usize` - Corresponding UTF-8 byte offset in `0..=s.len()`.
373    #[must_use]
374    fn byte_offset_for_char_index(s: &str, char_idx: usize) -> usize {
375        s.char_indices()
376            .nth(char_idx)
377            .map(|(idx, _): (usize, char)| idx)
378            .unwrap_or(s.len())
379    }
380
381    /// Creates an enabled single-line `InputNodeState` initialized with `value` and caret at the end.
382    ///
383    /// # Arguments
384    ///
385    /// - `S` - Initial input text value.
386    ///
387    /// # Returns
388    ///
389    /// - `Self` - Ready `InputNodeState`.
390    #[must_use]
391    pub fn text<S>(value: S) -> Self
392    where
393        S: Into<String>,
394    {
395        let s: String = value.into();
396        let caret: usize = s.len();
397        Self::new(s, String::new(), caret, false, false, false)
398    }
399
400    /// Sets placeholder text displayed when the input value is empty.
401    ///
402    /// # Arguments
403    ///
404    /// - `Self` - Source input state.
405    /// - `S` - Placeholder text.
406    ///
407    /// # Returns
408    ///
409    /// - `Self` - Updated input state.
410    #[must_use]
411    pub fn with_placeholder<S>(mut self, placeholder: S) -> Self
412    where
413        S: Into<String>,
414    {
415        self.set_placeholder(placeholder.into());
416        self
417    }
418
419    /// Toggles masked password rendering.
420    ///
421    /// # Arguments
422    ///
423    /// - `Self` - Source input state.
424    /// - `bool` - Password mode flag.
425    ///
426    /// # Returns
427    ///
428    /// - `Self` - Updated input state.
429    #[must_use]
430    pub fn with_password(mut self, password: bool) -> Self {
431        self.set_password(password);
432        self
433    }
434
435    /// Toggles multi-line text editing.
436    ///
437    /// # Arguments
438    ///
439    /// - `Self` - Source input state.
440    /// - `bool` - Multiline flag.
441    ///
442    /// # Returns
443    ///
444    /// - `Self` - Updated input state.
445    #[must_use]
446    pub fn with_multiline(mut self, multiline: bool) -> Self {
447        self.set_multiline(multiline);
448        self
449    }
450
451    /// Toggles disabled state preventing user edits.
452    ///
453    /// # Arguments
454    ///
455    /// - `Self` - Source input state.
456    /// - `bool` - Disabled flag.
457    ///
458    /// # Returns
459    ///
460    /// - `Self` - Updated input state.
461    #[must_use]
462    pub fn with_disabled(mut self, disabled: bool) -> Self {
463        self.set_disabled(disabled);
464        self
465    }
466
467    /// Clamps `caret` and `selection_anchor` to valid UTF-8 char boundaries inside `value`.
468    ///
469    /// # Arguments
470    ///
471    /// - `&Self` - Mutable input state.
472    pub fn clamp_caret(&mut self) {
473        let clamped_caret: usize = Self::snap_utf8_boundary(self.get_value(), self.get_caret());
474        self.set_caret(clamped_caret);
475        if let Some(anchor) = self.get_selection_anchor() {
476            let clamped_anchor: usize = Self::snap_utf8_boundary(self.get_value(), anchor);
477            if clamped_anchor == clamped_caret {
478                self.set_selection_anchor(None);
479            } else {
480                self.set_selection_anchor(Some(clamped_anchor));
481            }
482        }
483    }
484
485    /// Returns the clamped UTF-8 byte offset of the caret inside `value`.
486    ///
487    /// # Arguments
488    ///
489    /// - `&Self` - Input state reference.
490    ///
491    /// # Returns
492    ///
493    /// - `usize` - Valid UTF-8 char boundary byte offset in `0..=value.len()`.
494    #[must_use]
495    pub fn clamped_caret_byte(&self) -> usize {
496        Self::snap_utf8_boundary(self.get_value(), self.get_caret())
497    }
498
499    /// Returns the 0-based Unicode scalar character index of the caret inside `value`.
500    ///
501    /// # Arguments
502    ///
503    /// - `&Self` - Input state reference.
504    ///
505    /// # Returns
506    ///
507    /// - `usize` - Caret character index in `0..=value.chars().count()`.
508    #[must_use]
509    pub fn caret_char_index(&self) -> usize {
510        let pos: usize = self.clamped_caret_byte();
511        self.get_value()[..pos].chars().count()
512    }
513
514    /// Returns the sorted `(start_byte, end_byte)` range of the active selection, or `None` when collapsed.
515    ///
516    /// # Arguments
517    ///
518    /// - `&Self` - Input state reference.
519    ///
520    /// # Returns
521    ///
522    /// - `Option<(usize, usize)>` - Sorted valid UTF-8 byte bounds `(start, end)` with `start < end`.
523    #[must_use]
524    pub fn selection_byte_range(&self) -> Option<(usize, usize)> {
525        let anchor_raw: usize = self.get_selection_anchor()?;
526        let anchor: usize = Self::snap_utf8_boundary(self.get_value(), anchor_raw);
527        let caret: usize = self.clamped_caret_byte();
528        if anchor == caret {
529            None
530        } else if anchor < caret {
531            Some((anchor, caret))
532        } else {
533            Some((caret, anchor))
534        }
535    }
536
537    /// Returns the sorted `(start_char, end_char)` Unicode scalar range of the active selection, or `None` when collapsed.
538    ///
539    /// # Arguments
540    ///
541    /// - `&Self` - Input state reference.
542    ///
543    /// # Returns
544    ///
545    /// - `Option<(usize, usize)>` - Sorted character bounds `(start_char, end_char)` with `start_char < end_char`.
546    #[must_use]
547    pub fn selection_char_range(&self) -> Option<(usize, usize)> {
548        let (start_b, end_b): (usize, usize) = self.selection_byte_range()?;
549        let s: &str = self.get_value().as_str();
550        let start_c: usize = s[..start_b].chars().count();
551        let end_c: usize = s[..end_b].chars().count();
552        if start_c < end_c {
553            Some((start_c, end_c))
554        } else {
555            None
556        }
557    }
558
559    /// Returns the currently selected UTF-8 slice (or `None` when empty or password-masked).
560    ///
561    /// # Arguments
562    ///
563    /// - `&Self` - Input state reference.
564    ///
565    /// # Returns
566    ///
567    /// - `Option<&str>` - Selected UTF-8 text slice safe to copy to the clipboard.
568    #[must_use]
569    pub fn selected_text(&self) -> Option<&str> {
570        if self.get_password() {
571            return None;
572        }
573        let (start_b, end_b): (usize, usize) = self.selection_byte_range()?;
574        Some(&self.get_value()[start_b..end_b])
575    }
576
577    /// Returns the slice of `rendered_text` preceding the caret for `DrawCommand::TextCaret` glyph measurement.
578    ///
579    /// # Arguments
580    ///
581    /// - `&Self` - Input state reference.
582    /// - `&'a str` - Displayed text (`value`, or masked `"***"` for password inputs).
583    ///
584    /// # Returns
585    ///
586    /// - `&'a str` - UTF-8 prefix slice ending at the caret position.
587    #[must_use]
588    pub fn caret_prefix_for_display<'a>(&self, rendered_text: &'a str) -> &'a str {
589        if self.get_password() {
590            let chars_before: usize = self.caret_char_index();
591            let byte_end: usize = Self::byte_offset_for_char_index(rendered_text, chars_before);
592            return &rendered_text[..byte_end];
593        }
594        let pos: usize = Self::snap_utf8_boundary(rendered_text, self.get_caret());
595        &rendered_text[..pos]
596    }
597
598    /// Collapses any active selection without moving the caret.
599    ///
600    /// # Arguments
601    ///
602    /// - `&Self` - Mutable input state.
603    ///
604    /// # Returns
605    ///
606    /// - `bool` - `true` if a non-empty selection was cleared.
607    pub fn clear_selection(&mut self) -> bool {
608        let had_selection: bool = self.selection_byte_range().is_some();
609        self.set_selection_anchor(None);
610        had_selection
611    }
612
613    /// Selects the entire input text value and moves the caret to the end.
614    ///
615    /// # Arguments
616    ///
617    /// - `&Self` - Mutable input state.
618    ///
619    /// # Returns
620    ///
621    /// - `bool` - `true` when non-empty text was selected.
622    pub fn select_all(&mut self) -> bool {
623        let len: usize = self.get_value().len();
624        if len == 0 {
625            self.set_caret(0);
626            self.set_selection_anchor(None);
627            return false;
628        }
629        self.set_selection_anchor(Some(0));
630        self.set_caret(len);
631        true
632    }
633
634    /// Deletes the active selection range if present and collapses the caret to its start.
635    ///
636    /// # Arguments
637    ///
638    /// - `&Self` - Mutable input state.
639    ///
640    /// # Returns
641    ///
642    /// - `bool` - `true` when text was deleted.
643    pub fn delete_selection(&mut self) -> bool {
644        if self.get_disabled() {
645            return false;
646        }
647        let Some((start_b, end_b)) = self.selection_byte_range() else {
648            self.set_selection_anchor(None);
649            return false;
650        };
651        self.get_mut_value().replace_range(start_b..end_b, "");
652        self.set_caret(start_b);
653        self.set_selection_anchor(None);
654        true
655    }
656
657    /// Cuts the active selection, returning the copied text (when non-password) and deleting it from `value`.
658    ///
659    /// # Arguments
660    ///
661    /// - `&Self` - Mutable input state.
662    ///
663    /// # Returns
664    ///
665    /// - `Option<String>` - Cut UTF-8 text if a copyable selection was active.
666    pub fn cut_selected(&mut self) -> Option<String> {
667        if self.get_disabled() || self.get_password() {
668            return None;
669        }
670        let cut: String = self.selected_text()?.to_string();
671        let _: bool = self.delete_selection();
672        Some(cut)
673    }
674
675    /// Updates caret to `target_byte`, either extending/starting a selection or collapsing it.
676    ///
677    /// # Arguments
678    ///
679    /// - `&Self` - Mutable input state.
680    /// - `usize` - Destination UTF-8 byte offset.
681    /// - `bool` - When `true`, preserves or initializes `selection_anchor` from the prior caret.
682    fn move_caret_to(&mut self, target_byte: usize, extend_selection: bool) {
683        let cur: usize = self.clamped_caret_byte();
684        let next: usize = Self::snap_utf8_boundary(self.get_value(), target_byte);
685        if extend_selection {
686            let anchor: usize = self
687                .get_selection_anchor()
688                .map(|a: usize| Self::snap_utf8_boundary(self.get_value(), a))
689                .unwrap_or(cur);
690            if anchor == next {
691                self.set_selection_anchor(None);
692            } else {
693                self.set_selection_anchor(Some(anchor));
694            }
695        } else {
696            self.set_selection_anchor(None);
697        }
698        self.set_caret(next);
699    }
700
701    /// Places the caret at a 0-based Unicode scalar character index (used for pointer clicks inside an input).
702    ///
703    /// # Arguments
704    ///
705    /// - `&Self` - Mutable input state.
706    /// - `usize` - Target character index in `0..=value.chars().count()`.
707    /// - `bool` - When `true`, extends the active selection to `char_idx`.
708    pub fn set_caret_char_index(&mut self, char_idx: usize, extend_selection: bool) {
709        let target: usize = Self::byte_offset_for_char_index(self.get_value(), char_idx);
710        self.move_caret_to(target, extend_selection);
711    }
712
713    /// Moves the caret left by one char, one word (`word`), or to line start (`to_line_start`).
714    ///
715    /// # Arguments
716    ///
717    /// - `&Self` - Mutable input state.
718    /// - `bool` - When `true`, jumps to the previous word boundary.
719    /// - `bool` - When `true`, jumps to the start of the current line.
720    /// - `bool` - When `true`, extends the active selection.
721    pub fn move_left(&mut self, word: bool, to_line_start: bool, extend_selection: bool) {
722        if !extend_selection
723            && !word
724            && !to_line_start
725            && let Some((start_b, _)) = self.selection_byte_range()
726        {
727            self.set_caret(start_b);
728            self.set_selection_anchor(None);
729            return;
730        }
731        let cur: usize = self.clamped_caret_byte();
732        let target: usize = if to_line_start {
733            Self::line_start_offset(self.get_value(), cur)
734        } else if word {
735            Self::prev_word_boundary(self.get_value(), cur)
736        } else {
737            Self::prev_char_boundary(self.get_value(), cur)
738        };
739        self.move_caret_to(target, extend_selection);
740    }
741
742    /// Moves the caret right by one char, one word (`word`), or to line end (`to_line_end`).
743    ///
744    /// # Arguments
745    ///
746    /// - `&Self` - Mutable input state.
747    /// - `bool` - When `true`, jumps to the next word boundary.
748    /// - `bool` - When `true`, jumps to the end of the current line.
749    /// - `bool` - When `true`, extends the active selection.
750    pub fn move_right(&mut self, word: bool, to_line_end: bool, extend_selection: bool) {
751        if !extend_selection
752            && !word
753            && !to_line_end
754            && let Some((_, end_b)) = self.selection_byte_range()
755        {
756            self.set_caret(end_b);
757            self.set_selection_anchor(None);
758            return;
759        }
760        let cur: usize = self.clamped_caret_byte();
761        let target: usize = if to_line_end {
762            Self::line_end_offset(self.get_value(), cur)
763        } else if word {
764            Self::next_word_boundary(self.get_value(), cur)
765        } else {
766            Self::next_char_boundary(self.get_value(), cur)
767        };
768        self.move_caret_to(target, extend_selection);
769    }
770
771    /// Moves the caret to the start of the current line, or to the start of the full text when `full_start` is `true`.
772    ///
773    /// # Arguments
774    ///
775    /// - `&Self` - Mutable input state.
776    /// - `bool` - When `true`, jumps to byte `0` across all lines.
777    /// - `bool` - When `true`, extends the active selection.
778    pub fn move_home(&mut self, full_start: bool, extend_selection: bool) {
779        let cur: usize = self.clamped_caret_byte();
780        let target: usize = if full_start {
781            0
782        } else {
783            Self::line_start_offset(self.get_value(), cur)
784        };
785        self.move_caret_to(target, extend_selection);
786    }
787
788    /// Moves the caret to the end of the current line, or to the end of the full text when `full_end` is `true`.
789    ///
790    /// # Arguments
791    ///
792    /// - `&Self` - Mutable input state.
793    /// - `bool` - When `true`, jumps to `value.len()` across all lines.
794    /// - `bool` - When `true`, extends the active selection.
795    pub fn move_end(&mut self, full_end: bool, extend_selection: bool) {
796        let cur: usize = self.clamped_caret_byte();
797        let target: usize = if full_end {
798            self.get_value().len()
799        } else {
800            Self::line_end_offset(self.get_value(), cur)
801        };
802        self.move_caret_to(target, extend_selection);
803    }
804
805    /// Moves the caret up one line (preserving column in multiline inputs) or to start in single-line inputs.
806    ///
807    /// # Arguments
808    ///
809    /// - `&Self` - Mutable input state.
810    /// - `bool` - When `true`, extends the active selection.
811    pub fn move_up(&mut self, extend_selection: bool) {
812        if !self.get_multiline() {
813            self.move_caret_to(0, extend_selection);
814            return;
815        }
816        let s: &str = self.get_value().as_str();
817        let cur: usize = self.clamped_caret_byte();
818        let line_start: usize = Self::line_start_offset(s, cur);
819        if line_start == 0 {
820            self.move_caret_to(0, extend_selection);
821            return;
822        }
823        let col_chars: usize = s[line_start..cur].chars().count();
824        let prev_line_end: usize = line_start - 1;
825        let prev_line_start: usize = Self::line_start_offset(s, prev_line_end);
826        let prev_line: &str = &s[prev_line_start..prev_line_end];
827        let rel: usize = Self::byte_offset_for_char_index(prev_line, col_chars);
828        self.move_caret_to(prev_line_start + rel, extend_selection);
829    }
830
831    /// Moves the caret down one line (preserving column in multiline inputs) or to end in single-line inputs.
832    ///
833    /// # Arguments
834    ///
835    /// - `&Self` - Mutable input state.
836    /// - `bool` - When `true`, extends the active selection.
837    pub fn move_down(&mut self, extend_selection: bool) {
838        if !self.get_multiline() {
839            let end_b: usize = self.get_value().len();
840            self.move_caret_to(end_b, extend_selection);
841            return;
842        }
843        let s: &str = self.get_value().as_str();
844        let cur: usize = self.clamped_caret_byte();
845        let line_start: usize = Self::line_start_offset(s, cur);
846        let line_end: usize = Self::line_end_offset(s, cur);
847        if line_end >= s.len() {
848            self.move_caret_to(s.len(), extend_selection);
849            return;
850        }
851        let col_chars: usize = s[line_start..cur].chars().count();
852        let next_line_start: usize = line_end + 1;
853        let next_line_end: usize = Self::line_end_offset(s, next_line_start);
854        let next_line: &str = &s[next_line_start..next_line_end];
855        let rel: usize = Self::byte_offset_for_char_index(next_line, col_chars);
856        self.move_caret_to(next_line_start + rel, extend_selection);
857    }
858
859    /// Inserts `text` at the current caret position (replacing any active selection) and advances the caret.
860    ///
861    /// # Arguments
862    ///
863    /// - `&Self` - Mutable input state.
864    /// - `&str` - UTF-8 text to insert.
865    pub fn insert_str(&mut self, text: &str) {
866        if self.get_disabled() || text.is_empty() {
867            return;
868        }
869        let _: bool = self.delete_selection();
870        let pos: usize = self.clamped_caret_byte();
871        self.get_mut_value().insert_str(pos, text);
872        self.set_caret(pos + text.len());
873        self.set_selection_anchor(None);
874    }
875
876    /// Removes the active selection or the single Unicode scalar immediately preceding the caret.
877    ///
878    /// # Arguments
879    ///
880    /// - `&Self` - Mutable input state.
881    pub fn backspace(&mut self) {
882        if self.get_disabled() {
883            return;
884        }
885        if self.delete_selection() {
886            return;
887        }
888        let pos: usize = self.clamped_caret_byte();
889        if pos == 0 {
890            return;
891        }
892        let prev_char_start: usize = Self::prev_char_boundary(self.get_value(), pos);
893        self.get_mut_value().replace_range(prev_char_start..pos, "");
894        self.set_caret(prev_char_start);
895        self.set_selection_anchor(None);
896    }
897
898    /// Removes the active selection or the word immediately preceding the caret.
899    ///
900    /// # Arguments
901    ///
902    /// - `&Self` - Mutable input state.
903    pub fn backspace_word(&mut self) {
904        if self.get_disabled() {
905            return;
906        }
907        if self.delete_selection() {
908            return;
909        }
910        let pos: usize = self.clamped_caret_byte();
911        if pos == 0 {
912            return;
913        }
914        let prev_word: usize = Self::prev_word_boundary(self.get_value(), pos);
915        self.get_mut_value().replace_range(prev_word..pos, "");
916        self.set_caret(prev_word);
917        self.set_selection_anchor(None);
918    }
919
920    /// Removes the active selection or the single Unicode scalar immediately following the caret.
921    ///
922    /// # Arguments
923    ///
924    /// - `&Self` - Mutable input state.
925    pub fn delete_forward(&mut self) {
926        if self.get_disabled() {
927            return;
928        }
929        if self.delete_selection() {
930            return;
931        }
932        let pos: usize = self.clamped_caret_byte();
933        if pos >= self.get_value().len() {
934            return;
935        }
936        let next_char_end: usize = Self::next_char_boundary(self.get_value(), pos);
937        self.get_mut_value().replace_range(pos..next_char_end, "");
938        self.set_caret(pos);
939        self.set_selection_anchor(None);
940    }
941
942    /// Removes the active selection or the word immediately following the caret.
943    ///
944    /// # Arguments
945    ///
946    /// - `&Self` - Mutable input state.
947    pub fn delete_word_forward(&mut self) {
948        if self.get_disabled() {
949            return;
950        }
951        if self.delete_selection() {
952            return;
953        }
954        let pos: usize = self.clamped_caret_byte();
955        if pos >= self.get_value().len() {
956            return;
957        }
958        let next_word: usize = Self::next_word_boundary(self.get_value(), pos);
959        self.get_mut_value().replace_range(pos..next_word, "");
960        self.set_caret(pos);
961        self.set_selection_anchor(None);
962    }
963}