Skip to main content

iced_cube/editing/
mod.rs

1//! Undo, redo, word deletion and Escape for the library's text fields.
2//!
3//! iced's fields already handle select all, copy, cut, paste, moving by word
4//! and Home and End. This adds the rest as a wrapper widget that resolves a
5//! [`Keymap`] of [`Shortcut`]s while the field inside it has focus, and keeps
6//! the undo history in the widget tree, so apps get it without storing
7//! anything.
8
9mod history;
10
11use std::cell::Cell;
12use std::fmt;
13use std::rc::Rc;
14
15use iced::advanced::layout::{self, Layout};
16use iced::advanced::widget::{Operation, Tree, Widget, tree};
17use iced::advanced::{Clipboard, Shell, input_method, overlay, renderer};
18use iced::keyboard::{self, Key, Modifiers, key::Named};
19use iced::widget::text_input::{self, Value};
20use iced::{Element, Event, Length, Rectangle, Renderer, Size, Theme, Vector, mouse};
21
22use crate::keys::{self, Chord, Keymap};
23
24pub(crate) use history::{Edit, History, Restore};
25
26/// A shortcut that inputs, textareas and the search fields inside other
27/// components add to iced's own editing keys. Each can be switched off in a
28/// [`Shortcuts`] set.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30pub enum Shortcut {
31    Undo,
32    Redo,
33    DeleteWordBackward,
34    DeleteWordForward,
35    /// Escape removes focus from the field and goes no further, so a dialog
36    /// around it stays open. Switched off, the field ignores Escape and
37    /// leaves it to the app.
38    EscapeUnfocus,
39}
40
41impl Shortcut {
42    const fn bit(self) -> u8 {
43        1 << self as u8
44    }
45}
46
47impl keys::Action for Shortcut {
48    const ALL: &'static [Self] = &[
49        Shortcut::Undo,
50        Shortcut::Redo,
51        Shortcut::DeleteWordBackward,
52        Shortcut::DeleteWordForward,
53        Shortcut::EscapeUnfocus,
54    ];
55
56    fn defaults() -> Keymap<Self> {
57        default_keymap()
58    }
59
60    fn name(self) -> &'static str {
61        match self {
62            Shortcut::Undo => "Undo",
63            Shortcut::Redo => "Redo",
64            Shortcut::DeleteWordBackward => "Delete word backward",
65            Shortcut::DeleteWordForward => "Delete word forward",
66            Shortcut::EscapeUnfocus => "Unfocus",
67        }
68    }
69
70    fn description(self) -> &'static str {
71        match self {
72            Shortcut::Undo => "Undoes the last word typed, deletion, paste or cut.",
73            Shortcut::Redo => "Redoes what undo took back.",
74            Shortcut::DeleteWordBackward => {
75                "Deletes back to the start of the word, or the selection if there is one."
76            }
77            Shortcut::DeleteWordForward => {
78                "Deletes forward to the end of the word, or the selection if there is one."
79            }
80            Shortcut::EscapeUnfocus => {
81                "Removes focus from the field without closing a dialog around it."
82            }
83        }
84    }
85}
86
87/// The set of [`Shortcut`]s a text field handles. Every shortcut is on by
88/// default. A shortcut that is off is ignored by the field, so its keys
89/// reach the app instead.
90///
91/// ```
92/// use iced_cube::primitives::input::{Shortcut, Shortcuts};
93///
94/// let no_undo = Shortcuts::all().without(Shortcut::Undo).without(Shortcut::Redo);
95/// assert!(!no_undo.contains(Shortcut::Undo));
96/// assert!(no_undo.contains(Shortcut::EscapeUnfocus));
97/// assert!(Shortcuts::none().with(Shortcut::Undo).contains(Shortcut::Undo));
98/// ```
99#[derive(Clone, Copy, PartialEq, Eq, Hash)]
100pub struct Shortcuts(u8);
101
102impl Shortcuts {
103    /// Every shortcut, the default.
104    pub fn all() -> Self {
105        <Shortcut as keys::Action>::ALL
106            .iter()
107            .fold(Self::none(), |set, shortcut| set.with(*shortcut))
108    }
109
110    /// No shortcuts: the field behaves as iced's plain widget.
111    pub const fn none() -> Self {
112        Self(0)
113    }
114
115    pub const fn with(self, shortcut: Shortcut) -> Self {
116        Self(self.0 | shortcut.bit())
117    }
118
119    pub const fn without(self, shortcut: Shortcut) -> Self {
120        Self(self.0 & !shortcut.bit())
121    }
122
123    pub const fn contains(self, shortcut: Shortcut) -> bool {
124        self.0 & shortcut.bit() != 0
125    }
126
127    pub const fn is_empty(self) -> bool {
128        self.0 == 0
129    }
130
131    /// The shortcuts in the set, in the order of [`Shortcut`].
132    pub fn iter(self) -> impl Iterator<Item = Shortcut> {
133        <Shortcut as keys::Action>::ALL
134            .iter()
135            .copied()
136            .filter(move |shortcut| self.contains(*shortcut))
137    }
138
139    /// Whether edits need recording for undo and redo.
140    fn has_history(self) -> bool {
141        self.contains(Shortcut::Undo) || self.contains(Shortcut::Redo)
142    }
143}
144
145impl Default for Shortcuts {
146    fn default() -> Self {
147        Self::all()
148    }
149}
150
151impl fmt::Debug for Shortcuts {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        f.debug_set().entries(self.iter()).finish()
154    }
155}
156
157impl FromIterator<Shortcut> for Shortcuts {
158    fn from_iter<I: IntoIterator<Item = Shortcut>>(shortcuts: I) -> Self {
159        shortcuts
160            .into_iter()
161            .fold(Self::none(), |set, shortcut| set.with(shortcut))
162    }
163}
164
165/// The default shortcut keys. Mod is Cmd on macOS and Ctrl elsewhere;
166/// words are deleted with Alt on macOS.
167///
168/// | Keys | Shortcut |
169/// | --- | --- |
170/// | `Mod+Z` | [`Shortcut::Undo`] |
171/// | `Mod+Shift+Z`, `Mod+Y` | [`Shortcut::Redo`] |
172/// | `Ctrl+Backspace` | [`Shortcut::DeleteWordBackward`] |
173/// | `Ctrl+Delete` | [`Shortcut::DeleteWordForward`] |
174/// | `Escape` | [`Shortcut::EscapeUnfocus`] |
175pub fn default_keymap() -> Keymap<Shortcut> {
176    Keymap::new()
177        .bind(Chord::character('z').command(), Shortcut::Undo)
178        .bind(Chord::character('z').command().shift(), Shortcut::Redo)
179        .bind(Chord::character('y').command(), Shortcut::Redo)
180        .bind(word(Named::Backspace), Shortcut::DeleteWordBackward)
181        .bind(word(Named::Delete), Shortcut::DeleteWordForward)
182        .bind(Chord::named(Named::Escape), Shortcut::EscapeUnfocus)
183}
184
185fn word(key: Named) -> Chord {
186    let chord = Chord::named(key);
187    if cfg!(target_os = "macos") {
188        chord.alt()
189    } else {
190        chord.ctrl()
191    }
192}
193
194/// Which way a word is deleted.
195#[derive(Debug, Clone, Copy, PartialEq, Eq)]
196pub(crate) enum Direction {
197    Backward,
198    Forward,
199}
200
201/// The editing widget an [`Editing`] wraps.
202pub(crate) trait Field<Message> {
203    /// The text as the app last provided it.
204    fn text(&self) -> String;
205
206    /// Whether the field is focused. `tree` is the wrapped widget's tree.
207    fn is_focused(&self, tree: &Tree) -> bool;
208
209    fn has_selection(&self, tree: &Tree) -> bool;
210
211    /// Asks the app to show `restore`.
212    fn restore(&self, tree: &mut Tree, restore: Restore, shell: &mut Shell<'_, Message>);
213
214    /// Deletes a word or the selection. Returns whether anything was asked of the app.
215    fn delete_word(
216        &self,
217        tree: &mut Tree,
218        direction: Direction,
219        shell: &mut Shell<'_, Message>,
220    ) -> bool;
221
222    fn unfocus(&self, tree: &mut Tree);
223}
224
225/// Wraps a field to add the enabled [`Shortcut`]s of `keymap` and an undo
226/// history. `edited` must be set by the field's message closure whenever it
227/// reports an edit.
228pub(crate) struct Editing<'a, Message, F> {
229    content: Element<'a, Message>,
230    field: F,
231    keymap: Keymap<Shortcut>,
232    shortcuts: Shortcuts,
233    edited: Rc<Cell<bool>>,
234}
235
236impl<'a, Message, F> Editing<'a, Message, F> {
237    pub fn new(
238        content: impl Into<Element<'a, Message>>,
239        field: F,
240        keymap: Keymap<Shortcut>,
241        shortcuts: Shortcuts,
242        edited: Rc<Cell<bool>>,
243    ) -> Self {
244        Self {
245            content: content.into(),
246            field,
247            keymap,
248            shortcuts,
249            edited,
250        }
251    }
252}
253
254/// The shortcut bound to a key press. Letters also match by their Latin
255/// equivalent, so Ctrl+Z works on other keyboard layouts.
256pub(crate) fn resolve(
257    keymap: &Keymap<Shortcut>,
258    key: &Key,
259    physical_key: keyboard::key::Physical,
260    modifiers: Modifiers,
261) -> Option<Shortcut> {
262    keymap.resolve(key, modifiers).or_else(|| {
263        let latin = key.to_latin(physical_key)?;
264        keymap.resolve(&Key::Character(latin.to_string().into()), modifiers)
265    })
266}
267
268/// A key pressed with Ctrl or Cmd is a shortcut, but some platforms still
269/// attach its text, which iced would type. Returns the press without it.
270/// Ctrl+Alt is AltGr on Windows, so it keeps its text.
271pub(crate) fn without_shortcut_text(event: &Event) -> Option<Event> {
272    let Event::Keyboard(keyboard::Event::KeyPressed {
273        key,
274        modified_key,
275        physical_key,
276        location,
277        modifiers,
278        repeat,
279        text: Some(text),
280    }) = event
281    else {
282        return None;
283    };
284    if !modifiers.command() || modifiers.alt() || text.chars().any(char::is_control) {
285        return None;
286    }
287    Some(Event::Keyboard(keyboard::Event::KeyPressed {
288        key: key.clone(),
289        modified_key: modified_key.clone(),
290        physical_key: *physical_key,
291        location: *location,
292        modifiers: *modifiers,
293        repeat: *repeat,
294        text: None,
295    }))
296}
297
298/// Whether a captured event that edited nothing may have moved the caret.
299/// iced's text input captures the release of V even after typing a plain v,
300/// so key releases never count.
301fn moves_caret(event: &Event) -> bool {
302    !matches!(event, Event::Keyboard(keyboard::Event::KeyReleased { .. }))
303}
304
305/// How an event that produced an edit groups in the history.
306pub(crate) fn classify(event: &Event) -> Edit {
307    match event {
308        Event::Keyboard(keyboard::Event::KeyPressed {
309            key,
310            modifiers,
311            text,
312            ..
313        }) => match key.as_ref() {
314            Key::Named(Named::Enter) => Edit::Insert("\n".into()),
315            Key::Named(Named::Backspace | Named::Delete)
316                if !modifiers.control() && !modifiers.alt() && !modifiers.logo() =>
317            {
318                Edit::Delete
319            }
320            _ => match text {
321                Some(text) if !text.chars().any(char::is_control) => Edit::Insert(text.to_string()),
322                _ => Edit::Other,
323            },
324        },
325        Event::InputMethod(input_method::Event::Commit(text)) => Edit::Insert(text.clone()),
326        _ => Edit::Other,
327    }
328}
329
330impl<Message, F: Field<Message>> Widget<Message, Theme, Renderer> for Editing<'_, Message, F> {
331    fn tag(&self) -> tree::Tag {
332        tree::Tag::of::<History>()
333    }
334
335    fn state(&self) -> tree::State {
336        tree::State::new(History::default())
337    }
338
339    fn children(&self) -> Vec<Tree> {
340        vec![Tree::new(&self.content)]
341    }
342
343    fn diff(&self, tree: &mut Tree) {
344        tree.diff_children(std::slice::from_ref(&self.content));
345        let history = tree.state.downcast_mut::<History>();
346        if self.shortcuts.has_history() {
347            history.settle(|| self.field.text());
348        } else {
349            *history = History::default();
350        }
351    }
352
353    fn size(&self) -> Size<Length> {
354        self.content.as_widget().size()
355    }
356
357    fn size_hint(&self) -> Size<Length> {
358        self.content.as_widget().size_hint()
359    }
360
361    fn layout(
362        &mut self,
363        tree: &mut Tree,
364        renderer: &Renderer,
365        limits: &layout::Limits,
366    ) -> layout::Node {
367        self.content
368            .as_widget_mut()
369            .layout(&mut tree.children[0], renderer, limits)
370    }
371
372    fn draw(
373        &self,
374        tree: &Tree,
375        renderer: &mut Renderer,
376        theme: &Theme,
377        style: &renderer::Style,
378        layout: Layout<'_>,
379        cursor: mouse::Cursor,
380        viewport: &Rectangle,
381    ) {
382        self.content.as_widget().draw(
383            &tree.children[0],
384            renderer,
385            theme,
386            style,
387            layout,
388            cursor,
389            viewport,
390        );
391    }
392
393    fn operate(
394        &mut self,
395        tree: &mut Tree,
396        layout: Layout<'_>,
397        renderer: &Renderer,
398        operation: &mut dyn Operation,
399    ) {
400        self.content
401            .as_widget_mut()
402            .operate(&mut tree.children[0], layout, renderer, operation);
403    }
404
405    fn update(
406        &mut self,
407        tree: &mut Tree,
408        event: &Event,
409        layout: Layout<'_>,
410        cursor: mouse::Cursor,
411        renderer: &Renderer,
412        clipboard: &mut dyn Clipboard,
413        shell: &mut Shell<'_, Message>,
414        viewport: &Rectangle,
415    ) {
416        let focused = self.field.is_focused(&tree.children[0]);
417        if focused
418            && !shell.is_event_captured()
419            && let Event::Keyboard(keyboard::Event::KeyPressed {
420                key,
421                physical_key,
422                modifiers,
423                ..
424            }) = event
425            && let Some(shortcut) = resolve(&self.keymap, key, *physical_key, *modifiers)
426        {
427            // A shortcut that is off is left to the app: the field does not
428            // act on its keys either.
429            if self.shortcuts.contains(shortcut) {
430                self.perform(tree, shortcut, shell);
431                shell.capture_event();
432            }
433            return;
434        }
435
436        let stripped = focused.then(|| without_shortcut_text(event)).flatten();
437        let event = stripped.as_ref().unwrap_or(event);
438        let replacing = focused && self.field.has_selection(&tree.children[0]);
439        let captured = shell.is_event_captured();
440        self.edited.set(false);
441        self.content.as_widget_mut().update(
442            &mut tree.children[0],
443            event,
444            layout,
445            cursor,
446            renderer,
447            clipboard,
448            shell,
449            viewport,
450        );
451
452        if !self.shortcuts.has_history() {
453            return;
454        }
455        let history = tree.state.downcast_mut::<History>();
456        if self.edited.replace(false) {
457            history.record(classify(event), replacing, || self.field.text());
458        } else if !captured && shell.is_event_captured() && moves_caret(event) {
459            history.interrupt();
460        }
461    }
462
463    fn mouse_interaction(
464        &self,
465        tree: &Tree,
466        layout: Layout<'_>,
467        cursor: mouse::Cursor,
468        viewport: &Rectangle,
469        renderer: &Renderer,
470    ) -> mouse::Interaction {
471        self.content.as_widget().mouse_interaction(
472            &tree.children[0],
473            layout,
474            cursor,
475            viewport,
476            renderer,
477        )
478    }
479
480    fn overlay<'b>(
481        &'b mut self,
482        tree: &'b mut Tree,
483        layout: Layout<'b>,
484        renderer: &Renderer,
485        viewport: &Rectangle,
486        translation: Vector,
487    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
488        self.content.as_widget_mut().overlay(
489            &mut tree.children[0],
490            layout,
491            renderer,
492            viewport,
493            translation,
494        )
495    }
496}
497
498impl<Message, F: Field<Message>> Editing<'_, Message, F> {
499    fn perform(&self, tree: &mut Tree, shortcut: Shortcut, shell: &mut Shell<'_, Message>) {
500        let (state, children) = (&mut tree.state, &mut tree.children);
501        let history = state.downcast_mut::<History>();
502        let Some(child) = children.first_mut() else {
503            return;
504        };
505        let direction = match shortcut {
506            Shortcut::Undo | Shortcut::Redo => {
507                let text = self.field.text();
508                let restore = if shortcut == Shortcut::Undo {
509                    history.undo(text)
510                } else {
511                    history.redo(text)
512                };
513                if let Some(restore) = restore {
514                    self.field.restore(child, restore, shell);
515                }
516                return;
517            }
518            Shortcut::EscapeUnfocus => {
519                self.field.unfocus(child);
520                history.interrupt();
521                shell.request_redraw();
522                return;
523            }
524            Shortcut::DeleteWordBackward => Direction::Backward,
525            Shortcut::DeleteWordForward => Direction::Forward,
526        };
527        if self.field.delete_word(child, direction, shell) && self.shortcuts.has_history() {
528            history.record(Edit::Other, true, || self.field.text());
529        }
530    }
531}
532
533impl<'a, Message: 'a, F: Field<Message> + 'a> From<Editing<'a, Message, F>>
534    for Element<'a, Message>
535{
536    fn from(editing: Editing<'a, Message, F>) -> Self {
537        Element::new(editing)
538    }
539}
540
541type InputState = text_input::State<<Renderer as iced::advanced::text::Renderer>::Paragraph>;
542
543/// A single-line iced text input.
544pub(crate) struct Input<'a, Message> {
545    value: String,
546    secure: bool,
547    on_input: Rc<dyn Fn(String) -> Message + 'a>,
548}
549
550impl<'a, Message> Input<'a, Message> {
551    pub fn new(value: &str, secure: bool, on_input: Rc<dyn Fn(String) -> Message + 'a>) -> Self {
552        Self {
553            value: value.to_owned(),
554            secure,
555            on_input,
556        }
557    }
558}
559
560fn input_state(tree: &Tree) -> Option<&InputState> {
561    match &tree.state {
562        tree::State::Some(state) => state.downcast_ref::<InputState>(),
563        tree::State::None => None,
564    }
565}
566
567fn input_state_mut(tree: &mut Tree) -> Option<&mut InputState> {
568    match &mut tree.state {
569        tree::State::Some(state) => state.downcast_mut::<InputState>(),
570        tree::State::None => None,
571    }
572}
573
574impl<Message> Field<Message> for Input<'_, Message> {
575    fn text(&self) -> String {
576        self.value.clone()
577    }
578
579    fn is_focused(&self, tree: &Tree) -> bool {
580        input_state(tree).is_some_and(InputState::is_focused)
581    }
582
583    fn has_selection(&self, tree: &Tree) -> bool {
584        input_state(tree)
585            .is_some_and(|state| state.cursor().selection(&Value::new(&self.value)).is_some())
586    }
587
588    fn restore(&self, tree: &mut Tree, restore: Restore, shell: &mut Shell<'_, Message>) {
589        let caret = restore
590            .text
591            .get(..restore.caret)
592            .map_or(0, |head| Value::new(head).len());
593        shell.publish((self.on_input)(restore.text));
594        if let Some(state) = input_state_mut(tree) {
595            state.move_cursor_to(caret);
596        }
597    }
598
599    fn delete_word(
600        &self,
601        tree: &mut Tree,
602        direction: Direction,
603        shell: &mut Shell<'_, Message>,
604    ) -> bool {
605        let Some(state) = input_state_mut(tree) else {
606            return false;
607        };
608        let value = Value::new(&self.value);
609        let (start, end) = state
610            .cursor()
611            .selection(&value)
612            .unwrap_or_else(|| word_range(&value, caret(state, &value), direction, self.secure));
613        if start == end {
614            return false;
615        }
616        let kept = format!(
617            "{}{}",
618            value.select(0, start),
619            value.select(end, value.len())
620        );
621        shell.publish((self.on_input)(kept));
622        state.move_cursor_to(start);
623        true
624    }
625
626    fn unfocus(&self, tree: &mut Tree) {
627        if let Some(state) = input_state_mut(tree) {
628            state.unfocus();
629        }
630    }
631}
632
633fn caret(state: &InputState, value: &Value) -> usize {
634    match state.cursor().state(value) {
635        text_input::cursor::State::Index(index) => index,
636        text_input::cursor::State::Selection { end, .. } => end,
637    }
638}
639
640/// The graphemes a word deletion removes from `caret`. A secure field
641/// hides its words, so it deletes to the start or end instead.
642fn word_range(value: &Value, caret: usize, direction: Direction, secure: bool) -> (usize, usize) {
643    match (direction, secure) {
644        (Direction::Backward, true) => (0, caret),
645        (Direction::Backward, false) => (value.previous_start_of_word(caret), caret),
646        (Direction::Forward, true) => (caret, value.len()),
647        (Direction::Forward, false) => (caret, value.next_end_of_word(caret)),
648    }
649}
650
651#[cfg(test)]
652mod tests {
653    use super::*;
654    use iced::keyboard::key::{NativeCode, Physical};
655
656    fn press(chord: &str) -> Option<Shortcut> {
657        let chord: Chord = chord.parse().ok()?;
658        default_keymap().resolve(chord.key(), chord.modifiers())
659    }
660
661    fn key_press(key: Key, modifiers: Modifiers, text: Option<&str>) -> Event {
662        Event::Keyboard(keyboard::Event::KeyPressed {
663            key: key.clone(),
664            modified_key: key,
665            physical_key: Physical::Unidentified(NativeCode::Unidentified),
666            location: keyboard::Location::Standard,
667            modifiers,
668            repeat: false,
669            text: text.map(Into::into),
670        })
671    }
672
673    #[test]
674    fn default_keymap_binds_undo_redo_and_word_deletion() {
675        assert_eq!(press("Mod+Z"), Some(Shortcut::Undo));
676        assert_eq!(press("Mod+Shift+Z"), Some(Shortcut::Redo));
677        assert_eq!(press("Mod+Y"), Some(Shortcut::Redo));
678        let word = if cfg!(target_os = "macos") {
679            "Alt"
680        } else {
681            "Ctrl"
682        };
683        assert_eq!(
684            press(&format!("{word}+Backspace")),
685            Some(Shortcut::DeleteWordBackward)
686        );
687        assert_eq!(
688            press(&format!("{word}+Delete")),
689            Some(Shortcut::DeleteWordForward)
690        );
691        assert_eq!(press("Escape"), Some(Shortcut::EscapeUnfocus));
692        assert_eq!(press("Z"), None);
693        assert_eq!(press("Backspace"), None);
694    }
695
696    #[test]
697    fn every_shortcut_has_a_default_chord() {
698        let keymap = default_keymap();
699        for shortcut in <Shortcut as keys::Action>::ALL {
700            assert!(!keymap.chords(shortcut).is_empty(), "{shortcut:?}");
701        }
702    }
703
704    #[test]
705    fn shortcut_sets() {
706        let all = Shortcuts::all();
707        assert_eq!(Shortcuts::default(), all);
708        assert_eq!(all.iter().count(), <Shortcut as keys::Action>::ALL.len());
709        assert!(Shortcuts::none().is_empty());
710        assert_eq!(Shortcuts::none().iter().count(), 0);
711
712        let no_undo = all.without(Shortcut::Undo);
713        assert!(!no_undo.contains(Shortcut::Undo));
714        assert!(no_undo.contains(Shortcut::Redo));
715        assert_eq!(no_undo.with(Shortcut::Undo), all);
716        assert_eq!(all.without(Shortcut::Undo).without(Shortcut::Undo), no_undo);
717
718        let picked: Shortcuts = [Shortcut::EscapeUnfocus].into_iter().collect();
719        assert_eq!(picked, Shortcuts::none().with(Shortcut::EscapeUnfocus));
720        assert!(!picked.has_history());
721        assert!(Shortcuts::none().with(Shortcut::Redo).has_history());
722        assert_eq!(format!("{picked:?}"), "{EscapeUnfocus}");
723    }
724
725    #[test]
726    fn keymap_overrides_and_unbinding() {
727        let keymap = default_keymap()
728            .unbind_action(&Shortcut::Redo)
729            .bind(Chord::named(Named::F4), Shortcut::Redo);
730        let physical = Physical::Unidentified(NativeCode::Unidentified);
731        let y = Key::Character("y".into());
732        assert_eq!(resolve(&keymap, &y, physical, Modifiers::COMMAND), None);
733        assert_eq!(
734            resolve(
735                &keymap,
736                &Key::Named(Named::F4),
737                physical,
738                Modifiers::empty()
739            ),
740            Some(Shortcut::Redo)
741        );
742        assert_eq!(
743            resolve(&Keymap::new(), &y, physical, Modifiers::COMMAND),
744            None
745        );
746    }
747
748    #[test]
749    fn shift_with_a_capital_letter_still_matches() {
750        let physical = Physical::Unidentified(NativeCode::Unidentified);
751        let z = Key::Character("Z".into());
752        assert_eq!(
753            resolve(
754                &default_keymap(),
755                &z,
756                physical,
757                Modifiers::COMMAND | Modifiers::SHIFT
758            ),
759            Some(Shortcut::Redo)
760        );
761    }
762
763    #[test]
764    fn letters_match_by_their_latin_key_on_other_layouts() {
765        let physical = Physical::Code(keyboard::key::Code::KeyZ);
766        let cyrillic = Key::Character("я".into());
767        assert_eq!(
768            resolve(&default_keymap(), &cyrillic, physical, Modifiers::COMMAND),
769            Some(Shortcut::Undo)
770        );
771    }
772
773    #[test]
774    fn classify_groups_typing_and_deletion() {
775        let a = Key::Character("a".into());
776        assert_eq!(
777            classify(&key_press(a.clone(), Modifiers::empty(), Some("a"))),
778            Edit::Insert("a".into())
779        );
780        assert_eq!(
781            classify(&key_press(a, Modifiers::CTRL, Some("\u{1}"))),
782            Edit::Other
783        );
784        assert_eq!(
785            classify(&key_press(
786                Key::Named(Named::Enter),
787                Modifiers::empty(),
788                Some("\r")
789            )),
790            Edit::Insert("\n".into())
791        );
792        assert_eq!(
793            classify(&key_press(
794                Key::Named(Named::Backspace),
795                Modifiers::empty(),
796                None
797            )),
798            Edit::Delete
799        );
800        assert_eq!(
801            classify(&key_press(
802                Key::Named(Named::Backspace),
803                Modifiers::CTRL,
804                None
805            )),
806            Edit::Other
807        );
808        assert_eq!(
809            classify(&Event::InputMethod(input_method::Event::Commit(
810                "word".into()
811            ))),
812            Edit::Insert("word".into())
813        );
814    }
815
816    #[test]
817    fn shortcut_text_is_dropped_but_altgr_and_plain_typing_keep_it() {
818        let one = Key::Character("1".into());
819        let Some(Event::Keyboard(keyboard::Event::KeyPressed { text, .. })) =
820            without_shortcut_text(&key_press(one.clone(), Modifiers::COMMAND, Some("1")))
821        else {
822            panic!("Ctrl+1 loses its text");
823        };
824        assert_eq!(text, None);
825        assert_eq!(
826            without_shortcut_text(&key_press(
827                Key::Character("@".into()),
828                Modifiers::CTRL | Modifiers::ALT,
829                Some("@")
830            )),
831            None
832        );
833        assert_eq!(
834            without_shortcut_text(&key_press(one, Modifiers::empty(), Some("1"))),
835            None
836        );
837    }
838
839    #[test]
840    fn word_ranges_follow_the_caret() {
841        let value = Value::new("one two");
842        assert_eq!(word_range(&value, 7, Direction::Backward, false), (4, 7));
843        assert_eq!(word_range(&value, 0, Direction::Forward, false), (0, 3));
844        assert_eq!(word_range(&value, 7, Direction::Backward, true), (0, 7));
845        assert_eq!(word_range(&value, 2, Direction::Forward, true), (2, 7));
846    }
847}