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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
use std::cmp::Ordering;
use std::ops::Range;

use amethyst_core::timing::Time;
use clipboard::{ClipboardContext, ClipboardProvider};
use hibitset::BitSet;
use rusttype::PositionedGlyph;
use shrev::{EventChannel, ReaderId};
use specs::{Component, DenseVecStorage, Entities, Entity, Fetch, FetchMut, Join, ReadStorage,
            System, WriteStorage};
use unicode_normalization::UnicodeNormalization;
use unicode_normalization::char::is_combining_mark;
use unicode_segmentation::UnicodeSegmentation;
use winit::{ElementState, Event, KeyboardInput, ModifiersState, MouseButton, VirtualKeyCode,
            WindowEvent};

use super::*;

/// A component used to display text in this entity's UiTransform
#[derive(Clone, Derivative)]
#[derivative(Debug)]
pub struct UiText {
    /// The string rendered by this.
    pub text: String,
    /// The height of a line of text in pixels.
    pub font_size: f32,
    /// The color of the rendered text, using a range of 0.0 to 1.0 per channel.
    pub color: [f32; 4],
    /// The font used for rendering.
    pub font: FontHandle,
    /// If true this will be rendered as dots instead of the text.
    pub password: bool,
    /// Cached FontHandle, used to detect changes to the font.
    pub(crate) cached_font: FontHandle,
    /// Cached glyph positions, used to process mouse highlighting
    #[derivative(Debug = "ignore")]
    pub(crate) cached_glyphs: Vec<PositionedGlyph<'static>>,
    /// Cached id used to retrieve the `GlyphBrush` in the `UiPass`.
    pub(crate) brush_id: Option<u32>,
}

impl UiText {
    /// Initializes a new UiText
    ///
    /// # Parameters
    ///
    /// * `font`: A handle to a `Font` asset
    /// * `text`: the glyphs to render
    /// * `color`: RGBA color with a maximum of 1.0 and a minimum of 0.0 for each channel
    /// * `font_size`: a uniform scale applied to the glyphs
    pub fn new(font: FontHandle, text: String, color: [f32; 4], font_size: f32) -> UiText {
        UiText {
            text,
            color,
            font_size,
            font: font.clone(),
            password: false,
            cached_font: font,
            cached_glyphs: Vec::new(),
            brush_id: None,
        }
    }
}

impl Component for UiText {
    type Storage = DenseVecStorage<Self>;
}

/// If this component is attached to an entity with a UiText then that UiText is editable.
/// This component also controls how that editing works.
pub struct TextEditing {
    /// The current editing cursor position, specified in terms of glyphs, not characters.
    pub cursor_position: isize,
    /// The maximum graphemes permitted in this string.
    pub max_length: usize,
    /// The amount and direction of glyphs highlighted relative to the cursor.
    pub highlight_vector: isize,
    /// The color of the text itself when highlighted.
    pub selected_text_color: [f32; 4],
    /// The text background color when highlighted.
    pub selected_background_color: [f32; 4],
    /// If this is true the text will use a block cursor for editing.  Otherwise this uses a
    /// standard line cursor.  This is not recommended if your font is not monospace.
    pub use_block_cursor: bool,

    /// This value is used to control cursor blinking.
    ///
    /// When it is greater than 0.5 / CURSOR_BLINK_RATE the cursor should not display, when it
    /// is greater than or equal to 1.0 / CURSOR_BLINK_RATE it should be reset to 0.  When the
    /// player types it should be reset to 0.
    pub(crate) cursor_blink_timer: f32,
}

impl TextEditing {
    /// Create a new TextEditing Component
    pub fn new(
        max_length: usize,
        selected_text_color: [f32; 4],
        selected_background_color: [f32; 4],
        use_block_cursor: bool,
    ) -> TextEditing {
        TextEditing {
            cursor_position: 0,
            max_length,
            highlight_vector: 0,
            selected_text_color,
            selected_background_color,
            use_block_cursor,
            cursor_blink_timer: 0.0,
        }
    }
}

impl Component for TextEditing {
    type Storage = DenseVecStorage<Self>;
}

struct CachedTabOrder {
    pub cached: BitSet,
    pub cache: Vec<(i32, Entity)>,
}

/// This system processes the underlying UI data as needed.
pub struct UiSystem {
    /// A reader for winit events.
    reader: ReaderId<Event>,
    /// A cache sorted by tab order, and then by Entity.
    tab_order_cache: CachedTabOrder,
    /// This is set to true while the left mouse button is pressed.
    left_mouse_button_pressed: bool,
    /// The screen coordinates of the mouse
    mouse_position: (f32, f32),
}

