Files · Transfers: file operations, a transfer queue, downloads and storage
A file on its way is a Transfer with a state: waiting, moving at a rate, paused, done or failed with a reason. One row draws it for the queue and the downloads: its icon, its way, a bar while it moves or waits paused, a status with the time left, and only the actions its state allows. TransferQueue counts what moves and waits. DownloadManager keeps the finished below under Clear, opening on a press and showing their folder. FileOperationProgress tells a copy or move with its bar, time left and current file, its header wrapping by the header rule; a failure speaks in the danger tone. StorageUsage points to data_display's UsageBar. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f324702c89
commit
0fcde7dbbe
11 files changed
+1180
-5
No files matched your search
@@ -11,9 +11,12 @@ mod explorer;
|
||||
mod grid;
|
||||
mod icon;
|
||||
mod item;
|
||||
mod operation;
|
||||
mod preview;
|
||||
mod recent;
|
||||
mod search;
|
||||
mod transfer;
|
||||
mod transfers;
|
||||
|
||||
type OnEntry = Rc<dyn Fn(&DirEntry, &mut Window, &mut App)>;
|
||||
|
||||
@@ -26,6 +29,9 @@ pub use explorer::{FileExplorer, FileView};
|
||||
pub use grid::FileGrid;
|
||||
pub use icon::FileIcon;
|
||||
pub use item::FileItem;
|
||||
pub use operation::{FileOperation, FileOperationProgress};
|
||||
pub use preview::FilePreview;
|
||||
pub use recent::{RecentFile, RecentFiles};
|
||||
pub use search::{FileSearch, FoundFile};
|
||||
pub use transfer::{Transfer, TransferState};
|
||||
pub use transfers::{DownloadManager, TransferQueue};
|
||||
@@ -0,0 +1,243 @@
|
||||
use std::rc::Rc;
|
||||
|
||||
use gpui::{
|
||||
App, ElementId, FontWeight, IntoElement, ParentElement, RenderOnce, SharedString, Styled,
|
||||
Window, div, prelude::*,
|
||||
};
|
||||
|
||||
use super::transfer::TransferState;
|
||||
use crate::{
|
||||
buttons::{Button, ButtonVariant},
|
||||
forms::Run,
|
||||
motion::ProgressBar,
|
||||
primitives::{Icon, IconName, Severity},
|
||||
theme::{ActiveTheme, ControlSize, IconSize, Radius, TextSize},
|
||||
typography::{DurationStyle, Ellipsis, MiddleEllipsis, format},
|
||||
};
|
||||
|
||||
/// What an operation does to files.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum FileOperation {
|
||||
Copy,
|
||||
Move,
|
||||
}
|
||||
|
||||
/// What an operation says of itself, by what it does and where it stands.
|
||||
pub(crate) fn headline(
|
||||
operation: FileOperation,
|
||||
items: usize,
|
||||
to: &str,
|
||||
state: &TransferState,
|
||||
) -> String {
|
||||
let things = match items {
|
||||
1 => "1 item".to_string(),
|
||||
count => format!("{count} items"),
|
||||
};
|
||||
let (doing, done) = match operation {
|
||||
FileOperation::Copy => ("Copying", "Copied"),
|
||||
FileOperation::Move => ("Moving", "Moved"),
|
||||
};
|
||||
match state {
|
||||
TransferState::Queued => format!("{doing} {things} to {to} next"),
|
||||
TransferState::Moving { .. } => format!("{doing} {things} to {to}"),
|
||||
TransferState::Paused => format!("{doing} {things} to {to}, paused"),
|
||||
TransferState::Done => format!("{done} {things} to {to}"),
|
||||
TransferState::Failed(_) => format!("{doing} {things} to {to} stopped"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A copy or a move under way: what it does and where to, a bar, the bytes done of all with the time left, and the file it takes now. Pause or resume and cancel while it runs; a failure says why in the danger tone.
|
||||
#[derive(IntoElement)]
|
||||
pub struct FileOperationProgress {
|
||||
id: ElementId,
|
||||
operation: FileOperation,
|
||||
items: usize,
|
||||
to: SharedString,
|
||||
moved: u64,
|
||||
total: u64,
|
||||
state: TransferState,
|
||||
current: Option<SharedString>,
|
||||
on_pause: Option<Run>,
|
||||
on_resume: Option<Run>,
|
||||
on_cancel: Option<Run>,
|
||||
}
|
||||
|
||||
impl FileOperationProgress {
|
||||
/// `items` things to `to`, `moved` bytes of `total` so far.
|
||||
pub fn new(
|
||||
id: impl Into<ElementId>,
|
||||
operation: FileOperation,
|
||||
items: usize,
|
||||
to: impl Into<SharedString>,
|
||||
(moved, total): (u64, u64),
|
||||
state: TransferState,
|
||||
) -> Self {
|
||||
assert!(
|
||||
items > 0 && moved <= total,
|
||||
"{items} items, {moved} of {total} bytes"
|
||||
);
|
||||
Self {
|
||||
id: id.into(),
|
||||
operation,
|
||||
items,
|
||||
to: to.into(),
|
||||
moved,
|
||||
total,
|
||||
state,
|
||||
current: None,
|
||||
on_pause: None,
|
||||
on_resume: None,
|
||||
on_cancel: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The file it takes now.
|
||||
pub fn current(mut self, name: impl Into<SharedString>) -> Self {
|
||||
self.current = Some(name.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn on_pause(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
|
||||
self.on_pause = Some(Rc::new(handler));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn on_resume(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
|
||||
self.on_resume = Some(Rc::new(handler));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn on_cancel(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
|
||||
self.on_cancel = Some(Rc::new(handler));
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderOnce for FileOperationProgress {
|
||||
fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
|
||||
let theme = cx.theme();
|
||||
let colors = &theme.colors;
|
||||
let small = theme.text_size(TextSize::Sm);
|
||||
let share = if self.total == 0 {
|
||||
1.0
|
||||
} else {
|
||||
self.moved as f32 / self.total as f32
|
||||
};
|
||||
let (moved, total) = (
|
||||
format::file_size(self.moved, false),
|
||||
format::file_size(self.total, false),
|
||||
);
|
||||
let detail = match &self.state {
|
||||
TransferState::Moving { rate } if *rate > 0 => {
|
||||
let left = self.total.saturating_sub(self.moved) / rate;
|
||||
format!(
|
||||
"{moved} of {total} · {} left",
|
||||
format::duration(left.max(1), DurationStyle::Compact)
|
||||
)
|
||||
}
|
||||
TransferState::Failed(reason) => reason.to_string(),
|
||||
TransferState::Done => total,
|
||||
_ => format!("{moved} of {total}"),
|
||||
};
|
||||
let button = |key: &'static str, label: &'static str, run: Option<Run>| {
|
||||
run.map(|run| {
|
||||
Button::new((self.id.clone(), key), label)
|
||||
.variant(ButtonVariant::Ghost)
|
||||
.size(ControlSize::Sm)
|
||||
.on_click(move |_, window, cx| {
|
||||
log::info!("file operation: {key}");
|
||||
run(window, cx)
|
||||
})
|
||||
})
|
||||
};
|
||||
let (pause, resume, cancel) = match self.state {
|
||||
TransferState::Moving { .. } => (self.on_pause, None, self.on_cancel),
|
||||
TransferState::Paused => (None, self.on_resume, self.on_cancel),
|
||||
TransferState::Queued => (None, None, self.on_cancel),
|
||||
_ => (None, None, None),
|
||||
};
|
||||
let failed = matches!(self.state, TransferState::Failed(_));
|
||||
let icon = match (&self.state, self.operation) {
|
||||
(TransferState::Failed(_), _) => Severity::Danger.icon(),
|
||||
(TransferState::Done, _) => Severity::Success.icon(),
|
||||
(_, FileOperation::Copy) => IconName::Copy,
|
||||
(_, FileOperation::Move) => IconName::FolderOpen,
|
||||
};
|
||||
let tone = match &self.state {
|
||||
TransferState::Failed(_) => Severity::Danger.color(colors),
|
||||
TransferState::Done => Severity::Success.color(colors),
|
||||
_ => colors.fg_muted,
|
||||
};
|
||||
let running = matches!(
|
||||
self.state,
|
||||
TransferState::Moving { .. } | TransferState::Paused
|
||||
);
|
||||
div()
|
||||
.debug_selector(|| "file-operation".into())
|
||||
.w_full()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap_2()
|
||||
.p_4()
|
||||
.rounded(theme.radius(Radius::Lg))
|
||||
.border_1()
|
||||
.border_color(colors.border)
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.flex_wrap()
|
||||
.items_center()
|
||||
.justify_between()
|
||||
.gap_2()
|
||||
.child(
|
||||
div()
|
||||
.flex_1()
|
||||
.min_w(theme.label_width())
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap_3()
|
||||
.child(Icon::new(icon).size(IconSize::Lg).color(tone))
|
||||
.child(
|
||||
div()
|
||||
.flex_1()
|
||||
.min_w_0()
|
||||
.font_weight(FontWeight::MEDIUM)
|
||||
.text_color(colors.fg)
|
||||
.child(Ellipsis::new(headline(
|
||||
self.operation,
|
||||
self.items,
|
||||
&self.to,
|
||||
&self.state,
|
||||
))),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex_none()
|
||||
.flex()
|
||||
.children(button("pause", "Pause", pause))
|
||||
.children(button("resume", "Resume", resume))
|
||||
.children(button("cancel", "Cancel", cancel)),
|
||||
),
|
||||
)
|
||||
.when(running, |card| {
|
||||
card.child(ProgressBar::new((self.id.clone(), "bar"), share.min(1.0)))
|
||||
})
|
||||
.child(
|
||||
div()
|
||||
.text_size(small)
|
||||
.text_color(if failed {
|
||||
colors.danger
|
||||
} else {
|
||||
colors.fg_muted
|
||||
})
|
||||
.child(Ellipsis::new(detail)),
|
||||
)
|
||||
.children(self.current.filter(|_| running).map(|name| {
|
||||
div()
|
||||
.text_size(small)
|
||||
.text_color(colors.fg_subtle)
|
||||
.child(MiddleEllipsis::new(name))
|
||||
}))
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ use crate::{lists::DirEntry, primitives::FocusNext, theme::Theme};
|
||||
|
||||
mod explorer;
|
||||
mod find;
|
||||
mod transfers;
|
||||
|
||||
pub(super) fn setup(cx: &mut TestAppContext) {
|
||||
cx.update(|cx| {
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
use gpui::{
|
||||
Context, Entity, IntoElement, ParentElement, Render, SharedString, Styled, TestAppContext,
|
||||
VisualTestContext, Window, div, px,
|
||||
};
|
||||
|
||||
use super::{press, settle, setup};
|
||||
use crate::files::{
|
||||
DownloadManager, FileOperation, FileOperationProgress, Transfer, TransferQueue, TransferState,
|
||||
operation::headline, transfer::status, transfers::tally,
|
||||
};
|
||||
|
||||
/// Moves focus to the `nth` Tab stop from none.
|
||||
fn tab_to(nth: usize, cx: &mut VisualTestContext) {
|
||||
cx.update(|window, _| {
|
||||
window.blur();
|
||||
for _ in 0..nth {
|
||||
window.focus_next();
|
||||
}
|
||||
});
|
||||
settle(cx);
|
||||
}
|
||||
|
||||
fn transfer(key: &str, state: TransferState) -> Transfer {
|
||||
Transfer {
|
||||
key: SharedString::from(key.to_string()),
|
||||
name: SharedString::from(format!("{key}.mov")),
|
||||
upload: false,
|
||||
moved: 4_000_000,
|
||||
total: 16_000_000,
|
||||
state,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_status_says_how_far_how_fast_and_how_long() {
|
||||
let moving = transfer("a", TransferState::Moving { rate: 2_000_000 });
|
||||
assert_eq!(status(&moving), "4.0 MB of 16 MB · 2.0 MB/s · 6s left");
|
||||
assert_eq!(
|
||||
status(&transfer("a", TransferState::Paused)),
|
||||
"Paused at 4.0 MB of 16 MB"
|
||||
);
|
||||
assert_eq!(
|
||||
status(&transfer("a", TransferState::Queued)),
|
||||
"Waiting · 16 MB"
|
||||
);
|
||||
let failed = transfer("a", TransferState::Failed("The disk is full".into()));
|
||||
assert_eq!(status(&failed), "Failed: The disk is full");
|
||||
assert_eq!(status(&transfer("a", TransferState::Done)), "16 MB");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tally_counts_the_moving_and_the_waiting() {
|
||||
let all = [
|
||||
transfer("a", TransferState::Moving { rate: 1 }),
|
||||
transfer("b", TransferState::Queued),
|
||||
transfer("c", TransferState::Paused),
|
||||
transfer("d", TransferState::Done),
|
||||
];
|
||||
assert_eq!(tally(&all), "1 moving · 2 waiting");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_headline_says_what_an_operation_does_and_where() {
|
||||
let moving = TransferState::Moving { rate: 1 };
|
||||
assert_eq!(
|
||||
headline(FileOperation::Copy, 12, "Atrium", &moving),
|
||||
"Copying 12 items to Atrium"
|
||||
);
|
||||
assert_eq!(
|
||||
headline(FileOperation::Move, 1, "Atrium", &TransferState::Done),
|
||||
"Moved 1 item to Atrium"
|
||||
);
|
||||
}
|
||||
|
||||
/// A queue of three, one moving, one paused, one failed, and what its buttons asked.
|
||||
struct Queued {
|
||||
asked: Vec<String>,
|
||||
}
|
||||
|
||||
impl Render for Queued {
|
||||
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let ask = |what: &'static str, cx: &mut Context<Self>| {
|
||||
let owner = cx.entity();
|
||||
move |key: &SharedString, _: &mut Window, cx: &mut gpui::App| {
|
||||
owner.update(cx, |host, _| host.asked.push(format!("{what} {key}")))
|
||||
}
|
||||
};
|
||||
let transfers = [
|
||||
transfer("a", TransferState::Moving { rate: 1_000_000 }),
|
||||
transfer("b", TransferState::Paused),
|
||||
transfer("c", TransferState::Failed("Lost the network".into())),
|
||||
];
|
||||
div().w(px(420.0)).child(
|
||||
TransferQueue::new("queue", transfers)
|
||||
.pause(ask("pause", cx))
|
||||
.resume(ask("resume", cx))
|
||||
.retry(ask("retry", cx))
|
||||
.cancel(ask("cancel", cx)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn each_state_offers_what_it_can_do(cx: &mut TestAppContext) {
|
||||
setup(cx);
|
||||
let (host, cx) = cx.add_window_view(|_, _| Queued { asked: Vec::new() });
|
||||
cx.update(|window, _| window.activate_window());
|
||||
settle(cx);
|
||||
for nth in 1..=6 {
|
||||
tab_to(nth, cx);
|
||||
press("space", cx);
|
||||
}
|
||||
let asked = host.read_with(cx, |host, _| host.asked.clone());
|
||||
assert_eq!(
|
||||
asked,
|
||||
[
|
||||
"pause a", "cancel a", "resume b", "cancel b", "retry c", "cancel c"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// Two downloads, one on its way and one done, and what was asked.
|
||||
struct Downloading {
|
||||
asked: Vec<String>,
|
||||
}
|
||||
|
||||
impl Render for Downloading {
|
||||
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let (open, show, clear) = (cx.entity(), cx.entity(), cx.entity());
|
||||
let downloads = [
|
||||
transfer("done", TransferState::Done),
|
||||
transfer("going", TransferState::Moving { rate: 1_000_000 }),
|
||||
];
|
||||
div().w(px(420.0)).child(
|
||||
DownloadManager::new("downloads", downloads)
|
||||
.open(move |key, _, cx| {
|
||||
open.update(cx, |host, _| host.asked.push(format!("open {key}")))
|
||||
})
|
||||
.show(move |key, _, cx| {
|
||||
show.update(cx, |host, _| host.asked.push(format!("show {key}")))
|
||||
})
|
||||
.on_clear(move |_, cx| clear.update(cx, |host, _| host.asked.push("clear".into()))),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn the_finished_sit_below_and_open_show_and_clear(cx: &mut TestAppContext) {
|
||||
setup(cx);
|
||||
let (host, cx) = cx.add_window_view(|_, _| Downloading { asked: Vec::new() });
|
||||
cx.update(|window, _| window.activate_window());
|
||||
settle(cx);
|
||||
for nth in 1..=3 {
|
||||
tab_to(nth, cx);
|
||||
press("space", cx);
|
||||
}
|
||||
let asked = host.read_with(cx, |host, _| host.asked.clone());
|
||||
assert_eq!(
|
||||
asked,
|
||||
["clear", "open done", "show done"],
|
||||
"the one on its way has no handlers"
|
||||
);
|
||||
let going = cx
|
||||
.debug_bounds("transfer-row going")
|
||||
.expect("the one on its way draws");
|
||||
let done = cx
|
||||
.debug_bounds("transfer-row done")
|
||||
.expect("the finished one draws");
|
||||
assert!(going.bottom() <= done.top(), "{going:?} above {done:?}");
|
||||
}
|
||||
|
||||
/// A copy in one state, and what its buttons asked.
|
||||
struct Copying {
|
||||
state: TransferState,
|
||||
asked: Vec<&'static str>,
|
||||
}
|
||||
|
||||
impl Render for Copying {
|
||||
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let (pause, resume, cancel) = (cx.entity(), cx.entity(), cx.entity());
|
||||
div().w(px(420.0)).child(
|
||||
FileOperationProgress::new(
|
||||
"copy",
|
||||
FileOperation::Copy,
|
||||
3,
|
||||
"Atrium",
|
||||
(4_000, 16_000),
|
||||
self.state.clone(),
|
||||
)
|
||||
.current("Walkthrough.mov")
|
||||
.on_pause(move |_, cx| pause.update(cx, |host, _| host.asked.push("pause")))
|
||||
.on_resume(move |_, cx| resume.update(cx, |host, _| host.asked.push("resume")))
|
||||
.on_cancel(move |_, cx| cancel.update(cx, |host, _| host.asked.push("cancel"))),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn copying(
|
||||
state: TransferState,
|
||||
cx: &mut TestAppContext,
|
||||
) -> (Entity<Copying>, &mut VisualTestContext) {
|
||||
setup(cx);
|
||||
let (host, cx) = cx.add_window_view(move |_, _| Copying {
|
||||
state,
|
||||
asked: Vec::new(),
|
||||
});
|
||||
cx.update(|window, _| window.activate_window());
|
||||
settle(cx);
|
||||
(host, cx)
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn a_running_copy_pauses_and_cancels_and_a_paused_one_resumes(cx: &mut TestAppContext) {
|
||||
let (host, cx) = copying(TransferState::Moving { rate: 1_000 }, cx);
|
||||
for nth in 1..=2 {
|
||||
tab_to(nth, cx);
|
||||
press("space", cx);
|
||||
}
|
||||
host.update(cx, |host, cx| {
|
||||
host.state = TransferState::Paused;
|
||||
cx.notify();
|
||||
});
|
||||
settle(cx);
|
||||
tab_to(1, cx);
|
||||
press("space", cx);
|
||||
assert_eq!(
|
||||
host.read_with(cx, |host, _| host.asked.clone()),
|
||||
["pause", "cancel", "resume"]
|
||||
);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn a_finished_copy_offers_nothing(cx: &mut TestAppContext) {
|
||||
let (_, cx) = copying(TransferState::Done, cx);
|
||||
tab_to(1, cx);
|
||||
assert!(cx.update(|window, cx| window.focused(cx).is_none()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "transfer a twice")]
|
||||
fn a_transfer_is_listed_once() {
|
||||
let _ = TransferQueue::new(
|
||||
"queue",
|
||||
[
|
||||
transfer("a", TransferState::Queued),
|
||||
transfer("a", TransferState::Done),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "a goes up, not down")]
|
||||
fn a_download_comes_down() {
|
||||
let mut up = transfer("a", TransferState::Queued);
|
||||
up.upload = true;
|
||||
let _ = DownloadManager::new("downloads", [up]);
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
use std::rc::Rc;
|
||||
|
||||
use gpui::{
|
||||
AnyElement, App, ElementId, InteractiveElement, IntoElement, ParentElement, SharedString,
|
||||
StatefulInteractiveElement, Styled, Window, div, prelude::*,
|
||||
};
|
||||
|
||||
use super::FileIcon;
|
||||
use crate::{
|
||||
buttons::{ButtonVariant, IconButton},
|
||||
motion::ProgressBar,
|
||||
primitives::{FocusRing, Icon, IconName},
|
||||
theme::{ActiveTheme, ControlSize, IconSize, Radius, TextSize},
|
||||
typography::{DurationStyle, Ellipsis, MiddleEllipsis, format},
|
||||
};
|
||||
|
||||
pub(super) type OnKey = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
|
||||
|
||||
/// Where a transfer stands.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum TransferState {
|
||||
/// Waiting its turn.
|
||||
Queued,
|
||||
/// Moving `rate` bytes a second.
|
||||
Moving {
|
||||
rate: u64,
|
||||
},
|
||||
Paused,
|
||||
Done,
|
||||
/// Stopped, and why.
|
||||
Failed(SharedString),
|
||||
}
|
||||
|
||||
/// One file on its way: its key, its name, whether it goes up, the bytes moved of all, and where it stands.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Transfer {
|
||||
pub key: SharedString,
|
||||
pub name: SharedString,
|
||||
pub upload: bool,
|
||||
pub moved: u64,
|
||||
pub total: u64,
|
||||
pub state: TransferState,
|
||||
}
|
||||
|
||||
/// A transfer's line under its name: how far and how fast, or where it stopped.
|
||||
pub(crate) fn status(transfer: &Transfer) -> String {
|
||||
let (moved, total) = (
|
||||
format::file_size(transfer.moved, false),
|
||||
format::file_size(transfer.total, false),
|
||||
);
|
||||
match &transfer.state {
|
||||
TransferState::Queued => format!("Waiting · {total}"),
|
||||
TransferState::Moving { rate } if *rate > 0 => {
|
||||
let left = transfer.total.saturating_sub(transfer.moved) / rate;
|
||||
format!(
|
||||
"{moved} of {total} · {}/s · {} left",
|
||||
format::file_size(*rate, false),
|
||||
format::duration(left.max(1), DurationStyle::Compact)
|
||||
)
|
||||
}
|
||||
TransferState::Moving { .. } => format!("{moved} of {total}"),
|
||||
TransferState::Paused => format!("Paused at {moved} of {total}"),
|
||||
TransferState::Done => total,
|
||||
TransferState::Failed(reason) => format!("Failed: {reason}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// What a row can ask of its host, each shown only with its handler.
|
||||
#[derive(Clone, Default)]
|
||||
pub(super) struct Asks {
|
||||
pub pause: Option<OnKey>,
|
||||
pub resume: Option<OnKey>,
|
||||
pub retry: Option<OnKey>,
|
||||
pub cancel: Option<OnKey>,
|
||||
pub open: Option<OnKey>,
|
||||
pub show: Option<OnKey>,
|
||||
}
|
||||
|
||||
/// A transfer as a row: its file's icon and name, a bar while it moves or waits paused, its status, and the actions its state allows: pause or resume, retry after a failure, cancel until done; a finished one opens on a press and shows its folder.
|
||||
pub(super) fn row(id: ElementId, transfer: &Transfer, asks: &Asks, cx: &App) -> AnyElement {
|
||||
let theme = cx.theme();
|
||||
let colors = &theme.colors;
|
||||
let key = transfer.key.clone();
|
||||
let action = |name: &'static str, icon: IconName, tip: &'static str, ask: &Option<OnKey>| {
|
||||
ask.clone().map(|ask| {
|
||||
let key = key.clone();
|
||||
IconButton::new((id.clone(), name), icon)
|
||||
.variant(ButtonVariant::Ghost)
|
||||
.size(ControlSize::Sm)
|
||||
.tooltip(tip)
|
||||
.on_click(move |_, window, cx| {
|
||||
log::info!("transfer {key}: {name}");
|
||||
ask(&key, window, cx)
|
||||
})
|
||||
})
|
||||
};
|
||||
let actions: Vec<_> = match transfer.state {
|
||||
TransferState::Moving { .. } => vec![
|
||||
action("pause", IconName::Pause, "Pause", &asks.pause),
|
||||
action("cancel", IconName::X, "Cancel", &asks.cancel),
|
||||
],
|
||||
TransferState::Paused => vec![
|
||||
action("resume", IconName::Play, "Resume", &asks.resume),
|
||||
action("cancel", IconName::X, "Cancel", &asks.cancel),
|
||||
],
|
||||
TransferState::Queued => vec![action("cancel", IconName::X, "Cancel", &asks.cancel)],
|
||||
TransferState::Failed(_) => vec![
|
||||
action("retry", IconName::RotateCw, "Retry", &asks.retry),
|
||||
action("cancel", IconName::X, "Remove", &asks.cancel),
|
||||
],
|
||||
TransferState::Done => vec![action(
|
||||
"show",
|
||||
IconName::FolderOpen,
|
||||
"Show in folder",
|
||||
&asks.show,
|
||||
)],
|
||||
};
|
||||
let bar = matches!(
|
||||
transfer.state,
|
||||
TransferState::Moving { .. } | TransferState::Paused
|
||||
)
|
||||
.then(|| {
|
||||
let share = if transfer.total == 0 {
|
||||
0.0
|
||||
} else {
|
||||
(transfer.moved as f64 / transfer.total as f64).min(1.0) as f32
|
||||
};
|
||||
ProgressBar::new((id.clone(), "bar"), share)
|
||||
});
|
||||
let failed = matches!(transfer.state, TransferState::Failed(_));
|
||||
let way = if transfer.upload {
|
||||
IconName::Upload
|
||||
} else {
|
||||
IconName::Download
|
||||
};
|
||||
let opens = asks
|
||||
.open
|
||||
.clone()
|
||||
.filter(|_| transfer.state == TransferState::Done);
|
||||
let name = transfer.key.clone();
|
||||
div()
|
||||
.id(id.clone())
|
||||
.debug_selector(move || format!("transfer-row {name}"))
|
||||
.w_full()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap_3()
|
||||
.px_3()
|
||||
.py_2()
|
||||
.rounded(theme.radius(Radius::Md))
|
||||
.border_1()
|
||||
.border_color(gpui::transparent_black())
|
||||
.when_some(opens, |row, open| {
|
||||
let key = key.clone();
|
||||
row.cursor_pointer()
|
||||
.tab_index(0)
|
||||
.focus_ring(cx)
|
||||
.hover(|style| style.bg(colors.hover))
|
||||
.on_click(move |_, window, cx| {
|
||||
log::info!("transfer {key}: open");
|
||||
open(&key, window, cx)
|
||||
})
|
||||
})
|
||||
.child(
|
||||
div()
|
||||
.flex_none()
|
||||
.child(FileIcon::file(&transfer.name).size(IconSize::Lg)),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex_1()
|
||||
.min_w_0()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap_1()
|
||||
.child(
|
||||
div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap_1p5()
|
||||
.child(Icon::new(way).size(IconSize::Xs).color(colors.fg_subtle))
|
||||
.child(
|
||||
div()
|
||||
.flex_1()
|
||||
.min_w_0()
|
||||
.text_color(colors.fg)
|
||||
.child(MiddleEllipsis::new(transfer.name.clone())),
|
||||
),
|
||||
)
|
||||
.children(bar)
|
||||
.child(
|
||||
div()
|
||||
.text_size(theme.text_size(TextSize::Xs))
|
||||
.text_color(if failed {
|
||||
colors.danger
|
||||
} else {
|
||||
colors.fg_muted
|
||||
})
|
||||
.child(Ellipsis::new(status(transfer))),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex_none()
|
||||
.flex()
|
||||
.children(actions.into_iter().flatten()),
|
||||
)
|
||||
.into_any_element()
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
use std::rc::Rc;
|
||||
|
||||
use gpui::{
|
||||
App, ElementId, FontWeight, IntoElement, ParentElement, RenderOnce, SharedString, Styled,
|
||||
Window, div, prelude::*,
|
||||
};
|
||||
|
||||
use super::transfer::{Asks, OnKey, Transfer, TransferState, row};
|
||||
use crate::{
|
||||
buttons::{Button, ButtonVariant},
|
||||
forms::Run,
|
||||
theme::{ActiveTheme, ControlSize, TextSize},
|
||||
};
|
||||
|
||||
/// Keys asserted once a list.
|
||||
fn unique(transfers: &[Transfer]) {
|
||||
for (ix, transfer) in transfers.iter().enumerate() {
|
||||
assert!(
|
||||
!transfers[..ix]
|
||||
.iter()
|
||||
.any(|other| other.key == transfer.key),
|
||||
"transfer {} twice",
|
||||
transfer.key
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// How many move and how many wait, as a header says it.
|
||||
pub(crate) fn tally(transfers: &[Transfer]) -> String {
|
||||
let moving = transfers
|
||||
.iter()
|
||||
.filter(|each| matches!(each.state, TransferState::Moving { .. }))
|
||||
.count();
|
||||
let waiting = transfers
|
||||
.iter()
|
||||
.filter(|each| matches!(each.state, TransferState::Queued | TransferState::Paused))
|
||||
.count();
|
||||
format!("{moving} moving · {waiting} waiting")
|
||||
}
|
||||
|
||||
macro_rules! asks {
|
||||
($name:ident) => {
|
||||
pub fn $name(
|
||||
mut self,
|
||||
handler: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
|
||||
) -> Self {
|
||||
self.asks.$name = Some(Rc::new(handler) as OnKey);
|
||||
self
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Uploads and downloads in one queue, a row a file: which way it goes, its bar, its status, and pause, resume, retry or cancel. How many move and wait sits above.
|
||||
#[derive(IntoElement)]
|
||||
pub struct TransferQueue {
|
||||
id: ElementId,
|
||||
transfers: Vec<Transfer>,
|
||||
asks: Asks,
|
||||
}
|
||||
|
||||
impl TransferQueue {
|
||||
pub fn new(id: impl Into<ElementId>, transfers: impl IntoIterator<Item = Transfer>) -> Self {
|
||||
let transfers: Vec<Transfer> = transfers.into_iter().collect();
|
||||
unique(&transfers);
|
||||
Self {
|
||||
id: id.into(),
|
||||
transfers,
|
||||
asks: Asks::default(),
|
||||
}
|
||||
}
|
||||
|
||||
asks!(pause);
|
||||
asks!(resume);
|
||||
asks!(retry);
|
||||
asks!(cancel);
|
||||
}
|
||||
|
||||
impl RenderOnce for TransferQueue {
|
||||
fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
|
||||
let theme = cx.theme();
|
||||
div()
|
||||
.debug_selector(|| "transfer-queue".into())
|
||||
.w_full()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap_1()
|
||||
.child(
|
||||
div()
|
||||
.px_3()
|
||||
.text_size(theme.text_size(TextSize::Sm))
|
||||
.text_color(theme.colors.fg_muted)
|
||||
.child(tally(&self.transfers)),
|
||||
)
|
||||
.children(self.transfers.iter().map(|transfer| {
|
||||
row(
|
||||
(self.id.clone(), format!("transfer-{}", transfer.key)).into(),
|
||||
transfer,
|
||||
&self.asks,
|
||||
cx,
|
||||
)
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
/// Downloads as a browser keeps them: those on their way above, those finished below under a header with Clear. A finished one opens with a press and shows its folder; the rest pause, resume, retry or cancel.
|
||||
#[derive(IntoElement)]
|
||||
pub struct DownloadManager {
|
||||
id: ElementId,
|
||||
downloads: Vec<Transfer>,
|
||||
asks: Asks,
|
||||
on_clear: Option<Run>,
|
||||
}
|
||||
|
||||
impl DownloadManager {
|
||||
pub fn new(id: impl Into<ElementId>, downloads: impl IntoIterator<Item = Transfer>) -> Self {
|
||||
let downloads: Vec<Transfer> = downloads.into_iter().collect();
|
||||
unique(&downloads);
|
||||
for download in &downloads {
|
||||
assert!(!download.upload, "{} goes up, not down", download.key);
|
||||
}
|
||||
Self {
|
||||
id: id.into(),
|
||||
downloads,
|
||||
asks: Asks::default(),
|
||||
on_clear: None,
|
||||
}
|
||||
}
|
||||
|
||||
asks!(pause);
|
||||
asks!(resume);
|
||||
asks!(retry);
|
||||
asks!(cancel);
|
||||
asks!(open);
|
||||
asks!(show);
|
||||
|
||||
/// Clears the finished ones from the list.
|
||||
pub fn on_clear(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
|
||||
self.on_clear = Some(Rc::new(handler));
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderOnce for DownloadManager {
|
||||
fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
|
||||
let theme = cx.theme();
|
||||
let colors = &theme.colors;
|
||||
let (done, going): (Vec<&Transfer>, Vec<&Transfer>) = self
|
||||
.downloads
|
||||
.iter()
|
||||
.partition(|download| download.state == TransferState::Done);
|
||||
let drawn = |download: &Transfer| {
|
||||
row(
|
||||
(self.id.clone(), format!("download-{}", download.key)).into(),
|
||||
download,
|
||||
&self.asks,
|
||||
cx,
|
||||
)
|
||||
};
|
||||
let clear = self.on_clear.map(|clear| {
|
||||
Button::new((self.id.clone(), "clear"), "Clear")
|
||||
.variant(ButtonVariant::Ghost)
|
||||
.size(ControlSize::Sm)
|
||||
.on_click(move |_, window, cx| {
|
||||
log::info!("download manager: cleared the finished");
|
||||
clear(window, cx)
|
||||
})
|
||||
});
|
||||
let finished = (!done.is_empty()).then(|| {
|
||||
div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_between()
|
||||
.gap_2()
|
||||
.px_3()
|
||||
.pt_2()
|
||||
.child(
|
||||
div()
|
||||
.text_size(theme.text_size(TextSize::Sm))
|
||||
.font_weight(FontWeight::SEMIBOLD)
|
||||
.text_color(colors.fg_muted)
|
||||
.child("Finished"),
|
||||
)
|
||||
.children(clear)
|
||||
});
|
||||
let empty = self.downloads.is_empty().then(|| {
|
||||
div()
|
||||
.px_3()
|
||||
.py_4()
|
||||
.text_size(theme.text_size(TextSize::Sm))
|
||||
.text_color(colors.fg_muted)
|
||||
.child("No downloads yet.")
|
||||
});
|
||||
div()
|
||||
.debug_selector(|| "download-manager".into())
|
||||
.w_full()
|
||||
.flex()
|
||||
.flex_col()
|
||||
.gap_1()
|
||||
.children(empty)
|
||||
.children(going.into_iter().map(drawn))
|
||||
.children(finished)
|
||||
.children(done.into_iter().map(drawn))
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user