Improve download_progress example (#283)

* Add advanced download example

* Rename to task fields and variables

* Cargo fmt advanced_download/src/download.rs

* Add progress bar for advanced download example

* Merge two download examples to single one

* Apply great review suggestions

* Change to url::Url instead of plain String

* Simplify `download_progress` example

* Update `README` of `download_progress` example

Co-authored-by: Héctor Ramón Jiménez <hector0193@gmail.com>
This commit is contained in:
Folyd 2021-02-13 05:00:52 +08:00 committed by GitHub
parent 9e453843b2
commit 9f5c2eb0c4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 168 additions and 81 deletions

View File

@ -1,12 +1,12 @@
[package] [package]
name = "download_progress" name = "download_progress"
version = "0.1.0" version = "0.1.0"
authors = ["Songtronix <contact@songtronix.com>"] authors = ["Songtronix <contact@songtronix.com>", "Folyd <lyshuhow@gmail.com>"]
edition = "2018" edition = "2018"
publish = false publish = false
[dependencies] [dependencies]
iced = { path = "../..", features = ["tokio_old"] } iced = { path = "../..", features = ["tokio"] }
iced_native = { path = "../../native" } iced_native = { path = "../../native" }
iced_futures = { path = "../../futures" } iced_futures = { path = "../../futures" }
reqwest = "0.10" reqwest = "0.11"

View File

@ -1,6 +1,6 @@
## Download progress ## Download progress
A basic application that asynchronously downloads a dummy file of 100 MB and tracks the download progress. A basic application that asynchronously downloads multiple dummy files of 100 MB and tracks the download progress.
The example implements a custom `Subscription` in the __[`download`](src/download.rs)__ module. This subscription downloads and produces messages that can be used to keep track of its progress. The example implements a custom `Subscription` in the __[`download`](src/download.rs)__ module. This subscription downloads and produces messages that can be used to keep track of its progress.

View File

@ -1,37 +1,46 @@
use iced_futures::futures; use iced_futures::futures;
use std::hash::{Hash, Hasher};
// Just a little utility function // Just a little utility function
pub fn file<T: ToString>(url: T) -> iced::Subscription<Progress> { pub fn file<I: 'static + Hash + Copy + Send, T: ToString>(
id: I,
url: T,
) -> iced::Subscription<(I, Progress)> {
iced::Subscription::from_recipe(Download { iced::Subscription::from_recipe(Download {
id,
url: url.to_string(), url: url.to_string(),
}) })
} }
pub struct Download { pub struct Download<I> {
id: I,
url: String, url: String,
} }
// Make sure iced can use our download stream // Make sure iced can use our download stream
impl<H, I> iced_native::subscription::Recipe<H, I> for Download impl<H, I, T> iced_native::subscription::Recipe<H, I> for Download<T>
where where
H: std::hash::Hasher, T: 'static + Hash + Copy + Send,
H: Hasher,
{ {
type Output = Progress; type Output = (T, Progress);
fn hash(&self, state: &mut H) { fn hash(&self, state: &mut H) {
use std::hash::Hash; struct Marker;
std::any::TypeId::of::<Marker>().hash(state);
std::any::TypeId::of::<Self>().hash(state); self.id.hash(state);
self.url.hash(state);
} }
fn stream( fn stream(
self: Box<Self>, self: Box<Self>,
_input: futures::stream::BoxStream<'static, I>, _input: futures::stream::BoxStream<'static, I>,
) -> futures::stream::BoxStream<'static, Self::Output> { ) -> futures::stream::BoxStream<'static, Self::Output> {
let id = self.id;
Box::pin(futures::stream::unfold( Box::pin(futures::stream::unfold(
State::Ready(self.url), State::Ready(self.url),
|state| async move { move |state| async move {
match state { match state {
State::Ready(url) => { State::Ready(url) => {
let response = reqwest::get(&url).await; let response = reqwest::get(&url).await;
@ -40,7 +49,7 @@ where
Ok(response) => { Ok(response) => {
if let Some(total) = response.content_length() { if let Some(total) = response.content_length() {
Some(( Some((
Progress::Started, (id, Progress::Started),
State::Downloading { State::Downloading {
response, response,
total, total,
@ -48,11 +57,14 @@ where
}, },
)) ))
} else { } else {
Some((Progress::Errored, State::Finished)) Some((
(id, Progress::Errored),
State::Finished,
))
} }
} }
Err(_) => { Err(_) => {
Some((Progress::Errored, State::Finished)) Some(((id, Progress::Errored), State::Finished))
} }
} }
} }
@ -68,7 +80,7 @@ where
(downloaded as f32 / total as f32) * 100.0; (downloaded as f32 / total as f32) * 100.0;
Some(( Some((
Progress::Advanced(percentage), (id, Progress::Advanced(percentage)),
State::Downloading { State::Downloading {
response, response,
total, total,
@ -76,8 +88,12 @@ where
}, },
)) ))
} }
Ok(None) => Some((Progress::Finished, State::Finished)), Ok(None) => {
Err(_) => Some((Progress::Errored, State::Finished)), Some(((id, Progress::Finished), State::Finished))
}
Err(_) => {
Some(((id, Progress::Errored), State::Finished))
}
}, },
State::Finished => { State::Finished => {
// We do not let the stream die, as it would start a // We do not let the stream die, as it would start a

View File

@ -10,17 +10,17 @@ pub fn main() -> iced::Result {
} }
#[derive(Debug)] #[derive(Debug)]
enum Example { struct Example {
Idle { button: button::State }, downloads: Vec<Download>,
Downloading { progress: f32 }, last_id: usize,
Finished { button: button::State }, add: button::State,
Errored { button: button::State },
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum Message { pub enum Message {
Download, Add,
DownloadProgressed(download::Progress), Download(usize),
DownloadProgressed((usize, download::Progress)),
} }
impl Application for Example { impl Application for Example {
@ -30,8 +30,10 @@ impl Application for Example {
fn new(_flags: ()) -> (Example, Command<Message>) { fn new(_flags: ()) -> (Example, Command<Message>) {
( (
Example::Idle { Example {
button: button::State::new(), downloads: vec![Download::new(0)],
last_id: 0,
add: button::State::new(),
}, },
Command::none(), Command::none(),
) )
@ -43,16 +45,94 @@ impl Application for Example {
fn update(&mut self, message: Message) -> Command<Message> { fn update(&mut self, message: Message) -> Command<Message> {
match message { match message {
Message::Download => match self { Message::Add => {
Example::Idle { .. } self.last_id = self.last_id + 1;
| Example::Finished { .. }
| Example::Errored { .. } => { self.downloads.push(Download::new(self.last_id));
*self = Example::Downloading { progress: 0.0 }; }
Message::Download(index) => {
if let Some(download) = self.downloads.get_mut(index) {
download.start();
}
}
Message::DownloadProgressed((id, progress)) => {
if let Some(download) =
self.downloads.iter_mut().find(|download| download.id == id)
{
download.progress(progress);
}
}
};
Command::none()
}
fn subscription(&self) -> Subscription<Message> {
Subscription::batch(self.downloads.iter().map(Download::subscription))
}
fn view(&mut self) -> Element<Message> {
let downloads = self
.downloads
.iter_mut()
.fold(Column::new().spacing(20), |column, download| {
column.push(download.view())
})
.push(
Button::new(&mut self.add, Text::new("Add another download"))
.on_press(Message::Add)
.padding(10),
)
.align_items(Align::End);
Container::new(downloads)
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.padding(20)
.into()
}
}
#[derive(Debug)]
struct Download {
id: usize,
state: State,
}
#[derive(Debug)]
enum State {
Idle { button: button::State },
Downloading { progress: f32 },
Finished { button: button::State },
Errored { button: button::State },
}
impl Download {
pub fn new(id: usize) -> Self {
Download {
id,
state: State::Idle {
button: button::State::new(),
},
}
}
pub fn start(&mut self) {
match self.state {
State::Idle { .. }
| State::Finished { .. }
| State::Errored { .. } => {
self.state = State::Downloading { progress: 0.0 };
} }
_ => {} _ => {}
}, }
Message::DownloadProgressed(message) => match self { }
Example::Downloading { progress } => match message {
pub fn progress(&mut self, new_progress: download::Progress) {
match &mut self.state {
State::Downloading { progress } => match new_progress {
download::Progress::Started => { download::Progress::Started => {
*progress = 0.0; *progress = 0.0;
} }
@ -60,85 +140,76 @@ impl Application for Example {
*progress = percentage; *progress = percentage;
} }
download::Progress::Finished => { download::Progress::Finished => {
*self = Example::Finished { self.state = State::Finished {
button: button::State::new(), button: button::State::new(),
} }
} }
download::Progress::Errored => { download::Progress::Errored => {
*self = Example::Errored { self.state = State::Errored {
button: button::State::new(), button: button::State::new(),
}; };
} }
}, },
_ => {} _ => {}
}, }
};
Command::none()
} }
fn subscription(&self) -> Subscription<Message> { pub fn subscription(&self) -> Subscription<Message> {
match self { match self.state {
Example::Downloading { .. } => { State::Downloading { .. } => {
download::file("https://speed.hetzner.de/100MB.bin") download::file(self.id, "https://speed.hetzner.de/100MB.bin?")
.map(Message::DownloadProgressed) .map(Message::DownloadProgressed)
} }
_ => Subscription::none(), _ => Subscription::none(),
} }
} }
fn view(&mut self) -> Element<Message> { pub fn view(&mut self) -> Element<Message> {
let current_progress = match self { let current_progress = match &self.state {
Example::Idle { .. } => 0.0, State::Idle { .. } => 0.0,
Example::Downloading { progress } => *progress, State::Downloading { progress } => *progress,
Example::Finished { .. } => 100.0, State::Finished { .. } => 100.0,
Example::Errored { .. } => 0.0, State::Errored { .. } => 0.0,
}; };
let progress_bar = ProgressBar::new(0.0..=100.0, current_progress); let progress_bar = ProgressBar::new(0.0..=100.0, current_progress);
let control: Element<_> = match self { let control: Element<_> = match &mut self.state {
Example::Idle { button } => { State::Idle { button } => {
Button::new(button, Text::new("Start the download!")) Button::new(button, Text::new("Start the download!"))
.on_press(Message::Download) .on_press(Message::Download(self.id))
.into() .into()
} }
Example::Finished { button } => Column::new() State::Finished { button } => Column::new()
.spacing(10) .spacing(10)
.align_items(Align::Center) .align_items(Align::Center)
.push(Text::new("Download finished!")) .push(Text::new("Download finished!"))
.push( .push(
Button::new(button, Text::new("Start again")) Button::new(button, Text::new("Start again"))
.on_press(Message::Download), .on_press(Message::Download(self.id)),
) )
.into(), .into(),
Example::Downloading { .. } => { State::Downloading { .. } => {
Text::new(format!("Downloading... {:.2}%", current_progress)) Text::new(format!("Downloading... {:.2}%", current_progress))
.into() .into()
} }
Example::Errored { button } => Column::new() State::Errored { button } => Column::new()
.spacing(10) .spacing(10)
.align_items(Align::Center) .align_items(Align::Center)
.push(Text::new("Something went wrong :(")) .push(Text::new("Something went wrong :("))
.push( .push(
Button::new(button, Text::new("Try again")) Button::new(button, Text::new("Try again"))
.on_press(Message::Download), .on_press(Message::Download(self.id)),
) )
.into(), .into(),
}; };
let content = Column::new() Column::new()
.spacing(10) .spacing(10)
.padding(10) .padding(10)
.align_items(Align::Center) .align_items(Align::Center)
.push(progress_bar) .push(progress_bar)
.push(control); .push(control)
Container::new(content)
.width(Length::Fill)
.height(Length::Fill)
.center_x()
.center_y()
.into() .into()
} }
} }