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
#![allow(unused)]
pub use crate::Selection;
use crate::{Options, SelectionMode, TextBuffer, TextEdit};
use nalgebra::Point2;
use std::marker::PhantomData;
use std::sync::Arc;
pub use ultron_syntaxes_themes::{Style, TextHighlighter};

/// An editor with core functionality platform specific UI
#[derive(Default)]
pub struct Editor<XMSG> {
    options: Options,
    pub text_edit: TextEdit,
    /// Other components can listen to the an event.
    /// When the content of the text editor changes, the change listener will be emitted
    #[cfg(feature = "callback")]
    change_listeners: Vec<Callback<String, XMSG>>,
    /// a cheaper listener which doesn't need to assemble the text content
    /// of the text editor everytime
    #[cfg(feature = "callback")]
    change_notify_listeners: Vec<Callback<(), XMSG>>,
    _phantom: PhantomData<XMSG>,
}

#[derive(Debug)]
pub enum Command {
    IndentForward,
    IndentBackward,
    BreakLine,
    DeleteBack,
    DeleteForward,
    MoveUp,
    MoveDown,
    MoveLeft,
    MoveLeftStart,
    MoveRight,
    MoveRightEnd,
    InsertChar(char),
    ReplaceChar(char),
    InsertText(String),
    PasteTextBlock(String),
    MergeText(String),
    /// set a new content to the editor, resetting to a new history for undo/redo
    SetContent(String),
    Undo,
    Redo,
    BumpHistory,
    SetSelection(Point2<i32>, Point2<i32>),
    SelectAll,
    ClearSelection,
    SetPosition(Point2<i32>),
}

pub struct Callback<IN, OUT> {
    func: Arc<dyn Fn(IN) -> OUT>,
}

impl<IN, F, OUT> From<F> for Callback<IN, OUT>
where
    F: Fn(IN) -> OUT + 'static,
{
    fn from(func: F) -> Self {
        Self {
            func: Arc::new(func),
        }
    }
}

impl<IN, OUT> Callback<IN, OUT> {
    /// This method calls the actual callback.
    pub fn emit(&self, input: IN) -> OUT {
        (self.func)(input)
    }
}

impl<XMSG> Editor<XMSG> {
    pub fn from_str(options: Options, content: &str) -> Self {
        let text_edit = TextEdit::from_str(content);

        Editor {
            options,
            text_edit,
            #[cfg(feature = "callback")]
            change_listeners: vec![],
            #[cfg(feature = "callback")]
            change_notify_listeners: vec![],
            _phantom: PhantomData,
        }
    }

    pub fn text_buffer(&self) -> &TextBuffer {
        self.text_edit.text_buffer()
    }

    pub fn set_selection(&mut self, start: Point2<i32>, end: Point2<i32>) {
        self.text_edit.set_selection(start, end);
    }

    pub fn selection(&self) -> &Selection {
        self.text_edit.selection()
    }

    pub fn selected_text(&self) -> Option<String> {
        match self.options.selection_mode {
            SelectionMode::Linear => self.text_edit.selected_text_in_linear_mode(),
            SelectionMode::Block => self.text_edit.selected_text_in_block_mode(),
        }
    }

    pub fn cut_selected_text(&mut self) -> Option<String> {
        match self.options.selection_mode {
            SelectionMode::Linear => self.text_edit.cut_selected_text_in_linear_mode(),
            SelectionMode::Block => self.text_edit.cut_selected_text_in_block_mode(),
        }
    }

    pub fn is_selected(&self, loc: Point2<i32>) -> bool {
        match self.options.selection_mode {
            SelectionMode::Linear => self.text_edit.is_selected_in_linear_mode(loc),
            SelectionMode::Block => self.text_edit.is_selected_in_block_mode(loc),
        }
    }

    pub fn clear_selection(&mut self) {
        self.text_edit.clear_selection()
    }

    pub fn set_selection_start(&mut self, start: Point2<i32>) {
        self.text_edit.set_selection_start(start);
    }

    pub fn set_selection_end(&mut self, end: Point2<i32>) {
        self.text_edit.set_selection_end(end);
    }

    pub fn get_char(&self, loc: Point2<usize>) -> Option<char> {
        self.text_edit.get_char(loc)
    }

    pub fn get_position(&self) -> Point2<usize> {
        self.text_edit.get_position()
    }

    pub fn get_content(&self) -> String {
        self.text_edit.get_content()
    }

    pub fn total_lines(&self) -> usize {
        self.text_edit.total_lines()
    }
}

impl<XMSG> Editor<XMSG> {
    pub fn process_commands(&mut self, commands: impl IntoIterator<Item = Command>) -> Vec<XMSG> {
        let results: Vec<bool> = commands
            .into_iter()
            .map(|command| self.process_command(command))
            .collect();

        #[cfg(feature = "callback")]
        if results.into_iter().any(|v| v) {
            self.emit_on_change_listeners()
        } else {
            vec![]
        }
        #[cfg(not(feature = "callback"))]
        vec![]
    }

