cosmic/widget/text_input/
editor.rs

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