forked from iced-rs/iced
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
94 lines (81 loc) · 2.44 KB
/
main.rs
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
use iced::alignment;
use iced::event::{self, Event};
use iced::widget::{button, checkbox, container, text, Column};
use iced::window;
use iced::{Alignment, Command, Element, Length, Subscription};
pub fn main() -> iced::Result {
iced::program("Events - Iced", Events::update, Events::view)
.subscription(Events::subscription)
.exit_on_close_request(false)
.run()
}
#[derive(Debug, Default)]
struct Events {
last: Vec<Event>,
enabled: bool,
}
#[derive(Debug, Clone)]
enum Message {
EventOccurred(Event),
Toggled(bool),
Exit,
}
impl Events {
fn update(&mut self, message: Message) -> Command<Message> {
match message {
Message::EventOccurred(event) if self.enabled => {
self.last.push(event);
if self.last.len() > 5 {
let _ = self.last.remove(0);
}
Command::none()
}
Message::EventOccurred(event) => {
if let Event::Window(id, window::Event::CloseRequested) = event
{
window::close(id)
} else {
Command::none()
}
}
Message::Toggled(enabled) => {
self.enabled = enabled;
Command::none()
}
Message::Exit => window::close(window::Id::MAIN),
}
}
fn subscription(&self) -> Subscription<Message> {
event::listen().map(Message::EventOccurred)
}
fn view(&self) -> Element<Message> {
let events = Column::with_children(
self.last
.iter()
.map(|event| text(format!("{event:?}")).size(40))
.map(Element::from),
);
let toggle = checkbox("Listen to runtime events", self.enabled)
.on_toggle(Message::Toggled);
let exit = button(
text("Exit")
.width(Length::Fill)
.horizontal_alignment(alignment::Horizontal::Center),
)
.width(100)
.padding(10)
.on_press(Message::Exit);
let content = Column::new()
.align_items(Alignment::Center)
.spacing(20)
.push(events)
.push(toggle)
.push(exit);
container(content)
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
}
}