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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
// Widget Base Definition
//
// 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 piston_window::*;

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

/// Implementable trait that is used by every `Widget`.  These are the public methods,
/// and a function _may_ override them.
///
/// You _must_ implement the following methods:
///
/// - config
/// - callbacks
///
/// You _should_ override `draw`, but you are not required to.  (If you don't, however, your
/// widget won't really do much.)
///
/// If you want a blank base widget, refer to the `CanvasWidget`, which will create a
/// base widget that paints the contents of its bounds with whatever color has been
/// specified with `set_color`.
pub trait Widget {
    /// Retrieves the configuration HashMap that stores the configuration list of settings
    /// for this widget.
    ///
    /// To implement this, the following code could be used in your object's structure:
    ///
    /// ```
    /// # use pushrod::widget::widget::*;
    /// # use pushrod::widget::config::*;
    /// struct MyWidget {
    ///   config: Configurable,
    /// }
    ///
    /// impl MyWidget {
    ///   fn new() -> Self {
    ///     Self {
    ///       config: Configurable::new(),
    ///     }
    ///   }
    /// }
    /// ```
    ///
    /// And in the overridden function for get_config in your implementation, use:
    ///
    /// ```
    /// # use pushrod::widget::widget::*;
    /// # use pushrod::widget::config::*;
    /// # use pushrod::core::callbacks::*;
    /// # use pushrod::core::point::Point;
    /// struct MyWidget {
    ///   config: Configurable,
    ///   callbacks: CallbackStore,
    /// }
    ///
    /// impl Widget for MyWidget {
    ///   fn config(&mut self) -> &mut Configurable {
    ///     &mut self.config
    ///   }
    ///
    ///   fn callbacks(&mut self) -> &mut CallbackStore {
    ///     &mut self.callbacks
    ///   }
    ///
    ///   // Not necessary below, but here for illustration if you want to override these calls.
    ///   fn mouse_entered(&mut self, widget_id: i32) {}
    ///   fn mouse_exited(&mut self, widget_id: i32) {}
    ///   fn mouse_scrolled(&mut self, widget_id: i32, point: Point) {}
    /// }
    /// ```
    ///
    /// This uses a `RefCell`, since configurations require a mutable reference to the HashMap
    /// that stores the configs.
    fn config(&mut self) -> &mut Configurable;

    /// Returns the `CallbackStore` for this `Widget`.  This contains a set of callbacks that only
    /// apply to this `Widget`.
    fn callbacks(&mut self) -> &mut CallbackStore;

    /// Indicates that a widget needs to be redrawn/refreshed.
    fn invalidate(&mut self) {
        self.config().set(Invalidate);
    }

    /// Clears the invalidation flag.
    fn clear_invalidate(&mut self) {
        self.config().remove::<Invalidate>();
    }

    /// Checks to see whether or not the widget needs to be redrawn/refreshed.
    fn is_invalidated(&mut self) -> bool {
        self.config().contains_key::<Invalidate>()
    }

    /// Sets the `Point` of origin for this widget, given the X and Y origin points.  Invalidates the widget afterward.
    fn set_origin(&mut self, x: i32, y: i32) {
        self.config().set(Origin(Point { x, y }));
        self.invalidate();
    }

    /// Retrieves the `Point` of origin for this object.
    /// Defaults to origin (0, 0) if not set.
    fn get_origin(&mut self) -> Point {
        self.config()
            .get::<Origin>()
            .unwrap_or(&Origin(Point { x: 0, y: 0 }))
            .0
            .clone()
    }

    /// Sets the `Size` for this widget, given a width and height.  Invalidates the widget afterward.
    fn set_size(&mut self, w: i32, h: i32) {
        self.config()
            .set(BodySize(crate::core::point::Size { w, h }));
        self.invalidate();
    }

    /// Retrieves the `Size` bounds for this widget.
    /// Defaults to size (0, 0) if not set.
    fn get_size(&mut self) -> crate::core::point::Size {
        self.config()
            .get::<BodySize>()
            .unwrap_or(&BodySize(crate::core::point::Size { w: 0, h: 0 }))
            .0
            .clone()
    }

