1use std::cell::Cell;
15use std::path::PathBuf;
16use std::rc::Rc;
17use std::time::Duration;
18
19use reactive::Scope;
20use scene::Angle;
21
22use crate::image::RgbaImage;
23use crate::rich_text::SpanInfo;
24use crate::input::{Buttons, GesturePhase, Key, Modifiers, MouseButton, PhysicalKey, PointerId, PointerKind, WheelDelta};
25use crate::interaction::{Chord, FocusHandle};
26
27#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
29pub enum PropagationPhase {
30 Capture,
32 #[default]
34 Target,
35 Bubble,
37}
38
39bitflags::bitflags! {
40 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
42 pub struct Builtin: u16 {
43 const FOCUS = 1;
45 const TEXT_SELECT = 1 << 1;
47 const DRAG = 1 << 2;
49 const SCROLL = 1 << 3;
51 const ACTIVATE = 1 << 4;
53 const DISMISS = 1 << 5;
55 const TAB = 1 << 6;
57 const ARROWS = 1 << 7;
59 const CONTEXT_MENU = 1 << 8;
61 const EDIT = 1 << 9;
63 const CLOSE = 1 << 10;
65 const WINDOW_DRAG = 1 << 11;
67 const ALL = (1 << 12) - 1;
69 }
70}
71
72#[derive(Clone, Debug, Default)]
74pub(crate) struct Flow {
75 stopped: Cell<bool>,
76 prevented: Cell<Builtin>,
77 capture: Cell<bool>,
78 phase: Cell<PropagationPhase>,
79 claim: Cell<Claim>,
81}
82
83#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
85pub(crate) enum Claim {
86 #[default]
88 Undecided,
89 Claimed,
91 Declined,
93}
94
95impl PartialEq for Flow {
97 fn eq(&self, _: &Self) -> bool {
98 true
99 }
100}
101
102impl Flow {
103 pub fn stopped(&self) -> bool {
104 self.stopped.get()
105 }
106
107 pub fn stop(&self) {
109 self.stopped.set(true);
110 }
111
112 pub fn take_claim(&self) -> Claim {
114 self.claim.replace(Claim::Undecided)
115 }
116
117 pub fn prevented(&self) -> Builtin {
118 self.prevented.get()
119 }
120
121 pub fn prevent(&self, builtin: Builtin) {
122 self.prevented.set(self.prevented.get() | builtin);
123 }
124
125 pub fn set_phase(&self, phase: PropagationPhase) {
126 self.phase.set(phase);
127 }
128
129 pub fn take_capture(&self) -> bool {
131 self.capture.replace(false)
132 }
133}
134
135macro_rules! propagation {
137 ($($ty:ident),*) => {
138 $(
139 impl $ty {
140 pub fn stop_propagation(&self) {
142 self.flow.stopped.set(true);
143 }
144
145 pub fn is_propagation_stopped(&self) -> bool {
147 self.flow.stopped.get()
148 }
149
150 pub fn prevent_builtin(&self, builtin: Builtin) {
152 self.flow.prevent(builtin);
153 }
154
155 pub fn is_builtin_prevented(&self, builtin: Builtin) -> bool {
157 self.flow.prevented.get().contains(builtin)
158 }
159
160 pub fn phase(&self) -> PropagationPhase {
162 self.flow.phase.get()
163 }
164
165 pub(crate) fn flow(&self) -> &Flow {
166 &self.flow
167 }
168 }
169 )*
170 };
171}
172
173propagation!(PointerEvent, ClickEvent, KeyEvent, WheelEvent);
174
175macro_rules! gesture {
177 ($($ty:ident),*) => {
178 $(
179 impl $ty {
180 pub fn stop_propagation(&self) {
183 self.flow.stopped.set(true);
184 }
185
186 pub fn is_propagation_stopped(&self) -> bool {
188 self.flow.stopped.get()
189 }
190
191 pub fn phase(&self) -> PropagationPhase {
194 self.flow.phase.get()
195 }
196
197 pub fn claim_gesture(&self) {
201 self.flow.claim.set(Claim::Claimed);
202 }
203
204 pub fn decline_gesture(&self) {
208 self.flow.claim.set(Claim::Declined);
209 }
210
211 pub(crate) fn flow(&self) -> &Flow {
212 &self.flow
213 }
214 }
215 )*
216 };
217}
218
219gesture!(DragEvent, PinchEvent, RotateEvent);
220
221impl FieldChangeEvent {
222 pub(crate) fn new(name: Option<String>, focus_handle: Option<FocusHandle>, value: FieldValue, source: ChangeSource) -> Self {
223 Self { name, focus_handle, value, source, flow: Flow::default() }
224 }
225
226 pub fn stop_propagation(&self) {
228 self.flow.stopped.set(true);
229 }
230
231 pub fn is_propagation_stopped(&self) -> bool {
233 self.flow.stopped.get()
234 }
235
236 pub fn phase(&self) -> PropagationPhase {
238 self.flow.phase.get()
239 }
240
241 pub(crate) fn flow(&self) -> &Flow {
242 &self.flow
243 }
244}
245
246#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
248#[non_exhaustive]
249pub enum PointerEventKind {
250 Down,
252 Up,
254 #[default]
256 Move,
257 Enter,
259 Leave,
261 Cancel,
263}
264
265#[derive(Clone, Debug)]
268pub struct PointerEvent {
269 pub kind: PointerEventKind,
271 pub position: [f32; 2],
273 pub window_position: [f32; 2],
275 pub button: Option<MouseButton>,
277 pub buttons: Buttons,
279 pub modifiers: Modifiers,
281 pub clicks: u32,
283 pub device: PointerKind,
285 pub pointer_id: PointerId,
287 pub time: Duration,
289 pub(crate) flow: Flow,
290}
291
292impl PointerEvent {
293 pub(crate) fn new(kind: PointerEventKind, window_position: [f32; 2], button: Option<MouseButton>, modifiers: Modifiers, clicks: u32) -> Self {
294 Self {
295 kind,
296 position: window_position,
297 window_position,
298 button,
299 buttons: Buttons::empty(),
300 modifiers,
301 clicks,
302 device: PointerKind::Mouse,
303 pointer_id: PointerId::MOUSE,
304 time: crate::timer::now_duration(),
305 flow: Flow::default(),
306 }
307 }
308
309 pub fn capture_pointer(&self) {
311 self.flow.capture.set(true);
312 }
313}
314
315#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
317#[non_exhaustive]
318pub enum ClickSource {
319 #[default]
321 Pointer,
322 Keyboard,
324 Accessibility,
326 Label,
328}
329
330#[derive(Clone, Debug)]
333pub struct ClickEvent {
334 pub source: ClickSource,
336 pub button: MouseButton,
338 pub position: [f32; 2],
340 pub window_position: [f32; 2],
342 pub modifiers: Modifiers,
344 pub clicks: u32,
346 pub time: Duration,
348 pub(crate) flow: Flow,
349}
350
351impl ClickEvent {
352 pub(crate) fn new(source: ClickSource, button: MouseButton, window_position: [f32; 2], modifiers: Modifiers, clicks: u32) -> Self {
353 Self {
354 source,
355 button,
356 position: window_position,
357 window_position,
358 modifiers,
359 clicks,
360 time: crate::timer::now_duration(),
361 flow: Flow::default(),
362 }
363 }
364}
365
366#[derive(Clone, Debug)]
368pub struct KeyEvent {
369 pub key: Key,
371 pub base: Key,
373 pub physical: Option<PhysicalKey>,
375 pub text: Option<String>,
377 pub modifiers: Modifiers,
379 pub repeated: bool,
381 pub composing: bool,
383 pub time: Duration,
385 altgr: bool,
387 pub(crate) flow: Flow,
388}
389
390impl KeyEvent {
391 pub(crate) fn new(key: Key, base: Key, physical: Option<PhysicalKey>, text: Option<String>, modifiers: Modifiers, repeated: bool) -> Self {
392 let altgr = modifiers.has_control()
394 && modifiers.has_alt()
395 && !modifiers.has_super()
396 && crate::system::conventions().primary_modifier == Modifiers::CONTROL;
397 Self { key, base, physical, text, modifiers, repeated, composing: false, time: crate::timer::now_duration(), altgr, flow: Flow::default() }
398 }
399
400 pub fn is(&self, chord: &str) -> bool {
402 Chord::parse(chord).is_some_and(|c| c.matches(&self.key, &self.base, self.modifiers))
403 }
404
405 pub fn has_primary_modifier(&self) -> bool {
407 self.modifiers.intersects(crate::system::conventions().primary_modifier) && !self.altgr
408 }
409
410 pub fn is_chord(&self) -> bool {
413 self.modifiers.has_super() || (self.modifiers.has_control() && !self.altgr)
414 }
415
416 pub fn typed_text(&self) -> Option<&str> {
419 let text = self.text.as_deref().filter(|t| !t.is_empty() && !t.chars().any(char::is_control))?;
420 (!self.is_chord() && !self.composing).then_some(text)
421 }
422}
423
424#[derive(Clone, Debug)]
427pub struct WheelEvent {
428 pub delta: WheelDelta,
430 pub phase: GesturePhase,
432 pub inertial: bool,
434 pub position: [f32; 2],
436 pub window_position: [f32; 2],
438 pub modifiers: Modifiers,
440 pub time: Duration,
442 pub(crate) flow: Flow,
443}
444
445impl WheelEvent {
446 pub(crate) fn new(delta: WheelDelta, phase: GesturePhase, inertial: bool, window_position: [f32; 2], modifiers: Modifiers) -> Self {
447 Self {
448 delta,
449 phase,
450 inertial,
451 position: window_position,
452 window_position,
453 modifiers,
454 time: crate::timer::now_duration(),
455 flow: Flow::default(),
456 }
457 }
458}
459
460#[derive(Clone, Copy, Debug, PartialEq)]
462pub struct ScrollEvent {
463 pub offset: [f32; 2],
465 pub delta: [f32; 2],
467}
468
469#[derive(Clone, Debug, PartialEq)]
474pub struct DragEvent {
475 pub phase: GesturePhase,
477 pub position: [f32; 2],
479 pub window_position: [f32; 2],
481 pub start_position: [f32; 2],
483 pub delta: [f32; 2],
485 pub translation: [f32; 2],
487 pub velocity: [f32; 2],
489 pub button: MouseButton,
491 pub modifiers: Modifiers,
493 pub(crate) flow: Flow,
494}
495
496#[derive(Clone, Debug, PartialEq)]
498pub struct PinchEvent {
499 pub phase: GesturePhase,
501 pub scale: f32,
503 pub delta: f32,
505 pub position: [f32; 2],
507 pub window_position: [f32; 2],
509 pub(crate) flow: Flow,
510}
511
512#[derive(Clone, Debug, PartialEq)]
515pub struct RotateEvent {
516 pub phase: GesturePhase,
518 pub rotation: Angle,
520 pub delta: Angle,
522 pub position: [f32; 2],
524 pub window_position: [f32; 2],
526 pub(crate) flow: Flow,
527}
528
529impl PinchEvent {
530 pub(crate) fn new(phase: GesturePhase, scale: f32, delta: f32, window_position: [f32; 2]) -> Self {
531 Self { phase, scale, delta, position: window_position, window_position, flow: Flow::default() }
532 }
533}
534
535impl RotateEvent {
536 pub(crate) fn new(phase: GesturePhase, rotation: Angle, delta: Angle, window_position: [f32; 2]) -> Self {
537 Self { phase, rotation, delta, position: window_position, window_position, flow: Flow::default() }
538 }
539}
540
541#[derive(Clone, Debug, PartialEq)]
543pub struct FileDropEvent {
544 pub paths: Vec<PathBuf>,
546 pub position: [f32; 2],
548 pub window_position: [f32; 2],
550}
551
552bitflags::bitflags! {
553 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
555 pub struct ExternalDataKinds: u8 {
556 const TEXT = 1;
558 const LINK = 1 << 1;
560 const IMAGE = 1 << 2;
562 const FILES = 1 << 3;
564 const RICH_TEXT = 1 << 4;
566 const CUSTOM = 1 << 5;
568 }
569}
570
571#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
573#[non_exhaustive]
574pub enum ExternalDropEffect {
575 #[default]
577 Copy,
578 Move,
580 Link,
582}
583
584#[derive(Clone, Debug, PartialEq)]
586pub struct ExternalDragEvent {
587 pub kinds: ExternalDataKinds,
589 pub position: [f32; 2],
591 pub window_position: [f32; 2],
593 pub(crate) effect: Cell<Option<ExternalDropEffect>>,
594}
595
596impl ExternalDragEvent {
597 pub(crate) fn new(kinds: ExternalDataKinds, position: [f32; 2], window_position: [f32; 2]) -> Self {
598 Self { kinds, position, window_position, effect: Cell::new(None) }
599 }
600
601 pub fn accept(&self) {
604 self.effect.set(Some(ExternalDropEffect::Copy));
605 }
606
607 pub fn accept_with(&self, effect: ExternalDropEffect) {
609 self.effect.set(Some(effect));
610 }
611
612 pub fn is_accepted(&self) -> bool {
614 self.effect.get().is_some()
615 }
616}
617
618#[derive(Clone, Debug, Default, PartialEq)]
620pub struct ExternalDropData {
621 pub text: Option<String>,
623 pub link: Option<String>,
625 pub image: Option<RgbaImage>,
627 pub files: Vec<PathBuf>,
629 pub rich_text: Vec<SpanInfo>,
631 pub custom: Vec<(String, Vec<u8>)>,
633}
634
635impl ExternalDropData {
636 pub fn kinds(&self) -> ExternalDataKinds {
638 let mut kinds = ExternalDataKinds::empty();
639 kinds.set(ExternalDataKinds::TEXT, self.text.is_some());
640 kinds.set(ExternalDataKinds::LINK, self.link.is_some());
641 kinds.set(ExternalDataKinds::IMAGE, self.image.is_some());
642 kinds.set(ExternalDataKinds::FILES, !self.files.is_empty());
643 kinds.set(ExternalDataKinds::RICH_TEXT, !self.rich_text.is_empty());
644 kinds.set(ExternalDataKinds::CUSTOM, !self.custom.is_empty());
645 kinds
646 }
647
648 pub fn custom(&self, format: &str) -> Option<&[u8]> {
650 custom_of(&self.custom, format)
651 }
652}
653
654fn custom_of<'a>(custom: &'a [(String, Vec<u8>)], format: &str) -> Option<&'a [u8]> {
655 custom.iter().find(|(name, _)| name == format).map(|(_, bytes)| bytes.as_slice())
656}
657
658#[derive(Clone, Debug, PartialEq)]
660pub struct ExternalDropEvent {
661 pub text: Option<String>,
663 pub link: Option<String>,
665 pub image: Option<RgbaImage>,
667 pub files: Vec<PathBuf>,
669 pub rich_text: Vec<SpanInfo>,
671 pub custom: Vec<(String, Vec<u8>)>,
673 pub position: [f32; 2],
675 pub window_position: [f32; 2],
677}
678
679impl ExternalDropEvent {
680 pub fn custom(&self, format: &str) -> Option<&[u8]> {
682 custom_of(&self.custom, format)
683 }
684}
685
686#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
690#[non_exhaustive]
691pub enum ChangeSource {
692 #[default]
694 Pointer,
695 Keyboard,
697 Accessibility,
699 Label,
701}
702
703impl From<ClickSource> for ChangeSource {
704 fn from(activation: ClickSource) -> Self {
705 match activation {
706 ClickSource::Pointer => Self::Pointer,
707 ClickSource::Keyboard => Self::Keyboard,
708 ClickSource::Accessibility => Self::Accessibility,
709 ClickSource::Label => Self::Label,
710 }
711 }
712}
713
714#[derive(Clone, Debug, PartialEq)]
717pub struct ChangeEvent<T> {
718 pub value: T,
720 pub source: ChangeSource,
722}
723
724#[derive(Clone, Debug, PartialEq)]
727#[non_exhaustive]
728pub enum FieldValue {
729 Bool(bool),
731 Number(f64),
733 Text(String),
735 Secret,
737 Choice {
739 index: usize,
741 text: String,
743 },
744}
745
746impl std::fmt::Display for FieldValue {
747 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
748 match self {
749 Self::Bool(v) => write!(f, "{v}"),
750 Self::Number(v) => write!(f, "{v}"),
751 Self::Text(v) => f.write_str(v),
752 Self::Secret => f.write_str("••••"),
753 Self::Choice { text, .. } => f.write_str(text),
754 }
755 }
756}
757
758#[derive(Clone, Debug)]
763pub struct FieldChangeEvent {
764 pub name: Option<String>,
766 pub focus_handle: Option<FocusHandle>,
768 pub value: FieldValue,
770 pub source: ChangeSource,
772 pub(crate) flow: Flow,
773}
774
775pub trait IntoChangeHandler<T, Marker> {
780 #[allow(clippy::type_complexity, reason = "处理器的类型就是这样,起个别名反而要多找一处")]
782 fn into_change_handler(self) -> Rc<dyn Fn(&ChangeEvent<T>)>;
783}
784
785impl<T: Clone + 'static, R, F: Fn(T) -> R + 'static> IntoChangeHandler<T, fn(T) -> R> for F {
786 fn into_change_handler(self) -> Rc<dyn Fn(&ChangeEvent<T>)> {
787 IntoHandler::<ChangeEvent<T>, fn(&ChangeEvent<T>)>::into_handler(move |e: &ChangeEvent<T>| {
788 self(e.value.clone());
789 })
790 }
791}
792
793impl<T: 'static, R, F: Fn(&ChangeEvent<T>) -> R + 'static> IntoChangeHandler<T, fn(&ChangeEvent<T>) -> R> for F {
794 fn into_change_handler(self) -> Rc<dyn Fn(&ChangeEvent<T>)> {
795 IntoHandler::<ChangeEvent<T>, fn(&ChangeEvent<T>)>::into_handler(move |e: &ChangeEvent<T>| {
796 self(e);
797 })
798 }
799}
800
801pub trait IntoHandler<E, Marker> {
807 fn into_handler(self) -> Rc<dyn Fn(&E)>;
809}
810
811impl<E: 'static, R, F: Fn() -> R + 'static> IntoHandler<E, fn() -> R> for F {
812 fn into_handler(self) -> Rc<dyn Fn(&E)> {
813 match Scope::current() {
814 Some(scope) => Rc::new(move |_: &E| {
815 scope.run(|| {
816 self();
817 })
818 }),
819 None => Rc::new(move |_: &E| {
820 self();
821 }),
822 }
823 }
824}
825
826impl<E: 'static, R, F: Fn(&E) -> R + 'static> IntoHandler<E, fn(&E) -> R> for F {
827 fn into_handler(self) -> Rc<dyn Fn(&E)> {
828 match Scope::current() {
829 Some(scope) => Rc::new(move |e: &E| {
830 scope.run(|| {
831 self(e);
832 })
833 }),
834 None => Rc::new(move |e: &E| {
835 self(e);
836 }),
837 }
838 }
839}