1use super::button::{Button, ButtonAction};
27use std::sync::mpsc::{self, Receiver, Sender, SyncSender};
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
31pub enum NativeEventOperation {
32 Block,
34
35 Dispatch,
37}
38
39impl Default for &NativeEventOperation {
40 fn default() -> Self {
41 &NativeEventOperation::Dispatch
42 }
43}
44
45impl Default for NativeEventOperation {
46 fn default() -> Self {
47 *<&NativeEventOperation>::default()
48 }
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
53pub struct ButtonEvent {
54 pub target: Button,
56
57 pub action: ButtonAction,
59
60 pub injected: bool,
63}
64
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
67pub struct CursorEvent {
68 pub delta: (i32, i32),
70
71 pub injected: bool,
73}
74
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
77pub struct WheelEvent {
78 pub delta: i32,
81
82 pub injected: bool,
84}
85
86#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
88pub enum Event {
89 Button(ButtonEvent),
91
92 Wheel(WheelEvent),
94
95 Cursor(CursorEvent),
97}
98
99#[derive(Debug)]
101pub struct NativeEventHandler {
102 tx: Option<Sender<NativeEventOperation>>,
103}
104
105impl NativeEventHandler {
106 fn new(tx: Sender<NativeEventOperation>) -> Self {
107 Self { tx: Some(tx) }
108 }
109
110 pub fn handle(mut self, operation: NativeEventOperation) {
112 self.tx.take().unwrap().send(operation).unwrap();
113 }
114
115 pub fn dispatch(self) {
117 self.handle(NativeEventOperation::Dispatch);
118 }
119
120 pub fn block(self) {
122 self.handle(NativeEventOperation::Block);
123 }
124}
125
126impl Drop for NativeEventHandler {
127 fn drop(&mut self) {
128 if let Some(tx) = self.tx.take() {
129 tx.send(NativeEventOperation::default()).unwrap();
130 }
131 }
132}
133
134#[derive(Debug, Clone)]
135pub(crate) struct EventSender {
136 tx: SyncSender<(Event, NativeEventHandler)>,
137}
138
139impl EventSender {
140 pub(crate) fn new(tx: SyncSender<(Event, NativeEventHandler)>) -> Self {
141 Self { tx }
142 }
143
144 pub(crate) fn send(&self, event: Event) -> NativeEventOperation {
145 let (tx, rx) = mpsc::channel();
146 let sent_data = (event, NativeEventHandler::new(tx));
147
148 self.tx.send(sent_data).unwrap();
149 rx.recv().unwrap()
150 }
151}
152
153pub type EventReceiver = Receiver<(Event, NativeEventHandler)>;
154
155pub(crate) fn channel() -> (EventSender, EventReceiver) {
156 const BOUND: usize = 1;
157 let (tx, rx) = mpsc::sync_channel(BOUND);
158 (EventSender::new(tx), rx)
159}