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
413
414
415
use std::ops::Range;

use clipboard::{ClipboardContext, ClipboardProvider};
use log::error;
use unicode_normalization::{char::is_combining_mark, UnicodeNormalization};
use unicode_segmentation::UnicodeSegmentation;
use winit::{ElementState, Event, KeyboardInput, ModifiersState, VirtualKeyCode, WindowEvent};

use amethyst_core::{
    ecs::prelude::{
        Entities, Join, Read, ReadStorage, System, SystemData, World, Write, WriteStorage,
    },
    shrev::{EventChannel, ReaderId},
    SystemDesc,
};
use amethyst_derive::SystemDesc;

use crate::{LineMode, Selected, TextEditing, UiEvent, UiEventType, UiText};

/// System managing the keyboard inputs for the editable text fields.
/// ## Features
/// * Adds and removes text.
/// * Moves selection cursor.
/// * Grows and shrinks selected text zone.
#[derive(Debug, SystemDesc)]
#[system_desc(name(TextEditingInputSystemDesc))]
pub struct TextEditingInputSystem {
    /// A reader for winit events.
    #[system_desc(event_channel_reader)]
    reader: ReaderId<Event>,
}

impl TextEditingInputSystem {
    /// Creates a new instance of this system
    pub fn new(reader: ReaderId<Event>) -> Self {
        Self { reader }
    }
}

impl<'a> System<'a> for TextEditingInputSystem {
    type SystemData = (
        Entities<'a>,
        WriteStorage<'a, UiText>,
        WriteStorage<'a, TextEditing>,
        ReadStorage<'a, Selected>,
        Read<'a, EventChannel<Event>>,
        Write<'a, EventChannel<UiEvent>>,
    );

