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
// Pushrod Widgets
// Cache
//
// 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 crate::properties::{
    WidgetProperties, PROPERTY_BORDER_WIDTH, PROPERTY_FONT_COLOR, PROPERTY_FONT_NAME,
    PROPERTY_FONT_SIZE, PROPERTY_FONT_STYLE, PROPERTY_HIDDEN, PROPERTY_ID, PROPERTY_INVALIDATED,
    PROPERTY_NEEDS_LAYOUT, PROPERTY_TEXT,
};
use crate::system_widgets::base_widget::BaseWidget;
use crate::widget::Widget;
use sdl2::image::LoadTexture;
use sdl2::pixels::Color;
use sdl2::rect::Rect;
use sdl2::render::{Canvas, Texture, TextureQuery};
use sdl2::ttf::{FontStyle, Sdl2TtfContext};
use sdl2::video::Window;
use std::cell::{RefCell, RefMut};
use std::collections::HashMap;
use std::path::Path;

struct WidgetCacheContainer {
    widget: RefCell<Box<dyn Widget>>,
    _name: String,
    parent: u32,
    children: Vec<u32>,
}

impl WidgetCacheContainer {
    pub fn new(widget: Box<dyn Widget>, name: String, parent: u32) -> Self {
        Self {
            widget: RefCell::new(widget),
            _name: name,
            parent,
            children: Vec::new(),
        }
    }
}

/// This is the `WidgetCache` store structure.
pub struct WidgetCache {
    // TODO cache should be BTreeMap<i32, WidgetCacheContainer>
    cache: Vec<WidgetCacheContainer>,
    texture_cache: TextureCache,
}

/// This is the `WidgetCache` that is used to store `Widget` references in a drawing tree by ID.
impl WidgetCache {
    /// Creates a new `WidgetCache`, adding the `BaseWidget` to the top level of the Window, with the name
    /// `root` as the root `Widget`.  This `Widget` can be modified like any other - its properties
    /// can be changed, background color, border color, etc. can all be manipulated just like any
    /// other `Widget`.  Its ID is `0`.
    pub fn new(w: u32, h: u32) -> Self {
        let mut base_widget = BaseWidget::default();

        base_widget
            .properties()
            .set_bounds(w, h)
            .set_origin(0, 0)
            .invalidate();

        Self {
            cache: vec![WidgetCacheContainer::new(
                Box::new(base_widget),
                String::from("root"),
                0,
            )],
            texture_cache: TextureCache::default(),
        }
    }

    /// Retrieves the ID of the widget at the X/Y coordinates given.
    ///
    /// Follows the following rules:
    /// - If the object is hidden, any objects underneath that object are short-circuited
    /// - If an object is visible, it walks the object's children to see if they are within the same
    ///   given coordinates
    ///
    /// The found ID is then returned having met all of those criteria.  If no ID was found, a
    /// 0 value (root level widget) is returned.
    #[inline]
    pub fn id_at_point(&self, x: u32, y: u32) -> u32 {
        let mut found_id: u32 = 0;
        let mut hidden_widgets: Vec<u32> = vec![];
        let cache_size = self.size();

        for id in 0..cache_size {
            let is_hidden = self.cache[id as usize]
                .widget
                .borrow_mut()
                .properties()
                .get_bool(PROPERTY_HIDDEN);
            let widget_xy = self.cache[id as usize]
                .widget
                .borrow_mut()
                .properties()
                .get_origin();
            let widget_wh = self.cache[id as usize]
                .widget
                .borrow_mut()
                .properties()
                .get_bounds();

            if !is_hidden {
                if x >= widget_xy.0
                    && x <= widget_xy.0 + widget_wh.0
                    && y >= widget_xy.1
                    && y <= widget_xy.1 + widget_wh.1
                    && !hidden_widgets.contains(&id)
                {
                    found_id = id;
                }
            } else {
                hidden_widgets.push(id);

                for hidden_widget_id in self.get_children_of(id) {
                    hidden_widgets.push(hidden_widget_id);
                }
            }
        }

        found_id
    }

    /// Retrieves the `Widget` stored by its `RefMut<Box>` reference.  This is a mutable reference
    /// to the `Widget`, allowing for its properties and other accessors to be immutably changed.
    #[inline]
    pub fn get(&self, widget_id: u32) -> RefMut<Box<dyn Widget>> {
        self.cache[widget_id as usize].widget.borrow_mut()
    }

    /// Retrieves the `Widget` stored by its `RefMut<Box>` reference.  This is a mutable reference
    /// to the `Widget`, allowing for its properties and other accessors to be mutably changed.
    #[inline]
    pub fn get_mut(&mut self, widget_id: u32) -> RefMut<Box<dyn Widget>> {
        self.cache[widget_id as usize].widget.borrow_mut()
    }

