1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
use std::{borrow::Cow, fmt::Display, ops::Range};

use freya_elements::events::keyboard::{Code, Key, Modifiers};
pub use ropey::Rope;

/// Holds the position of a cursor in a text
#[derive(Clone, Default, PartialEq, Debug)]
pub struct TextCursor {
    col: usize,
    row: usize,
}

impl TextCursor {
    /// Construct a new [TextCursor] given a row and a column
    pub fn new(row: usize, col: usize) -> Self {
        Self { col, row }
    }

    /// Move the cursor to a new row and column
    pub fn move_to(&mut self, row: usize, col: usize) {
        self.col = col;
        self.row = row;
    }

    /// Get the current column
    pub fn col(&self) -> usize {
        self.col
    }

    /// Get the current row
    pub fn row(&self) -> usize {
        self.row
    }

    /// Set a new column
    pub fn set_col(&mut self, col: usize) {
        self.col = col;
    }

    /// Set a new row
    pub fn set_row(&mut self, row: usize) {
        self.row = row;
    }

    pub fn as_tuple(&self) -> (usize, usize) {
        (self.row, self.col)
    }
}

/// A text line from a [TextEditor]
#[derive(Clone)]
pub struct Line<'a> {
    pub text: Cow<'a, str>,
}

impl Line<'_> {
    /// Get the length of the line
    pub fn len_chars(&self) -> usize {
        self.text.chars().filter(|c| c != &'\r').count()
    }

    /// Get the text of the line
    fn as_str(&self) -> &str {
        &self.text
    }
}

impl Display for Line<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.text)
    }
}

/// Events for [TextEditor]
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum TextEvent {
    /// Cursor position has been moved
    CursorChanged,
    /// Text has changed
    TextChanged,
    /// Nothing happened
    None,
}

/// Common trait for editable texts
pub trait TextEditor: Sized + Clone + Display {
    type LinesIterator<'a>: Iterator<Item = Line<'a>>
    where
        Self: 'a;

    fn set(&mut self, text: &str);

    /// Iterator over all the lines in the text.
    fn lines(&self) -> Self::LinesIterator<'_>;

    /// Insert a character in the text in the given position.
    fn insert_char(&mut self, char: char, char_idx: usize);

    /// Insert a string in the text in the given position.
    fn insert(&mut self, text: &str, char_idx: usize);

    /// Remove a part of the text.
    fn remove(&mut self, range: Range<usize>);

    /// Get line from the given char
    fn char_to_line(&self, char_idx: usize) -> usize;

    /// Get the first char from the given line
    fn line_to_char(&self, line_idx: usize) -> usize;

    /// Get a line from the text
    fn line(&self, line_idx: usize) -> Option<Line<'_>>;

    /// Total of lines
    fn len_lines(&self) -> usize;

    /// Get a readable cursor
    fn cursor(&self) -> &TextCursor;

    /// Get a mutable cursor
    fn cursor_mut(&mut self) -> &mut TextCursor;

    /// Get the cursor row
    fn cursor_row(&self) -> usize {
        self.cursor().row()
    }

    /// Get the cursor column
    fn cursor_col(&self) -> usize {
        self.cursor().col()
    }

    /// Move the cursor 1 line down
    fn cursor_down(&mut self) {
        let new_row = self.cursor_row() + 1;
        self.cursor_mut().set_row(new_row);
    }

    /// Move the cursor 1 line up
    fn cursor_up(&mut self) {
        let new_row = self.cursor_row() - 1;
        self.cursor_mut().set_row(new_row);
    }

    /// Move the cursor 1 char to the right
    fn cursor_right(&mut self) {
        let new_col = self.cursor_col() + 1;
        self.cursor_mut().set_col(new_col);
    }

    /// Move the cursor 1 char to the left
    fn cursor_left(&mut self) {
        let new_col = self.cursor_col() - 1;
        self.cursor_mut().set_col(new_col);
    }

    /// Get the cursor position
    fn cursor_pos(&self) -> usize {
        let line_begining = self.line_to_char(self.cursor_row());
        line_begining + self.cursor_col()
    }

    /// Set the cursor position
    fn set_cursor_pos(&mut self, pos: usize) {
        let row = self.char_to_line(pos);
        let row_idx = self.line_to_char(row);
        let col = pos - row_idx;
        self.cursor_mut().move_to(row, col)
    }

    // Return the highlighted text from a given editor Id
    fn highlights(&self, editor_id: usize) -> Option<(usize, usize)>;

    // Cancel highlight
    fn unhighlight(&mut self);

    // Highlight some text
    fn highlight_text(&mut self, from: usize, to: usize, editor_id: usize);

    fn move_highlight_to_cursor(&mut self);

