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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
// Window Container
// Contains a PistonWindow and a list of widgets
//
// 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 gl::types::GLuint;
use graphics::*;
use opengl_graphics::GlGraphics;
use std::cell::RefCell;

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

/// This is a container object that stores a `Widget`, assigns a name, a `Widget` ID, and its
/// parent.
pub struct WidgetContainer {
    /// The `Widget` being stored.
    pub widget: RefCell<Box<dyn Widget>>,

    widget_name: String,

    /// The `Widget`'s automatically assigned ID.
    pub widget_id: i32,

    parent_id: i32,
}

pub struct LayoutManagerContainer {
    pub container_id: i32,
    pub widget_ids: RefCell<Vec<i32>>,
    pub widget_positions: RefCell<Vec<Point>>,
    pub layout_manager: RefCell<Box<dyn LayoutManager>>,
}

/// This is the `WidgetStore`, which contains a list of `Widget` objects for a GUI window.
pub struct WidgetStore {
    pub widgets: Vec<WidgetContainer>,
    pub layout_managers: Vec<LayoutManagerContainer>,
}

impl WidgetStore {
    /// Constructor, creates a new `WidgetStore`, assigning a top-level `CanvasWidget` as the
    /// very top-level widget.  All `Widget` objects added will be a parent to this `Widget`,
    /// which is stored at ID 0.  If this `Widget` object ever becomes invalidated, the entire
    /// window is force refreshed.
    pub fn new() -> Self {
        let mut widgets_list: Vec<WidgetContainer> = Vec::new();
        let mut base_widget = CanvasWidget::new();

        base_widget.config().set(
            CONFIG_BODY_SIZE,
            Config::Size(crate::core::point::Size { w: 800, h: 600 }),
        );
        widgets_list.push(WidgetContainer {
            widget: RefCell::new(Box::new(base_widget)),
            widget_name: String::from("_WidgetStoreBase"),
            widget_id: 0,
            parent_id: 0,
        });

        Self {
            widgets: widgets_list,
            layout_managers: Vec::new(),
        }
    }

    /// Invalidates all `Widget`s in the GUI stack, forcing a redraw.
    pub fn invalidate_all_widgets(&mut self) {
        self.widgets
            .iter_mut()
            .for_each(|x| x.widget.borrow_mut().invalidate());
    }

    /// Indicates whether or not a widget in the store has been invalidated.
    pub fn needs_repaint(&mut self) -> bool {
        self.widgets
            .iter_mut()
            .map(|x| x.widget.borrow_mut().is_invalidated())
            .find(|x| x == &true)
            .unwrap_or(false)
    }

    /// Adds a `Widget` to the stack by name.
    pub fn add_widget(&mut self, name: &str, widget: Box<dyn Widget>) -> i32 {
        let widget_size = self.widgets.len() as i32;
        let container = WidgetContainer {
            widget: RefCell::new(widget),
            widget_name: String::from(name),
            widget_id: widget_size,
            parent_id: 0,
        };

        // #117 - assigns widget ID to itself
        container
            .widget
            .borrow_mut()
            .config()
            .set_numeric(CONFIG_WIDGET_ID, widget_size as u64);

        self.widgets.push(container);

        widget_size
    }

    /// Adds a `Widget` object to the parent specified by ID.
    pub fn add_widget_to_parent(
        &mut self,
        name: &str,
        widget: Box<dyn Widget>,
        parent_id: i32,
    ) -> i32 {
        // TODO Validate parent_id
        let widget_size = self.widgets.len() as i32;
        let container = WidgetContainer {
            widget: RefCell::new(widget),
            widget_name: String::from(name),
            widget_id: widget_size,
            parent_id,
        };

        // #117 - assigns widget ID to itself
        container
            .widget
            .borrow_mut()
            .config()
            .set_numeric(CONFIG_WIDGET_ID, widget_size as u64);

        self.widgets.push(container);

        widget_size
    }

