textloom 0.1.0

A reusable native rich-text editing core with optional egui, winit, and AccessKit adapters
Documentation
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
//! Winit keyboard and IME bridge, independent of the renderer and OS clipboard.
//!
//! Call [`WinitAdapter::set_focused`] when the editor gains or loses widget focus,
//! then pass window events to [`WinitAdapter::handle_window_event`]. Do not pass
//! those same text events to another editor adapter. The host renders the
//! document and `Editor::composition()`, performs pointer hit testing, services
//! clipboard requests, and calls [`WinitAdapter::sync_ime`] with the caret area.

use crate::{Editor, Error, Fragment, Movement, ParagraphKind, StylePatch};
use winit::{
    dpi::{LogicalPosition, LogicalSize},
    event::{ElementState, Ime, WindowEvent},
    keyboard::{Key, ModifiersState, NamedKey},
    window::Window,
};

/// Clipboard operations are owned by the host, avoiding platform dependencies.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ClipboardEvent {
    Copy(String),
    /// Enabled through [`WinitAdapter::rich_clipboard`]; encode native data or HTML in the host.
    CopyRich(Fragment),
    /// The selection has already been removed from the document.
    Cut(String),
    /// Rich content captured before the selection is removed.
    CutRich(Fragment),
    /// Read the clipboard, then call [`WinitAdapter::paste`].
    PasteRequest,
}

/// A host should stop dispatching handled input and redraw after a change.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct InputOutcome {
    pub handled: bool,
    /// Includes changes to the caret, typing style, and preedit text.
    pub changed: bool,
    pub clipboard: Option<ClipboardEvent>,
}

/// The command modifier can be overridden for a host's shortcut preferences.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CommandModifier {
    Control,
    Super,
}

impl Default for CommandModifier {
    fn default() -> Self {
        if cfg!(target_os = "macos") {
            Self::Super
        } else {
            Self::Control
        }
    }
}

#[derive(Debug, Default)]
pub struct WinitAdapter {
    focused: bool,
    window_unfocused: bool,
    modifiers: ModifiersState,
    ime_enabled: bool,
    command_modifier: CommandModifier,
    rich_clipboard: bool,
}

impl WinitAdapter {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn command_modifier(mut self, modifier: CommandModifier) -> Self {
        self.command_modifier = modifier;
        self
    }

    /// Request rich clipboard payloads for copy/cut instead of plain strings.
    /// The host owns MIME types and clipboard transport.
    pub fn rich_clipboard(mut self, enabled: bool) -> Self {
        self.rich_clipboard = enabled;
        self
    }

    pub fn is_focused(&self) -> bool {
        self.focused && !self.window_unfocused
    }

    pub fn ime_enabled(&self) -> bool {
        self.ime_enabled
    }

    pub fn modifiers(&self) -> ModifiersState {
        self.modifiers
    }

    /// Also useful when the host routes modifier state through its own input API.
    pub fn set_modifiers(&mut self, modifiers: ModifiersState) {
        self.modifiers = modifiers;
    }

    pub fn set_focused(&mut self, focused: bool, editor: &mut Editor) -> InputOutcome {
        let changed = self.focused != focused;
        self.focused = focused;
        let composition_changed = if !focused {
            self.ime_enabled = false;
            self.modifiers = ModifiersState::empty();
            editor.cancel_composition()
        } else {
            false
        };
        InputOutcome {
            changed: changed || composition_changed,
            ..InputOutcome::default()
        }
    }

    /// Enable platform IME while this widget has focus and keep its candidate
    /// popup near the caret. Coordinates are logical window coordinates.
    pub fn sync_ime(
        &self,
        window: &Window,
        position: LogicalPosition<f64>,
        size: LogicalSize<f64>,
    ) {
        window.set_ime_allowed(self.is_focused());
        if self.is_focused() && self.ime_enabled {
            window.set_ime_cursor_area(position, size);
        }
    }

