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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
// Pushrod Events
// Event Trait and Handler
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use sdl2::video::Window;
use sdl2::Sdl;

use pushrod_widgets::caches::WidgetCache;
use pushrod_widgets::event::PushrodEvent::{DrawFrame, WidgetRadioSelected};
use pushrod_widgets::event::{Event, PushrodEvent};
use pushrod_widgets::properties::PROPERTY_NEEDS_LAYOUT;
use pushrod_widgets::widget::Widget;
use std::thread::sleep;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

/// This is an event handler that is passed into a main event loop.  Since there can be multiple
/// windows open at any one time, the event handler that is implemented using this `trait` should
/// be for the window with which it is interacting.
///
/// It is inadvisable to create a single event handler "catch-all" for all application windows.
/// You will most likely get unexpected results.
pub trait EventHandler {
    /// This is the event handler that should be implemented when the `Event` handler is used.
    /// It provides the currently active widget ID and the event that was generated.
    /// Any events that could not be translated by `Pushrod` are either swallowed, or handled
    /// directly by the `run` method.  The cache is also provide as a way to get access to any
    /// `Widget`s in the list that need to be modified as the result of acting upon an `Event`.
    ///
    /// If this method is not implemented, it does not have any effect on the main application.
    fn handle_event(&mut self, _event: Event, _cache: &mut WidgetCache) {}

    /// This callback is used when the screen needs to be built for the first time.  It is called
    /// by the `Engine`'s `run` method before the event loop starts.  The `cache` is sent such that
    /// `Widget`s can be added to the display list by using the `WidgetCache`'s functions.
    ///
    /// This function **must** be implemented, as it creates a layout for the application `Window`
    /// upon creation.
    fn build_layout(&mut self, cache: &mut WidgetCache);
}

/// This is a `Pushrod` main loop struct.  All of the members of this object are
/// private, and used to track interaction with widgets on the screen, and other `SDL2`-related
/// events.
pub struct Engine {
    current_widget_id: u32,
    handler: Box<dyn EventHandler>,
    cache: WidgetCache,
    running: bool,
}

#[derive(Default)]
pub struct WidgetAddList {
    add_list: Vec<Box<dyn Widget>>,
    parent_id: u32,
}

/// This is an implementation of `Pushrod`, the main loop handler.  Multiple `Pushrod`s
/// can be created for multiple windows if your application provides more than one window
/// with which to interact.
impl Engine {
    /// Creates a new `Pushrod` run loop, taking a reference to the `EventHandler` that handles
    /// run loop events for this `Window`.
    pub fn new(handler: Box<dyn EventHandler>, window: &Window) -> Self {
        Self {
            current_widget_id: 0,
            handler,
            cache: WidgetCache::new(window.size().0, window.size().1),
            running: true,
        }
    }

    /// Stops the Pushrod run loop.
    pub fn stop(&mut self) {
        self.running = false;
    }

    /// Retrieves the `WidgetCache`.
    pub fn get_cache(&mut self) -> &mut WidgetCache {
        &mut self.cache
    }

    /// Broadcasts a generated `PushrodEvent` to the current `Widget`, capturing the response, and
    /// forwarding it on to the application if an event was returned.
    fn send_event_to_widget(&mut self, widget_id: u32, event: PushrodEvent) {
        let handled_event = self.cache.get(widget_id).handle_event(event);

        if let Some(x) = handled_event {
            self.handler
                .handle_event(Event::Pushrod(x), &mut self.cache)
        }
    }

    /// Sends an event to all `Widget`s.
    fn send_event_to_all(&mut self, event: PushrodEvent) {
        let cache_size = self.cache.size();

        for i in 0..cache_size {
            let handled_event = self.cache.get(i).handle_event(event.clone());

            if let Some(x) = handled_event {
                self.handler
                    .handle_event(Event::Pushrod(x.clone()), &mut self.cache);

                // RESEND the event ONLY IF the event qualifies as a re-distributable event, as the widget's
                // generated event has already been sent to the handler.  This could potentially cause
                // an infinite loop, so this needs to be used with care.
                //
                // Clippy is complaining about this being only one event.  This will eventually become
                // multiple events that are handled by a "rebroadcast" flag soon.
                match x {
                    WidgetRadioSelected { .. } => self.send_event_to_all(x.clone()),
                    _ => {}
                }
            }
        }
    }

    /// This function handles the `MouseMotion` event, converting it into an `Event` that can be
    /// used by `Pushrod`.  The X and Y coordinates are translated into relative offsets based on the
    /// position of the `Widget`.  This way, the X and Y coordinates can be based on drawing
    /// functions inside the `Widget` if necessary.
    fn handle_mouse_move(&mut self, x: u32, y: u32) {
        let cur_widget_id = self.current_widget_id;

        self.current_widget_id = self.cache.id_at_point(x as u32, y as u32);

        if cur_widget_id != self.current_widget_id {
            let exited_event = PushrodEvent::WidgetMouseExited {
                widget_id: cur_widget_id,
            };

            self.handler
                .handle_event(Event::Pushrod(exited_event.clone()), &mut self.cache);

            self.send_event_to_widget(cur_widget_id, exited_event);

            let entered_event = PushrodEvent::WidgetMouseEntered {
                widget_id: self.current_widget_id,
            };

            self.handler
                .handle_event(Event::Pushrod(entered_event.clone()), &mut self.cache);

            self.send_event_to_widget(self.current_widget_id, entered_event);
        }

        let points = self
            .cache
            .get(self.current_widget_id)
            .properties()
            .get_origin();
        let event = PushrodEvent::MouseMoved {
            widget_id: self.current_widget_id,
            x: (x - points.0),
            y: (y - points.1),
        };

        self.handler
            .handle_event(Event::Pushrod(event.clone()), &mut self.cache);

        self.send_event_to_widget(self.current_widget_id, event);
    }

