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
// Pushrod Widgets
// Checkbox Button Widget
//
// 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::render::{Canvas, Texture};
use sdl2::video::Window;

use crate::caches::TextureCache;
use crate::event::PushrodEvent;
use crate::event::PushrodEvent::{
    DrawFrame, MouseButton, WidgetMouseEntered, WidgetMouseExited, WidgetSelected,
};
use crate::primitives::draw_base;
use crate::properties::{
    WidgetProperties, PROPERTY_BORDER_WIDTH, PROPERTY_ID, PROPERTY_MAIN_COLOR,
    PROPERTY_TEXT_JUSTIFICATION, PROPERTY_TOGGLED, TEXT_JUSTIFY_LEFT, TEXT_JUSTIFY_RIGHT,
};
use crate::texture_store::TextureStore;
use crate::widget::Widget;
use sdl2::pixels::Color;
use sdl2::rect::Rect;
use std::cmp::min;

/// Internal flag indicating if the button is currently accepting mouse button focus.
const PROPERTY_BUTTON_ACTIVE: u32 = 20000;

/// Internal flag indicating if the mouse is in the bounds of the `Widget`.
const PROPERTY_BUTTON_IN_BOUNDS: u32 = 20001;

/// Internal flag indicating whether or not this `Widget` originated the `MouseButton` state of `true`.
const PROPERTY_BUTTON_ORIGINATED: u32 = 20002;

/// Internal flag indicating whether or not this `Widget` has the mouse currently hovered over it, and
/// the button state is highlighted.
const PROPERTY_BUTTON_HOVERED: u32 = 20003;

/// Base Widget.
#[derive(Default)]
pub struct CheckBoxWidget {
    texture_store: TextureStore,
    properties: WidgetProperties,
}

/// Auxiliary functions for the `CheckBoxWidget`.
impl CheckBoxWidget {
    /// Sets the state to hovered, meaning the mouse has entered the bounds of the `Widget`.
    fn set_hovered(&mut self) {
        self.properties.set_bool(PROPERTY_BUTTON_HOVERED);
        self.invalidate();
    }

    /// Sets the state to unhovered, meaning the mouse has left the bounds of the `Widget`.
    fn set_unhovered(&mut self) {
        self.properties.delete(PROPERTY_BUTTON_HOVERED);
        self.invalidate();
    }

    /// Swaps the toggled state.
    fn toggle_selected(&mut self) {
        if self.properties.get_bool(PROPERTY_TOGGLED) {
            self.properties.delete(PROPERTY_TOGGLED);
        } else {
            self.properties.set_bool(PROPERTY_TOGGLED);
        }
    }

    /// Shortcut function to determine if the button is currently in a selected state or not.
    fn is_selected(&self) -> bool {
        self.properties.get_bool(PROPERTY_TOGGLED)
    }

    /// Shortcut function to determine if the button is currently being hovered over.
    fn is_hovered(&self) -> bool {
        self.properties.get_bool(PROPERTY_BUTTON_HOVERED)
    }
}

/// Implementation for drawing a `CheckBoxWidget`, with the `Widget` trait objects applied.
impl Widget for CheckBoxWidget {
    widget_default_impl!();