    /// Gets the parent of the child `Widget` by ID.  If the child has no assigned parent, the
    /// top-level `CanvasWidget` is returned (ID 0).
    pub fn get_parent_of(&mut self, widget_id: i32) -> i32 {
        if widget_id <= 0 {
            0
        } else {
            self.widgets[widget_id as usize].parent_id
        }
    }

    /// Returns a list of the children that are owned by a parent ID.  Does not return a list of
    /// siblings, only the first-level children.
    pub fn get_children_of(&self, parent_id: i32) -> Vec<i32> {
        self.widgets
            .iter()
            .filter(|x| x.parent_id == parent_id)
            .map(|x| x.widget_id)
            .collect()
    }

    /// Gets a `Widget` by ID for a point in the screen.  If the GUI object is hidden or disabled,
    /// the ID is not returned.  If no widget is found under the point specified, an ID of -1 is
    /// returned.
    pub fn get_widget_id_for_point(&mut self, point: Point) -> i32 {
        let mut found_id = -1;

        for (pos, obj) in self.widgets.iter_mut().enumerate() {
            let hidden = *&obj
                .widget
                .borrow_mut()
                .config()
                .get_toggle(CONFIG_WIDGET_HIDDEN);
            let disabled = *&obj
                .widget
                .borrow_mut()
                .config()
                .get_toggle(CONFIG_WIDGET_DISABLED);

            if !hidden && !disabled {
                let widget_point = &obj.widget.borrow_mut().config().get_point(CONFIG_ORIGIN);
                let widget_size: crate::core::point::Size =
                    obj.widget.borrow_mut().config().get_size(CONFIG_BODY_SIZE);

                // Skip over item widgets that have a width and height of 0.
                if widget_size.w > 0 && widget_size.h > 0 {
                    if point.x >= widget_point.x
                        && point.x <= widget_point.x + widget_size.w
                        && point.y >= widget_point.y
                        && point.y <= widget_point.y + widget_size.h
                    {
                        found_id = pos as i32;
                    }
                }
            }
        }

        found_id
    }

    /// Returns the name of the `Widget` by specified ID.
    pub fn get_name_for_widget_id(&mut self, widget_id: i32) -> &str {
        self.widgets[widget_id as usize].widget_name.as_str()
    }

    /// Retrieves a widget ID for the name specified.  Returns top-level `CanvasWidget` ID if
    /// not found.
    pub fn get_widget_id_for_name(&mut self, name: &str) -> i32 {
        match self
            .widgets
            .iter_mut()
            .find(|x| x.widget_name == String::from(name))
        {
            Some(x) => x.widget_id,
            None => 0,
        }
    }

    /// Retrieves a reference to a `Widget` by its name.  Returns the top-level `CanvasWidget`
    /// object if not found.
    pub fn get_widget_for_name(&mut self, name: &str) -> &RefCell<Box<dyn Widget>> {
        let widget_id = match self
            .widgets
            .iter_mut()
            .find(|x| x.widget_name == String::from(name))
        {
            Some(x) => x.widget_id,
            None => 0,
        };

        self.get_widget_for_id(widget_id)
    }

    /// Retrieves a `Widget` by its ID.
    pub fn get_widget_for_id(&mut self, id: i32) -> &RefCell<Box<dyn Widget>> {
        &self.widgets[id as usize].widget
    }

    /// Handles a specific event generated by the OS or the GUI interaction.
    pub fn handle_event(&mut self, widget_id: i32, event: CallbackEvent) -> Option<CallbackEvent> {
        self.widgets[widget_id as usize]
            .widget
            .borrow_mut()
            .handle_event(false, event)
    }

    /// Injects an event to all widgets, allowing them to exhibit custom event handling behavior if
    /// required.  This is usually used in cases where special triggering needs to take place, like
    /// an indication of a timeout or transient error.
    pub fn inject_event(&mut self, event: CallbackEvent) {
        self.widgets.iter_mut().for_each(|x| {
            x.widget.borrow_mut().handle_event(true, event.clone());
        });
    }