    pub fn handle_window_event(
        &mut self,
        event: &WindowEvent,
        editor: &mut Editor,
    ) -> Result<InputOutcome, Error> {
        match event {
            WindowEvent::ModifiersChanged(modifiers) => {
                self.modifiers = modifiers.state();
                Ok(InputOutcome::default())
            }
            WindowEvent::Focused(focused) => {
                let changed = self.window_unfocused == *focused;
                self.window_unfocused = !focused;
                let canceled = if !focused {
                    self.ime_enabled = false;
                    self.modifiers = ModifiersState::empty();
                    editor.cancel_composition()
                } else {
                    false
                };
                Ok(InputOutcome {
                    changed: changed || canceled,
                    ..InputOutcome::default()
                })
            }
            WindowEvent::KeyboardInput {
                event,
                is_synthetic: false,
                ..
            } => self.handle_key(
                &event.logical_key,
                event.state,
                event.text.as_deref(),
                editor,
            ),
            WindowEvent::Ime(event) => self.handle_ime(event, editor),
            _ => Ok(InputOutcome::default()),
        }
    }

    /// Routes a logical key and its produced text. Insertion uses `text` only;
    /// using both it and `Key::Character` would duplicate dead-key output.
    pub fn handle_key(
        &mut self,
        key: &Key,
        state: ElementState,
        text: Option<&str>,
        editor: &mut Editor,
    ) -> Result<InputOutcome, Error> {
        if !self.is_focused() || state != ElementState::Pressed {
            return Ok(InputOutcome::default());
        }
        if editor.composition().is_some_and(|composition| {
            !composition.text.is_empty() || matches!(key, Key::Named(NamedKey::Escape))
        }) {
            // The IME owns navigation and editing while composing.
            return Ok(InputOutcome {
                handled: true,
                changed: matches!(key, Key::Named(NamedKey::Escape)) && editor.cancel_composition(),
                clipboard: None,
            });
        }
        let before = EditorState::capture(editor);
        // Empty preedit can precede either Commit or IME cancellation. Keep
        // its replacement for Commit, but resume normal editing when a new
        // key arrives instead. Winit suppresses key events during composition.
        if editor.composition().is_some() {
            editor.cancel_composition();
        }
        let mut outcome = InputOutcome {
            handled: true,
            ..InputOutcome::default()
        };
        let command = self.command_pressed();
        let shift = self.modifiers.shift_key();
        if command && let Key::Character(character) = key {
            match character.to_ascii_lowercase().as_str() {
                "a" => editor.select_all(),
                "c" => {
                    if !editor.selection().is_caret() {
                        outcome.clipboard = Some(if self.rich_clipboard {
                            ClipboardEvent::CopyRich(editor.selected_fragment())
                        } else {
                            ClipboardEvent::Copy(editor.selected_text())
                        });
                    }
                }
                "x" => {
                    if !editor.selection().is_caret() {
                        let selected = if self.rich_clipboard {
                            ClipboardEvent::CutRich(editor.selected_fragment())
                        } else {
                            ClipboardEvent::Cut(editor.selected_text())
                        };
                        editor.insert_text("")?;
                        outcome.clipboard = Some(selected);
                    }
                }
                "v" => outcome.clipboard = Some(ClipboardEvent::PasteRequest),
                "z" => {
                    if shift {
                        editor.redo();
                    } else {
                        editor.undo();
                    }
                }
                "y" => {
                    editor.redo();
                }
                "b" => editor.apply_style(StylePatch {
                    bold: Some(!editor.typing_style().bold),
                    ..StylePatch::default()
                })?,
                "i" => editor.apply_style(StylePatch {
                    italic: Some(!editor.typing_style().italic),
                    ..StylePatch::default()
                })?,
                "u" => editor.apply_style(StylePatch {
                    underline: Some(!editor.typing_style().underline),
                    ..StylePatch::default()
                })?,
                "7" | "&" if shift => editor.set_paragraph_kind(ParagraphKind::Ordered {
                    indent: 0,
                    start: 1,
                })?,
                "8" | "*" if shift => {
                    editor.set_paragraph_kind(ParagraphKind::Bullet { indent: 0 })?
                }
                "]" => editor.indent_list()?,
                "[" => editor.outdent_list()?,
                _ => outcome.handled = false,
            }
            outcome.changed = before != EditorState::capture(editor);
            return Ok(outcome);
        }

        let word = self.modifiers.alt_key()
            || (self.modifiers.control_key() && !self.modifiers.super_key());
        let super_command = command && self.command_modifier == CommandModifier::Super;
        let movement = match key {
            Key::Named(NamedKey::ArrowLeft) if super_command => Some(Movement::ParagraphStart),
            Key::Named(NamedKey::ArrowRight) if super_command => Some(Movement::ParagraphEnd),
            Key::Named(NamedKey::ArrowLeft) if word => Some(Movement::WordBackward),
            Key::Named(NamedKey::ArrowRight) if word => Some(Movement::WordForward),
            Key::Named(NamedKey::ArrowLeft) => Some(Movement::GraphemeBackward),
            Key::Named(NamedKey::ArrowRight) => Some(Movement::GraphemeForward),
            Key::Named(NamedKey::ArrowUp) if command => Some(Movement::DocumentStart),
            Key::Named(NamedKey::ArrowDown) if command => Some(Movement::DocumentEnd),
            Key::Named(NamedKey::ArrowUp) => Some(Movement::ParagraphUp),
            Key::Named(NamedKey::ArrowDown) => Some(Movement::ParagraphDown),
            Key::Named(NamedKey::Home) if command => Some(Movement::DocumentStart),
            Key::Named(NamedKey::End) if command => Some(Movement::DocumentEnd),
            Key::Named(NamedKey::Home) => Some(Movement::ParagraphStart),
            Key::Named(NamedKey::End) => Some(Movement::ParagraphEnd),
            _ => None,
        };
        if let Some(movement) = movement {
            editor.move_cursor(movement, shift)?;
        } else {
            match key {
                Key::Named(NamedKey::Enter) if !command => editor.insert_paragraph()?,
                Key::Named(NamedKey::Backspace) if word => editor.delete_word_backward()?,
                Key::Named(NamedKey::Delete) if word => editor.delete_word_forward()?,
                Key::Named(NamedKey::Backspace) => editor.delete_backward()?,
                Key::Named(NamedKey::Delete) => editor.delete_forward()?,
                Key::Named(NamedKey::Tab)
                    if !self.modifiers.intersects(
                        ModifiersState::CONTROL | ModifiersState::ALT | ModifiersState::SUPER,
                    ) && selection_contains_list(editor) =>
                {
                    if shift {
                        editor.outdent_list()?;
                    } else {
                        editor.indent_list()?;
                    }
                }
                _ if !self.modifiers.super_key()
                    && (!self.modifiers.control_key() || self.modifiers.alt_key()) =>
                {
                    let produced = text.unwrap_or("");
                    let clean: String = produced
                        .chars()
                        .filter(|character| !character.is_control())
                        .collect();
                    if clean.is_empty() {
                        outcome.handled = false;
                    } else {
                        editor.insert_text(&clean)?;
                    }
                }
                _ => outcome.handled = false,
            }
        }
        outcome.changed = before != EditorState::capture(editor);
        Ok(outcome)
    }

