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
use std::cell::RefCell;
use std::fmt::Debug;
use std::rc::Rc;

/// Dispatcher is used to dispatch any event to a dynamically built chain of handlers.
/// The dispatch is a one-shot event. After an event is successfully processed, the dispatch chain is emptied.
/// ```
/// extern crate tui_logger;
/// extern crate termion;
///
/// use tui_logger::Dispatcher;
/// use termion::event::{Event,Key};
///
/// let mut dispatcher = Dispatcher::new();
/// dispatcher.add_listener(|ev| { println!("called"); true });
/// dispatcher.dispatch(&Event::Key(Key::Up));
/// ```
pub struct Dispatcher<E: Debug> {
    map: Vec<Box<dyn Fn(&E) -> bool>>,
}
#[allow(dead_code)]
impl<E> Dispatcher<E>
where
    E: Debug,
{
    /// Create a new dispatcher
    pub fn new() -> Dispatcher<E> {
        trace!("New dispatcher is created.");
        Dispatcher::<E> { map: vec![] }
    }
    /// Add a listener at the end of the dispatch chain.
    /// Every Listener has to be a closure receiving a termion event as parameter and shall return a boolean.
    pub fn add_listener<F: 'static + Fn(&E) -> bool>(&mut self, f: F) {
        trace!("Add listener to this dispatcher.");
        self.map.push(Box::new(f));
    }
    /// Dispatches an event to the queue.
    /// The event is sent to the event handlers in the queue in FIFO order.
    /// If an event handler returns true, then the following event handlers will not be processed anymore,
    /// the queue will be emptied and the return value of dispatch() is true.
    /// If no event handler has returned true, or the event queue is empty, then the function returns false.
    pub fn dispatch(&mut self, ev: &E) -> bool {
        let mut processed = false;
        trace!(
            "Dispatcher with {} handlers shall dispatch event {:?}",
            self.map.len(),
            ev
        );
        for f in &self.map {
            if f(ev) {
                processed = true;
                break;
            }
        }
        if processed {
            self.map.clear();
        }
        trace!("Event dispatching result for {:?} is {}", ev, processed);
        processed
    }
    /// Clear the dispatcher queue
    pub fn clear(&mut self) {
        trace!("Dispatcher clear called.");
        self.map.clear();
    }
}

/// The EventListener Trait is only a standard way to implement a tui widget, which can listen to events.
pub trait EventListener<E: Debug> {
    /// Hand over a Dispatcher to the widget.
    fn dispatcher(self, dispatcher: Rc<RefCell<Dispatcher<E>>>) -> Self;
}

#[cfg(test)]
mod tests {
    use crate::Dispatcher;
    use std::cell::RefCell;
    use std::rc::Rc;

    #[cfg(feature = "tui-crossterm")]
    use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
    #[cfg(feature = "tui-termion")]
    use termion::event::{Event, Key};

    fn make_queue(dispatcher: &mut Dispatcher<Event>, v: Rc<RefCell<u64>>) {
        macro_rules! match_key {
            ($ev:expr, $name:ident) => {{
                let ev = $ev;
                #[cfg(feature = "tui-crossterm")]
                let m = matches!(
                    ev,
                    &Event::Key(KeyEvent {
                        code: KeyCode::$name,
                        modifiers: _,
                    })
                );
                #[cfg(feature = "tui-termion")]
                let m = ev == &Event::Key(Key::$name);
                m
            }};
        }

        let vx = v.clone();
        dispatcher.add_listener(move |ev| {
            if match_key!(ev, Left) {
                *vx.borrow_mut() += 1;
                true
            } else {
                false
            }
        });
        let vx = v.clone();
        dispatcher.add_listener(move |ev| {
            if match_key!(ev, Left) {
                *vx.borrow_mut() += 2;
                true
            } else {
                false
            }
        });
        let vx = v.clone();
        dispatcher.add_listener(move |ev| {
            if match_key!(ev, Down) {
                *vx.borrow_mut() += 4;
                true
            } else {
                false
            }
        });
    }

    #[test]
    fn test_dispatch() {
        macro_rules! gen_key {
            ($name:ident) => {{
                #[cfg(feature = "tui-crossterm")]
                let ev = Event::Key(KeyEvent {
                    code: KeyCode::$name,
                    modifiers: KeyModifiers::NONE,
                });
                #[cfg(feature = "tui-termion")]
                let ev = Event::Key(Key::$name);
                ev
            }};
        }

        let v = Rc::new(RefCell::new(0));

        let mut dispatcher = crate::Dispatcher::<Event>::new();
        make_queue(&mut dispatcher, v.clone());
        assert_eq!(*v.borrow(), 0);
        let processed = dispatcher.dispatch(&gen_key!(Left));
        assert_eq!(processed, true);
        assert_eq!(*v.borrow(), 1);

        make_queue(&mut dispatcher, v.clone());
        assert_eq!(*v.borrow(), 1);
        let processed = dispatcher.dispatch(&gen_key!(Down));
        assert_eq!(processed, true);
        assert_eq!(*v.borrow(), 5);

        make_queue(&mut dispatcher, v.clone());
        assert_eq!(*v.borrow(), 5);
        let processed = dispatcher.dispatch(&gen_key!(Up));
        assert_eq!(processed, false);
        assert_eq!(*v.borrow(), 5);
        let processed = dispatcher.dispatch(&gen_key!(Down));
        assert_eq!(processed, true);
        assert_eq!(*v.borrow(), 9);
    }
}