    /// Sets the color for this widget.  Invalidates the widget afterward.
    fn set_color(&mut self, color: types::Color) {
        self.config().set(MainColor(color));
        self.invalidate();
    }

    /// Retrieves the color of this widget.
    /// Defaults to white color `[1.0; 4]` if not set.
    fn get_color(&mut self) -> types::Color {
        self.config()
            .get::<MainColor>()
            .unwrap_or(&MainColor([1.0; 4]))
            .0
    }

    // Callbacks

    /// Performs a callback stored in the `CallbackStore` for this `Widget`, but only for the
    /// `CallbackTypes::SingleCallback` enum type.  If the callback does not exist, or is not
    /// defined properly, it will be silently dropped and ignored.
    fn perform_single_callback(&mut self, callback_id: u32, widget_id: i32) {
        match self.callbacks().get(callback_id) {
            CallbackTypes::SingleCallback { callback } => callback(widget_id),
            _ => (),
        }
    }

    /// Performs a callback stored in the `CallbackStore` for this `Widget`, but only for the
    /// `CallbackTypes::BoolCallback` enum type.  If the callback does not exist, or is not
    /// defined properly, it will be silently dropped and ignored.
    fn perform_bool_callback(&mut self, callback_id: u32, widget_id: i32, flag: bool) {
        match self.callbacks().get(callback_id) {
            CallbackTypes::BoolCallback { callback } => callback(widget_id, flag),
            _ => (),
        }
    }

    /// Performs a callback stored in the `CallbackStore` for this `Widget`, but only for the
    /// `CallbackTypes::PointCallback` enum type.  If the callback does not exist, or is not
    /// defined properly, it will be silently dropped and ignored.
    fn perform_point_callback(&mut self, callback_id: u32, widget_id: i32, point: Point) {
        match self.callbacks().get(callback_id) {
            CallbackTypes::PointCallback { callback } => callback(widget_id, point.clone()),
            _ => (),
        }
    }

    /// Performs a callback stored in the `CallbackStore` for this `Widget`, but only for the
    /// `CallbackTypes::SizeCallback` enum type.  If the callback does not exist, or is not
    /// defined properly, it will be silently dropped and ignored.
    fn perform_size_callback(
        &mut self,
        callback_id: u32,
        widget_id: i32,
        size: crate::core::point::Size,
    ) {
        match self.callbacks().get(callback_id) {
            CallbackTypes::SizeCallback { callback } => callback(widget_id, size.clone()),
            _ => (),
        }
    }

    fn perform_button_callback(&mut self, callback_id: u32, widget_id: i32, button: Button) {
        match self.callbacks().get(callback_id) {
            CallbackTypes::ButtonCallback { callback } => callback(widget_id, button),
            _ => (),
        }
    }

    /// Performs a callback stored in the `CallbackStore` for this `Widget`, but only for the
    /// `CallbackTypes::KeyCallback` enum type.  If the callback does not exist, or is not
    /// defined properly, it will be silently dropped and ignored.
    fn perform_key_callback(
        &mut self,
        callback_id: u32,
        widget_id: i32,
        key: Key,
        state: ButtonState,
    ) {
        match self.callbacks().get(callback_id) {
            CallbackTypes::KeyCallback { callback } => {
                callback(widget_id, key.clone(), state.clone())
            }
            _ => (),
        }
    }

    // Callback Triggers

    /// Called when a keyboard event takes place within the bounds of a widget.  Includes the widget
    /// ID, the key code that was affected, and its state - pressed or released.
    fn key_pressed(&mut self, widget_id: i32, key: &Key, state: &ButtonState) {
        self.perform_key_callback(CALLBACK_KEY_PRESSED, widget_id, key.clone(), state.clone());
    }

    /// Called when a mouse enters the bounds of the widget.  Includes the widget ID.  Only override
    /// if you want to signal a mouse enter event.
    fn mouse_entered(&mut self, widget_id: i32) {
        self.perform_single_callback(CALLBACK_MOUSE_ENTERED, widget_id);
    }

    /// Called when a mouse exits the bounds of the widget.  Includes the widget ID.  Only override
    /// if you want to signal a mouse exit event.
    fn mouse_exited(&mut self, widget_id: i32) {
        self.perform_single_callback(CALLBACK_MOUSE_EXITED, widget_id);
    }

