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
use std::any::Any;

use crate::{
    assets::{AssetOrPath, LoadedAsset},
    canvas::Canvas,
    font::Font,
    sprite::{Sprite, SpriteMetadata},
};

use blit::slice::Slice;
use taffy::NodeId;
use vek::{Extent2, Rect, Vec2};
use winit::event::MouseButton;
use winit_input_helper::WinitInputHelper;

use super::{Widget, WidgetRef};

/// A simple button widget.
#[derive(Debug)]
pub struct Button {
    /// Top-left position of the widget in pixels.
    pub offset: Vec2<f64>,
    /// Size of the button in pixels.
    pub size: Extent2<f64>,
    /// Extra size of the click region in pixels.
    ///
    /// Relative to the offset.
    pub click_region: Option<Rect<f64, f64>>,
    /// A custom label with text centered at the button.
    pub label: Option<String>,
    /// Current button state.
    pub state: State,
    /// Taffy layout node.
    pub node: NodeId,
    /// Where to load the assets.
    pub assets: ButtonAssetPaths,
}

impl Button {
    /// Handle the input.
    ///
    /// Return when the button is released.
    pub fn update(&mut self, input: &WinitInputHelper, mouse_pos: Option<Vec2<usize>>) -> bool {
        let mut rect = Rect::new(self.offset.x, self.offset.y, self.size.w, self.size.h);
        if let Some(mut click_region) = self.click_region {
            click_region.x += self.offset.x;
            click_region.y += self.offset.y;
            rect = rect.union(click_region);
        }

        match self.state {
            State::Normal => {
                if let Some(mouse_pos) = mouse_pos {
                    if !input.mouse_held(MouseButton::Left) && rect.contains_point(mouse_pos.as_())
                    {
                        self.state = State::Hover;
                    }
                }

                false
            }
            State::Hover => {
                if let Some(mouse_pos) = mouse_pos {
                    if !rect.contains_point(mouse_pos.as_()) {
                        self.state = State::Normal;
                    } else if input.mouse_pressed(MouseButton::Left) {
                        self.state = State::Down;
                    }
                }

                false
            }
            State::Down => {
                if input.mouse_released(MouseButton::Left) {
                    self.state = State::Normal;

                    true
                } else {
                    false
                }
            }
        }
    }

    /// Render the button.
    pub fn render(&self, canvas: &mut Canvas) {
        let button: LoadedAsset<Sprite> = match self.state {
            State::Normal => &self.assets.normal,
            State::Hover => &self.assets.hover,
            State::Down => &self.assets.down,
        }
        .into();
        button.render_area(self.offset, self.size.as_(), canvas);

        if let Some(label) = &self.label {
            let font: LoadedAsset<Font> = (&self.assets.font).into();
            font.render_centered(
                label,
                self.offset + (self.size.w / 2.0, self.size.h / 2.0),
                canvas,
            );
        }
    }
}

impl Widget for Button {
    fn update_layout(&mut self, location: Vec2<f64>, size: Extent2<f64>) {
        self.offset = location;
        self.size = size;
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}

#[cfg(feature = "default-gui")]
impl Default for Button {
    fn default() -> Self {
        Self {
            offset: Vec2::zero(),
            size: Extent2::zero(),
            label: None,
            state: State::default(),
            click_region: None,
            node: NodeId::new(0),
            assets: ButtonAssetPaths::default(),
        }
    }
}

/// In which state the button can be.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum State {
    /// Button is doing nothing.
    #[default]
    Normal,
    /// Button is hovered over by the mouse.
    Hover,
    /// Button is hold down.
    Down,
}

/// Asset paths for the sprites used for drawing a button.
#[derive(Debug)]
pub struct ButtonAssetPaths {
    /// Normal background, when not hovering or pressing.
    pub normal: AssetOrPath<Sprite>,
    /// Hover background, when the mouse is over the button but not pressing it.
    pub hover: AssetOrPath<Sprite>,
    /// Down background, when the mouse is pressing on the button.
    pub down: AssetOrPath<Sprite>,
    /// Font asset path.
    pub font: AssetOrPath<Font>,
}

#[cfg(feature = "default-gui")]
impl Default for ButtonAssetPaths {
    fn default() -> Self {
        // Sprite metadata is the same for each button
        let sprite_metadata = SpriteMetadata {
            vertical_slice: Some(Slice::Ternary {
                split_first: 3,
                split_last: 4,
            }),
            horizontal_slice: Some(Slice::Ternary {
                split_first: 3,
                split_last: 6,
            }),
            ..Default::default()
        };

        let normal = AssetOrPath::Owned(
            Sprite::from_png_bytes(
                include_bytes!("../../assets/button-normal.png"),
                sprite_metadata.clone(),
            )
            .unwrap(),
        );
        let hover = AssetOrPath::Owned(
            Sprite::from_png_bytes(
                include_bytes!("../../assets/button-hover.png"),
                sprite_metadata.clone(),
            )
            .unwrap(),
        );
        let down = AssetOrPath::Owned(
            Sprite::from_png_bytes(
                include_bytes!("../../assets/button-down.png"),
                sprite_metadata,
            )
            .unwrap(),
        );

        Self {
            normal,
            hover,
            down,
            #[cfg(feature = "default-font")]
            font: AssetOrPath::Owned(Font::default()),
            #[cfg(not(feature = "default-font"))]
            font: "font".into(),
        }
    }
}

/// Gui reference for retrieving constructed buttons.
///
/// See [`WidgetRef`].
#[derive(Copy, Clone)]
pub struct ButtonRef(NodeId);

impl WidgetRef for ButtonRef {
    type Widget = Button;
}

impl From<ButtonRef> for NodeId {
    fn from(val: ButtonRef) -> Self {
        val.0
    }
}

impl From<NodeId> for ButtonRef {
    fn from(value: NodeId) -> Self {
        Self(value)
    }
}