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
// Main Event Dispatcher
// Master of the Universe
//
// 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 std::cell::RefCell;
use std::collections::HashMap;
use std::collections::HashSet;

use crate::core::callbacks::*;
use crate::core::point::*;
use crate::core::widget_store::*;
use crate::widget::widget::*;

use piston_window::*;

/// This structure is returned when instantiating a new Pushrod main object.
/// It stores the OpenGL configuration that is desired for drawing, a list of references
/// to a managed set of `PushrodWindow` objects, registered `EventListener`s, and
/// `PushrodEvent` objects that are pending dispatch.
///
/// The objects contained within this structure are used by the `Pushrod` run loop, and
/// are not intended to be modified except through methods in the `Pushrod` impl.
pub struct Pushrod {
    window: PistonWindow,
    pub widget_store: RefCell<WidgetStore>,
}

/// Pushrod implementation.  Create a `Pushrod::new( OpenGL )` object to create a new
/// main loop.  Only one of these should be set for the entire application runtime.
///
/// Example usage:
/// IN PROGRESS
impl Pushrod {
    /// Pushrod Object Constructor.  Takes in a single OpenGL configuration type.
    pub fn new(window: PistonWindow) -> Self {
        Self {
            window,
            widget_store: RefCell::new(WidgetStore::new()),
        }
    }

    /// Retrieves the window `GfxFactory` factory object for graphics textures.
    pub fn get_factory(&mut self) -> &mut GfxFactory {
        &mut self.window.factory
    }

    /// Helper method that adds a `Widget` to the `WidgetStore`, returning the ID of the `Widget`
    /// after it has been added.
    pub fn add_widget(&mut self, name: &str, widget: Box<dyn Widget>) -> i32 {
        self.widget_store.borrow_mut().add_widget(name, widget)
    }

    /// Helper method that adds a `Widget` to the `WidgetStore`, specifying the `parent_id` as the
    /// parent of which to add this object to.  Returns the new ID of the `Widget` after it has
    /// been added.
    pub fn add_widget_to_parent(
        &mut self,
        name: &str,
        widget: Box<dyn Widget>,
        parent_id: i32,
    ) -> i32 {
        self.widget_store
            .borrow_mut()
            .add_widget_to_parent(name, widget, parent_id)
    }

    fn handle_draw(&mut self, event: &Event) {
        let widgets = &mut self.widget_store.borrow_mut();

        self.window.draw_2d(event, |c, g| widgets.draw(0, c, g));
    }

    fn handle_event(
        &mut self,
        widget_id: i32,
        event_handler: &mut PushrodCallbackEvents,
        event: CallbackEvent,
    ) {
        if widget_id == -1 {
            return;
        }

        let injectable_event = self
            .widget_store
            .borrow_mut()
            .handle_event(widget_id, event.clone());

        event_handler.handle_event(event.clone(), &mut self.widget_store.borrow_mut());

        match injectable_event {
            Some(new_event) => {
                event_handler.handle_event(new_event.clone(), &mut self.widget_store.borrow_mut())
            }
            None => (),
        }
    }