    // --- Layout Manager Routines ---

    pub fn add_layout_manager(&mut self, manager: Box<dyn LayoutManager>) -> i32 {
        let managers_size = self.layout_managers.len() as i32;

        self.layout_managers.push(LayoutManagerContainer {
            container_id: managers_size,
            widget_ids: RefCell::new(Vec::new()),
            widget_positions: RefCell::new(Vec::new()),
            layout_manager: RefCell::new(manager),
        });

        managers_size
    }

    fn get_widget_origins(&mut self, manager_id: i32) -> Vec<Point> {
        let mut widget_ids_copy = self.layout_managers[manager_id as usize]
            .widget_ids
            .borrow_mut()
            .clone();

        widget_ids_copy
            .iter_mut()
            .map(|x| {
                self.get_widget_for_id(*x)
                    .borrow_mut()
                    .config()
                    .get_point(CONFIG_ORIGIN)
            })
            .collect()
    }

    fn get_widget_sizes(&mut self, manager_id: i32) -> Vec<Size> {
        let mut widget_ids_copy = self.layout_managers[manager_id as usize]
            .widget_ids
            .borrow_mut()
            .clone();

        widget_ids_copy
            .iter_mut()
            .map(|x| {
                self.get_widget_for_id(*x)
                    .borrow_mut()
                    .config()
                    .get_size(CONFIG_BODY_SIZE)
            })
            .collect()
    }

    pub fn do_layout_for_manager(&mut self, manager_id: i32) {
        let widget_origins = self.get_widget_origins(manager_id);
        let widget_sizes = self.get_widget_sizes(manager_id);
        let widget_positions = self.layout_managers[manager_id as usize]
            .widget_positions
            .borrow()
            .clone();
        let container_widget_id = self.layout_managers[manager_id as usize]
            .layout_manager
            .borrow_mut()
            .get_widget_id();
        let master_container_origin = self
            .get_widget_for_id(container_widget_id)
            .borrow_mut()
            .config()
            .get_point(CONFIG_ORIGIN);
        let master_container_size = self
            .get_widget_for_id(container_widget_id)
            .borrow_mut()
            .config()
            .get_size(CONFIG_BODY_SIZE);
        let adjusted_sizes = self.layout_managers[manager_id as usize]
            .layout_manager
            .borrow_mut()
            .do_layout(
                master_container_origin,
                master_container_size,
                LayoutManagerCoordinates {
                    widget_origins,
                    widget_sizes,
                    widget_positions,
                },
            );

        self.layout_managers[manager_id as usize].widget_positions =
            RefCell::new(adjusted_sizes.widget_positions.clone());

        let num_widgets = adjusted_sizes.widget_positions.len();

        for x in 0..num_widgets {
            let widget_id = self.layout_managers[manager_id as usize]
                .widget_ids
                .borrow_mut()[x as usize];
            let point: Point = adjusted_sizes.widget_origins[x].clone();
            let size: Size = adjusted_sizes.widget_sizes[x].clone();
            let mut widget = self.get_widget_for_id(widget_id).borrow_mut();

            widget.config().set_point(CONFIG_ORIGIN, point.x, point.y);
            widget.config().set_size(CONFIG_BODY_SIZE, size.w, size.h);
        }

        eprintln!("Doing manager layout.");
    }

    pub fn add_widget_to_layout_manager(
        &mut self,
        name: &str,
        widget: Box<dyn Widget>,
        manager_id: i32,
        position: Point,
    ) -> i32 {
        let layout_container = &self.layout_managers[manager_id as usize];
        let layout_manager = layout_container.layout_manager.borrow();

        // Get the layout manager's top level widget ID
        let layout_manager_widget_id = layout_manager.get_widget_id();

        eprintln!(
            "Add to layout manager: widget id={}",
            layout_manager_widget_id
        );

        // Add the widget to the ID of the layout manager by add_widget_to_parent(name, widget, manager_id_widget_id)
        let widget_size = self.widgets.len() as i32;
        let container = WidgetContainer {
            widget: RefCell::new(widget),
            widget_name: String::from(name),
            widget_id: widget_size,
            parent_id: layout_manager_widget_id,
        };

        // #117 - assigns widget ID to itself
        container
            .widget
            .borrow_mut()
            .config()
            .set_numeric(CONFIG_WIDGET_ID, widget_size as u64);

        self.widgets.push(container);

        eprintln!("Added widget ID: id={}", widget_size);

        // Add to the widget_store with the widget_id and position
        layout_container.widget_ids.borrow_mut().push(widget_size);
        layout_container
            .widget_positions
            .borrow_mut()
            .push(position);

        widget_size
    }