    fn run(
        &mut self,
        (entities, mut texts, mut editables, selecteds, events, mut edit_events): Self::SystemData,
    ) {
        for text in (&mut texts).join() {
            if (*text.text).chars().any(is_combining_mark) {
                let normalized = text.text.nfd().collect::<String>();
                text.text = normalized;
            }
        }

        for event in events.read(&mut self.reader) {
            // Process events for the focused text element
            if let Some((entity, ref mut focused_text, ref mut focused_edit, _)) =
                (&*entities, &mut texts, &mut editables, &selecteds)
                    .join()
                    .next()
            {
                match *event {
                    Event::WindowEvent {
                        event: WindowEvent::ReceivedCharacter(input),
                        ..
                    } => {
                        if should_skip_char(input) {
                            continue;
                        }
                        focused_edit.cursor_blink_timer = 0.0;
                        delete_highlighted(focused_edit, focused_text);
                        let start_byte = focused_text
                            .text
                            .grapheme_indices(true)
                            .nth(focused_edit.cursor_position as usize)
                            .map(|i| i.0)
                            .unwrap_or_else(|| {
                                // We are either in a 0 length string, or at the end of a string
                                // This line returns the correct byte index for both.
                                focused_text.text.len()
                            });
                        if focused_text.text.graphemes(true).count() < focused_edit.max_length {
                            focused_text.text.insert(start_byte, input);
                            focused_edit.cursor_position += 1;

                            edit_events
                                .single_write(UiEvent::new(UiEventType::ValueChange, entity));
                        }
                    }
                    Event::WindowEvent {
                        event:
                            WindowEvent::KeyboardInput {
                                input:
                                    KeyboardInput {
                                        state: ElementState::Pressed,
                                        virtual_keycode: Some(v_keycode),
                                        modifiers,
                                        ..
                                    },
                                ..
                            },
                        ..
                    } => match v_keycode {
                        VirtualKeyCode::Home | VirtualKeyCode::Up => {
                            focused_edit.highlight_vector = if modifiers.shift {
                                focused_edit.cursor_position
                            } else {
                                0
                            };
                            focused_edit.cursor_position = 0;
                            focused_edit.cursor_blink_timer = 0.0;
                        }
                        VirtualKeyCode::End | VirtualKeyCode::Down => {
                            let glyph_len = focused_text.text.graphemes(true).count() as isize;
                            focused_edit.highlight_vector = if modifiers.shift {
                                focused_edit.cursor_position - glyph_len
                            } else {
                                0
                            };
                            focused_edit.cursor_position = glyph_len;
                            focused_edit.cursor_blink_timer = 0.0;
                        }
                        VirtualKeyCode::Back => {
                            if !delete_highlighted(focused_edit, focused_text)
                                && focused_edit.cursor_position > 0
                            {
                                if let Some((byte, len)) = focused_text
                                    .text
                                    .grapheme_indices(true)
                                    .nth(focused_edit.cursor_position as usize - 1)
                                    .map(|i| (i.0, i.1.len()))
                                {
                                    focused_text.text.drain(byte..(byte + len));
                                    focused_edit.cursor_position -= 1;
                                }
                            }
                        }
                        VirtualKeyCode::Delete => {
                            if !delete_highlighted(focused_edit, focused_text) {
                                if let Some((start_byte, start_glyph_len)) = focused_text
                                    .text
                                    .grapheme_indices(true)
                                    .nth(focused_edit.cursor_position as usize)
                                    .map(|i| (i.0, i.1.len()))
                                {
                                    focused_edit.cursor_blink_timer = 0.0;
                                    focused_text
                                        .text
                                        .drain(start_byte..(start_byte + start_glyph_len));
                                }
                            }
                        }
                        VirtualKeyCode::Left => {
                            if focused_edit.highlight_vector == 0 || modifiers.shift {
                                if focused_edit.cursor_position > 0 {
                                    let delta = if ctrl_or_cmd(modifiers) {
                                        let mut graphemes = 0;
                                        for word in focused_text.text.split_word_bounds() {
                                            let word_graphemes =
                                                word.graphemes(true).count() as isize;
                                            if graphemes + word_graphemes
                                                >= focused_edit.cursor_position
                                            {
                                                break;
                                            }
                                            graphemes += word_graphemes;
                                        }
                                        focused_edit.cursor_position - graphemes
                                    } else {
                                        1
                                    };
                                    focused_edit.cursor_position -= delta;
                                    if modifiers.shift {
                                        focused_edit.highlight_vector += delta;
                                    }
                                    focused_edit.cursor_blink_timer = 0.0;
                                }
                            } else {
                                focused_edit.cursor_position = focused_edit.cursor_position.min(
                                    focused_edit.cursor_position + focused_edit.highlight_vector,
                                );
                                focused_edit.highlight_vector = 0;
                            }
                        }
                        VirtualKeyCode::Right => {
                            if focused_edit.highlight_vector == 0 || modifiers.shift {
                                let glyph_len = focused_text.text.graphemes(true).count();
                                if (focused_edit.cursor_position as usize) < glyph_len {
                                    let delta = if ctrl_or_cmd(modifiers) {
                                        let mut graphemes = 0;
                                        for word in focused_text.text.split_word_bounds() {
                                            graphemes += word.graphemes(true).count() as isize;
                                            if graphemes > focused_edit.cursor_position {
                                                break;
                                            }
                                        }
                                        graphemes - focused_edit.cursor_position
                                    } else {
                                        1
                                    };
                                    focused_edit.cursor_position += delta;
                                    if modifiers.shift {
                                        focused_edit.highlight_vector -= delta;
                                    }
                                    focused_edit.cursor_blink_timer = 0.0;
                                }
                            } else {
                                focused_edit.cursor_position = focused_edit.cursor_position.max(
                                    focused_edit.cursor_position + focused_edit.highlight_vector,
                                );
                                focused_edit.highlight_vector = 0;
                            }
                        }
                        VirtualKeyCode::A => {
                            if ctrl_or_cmd(modifiers) {
                                let glyph_len = focused_text.text.graphemes(true).count() as isize;
                                focused_edit.cursor_position = glyph_len;
                                focused_edit.highlight_vector = -glyph_len;
                            }
                        }
                        VirtualKeyCode::X => {
                            if ctrl_or_cmd(modifiers) {
                                let new_clip = extract_highlighted(focused_edit, focused_text);
                                if !new_clip.is_empty() {
                                    match ClipboardProvider::new().and_then(
                                        |mut ctx: ClipboardContext| ctx.set_contents(new_clip),
                                    ) {
                                        Ok(_) => edit_events.single_write(UiEvent::new(
                                            UiEventType::ValueChange,
                                            entity,
                                        )),
                                        Err(e) => error!(
                                            "Error occured when cutting to clipboard: {:?}",
                                            e
                                        ),
                                    }
                                }
                            }
                        }
                        VirtualKeyCode::C => {
                            if ctrl_or_cmd(modifiers) {
                                let new_clip = read_highlighted(focused_edit, focused_text);
                                if !new_clip.is_empty() {
                                    if let Err(e) = ClipboardProvider::new().and_then(
                                        |mut ctx: ClipboardContext| {
                                            ctx.set_contents(new_clip.to_owned())
                                        },
                                    ) {
                                        error!("Error occured when copying to clipboard: {:?}", e);
                                    }
                                }
                            }
                        }
                        VirtualKeyCode::V => {
                            if ctrl_or_cmd(modifiers) {
                                delete_highlighted(focused_edit, focused_text);

                                match ClipboardProvider::new()
                                    .and_then(|mut ctx: ClipboardContext| ctx.get_contents())
                                {
                                    Ok(contents) => {
                                        let index = cursor_byte_index(focused_edit, focused_text);
                                        let empty_space = focused_edit.max_length
                                            - focused_text.text.graphemes(true).count();
                                        let contents = contents
                                            .graphemes(true)
                                            .take(empty_space)
                                            .fold(String::new(), |mut init, new| {
                                                init.push_str(new);
                                                init
                                            });
                                        focused_text.text.insert_str(index, &contents);
                                        focused_edit.cursor_position +=
                                            contents.graphemes(true).count() as isize;

                                        edit_events.single_write(UiEvent::new(
                                            UiEventType::ValueChange,
                                            entity,
                                        ));
                                    }
                                    Err(e) => error!(
                                        "Error occured when pasting contents of clipboard: {:?}",
                                        e
                                    ),
                                }
                            }
                        }
                        VirtualKeyCode::Return | VirtualKeyCode::NumpadEnter => {
                            match focused_text.line_mode {
                                LineMode::Single => {
                                    edit_events.single_write(UiEvent::new(
                                        UiEventType::ValueCommit,
                                        entity,
                                    ));
                                }
                                LineMode::Wrap => {
                                    if modifiers.shift {
                                        if focused_text.text.graphemes(true).count()
                                            < focused_edit.max_length
                                        {
                                            let start_byte = focused_text
                                                .text
                                                .grapheme_indices(true)
                                                .nth(focused_edit.cursor_position as usize)
                                                .map(|i| i.0)
                                                .unwrap_or_else(|| focused_text.text.len());

                                            focused_text.text.insert(start_byte, '\n');
                                            focused_edit.cursor_position += 1;

                                            edit_events.single_write(UiEvent::new(
                                                UiEventType::ValueChange,
                                                entity,
                                            ));
                                        }
                                    } else {
                                        edit_events.single_write(UiEvent::new(
                                            UiEventType::ValueCommit,
                                            entity,
                                        ));
                                    }
                                }
                            }
                        }
                        _ => {}
                    },
                    _ => {}
                }
            }
        }
    }
}

