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:
ZacharyZhang-NYandClaude Opus 5.5 committed 2026-09-26 21:05:59 -04:00
1 parent f324702c89
commit 0fcde7dbbe
11 files changed
+1180 -5

No files matched your search

+1
View File
@@ -113,6 +113,7 @@ Ely GPUI Component. A component library for GPUI, in light and dark.
- gpui 0.2.2's `line_clamp` wraps once and lays the rest on the last line, cut hard; centered, it loses both ends. A name whose ends matter is a `typography::MiddleEllipsis` on one line (`files::FileGrid`).
- Set an explicit line height on any box that clips text. gpui's default leading is taller than a tight box, and the clip eats descenders.
- gpui's `img` takes its picture's pixel size for any `Auto` side, and its aspect ratio beats percent heights in flow. `Image` pins it absolute at full size, so an `Image` needs a sized box.
- A file on its way is a `files::Transfer` drawn by one row in `files::transfer`: TransferQueue and DownloadManager share it, and its actions follow its state.
- Paths with `/` between folders become a tree through `lists::Folder::of`, for `FileTree` and `files::ArchiveViewer` alike.
- A folder's path over its entries is `lists::path_bar`, and its first order is `lists::listed`, folders first by name: DirectoryListing and FileExplorer share both, so every view shows one path and one order.
- A file's icon comes from `primitives::file_icon`, one map from name to icon for every chapter; `files::FileIcon` draws it. What fits across a width comes from `layout::columns_for`, and `layout::fit` adds the inset that centers it.
+2 -1
View File
@@ -96,7 +96,7 @@ Per-component lines live in `tasks/`. Tags there:
- [x] T26e Media · Capture and devices
- [x] T27a Files · Items
- [x] T27b Files · Explorer
- [ ] T27c Files · Find and look
- [x] T27c Files · Find and look
- [ ] T27d Files · Transfers
- [ ] T28 Messaging
- [ ] T29 Mail
@@ -326,3 +326,4 @@ Per-component lines live in `tasks/`. Tags there:
| T27b | 1 | FAIL | the listing's fixed columns left no room for names at 280px; a column keyed by its depth handed its cursor to the next folder there |
| T27b | 2 | PASS | |
| T27c | 1 | FAIL | recent and found files were keyed by their place, so the cursor left a file an open moved |
| T27c | 2 | PASS | |
+5
View File
@@ -9,6 +9,7 @@ use jiff::{Timestamp, ToSpan};
mod actions;
mod explorer;
mod find;
mod transfers;
use super::Page;
use crate::{
@@ -216,5 +217,9 @@ fn render(window: &mut Window, cx: &mut App) -> AnyElement {
.child(find::duplicates(window, cx))
.child(find::archive(cx))
.child(find::hex(window, cx))
.child(transfers::operations(window, cx))
.child(transfers::queue(window, cx))
.child(transfers::downloads(window, cx))
.child(transfers::storage(cx))
.into_any_element()
}
+248
View File
@@ -0,0 +1,248 @@
use ely_gpui_component::{
data_display::UsageBar,
files::{
DownloadManager, FileOperation, FileOperationProgress, Transfer, TransferQueue,
TransferState,
},
typography::format,
};
use gpui::{App, IntoElement, ParentElement, SharedString, Styled, Window, div, px};
use crate::{
probe::probe,
ui::{change, keep, section},
};
fn transfer(
key: &str,
name: &str,
upload: bool,
(moved, total): (u64, u64),
state: TransferState,
) -> Transfer {
Transfer {
key: SharedString::from(key.to_string()),
name: SharedString::from(name.to_string()),
upload,
moved,
total,
state,
}
}
pub fn operations(window: &mut Window, cx: &mut App) -> impl IntoElement + use<> {
let copy = keep(
"files-copy",
|| TransferState::Moving { rate: 38_000_000 },
window,
cx,
);
let now = copy.read(cx).clone();
let (pause, resume, cancel) = (copy.clone(), copy.clone(), copy);
let running = FileOperationProgress::new(
"files-copy",
FileOperation::Copy,
12,
"Atrium",
(46_000_000, 184_000_000),
now,
)
.current("Recordings/Walkthrough.mov")
.on_pause(move |_, cx| change(&pause, cx, |state| *state = TransferState::Paused))
.on_resume(move |_, cx| {
change(&resume, cx, |state| {
*state = TransferState::Moving { rate: 38_000_000 }
})
})
.on_cancel(move |_, cx| {
change(&cancel, cx, |state| {
*state = TransferState::Failed("Cancelled".into())
})
});
let failed = FileOperationProgress::new(
"files-move-failed",
FileOperation::Move,
3,
"Backup",
(820_000, 4_800_000),
TransferState::Failed("The disk Backup is full.".into()),
);
let done = FileOperationProgress::new(
"files-move-done",
FileOperation::Move,
1,
"Documents",
(88_000, 88_000),
TransferState::Done,
);
section(
"FileOperationProgress",
"A copy or a move under way: what it does and where to, a bar, the bytes done with the time left, and the file it takes now. Pause, resume and cancel while it runs.",
cx,
)
.child(probe(
"files-operations",
div()
.w(px(480.))
.flex()
.flex_col()
.gap_3()
.child(running)
.child(failed)
.child(done),
))
}
pub fn queue(window: &mut Window, cx: &mut App) -> impl IntoElement + use<> {
let transfers = keep(
"files-queue",
|| {
vec![
transfer(
"walkthrough",
"Walkthrough.mov",
true,
(61_000_000, 184_000_000),
TransferState::Moving { rate: 4_200_000 },
),
transfer(
"budget",
"Budget.csv",
true,
(0, 18_300),
TransferState::Queued,
),
transfer(
"moodboard",
"Moodboard.png",
false,
(1_100_000, 3_200_000),
TransferState::Paused,
),
transfer(
"survey",
"Survey.csv",
false,
(9_000, 42_000),
TransferState::Failed("The server hung up.".into()),
),
transfer(
"brief",
"Brief.md",
true,
(4_800, 4_800),
TransferState::Done,
),
]
},
window,
cx,
);
let now = transfers.read(cx).clone();
let set = |to: TransferState| {
let transfers = transfers.clone();
move |key: &SharedString, _: &mut Window, cx: &mut App| {
let to = to.clone();
change(&transfers, cx, |all| {
for each in all.iter_mut().filter(|each| each.key == *key) {
each.state = to.clone();
}
})
}
};
let drop = transfers.clone();
section(
"TransferQueue",
"Uploads and downloads in one queue: which way each goes, its bar and status, and pause, resume, retry or cancel as its state allows.",
cx,
)
.child(probe(
"files-queue",
div().w(px(480.)).child(
TransferQueue::new("files-queue", now)
.pause(set(TransferState::Paused))
.resume(set(TransferState::Moving { rate: 4_200_000 }))
.retry(set(TransferState::Moving { rate: 2_000_000 }))
.cancel(move |key, _, cx| change(&drop, cx, |all| all.retain(|each| each.key != *key))),
),
))
}
pub fn downloads(window: &mut Window, cx: &mut App) -> impl IntoElement + use<> {
let downloads = keep(
"files-downloads",
|| {
vec![
transfer(
"inter",
"Inter-4.1.zip",
false,
(2_600_000, 6_900_000),
TransferState::Moving { rate: 1_800_000 },
),
transfer(
"rust",
"rust-1.95.pkg",
false,
(0, 312_000_000),
TransferState::Queued,
),
transfer(
"atrium",
"Atrium.jpg",
false,
(2_140_000, 2_140_000),
TransferState::Done,
),
transfer(
"notes",
"Release notes.pdf",
false,
(430_000, 430_000),
TransferState::Done,
),
]
},
window,
cx,
);
let now = downloads.read(cx).clone();
let (drop, clear) = (downloads.clone(), downloads);
section(
"DownloadManager",
"Downloads as a browser keeps them: those on their way above, the finished below under Clear. A finished one opens with a press and shows its folder.",
cx,
)
.child(probe(
"files-downloads",
div().w(px(480.)).child(
DownloadManager::new("files-downloads", now)
.open(|key, _, _| log::info!("gallery: open {key}"))
.show(|key, _, _| log::info!("gallery: show {key} in its folder"))
.cancel(move |key, _, cx| change(&drop, cx, |all| all.retain(|each| each.key != *key)))
.on_clear(move |_, cx| {
change(&clear, cx, |all| all.retain(|each| each.state != TransferState::Done))
}),
),
))
}
pub fn storage(cx: &mut App) -> impl IntoElement + use<> {
const GB: f64 = 1_000_000_000.0;
section(
"StorageUsage",
"Where a disk's room goes, as data_display::UsageBar shows it: a part a kind, and what is left free.",
cx,
)
.child(probe(
"files-storage",
div().w(px(480.)).child(
UsageBar::new(512.0 * GB)
.part("Documents", 38.0 * GB)
.part("Photos", 142.0 * GB)
.part("Music", 61.0 * GB)
.part("Apps", 96.0 * GB)
.amounts(|bytes| format::file_size(bytes as u64, false)),
),
))
}
+6
View File
@@ -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};
+243
View File
@@ -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))
}))
}
}
+1
View File
@@ -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| {
+257
View File
@@ -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]);
}
+209
View File
@@ -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()
}
+204
View File
@@ -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))
}
}
+4 -4
View File
@@ -315,10 +315,10 @@
## T27d Files · Transfers
- [ ] FileOperationProgress
- [ ] TransferQueue
- [ ] DownloadManager
- [ ] StorageUsage → `data_display::UsageBar`
- [x] FileOperationProgress
- [x] TransferQueue
- [x] DownloadManager
- [x] StorageUsage → `data_display::UsageBar`
## T28 Messaging — `src/messaging`