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
use crate::{core::state::MouseState, prelude::*};
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct Button<'a> {
rect: Rect<i32>,
label: &'a str,
hovered: bool,
clicked: bool,
}
impl Button<'_> {
pub fn rect(&self) -> Rect<i32> {
self.rect
}
pub fn label(&self) -> &str {
self.label
}
pub fn hovered(&self) -> bool {
self.hovered
}
pub fn clicked(&self) -> bool {
self.clicked
}
}
impl<'a> Button<'a> {
#[inline]
fn new(rect: Rect<i32>, label: &'a str, mouse: &MouseState) -> Self {
let hovered = rect.contains_point(mouse.pos());
let clicked = hovered && mouse.was_clicked(&Mouse::Left);
Self {
rect,
label,
hovered,
clicked,
}
}
}
impl Draw for Button<'_> {
fn draw(&self, s: &mut PixState) -> PixResult<()> {
s.push();
if self.hovered {
s.fill(NAVY);
s.frame_cursor(&Cursor::hand())?;
} else {
s.fill(GRAY);
}
s.stroke(WHITE);
s.rect_mode(RectMode::Corner);
s.rounded_rect(self.rect, 6.0)?;
s.fill(WHITE);
s.rect_mode(RectMode::Center);
s.text(self.rect.center(), self.label)?;
s.pop();
Ok(())
}
}
impl PixState {
pub fn button<'a, R>(&mut self, rect: R, label: &'a str) -> PixResult<Button<'a>>
where
R: Into<Rect<i32>>,
{
let mut rect = rect.into();
if let RectMode::Center = self.settings.rect_mode {
rect.center_on(rect.top_left());
};
let button = Button::new(rect, label, &self.mouse);
button.draw(self)?;
Ok(button)
}
}