    /// Called when a scroll event is called within the bounds of the widget.  Includes the widget ID.
    /// Only override if you want to signal a mouse scroll event.
    fn mouse_scrolled(&mut self, widget_id: i32, point: Point) {
        self.perform_point_callback(CALLBACK_MOUSE_SCROLLED, widget_id, point.clone());
    }

    /// Called when the mouse pointer is moved inside a widget.  Includes the widget ID and point.
    /// Only override if you want to track mouse movement.
    fn mouse_moved(&mut self, widget_id: i32, point: Point) {
        self.perform_point_callback(CALLBACK_MOUSE_MOVED, widget_id, point.clone());
    }

    /// Called when the main window is resized.  Includes the widget ID and the new window size.
    /// Only override if you want to respond to a window resize (and if the window is resizable.)
    fn window_resized(&mut self, widget_id: i32, size: crate::core::point::Size) {
        self.perform_size_callback(CALLBACK_WINDOW_RESIZED, widget_id, size.clone());
    }

    /// Called when a window focus state changes.  Includes the widget ID and a focus flag: `true`
    /// when window gains focus, `false` otherwise.  Only override if you want to signal a window
    /// focus event.
    fn window_focused(&mut self, widget_id: i32, focused: bool) {
        self.perform_bool_callback(CALLBACK_WINDOW_FOCUSED, widget_id, focused);
    }

    /// Called when a mouse button is clicked down.  Includes the widget ID and the button code.
    /// Only override if you want to respond to a mouse click.
    fn button_down(&mut self, widget_id: i32, button: Button) {
        self.perform_button_callback(CALLBACK_BUTTON_DOWN, widget_id, button);
    }

    /// Called when a mouse button is released inside the same `Widget` that it was clicked inside.
    /// Includes the widget ID and the button code.  Only override if you want to respond to a mouse
    /// button release.
    fn button_up_inside(&mut self, widget_id: i32, button: Button) {
        self.perform_button_callback(CALLBACK_BUTTON_UP_INSIDE, widget_id, button);
    }

    /// Called when a mouse button is released outside the same `Widget` that it was clicked inside.
    /// Includes the widget ID and the button code.  Only override if you want to respond to a mouse
    /// button release.
    fn button_up_outside(&mut self, widget_id: i32, button: Button) {
        self.perform_button_callback(CALLBACK_BUTTON_UP_OUTSIDE, widget_id, button);
    }

    // Callback Setters
    fn on_key_pressed(&mut self, callback: KeyCallback) {
        self.callbacks().put(
            CALLBACK_KEY_PRESSED,
            CallbackTypes::KeyCallback { callback },
        );
    }

    /// Sets the closure action to be performed when a mouse enters a `Widget`.
    fn on_mouse_entered(&mut self, callback: SingleCallback) {
        self.callbacks().put(
            CALLBACK_MOUSE_ENTERED,
            CallbackTypes::SingleCallback { callback },
        );
    }

    /// Sets the closure action to be performed when a mouse exits a `Widget`.
    fn on_mouse_exited(&mut self, callback: SingleCallback) {
        self.callbacks().put(
            CALLBACK_MOUSE_EXITED,
            CallbackTypes::SingleCallback { callback },
        );
    }

    /// Sets the closure action to be performed when a mouse scrolls inside a `Widget`.
    fn on_mouse_scrolled(&mut self, callback: PointCallback) {
        self.callbacks().put(
            CALLBACK_MOUSE_SCROLLED,
            CallbackTypes::PointCallback { callback },
        );
    }

    /// Sets the closure action to be performed when a mouse moves within a `Widget`.  The mouse
    /// point is based on the position within the `Widget`, not its `Point` relative to the window.
    fn on_mouse_moved(&mut self, callback: PointCallback) {
        self.callbacks().put(
            CALLBACK_MOUSE_MOVED,
            CallbackTypes::PointCallback { callback },
        );
    }

    /// Sets the window resize action to be performed when the window is resized.
    fn on_window_resized(&mut self, callback: SizeCallback) {
        self.callbacks().put(
            CALLBACK_WINDOW_RESIZED,
            CallbackTypes::SizeCallback { callback },
        );
    }

