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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
use std::{borrow::Cow, cmp::Ordering, fmt::Display, ops::Range};

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

/// 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)
    }
}

bitflags::bitflags! {
    /// Events for [TextEditor]
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
    pub struct TextEvent: u8 {
         /// Cursor position has been moved
        const CURSOR_CHANGED = 0x01;
        /// Text has changed
        const TEXT_CHANGED = 0x02;
        /// Selected text has changed
        const SELECTION_CHANGED = 0x04;
    }
}

/// 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)
    }

    // Check if has any highlight at all
    fn has_any_highlight(&self) -> bool;

    // 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 = if self.has_any_highlight() {
            TextEvent::SELECTION_CHANGED
        } else {
            TextEvent::empty()
        };

        match key {
            Key::Shift => {
                event.remove(TextEvent::SELECTION_CHANGED);
            }
            Key::Control => {
                event.remove(TextEvent::SELECTION_CHANGED);
            }
            Key::Alt => {
                event.remove(TextEvent::SELECTION_CHANGED);
            }
            Key::Escape => {
                event.insert(TextEvent::SELECTION_CHANGED);
            }
            Key::ArrowDown => {
                if modifiers.contains(Modifiers::SHIFT) {
                    event.remove(TextEvent::SELECTION_CHANGED);
                    self.move_highlight_to_cursor();
                }

                let last_line = self.len_lines() - 1;

                // Go one line down
                match self.cursor_row().cmp(&last_line) {
                    Ordering::Equal => {
                        // Move the cursor to the end of the line
                        let current_line = self.line(self.cursor_row()).unwrap();
                        let last_char = current_line.len_chars();
                        self.cursor_mut().set_col(last_char);
                        event.insert(TextEvent::CURSOR_CHANGED);
                    }
                    Ordering::Less => {
                        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.insert(TextEvent::CURSOR_CHANGED);
                    }
                    _ => {}
                }

                if modifiers.contains(Modifiers::SHIFT) {
                    self.move_highlight_to_cursor();
                }
            }
            Key::ArrowLeft => {
                if modifiers.contains(Modifiers::SHIFT) {
                    event.remove(TextEvent::SELECTION_CHANGED);
                    self.move_highlight_to_cursor();
                }

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

                    event.insert(TextEvent::CURSOR_CHANGED);
                } 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.insert(TextEvent::CURSOR_CHANGED);
                    }
                }

                if modifiers.contains(Modifiers::SHIFT) {
                    self.move_highlight_to_cursor();
                }
            }
            Key::ArrowRight => {
                if modifiers.contains(Modifiers::SHIFT) {
                    event.remove(TextEvent::SELECTION_CHANGED);
                    self.move_highlight_to_cursor();
                }

                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() < self.len_lines() - 1
                    && self.cursor_col() == current_line.len_chars().max(1) - 1
                {
                    self.cursor_down();
                    self.cursor_mut().set_col(0);

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

                    event.insert(TextEvent::CURSOR_CHANGED);
                }

                if modifiers.contains(Modifiers::SHIFT) {
                    self.move_highlight_to_cursor();
                }
            }
            Key::ArrowUp => {
                if modifiers.contains(Modifiers::SHIFT) {
                    event.remove(TextEvent::SELECTION_CHANGED);
                    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.insert(TextEvent::CURSOR_CHANGED);
                } else if self.cursor_col() > 0 {
                    // Move the cursor to the begining of the line
                    self.cursor_mut().set_col(0);
                    event.insert(TextEvent::CURSOR_CHANGED);
                }

                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.insert(TextEvent::TEXT_CHANGED);
                } 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.insert(TextEvent::TEXT_CHANGED);
                }
            }
            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.insert(TextEvent::TEXT_CHANGED);
            }
            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.insert(TextEvent::TEXT_CHANGED);
                    }
                    _ => {
                        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.insert(TextEvent::TEXT_CHANGED);
                            }
                        }
                    }
                }
            }
            _ => {}
        }

        if event.contains(TextEvent::SELECTION_CHANGED) {
            self.unhighlight();
        }

        event
    }
}