dioxus_native/
event_handlers.rs1use slotmap::{DefaultKey, Key, KeyData, SlotMap};
2use std::cell::RefCell;
3use std::rc::Rc;
4use winit::{event::WindowEvent, event_loop::ActiveEventLoop, window::WindowId};
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8pub struct WinitEventHandlerId(pub(crate) u64);
9
10impl WinitEventHandlerId {
11 pub fn remove(&self) {
13 let handlers: Rc<WindowEventHandlers> = dioxus_core::consume_context();
14 handlers.remove(*self);
15 }
16}
17
18struct WinitWindowEventHandlerInner {
19 window_id: WindowId,
20
21 #[allow(clippy::type_complexity)]
22 handler: Box<dyn FnMut(&WindowEvent, &dyn ActiveEventLoop) + 'static>,
23}
24
25#[derive(Default)]
26pub(crate) struct WindowEventHandlers {
27 handlers: RefCell<SlotMap<DefaultKey, WinitWindowEventHandlerInner>>,
28}
29
30impl WindowEventHandlers {
31 pub(crate) fn add(
32 &self,
33 window_id: WindowId,
34 handler: impl FnMut(&WindowEvent, &dyn ActiveEventLoop) + 'static,
35 ) -> WinitEventHandlerId {
36 let key = self
37 .handlers
38 .borrow_mut()
39 .insert(WinitWindowEventHandlerInner {
40 window_id,
41 handler: Box::new(handler),
42 });
43 WinitEventHandlerId(key.data().as_ffi())
44 }
45
46 pub(crate) fn remove(&self, id: WinitEventHandlerId) {
47 let key = DefaultKey::from(KeyData::from_ffi(id.0));
48 self.handlers.borrow_mut().remove(key);
49 }
50
51 pub fn apply_event(
52 &self,
53 window_id: WindowId,
54 event: &WindowEvent,
55 target: &dyn ActiveEventLoop,
56 ) {
57 for (_, handler) in self.handlers.borrow_mut().iter_mut() {
58 if handler.window_id != window_id {
59 continue;
60 }
61 (handler.handler)(event, target)
62 }
63 }
64}