Skip to main content

cosmic/widget/text_input/
value.rs

1// Copyright 2019 H�ctor Ram�n, Iced contributors
2// Copyright 2023 System76 <info@system76.com>
3// SPDX-License-Identifier: MIT
4
5use unicode_segmentation::UnicodeSegmentation;
6
7/// The value of a [`TextInput`].
8///
9/// [`TextInput`]: crate::widget::TextInput
10// TODO: Reduce allocations, cache results (?)
11#[derive(Default, Debug, Clone, PartialEq)]
12pub struct Value {
13    graphemes: Vec<String>,
14}
15
16impl Value {
17    /// Creates a new [`Value`] from a string slice.
18    pub fn new(string: &str) -> Self {
19        let graphemes = UnicodeSegmentation::graphemes(string, true)
20            .map(String::from)
21            .collect();
22
23        Self { graphemes }
24    }
25
26    /// Returns whether the [`Value`] is empty or not.
27    ///
28    /// A [`Value`] is empty when it contains no graphemes.
29    #[must_use]
30    #[inline]
31    pub fn is_empty(&self) -> bool {
32        self.len() == 0
33    }
34
35    /// Returns the total amount of graphemes in the [`Value`].
36    #[must_use]
37    #[inline]
38    pub fn len(&self) -> usize {
39        self.graphemes.len()
40    }
41
42    /// Returns the position of the previous start of a word from the given
43    /// grapheme `index`.
44    #[must_use]
45    pub fn previous_start_of_word(&self, index: usize) -> usize {
46        let previous_string = &self.graphemes[..index.min(self.graphemes.len())].concat();
47
48        UnicodeSegmentation::split_word_bound_indices(previous_string as &str)
49            .rfind(|(_, word)| !word.trim_start().is_empty())
50            .map_or(0, |(i, previous_word)| {
51                index
52                    - UnicodeSegmentation::graphemes(previous_word, true).count()
53                    - UnicodeSegmentation::graphemes(
54                        &previous_string[i + previous_word.len()..] as &str,
55                        true,
56                    )
57                    .count()
58            })
59    }
60
61    /// Returns the position of the next end of a word from the given grapheme
62    /// `index`.
63    #[must_use]
64    pub fn next_end_of_word(&self, index: usize) -> usize {
65        let next_string = &self.graphemes[index..].concat();
66
67        UnicodeSegmentation::split_word_bound_indices(next_string as &str)
68            .find(|(_, word)| !word.trim_start().is_empty())
69            .map_or(self.len(), |(i, next_word)| {
70                index
71                    + UnicodeSegmentation::graphemes(next_word, true).count()
72                    + UnicodeSegmentation::graphemes(&next_string[..i] as &str, true).count()
73            })
74    }
75
76    /// Returns a new [`Value`] containing the graphemes from `start` until the
77    /// given `end`.
78    #[must_use]
79    #[inline]
80    pub fn select(&self, start: usize, end: usize) -> Self {
81        let graphemes = self.graphemes[start.min(self.len())..end.min(self.len())].to_vec();
82
83        Self { graphemes }
84    }
85
86    /// Returns a new [`Value`] containing the graphemes until the given
87    /// `index`.
88    #[must_use]
89    #[inline]
90    pub fn until(&self, index: usize) -> Self {
91        let graphemes = self.graphemes[..index.min(self.len())].to_vec();
92
93        Self { graphemes }
94    }
95
96    /// Inserts a new `char` at the given grapheme `index`.
97    #[inline]
98    pub fn insert(&mut self, index: usize, c: char) {
99        self.graphemes.insert(index, c.to_string());
100
101        self.graphemes = UnicodeSegmentation::graphemes(&self.to_string() as &str, true)
102            .map(String::from)
103            .collect();
104    }
105
106    /// Inserts a bunch of graphemes at the given grapheme `index`.
107    #[inline]
108    pub fn insert_many(&mut self, index: usize, mut value: Value) {
109        let _ = self
110            .graphemes
111            .splice(index..index, value.graphemes.drain(..));
112    }
113
114    /// Removes the grapheme at the given `index`.
115    #[inline]
116    pub fn remove(&mut self, index: usize) {
117        let _ = self.graphemes.remove(index);
118    }
119
120    /// Removes the graphemes from `start` to `end`.
121    #[inline]
122    pub fn remove_many(&mut self, start: usize, end: usize) {
123        let _ = self.graphemes.splice(start..end, std::iter::empty());
124    }
125
126    /// Returns a new [`Value`] with all its graphemes replaced with the
127    /// dot ('•') character.
128    #[must_use]
129    pub fn secure(&self) -> Self {
130        Self {
131            graphemes: std::iter::repeat_n(String::from("•"), self.graphemes.len()).collect(),
132        }
133    }
134
135    /// Converts a grapheme index to a byte index in the underlying string.
136    #[must_use]
137    pub fn byte_index_at_grapheme(&self, grapheme_index: usize) -> usize {
138        self.graphemes[..grapheme_index.min(self.graphemes.len())]
139            .iter()
140            .map(|g| g.len())
141            .sum()
142    }
143
144    /// Returns the grapheme index of the last occurrence of the given character,
145    /// searching from the end.
146    #[must_use]
147    pub fn rfind_char(&self, ch: char) -> Option<usize> {
148        let needle = ch.to_string();
149        self.graphemes.iter().rposition(|g| g == &needle)
150    }
151
152    /// Converts a byte index to a grapheme index.
153    #[must_use]
154    pub fn grapheme_index_at_byte(&self, byte_index: usize) -> usize {
155        let mut bytes = 0;
156        for (i, g) in self.graphemes.iter().enumerate() {
157            if bytes >= byte_index {
158                return i;
159            }
160            bytes += g.len();
161        }
162
163        self.graphemes.len()
164    }
165}
166
167impl std::fmt::Display for Value {
168    #[inline]
169    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
170        f.write_str(&self.graphemes.concat())
171    }
172}