    /// This is a `ButtonWidget` that is used as a standard blank `Widget`.
    ///
    /// - PROPERTY_MAIN_COLOR: the `Color` of the body of the `Widget`
    /// - PROPERTY_BORDER_WIDTH: the width of the border to draw
    /// - PROPERTY_BORDER_COLOR: the `Color` of the border
    /// - PROPERTY_FONT_COLOR: the color of the font
    /// - PROPERTY_FONT_NAME: full or relative path to the font file to use to render the text
    /// - PROPERTY_FONT_SIZE: the size in points of the font
    /// - PROPERTY_FONT_STYLE: the `FontStyle` to apply to the font
    /// - PROPERTY_TEXT_JUSTIFICATION: The `TEXT_JUSTIFY_*` constant to use to position the text inside the `Widget` (only left or right are allowed)
    /// - PROPERTY_TEXT: `String` containing the text to display
    /// - PROPERTY_TOGGLED: boolean indicating whether or not the button is in a selected state
    fn draw(&mut self, c: &mut Canvas<Window>, t: &mut TextureCache) -> Option<&Texture> {
        // ONLY update the texture if the `BaseWidget` shows that it's been invalidated.
        if self.invalidated() {
            let bounds = self.properties.get_bounds();
            let text_color = Some(Color::BLACK);
            let (font_texture, width, height) = t.render_text(c, &mut self.properties, text_color);
            let text_justification = self.properties.get_value(PROPERTY_TEXT_JUSTIFICATION);
            let border_width = self.properties.get_value(PROPERTY_BORDER_WIDTH);
            let widget_w = bounds.0;
            let texture_x: i32 = match text_justification {
                TEXT_JUSTIFY_LEFT => 0,
                TEXT_JUSTIFY_RIGHT => (widget_w - width) as i32,
                _ => 0,
            };

            self.texture_store
                .create_or_resize_texture(c, bounds.0, bounds.1);

            let cloned_properties = self.properties.clone();
            let back_color = self.properties.get_color(PROPERTY_MAIN_COLOR, Color::WHITE);

            let display_image = if self.is_selected() {
                if self.is_hovered() {
                    String::from("assets/checkbox_unselected.png")
                } else {
                    String::from("assets/checkbox_selected.png")
                }
            } else if self.is_hovered() {
                String::from("assets/checkbox_selected.png")
            } else {
                String::from("assets/checkbox_unselected.png")
            };

            let checkbox_texture = t.get_image(c, display_image);
            let image_size = min(bounds.1 - border_width as u32, 32);

            c.with_texture_canvas(self.texture_store.get_mut_ref(), |texture| {
                draw_base(texture, &cloned_properties, Some(back_color));

                let start_font_y = if height > bounds.1 {
                    border_width as u32
                } else {
                    (bounds.1 / 2) - (height / 2) - (border_width / 2) as u32
                };

                let start_font_x = if text_justification == TEXT_JUSTIFY_LEFT {
                    texture_x + border_width + image_size as i32 + 6 // 6 pixels of padding
                } else {
                    (bounds.0 - width - image_size - 6) as i32 // 6 pixels of padding
                };

                let checkbox_start_x = if text_justification == TEXT_JUSTIFY_LEFT {
                    border_width as u32
                } else {
                    bounds.0 - (border_width * 2) as u32 - image_size
                };

                texture
                    .copy(
                        &font_texture,
                        None,
                        Rect::new(start_font_x, start_font_y as i32, width, height),
                    )
                    .unwrap();

                texture
                    .copy(
                        &checkbox_texture,
                        None,
                        Rect::new(
                            checkbox_start_x as i32,
                            (bounds.1 / 2 - image_size / 2) as i32,
                            image_size,
                            image_size,
                        ),
                    )
                    .unwrap();
            })
            .unwrap();
        }

        self.texture_store.get_optional_ref()
    }

    /// Overrides the `handle_event` function, which handles the mouse button, widget entering and
    /// exiting events.
    fn handle_event(&mut self, event: PushrodEvent) -> Option<PushrodEvent> {
        match event {
            WidgetMouseEntered { .. } => {
                if self.properties.get_bool(PROPERTY_BUTTON_ACTIVE) {
                    self.set_hovered();
                }

                self.properties.set_bool(PROPERTY_BUTTON_IN_BOUNDS);
            }
            WidgetMouseExited { .. } => {
                if self.properties.get_bool(PROPERTY_BUTTON_ACTIVE) {
                    self.set_unhovered();
                }

                self.properties.delete(PROPERTY_BUTTON_IN_BOUNDS);
            }
            MouseButton {
                widget_id,
                button,
                state,
            } => {
                let current_widget_id = self.properties.get_value(PROPERTY_ID);

                if button == 1 {
                    if state {
                        self.set_hovered();
                        self.properties.set_bool(PROPERTY_BUTTON_ACTIVE);
                        self.properties.set_bool(PROPERTY_BUTTON_ORIGINATED);
                    } else {
                        let had_bounds = self.properties.get_bool(PROPERTY_BUTTON_ACTIVE);

                        self.set_unhovered();
                        self.properties.delete(PROPERTY_BUTTON_ACTIVE);

                        if self.properties.get_bool(PROPERTY_BUTTON_IN_BOUNDS)
                            && had_bounds
                            && self.properties.get_bool(PROPERTY_BUTTON_ORIGINATED)
                            && current_widget_id as u32 == widget_id
                        {
                            self.properties.delete(PROPERTY_BUTTON_ORIGINATED);

                            self.toggle_selected();

                            return Some(WidgetSelected {
                                widget_id: current_widget_id as u32,
                                state: self.is_selected(),
                            });
                        }

                        self.properties.delete(PROPERTY_BUTTON_ORIGINATED);
                    }
                }
            }
            DrawFrame { .. } => {}
            _ => eprintln!("ButtonWidget Event: {:?}", event),
        }

        None
    }
}