    /// Retrieves the parent ID of the widget ID specified.  If the widget is a top level widget (meaning
    /// there are no additional parents), a 0 will be returned.
    #[inline]
    pub fn get_parent_of(&self, widget_id: u32) -> u32 {
        self.cache[widget_id as usize].parent
    }

    /// Retrieves a list of children for the specified widget ID.  The child listing will always
    /// return a `Vec` - if any widgets have been added to this `Widget` as a parent, those IDs
    /// will be returned here.  If this widget has no children, an empty `Vec` will be returned.
    #[inline]
    pub fn get_children_of(&self, widget_id: u32) -> Vec<u32> {
        self.cache[widget_id as usize].children.clone()
    }

    /// Adds a new `Widget` to the cache, with the given mutable `Widget`, a name for the `Widget`,
    /// and the `Widget`'s parent ID.
    #[inline]
    pub fn add(&mut self, mut widget: Box<dyn Widget>, widget_name: String, parent_id: u32) -> u32 {
        // use get_by_name to make sure the widget doesn't already exist by name.  If it does,
        // throw an error.

        // Invalidate the Widget just in case.
        widget.invalidate();

        self.cache
            .push(WidgetCacheContainer::new(widget, widget_name, parent_id));

        let widget_id = self.size() - 1;

        self.cache[parent_id as usize].children.push(widget_id);
        self.cache[widget_id as usize]
            .widget
            .borrow_mut()
            .properties()
            .set_value(PROPERTY_ID, widget_id as i32);

        widget_id
    }

    /// Adds a list of `Widget`s, storing the IDs resulting from each add, to the parent ID.
    pub fn add_vec(&mut self, widgets: Vec<Box<dyn Widget>>, parent_id: u32) -> Vec<u32> {
        let mut return_vec: Vec<u32> = Vec::new();

        for widget in widgets {
            return_vec.push(self.add(widget, format!("widget{}", self.size() - 1), parent_id));
        }

        return_vec
    }

    /// Retrieves the total number of `Widget`s in the cache.
    #[inline]
    pub fn size(&self) -> u32 {
        self.cache.len() as u32
    }

    /// Sets the `Widget` ID's `PROPERTY_HIDDEN` value to true/false based on the `state` specified.
    /// Walks the child IDs of each of the `Widget`'s children and hides their IDs.  Does not allow
    /// for the root ID (`widget_id == 0`) to be hidden.
    #[inline]
    pub fn set_hidden(&mut self, widget_id: u32, state: bool) {
        if widget_id == 0 {
            return;
        }

        if !state {
            self.get(widget_id).hide();
        } else {
            self.get(widget_id).show();
        }

        let children = self.get_children_of(widget_id);

        for child_widget_id in children {
            self.set_hidden(child_widget_id, state);
        }
    }

    /// Determines whether any of the `Widget`s in the cache have indicated that they need to be
    /// redrawn.
    #[inline]
    pub fn invalidated(&self) -> bool {
        for x in &self.cache {
            if x.widget.borrow_mut().invalidated() {
                return true;
            }
        }

        false
    }

    /// Determines whether any of the `Widget`s in the cache have indicated that they need to extend
    /// a layout to the `WidgetCache`.
    #[inline]
    pub fn needs_layout(&self) -> bool {
        for x in &self.cache {
            if x.widget
                .borrow_mut()
                .properties()
                .get_bool(PROPERTY_NEEDS_LAYOUT)
            {
                return true;
            }
        }

        false
    }

    fn paint_widget(&mut self, widget_id: u32, c: &mut Canvas<Window>) {
        let paint_widget = &mut self.cache[widget_id as usize];
        let is_hidden = paint_widget
            .widget
            .borrow_mut()
            .properties()
            .get_bool(PROPERTY_HIDDEN);
        let widget_xy = paint_widget.widget.borrow_mut().properties().get_origin();
        let widget_wh = paint_widget.widget.borrow_mut().properties().get_bounds();

        if !is_hidden {
            match paint_widget
                .widget
                .borrow_mut()
                .draw(c, &mut self.texture_cache)
            {
                Some(texture) => {
                    c.copy(
                        texture,
                        None,
                        Rect::new(
                            widget_xy.0 as i32,
                            widget_xy.1 as i32,
                            widget_wh.0,
                            widget_wh.1,
                        ),
                    )
                    .unwrap();
                }
                None => eprintln!("No texture presented: ID={}", widget_id),
            };

            paint_widget
                .widget
                .borrow_mut()
                .properties()
                .delete(PROPERTY_INVALIDATED);
        }
    }