    pub fn handle_ime(&mut self, event: &Ime, editor: &mut Editor) -> Result<InputOutcome, Error> {
        if !self.is_focused() {
            return Ok(InputOutcome::default());
        }
        let before = EditorState::capture(editor);
        let was_enabled = self.ime_enabled;
        match event {
            Ime::Enabled => self.ime_enabled = true,
            Ime::Disabled => {
                self.ime_enabled = false;
                editor.cancel_composition();
            }
            Ime::Preedit(text, selection) => {
                if let Some((start, end)) = selection
                    && (start > end
                        || !text.is_char_boundary(*start)
                        || !text.is_char_boundary(*end))
                {
                    return Err(Error::InvalidCompositionSelection);
                }
                // An empty preedit preserves the captured replacement until
                // Commit. Clearing/canceling here would lose that range.
                if !text.is_empty() || editor.composition().is_some() {
                    if editor.composition().is_none() {
                        editor.begin_composition();
                    }
                    editor.update_composition(text, selection.map(|(start, end)| start..end))?;
                }
            }
            Ime::Commit(text) => {
                if editor.composition().is_none() {
                    editor.begin_composition();
                }
                editor.commit_composition(text)?;
            }
        }
        Ok(InputOutcome {
            handled: true,
            changed: before != EditorState::capture(editor) || was_enabled != self.ime_enabled,
            clipboard: None,
        })
    }