    /// TODO: convert this into process_commands
    /// where each command marks whether the content has changed or not
    /// then once all of the commands have been executed,
    /// the emit and rehighlight will commence
    ///
    /// TODO option2: have a boolean flag, for each of the command to determine
    /// if the editor content changed or not
    ///
    pub fn process_command(&mut self, command: Command) -> bool {
        match command {
            Command::IndentForward => {
                let indent = "    ";
                self.text_edit.command_insert_text(indent);
                true
            }
            Command::IndentBackward => true,
            Command::BreakLine => {
                self.text_edit.command_break_line();
                true
            }
            Command::DeleteBack => {
                self.text_edit.command_delete_back();
                true
            }
            Command::DeleteForward => {
                self.text_edit.command_delete_forward();
                true
            }
            Command::MoveUp => {
                self.command_move_up();
                false
            }
            Command::MoveDown => {
                self.command_move_down();
                false
            }
            Command::PasteTextBlock(text) => {
                self.text_edit.paste_text_in_block_mode(text);
                true
            }
            Command::MergeText(text) => {
                self.text_edit.command_merge_text(text);
                true
            }
            Command::MoveLeft => {
                self.text_edit.command_move_left();
                false
            }
            Command::MoveLeftStart => {
                self.text_edit.command_move_left_start();
                false
            }
            Command::MoveRightEnd => {
                self.text_edit.command_move_right_end();
                false
            }
            Command::MoveRight => {
                self.command_move_right();
                false
            }
            Command::InsertChar(c) => {
                self.text_edit.command_insert_char(c);
                true
            }
            Command::ReplaceChar(c) => {
                self.text_edit.command_replace_char(c);
                true
            }
            Command::InsertText(text) => {
                self.text_edit.command_insert_text(&text);
                true
            }
            Command::SetContent(content) => {
                self.text_edit = TextEdit::from_str(&content);
                true
            }
            Command::Undo => {
                self.text_edit.command_undo();
                true
            }
            Command::Redo => {
                self.text_edit.command_redo();
                true
            }
            Command::BumpHistory => {
                self.text_edit.bump_history();
                false
            }
            Command::SetSelection(start, end) => {
                self.text_edit.command_set_selection(start, end);
                false
            }
            Command::SelectAll => {
                self.text_edit.command_select_all();
                false
            }
            Command::ClearSelection => {
                self.text_edit.clear_selection();
                false
            }
            Command::SetPosition(pos) => {
                self.command_set_position(pos);
                false
            }
        }
    }

    fn command_move_up(&mut self) {
        if self.options.use_virtual_edit {
            self.text_edit.command_move_up();
        } else {
            self.text_edit.command_move_up_clamped();
        }
    }

    fn command_move_down(&mut self) {
        if self.options.use_virtual_edit {
            self.text_edit.command_move_down();
        } else {
            self.text_edit.command_move_down_clamped();
        }
    }

    fn command_move_left(&mut self) {
        self.text_edit.command_move_left();
    }

    fn command_move_right(&mut self) {
        if self.options.use_virtual_edit {
            self.text_edit.command_move_right();
        } else {
            self.text_edit.command_move_right_clamped();
        }
    }

    fn command_set_position(&mut self, loc: Point2<i32>) {
        let cursor = Point2::new(loc.x as usize, loc.y as usize);
        if self.options.use_virtual_edit {
            self.text_edit.command_set_position(cursor);
        } else {
            self.text_edit.command_set_position_clamped(cursor);
        }
    }

    pub fn clear(&mut self) {
        self.text_edit.clear();
    }

    /// Attach a callback to this editor where it is invoked when the content is changed.
    ///
    /// Note:The content is extracted into string and used as a parameter to the function.
    /// This may be a costly operation when the editor has lot of text on it.
    #[cfg(feature = "callback")]
    pub fn on_change<F>(mut self, f: F) -> Self
    where
        F: Fn(String) -> XMSG + 'static,
    {
        let cb = Callback::from(f);
        self.change_listeners.push(cb);
        self
    }

    #[cfg(feature = "callback")]
    pub fn add_on_change_listener<F>(&mut self, f: F)
    where
        F: Fn(String) -> XMSG + 'static,
    {
        let cb = Callback::from(f);
        self.change_listeners.push(cb);
    }

    /// Attach an callback to this editor where it is invoked when the content is changed.
    /// The callback function just notifies the parent component that uses the Editor component.
    /// It will be up to the parent component to extract the content of the editor manually.
    ///
    /// This is intended to be used in a debounced or throttled functionality where the component
    /// decides when to do an expensive operation based on time and recency.
    ///
    ///
    #[cfg(feature = "callback")]
    pub fn on_change_notify<F>(mut self, f: F) -> Self
    where
        F: Fn(()) -> XMSG + 'static,
    {
        let cb = Callback::from(f);
        self.change_notify_listeners.push(cb);
        self
    }

    #[cfg(feature = "callback")]
    pub fn add_on_change_notify<F>(&mut self, f: F)
    where
        F: Fn(()) -> XMSG + 'static,
    {
        let cb = Callback::from(f);
        self.change_notify_listeners.push(cb);
    }

    #[cfg(feature = "callback")]
    pub fn emit_on_change_listeners(&self) -> Vec<XMSG> {
        let mut extern_msgs: Vec<XMSG> = vec![];
        if !self.change_listeners.is_empty() {
            let content = self.text_edit.get_content();
            let xmsgs: Vec<XMSG> = self
                .change_listeners
                .iter()
                .map(|listener| listener.emit(content.clone()))
                .collect();
            extern_msgs.extend(xmsgs);
        }

        if !self.change_notify_listeners.is_empty() {
            let xmsgs: Vec<XMSG> = self
                .change_notify_listeners
                .iter()
                .map(|notify| notify.emit(()))
                .collect();
            extern_msgs.extend(xmsgs);
        }

        extern_msgs
    }

    pub fn numberline_wide(&self) -> usize {
        self.text_edit.numberline_wide()
    }
}