/// Returns if the command key is down on OSX, and the CTRL key for everything else.
fn ctrl_or_cmd(modifiers: ModifiersState) -> bool {
    (cfg!(target_os = "macos") && modifiers.logo)
        || (cfg!(not(target_os = "macos")) && modifiers.ctrl)
}

fn read_highlighted<'a>(edit: &TextEditing, text: &'a UiText) -> &'a str {
    let range = highlighted_bytes(edit, text);
    &text.text[range]
}

/// Removes the highlighted text and returns it in a String.
fn extract_highlighted(edit: &mut TextEditing, text: &mut UiText) -> String {
    let range = highlighted_bytes(edit, text);
    edit.cursor_position = range.start as isize;
    edit.highlight_vector = 0;
    text.text.drain(range).collect::<String>()
}

/// Removes the highlighted text and returns true if anything was deleted..
fn delete_highlighted(edit: &mut TextEditing, text: &mut UiText) -> bool {
    if edit.highlight_vector != 0 {
        let range = highlighted_bytes(edit, text);
        edit.cursor_position = range.start as isize;
        edit.highlight_vector = 0;
        text.text.drain(range);
        return true;
    }
    false
}

// Gets the byte index of the cursor.
fn cursor_byte_index(edit: &TextEditing, text: &UiText) -> usize {
    text.text
        .grapheme_indices(true)
        .nth(edit.cursor_position as usize)
        .map(|i| i.0)
        .unwrap_or_else(|| text.text.len())
}

/// Returns the byte indices that are highlighted in the string.
fn highlighted_bytes(edit: &TextEditing, text: &UiText) -> Range<usize> {
    let start = edit
        .cursor_position
        .min(edit.cursor_position + edit.highlight_vector) as usize;
    let end = edit
        .cursor_position
        .max(edit.cursor_position + edit.highlight_vector) as usize;
    let start_byte = text
        .text
        .grapheme_indices(true)
        .nth(start)
        .map(|i| i.0)
        .unwrap_or_else(|| text.text.len());
    let end_byte = text
        .text
        .grapheme_indices(true)
        .nth(end)
        .map(|i| i.0)
        .unwrap_or_else(|| text.text.len());
    start_byte..end_byte
}

fn should_skip_char(input: char) -> bool {
    // Ignore obsolete control characters, and tab characters we can't render
    // properly anyways.  Also ignore newline characters since we don't
    // support multi-line text at the moment.
    input < '\u{20}'
    // Ignore delete character too
    || input == '\u{7F}'
    // Unicode reserves some characters for "private use".  Systems emit
    // these for no clear reason, so we're just going to ignore all of them.
    || (input >= '\u{E000}' && input <= '\u{F8FF}')
    || (input >= '\u{F0000}' && input <= '\u{FFFFF}')
    || (input >= '\u{100000}' && input <= '\u{10FFFF}')
}