    /// Deliver a host clipboard response. Paste is a single undoable edit.
    pub fn paste(&mut self, editor: &mut Editor, text: &str) -> Result<InputOutcome, Error> {
        if !self.is_focused() {
            return Ok(InputOutcome::default());
        }
        let before = EditorState::capture(editor);
        let clean: String = text
            .chars()
            .filter(|character| !character.is_control() || matches!(character, '\n' | '\r' | '\t'))
            .collect();
        editor.break_history_group();
        editor.insert_text(&clean)?;
        editor.break_history_group();
        Ok(InputOutcome {
            handled: true,
            changed: before != EditorState::capture(editor),
            clipboard: None,
        })
    }

    /// Deliver a rich host clipboard response as one undoable edit.
    pub fn paste_fragment(
        &mut self,
        editor: &mut Editor,
        fragment: &Fragment,
    ) -> Result<InputOutcome, Error> {
        if !self.is_focused() {
            return Ok(InputOutcome::default());
        }
        let before = EditorState::capture(editor);
        editor.insert_fragment(fragment)?;
        Ok(InputOutcome {
            handled: true,
            changed: before != EditorState::capture(editor),
            clipboard: None,
        })
    }

    fn command_pressed(&self) -> bool {
        match self.command_modifier {
            // Ctrl+Alt is commonly AltGr and must remain available for text.
            CommandModifier::Control => {
                self.modifiers.control_key()
                    && !self.modifiers.alt_key()
                    && !self.modifiers.super_key()
            }
            CommandModifier::Super => {
                self.modifiers.super_key()
                    && !self.modifiers.alt_key()
                    && !self.modifiers.control_key()
            }
        }
    }
}

fn selection_contains_list(editor: &Editor) -> bool {
    let range = editor.selection().range();
    let end = if range.end.paragraph > range.start.paragraph && range.end.byte == 0 {
        range.end.paragraph
    } else {
        range.end.paragraph + 1
    };
    editor.document().paragraphs()[range.start.paragraph..end]
        .iter()
        .any(|paragraph| {
            matches!(
                paragraph.kind(),
                ParagraphKind::Bullet { .. } | ParagraphKind::Ordered { .. }
            )
        })
}

#[derive(PartialEq, Eq)]
struct EditorState {
    revision: u64,
    selection: crate::Selection,
    style: crate::InlineStyle,
    preedit: Option<(String, Option<std::ops::Range<usize>>)>,
}