    /// Handles a `MouseButton` event, which indicates that a mouse button has been pressed or released.
    fn handle_mouse_button(&mut self, mouse_button: u32, state: bool) {
        let event = PushrodEvent::MouseButton {
            widget_id: self.current_widget_id,
            button: mouse_button,
            state,
        };

        self.handler
            .handle_event(Event::Pushrod(event.clone()), &mut self.cache);

        if !state {
            self.send_event_to_all(event);
        } else {
            self.send_event_to_widget(self.current_widget_id, event);
        }
    }

    /// Handles a draw frame event.  This is a timer tick event that can be used by an application
    /// to refresh positions, redraw 3D objects, etc.  It provides a display tick so that the
    /// application can refresh at a rate of 60 frames/sec.
    #[inline]
    fn handle_draw_frame(&mut self, timestamp: u128) {
        let event = DrawFrame { timestamp };

        self.handler
            .handle_event(Event::Pushrod(event.clone()), &mut self.cache);

        let widget_count = self.cache.size();

        for i in 0..widget_count {
            let handled_event = self.cache.get(i).handle_event(event.clone());

            if let Some(x) = handled_event {
                self.handler
                    .handle_event(Event::Pushrod(x), &mut self.cache)
            }
        }
    }

    /// This function handles the building of additional `Widget`s to the `WidgetCache` if a newly
    /// added `Widget` (or one that has been interacted with) needs to have additional `Widget`s added
    /// to the `WidgetCache`.
    fn handle_build_layout(&mut self) {
        let num_widgets = self.cache.size();
        let mut add_list: Vec<WidgetAddList> = Vec::new();

        // First, build the list of Widgets that are required for each Widget that needs a layout.
        // Any Widgets that need to be built are stored in the add_list, and are processed after
        // processing the list that needs to be built.
        for i in 0..num_widgets {
            let mut widget = self.cache.get(i);

            if widget.properties().get_bool(PROPERTY_NEEDS_LAYOUT) {
                let widget_list = widget.build_layout();
                let mut add_entries = WidgetAddList::default();

                add_entries.add_list = widget_list;
                add_entries.parent_id = i;
                add_list.push(add_entries);

                widget.properties().delete(PROPERTY_NEEDS_LAYOUT);
            }
        }

        // Skip over the next logic if the list is empty.
        if add_list.is_empty() {
            return;
        }

        // Walk the tree of widgets to add, and add them directly to the cache here.
        for addable in add_list {
            let widget_list = addable.add_list;
            let parent_id = addable.parent_id;
            let resulting_ids = self.cache.add_vec(widget_list, parent_id);

            eprintln!("IDs: {:?}", resulting_ids);

            self.cache
                .get_mut(parent_id)
                .constructed_layout_ids(resulting_ids);
        }
    }

    /// This is the main event handler for the application.  It handles all of the events generated
    /// by the `SDL2` manager, and translates them into events that can be used by the `handle_event`
    /// method.
    pub fn run(&mut self, sdl: Sdl, window: Window) {
        let mut event_pump = sdl.event_pump().unwrap();
        let fps_as_ms = (1000.0 / 60_f64) as u128;
        let mut canvas = window
            .into_canvas()
            .target_texture()
            .accelerated()
            .build()
            .unwrap();

        // Call handler.build_layout() - this allows the application to build its `Window` contents,
        // preparing the application for use.  (This is where the deserialization will occur.)
        self.handler.build_layout(&mut self.cache);

        'running: loop {
            let start = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_millis();

            // Process events first
            for event in event_pump.poll_iter() {
                match event {
                    // TODO Change this to a callback that allows the application to handle a
                    // TODO closure of a window.  Returning true breaks the loop, false does not.
                    sdl2::event::Event::Quit { .. } => break 'running,

                    sdl2::event::Event::MouseMotion { x, y, .. } => {
                        self.handle_mouse_move(x as u32, y as u32);
                    }

                    sdl2::event::Event::MouseButtonDown { mouse_btn, .. } => {
                        self.handle_mouse_button(mouse_btn as u32, true);
                    }

                    sdl2::event::Event::MouseButtonUp { mouse_btn, .. } => {
                        self.handle_mouse_button(mouse_btn as u32, false);
                    }

                    unhandled_event => eprintln!("Event: {:?}", unhandled_event),
                }
            }

            // Tick event
            self.handle_draw_frame(
                SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap()
                    .as_millis(),
            );

            // Any Widgets that need a layout can be handled here.
            if self.cache.needs_layout() {
                eprintln!("Needs layout");
                self.handle_build_layout();
            }

            // Draw the screen if any widgets have been invalidated or added to the display list
            if self.cache.invalidated() {
                // Draw after events are processed.
                self.cache.refresh(&mut canvas);
            }

            // And pause the CPU if required to keep the system at 60 fps.
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_millis();

            if now - start < fps_as_ms {
                let diff = fps_as_ms - (now - start);

                sleep(Duration::from_millis(diff as u64));
            }

            if !self.running {
                break 'running;
            }
        }
    }
}