event_handlers.rs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. use crate::{ipc::UserWindowEvent, window};
  2. use slab::Slab;
  3. use std::cell::RefCell;
  4. use tao::{event::Event, event_loop::EventLoopWindowTarget, window::WindowId};
  5. /// The unique identifier of a window event handler. This can be used to later remove the handler.
  6. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
  7. pub struct WryEventHandler(pub(crate) usize);
  8. impl WryEventHandler {
  9. /// Unregister this event handler from the window
  10. pub fn remove(&self) {
  11. window().shared.event_handlers.remove(*self)
  12. }
  13. }
  14. #[derive(Default)]
  15. pub struct WindowEventHandlers {
  16. handlers: RefCell<Slab<WryWindowEventHandlerInner>>,
  17. }
  18. struct WryWindowEventHandlerInner {
  19. window_id: WindowId,
  20. #[allow(clippy::type_complexity)]
  21. handler:
  22. Box<dyn FnMut(&Event<UserWindowEvent>, &EventLoopWindowTarget<UserWindowEvent>) + 'static>,
  23. }
  24. impl WindowEventHandlers {
  25. pub(crate) fn add(
  26. &self,
  27. window_id: WindowId,
  28. handler: impl FnMut(&Event<UserWindowEvent>, &EventLoopWindowTarget<UserWindowEvent>) + 'static,
  29. ) -> WryEventHandler {
  30. WryEventHandler(
  31. self.handlers
  32. .borrow_mut()
  33. .insert(WryWindowEventHandlerInner {
  34. window_id,
  35. handler: Box::new(handler),
  36. }),
  37. )
  38. }
  39. pub(crate) fn remove(&self, id: WryEventHandler) {
  40. self.handlers.borrow_mut().try_remove(id.0);
  41. }
  42. pub fn apply_event(
  43. &self,
  44. event: &Event<UserWindowEvent>,
  45. target: &EventLoopWindowTarget<UserWindowEvent>,
  46. ) {
  47. for (_, handler) in self.handlers.borrow_mut().iter_mut() {
  48. // if this event does not apply to the window this listener cares about, return
  49. if let Event::WindowEvent { window_id, .. } = event {
  50. if *window_id != handler.window_id {
  51. return;
  52. }
  53. }
  54. (handler.handler)(event, target)
  55. }
  56. }
  57. }