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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
use neon::prelude::*;
use serde_json::Value;
use std::{
cell::RefCell,
iter::zip,
sync::{Arc, OnceLock},
time::{Duration, Instant},
};
use winit::{
event::{ElementState, Event, KeyEvent, WindowEvent},
event_loop::{ActiveEventLoop, ControlFlow, EventLoop, EventLoopProxy},
keyboard::{KeyCode, PhysicalKey},
platform::{pump_events::EventLoopExtPumpEvents, run_on_demand::EventLoopExtRunOnDemand},
};
use super::{event::AppEvent, window::WindowSpec, window_mgr::WindowManager};
use crate::context::{BoxedContext2D, page::Page};
thread_local!(
static APP: RefCell<App> = RefCell::new(App::default());
static EVENT_LOOP: RefCell<EventLoop<AppEvent>> = RefCell::new(
EventLoop::with_user_event()
.build()
// SAFETY: Event loop creation only fails on unsupported platforms.
.expect("Failed to create event loop"),
);
static PROXY: RefCell<EventLoopProxy<AppEvent>> =
RefCell::new(EVENT_LOOP.with_borrow(|event_loop| event_loop.create_proxy()));
);
static RENDER_CALLBACK: OnceLock<Arc<Root<JsFunction>>> = OnceLock::new();
#[derive(Copy, Clone)]
pub enum LoopMode {
Native,
Node,
}
pub struct App {
pub mode: LoopMode,
windows: WindowManager,
cadence: Cadence,
}
impl Default for App {
fn default() -> Self {
Self {
windows: WindowManager::default(),
cadence: Cadence::default(),
mode: LoopMode::Native,
}
}
}
fn add_event(event: AppEvent) {
PROXY.with_borrow_mut(|proxy| proxy.send_event(event).ok());
}
impl App {
pub fn register(callback: Root<JsFunction>) {
RENDER_CALLBACK.get_or_init(|| Arc::new(callback));
}
pub fn set_mode(mode: LoopMode) {
APP.with_borrow_mut(|app| app.mode = mode);
}
pub fn set_fps(fps: f32) {
add_event(AppEvent::FrameRate(fps as u64));
}
pub fn open_window(spec: WindowSpec, page: Page) {
add_event(AppEvent::Open(spec, page));
}
pub fn close_window(token: u32) {
add_event(AppEvent::Close(token));
}
pub fn quit() {
APP.with_borrow_mut(|app| app.windows.remove_all());
add_event(AppEvent::Quit);
}
#[allow(deprecated)]
pub fn activate(channel: Channel, deferred: neon::types::Deferred) {
std::thread::spawn(move || {
loop {
// schedule a callback on the node event loop
let keep_running = channel
.send(move |mut cx| {
// define closure to relay events to js and receive
// canvas updates in return
let dispatch = |payload: Value,
windows: Option<&mut WindowManager>|
-> NeonResult<()> {
App::dispatch_events(&mut cx, payload, windows)
};
// run the winit event loop (either once or until all
// windows are closed depending on mode)
APP.with_borrow_mut(|app| {
EVENT_LOOP.with_borrow_mut(|event_loop| {
match app.mode {
LoopMode::Native => {
let handler = app.event_handler(dispatch);
event_loop.set_control_flow(ControlFlow::Wait);
event_loop.run_on_demand(handler).ok();
Ok(false) // final window was closed
}
LoopMode::Node => {
let poll_time = app.cadence.next_wakeup() - Instant::now();
let handler = app.event_handler(dispatch);
event_loop.pump_events(Some(poll_time), handler);
Ok(app.cadence.should_continue() || !app.windows.is_empty())
}
}
})
})
})
.join();
match keep_running {
Ok(true) => continue,
_ => break,
}
}
// resolve the promise
deferred.settle_with(&channel, move |mut cx| Ok(cx.undefined()));
});
}
fn dispatch_events(
cx: &mut TaskContext,
events: Value,
window_mgr: Option<&mut WindowManager>,
) -> NeonResult<()> {
// window_mgr is only present if it's time to collect updated canvas
// contents from js
let is_render = window_mgr.is_some();
// js callback is passed render flag & json-encoded event queue
let mut call = match RENDER_CALLBACK.get() {
None => return Ok(()),
Some(callback) => callback.to_inner(cx).call_with(cx),
};
call.arg(cx.boolean(is_render))
.arg(cx.string(events.to_string()));
match window_mgr {
None => call.exec(cx)?, /* if this is just a UI-event delivery,
* fire & forget */
Some(window_mgr) => {
// for a full roundtrip, first pass events to js
let response = call
.apply::<JsValue, _>(cx)?
.downcast::<JsArray, _>(cx)
.or_throw(cx)?
.to_vec(cx)?;
// then unpack the returned window specs & contexts
let specs_json = response[0]
.downcast::<JsString, _>(cx)
.or_throw(cx)?
.value(cx);
let specs: Vec<WindowSpec> = serde_json::from_str(&specs_json).or_else(|err| {
cx.throw_error(format!(
"Malformed response from window event handler: {}",
err
))
})?;
let contexts = response[1]
.downcast::<JsArray, _>(cx)
.or_throw(cx)?
.to_vec(cx)?;
let pages = contexts.iter().map(|boxed| {
boxed
.downcast::<BoxedContext2D, _>(cx)
.ok()
.map(|ctx| ctx.borrow().get_page())
});
// update each window with its new state & content
zip(specs, pages)
.filter_map(|(spec, page)| page.map(|page| (spec, page)))
.for_each(|(spec, page)| window_mgr.update_window(spec, page));
}
};
Ok(())
}
fn event_handler<F>(
&mut self,
mut dispatch: F,
) -> impl FnMut(Event<AppEvent>, &ActiveEventLoop) + use<'_, F>
where
F: FnMut(Value, Option<&mut WindowManager>) -> NeonResult<()>,
{
move |event, event_loop| match event {
Event::WindowEvent {
event: ref win_event,
window_id,
} => {
self.windows
.find(&window_id, |win| win.sieve.capture(win_event));
match win_event {
WindowEvent::Destroyed | WindowEvent::CloseRequested => {
self.windows.remove(&window_id);
// after the last window is closed, either exit (in
// run_on_demand mode)
// or wait for the window destructor to run (in
// pump_events mode)
if self.windows.is_empty() {
match self.mode {
LoopMode::Native => event_loop.exit(),
LoopMode::Node => self.cadence.loop_again(),
}
}
}
WindowEvent::KeyboardInput {
event:
KeyEvent {
physical_key: PhysicalKey::Code(KeyCode::Escape),
state: ElementState::Pressed,
repeat: false,
..
},
..
} => {
self.windows
.find(&window_id, |win| win.set_fullscreen(false));
}
WindowEvent::Moved(loc) => {
self.windows.find(&window_id, |win| win.did_move(*loc));
}
WindowEvent::Resized(size) => {
self.windows.find(&window_id, |win| win.did_resize(*size));
}
#[cfg(target_os = "macos")]
WindowEvent::Occluded(is_hidden) => {
self.windows
.find(&window_id, |win| win.set_redrawing_suspended(*is_hidden));
}
WindowEvent::RedrawRequested => {
self.windows.find(&window_id, |win| win.redraw());
}
_ => {}
}
}
Event::UserEvent(app_event) => match app_event {
AppEvent::Open(spec, page) => {
self.windows.add(event_loop, spec, page);
dispatch(self.windows.get_geometry(), Some(&mut self.windows)).ok();
}
AppEvent::Close(token) => {
self.windows.remove_by_token(token);
}
AppEvent::FrameRate(fps) => self.cadence.set_frame_rate(fps),
AppEvent::Quit => {
event_loop.exit();
}
},
Event::AboutToWait => {
event_loop.set_control_flow(
// let the cadence decide when to switch to poll-mode or
// sleep the thread
self.cadence.on_next_frame(self.mode, || {
// relay UI-driven state changes to js and render the
// next frame in the (active) cadence
dispatch(self.windows.get_ui_changes(), Some(&mut self.windows)).ok();
}),
);
}
_ => {}
}
}
}
struct Cadence {
rate: u64,
last: Instant,
needs_cleanup: Option<bool>,
}
impl Default for Cadence {
fn default() -> Self {
Self {
rate: 60,
last: Instant::now(),
needs_cleanup: Some(true), // ensure at least one post-Init loop
}
}
}
impl Cadence {
fn loop_again(&mut self) {
// flag that a clean-up event-loop pass is necessary (e.g., for
// reflecting window closures)
self.needs_cleanup = Some(true)
}
fn should_continue(&mut self) -> bool {
self.needs_cleanup.take().is_some()
}
fn set_frame_rate(&mut self, rate: u64) {
self.rate = rate;
}
pub fn next_wakeup(&self) -> Instant {
let frame_time = 1_000_000_000 / self.rate.max(1);
let watch_interval = 1_500_000.min(frame_time / 10);
let wakeup = Duration::from_nanos(frame_time - watch_interval);
self.last + wakeup
}
pub fn on_next_frame<F: FnMut()>(&mut self, mode: LoopMode, mut draw: F) -> ControlFlow {
// determine the upcoming deadlines for actually rendering and for
// spinning in preparation
let frame_time = 1_000_000_000 / self.rate.max(1);
let watch_interval = 1_500_000.min(frame_time / 10);
let render = Duration::from_nanos(frame_time);
let wakeup = Duration::from_nanos(frame_time - watch_interval);
// if node is handling the event loop, we can't use polling to wait for
// the render deadline. so instead we'll pause the thread for
// the last 10% of the inter-frame time (up to 1.5ms), making
// sure we can then draw immediately after
let dt = self.last.elapsed();
if matches!(mode, LoopMode::Node)
&& dt >= wakeup
&& dt < render
&& let Some(sleep_time) = render.checked_sub(self.last.elapsed())
{
spin_sleep::sleep(sleep_time);
}
// call the draw callback if it's time & make sure the next deadline is
// in the future
if self.last.elapsed() >= render {
draw();
while self.last < Instant::now() - render {
self.last += render
}
}
// if winit is in control, we can use waiting & polling to hit the
// deadline
match self.last.elapsed() < wakeup {
true => ControlFlow::WaitUntil(self.last + wakeup),
false => ControlFlow::Poll,
}
}
}