impl EditorState {
    fn capture(editor: &Editor) -> Self {
        Self {
            revision: editor.document().revision(),
            selection: editor.selection(),
            style: editor.typing_style(),
            preedit: editor
                .composition()
                .map(|composition| (composition.text.clone(), composition.selection.clone())),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Position, Selection};

    fn focused(editor: &mut Editor) -> WinitAdapter {
        let mut adapter = WinitAdapter::new().command_modifier(CommandModifier::Control);
        adapter.set_focused(true, editor);
        adapter
    }

    fn key(
        adapter: &mut WinitAdapter,
        editor: &mut Editor,
        key: Key,
        text: Option<&str>,
    ) -> InputOutcome {
        adapter
            .handle_key(&key, ElementState::Pressed, text, editor)
            .unwrap()
    }

    #[test]
    fn text_dead_keys_enter_and_altgr_are_inserted_once() {
        let mut editor = Editor::from_text("");
        let mut adapter = focused(&mut editor);
        key(
            &mut adapter,
            &mut editor,
            Key::Character("e".into()),
            Some("´e"),
        );
        key(
            &mut adapter,
            &mut editor,
            Key::Named(NamedKey::Enter),
            Some("\r"),
        );
        adapter.set_modifiers(ModifiersState::CONTROL | ModifiersState::ALT);
        key(
            &mut adapter,
            &mut editor,
            Key::Character("@".into()),
            Some("@"),
        );
        assert_eq!(editor.document().plain_text(), "´e\n@");
        key(
            &mut adapter,
            &mut editor,
            Key::Character("x".into()),
            Some("\u{0}"),
        );
        assert_eq!(editor.document().plain_text(), "´e\n@");
    }

    #[test]
    fn rich_clipboard_captures_styles_before_cut_and_pastes_atomically() {
        let mut editor = Editor::from_text("café 👩‍💻");
        editor.select_all();
        editor
            .apply_style(StylePatch {
                bold: Some(true),
                ..Default::default()
            })
            .unwrap();
        let rich = editor.selected_fragment();
        let mut adapter = focused(&mut editor).rich_clipboard(true);
        adapter.set_modifiers(ModifiersState::CONTROL);
        let copy = key(&mut adapter, &mut editor, Key::Character("c".into()), None);
        assert_eq!(copy.clipboard, Some(ClipboardEvent::CopyRich(rich.clone())));
        let cut = key(&mut adapter, &mut editor, Key::Character("x".into()), None);
        assert_eq!(cut.clipboard, Some(ClipboardEvent::CutRich(rich.clone())));
        assert_eq!(editor.document().plain_text(), "");
        assert!(adapter.paste_fragment(&mut editor, &rich).unwrap().changed);
        assert_eq!(editor.document().to_bytes(), rich.to_bytes());
        assert!(editor.undo());
        assert_eq!(editor.document().plain_text(), "");
        assert!(editor.undo());
        assert_eq!(editor.document().to_bytes(), rich.to_bytes());
        adapter.set_focused(false, &mut editor);
        assert!(!adapter.paste_fragment(&mut editor, &rich).unwrap().handled);
    }

    #[test]
    fn word_deletion_and_list_tabs_route_to_core_and_leave_body_tab_to_host() {
        let mut editor = Editor::from_text("one café");
        editor
            .set_selection(Selection::caret(editor.document().end()))
            .unwrap();
        let mut adapter = focused(&mut editor);
        adapter.set_modifiers(ModifiersState::CONTROL);
        key(
            &mut adapter,
            &mut editor,
            Key::Named(NamedKey::Backspace),
            None,
        );
        assert_eq!(editor.document().plain_text(), "one ");
        assert!(editor.undo());
        editor
            .set_selection(Selection::caret(Position::default()))
            .unwrap();
        key(
            &mut adapter,
            &mut editor,
            Key::Named(NamedKey::Delete),
            None,
        );
        assert_eq!(editor.document().plain_text(), " café");
        editor
            .set_paragraph_kind(ParagraphKind::Bullet { indent: 0 })
            .unwrap();
        adapter.set_modifiers(ModifiersState::empty());
        assert!(key(&mut adapter, &mut editor, Key::Named(NamedKey::Tab), None).handled);
        assert_eq!(
            editor.document().paragraph(0).unwrap().kind(),
            ParagraphKind::Bullet { indent: 1 }
        );
        adapter.set_modifiers(ModifiersState::SHIFT);
        key(&mut adapter, &mut editor, Key::Named(NamedKey::Tab), None);
        key(&mut adapter, &mut editor, Key::Named(NamedKey::Tab), None);
        assert_eq!(
            editor.document().paragraph(0).unwrap().kind(),
            ParagraphKind::Body
        );
        assert!(!key(&mut adapter, &mut editor, Key::Named(NamedKey::Tab), None).handled);
    }

    #[test]
    fn modified_tabs_remain_with_host_and_list_selection_excludes_body_endpoint() {
        let mut editor = Editor::from_text("list\nbody");
        editor
            .set_paragraph_kind(ParagraphKind::Bullet { indent: 0 })
            .unwrap();
        let mut adapter = focused(&mut editor);
        for modifier in [
            ModifiersState::CONTROL,
            ModifiersState::ALT,
            ModifiersState::SUPER,
        ] {
            adapter.set_modifiers(modifier);
            assert!(!key(&mut adapter, &mut editor, Key::Named(NamedKey::Tab), None).handled);
            assert_eq!(
                editor.document().paragraph(0).unwrap().kind(),
                ParagraphKind::Bullet { indent: 0 }
            );
        }
        adapter.set_modifiers(ModifiersState::empty());
        editor
            .set_selection(Selection::new(Position::new(0, 0), Position::new(1, 0)))
            .unwrap();
        assert!(key(&mut adapter, &mut editor, Key::Named(NamedKey::Tab), None).handled);
        assert_eq!(
            editor.document().paragraph(0).unwrap().kind(),
            ParagraphKind::Bullet { indent: 1 }
        );
        assert_eq!(
            editor.document().paragraph(1).unwrap().kind(),
            ParagraphKind::Body
        );
    }

    #[test]
    fn clipboard_shortcuts_are_explicit_and_undoable() {
        let mut editor = Editor::from_text("hello");
        let mut adapter = focused(&mut editor);
        adapter.set_modifiers(ModifiersState::CONTROL);
        key(
            &mut adapter,
            &mut editor,
            Key::Character("a".into()),
            Some("\u{1}"),
        );
        let cut = key(&mut adapter, &mut editor, Key::Character("x".into()), None);
        assert_eq!(cut.clipboard, Some(ClipboardEvent::Cut("hello".into())));
        assert_eq!(editor.document().plain_text(), "");
        assert!(editor.undo());
        assert_eq!(editor.document().plain_text(), "hello");
        let paste = key(&mut adapter, &mut editor, Key::Character("v".into()), None);
        assert_eq!(paste.clipboard, Some(ClipboardEvent::PasteRequest));
        adapter.paste(&mut editor, "one\r\ntwo\u{0}").unwrap();
        assert_eq!(editor.document().plain_text(), "one\ntwo");
    }

    #[test]
    fn ime_empty_preedit_keeps_the_replacement_and_suppresses_keys() {
        let mut editor = Editor::from_text("ab");
        editor
            .set_selection(Selection::new(Position::new(0, 0), Position::new(0, 1)))
            .unwrap();
        let mut adapter = focused(&mut editor);
        adapter.handle_ime(&Ime::Enabled, &mut editor).unwrap();
        adapter
            .handle_ime(&Ime::Preedit("え".into(), Some((3, 3))), &mut editor)
            .unwrap();
        key(
            &mut adapter,
            &mut editor,
            Key::Character("e".into()),
            Some("e"),
        );
        assert_eq!(editor.document().plain_text(), "ab");
        adapter
            .handle_ime(&Ime::Preedit(String::new(), None), &mut editor)
            .unwrap();
        adapter
            .handle_ime(&Ime::Commit("é".into()), &mut editor)
            .unwrap();
        assert_eq!(editor.document().plain_text(), "éb");
        assert!(editor.undo());
        assert_eq!(editor.document().plain_text(), "ab");
    }

    #[test]
    fn invalid_preedit_and_focus_loss_do_not_modify_the_document() {
        let mut editor = Editor::from_text("a");
        let mut adapter = focused(&mut editor);
        assert_eq!(
            adapter.handle_ime(&Ime::Preedit("é".into(), Some((1, 1))), &mut editor),
            Err(Error::InvalidCompositionSelection)
        );
        assert!(editor.composition().is_none());
        adapter
            .handle_ime(&Ime::Preedit("候".into(), None), &mut editor)
            .unwrap();
        adapter
            .handle_window_event(&WindowEvent::Focused(false), &mut editor)
            .unwrap();
        assert!(editor.composition().is_none());
        assert!(!adapter.is_focused());
        assert!(
            !key(
                &mut adapter,
                &mut editor,
                Key::Character("b".into()),
                Some("b")
            )
            .handled
        );
        assert_eq!(editor.document().plain_text(), "a");
    }

    #[test]
    fn cleared_preedit_without_commit_does_not_block_future_typing() {
        let mut editor = Editor::from_text("ab");
        editor
            .set_selection(Selection::new(Position::new(0, 0), Position::new(0, 1)))
            .unwrap();
        let mut adapter = focused(&mut editor);
        adapter.handle_ime(&Ime::Enabled, &mut editor).unwrap();
        adapter
            .handle_ime(&Ime::Preedit("候".into(), None), &mut editor)
            .unwrap();
        adapter
            .handle_ime(&Ime::Preedit(String::new(), None), &mut editor)
            .unwrap();
        key(
            &mut adapter,
            &mut editor,
            Key::Character("c".into()),
            Some("c"),
        );
        assert_eq!(editor.document().plain_text(), "cb");
        assert!(editor.composition().is_none());
        assert!(adapter.ime_enabled());
    }
}