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
use crate::utils::EventHandler;

pub trait EventScheme {
    type Event;

    /// Trigger the event manually and call its handler immediately.
    fn trigger(&self, event: Self::Event);

    /// Subscribe events, call the `handler` when an input event occurs.
    /// If `once` is ture, unsubscribe automatically after handling.
    fn subscribe(&self, handler: EventHandler<Self::Event>, once: bool);
}

macro_rules! impl_event_scheme {
    ($struct:ident $(, $event_ty:ty)?) => {
        impl_event_scheme!(@impl_base $struct $(, $event_ty)?);
    };
    ($struct:ident<'_> $(, $event_ty:ty)?) => {
        impl_event_scheme!(@impl_base $struct<'_> $(, $event_ty)?);
    };
    ($struct:ident < $($types:ident),* > $(where $($preds:tt)+)? $(, $event_ty:ty)?) => {
        impl_event_scheme!(@impl_base $struct < $($types),* > $(where $($preds)+)? $(, $event_ty)?);
    };

    (@impl_base $struct:ident $(, $event_ty:ty)?) => {
        impl $crate::scheme::EventScheme for $struct {
            impl_event_scheme!(@impl_body $(, $event_ty)?);
        }
    };
    (@impl_base $struct:ident<'_> $(, $event_ty:ty)?) => {
        impl $crate::scheme::EventScheme for $struct<'_> {
            impl_event_scheme!(@impl_body $(, $event_ty)?);
        }
    };
    (@impl_base $struct:ident < $($types:ident),* > $(where $($preds:tt)+)? $(, $event_ty:ty)?) => {
        impl < $($types),* > $crate::scheme::EventScheme for $struct < $($types),* >
            $(where $($preds)+)?
        {
            impl_event_scheme!(@impl_body $(, $event_ty)?);
        }
    };

    (@impl_assoc_type) => {
        type Event = ();
    };
    (@impl_assoc_type, $event_ty:ty) => {
        type Event = $event_ty;
    };
    (@impl_body $(, $event_ty:ty)?) => {
        impl_event_scheme!(@impl_assoc_type $(, $event_ty)?);

        #[inline]
        fn trigger(&self, event: Self::Event) {
            self.listener.trigger(event);
        }

        #[inline]
        fn subscribe(&self, handler: $crate::utils::EventHandler<Self::Event>, once: bool) {
            self.listener.subscribe(handler, once);
        }
    };
}