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
|
use iced::{
button, executor, Align, Application, Button, Column, Command, Container,
Element, Length, ProgressBar, Settings, Subscription, Text,
};
mod download;
pub fn main() {
Example::run(Settings::default())
}
#[derive(Debug)]
enum Example {
Idle { button: button::State },
Downloading { progress: f32 },
Finished { button: button::State },
}
#[derive(Debug, Clone)]
pub enum Message {
DownloadProgressed(download::Progress),
Download,
}
impl Application for Example {
type Executor = executor::Default;
type Message = Message;
fn new() -> (Example, Command<Message>) {
(
Example::Idle {
button: button::State::new(),
},
Command::none(),
)
}
fn title(&self) -> String {
String::from("Download progress - Iced")
}
fn update(&mut self, message: Message) -> Command<Message> {
match message {
Message::Download => match self {
Example::Idle { .. } | Example::Finished { .. } => {
*self = Example::Downloading { progress: 0.0 };
}
_ => {}
},
Message::DownloadProgressed(message) => match self {
Example::Downloading { progress } => match message {
download::Progress::Started => {
*progress = 0.0;
}
download::Progress::Advanced(percentage) => {
*progress = percentage;
}
download::Progress::Finished => {
*self = Example::Finished {
button: button::State::new(),
}
}
},
_ => {}
},
};
Command::none()
}
fn subscription(&self) -> Subscription<Message> {
match self {
Example::Downloading { .. } => {
download::file("https://speed.hetzner.de/100MB.bin")
.map(Message::DownloadProgressed)
}
_ => Subscription::none(),
}
}
fn view(&mut self) -> Element<Message> {
let current_progress = match self {
Example::Idle { .. } => 0.0,
Example::Downloading { progress } => *progress,
Example::Finished { .. } => 100.0,
};
let progress_bar = ProgressBar::new(0.0..=100.0, current_progress);
let control: Element<_> = match self {
Example::Idle { button } => {
Button::new(button, Text::new("Start the download!"))
.on_press(Message::Download)
.into()
}
Example::Finished { button } => Column::new()
.spacing(10)
.align_items(Align::Center)
.push(Text::new("Download finished!"))
.push(
Button::new(button, Text::new("Start again"))
.on_press(Message::Download),
)
.into(),
Example::Downloading { .. } => {
Text::new(format!("Downloading... {:.2}%", current_progress))
.into()
}
};
let content = Column::new()
.spacing(10)
.padding(10)
.align_items(Align::Center)
.push(progress_bar)
.push(control);
Container::new(content)
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into()
}
}
|