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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
#![deny(missing_docs)]
/*!
See [README.md]
**/

/// A special action for the layer.
pub enum ChangeAction {
    /// No special action to the layer.
    None,
    /// Pass the event to the next layer.
    Pass,
    /// Remove the current layer.
    Remove,
    /// Remove all layers.
    Clear,
}

/// The action, that will be done after handling an event by a layer.
pub struct Change<S, E> {
    /// Add new layers on top of the current layer.
    add: Vec<Box<dyn Layer<S, E>>>,
    /// Special actions.
    action: ChangeAction,
}

impl<S, E> Change<S, E> {
    /// A simple change doing nothing.
    pub fn none() -> Self {
        Self {
            add: Vec::new(),
            action: ChangeAction::None,
        }
    }

    /// A change passing the event to the next layer.
    pub fn pass() -> Self {
        Self {
            add: Vec::new(),
            action: ChangeAction::Pass,
        }
    }

    /// A change just adding new layers.
    pub fn add(add: Vec<Box<dyn Layer<S, E>>>) -> Self {
        Self {
            add,
            action: ChangeAction::None,
        }
    }

    /// A simple change removing the current layer.
    pub fn remove() -> Self {
        Self {
            add: Vec::new(),
            action: ChangeAction::Remove,
        }
    }

    /// A change replacing the current layer with new layers.
    pub fn replace(add: Vec<Box<dyn Layer<S, E>>>) -> Self {
        Self {
            add,
            action: ChangeAction::Remove,
        }
    }

    /// A change removing all layers.
    pub fn close() -> Self {
        Self {
            add: Vec::new(),
            action: ChangeAction::Clear,
        }
    }

    /// A change replacing all layers with a new stack of layers.
    pub fn clear(add: Vec<Box<dyn Layer<S, E>>>) -> Self {
        Self {
            add,
            action: ChangeAction::Clear,
        }
    }
}

/// A trait, every layer has to implement, in order to be used by the layer manager;
pub trait Layer<S, E> {
    /// Executed for all layers from bottom to top. Most useful for rendering.
    fn passive_update(&mut self, _state: &mut S, _event: &E) {}

    /// Executed for top layer and optionally for more layers. Most useful for click events.
    fn update(&mut self, _state: &mut S, _event: &E) -> Change<S, E>;
}

/// The layer manager deals with the layers you create.
pub struct LayerManager<S, E>(Vec<Box<dyn Layer<S, E>>>);

impl<S, E> LayerManager<S, E> {
    /// Create a new layer manager containing specified initial layers.
    pub fn new(layers: Vec<Box<dyn Layer<S, E>>>) -> Self {
        LayerManager::<S, E>(layers)
    }

    /// Checks if the layer manger is still active. When not active, the program should terminate or new layers should be added before calling `update` again.
    pub fn is_active(&self) -> bool {
        !self.0.is_empty()
    }

    /// Everytime the program recieves or generates an event, which should be handled by a layer, this method has to be called.
    pub fn update(&mut self, state: &mut S, event: E) {
        let count = self.0.len();
        let mut i = count;
        while i > 0 {
            i -= 1;
            let layer = &mut self.0[i];
            let Change { add, action } = layer.update(state, &event);
            let add_index = i + 1;
            for (i, added) in add.into_iter().enumerate() {
                self.0.insert(add_index + i, added);
            }
            use ChangeAction::*;
            match action {
                None => (),
                Pass => continue,
                Remove => {
                    self.0.remove(i);
                }
                Clear => self.0.clear(),
            }
            break;
        }

        for layer in self.0.iter_mut() {
            layer.passive_update(state, &event);
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::*;

    pub enum Event {
        Idle,
        Input,
        Exit,
    }

    pub struct GlobalState;

    pub struct MainLayer;

    impl Layer<GlobalState, Event> for MainLayer {
        fn update(
            &mut self,
            _state: &mut GlobalState,
            event: &Event,
        ) -> Change<GlobalState, Event> {
            match event {
                Event::Input => Change::add(vec![Box::new(TopLayer)]),
                Event::Idle => Change::none(),
                Event::Exit => Change::remove(),
            }
        }
    }

    pub struct TopLayer;

    impl Layer<GlobalState, Event> for TopLayer {
        fn update(
            &mut self,
            _state: &mut GlobalState,
            event: &Event,
        ) -> Change<GlobalState, Event> {
            match event {
                Event::Input => Change::pass(),
                Event::Idle => Change::none(),
                Event::Exit => Change::remove(),
            }
        }
    }

    #[test]
    fn example() {
        let mut manager = LayerManager::new(vec![Box::new(MainLayer), Box::new(TopLayer)]);
        let mut state = GlobalState;

        manager.update(&mut state, Event::Idle);
        manager.update(&mut state, Event::Input);
        manager.update(&mut state, Event::Idle);

        while manager.is_active() {
            manager.update(&mut state, Event::Exit);
        }
    }
}