impl UiSystem {
    /// Initializes a new UiSystem that uses the given reader id.
    pub fn new(reader: ReaderId<Event>) -> Self {
        Self {
            reader,
            tab_order_cache: CachedTabOrder {
                cached: BitSet::new(),
                cache: Vec::new(),
            },
            left_mouse_button_pressed: false,
            mouse_position: (0., 0.),
        }
    }
}

impl<'a> System<'a> for UiSystem {
    type SystemData = (
        Entities<'a>,
        WriteStorage<'a, UiText>,
        WriteStorage<'a, TextEditing>,
        ReadStorage<'a, UiTransform>,
        FetchMut<'a, UiFocused>,
        Fetch<'a, EventChannel<Event>>,
        Fetch<'a, Time>,
    );

    fn run(
        &mut self,
        (entities, mut text, mut editable, transform, mut focused, events, time): Self::SystemData,
    ) {
        // Populate and update the tab order cache.
        {
            let bitset = &mut self.tab_order_cache.cached;
            self.tab_order_cache.cache.retain(|&(_t, entity)| {
                let keep = transform.get(entity).is_some();
                if !keep {
                    bitset.remove(entity.id());
                }
                keep
            });
        }


        for &mut (ref mut t, entity) in &mut self.tab_order_cache.cache {
            *t = transform.get(entity).unwrap().tab_order;
        }

        // Attempt to insert the new entities in sorted position.  Should reduce work during
        // the sorting step.
        let transform_set = transform.check();
        {
            // Create a bitset containing only the new indices.
            let new = (&transform_set ^ &self.tab_order_cache.cached) & &transform_set;
            for (entity, transform, _new) in (&*entities, &transform, &new).join() {
                let pos = self.tab_order_cache
                    .cache
                    .iter()
                    .position(|&(cached_t, _)| transform.tab_order < cached_t);
                match pos {
                    Some(pos) => self.tab_order_cache
                        .cache
                        .insert(pos, (transform.tab_order, entity)),
                    None => self.tab_order_cache
                        .cache
                        .push((transform.tab_order, entity)),
                }
            }
        }
        self.tab_order_cache.cached = transform_set;

        // Sort from smallest tab order to largest tab order, then by entity creation time.
        // Most of the time this shouldn't do anything but you still need it for if the tab orders
        // change.
        self.tab_order_cache
            .cache
            .sort_unstable_by(|&(t1, ref e1), &(t2, ref e2)| {
                let ret = t1.cmp(&t2);
                if ret == Ordering::Equal {
                    return e1.cmp(e2);
                }
                ret
            });


        for text in (&mut text).join() {
            if (*text.text).chars().any(|c| is_combining_mark(c)) {
                let normalized = text.text.nfd().collect::<String>();
                text.text = normalized;
            }
        }

        {
            let mut focused_text_edit = focused.entity.and_then(|entity| {
                text.get_mut(entity)
                    .into_iter()
                    .zip(editable.get_mut(entity).into_iter())
                    .next()
            });
            if let Some((ref mut _focused_text, ref mut focused_edit)) = focused_text_edit {
                focused_edit.cursor_blink_timer += time.delta_real_seconds();
                if focused_edit.cursor_blink_timer >= 1.0 / CURSOR_BLINK_RATE {
                    focused_edit.cursor_blink_timer = 0.0;
                }
            }
        }
        for event in events.read(&mut self.reader) {
            // Process events for the whole UI.
            match *event {
                Event::WindowEvent {
                    event:
                        WindowEvent::KeyboardInput {
                            input:
                                KeyboardInput {
                                    state: ElementState::Pressed,
                                    virtual_keycode: Some(VirtualKeyCode::Tab),
                                    modifiers,
                                    ..
                                },
                            ..
                        },
                    ..
                } => if let Some(focused) = focused.entity.as_mut() {
                    if let Some((i, _)) = self.tab_order_cache
                        .cache
                        .iter()
                        .enumerate()
                        .find(|&(_i, &(_, entity))| entity == *focused)
                    {
                        if self.tab_order_cache.cache.len() != 0 {
                            if modifiers.shift {
                                if i == 0 {
                                    let new_i = self.tab_order_cache.cache.len() - 1;
                                    *focused = self.tab_order_cache.cache[new_i].1;
                                } else {
                                    *focused = self.tab_order_cache.cache[i - 1].1;
                                }
                            } else {
                                if i + 1 == self.tab_order_cache.cache.len() {
                                    *focused = self.tab_order_cache.cache[0].1;
                                } else {
                                    *focused = self.tab_order_cache.cache[i + 1].1;
                                }
                            }
                        }
                    }
                },
                Event::WindowEvent {
                    event: WindowEvent::MouseMoved { position, .. },
                    ..
                } => {
                    self.mouse_position = (position.0 as f32, position.1 as f32);
                    if self.left_mouse_button_pressed {
                        let mut focused_text_edit = focused.entity.and_then(|entity| {
                            text.get_mut(entity)
                                .into_iter()
                                .zip(editable.get_mut(entity).into_iter())
                                .next()
                        });
                        if let Some((ref mut focused_text, ref mut focused_edit)) =
                            focused_text_edit 
                        {
                            use std::f32::NAN;

                            let mouse_x = self.mouse_position.0;
                            let mouse_y = self.mouse_position.1;
                            // Find the glyph closest to the mouse position.
                            focused_edit.highlight_vector = focused_text
                                .cached_glyphs
                                .iter()
                                .enumerate()
                                .fold((0, (NAN, NAN)), |(index, (x, y)), (i, g)| {
                                    let pos = g.position();
                                    // Use Pythagorean theorem to compute distance
                                    if ((x - mouse_x).powi(2) + (y - mouse_y).powi(2)).sqrt()
                                        < ((pos.x - mouse_x).powi(2)
                                            + (pos.y - mouse_y).powi(2))
                                            .sqrt()
                                    {
                                        (index, (x, y))
                                    } else {
                                        (i, (pos.x, pos.y))
                                    }
                                })
                                .0
                                as isize - focused_edit.cursor_position;
                            // The end of the text, while not a glyph, is still something
                            // you'll likely want to click your cursor to, so if the cursor is
                            // near the end of the text, check if we should put it at the end
                            // of the text.
                            if focused_edit.cursor_position + focused_edit.highlight_vector + 1
                                == focused_text.cached_glyphs.len() as isize
                            {
                                if let Some(last_glyph) =
                                    focused_text.cached_glyphs.iter().last()
                                {
                                    if (last_glyph.position().x - mouse_x).abs()
                                        > ((last_glyph.position().x
                                            + last_glyph
                                                .unpositioned()
                                                .h_metrics()
                                                .advance_width)
                                            - mouse_x)
                                            .abs()
                                    {
                                        focused_edit.highlight_vector += 1;
                                    }
                                }
                            }
                        }
                    }
                }
                Event::WindowEvent {
                    event:
                        WindowEvent::MouseInput {
                            button: MouseButton::Left,
                            state,
                            ..
                        },
                    ..
                } => {
                    match state {
                        ElementState::Pressed => {
                            use std::f32::INFINITY;

                            self.left_mouse_button_pressed = true;
                            // Start searching for an element to focus.
                            // Find all eligible elements
                            let mut eligible = (&*entities, &transform)
                                .join()
                                .filter(|&(_, t)| {
                                    t.x <= self.mouse_position.0
                                        && t.x + t.width >= self.mouse_position.0
                                        && t.y <= self.mouse_position.1
                                        && t.y + t.height >= self.mouse_position.1
                                })
                                .collect::<Vec<_>>();
                            // In instances of ambiguity we want to select the element with the
                            // lowest Z order, so we need to find the lowest Z order value among
                            // eligible elements
                            let lowest_z = eligible
                                .iter()
                                .fold(INFINITY, |lowest, &(_, t)| lowest.min(t.z));
                            // Then filter by it
                            eligible.retain(|&(_, t)| t.z == lowest_z);
                            // We may still have ambiguity as to what to select at this point,
                            // so we'll resolve that by selecting the most recently created
                            // element.
                            focused.entity = eligible.iter().fold(None, |most_recent, &(e, _)| {
                                Some(match most_recent {
                                    Some(most_recent) => if most_recent > e {
                                        most_recent
                                    } else {
                                        e
                                    },
                                    None => e,
                                })
                            });
                            // If we focused an editable text field be sure to position the cursor
                            // in it.
                            let mut focused_text_edit = focused.entity.and_then(|entity| {
                                text.get_mut(entity)
                                    .into_iter()
                                    .zip(editable.get_mut(entity).into_iter())
                                    .next()
                            });
                            if let Some((ref mut focused_text, ref mut focused_edit)) =
                                focused_text_edit
                            {
                                use std::f32::NAN;

                                let mouse_x = self.mouse_position.0;
                                let mouse_y = self.mouse_position.1;
                                // Find the glyph closest to the click position.
                                focused_edit.highlight_vector = 0;
                                focused_edit.cursor_position = focused_text
                                    .cached_glyphs
                                    .iter()
                                    .enumerate()
                                    .fold((0, (NAN, NAN)), |(index, (x, y)), (i, g)| {
                                        let pos = g.position();
                                        // Use Pythagorean theorem to compute distance
                                        if ((x - mouse_x).powi(2) + (y - mouse_y).powi(2)).sqrt()
                                            < ((pos.x - mouse_x).powi(2)
                                                + (pos.y - mouse_y).powi(2))
                                                .sqrt()
                                        {
                                            (index, (x, y))
                                        } else {
                                            (i, (pos.x, pos.y))
                                        }
                                    })
                                    .0
                                    as isize;
                                // The end of the text, while not a glyph, is still something
                                // you'll likely want to click your cursor to, so if the cursor is
                                // near the end of the text, check if we should put it at the end
                                // of the text.
                                if focused_edit.cursor_position + 1
                                    == focused_text.cached_glyphs.len() as isize
                                {
                                    if let Some(last_glyph) =
                                        focused_text.cached_glyphs.iter().last()
                                    {
                                        if (last_glyph.position().x - mouse_x).abs()
                                            > ((last_glyph.position().x
                                                + last_glyph
                                                    .unpositioned()
                                                    .h_metrics()
                                                    .advance_width)
                                                - mouse_x)
                                                .abs()
                                        {
                                            focused_edit.cursor_position += 1;
                                        }
                                    }
                                }
                            }
                        }
                        ElementState::Released => {
                            self.left_mouse_button_pressed = false;
                        }
                    }
                }
                _ => {}
            }
            let mut focused_text_edit = focused.entity.and_then(|entity| {
                text.get_mut(entity)
                    .into_iter()
                    .zip(editable.get_mut(entity).into_iter())
                    .next()
            });
            // Process events for the focused text element
            if let Some((ref mut focused_text, ref mut focused_edit)) = focused_text_edit {
                match *event {
                    Event::WindowEvent {
                        event: WindowEvent::ReceivedCharacter(input),
                        ..
                    } => {
                        // 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.
                        if input < '\u{8}' || (input > '\u{8}' && input < '\u{20}') {
                            continue;
                        }
                        // Since delete character isn't emitted on windows, ignore it too.
                        // We'll handle this with the KeyboardInput event instead.
                        if input == '\u{7F}' {
                            continue;
                        }
                        focused_edit.cursor_blink_timer = 0.0;
                        let deleted = 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()
                            });
                        match input {
                            '\u{8}' /*Backspace*/ => if !deleted {
                                if 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;
                                    }
                                }
                            },
                            _ => {
                                if focused_text.text.graphemes(true).count() < focused_edit.max_length {
                                    focused_text.text.insert(start_byte, input);
                                    focused_edit.cursor_position += 1;
                                }
                            }
                        }
                    }
                    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::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.len() > 0 {
                                let mut ctx: ClipboardContext = ClipboardProvider::new().unwrap();
                                ctx.set_contents(new_clip).unwrap();
                            }
                        },
                        VirtualKeyCode::C => if ctrl_or_cmd(&modifiers) {
                            let new_clip = read_highlighted(focused_edit, focused_text);
                            if new_clip.len() > 0 {
                                let mut ctx: ClipboardContext = ClipboardProvider::new().unwrap();
                                ctx.set_contents(new_clip.to_owned()).unwrap();
                            }
                        },
                        VirtualKeyCode::V => if ctrl_or_cmd(&modifiers) {
                            delete_highlighted(focused_edit, focused_text);
                            let mut ctx: ClipboardContext = ClipboardProvider::new().unwrap();
                            if let Ok(contents) = ctx.get_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;
                            }
                        },
                        _ => {}
                    },
                    _ => {}
                }
            }
        }
    }
}

/// 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(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(text.text.len());
    let end_byte = text.text
        .grapheme_indices(true)
        .nth(end)
        .map(|i| i.0)
        .unwrap_or(text.text.len());
    start_byte..end_byte
}