    // Process a Keyboard event
    fn process_key(&mut self, key: &Key, code: &Code, modifiers: &Modifiers) -> TextEvent {
        let mut event = TextEvent::None;
        let mut unhighlight = true;

        match key {
            Key::Shift => {
                unhighlight = false;
            }
            Key::Escape => {
                unhighlight = true;
            }
            Key::ArrowDown => {
                if modifiers.contains(Modifiers::SHIFT) {
                    unhighlight = false;
                    self.move_highlight_to_cursor();
                }

                let total_lines = self.len_lines() - 1;
                // Go one line down
                if self.cursor_row() < total_lines {
                    let next_line = self.line(self.cursor_row() + 1).unwrap();

                    // Try to use the current cursor column, otherwise use the new line length
                    let cursor_col = if self.cursor_col() <= next_line.len_chars() {
                        self.cursor_col()
                    } else {
                        next_line.len_chars().max(1) - 1
                    };

                    self.cursor_mut().set_col(cursor_col);
                    self.cursor_down();

                    event = TextEvent::CursorChanged
                }

                if modifiers.contains(Modifiers::SHIFT) {
                    self.move_highlight_to_cursor();
                }
            }
            Key::ArrowLeft => {
                if modifiers.contains(Modifiers::SHIFT) {
                    unhighlight = false;
                    self.move_highlight_to_cursor();
                }

                // Go one character to the left
                if self.cursor_col() > 0 {
                    self.cursor_left();

                    event = TextEvent::CursorChanged
                } else if self.cursor_row() > 0 {
                    // Go one line up if there is no more characters on the left
                    let prev_line = self.line(self.cursor_row() - 1);
                    if let Some(prev_line) = prev_line {
                        // Use the prev line length as new cursor column, otherwise just set it to 0
                        let cursor_col = if prev_line.len_chars() > 0 {
                            prev_line.len_chars() - 1
                        } else {
                            0
                        };

                        self.cursor_up();
                        self.cursor_mut().set_col(cursor_col);

                        event = TextEvent::CursorChanged
                    }
                }

                if modifiers.contains(Modifiers::SHIFT) {
                    self.move_highlight_to_cursor();
                }
            }
            Key::ArrowRight => {
                if modifiers.contains(Modifiers::SHIFT) {
                    unhighlight = false;
                    self.move_highlight_to_cursor();
                }

                let total_lines = self.len_lines() - 1;
                let current_line = self.line(self.cursor_row()).unwrap();

                // Go one line down if there isn't more characters on the right
                if self.cursor_row() < total_lines
                    && self.cursor_col() == current_line.len_chars().max(1) - 1
                {
                    self.cursor_down();
                    self.cursor_mut().set_col(0);

                    event = TextEvent::CursorChanged
                } else if self.cursor_col() < current_line.len_chars() {
                    // Go one character to the right if possible
                    self.cursor_right();

                    event = TextEvent::CursorChanged
                }

                if modifiers.contains(Modifiers::SHIFT) {
                    self.move_highlight_to_cursor();
                }
            }
            Key::ArrowUp => {
                if modifiers.contains(Modifiers::SHIFT) {
                    unhighlight = false;
                    self.move_highlight_to_cursor();
                }

                // Go one line up if there is any
                if self.cursor_row() > 0 {
                    let prev_line = self.line(self.cursor_row() - 1).unwrap();

                    // Try to use the current cursor column, otherwise use the prev line length
                    let cursor_col = if self.cursor_col() <= prev_line.len_chars() {
                        self.cursor_col()
                    } else {
                        prev_line.len_chars().max(1) - 1
                    };

                    self.cursor_up();
                    self.cursor_mut().set_col(cursor_col);

                    event = TextEvent::CursorChanged
                }

                if modifiers.contains(Modifiers::SHIFT) {
                    self.move_highlight_to_cursor();
                }
            }
            Key::Backspace => {
                if self.cursor_col() > 0 {
                    // Remove the character to the left if there is any
                    let char_idx = self.line_to_char(self.cursor_row()) + self.cursor_col();
                    self.remove(char_idx - 1..char_idx);

                    self.cursor_left();

                    event = TextEvent::TextChanged
                } else if self.cursor_row() > 0 {
                    // Moves the whole current line to the end of the line above.
                    let prev_line_len = self.line(self.cursor_row() - 1).unwrap().len_chars();
                    let current_line = self.line(self.cursor_row()).clone();

                    if let Some(current_line) = current_line {
                        let current_line_len = current_line.len_chars();
                        let prev_char_idx =
                            self.line_to_char(self.cursor_row() - 1) + prev_line_len - 1;
                        let char_idx = self.line_to_char(self.cursor_row()) + current_line_len - 1;

                        let line = current_line.as_str().to_string();
                        self.insert(&line, prev_char_idx);
                        self.remove(char_idx..(char_idx + current_line_len) + 1);
                    }

                    self.cursor_up();
                    self.cursor_mut().set_col(prev_line_len - 1);

                    event = TextEvent::TextChanged
                }
            }
            Key::Enter => {
                // Breaks the line
                let char_idx = self.line_to_char(self.cursor_row()) + self.cursor_col();
                self.insert_char('\n', char_idx);
                self.cursor_down();
                self.cursor_mut().set_col(0);

                event = TextEvent::TextChanged
            }
            Key::Character(character) => {
                match code {
                    Code::Delete => {}
                    Code::Space => {
                        // Simply adds an space
                        let char_idx = self.line_to_char(self.cursor_row()) + self.cursor_col();
                        self.insert_char(' ', char_idx);
                        self.cursor_right();

                        event = TextEvent::TextChanged
                    }
                    _ => {
                        if let Ok(ch) = character.parse::<char>() {
                            if !ch.is_ascii_control() {
                                // Adds a new character
                                let char_idx =
                                    self.line_to_char(self.cursor_row()) + self.cursor_col();
                                self.insert(character, char_idx);
                                self.cursor_right();

                                event = TextEvent::TextChanged
                            }
                        }
                    }
                }
            }
            _ => {}
        }

        if unhighlight {
            self.unhighlight();
        }

        event
    }
}