freya_core/
event_handler.rs

1use std::{
2    cell::RefCell,
3    rc::Rc,
4};
5
6pub struct Callback<A, R>(Rc<RefCell<dyn FnMut(A) -> R>>);
7
8impl<A, R> Callback<A, R> {
9    pub fn new(callback: impl FnMut(A) -> R + 'static) -> Self {
10        Self(Rc::new(RefCell::new(callback)))
11    }
12
13    pub fn call(&self, data: A) -> R {
14        (self.0.borrow_mut())(data)
15    }
16}
17
18impl<A, R> Clone for Callback<A, R> {
19    fn clone(&self) -> Self {
20        Self(self.0.clone())
21    }
22}
23
24impl<A, R> PartialEq for Callback<A, R> {
25    fn eq(&self, _other: &Self) -> bool {
26        true
27    }
28}
29
30impl<A, R, H: FnMut(A) -> R + 'static> From<H> for Callback<A, R> {
31    fn from(value: H) -> Self {
32        Callback::new(value)
33    }
34}
35pub struct EventHandler<T>(Rc<RefCell<dyn FnMut(T)>>);
36
37impl<T> EventHandler<T> {
38    pub fn new(handler: impl FnMut(T) + 'static) -> Self {
39        Self(Rc::new(RefCell::new(handler)))
40    }
41
42    pub fn call(&self, data: T) {
43        (self.0.borrow_mut())(data);
44    }
45}
46
47impl<T> Clone for EventHandler<T> {
48    fn clone(&self) -> Self {
49        Self(self.0.clone())
50    }
51}
52
53impl<T> PartialEq for EventHandler<T> {
54    fn eq(&self, _other: &Self) -> bool {
55        // TODO: Decide whether event handlers should be captured or not.
56        false
57    }
58}
59
60impl<H: FnMut(D) + 'static, D> From<H> for EventHandler<D> {
61    fn from(value: H) -> Self {
62        EventHandler::new(value)
63    }
64}