cosmic/widget/text_input/
editor.rs1use super::cursor::Cursor;
6use super::value::Value;
7
8pub struct Editor<'a> {
9 value: &'a mut Value,
10 cursor: &'a mut Cursor,
11}
12
13impl<'a> Editor<'a> {
14 #[inline]
15 pub fn new(value: &'a mut Value, cursor: &'a mut Cursor) -> Editor<'a> {
16 Editor { value, cursor }
17 }
18
19 #[must_use]
20 #[inline]
21 pub fn contents(&self) -> String {
22 self.value.to_string()
23 }
24
25 pub fn insert(&mut self, character: char) {
26 if let Some((left, right)) = self.cursor.selection(self.value) {
27 self.cursor.move_left(self.value);
28 self.value.remove_many(left, right);
29 }
30
31 self.value.insert(self.cursor.end(self.value), character);
32 self.cursor.move_right(self.value);
33 }
34
35 pub fn paste(&mut self, content: Value) {
36 let length = content.len();
37 if let Some((left, right)) = self.cursor.selection(self.value) {
38 self.cursor.move_left(self.value);
39 self.value.remove_many(left, right);
40 }
41
42 self.value.insert_many(self.cursor.end(self.value), content);
43
44 self.cursor.move_right_by_amount(self.value, length);
45 }
46
47 pub fn backspace(&mut self) {
48 if let Some((start, end)) = self.cursor.selection(self.value) {
49 self.cursor.move_left(self.value);
50 self.value.remove_many(start, end);
51 } else {
52 let start = self.cursor.start(self.value);
53
54 if start > 0 {
55 self.cursor.move_left(self.value);
56 self.value.remove(start - 1);
57 }
58 }
59 }
60
61 pub fn delete(&mut self) {
62 if self.cursor.selection(self.value).is_some() {
63 self.backspace();
64 } else {
65 let end = self.cursor.end(self.value);
66
67 if end < self.value.len() {
68 self.value.remove(end);
69 }
70 }
71 }
72}