    pub fn resize_layout_managers(&mut self, _w: u32, _h: u32) {
        let num_layout_managers = self.layout_managers.len();

        for pos in 0..num_layout_managers {
            let _layout_manager = self.layout_managers[pos as usize]
                .layout_manager
                .borrow_mut();

            eprintln!("WARNING: Unimplemented resize_layout_managers");

            //            let widget_ids = self.layout_managers[pos as usize].widget_ids.clone();
            //            let widget_positions = self.layout_managers[pos as usize].widget_positions.clone();
            //
            //            layout_manager.resize(
            //                Size {
            //                    w: w as i32,
            //                    h: h as i32,
            //                },
            //                widget_ids.borrow().clone(),
            //                widget_positions.borrow().clone(),
            //                &self.widgets,
            //            );
        }
    }

    // -- Display-related routines --

    /// Sets the hidden toggle for a parent, and all of its children.
    pub fn set_hidden(&mut self, widget_id: i32, state: bool) {
        if widget_id != 0 {
            let children = self.get_children_of(widget_id);

            children.iter().for_each(|w_id| {
                if *w_id != 0 && *w_id != widget_id {
                    &self.widgets[*w_id as usize]
                        .widget
                        .borrow_mut()
                        .set_toggle(CONFIG_WIDGET_HIDDEN, state);
                    self.set_hidden(*w_id, state);
                }
            });

            &self.widgets[widget_id as usize]
                .widget
                .borrow_mut()
                .set_toggle(CONFIG_WIDGET_HIDDEN, state);
        }
    }

    /// Draws a `Widget` by ID, and any children contained in that `Widget`.  Submitting a draw
    /// request from ID 0 will redraw the entire screen.
    pub fn draw(&mut self, widget_id: i32, c: Context, g: &mut GlGraphics, original_fbo: GLuint) {
        let parents_of_widget = self.get_children_of(widget_id);

        if parents_of_widget.len() == 0 {
            return;
        }

        for pos in 0..parents_of_widget.len() {
            c.reset();

            let paint_id = parents_of_widget[pos];
            let paint_widget = &mut self.widgets[paint_id as usize];
            let is_hidden = paint_widget
                .widget
                .borrow_mut()
                .config()
                .get_toggle(CONFIG_WIDGET_HIDDEN);
            let is_invalidated = *&paint_widget.widget.borrow_mut().is_invalidated();

            if !is_hidden && is_invalidated {
                let origin: Point = paint_widget
                    .widget
                    .borrow_mut()
                    .config()
                    .get_point(CONFIG_ORIGIN);

                let new_context: Context = Context {
                    viewport: c.viewport,
                    view: c.view,
                    transform: c.transform.trans(origin.x as f64, origin.y as f64),
                    draw_state: c.draw_state,
                };

                &paint_widget
                    .widget
                    .borrow_mut()
                    .draw(new_context, g, &c.draw_state);

                if paint_widget
                    .widget
                    .borrow_mut()
                    .config()
                    .get_toggle(CONFIG_WIDGET_DISABLED)
                {
                    &paint_widget
                        .widget
                        .borrow_mut()
                        .draw_disabled(new_context, g, &c.draw_state);
                }
            }

            if parents_of_widget[pos] != widget_id {
                self.draw(paint_id, c, g, original_fbo);
            }
        }
    }
}