1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
use std::any::Any;
use std::cmp::Ordering;
use std::sync::Arc;
use crossbeam_utils::atomic::AtomicCell;
use flume::{Receiver, Sender, TryRecvError, TrySendError};
use std::cell::{Cell, RefCell};
use std::collections::VecDeque;
use winit::window::{Window, WindowBuilder};
use winit::error::OsError;
use futures::executor::block_on;
use std::task::Waker;
use std::time::Instant;
use crate::event::Event;
use crate::future::{FutResponse, PendingRequest, FutEventLoop};
use crate::messages::{ProxyRegister, ProxyRegisterBody, ProxyRegisterInfo, ProxyRequest, ProxyResponse, REGISTER_PROXY};
pub struct EventLoop {
control_flow: Arc<AtomicCell<ControlFlow>>,
send: Sender<ProxyRequest>,
recv: Receiver<ProxyResponse>,
pending_requests: RefCell<VecDeque<PendingRequest>>,
locally_pending_events: RefCell<Vec<Event>>,
is_receiving_events: Cell<bool>
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[doc(hidden)]
pub enum EventIs {
Buffered,
New
}
impl EventLoop {
pub fn new() -> FutEventLoop {
let register_handle = Arc::new(AtomicCell::new(ProxyRegisterBody::Init));
let sent = unsafe {
REGISTER_PROXY.as_ref()
.expect("you must call winit_modular::run before creating proxy event loops")
.try_send(ProxyRegister(Arc::downgrade(®ister_handle)))
};
match sent {
Ok(()) => (),
Err(TrySendError::Full(_)) => unreachable!("REGISTER_PROXY (an unbounded queue) is full?"),
Err(TrySendError::Disconnected(_)) => panic!("main event loop crashed")
}
FutEventLoop {
body: register_handle
}
}
pub(crate) fn from(info: ProxyRegisterInfo) -> Self {
EventLoop {
control_flow: info.control_flow,
send: info.send,
recv: info.recv,
pending_requests: RefCell::new(VecDeque::new()),
locally_pending_events: RefCell::new(Vec::new()),
is_receiving_events: Cell::new(false)
}
}
pub fn on_main_thread<R: Any + Send>(&self, action: impl FnOnce() -> R + Send + 'static) -> FutResponse<'_, R> {
self.send(ProxyRequest::RunOnMainThread {
action: Box::new(move || Box::new(action()))
}, |response| {
match response {
ProxyResponse::RunOnMainThread { return_value } => {
Box::into_inner(return_value.downcast::<R>().expect("incorrect return value type, responses were received out-of-order"))
}
_ => panic!("incorrect response type, responses were received out-of-order")
}
})
}
pub fn create_window(&self, configure: impl FnOnce(WindowBuilder) -> WindowBuilder + Send + 'static) -> FutResponse<'_, Result<Window, OsError>> {
self.send(ProxyRequest::SpawnWindow {
configure: Box::new(configure)
}, |response| {
match response {
ProxyResponse::SpawnWindow { result } => result,
_ => panic!("incorrect response type, responses were received out-of-order")
}
})
}
pub fn run(&self, event_handler: impl FnMut(Event, &mut ControlFlow, EventIs)) {
block_on(self.run_async(event_handler))
}
pub async fn run_async(&self, mut event_handler: impl FnMut(Event, &mut ControlFlow, EventIs)) {
assert!(!self.is_receiving_events.get(), "already running");
self.is_receiving_events.set(true);
for event in self.locally_pending_events.borrow_mut().drain(..) {
match self.handle_event(event, |event, control_flow| {
event_handler(event, control_flow, EventIs::New)
}) {
std::ops::ControlFlow::Break(()) => {
self.is_receiving_events.set(false);
break
},
std::ops::ControlFlow::Continue(()) => ()
}
}
self._run_async(event_handler).await;
self.is_receiving_events.set(false);
}
async fn run_only_responses(&self) {
if !self.is_receiving_events.get() {
self._run_async(|_, _, _| unreachable!("called event handler but we are not receiving events")).await;
}
}
async fn _run_async(&self, mut event_handler: impl FnMut(Event, &mut ControlFlow, EventIs)) {
self.run_immediate(|event, control_flow| {
event_handler(event, control_flow, EventIs::Buffered);
});
loop {
let response = match self.recv.recv_async().await {
Ok(response) => response,
Err(_) => panic!("main event loop crashed")
};
match self.handle_response(response, |event, control_flow| {
event_handler(event, control_flow, EventIs::New)
}) {
std::ops::ControlFlow::Break(()) => break,
std::ops::ControlFlow::Continue(()) => ()
}
}
}
pub fn run_immediate(&self, mut event_handler: impl FnMut(Event, &mut ControlFlow)) {
loop {
let response = match self.recv.try_recv() {
Ok(response) => response,
Err(TryRecvError::Empty) => break,
Err(TryRecvError::Disconnected) => panic!("main event loop crashed")
};
match self.handle_response(response, &mut event_handler) {
std::ops::ControlFlow::Break(()) => break,
std::ops::ControlFlow::Continue(()) => ()
}
}
}
fn handle_response(
&self,
response: ProxyResponse,
event_handler: impl FnMut(Event, &mut ControlFlow)
) -> std::ops::ControlFlow<()> {
if self.is_receiving_events.get() {
if let ProxyResponse::Event(event) = response {
self.handle_event(event, event_handler)
} else if let Some(pending_request) = self.pending_requests.borrow_mut().pop_front() {
pending_request.resolve(response);
std::ops::ControlFlow::Continue(())
} else {
panic!("unhandled response with no associated request (is_receiving_events = true)");
}
} else {
let mut pending_requests = self.pending_requests.borrow_mut();
if let ProxyResponse::Event(event) = response {
self.locally_pending_events.borrow_mut().push(event);
std::ops::ControlFlow::Continue(())
} else if let Some(pending_request) = pending_requests.pop_front() {
pending_request.resolve(response);
if pending_requests.is_empty() {
std::ops::ControlFlow::Break(())
} else {
std::ops::ControlFlow::Continue(())
}
} else {
panic!("unhandled response with no associated request (is_receiving_events = false)");
}
}
}
fn handle_event(&self, event: Event, mut event_handler: impl FnMut(Event, &mut ControlFlow)) -> std::ops::ControlFlow<()> {
let mut control_flow = self.control_flow.load();
debug_assert_ne!(control_flow, ControlFlow::ExitLocal);
event_handler(event, &mut control_flow);
if control_flow == ControlFlow::ExitLocal {
std::ops::ControlFlow::Break(())
} else {
self.control_flow.store(control_flow);
std::ops::ControlFlow::Continue(())
}
}
fn send<T>(&self, message: ProxyRequest, convert_response: fn(ProxyResponse) -> T) -> FutResponse<'_, T> {
FutResponse::new(self, message, convert_response)
}
pub(crate) async fn actually_send(&self, message: ProxyRequest, waker: Waker, response_ptr: *mut Option<ProxyResponse>) {
match self.send.try_send(message) {
Ok(()) => (),
Err(TrySendError::Full(_)) => unreachable!("proxy event loop channel (unbounded) is full?"),
Err(TrySendError::Disconnected(_)) => panic!("main event loop crashed")
};
self.pending_requests.borrow_mut().push_back(PendingRequest::new(waker, response_ptr));
self.run_only_responses().await;
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ControlFlow {
Poll,
Wait,
WaitUntil(Instant),
ExitLocal,
ExitApp
}
impl Default for ControlFlow {
fn default() -> Self {
ControlFlow::Poll
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SharedControlFlow {
Wait,
WaitUntil(Instant),
Poll,
ExitApp
}
impl PartialOrd for SharedControlFlow {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
match (self, other) {
(SharedControlFlow::Wait, SharedControlFlow::Wait) => Some(Ordering::Equal),
(SharedControlFlow::WaitUntil(a), SharedControlFlow::WaitUntil(b)) => a.partial_cmp(&b),
(SharedControlFlow::Poll, SharedControlFlow::Poll) => Some(Ordering::Equal),
(SharedControlFlow::ExitApp, SharedControlFlow::ExitApp) => Some(Ordering::Equal),
(SharedControlFlow::Wait, SharedControlFlow::WaitUntil(_)) => Some(Ordering::Greater),
(SharedControlFlow::Wait, SharedControlFlow::Poll) => Some(Ordering::Greater),
(SharedControlFlow::Wait, SharedControlFlow::ExitApp) => Some(Ordering::Greater),
(SharedControlFlow::WaitUntil(_), SharedControlFlow::Poll) => Some(Ordering::Greater),
(SharedControlFlow::WaitUntil(_), SharedControlFlow::ExitApp) => Some(Ordering::Greater),
(SharedControlFlow::Poll, SharedControlFlow::ExitApp) => Some(Ordering::Greater),
(SharedControlFlow::WaitUntil(_), SharedControlFlow::Wait) => Some(Ordering::Less),
(SharedControlFlow::Poll, SharedControlFlow::Wait) => Some(Ordering::Less),
(SharedControlFlow::ExitApp, SharedControlFlow::Wait) => Some(Ordering::Less),
(SharedControlFlow::Poll, SharedControlFlow::WaitUntil(_)) => Some(Ordering::Less),
(SharedControlFlow::ExitApp, SharedControlFlow::WaitUntil(_)) => Some(Ordering::Less),
(SharedControlFlow::ExitApp, SharedControlFlow::Poll) => Some(Ordering::Less),
}
}
}
impl Ord for SharedControlFlow {
fn cmp(&self, other: &Self) -> Ordering {
self.partial_cmp(other).unwrap()
}
}