    /// Sets the window focused action to be performed when the window is (un)focused.
    fn on_focused(&mut self, callback: BoolCallback) {
        self.callbacks().put(
            CALLBACK_WINDOW_FOCUSED,
            CallbackTypes::BoolCallback { callback },
        );
    }

    /// Sets the button click action to be performed when a mouse button is clicked.
    fn on_button_down(&mut self, callback: ButtonCallback) {
        self.callbacks().put(
            CALLBACK_BUTTON_DOWN,
            CallbackTypes::ButtonCallback { callback },
        )
    }

    /// Sets the callback to be performed when a mouse button is released within the same `Widget`
    /// that it was pressed down inside.
    fn on_button_up_inside(&mut self, callback: ButtonCallback) {
        self.callbacks().put(
            CALLBACK_BUTTON_UP_INSIDE,
            CallbackTypes::ButtonCallback { callback },
        )
    }

    /// Sets the callback to be performed when a mouse button is released outside of the same `Widget`
    /// that it was pressed down inside.
    fn on_button_up_outside(&mut self, callback: ButtonCallback) {
        self.callbacks().put(
            CALLBACK_BUTTON_UP_OUTSIDE,
            CallbackTypes::ButtonCallback { callback },
        )
    }

    // Draw routines

    /// Draws the contents of the widget, provided a `piston2d` `Context` and `G2d` object.
    ///
    /// It is **highly recommended** that you call `clear_invalidate()` after the draw completes,
    /// otherwise, this will continue to be redrawn continuously (unless this is the desired
    /// behavior.)
    fn draw(&mut self, c: Context, g: &mut G2d, clip: &DrawState) {
        let size: crate::core::point::Size = self.get_size();

        Rectangle::new(self.get_color()).draw(
            [0.0 as f64, 0.0 as f64, size.w as f64, size.h as f64],
            clip,
            c.transform,
            g,
        );

        self.clear_invalidate();
    }
}

/// This is the `CanvasWidget`, which contains a top-level widget for display.  It does
/// not contain any special logic other than being a base for a display layer.
///
/// Example usage:
/// ```no_run
/// # use piston_window::*;
/// # use pushrod::core::point::*;
/// # use pushrod::core::main::*;
/// # use pushrod::widget::widget::*;
/// # fn main() {
/// #   let mut prod: Pushrod = Pushrod::new(
/// #       WindowSettings::new("Pushrod Window", [640, 480])
/// #           .opengl(OpenGL::V3_2)
/// #           .build()
/// #           .unwrap_or_else(|error| panic!("Failed to build PistonWindow: {}", error)));
/// #
///    let mut base_widget = CanvasWidget::new();
///
///    base_widget.set_origin(100, 100);
///    base_widget.set_size(200, 200);
///    base_widget.set_color([0.5, 0.5, 0.5, 1.0]);
///
///    // Widgets must be boxed, as they are trait objects.
///    let widget_id = prod.widget_store.add_widget(Box::new(base_widget));
///
///    eprintln!("Added widget: ID={}", widget_id);
///
///    let mut base_widget_2 = CanvasWidget::new();
///
///    base_widget_2.set_origin(125, 125);
///    base_widget_2.set_size(100, 100);
///    base_widget_2.set_color([0.75, 0.75, 0.75, 1.0]);
///
///    // Add the second widget to the top level base widget.
///    let widget_id_2 = prod.widget_store.add_widget_to_parent(Box::new(base_widget_2), widget_id);
/// # }
/// ```
pub struct CanvasWidget {
    config: Configurable,
    callbacks: CallbackStore,
}

/// Implementation of the constructor for the `CanvasWidget`.  Creates a new base widget
/// that can be positioned anywhere on the screen.
impl CanvasWidget {
    pub fn new() -> Self {
        Self {
            config: Configurable::new(),
            callbacks: CallbackStore::new(),
        }
    }
}

/// Implementation of the `CanvasWidget` object with the `Widget` traits implemented.
/// This function only implements `config` and `callbacks`, which are used as a base for
/// all `Widget`s.
impl Widget for CanvasWidget {
    fn config(&mut self) -> &mut Configurable {
        &mut self.config
    }

    fn callbacks(&mut self) -> &mut CallbackStore {
        &mut self.callbacks
    }
}