1#![warn(missing_docs)]
8
9use crate::cursor::MouseCursorInner;
10use crate::item_tree::ItemTreeRc;
11use crate::item_tree::{ItemRc, ItemWeak, VisitChildrenResult};
12use crate::items::{
13 AllowedDragActions, BuiltInMouseCursor, DropEvent, ItemRef, OperatingSystemType,
14 TextCursorDirection,
15};
16pub use crate::items::{FocusReason, KeyEvent, KeyboardModifiers, PointerEventButton};
17use crate::lengths::{ItemTransform, LogicalPoint, LogicalVector};
18use crate::window::{WindowAdapter, WindowInner};
19use crate::{Coord, Property, SharedString};
20use alloc::rc::Rc;
21use alloc::vec::Vec;
22use const_field_offset::FieldOffsets;
23use core::cell::Cell;
24use core::fmt::Display;
25use core::pin::Pin;
26use core::time::Duration;
27
28#[repr(C)]
33#[derive(Debug, Clone, PartialEq)]
34pub enum MouseEvent {
35 Pressed {
37 position: LogicalPoint,
39 button: PointerEventButton,
41 click_count: u8,
43 touch_finger_id: i32,
45 },
46 Released {
48 position: LogicalPoint,
50 button: PointerEventButton,
52 click_count: u8,
54 touch_finger_id: i32,
56 },
57 Moved {
59 position: LogicalPoint,
61 touch_finger_id: i32,
63 },
64 Wheel {
66 position: LogicalPoint,
68 delta_x: Coord,
70 delta_y: Coord,
72 phase: TouchPhase,
74 },
75 DragMove {
79 event: DropEvent,
81 allowed: AllowedDragActions,
83 },
84 Drop {
86 event: DropEvent,
88 allowed: AllowedDragActions,
90 },
91 PinchGesture {
93 position: LogicalPoint,
95 delta: f32,
97 phase: TouchPhase,
99 },
100 RotationGesture {
102 position: LogicalPoint,
104 delta: f32,
106 phase: TouchPhase,
108 },
109 Exit,
111}
112
113impl MouseEvent {
114 pub fn touch_finger_id(&self) -> i32 {
116 match self {
117 MouseEvent::Pressed { touch_finger_id, .. } => *touch_finger_id,
118 MouseEvent::Released { touch_finger_id, .. } => *touch_finger_id,
119 MouseEvent::Moved { touch_finger_id, .. } => *touch_finger_id,
120 _ => 0,
121 }
122 }
123
124 pub fn is_from_touch(&self) -> bool {
126 self.touch_finger_id() != 0
128 }
129
130 pub fn position(&self) -> Option<LogicalPoint> {
132 match self {
133 MouseEvent::Pressed { position, .. } => Some(*position),
134 MouseEvent::Released { position, .. } => Some(*position),
135 MouseEvent::Moved { position, .. } => Some(*position),
136 MouseEvent::Wheel { position, .. } => Some(*position),
137 MouseEvent::PinchGesture { position, .. } => Some(*position),
138 MouseEvent::RotationGesture { position, .. } => Some(*position),
139 MouseEvent::DragMove { event: e, .. } | MouseEvent::Drop { event: e, .. } => {
140 Some(crate::lengths::logical_point_from_api(e.position))
141 }
142 MouseEvent::Exit => None,
143 }
144 }
145
146 pub fn translate(&mut self, vec: LogicalVector) {
148 let pos = match self {
149 MouseEvent::Pressed { position, .. } => Some(position),
150 MouseEvent::Released { position, .. } => Some(position),
151 MouseEvent::Moved { position, .. } => Some(position),
152 MouseEvent::Wheel { position, .. } => Some(position),
153 MouseEvent::PinchGesture { position, .. } => Some(position),
154 MouseEvent::RotationGesture { position, .. } => Some(position),
155 MouseEvent::DragMove { event: e, .. } | MouseEvent::Drop { event: e, .. } => {
156 e.position = crate::api::LogicalPosition::from_euclid(
157 crate::lengths::logical_point_from_api(e.position) + vec,
158 );
159 None
160 }
161 MouseEvent::Exit => None,
162 };
163 if let Some(pos) = pos {
164 *pos += vec;
165 }
166 }
167
168 pub fn transform(&mut self, transform: ItemTransform) {
170 let pos = match self {
171 MouseEvent::Pressed { position, .. } => Some(position),
172 MouseEvent::Released { position, .. } => Some(position),
173 MouseEvent::Moved { position, .. } => Some(position),
174 MouseEvent::Wheel { position, .. } => Some(position),
175 MouseEvent::PinchGesture { position, .. } => Some(position),
176 MouseEvent::RotationGesture { position, .. } => Some(position),
177 MouseEvent::DragMove { event: e, .. } | MouseEvent::Drop { event: e, .. } => {
178 e.position = crate::api::LogicalPosition::from_euclid(
179 transform
180 .transform_point(crate::lengths::logical_point_from_api(e.position).cast())
181 .cast(),
182 );
183 None
184 }
185 MouseEvent::Exit => None,
186 };
187 if let Some(pos) = pos {
188 *pos = transform.transform_point(pos.cast()).cast();
189 }
190 }
191
192 fn set_click_count(&mut self, count: u8) {
194 match self {
195 MouseEvent::Pressed { click_count, .. } | MouseEvent::Released { click_count, .. } => {
196 *click_count = count
197 }
198 _ => (),
199 }
200 }
201}
202
203#[allow(missing_docs)]
205#[repr(C)]
206#[derive(Debug, Clone, Copy, PartialEq)]
207pub enum BackendMouseEvent {
208 Pressed {
210 position: LogicalPoint,
211 button: PointerEventButton,
212 click_count: u8,
213 touch_finger_id: i32,
214 },
215 Released {
217 position: LogicalPoint,
218 button: PointerEventButton,
219 click_count: u8,
220 touch_finger_id: i32,
221 },
222 Moved { position: LogicalPoint, touch_finger_id: i32 },
224 Wheel { position: LogicalPoint, delta_x: Coord, delta_y: Coord, phase: TouchPhase },
226 PinchGesture { position: LogicalPoint, delta: f32, phase: TouchPhase },
228 RotationGesture { position: LogicalPoint, delta: f32, phase: TouchPhase },
230 Exit,
232}
233
234impl From<BackendMouseEvent> for MouseEvent {
235 fn from(event: BackendMouseEvent) -> Self {
236 match event {
237 BackendMouseEvent::Pressed { position, button, click_count, touch_finger_id } => {
238 Self::Pressed { position, button, click_count, touch_finger_id }
239 }
240 BackendMouseEvent::Released { position, button, click_count, touch_finger_id } => {
241 Self::Released { position, button, click_count, touch_finger_id }
242 }
243 BackendMouseEvent::Moved { position, touch_finger_id } => {
244 Self::Moved { position, touch_finger_id }
245 }
246 BackendMouseEvent::Wheel { position, delta_x, delta_y, phase } => {
247 Self::Wheel { position, delta_x, delta_y, phase }
248 }
249 BackendMouseEvent::PinchGesture { position, delta, phase } => {
250 Self::PinchGesture { position, delta, phase }
251 }
252 BackendMouseEvent::RotationGesture { position, delta, phase } => {
253 Self::RotationGesture { position, delta, phase }
254 }
255 BackendMouseEvent::Exit => Self::Exit,
256 }
257 }
258}
259
260#[allow(missing_docs)]
262#[derive(Debug, Clone, PartialEq)]
263pub enum BackendDragEvent {
264 Move { event: DropEvent, allowed: AllowedDragActions },
266 Drop { event: DropEvent, allowed: AllowedDragActions },
268 Leave,
270}
271
272impl From<BackendDragEvent> for MouseEvent {
273 fn from(event: BackendDragEvent) -> Self {
274 match event {
275 BackendDragEvent::Move { event, allowed } => Self::DragMove { event, allowed },
276 BackendDragEvent::Drop { event, allowed } => Self::Drop { event, allowed },
277 BackendDragEvent::Leave => Self::Exit,
279 }
280 }
281}
282
283#[repr(u8)]
287#[derive(Debug, Clone, Copy, PartialEq)]
288pub enum TouchPhase {
289 Started,
291 Moved,
293 Ended,
295 Cancelled,
297}
298
299#[repr(u8)]
304#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
305pub enum InputEventResult {
306 EventAccepted,
309 #[default]
311 EventIgnored,
312 GrabMouse,
314 StartDrag,
316}
317
318#[repr(C)]
322#[derive(Debug, Copy, Clone, PartialEq, Default)]
323pub enum InputEventFilterResult {
324 #[default]
327 ForwardEvent,
328 ForwardAndIgnore,
331 ForwardAndInterceptGrab,
334 Intercept,
337 DelayForwarding(u64),
345 ForwardAndObserve,
348}
349
350#[allow(missing_docs, non_upper_case_globals)]
352pub mod key_codes {
353 macro_rules! declare_consts_for_special_keys {
354 ($($char:literal # $name:ident # $($shifted:ident)? $(=> $($_muda:ident)? # $($_qt:ident)|* # $($_winit:ident $(($_pos:ident))?)|* # $($_xkb:ident)|* )? ;)*) => {
355 $(pub const $name : char = $char;)*
356
357 #[allow(missing_docs)]
358 #[derive(Debug, Copy, Clone, PartialEq)]
359 #[non_exhaustive]
360 pub enum Key {
375 $($name,)*
376 }
377
378 impl From<Key> for char {
379 fn from(k: Key) -> Self {
380 match k {
381 $(Key::$name => $name,)*
382 }
383 }
384 }
385
386 impl From<Key> for crate::SharedString {
387 fn from(k: Key) -> Self {
388 char::from(k).into()
389 }
390 }
391 };
392 }
393
394 i_slint_common::for_each_keys!(declare_consts_for_special_keys);
395}
396
397#[derive(Clone, Copy, Default, Debug)]
400pub(crate) struct InternalKeyboardModifierState {
401 left_alt: bool,
402 right_alt: bool,
403 altgr: bool,
404 left_control: bool,
405 right_control: bool,
406 left_meta: bool,
407 right_meta: bool,
408 left_shift: bool,
409 right_shift: bool,
410}
411
412impl InternalKeyboardModifierState {
413 pub(crate) fn state_update(mut self, pressed: bool, text: &SharedString) -> Option<Self> {
416 if let Some(key_code) = text.chars().next() {
417 match key_code {
418 key_codes::Alt => self.left_alt = pressed,
419 key_codes::AltGr => self.altgr = pressed,
420 key_codes::Control => self.left_control = pressed,
421 key_codes::ControlR => self.right_control = pressed,
422 key_codes::Shift => self.left_shift = pressed,
423 key_codes::ShiftR => self.right_shift = pressed,
424 key_codes::Meta => self.left_meta = pressed,
425 key_codes::MetaR => self.right_meta = pressed,
426 _ => return None,
427 };
428
429 debug_assert_eq!(key_code.len_utf8(), text.len());
433 }
434
435 Some(self)
436 }
437
438 pub fn shift(&self) -> bool {
439 self.right_shift || self.left_shift
440 }
441 pub fn alt(&self) -> bool {
442 self.right_alt || self.left_alt
443 }
444 pub fn meta(&self) -> bool {
445 self.right_meta || self.left_meta
446 }
447 pub fn control(&self) -> bool {
448 self.right_control || self.left_control
449 }
450
451 pub fn modifiers_for(&self, _event: &InternalKeyEvent) -> KeyboardModifiers {
452 #[allow(unused_mut)]
453 let mut alt = self.alt();
454 #[allow(unused_mut)]
455 let mut control = self.control();
456
457 #[cfg(target_os = "windows")]
476 {
477 if !self.altgr && self.control() && self.alt() {
479 let implies_altgr = if _event.text_without_modifiers.is_empty() {
486 _event.key_event.text.chars().any(|c| !c.is_ascii_alphanumeric())
487 } else {
488 _event.text_without_modifiers.to_lowercase()
489 != _event.key_event.text.to_lowercase()
490 };
491 if implies_altgr {
492 alt = false;
493 control = false;
494 }
495 }
496 }
497 #[cfg(target_family = "wasm")]
498 if crate::detect_operating_system() == OperatingSystemType::Windows {
499 let is_altgr = self.altgr
503 || (self.control()
504 && self.alt()
505 && _event.key_event.text.chars().any(|c| !c.is_ascii_alphanumeric()));
506 if is_altgr {
507 alt = false;
508 control = false;
509 }
510 }
511
512 KeyboardModifiers { alt, control, meta: self.meta(), shift: self.shift() }
513 }
514}
515
516impl From<InternalKeyboardModifierState> for KeyboardModifiers {
517 fn from(internal_state: InternalKeyboardModifierState) -> Self {
518 Self {
519 alt: internal_state.alt(),
520 control: internal_state.control(),
521 meta: internal_state.meta(),
522 shift: internal_state.shift(),
523 }
524 }
525}
526
527#[i_slint_core_macros::slint_doc]
528#[derive(Clone, Eq, PartialEq, Default)]
561#[repr(C)]
562pub struct Keys {
563 inner: KeysInner,
564}
565
566#[derive(Debug, Clone, PartialEq, Eq)]
568enum KeysParseErrorInner {
569 NoKey,
571 MultipleKeys,
573 MultipleGraphemeClusters(SharedString),
576 NotLowercase(SharedString),
579 IncompatibleModifiers(SharedString),
582}
583
584#[derive(Debug, Clone, PartialEq, Eq)]
589pub struct KeysParseError(KeysParseErrorInner);
590
591impl core::fmt::Display for KeysParseError {
592 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
593 match &self.0 {
594 KeysParseErrorInner::NoKey => write!(f, "no key found (only modifiers)"),
595 KeysParseErrorInner::MultipleKeys => {
596 write!(f, "multiple non-modifier keys found")
597 }
598 KeysParseErrorInner::MultipleGraphemeClusters(s) => {
599 write!(f, "key string must be a single grapheme cluster, got: {s}")
600 }
601 KeysParseErrorInner::NotLowercase(s) => {
602 let lower = s.to_lowercase();
603 write!(f, "key string must be lowercase, use \"{lower}\" instead")
604 }
605 KeysParseErrorInner::IncompatibleModifiers(msg) => write!(f, "{msg}"),
606 }
607 }
608}
609
610impl core::error::Error for KeysParseError {}
611
612use i_slint_common::key_codes::{ShiftBehavior, lookup_key_name};
613
614pub fn make_keys(
616 key: SharedString,
617 modifiers: KeyboardModifiers,
618 ignore_shift: bool,
619 ignore_alt: bool,
620) -> Keys {
621 Keys {
622 inner: KeysInner { key: key.to_lowercase().into(), modifiers, ignore_shift, ignore_alt },
623 }
624}
625
626#[cfg(feature = "ffi")]
627#[allow(unsafe_code)]
628pub(crate) mod ffi {
629 use crate::api::ToSharedString as _;
630
631 use super::*;
632
633 #[unsafe(no_mangle)]
634 pub unsafe extern "C" fn slint_keys(
635 key: &SharedString,
636 alt: bool,
637 control: bool,
638 shift: bool,
639 meta: bool,
640 ignore_shift: bool,
641 ignore_alt: bool,
642 out: &mut Keys,
643 ) {
644 *out = make_keys(
645 key.clone(),
646 KeyboardModifiers { alt, control, shift, meta },
647 ignore_shift,
648 ignore_alt,
649 );
650 }
651
652 #[unsafe(no_mangle)]
653 pub unsafe extern "C" fn slint_keys_debug_string(shortcut: &Keys, out: &mut SharedString) {
654 *out = crate::format!("{shortcut:?}");
655 }
656
657 #[unsafe(no_mangle)]
658 pub unsafe extern "C" fn slint_keys_to_string(shortcut: &Keys, out: &mut SharedString) {
659 *out = shortcut.to_shared_string();
660 }
661
662 #[unsafe(no_mangle)]
663 pub unsafe extern "C" fn slint_keys_from_parts(
664 parts: crate::slice::Slice<'_, SharedString>,
665 out: &mut Keys,
666 ) -> bool {
667 match keys_from_parts(parts.as_slice().iter().map(|s| s.as_str())) {
668 Ok(keys) => {
669 *out = keys;
670 true
671 }
672 Err(_) => false,
673 }
674 }
675
676 #[unsafe(no_mangle)]
677 pub unsafe extern "C" fn slint_keys_to_parts(
678 keys: &Keys,
679 out: &mut crate::SharedVector<SharedString>,
680 ) {
681 *out = keys.to_parts().map(SharedString::from).collect();
682 }
683}
684
685fn normalize_key(key: &str) -> SharedString {
687 let lowered = key.to_lowercase();
688 cfg_if::cfg_if! {
689 if #[cfg(feature = "shared-parley")] {
690 let normalizer = icu_normalizer::ComposingNormalizer::new_nfc();
691 let normalized = normalizer.normalize(&lowered);
692 SharedString::from(normalized.as_ref())
693 } else {
694 SharedString::from(lowered.as_str())
695 }
696 }
697}
698
699fn keys_from_parts<'a>(parts: impl Iterator<Item = &'a str>) -> Result<Keys, KeysParseError> {
700 keys_from_parts_inner(parts).map_err(KeysParseError)
701}
702
703fn keys_from_parts_inner<'a>(
704 parts: impl Iterator<Item = &'a str>,
705) -> Result<Keys, KeysParseErrorInner> {
706 use unicode_segmentation::UnicodeSegmentation;
707
708 let mut modifiers = KeyboardModifiers::default();
709 let mut ignore_shift = false;
710 let mut ignore_alt = false;
711 let mut key_part: Option<&str> = None;
712
713 for part in parts {
714 if part.is_empty() {
721 continue;
722 }
723 match part {
724 "Control" => modifiers.control = true,
725 "Alt" => {
726 if ignore_alt {
727 return Err(KeysParseErrorInner::IncompatibleModifiers(
728 "Alt and Alt? cannot be combined".into(),
729 ));
730 }
731 modifiers.alt = true;
732 }
733 "Shift" => {
734 if ignore_shift {
735 return Err(KeysParseErrorInner::IncompatibleModifiers(
736 "Shift and Shift? cannot be combined".into(),
737 ));
738 }
739 modifiers.shift = true;
740 }
741 "Meta" => modifiers.meta = true,
742 "Shift?" => {
743 if modifiers.shift {
744 return Err(KeysParseErrorInner::IncompatibleModifiers(
745 "Shift and Shift? cannot be combined".into(),
746 ));
747 }
748 ignore_shift = true;
749 }
750 "Alt?" => {
751 if modifiers.alt {
752 return Err(KeysParseErrorInner::IncompatibleModifiers(
753 "Alt and Alt? cannot be combined".into(),
754 ));
755 }
756 ignore_alt = true;
757 }
758 _ => {
759 if key_part.is_some() {
760 return Err(KeysParseErrorInner::MultipleKeys);
761 }
762 key_part = Some(part);
763 }
764 }
765 }
766
767 let key_name = match key_part {
768 Some(k) => k,
769 None if modifiers == KeyboardModifiers::default() && !ignore_shift && !ignore_alt => {
770 return Ok(Keys::default());
772 }
773 None => return Err(KeysParseErrorInner::NoKey),
774 };
775
776 if let Some((key_char, shift_behavior)) = lookup_key_name(key_name) {
778 if matches!(shift_behavior, ShiftBehavior::LocalizedShiftable { .. }) {
780 if modifiers.shift {
781 return Err(KeysParseErrorInner::IncompatibleModifiers(
782 alloc::format!(
783 "Key bindings involving {key_name} ignore Shift to support different keyboard layouts; remove Shift"
784 ).into(),
785 ));
786 }
787 ignore_shift = true;
788 }
789 let key: SharedString = key_char.to_lowercase().collect::<alloc::string::String>().into();
791 return Ok(Keys { inner: KeysInner { key, modifiers, ignore_shift, ignore_alt } });
792 }
793
794 let grapheme_count = key_name.graphemes(true).count();
797 if grapheme_count > 1 {
798 return Err(KeysParseErrorInner::MultipleGraphemeClusters(key_name.into()));
799 }
800
801 let lowered = key_name.to_lowercase();
803 if lowered != key_name {
804 return Err(KeysParseErrorInner::NotLowercase(key_name.into()));
805 }
806
807 let key = normalize_key(key_name);
808 Ok(Keys { inner: KeysInner { key, modifiers, ignore_shift, ignore_alt } })
809}
810
811#[derive(PartialEq, Eq, Clone, Default)]
814#[repr(C)]
815pub struct KeysInner {
816 pub key: SharedString,
820 pub modifiers: KeyboardModifiers,
822 pub ignore_shift: bool,
824 pub ignore_alt: bool,
826}
827
828impl KeysInner {
829 pub fn from_pub(keys: &Keys) -> &Self {
831 &keys.inner
832 }
833}
834
835impl Keys {
836 #[i_slint_core_macros::slint_doc]
837 pub fn from_parts<'a>(
856 parts: impl IntoIterator<Item = &'a str>,
857 ) -> Result<Keys, KeysParseError> {
858 keys_from_parts(parts.into_iter())
859 }
860
861 #[i_slint_core_macros::slint_doc]
862 pub fn to_parts(&self) -> impl Iterator<Item = &str> {
889 let inner = &self.inner;
890 let has_key = !inner.key.is_empty();
891 [
901 (has_key && inner.modifiers.meta).then_some("Meta"),
902 (has_key && inner.modifiers.control).then_some("Control"),
903 (has_key && inner.modifiers.alt).then_some("Alt"),
904 (has_key && !inner.modifiers.alt && inner.ignore_alt).then_some("Alt?"),
905 (has_key && inner.modifiers.shift).then_some("Shift"),
906 (has_key && !inner.modifiers.shift && inner.ignore_shift).then_some("Shift?"),
907 has_key.then(|| inner.key.as_str()),
908 ]
909 .into_iter()
910 .flatten()
911 }
912
913 pub(crate) fn matches(&self, key_event: &KeyEvent) -> bool {
915 let inner = &self.inner;
916 if inner.key.is_empty() {
918 return false;
919 }
920
921 let mut expected_modifiers = inner.modifiers;
923 if inner.ignore_shift {
924 expected_modifiers.shift = key_event.modifiers.shift;
925 }
926 if inner.ignore_alt {
927 expected_modifiers.alt = key_event.modifiers.alt;
928 }
929 let event_text = key_event.text.chars().flat_map(|character| character.to_lowercase());
937
938 event_text.eq(inner.key.chars()) && key_event.modifiers == expected_modifiers
939 }
940
941 fn format_key_for_display(&self) -> crate::SharedString {
942 let key_str = self.inner.key.as_str();
943 let first_char = key_str.chars().next();
944
945 if let Some(first_char) = first_char {
946 macro_rules! check_special_key {
947 ($($char:literal # $name:ident # $($shifted:ident)? $(=> $($_muda:ident)? # $($qt:ident)|* # $($winit:ident $(($_pos:ident))?)|* # $($xkb:ident)|*)? ;)*) => {
948 match first_char {
949 $($(
950 $char => {
952 let _ = stringify!($($qt)|*); return stringify!($name).into();
954 }
955 )?)*
956 _ => ()
957 }
958 };
959 }
960 i_slint_common::for_each_keys!(check_special_key);
961 }
962
963 if key_str.chars().count() == 1 {
964 return key_str.to_uppercase().into();
965 }
966
967 key_str.into()
968 }
969}
970
971impl Display for Keys {
972 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
988 let inner = &self.inner;
989 if inner.key.is_empty() {
990 return Ok(());
991 }
992
993 if crate::is_apple_platform() {
994 if inner.modifiers.meta {
1001 f.write_str("⌃")?;
1002 }
1003 if !inner.ignore_alt && inner.modifiers.alt {
1004 f.write_str("⌥")?;
1005 }
1006 if !inner.ignore_shift && inner.modifiers.shift {
1007 f.write_str("⇧")?;
1008 }
1009 if inner.modifiers.control {
1010 f.write_str("⌘")?;
1011 }
1012 } else {
1013 let separator = "+";
1014
1015 let (ctrl_str, alt_str, shift_str, meta_str) =
1018 if crate::detect_operating_system() == OperatingSystemType::Windows {
1019 ("Ctrl", "Alt", "Shift", "Win")
1020 } else {
1021 ("Ctrl", "Alt", "Shift", "Super")
1022 };
1023
1024 if inner.modifiers.meta {
1025 f.write_str(meta_str)?;
1026 f.write_str(separator)?;
1027 }
1028 if inner.modifiers.control {
1029 f.write_str(ctrl_str)?;
1030 f.write_str(separator)?;
1031 }
1032 if !inner.ignore_alt && inner.modifiers.alt {
1033 f.write_str(alt_str)?;
1034 f.write_str(separator)?;
1035 }
1036 if !inner.ignore_shift && inner.modifiers.shift {
1037 f.write_str(shift_str)?;
1038 f.write_str(separator)?;
1039 }
1040 }
1041 f.write_str(&self.format_key_for_display())
1042 }
1043}
1044
1045impl core::fmt::Debug for Keys {
1046 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1048 let inner = &self.inner;
1049 if inner.key.is_empty() {
1051 write!(f, "")
1052 } else {
1053 let alt = inner
1054 .ignore_alt
1055 .then_some("Alt?+")
1056 .or(inner.modifiers.alt.then_some("Alt+"))
1057 .unwrap_or_default();
1058 let ctrl = if inner.modifiers.control { "Control+" } else { "" };
1059 let meta = if inner.modifiers.meta { "Meta+" } else { "" };
1060 let shift = inner
1061 .ignore_shift
1062 .then_some("Shift?+")
1063 .or(inner.modifiers.shift.then_some("Shift+"))
1064 .unwrap_or_default();
1065 let keycode: SharedString = inner
1066 .key
1067 .chars()
1068 .flat_map(|character| {
1069 let mut escaped = alloc::vec![];
1070 if character.is_control() {
1071 escaped.extend(character.escape_unicode());
1072 } else {
1073 escaped.push(character);
1074 }
1075 escaped
1076 })
1077 .collect();
1078 write!(f, "{meta}{ctrl}{alt}{shift}\"{keycode}\"")
1079 }
1080 }
1081}
1082
1083#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
1085#[repr(u8)]
1086pub enum KeyEventType {
1087 #[default]
1089 KeyPressed = 0,
1090 KeyReleased = 1,
1092 UpdateComposition = 2,
1095 CommitComposition = 3,
1097}
1098
1099#[derive(Default, Debug, Clone, PartialEq)]
1100pub struct InternalKeyEvent {
1102 pub key_event: KeyEvent,
1104 pub event_type: KeyEventType,
1106 #[cfg(target_os = "windows")]
1112 pub text_without_modifiers: SharedString,
1113 pub replacement_range: Option<core::ops::Range<i32>>,
1117 pub preedit_text: SharedString,
1119 pub preedit_selection: Option<core::ops::Range<i32>>,
1121 pub cursor_position: Option<i32>,
1123 pub anchor_position: Option<i32>,
1125}
1126
1127impl InternalKeyEvent {
1128 pub fn shortcut(&self) -> Option<StandardShortcut> {
1131 if self.key_event.modifiers.control && !self.key_event.modifiers.shift {
1132 match self.key_event.text.as_str() {
1133 #[cfg(not(target_arch = "wasm32"))]
1134 "c" => Some(StandardShortcut::Copy),
1135 #[cfg(not(target_arch = "wasm32"))]
1136 "x" => Some(StandardShortcut::Cut),
1137 #[cfg(not(target_arch = "wasm32"))]
1138 "v" => Some(StandardShortcut::Paste),
1139 "a" => Some(StandardShortcut::SelectAll),
1140 "f" => Some(StandardShortcut::Find),
1141 "s" => Some(StandardShortcut::Save),
1142 "p" => Some(StandardShortcut::Print),
1143 "z" => Some(StandardShortcut::Undo),
1144 #[cfg(target_os = "windows")]
1145 "y" => Some(StandardShortcut::Redo),
1146 "r" => Some(StandardShortcut::Refresh),
1147 _ => None,
1148 }
1149 } else if self.key_event.modifiers.control && self.key_event.modifiers.shift {
1150 match self.key_event.text.as_str() {
1151 #[cfg(not(target_os = "windows"))]
1152 "z" | "Z" => Some(StandardShortcut::Redo),
1153 _ => None,
1154 }
1155 } else {
1156 None
1157 }
1158 }
1159
1160 pub fn text_shortcut(&self) -> Option<TextShortcut> {
1163 let ke = &self.key_event;
1164 let keycode = ke.text.chars().next()?;
1165
1166 let is_apple = crate::is_apple_platform();
1167
1168 let move_mod = if is_apple {
1169 ke.modifiers.alt && !ke.modifiers.control && !ke.modifiers.meta
1170 } else {
1171 ke.modifiers.control && !ke.modifiers.alt && !ke.modifiers.meta
1172 };
1173
1174 if move_mod {
1175 match keycode {
1176 key_codes::LeftArrow => {
1177 return Some(TextShortcut::Move(TextCursorDirection::BackwardByWord));
1178 }
1179 key_codes::RightArrow => {
1180 return Some(TextShortcut::Move(TextCursorDirection::ForwardByWord));
1181 }
1182 key_codes::UpArrow => {
1183 return Some(TextShortcut::Move(TextCursorDirection::StartOfParagraph));
1184 }
1185 key_codes::DownArrow => {
1186 return Some(TextShortcut::Move(TextCursorDirection::EndOfParagraph));
1187 }
1188 key_codes::Backspace => {
1189 return Some(TextShortcut::DeleteWordBackward);
1190 }
1191 key_codes::Delete => {
1192 return Some(TextShortcut::DeleteWordForward);
1193 }
1194 _ => (),
1195 };
1196 }
1197
1198 #[cfg(not(target_os = "macos"))]
1199 {
1200 if ke.modifiers.control && !ke.modifiers.alt && !ke.modifiers.meta {
1201 match keycode {
1202 key_codes::Home => {
1203 return Some(TextShortcut::Move(TextCursorDirection::StartOfText));
1204 }
1205 key_codes::End => {
1206 return Some(TextShortcut::Move(TextCursorDirection::EndOfText));
1207 }
1208 _ => (),
1209 };
1210 }
1211 }
1212
1213 if is_apple && ke.modifiers.control {
1214 match keycode {
1215 key_codes::LeftArrow => {
1216 return Some(TextShortcut::Move(TextCursorDirection::StartOfLine));
1217 }
1218 key_codes::RightArrow => {
1219 return Some(TextShortcut::Move(TextCursorDirection::EndOfLine));
1220 }
1221 key_codes::UpArrow => {
1222 return Some(TextShortcut::Move(TextCursorDirection::StartOfText));
1223 }
1224 key_codes::DownArrow => {
1225 return Some(TextShortcut::Move(TextCursorDirection::EndOfText));
1226 }
1227 key_codes::Backspace => {
1228 return Some(TextShortcut::DeleteToStartOfLine);
1229 }
1230 _ => (),
1231 };
1232 }
1233
1234 if let Ok(direction) = TextCursorDirection::try_from(keycode) {
1235 Some(TextShortcut::Move(direction))
1236 } else {
1237 match keycode {
1238 key_codes::Backspace => Some(TextShortcut::DeleteBackward),
1239 key_codes::Delete => Some(TextShortcut::DeleteForward),
1240 _ => None,
1241 }
1242 }
1243 }
1244}
1245
1246pub enum StandardShortcut {
1248 Copy,
1250 Cut,
1252 Paste,
1254 SelectAll,
1256 Find,
1258 Save,
1260 Print,
1262 Undo,
1264 Redo,
1266 Refresh,
1268}
1269
1270pub enum TextShortcut {
1272 Move(TextCursorDirection),
1274 DeleteForward,
1276 DeleteBackward,
1278 DeleteWordForward,
1280 DeleteWordBackward,
1282 DeleteToStartOfLine,
1284}
1285
1286#[repr(u8)]
1289#[derive(Debug, Clone, Copy, PartialEq, Default)]
1290pub enum KeyEventResult {
1291 EventAccepted,
1293 #[default]
1295 EventIgnored,
1296}
1297
1298#[repr(u8)]
1301#[derive(Debug, Clone, Copy, PartialEq, Default)]
1302pub enum FocusEventResult {
1303 FocusAccepted,
1305 #[default]
1307 FocusIgnored,
1308}
1309
1310#[derive(Debug, Clone, Copy, PartialEq)]
1313#[repr(u8)]
1314pub enum FocusEvent {
1315 FocusIn(FocusReason),
1317 FocusOut(FocusReason),
1319}
1320
1321#[derive(Default)]
1323pub struct ClickState {
1324 click_count_time_stamp: Cell<Option<crate::animations::Instant>>,
1325 click_count: Cell<u8>,
1326 click_position: Cell<LogicalPoint>,
1327 click_button: Cell<PointerEventButton>,
1328}
1329
1330impl ClickState {
1331 fn restart(
1333 &self,
1334 position: LogicalPoint,
1335 button: PointerEventButton,
1336 now: crate::animations::Instant,
1337 ) {
1338 self.click_count.set(0);
1339 self.click_count_time_stamp.set(Some(now));
1340 self.click_position.set(position);
1341 self.click_button.set(button);
1342 }
1343
1344 pub fn reset(&self) {
1346 self.click_count.set(0);
1347 self.click_count_time_stamp.replace(None);
1348 }
1349
1350 pub fn check_repeat(&self, mouse_event: MouseEvent, ctx: &crate::SlintContext) -> MouseEvent {
1354 let click_interval = ctx.platform().click_interval();
1355 match mouse_event {
1356 MouseEvent::Pressed { position, button, touch_finger_id, .. } => {
1357 let instant_now = crate::animations::Instant::now(ctx);
1358
1359 if let Some(click_count_time_stamp) = self.click_count_time_stamp.get() {
1360 if instant_now - click_count_time_stamp < click_interval
1361 && button == self.click_button.get()
1362 && (position - self.click_position.get()).square_length() < 100 as _
1363 {
1364 self.click_count.set(self.click_count.get().wrapping_add(1));
1365 self.click_count_time_stamp.set(Some(instant_now));
1366 } else {
1367 self.restart(position, button, instant_now);
1368 }
1369 } else {
1370 self.restart(position, button, instant_now);
1371 }
1372
1373 return MouseEvent::Pressed {
1374 position,
1375 button,
1376 click_count: self.click_count.get(),
1377 touch_finger_id,
1378 };
1379 }
1380 MouseEvent::Released { position, button, touch_finger_id, .. } => {
1381 return MouseEvent::Released {
1382 position,
1383 button,
1384 click_count: self.click_count.get(),
1385 touch_finger_id,
1386 };
1387 }
1388 _ => {}
1389 };
1390
1391 mouse_event
1392 }
1393}
1394
1395#[derive(Clone)]
1397pub(crate) struct DragData {
1398 pub(crate) event: DropEvent,
1401 pub(crate) allowed: AllowedDragActions,
1403}
1404
1405#[derive(Default)]
1407pub struct MouseInputState {
1408 item_stack: Vec<(ItemWeak, InputEventFilterResult)>,
1411 observers: Vec<ItemWeak>,
1416 pub(crate) offset: LogicalPoint,
1418 grabbed: bool,
1420 pub(crate) drag_data: Option<DragData>,
1423 pub(crate) drag_source: Option<ItemWeak>,
1426 pub(crate) drop_target: Option<ItemWeak>,
1430 delayed: Option<(crate::timers::Timer, MouseEvent)>,
1431 delayed_exit_items: Vec<ItemWeak>,
1432 pub(crate) cursor: MouseCursorInner,
1433}
1434
1435impl MouseInputState {
1436 fn top_item(&self) -> Option<ItemRc> {
1438 self.item_stack.last().and_then(|x| x.0.upgrade())
1439 }
1440
1441 pub(crate) fn arm_in_window_drag(
1444 &mut self,
1445 drag_area: core::pin::Pin<&crate::items::DragArea>,
1446 source: ItemWeak,
1447 seed_position: crate::api::LogicalPosition,
1448 ) {
1449 let (mut drop_event, allowed) = drag_area.initial_drop_event();
1450 drop_event.position = seed_position;
1451 self.drag_data = Some(DragData { event: drop_event, allowed });
1452 self.drag_source = Some(source);
1453 drag_area.dragging.set(true);
1454 }
1455
1456 pub fn top_item_including_delayed(&self) -> Option<ItemRc> {
1458 self.delayed_exit_items.last().and_then(|x| x.upgrade()).or_else(|| self.top_item())
1459 }
1460
1461 pub fn has_delayed_event(&self) -> bool {
1463 self.delayed.is_some()
1464 }
1465
1466 pub fn drop_target_action(&self) -> Option<crate::items::DragAction> {
1469 let action = self
1470 .drop_target
1471 .as_ref()
1472 .and_then(|t| t.upgrade())
1473 .and_then(|i| i.downcast::<crate::items::DropArea>())
1474 .map(|d| d.as_pin_ref().current_action())?;
1475 (action != crate::items::DragAction::None).then_some(action)
1476 }
1477}
1478
1479pub(crate) struct MouseGrabResult {
1480 pub event: Option<MouseEvent>,
1483 pub accepted: bool,
1486}
1487
1488fn offer_native_drag(
1491 window_adapter: &Rc<dyn WindowAdapter>,
1492 drag_area: core::pin::Pin<&crate::items::DragArea>,
1493 source: ItemWeak,
1494 seed_position: crate::api::LogicalPosition,
1495 state: &mut MouseInputState,
1496) {
1497 let data = drag_area.data();
1498 if data.has_native_data() {
1499 let request = crate::window::DragRequest {
1500 data: data.clone(),
1501 allowed: drag_area.allowed_actions(),
1502 drag_image: drag_area.drag_image(),
1503 drag_image_offset: euclid::vec2(
1504 drag_area.drag_image_offset_x(),
1505 drag_area.drag_image_offset_y(),
1506 ),
1507 };
1508 if window_adapter.internal(crate::InternalToken).is_some_and(|i| i.start_drag(&request)) {
1509 let drag = crate::window::NativePendingDrag { request, source, seed_position };
1512 crate::window::WindowInner::from_pub(window_adapter.window())
1513 .set_native_drag(Some(drag));
1514 drag_area.dragging.set(true);
1515 return;
1516 }
1517 }
1518 state.arm_in_window_drag(drag_area, source, seed_position);
1520}
1521
1522pub(crate) fn handle_mouse_grab(
1524 mouse_event: &MouseEvent,
1525 window_adapter: &Rc<dyn WindowAdapter>,
1526 mouse_input_state: &mut MouseInputState,
1527) -> MouseGrabResult {
1528 if !mouse_input_state.grabbed || mouse_input_state.item_stack.is_empty() {
1529 return MouseGrabResult { event: Some(mouse_event.clone()), accepted: false };
1530 };
1531
1532 let mut event = mouse_event.clone();
1533 let mut intercept = false;
1534 let mut invalid = false;
1535
1536 event.translate(-mouse_input_state.offset.to_vector());
1537
1538 mouse_input_state.item_stack.retain(|it| {
1539 if invalid {
1540 return false;
1541 }
1542 let item = if let Some(item) = it.0.upgrade() {
1543 item
1544 } else {
1545 invalid = true;
1546 return false;
1547 };
1548 if intercept {
1549 item.borrow().as_ref().input_event(
1550 &MouseEvent::Exit,
1551 window_adapter,
1552 &item,
1553 &mut mouse_input_state.cursor,
1554 );
1555 return false;
1556 }
1557 let g = item.geometry();
1558 event.translate(-g.origin.to_vector());
1559 if window_adapter.renderer().supports_transformations()
1560 && let Some(inverse_transform) = item.inverse_children_transform()
1561 {
1562 event.transform(inverse_transform);
1563 }
1564
1565 let interested = matches!(
1566 it.1,
1567 InputEventFilterResult::ForwardAndInterceptGrab
1568 | InputEventFilterResult::DelayForwarding(_)
1569 );
1570
1571 if interested
1572 && item.borrow().as_ref().input_event_filter_before_children(
1573 &event,
1574 window_adapter,
1575 &item,
1576 &mut mouse_input_state.cursor,
1577 ) == InputEventFilterResult::Intercept
1578 {
1579 intercept = true;
1580 }
1581 true
1582 });
1583 if invalid {
1584 return MouseGrabResult { event: Some(mouse_event.clone()), accepted: false };
1585 }
1586
1587 let grabber = mouse_input_state.top_item().unwrap();
1588 let input_result = grabber.borrow().as_ref().input_event(
1589 &event,
1590 window_adapter,
1591 &grabber,
1592 &mut mouse_input_state.cursor,
1593 );
1594 match input_result {
1595 InputEventResult::GrabMouse => MouseGrabResult { event: None, accepted: true },
1596 InputEventResult::StartDrag => {
1597 mouse_input_state.grabbed = false;
1598 let drag_area_item = grabber.downcast::<crate::items::DragArea>().unwrap();
1599 let drag_area = drag_area_item.as_pin_ref();
1600 let seed_position = mouse_event
1603 .position()
1604 .map(crate::lengths::logical_position_to_api)
1605 .unwrap_or_default();
1606 offer_native_drag(
1607 window_adapter,
1608 drag_area,
1609 grabber.downgrade(),
1610 seed_position,
1611 mouse_input_state,
1612 );
1613 MouseGrabResult { event: None, accepted: true }
1614 }
1615 InputEventResult::EventAccepted | InputEventResult::EventIgnored => {
1616 mouse_input_state.grabbed = false;
1617 MouseGrabResult {
1619 event: Some(mouse_event.position().map_or(MouseEvent::Exit, |position| {
1620 MouseEvent::Moved { position, touch_finger_id: mouse_event.touch_finger_id() }
1621 })),
1622 accepted: input_result == InputEventResult::EventAccepted,
1623 }
1624 }
1625 }
1626}
1627
1628pub(crate) fn send_exit_events(
1629 old_input_state: &MouseInputState,
1630 new_input_state: &mut MouseInputState,
1631 mut pos: Option<LogicalPoint>,
1632 window_adapter: &Rc<dyn WindowAdapter>,
1633) {
1634 let cursor = &mut MouseCursorInner::BuiltIn(BuiltInMouseCursor::Default);
1636
1637 for it in core::mem::take(&mut new_input_state.delayed_exit_items) {
1638 let Some(item) = it.upgrade() else { continue };
1639 item.borrow().as_ref().input_event(&MouseEvent::Exit, window_adapter, &item, cursor);
1640 }
1641
1642 let mut clipped = false;
1643 for (idx, it) in old_input_state.item_stack.iter().enumerate() {
1644 let Some(item) = it.0.upgrade() else { break };
1645 let g = item.geometry();
1646 let contains = pos.is_some_and(|p| g.contains(p));
1647 if let Some(p) = pos.as_mut() {
1648 *p -= g.origin.to_vector();
1649 if window_adapter.renderer().supports_transformations()
1650 && let Some(inverse_transform) = item.inverse_children_transform()
1651 {
1652 *p = inverse_transform.transform_point(p.cast()).cast();
1653 }
1654 }
1655 if !contains || clipped {
1656 if item.borrow().as_ref().clips_children() {
1657 clipped = true;
1658 }
1659 item.borrow().as_ref().input_event(&MouseEvent::Exit, window_adapter, &item, cursor);
1660 } else if new_input_state.item_stack.get(idx).is_none_or(|(x, _)| *x != it.0) {
1661 if new_input_state.delayed.is_some() {
1663 new_input_state.delayed_exit_items.push(it.0.clone());
1664 } else {
1665 item.borrow().as_ref().input_event(
1666 &MouseEvent::Exit,
1667 window_adapter,
1668 &item,
1669 cursor,
1670 );
1671 }
1672 }
1673 }
1674
1675 for obs in &old_input_state.observers {
1681 if new_input_state.observers.iter().any(|x| x == obs)
1682 || new_input_state.item_stack.iter().any(|(x, _)| x == obs)
1683 {
1684 continue;
1685 }
1686 let Some(item) = obs.upgrade() else { continue };
1687 item.borrow().as_ref().input_event(&MouseEvent::Exit, window_adapter, &item, cursor);
1688 }
1689}
1690
1691pub struct MouseInputResult {
1693 pub state: MouseInputState,
1695 pub accepted: bool,
1698}
1699
1700pub fn process_mouse_input(
1704 root: ItemRc,
1705 mouse_event: &MouseEvent,
1706 window_adapter: &Rc<dyn WindowAdapter>,
1707 mut mouse_input_state: MouseInputState,
1708) -> MouseInputResult {
1709 let mut result = MouseInputState {
1710 drag_data: mouse_input_state.drag_data.clone(),
1711 drag_source: mouse_input_state.drag_source.clone(),
1712 drop_target: mouse_input_state.drop_target.clone(),
1713 cursor: mouse_input_state.cursor.clone(),
1714 ..Default::default()
1715 };
1716 let r = send_mouse_event_to_item(
1717 mouse_event,
1718 root.clone(),
1719 window_adapter,
1720 &mut result,
1721 mouse_input_state.top_item().as_ref(),
1722 false,
1723 );
1724 let accepted = r.has_aborted();
1725 if matches!(mouse_event, MouseEvent::DragMove { .. }) {
1726 result.drop_target =
1729 accepted.then(|| result.item_stack.last().map(|(w, _)| w.clone())).flatten();
1730 }
1731 if mouse_input_state.delayed.is_some()
1732 && (!accepted
1733 || Option::zip(result.item_stack.last(), mouse_input_state.item_stack.last())
1734 .is_none_or(|(a, b)| a.0 != b.0))
1735 {
1736 mouse_input_state.cursor = result.cursor;
1738 return MouseInputResult { state: mouse_input_state, accepted };
1739 }
1740 send_exit_events(&mouse_input_state, &mut result, mouse_event.position(), window_adapter);
1741
1742 if let MouseEvent::Wheel { position, .. } = mouse_event
1743 && accepted
1744 {
1745 let moved = process_mouse_input(
1749 root,
1750 &MouseEvent::Moved { position: *position, touch_finger_id: 0 },
1751 window_adapter,
1752 result,
1753 );
1754 return MouseInputResult { state: moved.state, accepted: true };
1755 }
1756
1757 MouseInputResult { state: result, accepted }
1758}
1759
1760pub(crate) fn process_delayed_event(
1761 window_adapter: &Rc<dyn WindowAdapter>,
1762 mut mouse_input_state: MouseInputState,
1763) -> MouseInputState {
1764 let event = match mouse_input_state.delayed.take() {
1766 Some(e) => e.1,
1767 None => return mouse_input_state,
1768 };
1769
1770 let top_item = match mouse_input_state.top_item() {
1771 Some(i) => i,
1772 None => return MouseInputState::default(),
1773 };
1774
1775 let prev_target = mouse_input_state.delayed_exit_items.last().and_then(|x| x.upgrade());
1777 let last_top_item = prev_target.as_ref().unwrap_or(&top_item);
1778
1779 let mut actual_visitor =
1780 |component: &ItemTreeRc, index: u32, _: Pin<ItemRef>| -> VisitChildrenResult {
1781 send_mouse_event_to_item(
1782 &event,
1783 ItemRc::new(component.clone(), index),
1784 window_adapter,
1785 &mut mouse_input_state,
1786 Some(last_top_item),
1787 true,
1788 )
1789 };
1790 vtable::new_vref!(let mut actual_visitor : VRefMut<crate::item_tree::ItemVisitorVTable> for crate::item_tree::ItemVisitor = &mut actual_visitor);
1791 vtable::VRc::borrow_pin(top_item.item_tree()).as_ref().visit_children_item(
1792 top_item.index() as isize,
1793 crate::item_tree::TraversalOrder::FrontToBack,
1794 actual_visitor,
1795 );
1796 mouse_input_state
1797}
1798
1799fn send_mouse_event_to_item(
1800 mouse_event: &MouseEvent,
1801 item_rc: ItemRc,
1802 window_adapter: &Rc<dyn WindowAdapter>,
1803 result: &mut MouseInputState,
1804 last_top_item: Option<&ItemRc>,
1805 ignore_delays: bool,
1806) -> VisitChildrenResult {
1807 let item = item_rc.borrow();
1808 let geom = item_rc.geometry();
1809 let mut event_for_children = mouse_event.clone();
1811 event_for_children.translate(-geom.origin.to_vector());
1813 if window_adapter.renderer().supports_transformations() {
1814 if let Some(inverse_transform) = item_rc.inverse_children_transform() {
1816 event_for_children.transform(inverse_transform);
1817 }
1818 }
1819
1820 let filter_result = if mouse_event.position().is_some_and(|p| geom.contains(p))
1821 || item.as_ref().clips_children()
1822 {
1823 item.as_ref().input_event_filter_before_children(
1824 &event_for_children,
1825 window_adapter,
1826 &item_rc,
1827 &mut result.cursor,
1828 )
1829 } else {
1830 InputEventFilterResult::ForwardAndIgnore
1831 };
1832
1833 let (forward_to_children, ignore) = match filter_result {
1834 InputEventFilterResult::ForwardEvent => (true, false),
1835 InputEventFilterResult::ForwardAndIgnore => (true, true),
1836 InputEventFilterResult::ForwardAndInterceptGrab => (true, false),
1837 InputEventFilterResult::Intercept => (false, false),
1838 InputEventFilterResult::DelayForwarding(_) if ignore_delays => (true, false),
1839 InputEventFilterResult::DelayForwarding(duration) => {
1840 let timer = WindowInner::from_pub(window_adapter.window()).context().new_timer();
1841 let w = Rc::downgrade(window_adapter);
1842 timer.start(
1843 crate::timers::TimerMode::SingleShot,
1844 Duration::from_millis(duration),
1845 move || {
1846 if let Some(w) = w.upgrade() {
1847 WindowInner::from_pub(w.window()).process_delayed_event();
1848 }
1849 },
1850 );
1851 result.delayed = Some((timer, event_for_children));
1852 result
1853 .item_stack
1854 .push((item_rc.downgrade(), InputEventFilterResult::DelayForwarding(duration)));
1855 return VisitChildrenResult::abort(item_rc.index(), 0);
1856 }
1857 InputEventFilterResult::ForwardAndObserve => (true, true),
1861 };
1862
1863 result.item_stack.push((item_rc.downgrade(), filter_result));
1864 if forward_to_children {
1865 let mut actual_visitor =
1866 |component: &ItemTreeRc, index: u32, _: Pin<ItemRef>| -> VisitChildrenResult {
1867 send_mouse_event_to_item(
1868 &event_for_children,
1869 ItemRc::new(component.clone(), index),
1870 window_adapter,
1871 result,
1872 last_top_item,
1873 ignore_delays,
1874 )
1875 };
1876 vtable::new_vref!(let mut actual_visitor : VRefMut<crate::item_tree::ItemVisitorVTable> for crate::item_tree::ItemVisitor = &mut actual_visitor);
1877 let r = vtable::VRc::borrow_pin(item_rc.item_tree()).as_ref().visit_children_item(
1878 item_rc.index() as isize,
1879 crate::item_tree::TraversalOrder::FrontToBack,
1880 actual_visitor,
1881 );
1882 if r.has_aborted() {
1883 return r;
1884 }
1885 };
1886
1887 let r = if ignore {
1888 InputEventResult::EventIgnored
1889 } else {
1890 let mut event = mouse_event.clone();
1891 event.translate(-geom.origin.to_vector());
1892 if last_top_item.is_none_or(|x| *x != item_rc) {
1893 event.set_click_count(0);
1894 }
1895 item.as_ref().input_event(&event, window_adapter, &item_rc, &mut result.cursor)
1896 };
1897 match r {
1898 InputEventResult::EventAccepted => VisitChildrenResult::abort(item_rc.index(), 0),
1899 InputEventResult::EventIgnored => {
1900 let popped = result.item_stack.pop();
1901 debug_assert_eq!(
1902 popped.as_ref().map(|x| (x.0.upgrade().unwrap().index(), x.1)).unwrap(),
1903 (item_rc.index(), filter_result)
1904 );
1905 if filter_result == InputEventFilterResult::ForwardAndObserve
1908 && let Some((weak, _)) = popped
1909 && !result.observers.contains(&weak)
1910 {
1911 result.observers.push(weak);
1912 }
1913 VisitChildrenResult::CONTINUE
1914 }
1915 InputEventResult::GrabMouse => {
1916 result.item_stack.last_mut().unwrap().1 =
1917 InputEventFilterResult::ForwardAndInterceptGrab;
1918 result.grabbed = true;
1919 VisitChildrenResult::abort(item_rc.index(), 0)
1920 }
1921 InputEventResult::StartDrag => {
1922 result.item_stack.last_mut().unwrap().1 =
1923 InputEventFilterResult::ForwardAndInterceptGrab;
1924 result.grabbed = false;
1925 let drag_area_item = item_rc.downcast::<crate::items::DragArea>().unwrap();
1926 let drag_area = drag_area_item.as_pin_ref();
1927 let seed_position = mouse_event
1931 .position()
1932 .map(|p| p - geom.origin.to_vector())
1933 .map(|p| item_rc.map_to_window(p))
1934 .map(crate::lengths::logical_position_to_api)
1935 .unwrap_or_default();
1936 offer_native_drag(
1937 window_adapter,
1938 drag_area,
1939 item_rc.downgrade(),
1940 seed_position,
1941 result,
1942 );
1943 VisitChildrenResult::abort(item_rc.index(), 0)
1944 }
1945 }
1946}
1947
1948#[derive(FieldOffsets)]
1955#[repr(C)]
1956#[pin]
1957pub(crate) struct TextCursorBlinker {
1958 cursor_visible: Property<bool>,
1959 cursor_blink_timer: crate::timers::Timer,
1960}
1961
1962impl TextCursorBlinker {
1963 pub fn new() -> Pin<Rc<Self>> {
1966 Rc::pin(Self {
1967 cursor_visible: Property::new(true),
1968 cursor_blink_timer: Default::default(),
1969 })
1970 }
1971
1972 pub fn set_binding(
1975 instance: Pin<Rc<TextCursorBlinker>>,
1976 prop: &Property<bool>,
1977 ctx: &crate::SlintContext,
1978 cycle_duration: Duration,
1979 ) {
1980 instance.as_ref().cursor_visible.set(true);
1981 Self::start(&instance, ctx, cycle_duration);
1983 prop.set_binding(move || {
1984 TextCursorBlinker::FIELD_OFFSETS.cursor_visible().apply_pin(instance.as_ref()).get()
1985 });
1986 }
1987
1988 pub fn start(self: &Pin<Rc<Self>>, ctx: &crate::SlintContext, cycle_duration: Duration) {
1991 if self.cursor_blink_timer.running() {
1992 self.cursor_blink_timer.restart();
1993 } else {
1994 let toggle_cursor = {
1995 let weak_blinker = pin_weak::rc::PinWeak::downgrade(self.clone());
1996 move || {
1997 if let Some(blinker) = weak_blinker.upgrade() {
1998 let visible = TextCursorBlinker::FIELD_OFFSETS
1999 .cursor_visible()
2000 .apply_pin(blinker.as_ref())
2001 .get();
2002 blinker.cursor_visible.set(!visible);
2003 }
2004 }
2005 };
2006 if !cycle_duration.is_zero() {
2007 self.cursor_blink_timer.start_on(
2008 ctx,
2009 crate::timers::TimerMode::Repeated,
2010 cycle_duration / 2,
2011 toggle_cursor,
2012 );
2013 }
2014 }
2015 }
2016
2017 pub fn stop(&self) {
2020 self.cursor_blink_timer.stop()
2021 }
2022}
2023
2024#[derive(Clone, Copy, Default)]
2026struct TouchPoint {
2027 id: i32,
2028 position: LogicalPoint,
2029}
2030
2031const MAX_TRACKED_TOUCHES: usize = 5;
2037
2038#[derive(Clone)]
2039struct TouchMap {
2040 entries: [TouchPoint; MAX_TRACKED_TOUCHES],
2041 len: usize,
2042}
2043
2044impl Default for TouchMap {
2045 fn default() -> Self {
2046 Self { entries: [TouchPoint::default(); MAX_TRACKED_TOUCHES], len: 0 }
2047 }
2048}
2049
2050impl TouchMap {
2051 fn get(&self, id: i32) -> Option<&TouchPoint> {
2052 self.entries[..self.len].iter().find(|tp| tp.id == id)
2053 }
2054
2055 fn get_mut(&mut self, id: i32) -> Option<&mut TouchPoint> {
2056 self.entries[..self.len].iter_mut().find(|tp| tp.id == id)
2057 }
2058
2059 fn insert(&mut self, point: TouchPoint) {
2060 if let Some(existing) = self.entries[..self.len].iter_mut().find(|tp| tp.id == point.id) {
2061 *existing = point;
2062 } else if self.len < MAX_TRACKED_TOUCHES {
2063 self.entries[self.len] = point;
2064 self.len += 1;
2065 }
2066 }
2067
2068 fn remove(&mut self, id: i32) {
2069 if let Some(idx) = self.entries[..self.len].iter().position(|tp| tp.id == id) {
2070 self.len -= 1;
2071 self.entries[idx] = self.entries[self.len];
2072 }
2073 }
2074
2075 fn len(&self) -> usize {
2076 self.len
2077 }
2078
2079 fn first_two_ids(&self) -> Option<(i32, i32)> {
2081 if self.len >= 2 { Some((self.entries[0].id, self.entries[1].id)) } else { None }
2082 }
2083
2084 fn first(&self) -> Option<&TouchPoint> {
2086 if self.len > 0 { Some(&self.entries[0]) } else { None }
2087 }
2088}
2089
2090const MAX_TOUCH_EVENTS: usize = 4;
2096
2097#[derive(Clone)]
2098pub(crate) struct TouchEventBuffer {
2099 events: [Option<MouseEvent>; MAX_TOUCH_EVENTS],
2100 len: usize,
2101}
2102
2103impl TouchEventBuffer {
2104 fn new() -> Self {
2105 Self { events: [None, None, None, None], len: 0 }
2106 }
2107
2108 fn push(&mut self, event: MouseEvent) {
2109 debug_assert!(self.len < MAX_TOUCH_EVENTS, "TouchEventBuffer overflow");
2110 if self.len < MAX_TOUCH_EVENTS {
2111 self.events[self.len] = Some(event);
2112 self.len += 1;
2113 }
2114 }
2115
2116 pub(crate) fn into_iter(self) -> impl Iterator<Item = MouseEvent> {
2118 let len = self.len;
2119 self.events.into_iter().take(len).flatten()
2120 }
2121}
2122
2123#[derive(Default, Debug, Clone, Copy)]
2125enum GestureRecognitionState {
2126 #[default]
2128 Idle,
2129 TwoFingersDown { finger_ids: (i32, i32), initial_distance: f32, last_angle: euclid::Angle<f32> },
2131 Pinching {
2133 finger_ids: (i32, i32),
2134 initial_distance: f32,
2135 last_scale: f32,
2136 last_angle: euclid::Angle<f32>,
2137 },
2138}
2139
2140pub(crate) struct TouchState {
2147 active_touches: TouchMap,
2148 primary_touch_id: Option<i32>,
2150 gesture_state: GestureRecognitionState,
2151}
2152
2153impl Default for TouchState {
2154 fn default() -> Self {
2155 Self {
2156 active_touches: TouchMap::default(),
2157 primary_touch_id: None,
2158 gesture_state: GestureRecognitionState::Idle,
2159 }
2160 }
2161}
2162
2163impl TouchState {
2164 const PINCH_THRESHOLD: f32 = 8.0;
2166
2167 const ROTATION_THRESHOLD: f32 = 5.0;
2169
2170 fn gesture_finger_ids(&self) -> Option<(i32, i32)> {
2172 match self.gesture_state {
2173 GestureRecognitionState::TwoFingersDown { finger_ids, .. }
2174 | GestureRecognitionState::Pinching { finger_ids, .. } => Some(finger_ids),
2175 GestureRecognitionState::Idle => None,
2176 }
2177 }
2178
2179 fn geometry_for(&self, (id_a, id_b): (i32, i32)) -> Option<(f32, euclid::Angle<f32>)> {
2181 let a = self.active_touches.get(id_a)?;
2182 let b = self.active_touches.get(id_b)?;
2183 let delta = (b.position - a.position).cast::<f32>();
2184 Some((delta.length(), delta.angle_from_x_axis()))
2185 }
2186
2187 fn gesture_finger_positions(&self) -> Option<(&TouchPoint, &TouchPoint)> {
2189 let (id_a, id_b) = self.gesture_finger_ids()?;
2190 let a = self.active_touches.get(id_a)?;
2191 let b = self.active_touches.get(id_b)?;
2192 Some((a, b))
2193 }
2194
2195 fn gesture_midpoint(&self) -> Option<LogicalPoint> {
2197 let (a, b) = self.gesture_finger_positions()?;
2198 let mid = a.position.cast::<f32>().lerp(b.position.cast::<f32>(), 0.5);
2199 Some(mid.cast())
2200 }
2201
2202 fn gesture_geometry(&self) -> Option<(f32, euclid::Angle<f32>)> {
2204 let (a, b) = self.gesture_finger_positions()?;
2205 let delta = (b.position - a.position).cast::<f32>();
2206 Some((delta.length(), delta.angle_from_x_axis()))
2207 }
2208
2209 fn is_gesture_finger(&self, id: i32) -> bool {
2211 self.gesture_finger_ids().is_some_and(|(a, b)| id == a || id == b)
2212 }
2213
2214 pub(crate) fn process(
2221 &mut self,
2222 id: i32,
2223 position: LogicalPoint,
2224 phase: TouchPhase,
2225 ) -> TouchEventBuffer {
2226 let mut events = TouchEventBuffer::new();
2227 match phase {
2228 TouchPhase::Started => self.process_started(id, position, &mut events),
2229 TouchPhase::Moved => self.process_moved(id, position, &mut events),
2230 TouchPhase::Ended => self.process_ended(id, position, false, &mut events),
2231 TouchPhase::Cancelled => self.process_ended(id, position, true, &mut events),
2232 }
2233 events
2234 }
2235
2236 fn process_started(&mut self, id: i32, position: LogicalPoint, events: &mut TouchEventBuffer) {
2237 self.active_touches.insert(TouchPoint { id, position });
2238
2239 let total = self.active_touches.len();
2240 if total == 1 {
2241 self.primary_touch_id = Some(id);
2243 self.gesture_state = GestureRecognitionState::Idle;
2244 events.push(MouseEvent::Pressed {
2245 position,
2246 button: PointerEventButton::Left,
2247 click_count: 0,
2248 touch_finger_id: id + 1,
2249 });
2250 } else if total == 2 {
2251 let finger_ids = self.active_touches.first_two_ids().unwrap_or((0, 0));
2253
2254 let primary_pos = self
2257 .primary_touch_id
2258 .and_then(|pid| self.active_touches.get(pid))
2259 .map(|tp| tp.position)
2260 .unwrap_or(position);
2261
2262 let (initial_distance, last_angle) =
2264 self.geometry_for(finger_ids).unwrap_or((0.0, euclid::Angle::zero()));
2265 self.gesture_state = GestureRecognitionState::TwoFingersDown {
2266 finger_ids,
2267 initial_distance,
2268 last_angle,
2269 };
2270
2271 events.push(MouseEvent::Released {
2272 position: primary_pos,
2273 button: PointerEventButton::Left,
2274 click_count: 0,
2275 touch_finger_id: id + 1,
2276 });
2277 }
2278 }
2280
2281 #[allow(clippy::collapsible_match)]
2282 fn process_moved(&mut self, id: i32, position: LogicalPoint, events: &mut TouchEventBuffer) {
2283 if let Some(tp) = self.active_touches.get_mut(id) {
2284 tp.position = position;
2285 }
2286
2287 let is_gesture_finger = self.is_gesture_finger(id);
2288
2289 match self.gesture_state {
2290 GestureRecognitionState::Idle => {
2291 if self.primary_touch_id == Some(id) {
2292 events.push(MouseEvent::Moved { position, touch_finger_id: id + 1 });
2293 }
2294 }
2295 GestureRecognitionState::TwoFingersDown {
2296 finger_ids,
2297 initial_distance,
2298 last_angle,
2299 } if is_gesture_finger => {
2300 if let Some((dist, angle)) = self.gesture_geometry() {
2301 let delta_dist = (dist - initial_distance).abs();
2302 let delta_angle = (angle - last_angle).signed().to_degrees().abs();
2303 if delta_dist > Self::PINCH_THRESHOLD || delta_angle > Self::ROTATION_THRESHOLD
2304 {
2305 self.gesture_state = GestureRecognitionState::Pinching {
2309 finger_ids,
2310 initial_distance: dist,
2311 last_scale: 1.0,
2312 last_angle: angle,
2313 };
2314
2315 let midpoint = self.gesture_midpoint().unwrap_or(position);
2316
2317 events.push(MouseEvent::PinchGesture {
2318 position: midpoint,
2319 delta: 0.0,
2320 phase: TouchPhase::Started,
2321 });
2322 events.push(MouseEvent::RotationGesture {
2323 position: midpoint,
2324 delta: 0.0,
2325 phase: TouchPhase::Started,
2326 });
2327 }
2328 }
2329 }
2330 GestureRecognitionState::Pinching {
2331 initial_distance, last_scale, last_angle, ..
2332 } if is_gesture_finger => {
2333 if let Some((dist, angle)) = self.gesture_geometry() {
2334 let midpoint = self.gesture_midpoint().unwrap_or(position);
2335
2336 let current_scale =
2337 if initial_distance > 0.0 { dist / initial_distance } else { 1.0 };
2338 let scale_delta = current_scale - last_scale;
2339
2340 let rotation_delta = (angle - last_angle).signed().to_degrees();
2343
2344 if let GestureRecognitionState::Pinching {
2346 last_scale: ref mut ls,
2347 last_angle: ref mut la,
2348 ..
2349 } = self.gesture_state
2350 {
2351 *ls = current_scale;
2352 *la = angle;
2353 }
2354
2355 events.push(MouseEvent::PinchGesture {
2356 position: midpoint,
2357 delta: scale_delta,
2358 phase: TouchPhase::Moved,
2359 });
2360 events.push(MouseEvent::RotationGesture {
2361 position: midpoint,
2362 delta: rotation_delta,
2363 phase: TouchPhase::Moved,
2364 });
2365 }
2366 }
2367 _ => {}
2368 }
2369 }
2370
2371 #[allow(clippy::collapsible_match)]
2372 fn process_ended(
2373 &mut self,
2374 id: i32,
2375 position: LogicalPoint,
2376 is_cancelled: bool,
2377 events: &mut TouchEventBuffer,
2378 ) {
2379 let is_gesture_finger = self.is_gesture_finger(id);
2381 let midpoint = self.gesture_midpoint().unwrap_or(position);
2382 self.active_touches.remove(id);
2383
2384 match self.gesture_state {
2385 GestureRecognitionState::Idle => {
2386 if self.primary_touch_id == Some(id) {
2387 self.primary_touch_id = None;
2388 events.push(MouseEvent::Released {
2389 position,
2390 button: PointerEventButton::Left,
2391 click_count: 0,
2392 touch_finger_id: id + 1,
2393 });
2394 events.push(MouseEvent::Exit);
2395 }
2396 }
2397 GestureRecognitionState::TwoFingersDown { .. } if is_gesture_finger => {
2398 self.gesture_state = GestureRecognitionState::Idle;
2399 if !is_cancelled {
2400 if let Some(remaining) = self.active_touches.first() {
2401 let remaining_pos = remaining.position;
2402 self.primary_touch_id = Some(remaining.id);
2403 events.push(MouseEvent::Pressed {
2404 position: remaining_pos,
2405 button: PointerEventButton::Left,
2406 click_count: 0,
2407 touch_finger_id: remaining.id + 1,
2408 });
2409 } else {
2410 self.primary_touch_id = None;
2411 events.push(MouseEvent::Exit);
2412 }
2413 } else {
2414 self.primary_touch_id = None;
2415 events.push(MouseEvent::Exit);
2416 }
2417 }
2418 GestureRecognitionState::Pinching { .. } if is_gesture_finger => {
2419 self.gesture_state = GestureRecognitionState::Idle;
2420
2421 let gesture_phase =
2422 if is_cancelled { TouchPhase::Cancelled } else { TouchPhase::Ended };
2423
2424 let remaining = if !is_cancelled {
2425 self.active_touches.first().map(|tp| (tp.id, tp.position))
2426 } else {
2427 None
2428 };
2429 if let Some((rid, _)) = remaining {
2430 self.primary_touch_id = Some(rid);
2431 } else {
2432 self.primary_touch_id = None;
2433 }
2434
2435 events.push(MouseEvent::PinchGesture {
2436 position: midpoint,
2437 delta: 0.0,
2438 phase: gesture_phase,
2439 });
2440 events.push(MouseEvent::RotationGesture {
2441 position: midpoint,
2442 delta: 0.0,
2443 phase: gesture_phase,
2444 });
2445
2446 if let Some((rid, rpos)) = remaining {
2447 events.push(MouseEvent::Pressed {
2448 position: rpos,
2449 button: PointerEventButton::Left,
2450 click_count: 0,
2451 touch_finger_id: rid + 1,
2452 });
2453 } else {
2454 events.push(MouseEvent::Exit);
2455 }
2456 }
2457 _ => {}
2458 }
2459 }
2460}
2461
2462#[cfg(test)]
2463mod touch_tests {
2464 extern crate alloc;
2465 use alloc::vec;
2466 use alloc::vec::Vec;
2467
2468 use super::*;
2469 use crate::lengths::LogicalPoint;
2470
2471 fn pt(x: f32, y: f32) -> LogicalPoint {
2472 euclid::point2(x, y)
2473 }
2474
2475 #[test]
2480 fn touch_map_insert_and_get() {
2481 let mut map = TouchMap::default();
2482 assert_eq!(map.len(), 0);
2483 map.insert(TouchPoint { id: 1, position: pt(10.0, 20.0) });
2484 assert_eq!(map.len(), 1);
2485 assert!(map.get(1).is_some());
2486 assert!((map.get(1).unwrap().position.x - 10.0).abs() < f32::EPSILON);
2487 assert!(map.get(2).is_none());
2488 }
2489
2490 #[test]
2491 fn touch_map_update_existing() {
2492 let mut map = TouchMap::default();
2493 map.insert(TouchPoint { id: 1, position: pt(10.0, 20.0) });
2494 map.insert(TouchPoint { id: 1, position: pt(30.0, 40.0) });
2495 assert_eq!(map.len(), 1);
2496 assert!((map.get(1).unwrap().position.x - 30.0).abs() < f32::EPSILON);
2497 }
2498
2499 #[test]
2500 fn touch_map_remove() {
2501 let mut map = TouchMap::default();
2502 map.insert(TouchPoint { id: 1, position: pt(10.0, 20.0) });
2503 map.insert(TouchPoint { id: 2, position: pt(30.0, 40.0) });
2504 assert_eq!(map.len(), 2);
2505 map.remove(1);
2506 assert_eq!(map.len(), 1);
2507 assert!(map.get(1).is_none());
2508 assert!(map.get(2).is_some());
2509 }
2510
2511 #[test]
2512 fn touch_map_remove_nonexistent() {
2513 let mut map = TouchMap::default();
2514 map.insert(TouchPoint { id: 1, position: pt(10.0, 20.0) });
2515 map.remove(99);
2516 assert_eq!(map.len(), 1);
2517 }
2518
2519 #[test]
2520 fn touch_map_capacity() {
2521 let mut map = TouchMap::default();
2522 for i in 0..MAX_TRACKED_TOUCHES {
2523 map.insert(TouchPoint { id: i as i32, position: pt(i as f32, 0.0) });
2524 }
2525 assert_eq!(map.len(), MAX_TRACKED_TOUCHES);
2526 map.insert(TouchPoint { id: 99, position: pt(99.0, 0.0) });
2528 assert_eq!(map.len(), MAX_TRACKED_TOUCHES);
2529 assert!(map.get(99).is_none());
2530 }
2531
2532 #[test]
2533 fn touch_map_first_two_ids() {
2534 let mut map = TouchMap::default();
2535 assert!(map.first_two_ids().is_none());
2536 map.insert(TouchPoint { id: 5, position: pt(0.0, 0.0) });
2537 assert!(map.first_two_ids().is_none());
2538 map.insert(TouchPoint { id: 10, position: pt(0.0, 0.0) });
2539 assert_eq!(map.first_two_ids(), Some((5, 10)));
2540 }
2541
2542 #[test]
2543 fn touch_map_first() {
2544 let mut map = TouchMap::default();
2545 assert!(map.first().is_none());
2546 map.insert(TouchPoint { id: 7, position: pt(1.0, 2.0) });
2547 let tp = map.first().unwrap();
2548 assert_eq!(tp.id, 7);
2549 assert!((tp.position.x - 1.0).abs() < f32::EPSILON);
2550 }
2551
2552 #[test]
2553 fn touch_map_get_mut() {
2554 let mut map = TouchMap::default();
2555 map.insert(TouchPoint { id: 1, position: pt(0.0, 0.0) });
2556 map.get_mut(1).unwrap().position = pt(5.0, 6.0);
2557 assert!((map.get(1).unwrap().position.x - 5.0).abs() < f32::EPSILON);
2558 }
2559
2560 #[derive(Debug, PartialEq)]
2565 enum Ev {
2566 Pressed(f32, f32),
2567 Released(f32, f32),
2568 Moved(f32, f32),
2569 Exit,
2570 PinchStarted,
2571 PinchMoved(f32),
2572 PinchEnded,
2573 PinchCancelled,
2574 RotationStarted,
2575 RotationMoved(f32),
2576 RotationEnded,
2577 RotationCancelled,
2578 }
2579
2580 fn classify(events: &TouchEventBuffer) -> Vec<Ev> {
2581 events
2582 .clone()
2583 .into_iter()
2584 .map(|e| match e {
2585 MouseEvent::Pressed { position, .. } => Ev::Pressed(position.x, position.y),
2586 MouseEvent::Released { position, .. } => Ev::Released(position.x, position.y),
2587 MouseEvent::Moved { position, .. } => Ev::Moved(position.x, position.y),
2588 MouseEvent::Exit => Ev::Exit,
2589 MouseEvent::PinchGesture { delta, phase, .. } => match phase {
2590 TouchPhase::Started => Ev::PinchStarted,
2591 TouchPhase::Moved => Ev::PinchMoved(delta),
2592 TouchPhase::Ended => Ev::PinchEnded,
2593 TouchPhase::Cancelled => Ev::PinchCancelled,
2594 },
2595 MouseEvent::RotationGesture { delta, phase, .. } => match phase {
2596 TouchPhase::Started => Ev::RotationStarted,
2597 TouchPhase::Moved => Ev::RotationMoved(delta),
2598 TouchPhase::Ended => Ev::RotationEnded,
2599 TouchPhase::Cancelled => Ev::RotationCancelled,
2600 },
2601 _ => panic!("unexpected event: {:?}", e),
2602 })
2603 .collect()
2604 }
2605
2606 #[test]
2611 fn single_finger_press_move_release() {
2612 let mut state = TouchState::default();
2613
2614 let evs = state.process(1, pt(100.0, 200.0), TouchPhase::Started);
2615 assert_eq!(classify(&evs), vec![Ev::Pressed(100.0, 200.0)]);
2616
2617 let evs = state.process(1, pt(110.0, 200.0), TouchPhase::Moved);
2618 assert_eq!(classify(&evs), vec![Ev::Moved(110.0, 200.0)]);
2619
2620 let evs = state.process(1, pt(110.0, 200.0), TouchPhase::Ended);
2621 assert_eq!(classify(&evs), vec![Ev::Released(110.0, 200.0), Ev::Exit]);
2622 }
2623
2624 #[test]
2625 fn single_finger_cancel() {
2626 let mut state = TouchState::default();
2627
2628 state.process(1, pt(100.0, 200.0), TouchPhase::Started);
2629
2630 let evs = state.process(1, pt(100.0, 200.0), TouchPhase::Cancelled);
2631 assert_eq!(classify(&evs), vec![Ev::Released(100.0, 200.0), Ev::Exit]);
2632 }
2633
2634 #[test]
2635 fn non_primary_move_ignored() {
2636 let mut state = TouchState::default();
2637 state.process(1, pt(100.0, 200.0), TouchPhase::Started);
2639
2640 let evs = state.process(99, pt(50.0, 50.0), TouchPhase::Moved);
2642 assert!(classify(&evs).is_empty());
2643 }
2644
2645 #[test]
2650 fn two_fingers_synthesize_release_then_gesture() {
2651 let mut state = TouchState::default();
2652
2653 let evs = state.process(1, pt(100.0, 200.0), TouchPhase::Started);
2655 assert_eq!(classify(&evs), vec![Ev::Pressed(100.0, 200.0)]);
2656
2657 let evs = state.process(2, pt(200.0, 200.0), TouchPhase::Started);
2659 assert_eq!(classify(&evs), vec![Ev::Released(100.0, 200.0)]);
2660 assert!(matches!(state.gesture_state, GestureRecognitionState::TwoFingersDown { .. }));
2661
2662 let evs = state.process(2, pt(220.0, 200.0), TouchPhase::Moved);
2664 assert_eq!(classify(&evs), vec![Ev::PinchStarted, Ev::RotationStarted]);
2665 assert!(matches!(state.gesture_state, GestureRecognitionState::Pinching { .. }));
2666 }
2667
2668 #[test]
2669 fn two_fingers_below_threshold_no_gesture() {
2670 let mut state = TouchState::default();
2671
2672 state.process(1, pt(100.0, 200.0), TouchPhase::Started);
2673 state.process(2, pt(200.0, 200.0), TouchPhase::Started);
2674
2675 let evs = state.process(2, pt(202.0, 200.0), TouchPhase::Moved);
2677 assert!(classify(&evs).is_empty());
2678 assert!(matches!(state.gesture_state, GestureRecognitionState::TwoFingersDown { .. }));
2679 }
2680
2681 #[test]
2682 fn pinch_produces_scale_deltas() {
2683 let mut state = TouchState::default();
2684
2685 state.process(1, pt(0.0, 0.0), TouchPhase::Started);
2687 state.process(2, pt(100.0, 0.0), TouchPhase::Started);
2688
2689 state.process(2, pt(120.0, 0.0), TouchPhase::Moved);
2691 assert!(matches!(state.gesture_state, GestureRecognitionState::Pinching { .. }));
2692
2693 let evs = state.process(2, pt(180.0, 0.0), TouchPhase::Moved);
2697 let classified = classify(&evs);
2698 assert_eq!(classified.len(), 2);
2699 if let Ev::PinchMoved(delta) = classified[0] {
2700 assert!((delta - 0.5).abs() < 0.01, "expected ~0.5, got {}", delta);
2701 } else {
2702 panic!("expected PinchMoved, got {:?}", classified[0]);
2703 }
2704 }
2705
2706 #[test]
2707 fn rotation_produces_correct_deltas() {
2708 let mut state = TouchState::default();
2709
2710 state.process(1, pt(0.0, 0.0), TouchPhase::Started);
2713 state.process(2, pt(100.0, 0.0), TouchPhase::Started);
2714
2715 state.process(2, pt(120.0, 0.0), TouchPhase::Moved);
2717 assert!(matches!(state.gesture_state, GestureRecognitionState::Pinching { .. }));
2718
2719 let evs = state.process(2, pt(70.7, 70.7), TouchPhase::Moved);
2724 let classified = classify(&evs);
2725 assert_eq!(classified.len(), 2);
2726 if let Ev::RotationMoved(delta) = classified[1] {
2727 assert!((delta - 45.0).abs() < 1.0, "expected ~45.0 (clockwise), got {}", delta);
2728 } else {
2729 panic!("expected RotationMoved, got {:?}", classified[1]);
2730 }
2731 }
2732
2733 #[test]
2734 fn rotation_across_180_degree_boundary() {
2735 let mut state = TouchState::default();
2736
2737 state.process(1, pt(0.0, 0.0), TouchPhase::Started);
2740 state.process(2, pt(-100.0, -10.0), TouchPhase::Started);
2741
2742 state.process(2, pt(-120.0, -10.0), TouchPhase::Moved);
2744 assert!(matches!(state.gesture_state, GestureRecognitionState::Pinching { .. }));
2745
2746 let evs = state.process(2, pt(-100.0, 10.0), TouchPhase::Moved);
2751 let classified = classify(&evs);
2752 if let Ev::RotationMoved(delta) = classified[1] {
2753 assert!(
2754 delta.abs() < 20.0,
2755 "rotation should be a small delta (~11°), got {} (discontinuity!)",
2756 delta
2757 );
2758 } else {
2759 panic!("expected RotationMoved, got {:?}", classified[1]);
2760 }
2761 }
2762
2763 #[test]
2768 fn pinch_end_with_remaining_finger() {
2769 let mut state = TouchState::default();
2770
2771 state.process(1, pt(0.0, 0.0), TouchPhase::Started);
2772 state.process(2, pt(100.0, 0.0), TouchPhase::Started);
2773 state.process(2, pt(120.0, 0.0), TouchPhase::Moved);
2775
2776 let evs = state.process(2, pt(120.0, 0.0), TouchPhase::Ended);
2778 let classified = classify(&evs);
2779 assert_eq!(classified, vec![Ev::PinchEnded, Ev::RotationEnded, Ev::Pressed(0.0, 0.0)]);
2780 assert!(matches!(state.gesture_state, GestureRecognitionState::Idle));
2781 assert_eq!(state.primary_touch_id, Some(1));
2782 }
2783
2784 #[test]
2785 fn pinch_cancel_emits_cancelled_and_exit() {
2786 let mut state = TouchState::default();
2787
2788 state.process(1, pt(0.0, 0.0), TouchPhase::Started);
2789 state.process(2, pt(100.0, 0.0), TouchPhase::Started);
2790 state.process(2, pt(120.0, 0.0), TouchPhase::Moved);
2791
2792 let evs = state.process(2, pt(120.0, 0.0), TouchPhase::Cancelled);
2794 let classified = classify(&evs);
2795 assert_eq!(classified, vec![Ev::PinchCancelled, Ev::RotationCancelled, Ev::Exit]);
2796 assert!(state.primary_touch_id.is_none());
2797 }
2798
2799 #[test]
2800 fn two_fingers_down_lift_before_threshold_returns_to_idle() {
2801 let mut state = TouchState::default();
2802
2803 state.process(1, pt(100.0, 200.0), TouchPhase::Started);
2804 state.process(2, pt(200.0, 200.0), TouchPhase::Started);
2805 assert!(matches!(state.gesture_state, GestureRecognitionState::TwoFingersDown { .. }));
2806
2807 let evs = state.process(2, pt(200.0, 200.0), TouchPhase::Ended);
2809 let classified = classify(&evs);
2810 assert_eq!(classified, vec![Ev::Pressed(100.0, 200.0)]);
2812 assert!(matches!(state.gesture_state, GestureRecognitionState::Idle));
2813 assert_eq!(state.primary_touch_id, Some(1));
2814 }
2815
2816 #[test]
2817 fn two_fingers_down_cancel_both_emits_exit() {
2818 let mut state = TouchState::default();
2819
2820 state.process(1, pt(100.0, 200.0), TouchPhase::Started);
2821 state.process(2, pt(200.0, 200.0), TouchPhase::Started);
2822
2823 let evs = state.process(2, pt(200.0, 200.0), TouchPhase::Cancelled);
2825 assert_eq!(classify(&evs), vec![Ev::Exit]);
2826
2827 let evs = state.process(1, pt(100.0, 200.0), TouchPhase::Cancelled);
2829 assert!(classify(&evs).is_empty());
2830 }
2831
2832 #[test]
2837 fn third_finger_ignored_for_gesture() {
2838 let mut state = TouchState::default();
2839
2840 state.process(1, pt(0.0, 0.0), TouchPhase::Started);
2841 state.process(2, pt(100.0, 0.0), TouchPhase::Started);
2842
2843 let evs = state.process(3, pt(50.0, 50.0), TouchPhase::Started);
2845 assert!(classify(&evs).is_empty());
2846 assert_eq!(state.active_touches.len(), 3);
2847 }
2848
2849 #[test]
2854 fn euclid_angle_signed_wrapping() {
2855 use euclid::Angle;
2856 let wrap = |deg: f32| Angle::degrees(deg).signed().to_degrees();
2857 assert!(wrap(0.0).abs() < f32::EPSILON);
2858 assert!((wrap(180.0) - 180.0).abs() < 0.01);
2859 assert!((wrap(181.0) - (-179.0)).abs() < 0.01);
2860 assert!((wrap(-181.0) - 179.0).abs() < 0.01);
2861 assert!(wrap(360.0).abs() < 0.01);
2862 }
2863
2864 #[test]
2865 fn zero_distance_fingers_no_division_by_zero() {
2866 let mut state = TouchState::default();
2867
2868 state.process(1, pt(100.0, 100.0), TouchPhase::Started);
2870 state.process(2, pt(100.0, 100.0), TouchPhase::Started);
2871 assert!(matches!(state.gesture_state, GestureRecognitionState::TwoFingersDown { .. }));
2872
2873 let evs = state.process(2, pt(120.0, 100.0), TouchPhase::Moved);
2875 assert!(matches!(state.gesture_state, GestureRecognitionState::Pinching { .. }));
2876 let classified = classify(&evs);
2877 assert_eq!(classified.len(), 2);
2878 assert_eq!(classified[0], Ev::PinchStarted);
2879
2880 let evs = state.process(2, pt(140.0, 100.0), TouchPhase::Moved);
2883 let classified = classify(&evs);
2884 if let Ev::PinchMoved(delta) = classified[0] {
2885 assert!(delta.is_finite(), "scale delta should be finite, got {}", delta);
2886 } else {
2887 panic!("expected PinchMoved, got {:?}", classified[0]);
2888 }
2889 }
2890}
2891
2892#[cfg(test)]
2893mod tests {
2894 use super::*;
2895 extern crate alloc;
2896
2897 #[test]
2898 fn test_to_string() {
2899 let test_cases = [
2900 (
2901 "a",
2902 KeyboardModifiers { alt: false, control: true, shift: false, meta: false },
2903 false,
2904 false,
2905 "⌘A",
2906 "Ctrl+A",
2907 "Ctrl+A",
2908 ),
2909 (
2910 "a",
2911 KeyboardModifiers { alt: true, control: true, shift: true, meta: true },
2912 false,
2913 false,
2914 "⌃⌥⇧⌘A",
2915 "Win+Ctrl+Alt+Shift+A",
2916 "Super+Ctrl+Alt+Shift+A",
2917 ),
2918 (
2919 "\u{001b}",
2920 KeyboardModifiers { alt: false, control: true, shift: true, meta: false },
2921 false,
2922 false,
2923 "⇧⌘Escape",
2924 "Ctrl+Shift+Escape",
2925 "Ctrl+Shift+Escape",
2926 ),
2927 (
2928 "+",
2929 KeyboardModifiers { alt: false, control: true, shift: false, meta: false },
2930 true,
2931 false,
2932 "⌘+",
2933 "Ctrl++",
2934 "Ctrl++",
2935 ),
2936 (
2937 "a",
2938 KeyboardModifiers { alt: true, control: true, shift: false, meta: false },
2939 false,
2940 true,
2941 "⌘A",
2942 "Ctrl+A",
2943 "Ctrl+A",
2944 ),
2945 (
2946 "",
2947 KeyboardModifiers { alt: false, control: true, shift: false, meta: false },
2948 false,
2949 false,
2950 "",
2951 "",
2952 "",
2953 ),
2954 (
2955 "\u{000a}",
2956 KeyboardModifiers { alt: false, control: false, shift: false, meta: false },
2957 false,
2958 false,
2959 "Return",
2960 "Return",
2961 "Return",
2962 ),
2963 (
2964 "\u{0009}",
2965 KeyboardModifiers { alt: false, control: false, shift: false, meta: false },
2966 false,
2967 false,
2968 "Tab",
2969 "Tab",
2970 "Tab",
2971 ),
2972 (
2973 "\u{0020}",
2974 KeyboardModifiers { alt: false, control: false, shift: false, meta: false },
2975 false,
2976 false,
2977 "Space",
2978 "Space",
2979 "Space",
2980 ),
2981 (
2982 "\u{0008}",
2983 KeyboardModifiers { alt: false, control: false, shift: false, meta: false },
2984 false,
2985 false,
2986 "Backspace",
2987 "Backspace",
2988 "Backspace",
2989 ),
2990 ];
2991
2992 for (
2993 key,
2994 modifiers,
2995 ignore_shift,
2996 ignore_alt,
2997 _expected_macos,
2998 _expected_windows,
2999 _expected_linux,
3000 ) in test_cases
3001 {
3002 let shortcut = make_keys(key.into(), modifiers, ignore_shift, ignore_alt);
3003
3004 use crate::alloc::string::ToString;
3005 let result = shortcut.to_string();
3006
3007 #[cfg(target_os = "macos")]
3008 assert_eq!(result.as_str(), _expected_macos, "Failed for key: {:?}", key);
3009
3010 #[cfg(target_os = "windows")]
3011 assert_eq!(result.as_str(), _expected_windows, "Failed for key: {:?}", key);
3012
3013 #[cfg(not(any(target_os = "macos", target_os = "windows")))]
3014 assert_eq!(result.as_str(), _expected_linux, "Failed for key: {:?}", key);
3015 }
3016 }
3017
3018 #[test]
3019 fn test_from_parts_valid() {
3020 let f5_key = alloc::string::String::from(char::from(key_codes::Key::F5));
3021 let ret_key = alloc::string::String::from(char::from(key_codes::Key::Return));
3022 let pause_key = alloc::string::String::from(char::from(key_codes::Key::Pause));
3023
3024 let cases: &[(&str, &[&str], &str, KeyboardModifiers, bool, bool)] = &[
3026 (
3027 "Control+A",
3028 &["Control", "A"],
3029 "a",
3030 KeyboardModifiers { control: true, ..Default::default() },
3031 false,
3032 false,
3033 ),
3034 (
3035 "Control+Shift+A",
3036 &["Control", "Shift", "A"],
3037 "a",
3038 KeyboardModifiers { control: true, shift: true, ..Default::default() },
3039 false,
3040 false,
3041 ),
3042 (
3043 "Control+Shift?+Z (explicit ignore_shift)",
3044 &["Control", "Shift?", "Z"],
3045 "z",
3046 KeyboardModifiers { control: true, ..Default::default() },
3047 true,
3048 false,
3049 ),
3050 (
3051 "Control+Alt?+A (ignore_alt)",
3052 &["Control", "Alt?", "A"],
3053 "a",
3054 KeyboardModifiers { control: true, ..Default::default() },
3055 false,
3056 true,
3057 ),
3058 (
3059 "F5 alone (special key)",
3060 &["F5"],
3061 &f5_key,
3062 KeyboardModifiers::default(),
3063 false,
3064 false,
3065 ),
3066 ("Return key", &["Return"], &ret_key, KeyboardModifiers::default(), false, false),
3067 (
3068 "Control+Plus (LocalizedShiftable → auto ignore_shift)",
3069 &["Control", "Plus"],
3070 "+",
3071 KeyboardModifiers { control: true, ..Default::default() },
3072 true,
3073 false,
3074 ),
3075 (
3076 "Control+'+' (literal, no auto ignore_shift)",
3077 &["Control", "+"],
3078 "+",
3079 KeyboardModifiers { control: true, ..Default::default() },
3080 false,
3081 false,
3082 ),
3083 (
3084 "Control+Shift+Alt+A (all modifiers)",
3085 &["Control", "Shift", "Alt", "A"],
3086 "a",
3087 KeyboardModifiers { control: true, shift: true, alt: true, ..Default::default() },
3088 false,
3089 false,
3090 ),
3091 ("empty input → Keys::default()", &[], "", KeyboardModifiers::default(), false, false),
3092 (
3093 "Control+€ (unicode literal)",
3094 &["Control", "€"],
3095 "€",
3096 KeyboardModifiers { control: true, ..Default::default() },
3097 false,
3098 false,
3099 ),
3100 (
3101 "Control+é (lowercase literal)",
3102 &["Control", "é"],
3103 "é",
3104 KeyboardModifiers { control: true, ..Default::default() },
3105 false,
3106 false,
3107 ),
3108 ("A alone (named key)", &["A"], "a", KeyboardModifiers::default(), false, false),
3109 (
3113 "F5 codepoint literal",
3114 &[&f5_key],
3115 &f5_key,
3116 KeyboardModifiers::default(),
3117 false,
3118 false,
3119 ),
3120 (
3121 "Pause codepoint literal",
3122 &[&pause_key],
3123 &pause_key,
3124 KeyboardModifiers::default(),
3125 false,
3126 false,
3127 ),
3128 (
3129 "Control + F5 codepoint literal",
3130 &["Control", &f5_key],
3131 &f5_key,
3132 KeyboardModifiers { control: true, ..Default::default() },
3133 false,
3134 false,
3135 ),
3136 ("\" \" literal → Space", &[" "], " ", KeyboardModifiers::default(), false, false),
3139 ("Space named", &["Space"], " ", KeyboardModifiers::default(), false, false),
3140 ("\"\\t\" literal → Tab", &["\t"], "\t", KeyboardModifiers::default(), false, false),
3141 ("Tab named", &["Tab"], "\t", KeyboardModifiers::default(), false, false),
3142 (
3143 "\"\\n\" literal → Return",
3144 &["\n"],
3145 &ret_key,
3146 KeyboardModifiers::default(),
3147 false,
3148 false,
3149 ),
3150 (
3151 "Control+\" \" (literal space with a modifier)",
3152 &["Control", " "],
3153 " ",
3154 KeyboardModifiers { control: true, ..Default::default() },
3155 false,
3156 false,
3157 ),
3158 (
3159 "empty part is skipped → Keys::default()",
3160 &[""],
3161 "",
3162 KeyboardModifiers::default(),
3163 false,
3164 false,
3165 ),
3166 (
3167 "a alone (literal fallback, same result as named A)",
3168 &["a"],
3169 "a",
3170 KeyboardModifiers::default(),
3171 false,
3172 false,
3173 ),
3174 ];
3175
3176 for (desc, parts, expected_key, mods, is, ia) in cases {
3177 let result =
3178 Keys::from_parts(parts.iter().copied()).unwrap_or_else(|e| panic!("{desc}: {e}"));
3179 assert_eq!(result, make_keys((*expected_key).into(), *mods, *is, *ia), "{desc}");
3180 }
3181 }
3182
3183 #[test]
3184 fn test_from_parts_invalid() {
3185 use super::KeysParseErrorInner;
3186 let cases: &[(&str, &[&str], KeysParseError)] = &[
3187 ("lowercase 'control'", &["control", "A"], KeysParseError(KeysParseErrorInner::MultipleKeys)),
3189 ("uppercase 'CONTROL'", &["CONTROL", "A"], KeysParseError(KeysParseErrorInner::MultipleKeys)),
3190 ("'Ctrl' alias", &["Ctrl", "A"], KeysParseError(KeysParseErrorInner::MultipleKeys)),
3191 ("'ctrl' alias", &["ctrl", "A"], KeysParseError(KeysParseErrorInner::MultipleKeys)),
3192 ("'Win' alias", &["Win", "A"], KeysParseError(KeysParseErrorInner::MultipleKeys)),
3194 ("'Super' alias", &["Super", "A"], KeysParseError(KeysParseErrorInner::MultipleKeys)),
3195 ("modifiers only", &["Control", "Shift"], KeysParseError(KeysParseErrorInner::NoKey)),
3197 ("two keys", &["A", "B"], KeysParseError(KeysParseErrorInner::MultipleKeys)),
3199 (
3201 "multi-char unknown",
3202 &["Control", "Foobar"],
3203 KeysParseError(KeysParseErrorInner::MultipleGraphemeClusters("Foobar".into())),
3204 ),
3205 (
3206 "two-char literal",
3207 &["Control", "ab"],
3208 KeysParseError(KeysParseErrorInner::MultipleGraphemeClusters("ab".into())),
3209 ),
3210 (
3213 "padded modifier ' Control ' alone",
3214 &[" Control "],
3215 KeysParseError(KeysParseErrorInner::MultipleGraphemeClusters(" Control ".into())),
3216 ),
3217 (
3218 "padded modifier ' Control ' is a key, so 'A' is a second key",
3219 &[" Control ", "A"],
3220 KeysParseError(KeysParseErrorInner::MultipleKeys),
3221 ),
3222 (
3223 "padded key ' A '",
3224 &["Control", " A "],
3225 KeysParseError(KeysParseErrorInner::MultipleGraphemeClusters(" A ".into())),
3226 ),
3227 ("two space literals", &[" ", " "], KeysParseError(KeysParseErrorInner::MultipleKeys)),
3229 (
3230 "lowercase 'return' (not a named key)",
3231 &["return"],
3232 KeysParseError(KeysParseErrorInner::MultipleGraphemeClusters("return".into())),
3233 ),
3234 (
3236 "uppercase literal É",
3237 &["Control", "É"],
3238 KeysParseError(KeysParseErrorInner::NotLowercase("É".into())),
3239 ),
3240 (
3242 "Shift + Shift?",
3243 &["Shift", "Shift?", "A"],
3244 KeysParseError(KeysParseErrorInner::IncompatibleModifiers("Shift and Shift? cannot be combined".into())),
3245 ),
3246 (
3247 "Alt + Alt?",
3248 &["Alt", "Alt?", "A"],
3249 KeysParseError(KeysParseErrorInner::IncompatibleModifiers("Alt and Alt? cannot be combined".into())),
3250 ),
3251 (
3252 "Shift + LocalizedShiftable key (Plus)",
3253 &["Control", "Shift", "Plus"],
3254 KeysParseError(KeysParseErrorInner::IncompatibleModifiers(
3255 "Key bindings involving Plus ignore Shift to support different keyboard layouts; remove Shift".into(),
3256 )),
3257 ),
3258 ];
3259
3260 for (desc, parts, expected_err) in cases {
3261 let result = Keys::from_parts(parts.iter().copied());
3262 assert!(result.is_err(), "{desc}: expected error, got {result:?}");
3263 assert_eq!(&result.unwrap_err(), expected_err, "{desc}");
3264 }
3265 }
3266
3267 #[test]
3268 fn test_to_parts_roundtrip() {
3269 let inputs: &[&[&str]] = &[
3271 &[],
3272 &["A"],
3273 &["Control", "A"],
3274 &["Control", "Shift", "A"],
3275 &["Control", "Shift?", "Z"],
3276 &["Control", "Alt?", "A"],
3277 &["Control", "Alt", "Shift", "Meta", "A"],
3278 &["Meta", "Control", "Alt", "Shift", "A"],
3279 &["F5"],
3280 &["Return"],
3281 &["Space"],
3282 &[" "], &["\t"], &["\n"], &["Control", " "],
3286 &["Control", "Plus"], &["Control", "+"], &["Control", "Digit0"],
3289 &["Control", "€"],
3290 &["Control", "é"],
3291 ];
3292 for parts in inputs {
3293 let k = Keys::from_parts(parts.iter().copied()).unwrap();
3294 let out_strs: alloc::vec::Vec<&str> = k.to_parts().collect();
3295 let k2 = Keys::from_parts(out_strs.iter().copied()).unwrap();
3296 assert_eq!(k, k2, "round-trip mismatch for {parts:?} → {out_strs:?}");
3297 }
3298 }
3299
3300 #[test]
3301 fn test_to_parts_canonical_form() {
3302 let f5 = alloc::string::String::from(char::from(key_codes::Key::F5));
3305 let ret = alloc::string::String::from(char::from(key_codes::Key::Return));
3306 let pause = alloc::string::String::from(char::from(key_codes::Key::Pause));
3307 let cases: &[(&[&str], &[&str])] = &[
3308 (&[], &[]),
3309 (&["A"], &["a"]), (&["a"], &["a"]),
3311 (&["Control", "S"], &["Control", "s"]),
3312 (&["Control", "Shift?", "Z"], &["Control", "Shift?", "z"]),
3313 (&["Control", "Alt?", "A"], &["Control", "Alt?", "a"]),
3314 (&["F5"], &[&f5]),
3315 (&[&f5], &[&f5]), (&["Pause"], &[&pause]),
3317 (&[&pause], &[&pause]),
3318 (&[" "], &[" "]),
3322 (&["Space"], &[" "]),
3323 (&["\t"], &["\t"]),
3324 (&["Tab"], &["\t"]),
3325 (&["\n"], &[&ret]),
3326 (&["Return"], &[&ret]),
3327 (&["Control", " "], &["Control", " "]),
3328 (&["Control", "Plus"], &["Control", "Shift?", "+"]),
3331 (&["Control", "+"], &["Control", "+"]), (&["Control", "€"], &["Control", "€"]),
3333 (&["Meta", "Control", "Alt", "Shift", "A"], &["Meta", "Control", "Alt", "Shift", "a"]),
3334 ];
3335 for (input, expected) in cases {
3336 let k = Keys::from_parts(input.iter().copied()).unwrap();
3337 let out_strs: alloc::vec::Vec<&str> = k.to_parts().collect();
3338 assert_eq!(&out_strs.as_slice(), expected, "for input {input:?}");
3339 }
3340 }
3341
3342 #[test]
3343 fn test_from_parts_matching() {
3344 let cases: &[(&str, &[&str], &str, KeyboardModifiers, bool)] = &[
3346 (
3347 "Control+A matches",
3348 &["Control", "A"],
3349 "a",
3350 KeyboardModifiers { control: true, ..Default::default() },
3351 true,
3352 ),
3353 (
3354 "Control+A wrong key",
3355 &["Control", "A"],
3356 "b",
3357 KeyboardModifiers { control: true, ..Default::default() },
3358 false,
3359 ),
3360 (
3361 "Control+A wrong modifier",
3362 &["Control", "A"],
3363 "a",
3364 KeyboardModifiers { alt: true, ..Default::default() },
3365 false,
3366 ),
3367 (
3368 "Shift? matches with shift",
3369 &["Control", "Shift?", "Z"],
3370 "z",
3371 KeyboardModifiers { control: true, shift: true, ..Default::default() },
3372 true,
3373 ),
3374 (
3375 "Shift? matches without shift",
3376 &["Control", "Shift?", "Z"],
3377 "z",
3378 KeyboardModifiers { control: true, ..Default::default() },
3379 true,
3380 ),
3381 ];
3382
3383 for (desc, parts, text, mods, expected) in cases {
3384 let k =
3385 Keys::from_parts(parts.iter().copied()).unwrap_or_else(|e| panic!("{desc}: {e}"));
3386 let event = KeyEvent { text: (*text).into(), modifiers: *mods, ..Default::default() };
3387 assert_eq!(k.matches(&event), *expected, "{desc}");
3388 }
3389
3390 let return_char: char = key_codes::Key::Return.into();
3392 let k = Keys::from_parts(["Return"]).unwrap();
3393 let event = KeyEvent {
3394 text: SharedString::from(alloc::string::String::from(return_char)),
3395 modifiers: KeyboardModifiers::default(),
3396 ..Default::default()
3397 };
3398 assert!(k.matches(&event), "Return key should match Return event");
3399 }
3400}