    /// This is the main run loop that is called to process all UI events.  This loop is responsible
    /// for handling events from the OS, converting them to workable objects, and passing them off
    /// to quick callback dispatchers.
    ///
    /// The run loop handles events in the following order:
    ///
    /// - Mouse events
    ///   - Movement events
    ///   - Button events
    ///   - Scroll button events
    /// - Custom events are then dispatched to any registered event listeners
    /// - Draw loop
    ///   - Draw only widgets whose states have become invalidated
    ///   - Swap display buffers if required
    ///
    /// This event is handled window-by-window.  Once a window has processed all of its pending
    /// events, the next window is then processed.  No particular window takes precidence - any
    /// window that has events to process gets handled in order.
    pub fn run(&mut self, event_handler: &mut PushrodCallbackEvents) {
        let mut last_widget_id = -1;
        let mut previous_mouse_position: Point = make_origin_point();
        let mut button_map: HashMap<i32, HashSet<Button>> = HashMap::new();
        let injectable_map: Vec<i32> = self
            .widget_store
            .borrow_mut()
            .widgets
            .iter()
            .filter(|x| x.widget.borrow_mut().injects_events())
            .map(|x| x.widget_id)
            .collect();

        while let Some(ref event) = &self.window.next() {
            event.mouse_cursor(|x, y| {
                let mouse_point = make_point_f64(x, y);

                if mouse_point.x != previous_mouse_position.x
                    || mouse_point.y != previous_mouse_position.y
                {
                    previous_mouse_position = mouse_point.clone();

                    let current_widget_id = self
                        .widget_store
                        .borrow_mut()
                        .get_widget_id_for_point(mouse_point.clone());
                    let current_parent_for_widget = self
                        .widget_store
                        .borrow_mut()
                        .get_parent_of(current_widget_id);

                    // Handles the mouse move callback.
                    if current_widget_id != -1 {
                        self.handle_event(
                            current_widget_id,
                            event_handler,
                            CallbackEvent::MouseMoved {
                                widget_id: current_widget_id,
                                point: mouse_point.clone(),
                            },
                        );
                    }

                    if current_widget_id != last_widget_id {
                        if last_widget_id != -1 {
                            self.handle_event(
                                last_widget_id,
                                event_handler,
                                CallbackEvent::MouseExited {
                                    widget_id: last_widget_id,
                                },
                            );
                        }

                        last_widget_id = current_widget_id;

                        if last_widget_id != -1 {
                            self.handle_event(
                                last_widget_id,
                                event_handler,
                                CallbackEvent::MouseEntered {
                                    widget_id: last_widget_id,
                                },
                            );
                        }

                        eprintln!(
                            "Widget IDs: current={} parent={} children={:?}",
                            current_widget_id,
                            current_parent_for_widget,
                            self.widget_store
                                .borrow_mut()
                                .get_children_of(current_widget_id)
                        );
                    }
                }
            });

            event.mouse_scroll(|x, y| {
                let mouse_point = make_point_f64(x, y);

                if last_widget_id != -1 {
                    self.handle_event(
                        last_widget_id,
                        event_handler,
                        CallbackEvent::MouseScrolled {
                            widget_id: last_widget_id,
                            point: mouse_point.clone(),
                        },
                    );
                }
            });

            event.button(|args| match args.state {
                ButtonState::Press => {
                    button_map
                        .entry(last_widget_id)
                        .or_insert(HashSet::new())
                        .insert(args.button);

                    self.handle_event(
                        last_widget_id,
                        event_handler,
                        CallbackEvent::MouseButtonDown {
                            widget_id: last_widget_id,
                            button: args.button,
                        },
                    );
                }

                ButtonState::Release => {
                    let button_set = button_map.entry(last_widget_id).or_insert(HashSet::new());

                    if button_set.contains(&args.button) {
                        button_set.remove(&args.button);

                        self.handle_event(
                            last_widget_id,
                            event_handler,
                            CallbackEvent::MouseButtonUpInside {
                                widget_id: last_widget_id,
                                button: args.button,
                            },
                        );
                    } else {
                        for (widget_id, button_set) in button_map.iter_mut() {
                            if button_set.contains(&args.button) {
                                self.handle_event(
                                    *widget_id,
                                    event_handler,
                                    CallbackEvent::MouseButtonUpOutside {
                                        widget_id: *widget_id,
                                        button: args.button,
                                    },
                                );

                                button_set.remove(&args.button);
                            }
                        }
                    }
                }
            });

            event.resize(|w, h| {
                event_handler.handle_event(
                    CallbackEvent::WindowResized {
                        size: crate::core::point::Size {
                            w: w as i32,
                            h: h as i32,
                        },
                    },
                    &mut self.widget_store.borrow_mut(),
                );
            });

            event.focus(|focused| {
                self.handle_event(
                    last_widget_id,
                    event_handler,
                    CallbackEvent::WindowFocused { flag: focused },
                );
            });

            match event {
                Event::Input(Input::Button(ButtonArgs {
                    state,
                    button: Button::Keyboard(key),
                    scancode: _,
                })) => {
                    self.handle_event(
                        last_widget_id,
                        event_handler,
                        CallbackEvent::KeyPressed {
                            widget_id: last_widget_id,
                            key: *key,
                            state: *state,
                        },
                    );
                }
                _ => {}
            };

            event.resize(|_, _| {
                self.widget_store.borrow_mut().invalidate_all_widgets();
            });

            // FPS loop handling

            event.render(|_| {
                injectable_map.iter().for_each(|widget_id| {
                    let injectable_event = self
                        .widget_store
                        .borrow_mut()
                        .get_widget_for_id(*widget_id)
                        .borrow_mut()
                        .inject_event(*widget_id);

                    match injectable_event {
                        Some(x) => self.handle_event(*widget_id, event_handler, x.clone()),
                        None => (),
                    }
                });

                self.handle_draw(&event);
                self.widget_store.borrow_mut().invalidate_all_widgets();
            });
        }
    }
}