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 /// - `ParamValue` - 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<ParamValue>(width: u32, height: u32, pixels: ParamValue) -> Self
45 where
46 ParamValue: 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(text_value: &str, idx: usize) -> usize {
195 let mut pos: usize = idx.min(text_value.len());
196 while pos > 0 && !text_value.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(text_value: &str, pos: usize) -> usize {
228 let safe_pos: usize = Self::snap_utf8_boundary(text_value, pos);
229 text_value[..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(text_value: &str, pos: usize) -> usize {
248 let safe_pos: usize = Self::snap_utf8_boundary(text_value, pos);
249 if safe_pos >= text_value.len() {
250 return text_value.len();
251 }
252 text_value[safe_pos..]
253 .chars()
254 .next()
255 .map(|ch: char| safe_pos + ch.len_utf8())
256 .unwrap_or(text_value.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(text_value: &str, pos: usize) -> usize {
271 let safe_pos: usize = Self::snap_utf8_boundary(text_value, 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 text_value[..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(text_value: &str, pos: usize) -> usize {
305 let safe_pos: usize = Self::snap_utf8_boundary(text_value, pos);
306 let tail: &str = &text_value[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 text_value.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(text_value: &str, pos: usize) -> usize {
337 let safe_pos: usize = Self::snap_utf8_boundary(text_value, pos);
338 text_value[..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(text_value: &str, pos: usize) -> usize {
356 let safe_pos: usize = Self::snap_utf8_boundary(text_value, pos);
357 text_value[safe_pos..]
358 .find('\n')
359 .map(|rel: usize| safe_pos + rel)
360 .unwrap_or(text_value.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(text_value: &str, char_idx: usize) -> usize {
375 text_value
376 .char_indices()
377 .nth(char_idx)
378 .map(|(idx, _): (usize, char)| idx)
379 .unwrap_or(text_value.len())
380 }
381
382 /// Creates an enabled single-line `InputNodeState` initialized with `value` and caret at the end.
383 ///
384 /// # Arguments
385 ///
386 /// - `TextValue` - Initial input text value.
387 ///
388 /// # Returns
389 ///
390 /// - `Self` - Ready `InputNodeState`.
391 #[must_use]
392 pub fn text<TextValue>(value: TextValue) -> Self
393 where
394 TextValue: Into<String>,
395 {
396 let text_value: String = value.into();
397 let caret: usize = text_value.len();
398 Self::new(text_value, String::new(), caret, false, false, false)
399 }
400
401 /// Sets placeholder text displayed when the input value is empty.
402 ///
403 /// # Arguments
404 ///
405 /// - `Self` - Source input state.
406 /// - `TextValue` - Placeholder text.
407 ///
408 /// # Returns
409 ///
410 /// - `Self` - Updated input state.
411 #[must_use]
412 pub fn with_placeholder<TextValue>(mut self, placeholder: TextValue) -> Self
413 where
414 TextValue: Into<String>,
415 {
416 self.set_placeholder(placeholder.into());
417 self
418 }
419
420 /// Toggles masked password rendering.
421 ///
422 /// # Arguments
423 ///
424 /// - `Self` - Source input state.
425 /// - `bool` - Password mode flag.
426 ///
427 /// # Returns
428 ///
429 /// - `Self` - Updated input state.
430 #[must_use]
431 pub fn with_password(mut self, password: bool) -> Self {
432 self.set_password(password);
433 self
434 }
435
436 /// Toggles multi-line text editing.
437 ///
438 /// # Arguments
439 ///
440 /// - `Self` - Source input state.
441 /// - `bool` - Multiline flag.
442 ///
443 /// # Returns
444 ///
445 /// - `Self` - Updated input state.
446 #[must_use]
447 pub fn with_multiline(mut self, multiline: bool) -> Self {
448 self.set_multiline(multiline);
449 self
450 }
451
452 /// Toggles disabled state preventing user edits.
453 ///
454 /// # Arguments
455 ///
456 /// - `Self` - Source input state.
457 /// - `bool` - Disabled flag.
458 ///
459 /// # Returns
460 ///
461 /// - `Self` - Updated input state.
462 #[must_use]
463 pub fn with_disabled(mut self, disabled: bool) -> Self {
464 self.set_disabled(disabled);
465 self
466 }
467
468 /// Clamps `caret` and `selection_anchor` to valid UTF-8 char boundaries inside `value`.
469 ///
470 /// # Arguments
471 ///
472 /// - `&Self` - Mutable input state.
473 pub fn clamp_caret(&mut self) {
474 let clamped_caret: usize = Self::snap_utf8_boundary(self.get_value(), self.get_caret());
475 self.set_caret(clamped_caret);
476 if let Some(anchor) = self.get_selection_anchor() {
477 let clamped_anchor: usize = Self::snap_utf8_boundary(self.get_value(), anchor);
478 if clamped_anchor == clamped_caret {
479 self.set_selection_anchor(None);
480 } else {
481 self.set_selection_anchor(Some(clamped_anchor));
482 }
483 }
484 }
485
486 /// Returns the clamped UTF-8 byte offset of the caret inside `value`.
487 ///
488 /// # Arguments
489 ///
490 /// - `&Self` - Input state reference.
491 ///
492 /// # Returns
493 ///
494 /// - `usize` - Valid UTF-8 char boundary byte offset in `0..=value.len()`.
495 #[must_use]
496 pub fn clamped_caret_byte(&self) -> usize {
497 Self::snap_utf8_boundary(self.get_value(), self.get_caret())
498 }
499
500 /// Returns the 0-based Unicode scalar character index of the caret inside `value`.
501 ///
502 /// # Arguments
503 ///
504 /// - `&Self` - Input state reference.
505 ///
506 /// # Returns
507 ///
508 /// - `usize` - Caret character index in `0..=value.chars().count()`.
509 #[must_use]
510 pub fn caret_char_index(&self) -> usize {
511 let pos: usize = self.clamped_caret_byte();
512 self.get_value()[..pos].chars().count()
513 }
514
515 /// Returns the sorted `(start_byte, end_byte)` range of the active selection, or `None` when collapsed.
516 ///
517 /// # Arguments
518 ///
519 /// - `&Self` - Input state reference.
520 ///
521 /// # Returns
522 ///
523 /// - `Option<(usize, usize)>` - Sorted valid UTF-8 byte bounds `(start, end)` with `start < end`.
524 #[must_use]
525 pub fn selection_byte_range(&self) -> Option<(usize, usize)> {
526 let anchor_raw: usize = self.get_selection_anchor()?;
527 let anchor: usize = Self::snap_utf8_boundary(self.get_value(), anchor_raw);
528 let caret: usize = self.clamped_caret_byte();
529 if anchor == caret {
530 None
531 } else if anchor < caret {
532 Some((anchor, caret))
533 } else {
534 Some((caret, anchor))
535 }
536 }
537
538 /// Returns the sorted `(start_char, end_char)` Unicode scalar range of the active selection, or `None` when collapsed.
539 ///
540 /// # Arguments
541 ///
542 /// - `&Self` - Input state reference.
543 ///
544 /// # Returns
545 ///
546 /// - `Option<(usize, usize)>` - Sorted character bounds `(start_char, end_char)` with `start_char < end_char`.
547 #[must_use]
548 pub fn selection_char_range(&self) -> Option<(usize, usize)> {
549 let (start_b, end_b): (usize, usize) = self.selection_byte_range()?;
550 let text_value: &str = self.get_value().as_str();
551 let start_c: usize = text_value[..start_b].chars().count();
552 let end_c: usize = text_value[..end_b].chars().count();
553 if start_c < end_c {
554 Some((start_c, end_c))
555 } else {
556 None
557 }
558 }
559
560 /// Returns the currently selected UTF-8 slice (or `None` when empty or password-masked).
561 ///
562 /// # Arguments
563 ///
564 /// - `&Self` - Input state reference.
565 ///
566 /// # Returns
567 ///
568 /// - `Option<&str>` - Selected UTF-8 text slice safe to copy to the clipboard.
569 #[must_use]
570 pub fn selected_text(&self) -> Option<&str> {
571 if self.get_password() {
572 return None;
573 }
574 let (start_b, end_b): (usize, usize) = self.selection_byte_range()?;
575 Some(&self.get_value()[start_b..end_b])
576 }
577
578 /// Returns the slice of `rendered_text` preceding the caret for `DrawCommand::TextCaret` glyph measurement.
579 ///
580 /// # Arguments
581 ///
582 /// - `&Self` - Input state reference.
583 /// - `&'a str` - Displayed text (`value`, or masked `"***"` for password inputs).
584 ///
585 /// # Returns
586 ///
587 /// - `&'a str` - UTF-8 prefix slice ending at the caret position.
588 #[must_use]
589 pub fn caret_prefix_for_display<'a>(&self, rendered_text: &'a str) -> &'a str {
590 if self.get_password() {
591 let chars_before: usize = self.caret_char_index();
592 let byte_end: usize = Self::byte_offset_for_char_index(rendered_text, chars_before);
593 return &rendered_text[..byte_end];
594 }
595 let pos: usize = Self::snap_utf8_boundary(rendered_text, self.get_caret());
596 &rendered_text[..pos]
597 }
598
599 /// Collapses any active selection without moving the caret.
600 ///
601 /// # Arguments
602 ///
603 /// - `&Self` - Mutable input state.
604 ///
605 /// # Returns
606 ///
607 /// - `bool` - `true` if a non-empty selection was cleared.
608 pub fn clear_selection(&mut self) -> bool {
609 let had_selection: bool = self.selection_byte_range().is_some();
610 self.set_selection_anchor(None);
611 had_selection
612 }
613
614 /// Selects the entire input text value and moves the caret to the end.
615 ///
616 /// # Arguments
617 ///
618 /// - `&Self` - Mutable input state.
619 ///
620 /// # Returns
621 ///
622 /// - `bool` - `true` when non-empty text was selected.
623 pub fn select_all(&mut self) -> bool {
624 let len: usize = self.get_value().len();
625 if len == 0 {
626 self.set_caret(0);
627 self.set_selection_anchor(None);
628 return false;
629 }
630 self.set_selection_anchor(Some(0));
631 self.set_caret(len);
632 true
633 }
634
635 /// Deletes the active selection range if present and collapses the caret to its start.
636 ///
637 /// # Arguments
638 ///
639 /// - `&Self` - Mutable input state.
640 ///
641 /// # Returns
642 ///
643 /// - `bool` - `true` when text was deleted.
644 pub fn delete_selection(&mut self) -> bool {
645 if self.get_disabled() {
646 return false;
647 }
648 let Some((start_b, end_b)) = self.selection_byte_range() else {
649 self.set_selection_anchor(None);
650 return false;
651 };
652 self.get_mut_value().replace_range(start_b..end_b, "");
653 self.set_caret(start_b);
654 self.set_selection_anchor(None);
655 true
656 }
657
658 /// Cuts the active selection, returning the copied text (when non-password) and deleting it from `value`.
659 ///
660 /// # Arguments
661 ///
662 /// - `&Self` - Mutable input state.
663 ///
664 /// # Returns
665 ///
666 /// - `Option<String>` - Cut UTF-8 text if a copyable selection was active.
667 pub fn cut_selected(&mut self) -> Option<String> {
668 if self.get_disabled() || self.get_password() {
669 return None;
670 }
671 let cut: String = self.selected_text()?.to_string();
672 let _: bool = self.delete_selection();
673 Some(cut)
674 }
675
676 /// Updates caret to `target_byte`, either extending/starting a selection or collapsing it.
677 ///
678 /// # Arguments
679 ///
680 /// - `&Self` - Mutable input state.
681 /// - `usize` - Destination UTF-8 byte offset.
682 /// - `bool` - When `true`, preserves or initializes `selection_anchor` from the prior caret.
683 fn move_caret_to(&mut self, target_byte: usize, extend_selection: bool) {
684 let cur: usize = self.clamped_caret_byte();
685 let next: usize = Self::snap_utf8_boundary(self.get_value(), target_byte);
686 if extend_selection {
687 let anchor: usize = self
688 .get_selection_anchor()
689 .map(|alpha_val: usize| Self::snap_utf8_boundary(self.get_value(), alpha_val))
690 .unwrap_or(cur);
691 if anchor == next {
692 self.set_selection_anchor(None);
693 } else {
694 self.set_selection_anchor(Some(anchor));
695 }
696 } else {
697 self.set_selection_anchor(None);
698 }
699 self.set_caret(next);
700 }
701
702 /// Places the caret at a 0-based Unicode scalar character index (used for pointer clicks inside an input).
703 ///
704 /// # Arguments
705 ///
706 /// - `&Self` - Mutable input state.
707 /// - `usize` - Target character index in `0..=value.chars().count()`.
708 /// - `bool` - When `true`, extends the active selection to `char_idx`.
709 pub fn set_caret_char_index(&mut self, char_idx: usize, extend_selection: bool) {
710 let target: usize = Self::byte_offset_for_char_index(self.get_value(), char_idx);
711 self.move_caret_to(target, extend_selection);
712 }
713
714 /// Moves the caret left by one char, one word (`word`), or to line start (`to_line_start`).
715 ///
716 /// # Arguments
717 ///
718 /// - `&Self` - Mutable input state.
719 /// - `bool` - When `true`, jumps to the previous word boundary.
720 /// - `bool` - When `true`, jumps to the start of the current line.
721 /// - `bool` - When `true`, extends the active selection.
722 pub fn move_left(&mut self, word: bool, to_line_start: bool, extend_selection: bool) {
723 if !extend_selection
724 && !word
725 && !to_line_start
726 && let Some((start_b, _)) = self.selection_byte_range()
727 {
728 self.set_caret(start_b);
729 self.set_selection_anchor(None);
730 return;
731 }
732 let cur: usize = self.clamped_caret_byte();
733 let target: usize = if to_line_start {
734 Self::line_start_offset(self.get_value(), cur)
735 } else if word {
736 Self::prev_word_boundary(self.get_value(), cur)
737 } else {
738 Self::prev_char_boundary(self.get_value(), cur)
739 };
740 self.move_caret_to(target, extend_selection);
741 }
742
743 /// Moves the caret right by one char, one word (`word`), or to line end (`to_line_end`).
744 ///
745 /// # Arguments
746 ///
747 /// - `&Self` - Mutable input state.
748 /// - `bool` - When `true`, jumps to the next word boundary.
749 /// - `bool` - When `true`, jumps to the end of the current line.
750 /// - `bool` - When `true`, extends the active selection.
751 pub fn move_right(&mut self, word: bool, to_line_end: bool, extend_selection: bool) {
752 if !extend_selection
753 && !word
754 && !to_line_end
755 && let Some((_, end_b)) = self.selection_byte_range()
756 {
757 self.set_caret(end_b);
758 self.set_selection_anchor(None);
759 return;
760 }
761 let cur: usize = self.clamped_caret_byte();
762 let target: usize = if to_line_end {
763 Self::line_end_offset(self.get_value(), cur)
764 } else if word {
765 Self::next_word_boundary(self.get_value(), cur)
766 } else {
767 Self::next_char_boundary(self.get_value(), cur)
768 };
769 self.move_caret_to(target, extend_selection);
770 }
771
772 /// Moves the caret to the start of the current line, or to the start of the full text when `full_start` is `true`.
773 ///
774 /// # Arguments
775 ///
776 /// - `&Self` - Mutable input state.
777 /// - `bool` - When `true`, jumps to byte `0` across all lines.
778 /// - `bool` - When `true`, extends the active selection.
779 pub fn move_home(&mut self, full_start: bool, extend_selection: bool) {
780 let cur: usize = self.clamped_caret_byte();
781 let target: usize = if full_start {
782 0
783 } else {
784 Self::line_start_offset(self.get_value(), cur)
785 };
786 self.move_caret_to(target, extend_selection);
787 }
788
789 /// Moves the caret to the end of the current line, or to the end of the full text when `full_end` is `true`.
790 ///
791 /// # Arguments
792 ///
793 /// - `&Self` - Mutable input state.
794 /// - `bool` - When `true`, jumps to `value.len()` across all lines.
795 /// - `bool` - When `true`, extends the active selection.
796 pub fn move_end(&mut self, full_end: bool, extend_selection: bool) {
797 let cur: usize = self.clamped_caret_byte();
798 let target: usize = if full_end {
799 self.get_value().len()
800 } else {
801 Self::line_end_offset(self.get_value(), cur)
802 };
803 self.move_caret_to(target, extend_selection);
804 }
805
806 /// Moves the caret up one line (preserving column in multiline inputs) or to start in single-line inputs.
807 ///
808 /// # Arguments
809 ///
810 /// - `&Self` - Mutable input state.
811 /// - `bool` - When `true`, extends the active selection.
812 pub fn move_up(&mut self, extend_selection: bool) {
813 if !self.get_multiline() {
814 self.move_caret_to(0, extend_selection);
815 return;
816 }
817 let text_value: &str = self.get_value().as_str();
818 let cur: usize = self.clamped_caret_byte();
819 let line_start: usize = Self::line_start_offset(text_value, cur);
820 if line_start == 0 {
821 self.move_caret_to(0, extend_selection);
822 return;
823 }
824 let col_chars: usize = text_value[line_start..cur].chars().count();
825 let prev_line_end: usize = line_start - 1;
826 let prev_line_start: usize = Self::line_start_offset(text_value, prev_line_end);
827 let prev_line: &str = &text_value[prev_line_start..prev_line_end];
828 let rel: usize = Self::byte_offset_for_char_index(prev_line, col_chars);
829 self.move_caret_to(prev_line_start + rel, extend_selection);
830 }
831
832 /// Moves the caret down one line (preserving column in multiline inputs) or to end in single-line inputs.
833 ///
834 /// # Arguments
835 ///
836 /// - `&Self` - Mutable input state.
837 /// - `bool` - When `true`, extends the active selection.
838 pub fn move_down(&mut self, extend_selection: bool) {
839 if !self.get_multiline() {
840 let end_b: usize = self.get_value().len();
841 self.move_caret_to(end_b, extend_selection);
842 return;
843 }
844 let text_value: &str = self.get_value().as_str();
845 let cur: usize = self.clamped_caret_byte();
846 let line_start: usize = Self::line_start_offset(text_value, cur);
847 let line_end: usize = Self::line_end_offset(text_value, cur);
848 if line_end >= text_value.len() {
849 self.move_caret_to(text_value.len(), extend_selection);
850 return;
851 }
852 let col_chars: usize = text_value[line_start..cur].chars().count();
853 let next_line_start: usize = line_end + 1;
854 let next_line_end: usize = Self::line_end_offset(text_value, next_line_start);
855 let next_line: &str = &text_value[next_line_start..next_line_end];
856 let rel: usize = Self::byte_offset_for_char_index(next_line, col_chars);
857 self.move_caret_to(next_line_start + rel, extend_selection);
858 }
859
860 /// Inserts `text` at the current caret position (replacing any active selection) and advances the caret.
861 ///
862 /// # Arguments
863 ///
864 /// - `&Self` - Mutable input state.
865 /// - `&str` - UTF-8 text to insert.
866 pub fn insert_str(&mut self, text: &str) {
867 if self.get_disabled() || text.is_empty() {
868 return;
869 }
870 let _: bool = self.delete_selection();
871 let pos: usize = self.clamped_caret_byte();
872 self.get_mut_value().insert_str(pos, text);
873 self.set_caret(pos + text.len());
874 self.set_selection_anchor(None);
875 }
876
877 /// Removes the active selection or the single Unicode scalar immediately preceding the caret.
878 ///
879 /// # Arguments
880 ///
881 /// - `&Self` - Mutable input state.
882 pub fn backspace(&mut self) {
883 if self.get_disabled() {
884 return;
885 }
886 if self.delete_selection() {
887 return;
888 }
889 let pos: usize = self.clamped_caret_byte();
890 if pos == 0 {
891 return;
892 }
893 let prev_char_start: usize = Self::prev_char_boundary(self.get_value(), pos);
894 self.get_mut_value().replace_range(prev_char_start..pos, "");
895 self.set_caret(prev_char_start);
896 self.set_selection_anchor(None);
897 }
898
899 /// Removes the active selection or the word immediately preceding the caret.
900 ///
901 /// # Arguments
902 ///
903 /// - `&Self` - Mutable input state.
904 pub fn backspace_word(&mut self) {
905 if self.get_disabled() {
906 return;
907 }
908 if self.delete_selection() {
909 return;
910 }
911 let pos: usize = self.clamped_caret_byte();
912 if pos == 0 {
913 return;
914 }
915 let prev_word: usize = Self::prev_word_boundary(self.get_value(), pos);
916 self.get_mut_value().replace_range(prev_word..pos, "");
917 self.set_caret(prev_word);
918 self.set_selection_anchor(None);
919 }
920
921 /// Removes the active selection or the single Unicode scalar immediately following the caret.
922 ///
923 /// # Arguments
924 ///
925 /// - `&Self` - Mutable input state.
926 pub fn delete_forward(&mut self) {
927 if self.get_disabled() {
928 return;
929 }
930 if self.delete_selection() {
931 return;
932 }
933 let pos: usize = self.clamped_caret_byte();
934 if pos >= self.get_value().len() {
935 return;
936 }
937 let next_char_end: usize = Self::next_char_boundary(self.get_value(), pos);
938 self.get_mut_value().replace_range(pos..next_char_end, "");
939 self.set_caret(pos);
940 self.set_selection_anchor(None);
941 }
942
943 /// Removes the active selection or the word immediately following the caret.
944 ///
945 /// # Arguments
946 ///
947 /// - `&Self` - Mutable input state.
948 pub fn delete_word_forward(&mut self) {
949 if self.get_disabled() {
950 return;
951 }
952 if self.delete_selection() {
953 return;
954 }
955 let pos: usize = self.clamped_caret_byte();
956 if pos >= self.get_value().len() {
957 return;
958 }
959 let next_word: usize = Self::next_word_boundary(self.get_value(), pos);
960 self.get_mut_value().replace_range(pos..next_word, "");
961 self.set_caret(pos);
962 self.set_selection_anchor(None);
963 }
964}