    /// Recursive drawing function that takes a `Widget`'s ID, and gets a list of the children that
    /// are owned for that `Widget`.  It then walks the tree of all of the children, and draws the
    /// contents into a `Texture`.  The `TextureCache` is sent such that the `Widget` has the ability
    /// to load in an image, or render a font.  This cache should be used sparingly.
    ///
    /// If a draw method is called on a `Widget` but the `Widget` has not been invalidated (meaning
    /// it does not to be redrawn), the cached `Texture` for the `Widget`'s draw surface is returned,
    /// which is a reference to an `SDL2 Texture`.  This way, the image from GPU memory is simply
    /// copied back to screen in a very quick operation.
    ///
    /// Any `Widget`s that have a property of `PROPERTY_HIDDEN` set will short circuit the draw
    /// for that `Widget` and its children.
    ///
    /// Drawing is computed off-screen in GPU memory, so this is also a very fast operation, which
    /// should theoretically take place in less than a single draw frame.
    fn draw(&mut self, widget_id: u32, c: &mut Canvas<Window>) {
        let children_of_widget = self.get_children_of(widget_id);

        if children_of_widget.is_empty() {
            return;
        }

        for id in &children_of_widget {
            self.paint_widget(*id, c);

            if *id != widget_id {
                self.draw(*id, c);
            }
        }
    }

    /// Redraws the screen, redrawing any `Widget`s that have been invalidated, and copying their
    /// `Texture`s to the screen if necessary.  If none of the `Widget`s have been invalidated,
    /// the screen already contains the main `Texture` with all of the objects, so it does not
    /// make sense to run this method if the screen does not need refreshing.
    pub fn refresh(&mut self, c: &mut Canvas<Window>) {
        // Clear the canvas first.
        c.set_draw_color(Color::RGBA(255, 255, 255, 255));
        c.clear();

        self.paint_widget(0, c);
        self.draw(0, c);

        // Then swap the canvas once the draw is complete.
        c.present();
    }
}

/// This is a storage object for the `TextureCache`.
pub struct TextureCache {
    images: HashMap<String, Texture>,
    ttf_context: Sdl2TtfContext,
}

/// Default implementation for TextureCache.
impl Default for TextureCache {
    fn default() -> Self {
        Self {
            images: HashMap::new(),
            ttf_context: sdl2::ttf::init().map_err(|e| e.to_string()).unwrap(),
        }
    }
}

/// The `TextureCache` provides a mechanism for caching images, and returning the current
/// text rendering context.
impl TextureCache {
    /// Returns the currently available text context as a reference.
    pub fn get_ttf_context(&self) -> &Sdl2TtfContext {
        &self.ttf_context
    }

    /// Returns an image loaded into a `Texture` reference, caching it in memory.
    pub fn get_image(&mut self, c: &mut Canvas<Window>, image_name: String) -> &Texture {
        self.images.entry(image_name.clone()).or_insert({
            c.texture_creator()
                .load_texture(Path::new(&image_name))
                .unwrap()
        })
    }

    /// Renders text, given the font name, size, style, color, string, and max width.  Transfers
    /// ownership of the `Texture` to the calling function, returns the width and height of the
    /// texture after rendering.  By using the identical font name, size, and style, if SDL2 caches
    /// the font data, this will allow the font to be cached internally.
    pub fn render_text(
        &mut self,
        c: &mut Canvas<Window>,
        properties: &mut WidgetProperties,
        alt_color: Option<Color>,
    ) -> (Texture, u32, u32) {
        let ttf_context = self.get_ttf_context();
        let texture_creator = c.texture_creator();
        let bounds = properties.get_bounds();
        let font_name = properties.get(PROPERTY_FONT_NAME);
        let text_color =
            alt_color.unwrap_or_else(|| properties.get_color(PROPERTY_FONT_COLOR, Color::BLACK));
        let font_size = properties.get_value(PROPERTY_FONT_SIZE);
        let border_width = properties.get_value(PROPERTY_BORDER_WIDTH);
        let font_style: FontStyle =
            FontStyle::from_bits_truncate(properties.get_value(PROPERTY_FONT_STYLE));
        let text_message = properties.get(PROPERTY_TEXT);
        let mut font = ttf_context
            .load_font(Path::new(&font_name), font_size as u16)
            .unwrap();
        let text_max_width = bounds.0;
        let surface = font
            .render(&text_message)
            .blended_wrapped(text_color, text_max_width - (border_width * 2) as u32)
            .map_err(|e| e.to_string())
            .unwrap();
        let font_texture = texture_creator
            .create_texture_from_surface(&surface)
            .map_err(|e| e.to_string())
            .unwrap();
        let TextureQuery { width, height, .. } = font_texture.query();

        font.set_style(font_style);

        (font_texture, width, height)
    }
}