Improve download_progress
example
- Use `reqwest` with `Response::chunk` to notify progress. - Turn example state into an enum
This commit is contained in:
parent
fff333f89b
commit
30c7db3f25
@ -6,8 +6,7 @@ edition = "2018"
|
|||||||
publish = false
|
publish = false
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
iced = { path = "../.." }
|
iced = { path = "../..", features = ["tokio"] }
|
||||||
iced_native = { path = "../../native" }
|
iced_native = { path = "../../native" }
|
||||||
iced_futures = { path = "../../futures" }
|
iced_futures = { path = "../../futures" }
|
||||||
async-std = { version = "1.0", features = ["unstable"] }
|
reqwest = "0.10"
|
||||||
isahc = "0.9.1"
|
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
use iced_futures::futures;
|
use iced_futures::futures;
|
||||||
|
|
||||||
// Just a little utility function
|
// Just a little utility function
|
||||||
pub fn file<T: ToString>(url: T) -> iced::Subscription<DownloadMessage> {
|
pub fn file<T: ToString>(url: T) -> iced::Subscription<Progress> {
|
||||||
iced::Subscription::from_recipe(Downloader {
|
iced::Subscription::from_recipe(Downloader {
|
||||||
url: url.to_string(),
|
url: url.to_string(),
|
||||||
})
|
})
|
||||||
@ -16,7 +16,7 @@ impl<H, I> iced_native::subscription::Recipe<H, I> for Downloader
|
|||||||
where
|
where
|
||||||
H: std::hash::Hasher,
|
H: std::hash::Hasher,
|
||||||
{
|
{
|
||||||
type Output = DownloadMessage;
|
type Output = Progress;
|
||||||
|
|
||||||
fn hash(&self, state: &mut H) {
|
fn hash(&self, state: &mut H) {
|
||||||
use std::hash::Hash;
|
use std::hash::Hash;
|
||||||
@ -27,73 +27,68 @@ where
|
|||||||
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> {
|
||||||
use isahc::prelude::*;
|
|
||||||
|
|
||||||
Box::pin(futures::stream::unfold(
|
Box::pin(futures::stream::unfold(
|
||||||
DownloadState::Ready(self.url),
|
State::Ready(self.url),
|
||||||
|state| async move {
|
|state| async move {
|
||||||
match state {
|
match state {
|
||||||
DownloadState::Ready(url) => {
|
State::Ready(url) => {
|
||||||
let resp = Request::get(&url)
|
let response = reqwest::get(&url).await;
|
||||||
.metrics(true)
|
|
||||||
.body(())
|
|
||||||
.unwrap()
|
|
||||||
.send_async()
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
let metrics = resp.metrics().unwrap().clone();
|
|
||||||
// If you actually want to download:
|
|
||||||
/*let file = async_std::fs::File::create("download.bin")
|
|
||||||
.await
|
|
||||||
.unwrap();*/
|
|
||||||
|
|
||||||
async_std::task::spawn(async_std::io::copy(
|
match response {
|
||||||
resp.into_body(),
|
Ok(response) => Some((
|
||||||
async_std::io::sink(), //file
|
Progress::Started,
|
||||||
));
|
State::Downloading {
|
||||||
|
total: response.content_length().unwrap(),
|
||||||
Some((
|
downloaded: 0,
|
||||||
DownloadMessage::DownloadStarted,
|
response,
|
||||||
DownloadState::Downloading(metrics),
|
},
|
||||||
))
|
)),
|
||||||
}
|
Err(_) => None,
|
||||||
DownloadState::Downloading(metrics) => {
|
|
||||||
async_std::task::sleep(
|
|
||||||
std::time::Duration::from_millis(100),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
let percentage = metrics.download_progress().0 * 100
|
|
||||||
/ metrics.download_progress().1;
|
|
||||||
|
|
||||||
if percentage == 100 {
|
|
||||||
Some((
|
|
||||||
DownloadMessage::Done,
|
|
||||||
DownloadState::Finished,
|
|
||||||
))
|
|
||||||
} else {
|
|
||||||
Some((
|
|
||||||
DownloadMessage::Downloading(percentage),
|
|
||||||
DownloadState::Downloading(metrics),
|
|
||||||
))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
DownloadState::Finished => None,
|
State::Downloading {
|
||||||
|
mut response,
|
||||||
|
total,
|
||||||
|
downloaded,
|
||||||
|
} => match response.chunk().await {
|
||||||
|
Ok(Some(chunk)) => {
|
||||||
|
let downloaded = downloaded + chunk.len() as u64;
|
||||||
|
|
||||||
|
let percentage =
|
||||||
|
(downloaded as f32 / total as f32) * 100.0;
|
||||||
|
|
||||||
|
Some((
|
||||||
|
Progress::Advanced(percentage),
|
||||||
|
State::Downloading {
|
||||||
|
response,
|
||||||
|
total,
|
||||||
|
downloaded,
|
||||||
|
},
|
||||||
|
))
|
||||||
|
}
|
||||||
|
Ok(None) => Some((Progress::Finished, State::Finished)),
|
||||||
|
Err(_) => None,
|
||||||
|
},
|
||||||
|
State::Finished => None,
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug, Clone)]
|
||||||
pub enum DownloadMessage {
|
pub enum Progress {
|
||||||
DownloadStarted,
|
Started,
|
||||||
Downloading(u64),
|
Advanced(f32),
|
||||||
Done,
|
Finished,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub enum DownloadState {
|
pub enum State {
|
||||||
Ready(String),
|
Ready(String),
|
||||||
Downloading(isahc::Metrics),
|
Downloading {
|
||||||
|
response: reqwest::Response,
|
||||||
|
total: u64,
|
||||||
|
downloaded: u64,
|
||||||
|
},
|
||||||
Finished,
|
Finished,
|
||||||
}
|
}
|
||||||
|
@ -6,60 +6,61 @@ use iced::{
|
|||||||
mod downloader;
|
mod downloader;
|
||||||
|
|
||||||
pub fn main() {
|
pub fn main() {
|
||||||
Downloader::run(Settings::default())
|
Example::run(Settings::default())
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Default)]
|
|
||||||
struct Downloader {
|
|
||||||
// Whether to start the download or not.
|
|
||||||
enabled: bool,
|
|
||||||
// The current percentage of the download
|
|
||||||
current_progress: u64,
|
|
||||||
|
|
||||||
btn_state: button::State,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum Message {
|
enum Example {
|
||||||
DownloadUpdate(downloader::DownloadMessage),
|
Idle { button: button::State },
|
||||||
Interaction(Interaction),
|
Downloading { progress: f32 },
|
||||||
|
Finished { button: button::State },
|
||||||
}
|
}
|
||||||
|
|
||||||
// For explanation of why we use an Interaction enum see here:
|
|
||||||
// https://github.com/hecrj/iced/pull/155#issuecomment-573523405
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub enum Interaction {
|
pub enum Message {
|
||||||
// User pressed the button to start the download
|
DownloadProgressed(downloader::Progress),
|
||||||
StartDownload,
|
Download,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Application for Downloader {
|
impl Application for Example {
|
||||||
type Executor = executor::Default;
|
type Executor = executor::Default;
|
||||||
type Message = Message;
|
type Message = Message;
|
||||||
|
|
||||||
fn new() -> (Downloader, Command<Message>) {
|
fn new() -> (Example, Command<Message>) {
|
||||||
(Downloader::default(), Command::none())
|
(
|
||||||
|
Example::Idle {
|
||||||
|
button: button::State::new(),
|
||||||
|
},
|
||||||
|
Command::none(),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn title(&self) -> String {
|
fn title(&self) -> String {
|
||||||
String::from("Download Progress - Iced")
|
String::from("Download progress - Iced")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn update(&mut self, message: Message) -> Command<Message> {
|
fn update(&mut self, message: Message) -> Command<Message> {
|
||||||
match message {
|
match message {
|
||||||
Message::Interaction(action) => match action {
|
Message::Download => match self {
|
||||||
Interaction::StartDownload => {
|
Example::Idle { .. } | Example::Finished { .. } => {
|
||||||
self.enabled = true;
|
*self = Example::Downloading { progress: 0.0 };
|
||||||
}
|
}
|
||||||
|
_ => {}
|
||||||
},
|
},
|
||||||
Message::DownloadUpdate(update) => match update {
|
Message::DownloadProgressed(message) => match self {
|
||||||
downloader::DownloadMessage::Downloading(percentage) => {
|
Example::Downloading { progress } => match message {
|
||||||
self.current_progress = percentage;
|
downloader::Progress::Started => {
|
||||||
}
|
*progress = 0.0;
|
||||||
downloader::DownloadMessage::Done => {
|
}
|
||||||
self.current_progress = 100;
|
downloader::Progress::Advanced(percentage) => {
|
||||||
self.enabled = false;
|
*progress = percentage;
|
||||||
}
|
}
|
||||||
|
downloader::Progress::Finished => {
|
||||||
|
*self = Example::Finished {
|
||||||
|
button: button::State::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
_ => {}
|
_ => {}
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@ -68,43 +69,51 @@ impl Application for Downloader {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn subscription(&self) -> Subscription<Message> {
|
fn subscription(&self) -> Subscription<Message> {
|
||||||
if self.enabled {
|
match self {
|
||||||
downloader::file("https://speed.hetzner.de/100MB.bin")
|
Example::Downloading { .. } => {
|
||||||
.map(Message::DownloadUpdate)
|
downloader::file("https://speed.hetzner.de/100MB.bin")
|
||||||
} else {
|
.map(Message::DownloadProgressed)
|
||||||
Subscription::none()
|
}
|
||||||
|
_ => Subscription::none(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn view(&mut self) -> Element<Message> {
|
fn view(&mut self) -> Element<Message> {
|
||||||
// Construct widgets
|
let current_progress = match self {
|
||||||
|
Example::Idle { .. } => 0.0,
|
||||||
let toggle_text = match self.enabled {
|
Example::Downloading { progress } => *progress,
|
||||||
true => "Downloading...",
|
Example::Finished { .. } => 100.0,
|
||||||
false => "Start the download!",
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let toggle: Element<Interaction> =
|
let progress_bar = ProgressBar::new(0.0..=100.0, current_progress);
|
||||||
Button::new(&mut self.btn_state, Text::new(toggle_text))
|
|
||||||
.on_press(Interaction::StartDownload)
|
|
||||||
.into();
|
|
||||||
|
|
||||||
let progress_bar =
|
let control: Element<_> = match self {
|
||||||
ProgressBar::new(0.0..=100.0, self.current_progress as f32);
|
Example::Idle { button } => {
|
||||||
|
Button::new(button, Text::new("Start the download!"))
|
||||||
let progress_text = &match self.enabled {
|
.on_press(Message::Download)
|
||||||
true => format!("Downloading {}%", self.current_progress),
|
.into()
|
||||||
false => "Ready to rock!".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()
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Construct layout
|
|
||||||
let content = Column::new()
|
let content = Column::new()
|
||||||
|
.spacing(10)
|
||||||
|
.padding(10)
|
||||||
.align_items(Align::Center)
|
.align_items(Align::Center)
|
||||||
.spacing(20)
|
|
||||||
.padding(20)
|
|
||||||
.push(Text::new(progress_text))
|
|
||||||
.push(progress_bar)
|
.push(progress_bar)
|
||||||
.push(toggle.map(Message::Interaction));
|
.push(control);
|
||||||
|
|
||||||
Container::new(content)
|
Container::new(content)
|
||||||
.width(Length::Fill)
|
.width(Length::Fill)
|
||||||
|
Loading…
Reference in New Issue
Block a user