From 99a0cb26cf04e9f605ec8f21397ad02f1e4a951c Mon Sep 17 00:00:00 2001 From: w33d Date: Sun, 25 Oct 2026 12:36:29 +0800 Subject: [PATCH 1/3] fix(ui): truncate paths by character, not byte truncate_path_middle sliced with a byte offset in its multi-segment branch, so any path containing CJK (or emoji) panicked the UI thread with "byte index N is not a char boundary". Uploading a Chinese-named file and rendering the transfer chip hit it immediately. All measurements are now in characters. ASCII output is unchanged. --- crabport-ui/src/layouts/toolbar.rs | 80 ++++++++++++++++++++++++------ 1 file changed, 65 insertions(+), 15 deletions(-) diff --git a/crabport-ui/src/layouts/toolbar.rs b/crabport-ui/src/layouts/toolbar.rs index a0cf9d1..ac76d09 100644 --- a/crabport-ui/src/layouts/toolbar.rs +++ b/crabport-ui/src/layouts/toolbar.rs @@ -397,43 +397,93 @@ pub fn format_byte_ratio(done: u64, total: u64) -> String { /// /// Lifted verbatim from the previous terminal-toolbar module so the SFTP /// progress chip keeps its existing behavior. +/// directory) and tail (filename) visible with `…` between them. +/// +/// Lifted from the previous terminal-toolbar module so the SFTP progress +/// chip keeps its existing behavior. +/// +/// **All measurements are in characters, not bytes.** Paths routinely +/// contain CJK names (e.g. `第二课堂__秦子皓.zip`); slicing a `&str` by a +/// byte offset lands mid-codepoint and panics the whole UI thread. pub fn truncate_path_middle(path: &str, max: usize) -> String { - if path.len() <= max { + // Take the first / last `n` characters of `s`. + fn head_chars(s: &str, n: usize) -> String { + s.chars().take(n).collect() + } + fn tail_chars(s: &str, n: usize) -> String { + let count = s.chars().count(); + s.chars().skip(count.saturating_sub(n)).collect() + } + + let char_len = path.chars().count(); + if char_len <= max { return path.to_string(); } let parts: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect(); let is_absolute = path.starts_with('/'); let prefix = if is_absolute { "/" } else { "" }; + let prefix_len = prefix.chars().count(); if parts.len() >= 3 { let head = parts[0]; - let tail = parts.last().unwrap(); + let tail = *parts.last().unwrap(); + let head_len = head.chars().count(); let candidate = format!("{prefix}{head}/…/{tail}"); - if candidate.len() <= max { + if candidate.chars().count() <= max { return candidate; } - let budget = max.saturating_sub(prefix.len() + head.len() + 4); // "/…/…" + let budget = max.saturating_sub(prefix_len + head_len + 4); // "/…/…" if budget > 4 { let half = budget / 2; - let t_len = tail.len(); - if t_len > budget { - let keep_head = &tail[..half]; - let keep_tail = &tail[t_len - half..]; + if tail.chars().count() > budget { + let keep_head = head_chars(tail, half); + let keep_tail = tail_chars(tail, half); return format!("{prefix}{head}/…/{keep_head}…{keep_tail}"); } } - let tail_budget = max.saturating_sub(prefix.len() + head.len() + 3); // "/…" + let tail_budget = max.saturating_sub(prefix_len + head_len + 3); // "/…" let cut = tail_budget.saturating_sub(1).max(1); - return format!("{prefix}{head}/…/{}…", &tail[..cut.min(tail.len())]); + return format!("{prefix}{head}/…/{}…", head_chars(tail, cut)); } let cut = max.saturating_sub(1); let half = cut / 2; - let chars: Vec = path.chars().collect(); - if chars.len() > cut { - let head: String = chars[..half].iter().collect(); - let tail: String = chars[chars.len() - half..].iter().collect(); + if char_len > cut { + let head = head_chars(path, half); + let tail = tail_chars(path, half); return format!("{head}…{tail}"); } - path.chars().take(cut).collect::() + "…" + head_chars(path, cut) + "…" +} + +#[cfg(test)] +mod tests { + use super::truncate_path_middle; + + #[test] + fn short_paths_are_returned_unchanged() { + assert_eq!(truncate_path_middle("/a/b.txt", 40), "/a/b.txt"); + assert_eq!(truncate_path_middle("第二课堂.zip", 40), "第二课堂.zip"); + } + + /// Regression: a CJK path used to panic the UI thread because the + /// multi-segment branch sliced `&tail[..n]` by *byte* offset. + #[test] + fn cjk_paths_truncate_without_panicking() { + let path = "/Users/weed/课程/第二课堂__秦子皓_2208210127.zip"; + let out = truncate_path_middle(path, 20); + assert!( + out.chars().count() <= 20, + "output wider than the limit: {out:?}" + ); + assert!(out.contains('…'), "expected an ellipsis: {out:?}"); + } + + #[test] + fn cjk_filename_without_directories_truncates_by_char() { + assert_eq!( + truncate_path_middle("文件名称非常长的一个文件.txt", 10), + "文件名称….txt" + ); + } } From 0348a1f73dba0d5354fa7cb7bbae72a869949d1c Mon Sep 17 00:00:00 2001 From: w33d Date: Sun, 25 Oct 2026 12:37:04 +0800 Subject: [PATCH 2/3] feat(sftp): transfer panel with per-task pause and cancel Replaces the read-only progress chip plus history-only popover with a real transfer queue for the SFTP tab. - crabport-sftp: new TransferControl carries pause / cancel intent and a live byte + stage mirror. The streaming loops checkpoint before every chunk, so pause takes effect within one chunk (256 KiB) and cancel ends the transfer. - crabport-terminal: *_controlled transfer entry points let callers hand in a control handle. Default impls keep the old fire-and-forget path, so backends without a streaming loop are unaffected. - crabport-ssh: threads the control through file / dir / batch transfers, mirrors progress into it, records the outcome, and keeps the SFTP channel in the cache when the user cancels (a cancellation is not a dead channel). - crabport-ui: TransferCenter replaces TransferHistoryController. Active jobs and recent history share one virtualized list, so the history stays visible while a transfer runs. It opens from the SFTP toolbar button or by clicking the in-flight progress chip. Each job row has pause / resume and cancel buttons, and its progress fill rides the row's bottom rule. - History rows show direction and status as icons (check / close) with colour instead of text labels. --- crabport-sftp/Cargo.toml | 2 +- crabport-sftp/src/control.rs | 238 ++++++ crabport-sftp/src/lib.rs | 4 + crabport-sftp/src/transfer.rs | 29 +- crabport-ssh/src/backend.rs | 19 + crabport-ssh/src/terminal.rs | 82 +- crabport-ssh/src/transfer.rs | 7 +- crabport-ssh/src/transfer/dir.rs | 15 +- crabport-ssh/src/transfer/file.rs | 29 +- crabport-ssh/src/transfer/handle.rs | 28 + crabport-terminal/src/terminal.rs | 67 ++ crabport-ui/assets/icons/pause.svg | 1 + crabport-ui/assets/icons/play.svg | 1 + crabport-ui/i18n/en.toml | 7 +- crabport-ui/i18n/zh-CN.toml | 7 +- crabport-ui/src/app.rs | 6 +- crabport-ui/src/app/context.rs | 9 +- crabport-ui/src/app/tabs.rs | 28 + crabport-ui/src/layouts/content.rs | 91 +- crabport-ui/src/views/sftp.rs | 6 +- crabport-ui/src/views/sftp/toolbar.rs | 29 +- crabport-ui/src/views/sftp/transfer_center.rs | 794 ++++++++++++++++++ .../src/views/sftp/transfer_history.rs | 384 --------- crabport-ui/src/views/sftp/view.rs | 108 ++- crabport-ui/src/views/terminal.rs | 35 + crabport-ui/src/views/terminal/toolbar.rs | 91 +- 26 files changed, 1580 insertions(+), 537 deletions(-) create mode 100644 crabport-sftp/src/control.rs create mode 100644 crabport-ui/assets/icons/pause.svg create mode 100644 crabport-ui/assets/icons/play.svg create mode 100644 crabport-ui/src/views/sftp/transfer_center.rs delete mode 100644 crabport-ui/src/views/sftp/transfer_history.rs diff --git a/crabport-sftp/Cargo.toml b/crabport-sftp/Cargo.toml index 5f7f52b..8b7b94a 100644 --- a/crabport-sftp/Cargo.toml +++ b/crabport-sftp/Cargo.toml @@ -7,7 +7,7 @@ edition.workspace = true anyhow = "1" russh = "0.45" russh-sftp = "2" -tokio = { version = "1", features = ["rt", "fs", "io-util", "macros"] } +tokio = { version = "1", features = ["rt", "fs", "io-util", "macros", "sync"] } async-compression = { version = "0.4", features = ["tokio", "gzip"] } tar = "0.4" flate2 = "1" diff --git a/crabport-sftp/src/control.rs b/crabport-sftp/src/control.rs new file mode 100644 index 0000000..4d5c469 --- /dev/null +++ b/crabport-sftp/src/control.rs @@ -0,0 +1,238 @@ +//! Cooperative pause / cancel + live counters for an in-flight transfer. +//! +//! ## Why this exists +//! +//! The SFTP transfer loops in [`crate::SftpBackend`] stream a file chunk by +//! chunk. Before this module they had no way to be interrupted: once a +//! transfer started, the only way to stop it was to close the tab (which +//! aborts the whole backend task). Each transfer now carries an optional +//! `Arc`: +//! +//! - the streaming loop calls [`TransferControl::checkpoint`] before every +//! chunk — it returns immediately while running, awaits while paused, and +//! errors once cancelled; +//! - the backend mirrors byte counters and the current stage into it, so the +//! UI can render a progress bar for a *specific* job without needing +//! per-transfer ids on the shared event stream; +//! - [`TransferControl::finish`] records the outcome so the panel can retire +//! the job even if it missed the broadcast event. +//! +//! ## Stage ids +//! +//! Stages are stored as `u8` constants rather than +//! `crabport_terminal::SftpTransferStage` because this crate sits *below* +//! `crabport-terminal` in the dependency graph. The UI maps them back to its +//! own enum for labels. + +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; + +use anyhow::{Result, anyhow}; +use tokio::sync::Notify; + +/// Running normally — `checkpoint` returns immediately. +const RUNNING: u8 = 0; +/// Paused by the user — `checkpoint` waits for a resume (or cancel). +const PAUSED: u8 = 1; +/// Cancelled — `checkpoint` returns an error, ending the transfer. +const CANCELLED: u8 = 2; + +/// No stage reported yet. +pub const STAGE_NONE: u8 = 0; +/// Local compression / remote `gzip` staging (no byte progress). +pub const STAGE_COMPRESS: u8 = 1; +/// The byte-carrying SFTP stream. +pub const STAGE_TRANSFER: u8 = 2; +/// Decompression after the bytes have arrived. +pub const STAGE_DECOMPRESS: u8 = 3; +/// Temp-file cleanup. +pub const STAGE_CLEANUP: u8 = 4; + +/// Shared handle to one transfer's state. +/// +/// Always held as an `Arc`; `Send + Sync` so it can travel into the backend's +/// spawned task and still be read by the UI thread. +pub struct TransferControl { + /// One of `RUNNING` / `PAUSED` / `CANCELLED`. + state: AtomicU8, + /// One of the `STAGE_*` constants. + stage: AtomicU8, + /// Bytes processed in the current stage. + done: AtomicU64, + /// Total bytes for the current stage (0 = unknown). + total: AtomicU64, + /// Set once by [`Self::finish`]. + finished: AtomicBool, + /// Outcome recorded by [`Self::finish`]. + success: AtomicBool, + /// Human-readable result, set by [`Self::finish`]. + message: Mutex, + /// Wakes a paused loop on resume / cancel. `notify_one` (rather than + /// `notify_waiters`) stores a permit when nobody is waiting, which closes + /// the resume-before-await race. + notify: Notify, +} + +impl TransferControl { + /// Create a control in the `RUNNING` state. + pub fn new() -> Arc { + Arc::new(Self { + state: AtomicU8::new(RUNNING), + stage: AtomicU8::new(STAGE_NONE), + done: AtomicU64::new(0), + total: AtomicU64::new(0), + finished: AtomicBool::new(false), + success: AtomicBool::new(false), + message: Mutex::new(String::new()), + notify: Notify::new(), + }) + } + + /// Ask the transfer to pause. No-op when already paused, cancelled, or + /// finished (a finished transfer has no loop left to pause). + pub fn pause(&self) { + let _ = self + .state + .compare_exchange(RUNNING, PAUSED, Ordering::AcqRel, Ordering::Acquire); + } + + /// Resume a paused transfer. + pub fn resume(&self) { + if self + .state + .compare_exchange(PAUSED, RUNNING, Ordering::AcqRel, Ordering::Acquire) + .is_ok() + { + self.notify.notify_one(); + } + } + + /// Cancel the transfer. Idempotent; also wakes a paused loop so it can + /// observe the cancellation. + pub fn cancel(&self) { + self.state.store(CANCELLED, Ordering::Release); + self.notify.notify_one(); + } + + /// Toggle pause/resume and report the resulting paused state. + pub fn toggle_pause(&self) -> bool { + if self.is_paused() { + self.resume(); + false + } else { + self.pause(); + true + } + } + + pub fn is_paused(&self) -> bool { + self.state.load(Ordering::Acquire) == PAUSED + } + + pub fn is_cancelled(&self) -> bool { + self.state.load(Ordering::Acquire) == CANCELLED + } + + /// Current stage id (`STAGE_*`). + pub fn set_stage(&self, stage: u8) { + self.stage.store(stage, Ordering::Release); + } + + pub fn stage(&self) -> u8 { + self.stage.load(Ordering::Acquire) + } + + /// Mirror byte progress for the current stage. + pub fn set_progress(&self, done: u64, total: u64) { + self.done.store(done, Ordering::Relaxed); + self.total.store(total, Ordering::Relaxed); + } + + /// `(done, total)` for the current stage. `total == 0` means unknown. + pub fn progress(&self) -> (u64, u64) { + ( + self.done.load(Ordering::Relaxed), + self.total.load(Ordering::Relaxed), + ) + } + + /// Record the outcome. Called by the backend right before it broadcasts + /// the finished event, so the panel can retire the job even if the event + /// races the next render. + pub fn finish(&self, success: bool, message: impl Into) { + *self.message.lock().unwrap_or_else(|e| e.into_inner()) = message.into(); + self.success.store(success, Ordering::Release); + self.finished.store(true, Ordering::Release); + } + + pub fn is_finished(&self) -> bool { + self.finished.load(Ordering::Acquire) + } + + pub fn success(&self) -> bool { + self.success.load(Ordering::Acquire) + } + + pub fn message(&self) -> String { + self.message + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clone() + } + + /// Cooperative interruption point for a streaming loop. + /// + /// Returns `Ok(())` immediately while running; waits while paused; + /// returns an error once cancelled. Call it before each chunk so a pause + /// takes effect within one chunk (256 KiB at most). + pub async fn checkpoint(&self) -> Result<()> { + loop { + match self.state.load(Ordering::Acquire) { + CANCELLED => return Err(anyhow!("transfer cancelled")), + PAUSED => self.notify.notified().await, + _ => return Ok(()), + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pause_and_resume_toggle_state() { + let c = TransferControl::new(); + assert!(!c.is_paused()); + assert!(c.toggle_pause()); + assert!(c.is_paused()); + assert!(!c.toggle_pause()); + assert!(!c.is_paused()); + } + + #[test] + fn cancel_is_sticky() { + let c = TransferControl::new(); + assert!(!c.is_cancelled()); + c.cancel(); + c.cancel(); + assert!(c.is_cancelled()); + } + + #[test] + fn finish_records_outcome_once() { + let c = TransferControl::new(); + assert!(!c.is_finished()); + c.finish(false, "boom"); + assert!(c.is_finished()); + assert!(!c.success()); + assert_eq!(c.message(), "boom"); + } + + #[test] + fn progress_is_visible_to_readers() { + let c = TransferControl::new(); + c.set_progress(512, 1024); + assert_eq!(c.progress(), (512, 1024)); + } +} diff --git a/crabport-sftp/src/lib.rs b/crabport-sftp/src/lib.rs index 3ac5fd5..7d04d3c 100644 --- a/crabport-sftp/src/lib.rs +++ b/crabport-sftp/src/lib.rs @@ -7,9 +7,13 @@ mod api; mod archive; mod backend; +mod control; mod entry; mod transfer; pub use api::CrabPortSftp; pub use backend::SftpBackend; +pub use control::{ + STAGE_CLEANUP, STAGE_COMPRESS, STAGE_DECOMPRESS, STAGE_NONE, STAGE_TRANSFER, TransferControl, +}; pub use entry::FileEntry; diff --git a/crabport-sftp/src/transfer.rs b/crabport-sftp/src/transfer.rs index d2dbc6a..f902557 100644 --- a/crabport-sftp/src/transfer.rs +++ b/crabport-sftp/src/transfer.rs @@ -6,6 +6,7 @@ use tokio::io::{AsyncReadExt, AsyncWriteExt}; use crate::archive::{build_tar_gz, local_tmp_path, validate_gzip}; use crate::backend::SftpBackend; +use crate::control::TransferControl; /// Per-segment buffer size when streaming an upload. Larger buffers mean fewer /// SFTP write requests but more memory; 256 KiB is a reasonable default that @@ -29,6 +30,7 @@ impl SftpBackend { remote_path: &str, local_path: &str, progress: Option>, + control: Option<&TransferControl>, ) -> Result<()> { tracing::info!("SFTP download_file: remote={remote_path} local={local_path}"); let session = self.session(); @@ -51,6 +53,10 @@ impl SftpBackend { let mut file = session.open(remote_path).await?; let mut buf = vec![0u8; UPLOAD_CHUNK_SIZE]; loop { + // Cooperative pause / cancel point (no-op unless the user asked). + if let Some(c) = control { + c.checkpoint().await?; + } let n = file.read(&mut buf).await?; if n == 0 { break; @@ -79,6 +85,7 @@ impl SftpBackend { local_path: &str, remote_path: &str, progress: Option>, + control: Option<&TransferControl>, ) -> Result<()> { let session = self.session(); let mut local = tokio::fs::File::open(local_path).await?; @@ -87,6 +94,9 @@ impl SftpBackend { let mut total: u64 = 0; let mut buf = vec![0u8; UPLOAD_CHUNK_SIZE]; loop { + if let Some(c) = control { + c.checkpoint().await?; + } let n = local.read(&mut buf).await?; if n == 0 { break; @@ -118,6 +128,7 @@ impl SftpBackend { local_path: &str, remote_path: &str, progress: Option>, + control: Option<&TransferControl>, ) -> Result<()> { let session = self.session(); let mut local = tokio::fs::File::open(local_path).await?; @@ -127,6 +138,9 @@ impl SftpBackend { let mut total: u64 = 0; let mut buf = vec![0u8; UPLOAD_CHUNK_SIZE]; loop { + if let Some(c) = control { + c.checkpoint().await?; + } let n = local.read(&mut buf).await?; if n == 0 { break; @@ -161,12 +175,16 @@ impl SftpBackend { remote_path: &str, local_path: &str, progress: Option>, + control: Option<&TransferControl>, ) -> Result<()> { tracing::info!("SFTP download_file_gz: remote={remote_path} local={local_path}"); // 1. Download the .gz into a local tmp file. let tmp = local_tmp_path(".gz"); let tmp_str = tmp.to_str().unwrap().to_string(); - if let Err(e) = self.download_file(remote_path, &tmp_str, progress).await { + if let Err(e) = self + .download_file(remote_path, &tmp_str, progress, control) + .await + { let _ = std::fs::remove_file(&tmp); return Err(e); } @@ -229,6 +247,7 @@ impl SftpBackend { remote_tar_gz: &str, archive_name: &str, progress: Option>, + control: Option<&TransferControl>, ) -> Result<()> { // 1. Build a tmp tar.gz of the local directory. let tmp = local_tmp_path(".tar.gz"); @@ -242,7 +261,7 @@ impl SftpBackend { // non-gz `upload_file` because the data is already a tar.gz — // wrapping it in another gzip layer would just waste CPU. let upload_result = self - .upload_file(tmp.to_str().unwrap(), remote_tar_gz, progress) + .upload_file(tmp.to_str().unwrap(), remote_tar_gz, progress, control) .await; // 3. Always remove the local tmp file, even on upload failure. @@ -266,12 +285,16 @@ impl SftpBackend { remote_tar_gz: &str, local_dir: &str, progress: Option>, + control: Option<&TransferControl>, ) -> Result<()> { tracing::info!("SFTP download_dir: remote_tar_gz={remote_tar_gz} local_dir={local_dir}"); // 1. Download the remote tar.gz into a local tmp file. let tmp = local_tmp_path(".tar.gz"); let tmp_str = tmp.to_str().unwrap().to_string(); - if let Err(e) = self.download_file(remote_tar_gz, &tmp_str, progress).await { + if let Err(e) = self + .download_file(remote_tar_gz, &tmp_str, progress, control) + .await + { let _ = std::fs::remove_file(&tmp); return Err(e); } diff --git a/crabport-ssh/src/backend.rs b/crabport-ssh/src/backend.rs index b39719f..200034f 100644 --- a/crabport-ssh/src/backend.rs +++ b/crabport-ssh/src/backend.rs @@ -816,6 +816,7 @@ impl SshBackend { handle: self.handle.clone(), sftp_session: self.sftp_session.clone(), event_tx: Some(self.event_tx.clone()), + control: None, }; crate::transfer::sftp_download_impl(&backend, remote_path, local_path).await } @@ -830,6 +831,7 @@ impl SshBackend { handle: self.handle.clone(), sftp_session: self.sftp_session.clone(), event_tx: Some(self.event_tx.clone()), + control: None, }; crate::transfer::sftp_upload_impl(&backend, local_path, remote_path).await } @@ -862,6 +864,23 @@ impl SshBackend { let abort = join.abort_handle(); self.transfer_tasks.lock().push(abort); } + + /// Build the borrowed transfer handle for one SFTP operation. + /// + /// `control` carries the user's pause/cancel intent plus the live + /// byte/stage mirror; `None` for operations the UI doesn't expose controls + /// for (delete / rename / mkdir / edit), which have no streaming loop. + pub(crate) fn sftp_transfer_handle( + &self, + control: Option>, + ) -> crate::transfer::SftpTransferHandle { + crate::transfer::SftpTransferHandle { + handle: self.handle.clone(), + sftp_session: self.sftp_session.clone(), + event_tx: Some(self.event_tx.clone()), + control, + } + } } // --------------------------------------------------------------------------- diff --git a/crabport-ssh/src/terminal.rs b/crabport-ssh/src/terminal.rs index 230a8d0..667b386 100644 --- a/crabport-ssh/src/terminal.rs +++ b/crabport-ssh/src/terminal.rs @@ -10,7 +10,6 @@ use crabport_terminal::terminal::{ use crate::TOKIO; use crate::backend::{Command, SshBackend}; -use crate::transfer::SftpTransferHandle; impl CrabPortTerminal for SshBackend { fn write(&self, data: &[u8]) { @@ -147,11 +146,22 @@ impl CrabPortTerminal for SshBackend { } fn sftp_download(&self, remote_path: &str, local_path: &str) { - let backend = SftpTransferHandle { - handle: self.handle.clone(), - sftp_session: self.sftp_session.clone(), - event_tx: Some(self.event_tx.clone()), - }; + // No caller-supplied control: the transfer still runs, it just isn't + // pause/cancel-able from the panel (legacy fire-and-forget path). + self.sftp_download_controlled( + remote_path, + local_path, + crabport_sftp::TransferControl::new(), + ); + } + + fn sftp_download_controlled( + &self, + remote_path: &str, + local_path: &str, + control: Arc, + ) { + let backend = self.sftp_transfer_handle(Some(control.clone())); let event_tx = self.event_tx.clone(); let remote_path = remote_path.to_string(); let local_path = local_path.to_string(); @@ -162,6 +172,7 @@ impl CrabPortTerminal for SshBackend { Ok(()) => (true, format!("downloaded {local_path}")), Err(e) => (false, format!("download failed: {e}")), }; + control.finish(success, message.clone()); let _ = event_tx .broadcast(BackendEvent::SftpTransferFinished { kind: SftpTransferKind::Download, @@ -173,11 +184,20 @@ impl CrabPortTerminal for SshBackend { } fn sftp_upload(&self, local_path: &str, remote_path: &str) { - let backend = SftpTransferHandle { - handle: self.handle.clone(), - sftp_session: self.sftp_session.clone(), - event_tx: Some(self.event_tx.clone()), - }; + self.sftp_upload_controlled( + local_path, + remote_path, + crabport_sftp::TransferControl::new(), + ); + } + + fn sftp_upload_controlled( + &self, + local_path: &str, + remote_path: &str, + control: Arc, + ) { + let backend = self.sftp_transfer_handle(Some(control.clone())); let event_tx = self.event_tx.clone(); let remote_path = remote_path.to_string(); let local_path = local_path.to_string(); @@ -188,6 +208,7 @@ impl CrabPortTerminal for SshBackend { Ok(()) => (true, format!("uploaded {remote_path}")), Err(e) => (false, format!("upload failed: {e}")), }; + control.finish(success, message.clone()); let _ = event_tx .broadcast(BackendEvent::SftpTransferFinished { kind: SftpTransferKind::Upload, @@ -199,11 +220,15 @@ impl CrabPortTerminal for SshBackend { } fn sftp_upload_batch(&self, items: &[(String, String)]) { - let backend = SftpTransferHandle { - handle: self.handle.clone(), - sftp_session: self.sftp_session.clone(), - event_tx: Some(self.event_tx.clone()), - }; + self.sftp_upload_batch_controlled(items, crabport_sftp::TransferControl::new()); + } + + fn sftp_upload_batch_controlled( + &self, + items: &[(String, String)], + control: Arc, + ) { + let backend = self.sftp_transfer_handle(Some(control.clone())); let event_tx = self.event_tx.clone(); let items = items.to_vec(); self.spawn_transfer(async move { @@ -212,6 +237,7 @@ impl CrabPortTerminal for SshBackend { Ok(()) => (true, format!("uploaded {} files", items.len())), Err(e) => (false, format!("batch upload failed: {e}")), }; + control.finish(success, message.clone()); let _ = event_tx .broadcast(BackendEvent::SftpTransferFinished { kind: SftpTransferKind::Upload, @@ -228,11 +254,7 @@ impl CrabPortTerminal for SshBackend { // so the existing UI finish handling (toolbar clear, overlay log) // applies. We use the Download kind arbitrarily — the message text // carries the real semantics. - let backend = SftpTransferHandle { - handle: self.handle.clone(), - sftp_session: self.sftp_session.clone(), - event_tx: Some(self.event_tx.clone()), - }; + let backend = self.sftp_transfer_handle(None); let event_tx = self.event_tx.clone(); let remote_path = remote_path.to_string(); self.spawn_transfer(async move { @@ -252,11 +274,7 @@ impl CrabPortTerminal for SshBackend { } fn sftp_rename(&self, old_path: &str, new_path: &str) { - let backend = SftpTransferHandle { - handle: self.handle.clone(), - sftp_session: self.sftp_session.clone(), - event_tx: Some(self.event_tx.clone()), - }; + let backend = self.sftp_transfer_handle(None); let event_tx = self.event_tx.clone(); let old_path = old_path.to_string(); let new_path = new_path.to_string(); @@ -277,11 +295,7 @@ impl CrabPortTerminal for SshBackend { } fn sftp_open_in_editor(&self, remote_path: &str) { - let backend = SftpTransferHandle { - handle: self.handle.clone(), - sftp_session: self.sftp_session.clone(), - event_tx: Some(self.event_tx.clone()), - }; + let backend = self.sftp_transfer_handle(None); let event_tx = self.event_tx.clone(); let remote_path = remote_path.to_string(); self.spawn_transfer(async move { @@ -306,11 +320,7 @@ impl CrabPortTerminal for SshBackend { // sink. There's no actual transfer, but we emit a `SftpTransferFinished` // so the existing UI finish handling (listing refresh on success, // toast on failure) applies. - let backend = SftpTransferHandle { - handle: self.handle.clone(), - sftp_session: self.sftp_session.clone(), - event_tx: Some(self.event_tx.clone()), - }; + let backend = self.sftp_transfer_handle(None); let event_tx = self.event_tx.clone(); let remote_path = remote_path.to_string(); self.spawn_transfer(async move { diff --git a/crabport-ssh/src/transfer.rs b/crabport-ssh/src/transfer.rs index a648e86..a243c3b 100644 --- a/crabport-ssh/src/transfer.rs +++ b/crabport-ssh/src/transfer.rs @@ -160,7 +160,12 @@ async fn sftp_upload_batch_via_tar( let s = backend.take_or_open_sftp().await?; let local_tmp_str = local_tmp.to_string_lossy().into_owned(); let res = s - .upload_file(&local_tmp_str, &remote_tmp, Some(progress_cb)) + .upload_file( + &local_tmp_str, + &remote_tmp, + Some(progress_cb), + backend.control.as_deref(), + ) .await; backend.return_sftp(s, res).await?; diff --git a/crabport-ssh/src/transfer/dir.rs b/crabport-ssh/src/transfer/dir.rs index e7ec303..7898211 100644 --- a/crabport-ssh/src/transfer/dir.rs +++ b/crabport-ssh/src/transfer/dir.rs @@ -148,7 +148,12 @@ async fn sftp_download_dir_via_tar( .unwrap_or_else(|| std::path::PathBuf::from(".")); let unpack_dir_str = unpack_dir.to_string_lossy().into_owned(); let res = s - .download_dir(&tmp, &unpack_dir_str, Some(progress_cb)) + .download_dir( + &tmp, + &unpack_dir_str, + Some(progress_cb), + backend.control.as_deref(), + ) .await; backend.return_sftp(s, res).await?; @@ -187,7 +192,13 @@ async fn sftp_upload_dir_via_tar( progress_cb(0); let s = backend.take_or_open_sftp().await?; let res = s - .upload_dir(local_path, &tmp, &remote_base, Some(progress_cb)) + .upload_dir( + local_path, + &tmp, + &remote_base, + Some(progress_cb), + backend.control.as_deref(), + ) .await; backend.return_sftp(s, res).await?; diff --git a/crabport-ssh/src/transfer/file.rs b/crabport-ssh/src/transfer/file.rs index f99564e..39832e1 100644 --- a/crabport-ssh/src/transfer/file.rs +++ b/crabport-ssh/src/transfer/file.rs @@ -80,8 +80,20 @@ pub(crate) async fn sftp_download_file_impl( progress_cb(0); let s = backend.take_or_open_sftp().await?; let res = s - .download_file_gz(&tmp, local_path, Some(progress_cb)) + .download_file_gz( + &tmp, + local_path, + Some(progress_cb), + backend.control.as_deref(), + ) .await; + // A user cancellation is not a dead channel: park the session back in the + // cache so the next transfer doesn't pay for a fresh SFTP handshake, and + // surface the cancellation as its own error. + if backend.control.as_ref().is_some_and(|c| c.is_cancelled()) { + backend.return_sftp(s, Ok(())).await.ok(); + return Err(anyhow::anyhow!("transfer cancelled")); + } if let Err(ref e) = res { tracing::warn!("SFTP download file: transfer failed: {e}"); } @@ -128,7 +140,20 @@ pub(crate) async fn sftp_upload_file_impl( "SFTP upload file: step 1 transfer+compress local={local_path} -> remote_tmp={tmp} total={total}" ); let s = backend.take_or_open_sftp().await?; - let upload_res = s.upload_file_gz(local_path, &tmp, Some(progress_cb)).await; + let upload_res = s + .upload_file_gz( + local_path, + &tmp, + Some(progress_cb), + backend.control.as_deref(), + ) + .await; + if backend.control.as_ref().is_some_and(|c| c.is_cancelled()) { + // Keep the healthy session; the partial remote tmp is left for the + // next attempt to overwrite (same as any other failed upload). + backend.return_sftp(s, Ok(())).await.ok(); + return Err(anyhow::anyhow!("transfer cancelled")); + } backend.return_sftp(s, upload_res).await?; // Acquire the SSH handle for the exec step. diff --git a/crabport-ssh/src/transfer/handle.rs b/crabport-ssh/src/transfer/handle.rs index b953863..5085e96 100644 --- a/crabport-ssh/src/transfer/handle.rs +++ b/crabport-ssh/src/transfer/handle.rs @@ -4,6 +4,7 @@ use async_broadcast::Sender as BroadcastSender; use tokio::sync::Mutex as TokioMutex; use crabport_sftp::CrabPortSftp; +use crabport_sftp::TransferControl; use crabport_terminal::terminal::{ BackendEvent, SftpTransferBytes, SftpTransferKind, SftpTransferStage, }; @@ -26,6 +27,22 @@ pub(crate) struct SftpTransferHandle { /// handle is constructed by code paths that don't have an `event_tx` /// (e.g. tests); in that case progress is simply not reported. pub(crate) event_tx: Option>, + /// Optional pause / cancel + progress mirror for the panel. `None` for + /// transfers started through the legacy fire-and-forget methods (and for + /// tests) — the transfer then runs to completion with no user control. + pub(crate) control: Option>, +} + +/// Map the terminal crate's stage enum onto the control's `u8` stage ids. +/// Kept here (rather than in `crabport-sftp`) because that crate sits below +/// the one that defines the enum. +fn stage_id(stage: SftpTransferStage) -> u8 { + match stage { + SftpTransferStage::Compress => crabport_sftp::STAGE_COMPRESS, + SftpTransferStage::Transfer => crabport_sftp::STAGE_TRANSFER, + SftpTransferStage::Decompress => crabport_sftp::STAGE_DECOMPRESS, + SftpTransferStage::CleanUp => crabport_sftp::STAGE_CLEANUP, + } } impl SftpTransferHandle { @@ -93,6 +110,9 @@ impl SftpTransferHandle { let Some(tx) = self.event_tx.as_ref() else { return; }; + if let Some(c) = self.control.as_ref() { + c.set_stage(stage_id(stage)); + } let _ = tx .broadcast(BackendEvent::SftpTransferProgress { kind, @@ -119,9 +139,17 @@ impl SftpTransferHandle { total: u64, ) -> Arc { let tx = self.event_tx.clone(); + let control = self.control.clone(); let last = Arc::new(std::sync::atomic::AtomicU64::new(0)); let message = std::sync::Arc::new(message); Arc::new(move |done: u64| { + // Mirror every chunk into the control (unthrottled) so the + // panel's progress bar is smooth even though the broadcast + // event below is throttled. + if let Some(c) = control.as_ref() { + c.set_progress(done, total); + c.set_stage(crabport_sftp::STAGE_TRANSFER); + } // Throttle: only emit if at least 100ms of wall-clock has passed // since the last emit. We approximate "time" with a monotonic // nanos counter stored in the atomic — this avoids pulling in a diff --git a/crabport-terminal/src/terminal.rs b/crabport-terminal/src/terminal.rs index 2b6a210..303041d 100644 --- a/crabport-terminal/src/terminal.rs +++ b/crabport-terminal/src/terminal.rs @@ -288,6 +288,42 @@ pub trait CrabPortTerminal: Send + Sync { /// [`BackendEvent::SftpTransferFinished`] for the batch. fn sftp_upload_batch(&self, _items: &[(String, String)]) {} + /// Like [`Self::sftp_download`], but the transfer observes `control`: + /// the streaming loop pauses / aborts at the user's request and mirrors + /// byte progress + stage into the control so the transfer panel can + /// render this specific job. + /// + /// Backends without a cooperative transfer loop fall back to the plain + /// method (the control is simply ignored), which is correct for every + /// non-SSH backend since they have no SFTP transfers at all. + fn sftp_download_controlled( + &self, + remote_path: &str, + local_path: &str, + _control: std::sync::Arc, + ) { + self.sftp_download(remote_path, local_path); + } + + /// See [`Self::sftp_download_controlled`]. + fn sftp_upload_controlled( + &self, + local_path: &str, + remote_path: &str, + _control: std::sync::Arc, + ) { + self.sftp_upload(local_path, remote_path); + } + + /// See [`Self::sftp_download_controlled`]. + fn sftp_upload_batch_controlled( + &self, + _items: &[(String, String)], + _control: std::sync::Arc, + ) { + self.sftp_upload_batch(_items); + } + /// Create a directory on the remote host at `remote_path`. Parent /// directories must already exist (SFTP `mkdir` is not recursive). /// Completion is reported via [`BackendEvent::SftpTransferFinished`] @@ -1495,6 +1531,37 @@ impl TerminalSession { self.backend.sftp_upload_batch(items); } + /// Controlled variants — see [`CrabPortTerminal::sftp_download_controlled`]. + pub fn sftp_download_controlled( + &self, + remote_path: &str, + local_path: &str, + control: std::sync::Arc, + ) { + self.backend + .sftp_download_controlled(remote_path, local_path, control); + } + + /// See [`Self::sftp_download_controlled`]. + pub fn sftp_upload_controlled( + &self, + local_path: &str, + remote_path: &str, + control: std::sync::Arc, + ) { + self.backend + .sftp_upload_controlled(local_path, remote_path, control); + } + + /// See [`Self::sftp_download_controlled`]. + pub fn sftp_upload_batch_controlled( + &self, + items: &[(String, String)], + control: std::sync::Arc, + ) { + self.backend.sftp_upload_batch_controlled(items, control); + } + /// Delete a remote file or directory. /// Completion is reported via the backend's event stream as /// `BackendEvent::SftpTransferFinished`. diff --git a/crabport-ui/assets/icons/pause.svg b/crabport-ui/assets/icons/pause.svg new file mode 100644 index 0000000..bea531b --- /dev/null +++ b/crabport-ui/assets/icons/pause.svg @@ -0,0 +1 @@ + diff --git a/crabport-ui/assets/icons/play.svg b/crabport-ui/assets/icons/play.svg new file mode 100644 index 0000000..5954813 --- /dev/null +++ b/crabport-ui/assets/icons/play.svg @@ -0,0 +1 @@ + diff --git a/crabport-ui/i18n/en.toml b/crabport-ui/i18n/en.toml index 5f6bdf0..662fb49 100644 --- a/crabport-ui/i18n/en.toml +++ b/crabport-ui/i18n/en.toml @@ -290,8 +290,11 @@ drop_upload_hint = "Drop files to upload" drag_download_hint = "Drag to terminal to download" history_title = "Transfer history" history_empty = "No transfers yet" -history_status_success = "Success" -history_status_failed = "Failed" +transfers_title = "Transfers" +transfer_paused = "Paused" +transfer_cancelling = "Cancelling" +transfer_cancelled = "Cancelled" +transfer_waiting = "Waiting" [sftp.progress] download = "Download" diff --git a/crabport-ui/i18n/zh-CN.toml b/crabport-ui/i18n/zh-CN.toml index 176fead..a0dc17f 100644 --- a/crabport-ui/i18n/zh-CN.toml +++ b/crabport-ui/i18n/zh-CN.toml @@ -289,8 +289,11 @@ drop_upload_hint = "拖放文件以上传" drag_download_hint = "拖动到终端以下载" history_title = "传输历史" history_empty = "暂无传输记录" -history_status_success = "成功" -history_status_failed = "失败" +transfers_title = "传输任务" +transfer_paused = "已暂停" +transfer_cancelling = "正在取消" +transfer_cancelled = "已取消" +transfer_waiting = "等待中" [sftp.progress] download = "下载" diff --git a/crabport-ui/src/app.rs b/crabport-ui/src/app.rs index b8d8bed..00a09e9 100644 --- a/crabport-ui/src/app.rs +++ b/crabport-ui/src/app.rs @@ -266,7 +266,7 @@ impl CrabportApp { let tooltip = cx.new(|_cx| crate::components::tooltip::TooltipController::new()); let notifications = cx.new(|_cx| NotificationController::new(NotificationPosition::BottomRight)); - let transfer_history = cx.new(|_cx| crate::views::sftp::TransferHistoryController::new()); + let transfers = cx.new(|_cx| crate::views::sftp::TransferCenter::new()); let tunnels = Arc::new(crate::views::tunnels::TunnelRegistry::new()); // Read persisted data through the shared global store. The global @@ -295,7 +295,7 @@ impl CrabportApp { context_menu, tooltip, notifications, - transfer_history, + transfers, tunnels, command_palette, sftp_panel, @@ -651,7 +651,7 @@ impl Render for CrabportApp { // -- Global toast notifications -- .child(self.app_ctx.notifications.clone()) // -- Global SFTP transfer-history popover -- - .child(self.app_ctx.transfer_history.clone()) + .child(self.app_ctx.transfers.clone()) // -- Group form overlay (new / rename group, shared across kinds) -- .when_some(group_form_state, |el, state| { el.child(crate::views::groups::GroupFormView::new( diff --git a/crabport-ui/src/app/context.rs b/crabport-ui/src/app/context.rs index 8221cb2..713ef2e 100644 --- a/crabport-ui/src/app/context.rs +++ b/crabport-ui/src/app/context.rs @@ -52,10 +52,11 @@ pub struct AppCtx { pub tooltip: Entity, /// Global toast notification host. pub notifications: Entity, - /// Global SFTP transfer-history popover host. Toggled from the SFTP - /// toolbar's history button; records are pushed by - /// `SftpTabView::on_sftp_transfer_finished`. - pub transfer_history: Entity, + /// Global SFTP transfer panel host (live jobs + recent history). + /// Opened from the SFTP toolbar's transfer button or by clicking the + /// in-flight progress chip; jobs are registered by the surfaces that + /// start transfers (`SftpTabView`, terminal-tab SFTP callbacks). + pub transfers: Entity, // -- Shared data registries -- /// Central tunnel registry (stopped + running). Single source of truth diff --git a/crabport-ui/src/app/tabs.rs b/crabport-ui/src/app/tabs.rs index b8c86f6..03aae72 100644 --- a/crabport-ui/src/app/tabs.rs +++ b/crabport-ui/src/app/tabs.rs @@ -127,9 +127,18 @@ impl CrabportApp { // whole view to avoid re-rendering the app on every terminal frame // pump tick (~120Hz during output). let app_handle = cx.entity().downgrade(); + let transfers_for_progress = self.app_ctx.transfers.clone(); terminal_view.update(cx, |view, _cx| { view.set_on_sftp_progress_changed(move |cx| { let _ = app_handle.update(cx, |_, cx| cx.notify()); + // Keep the open transfer panel animating: it reads the job's + // control handle directly, so it needs a repaint when the + // backend pushes new byte counts. + let _ = transfers_for_progress.update(cx, |c, cx| { + if c.is_open() { + cx.notify(); + } + }); }); }); @@ -139,8 +148,27 @@ impl CrabportApp { // closure so the toast text follows the language active at toast // time, not the language at tab-creation time. let app_handle = cx.entity().downgrade(); + let transfers_for_history = self.app_ctx.transfers.clone(); terminal_view.update(cx, |view, _cx| { view.set_on_sftp_transfer_finished(move |kind, success, message, cx| { + // Keep the transfer panel in sync: a finished job is retired + // into history on its next render. + let _ = transfers_for_history.update(cx, |_, cx| cx.notify()); + // Uploads / downloads are recorded by the transfer center + // when it retires their job; only the non-job operations + // (rename / edit / delete / mkdir) need a record here. + if !matches!(kind, SftpTransferKind::Upload | SftpTransferKind::Download) { + let record = crate::views::sftp::TransferRecord { + kind, + success, + message: message.clone(), + finished_at: std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or(0), + }; + let _ = transfers_for_history.update(cx, |c, cx| c.push(record, cx)); + } let _ = app_handle.update(cx, |app, cx| { let (title, message_notif, level, duration) = match (kind, success) { (SftpTransferKind::Download, true) => ( diff --git a/crabport-ui/src/layouts/content.rs b/crabport-ui/src/layouts/content.rs index 168be79..89ca77a 100644 --- a/crabport-ui/src/layouts/content.rs +++ b/crabport-ui/src/layouts/content.rs @@ -22,7 +22,7 @@ use crate::views::sessions::{ConnectionFormState, ConnectionHost}; use crate::views::terminal::TerminalView; use crate::views::terminal::split::{SplitDir, SplitNode}; use crate::views::terminal::toolbar::{TerminalToolbarInput, render_terminal_toolbar}; -use crabport_terminal::terminal::{RemoteMetrics, RemoteStatus}; +use crabport_terminal::terminal::{RemoteMetrics, RemoteStatus, SftpTransferKind}; /// Clone the active terminal's `Entity` so a callback can forward calls to /// the backend without capturing a borrow on `terminal_views`. @@ -307,10 +307,12 @@ pub fn render_content( // Clone the download callback + terminal entity so the // on_drop handler can trigger a download when the user // drags an SFTP file row onto the terminal area. + let transfers_for_drop = ctx.transfers.clone(); let on_download_for_drop = term_entity_for_drop.clone().map(|entity| { move |drag: &SftpDragValue, cx: &mut App| { let remote_path = drag.remote_path.clone(); let name = drag.name.clone(); + let transfers = transfers_for_drop.clone(); let rx = cx.prompt_for_paths(PathPromptOptions { files: false, directories: true, @@ -324,10 +326,28 @@ pub fn render_content( _ => None, }; let Some(dest_dir) = picked else { return }; - let local_path = dest_dir.join(&name); + let local_path = dest_dir.join(&name).to_string_lossy().into_owned(); let _ = cx.update(|cx| { + // Same job registration as the SFTP panel's + // download callback, so a dropped file is + // pause/cancel-able from the transfer panel. + let control = crabport_sftp::TransferControl::new(); + let label = crate::views::sftp::transfer_label(&remote_path); + let job_control = control.clone(); + let _ = transfers.update(cx, |center, cx| { + center.start_job( + SftpTransferKind::Download, + label, + job_control, + cx, + ); + }); entity.read_with(cx, |view, _cx| { - view.sftp_download(&remote_path, &local_path.to_string_lossy()); + view.sftp_download_controlled( + &remote_path, + &local_path, + control, + ); }); }); }) @@ -474,7 +494,7 @@ pub fn render_content( context_menu.clone(), alert_controller.clone(), ctx.tooltip.clone(), - ctx.transfer_history.clone(), + ctx.transfers.clone(), hosts.to_vec(), handle.clone(), window, @@ -568,10 +588,46 @@ pub fn render_content( // active tab isn't a terminal or has no terminal entity. let sftp_navigate = term_cb!(sftp_term, (path: String), view => view.sftp_navigate(&path)); - let sftp_download = term_cb!(sftp_term, (remote_path: String, local_path: String), - view => view.sftp_download(&remote_path, &local_path)); - let sftp_upload = term_cb!(sftp_term, (local_path: String, remote_path: String), - view => view.sftp_upload(&local_path, &remote_path)); + // Downloads / uploads started from the right-hand SFTP panel register a + // job with the global transfer center before hitting the backend, so the + // transfer panel can show them with pause / cancel controls. (The plain + // `sftp_download` / `sftp_upload` wrappers are used by paths that don't + // have a center handle — e.g. the AI tools.) + let transfers_for_sftp = ctx.transfers.clone(); + let sftp_download: Option> = + sftp_term.clone().map(|entity| { + let transfers = transfers_for_sftp.clone(); + Rc::new( + move |remote_path: String, local_path: String, cx: &mut App| { + let control = crabport_sftp::TransferControl::new(); + let label = crate::views::sftp::transfer_label(&remote_path); + let job_control = control.clone(); + let _ = transfers.update(cx, |center, cx| { + center.start_job(SftpTransferKind::Download, label, job_control, cx); + }); + entity.read_with(cx, |view, _cx| { + view.sftp_download_controlled(&remote_path, &local_path, control); + }); + }, + ) as Rc + }); + let sftp_upload: Option> = + sftp_term.clone().map(|entity| { + let transfers = transfers_for_sftp.clone(); + Rc::new( + move |local_path: String, remote_path: String, cx: &mut App| { + let control = crabport_sftp::TransferControl::new(); + let label = crate::views::sftp::transfer_label(&local_path); + let job_control = control.clone(); + let _ = transfers.update(cx, |center, cx| { + center.start_job(SftpTransferKind::Upload, label, job_control, cx); + }); + entity.read_with(cx, |view, _cx| { + view.sftp_upload_controlled(&local_path, &remote_path, control); + }); + }, + ) as Rc + }); let sftp_delete = term_cb!(sftp_term, (remote_path: String), view => view.sftp_delete(&remote_path)); let sftp_rename = term_cb!(sftp_term, (old_path: String, new_path: String), @@ -923,15 +979,22 @@ pub fn render_content( // terminal toolbar knowing about SFTP. Terminal tabs pass an // empty vec (no trailing buttons). if is_sftp_tab { - let transfer_history = ctx.transfer_history.clone(); - let on = transfer_history.read_with(cx, |c, _| c.is_open()); - vec![ - crate::views::sftp::render_sftp_history_toggle(transfer_history, on) - .into_any_element(), - ] + let transfers = ctx.transfers.clone(); + let on = transfers.read_with(cx, |c, _| c.is_open()); + vec![crate::views::sftp::render_transfers_toggle(transfers, on).into_any_element()] } else { Vec::new() }, + // Clicking the in-flight transfer chip expands the transfer + // panel (anchored at the chip), so pause / cancel are one click + // away from the status the user is looking at. + Some(std::rc::Rc::new({ + let transfers = ctx.transfers.clone(); + move |pos: gpui::Point, cx: &mut App| { + let _ = transfers.update(cx, |c, cx| c.toggle(pos, cx)); + } + }) + as std::rc::Rc, &mut App)>), { let handle = handle.clone(); move |id, cx| { diff --git a/crabport-ui/src/views/sftp.rs b/crabport-ui/src/views/sftp.rs index 3f6d329..4e0bf82 100644 --- a/crabport-ui/src/views/sftp.rs +++ b/crabport-ui/src/views/sftp.rs @@ -12,11 +12,11 @@ mod helpers; pub(crate) mod pane; mod panel; pub mod toolbar; -pub mod transfer_history; +pub mod transfer_center; pub mod view; pub use drag::{LocalFileDragValue, SftpDragValue}; pub(crate) use helpers::upload_picker_options; -pub use toolbar::render_sftp_history_toggle; -pub use transfer_history::{TransferHistoryController, TransferRecord}; +pub use toolbar::render_transfers_toggle; +pub use transfer_center::{TransferCenter, TransferJob, TransferRecord, transfer_label}; pub use view::{PanelHost, SftpTabView}; diff --git a/crabport-ui/src/views/sftp/toolbar.rs b/crabport-ui/src/views/sftp/toolbar.rs index e2540ad..878a4be 100644 --- a/crabport-ui/src/views/sftp/toolbar.rs +++ b/crabport-ui/src/views/sftp/toolbar.rs @@ -5,43 +5,40 @@ //! `crabport-ui/src/views/terminal/toolbar.rs`). The terminal toolbar //! owns the "metrics + SFTP progress" slots; this module owns the //! SFTP-tab-only actions that don't fit the slot model — currently just -//! the "transfer history" toggle button, which toggles the global -//! [`TransferHistoryController`] popover instead of a slot. +//! the transfer-panel toggle button, which opens the global +//! [`TransferCenter`] (live jobs with pause / cancel, plus recent history). use gpui::*; use gpui_animation::animation::TransitionExt; use crate::color::*; use crate::motion::{EASE_STANDARD, RADIUS_SM, duration_slower}; -use crate::views::sftp::TransferHistoryController; +use crate::views::sftp::TransferCenter; // --------------------------------------------------------------------------- -// render_sftp_history_toggle +// render_transfers_toggle // --------------------------------------------------------------------------- -/// Render the "SFTP transfer history" toggle button shown in the SFTP -/// tab's toolbar (right-aligned, before the gear icon). +/// Render the transfer-panel toggle button shown in the SFTP tab's toolbar +/// (right-aligned, before the history button). /// /// Ghost button mirroring the terminal pane's split buttons: default bg /// is fully transparent so it blends with the toolbar background; the -/// `selected` state (i.e. the popover is currently open) tints the bg +/// `selected` state (i.e. the panel is currently open) tints the bg /// and switches the icon to `text_primary()` so the user can tell at a -/// glance whether the popover is open. +/// glance whether the panel is open. /// /// On click the button calls `controller.toggle(event.position)` so the -/// popover anchors to the button. The controller is the global -/// [`TransferHistoryController`] entity held by `AppCtx` — same pattern -/// as the context-menu / tooltip controllers. +/// panel anchors to the button. Clicking the in-flight progress chip in the +/// toolbar does the same thing (see `render_terminal_toolbar`), so both +/// affordances lead to the same panel. /// /// `on` is the controller's current open state, read by the caller /// (which has a `&App` available). We take it as a param rather than /// reading inside the element builder because `Entity::read_with` /// needs a `&App` that isn't available at element-build time. -pub fn render_sftp_history_toggle( - controller: Entity, - on: bool, -) -> impl IntoElement { - let btn_id = ElementId::Name("sftp-history-toggle".into()); +pub fn render_transfers_toggle(controller: Entity, on: bool) -> impl IntoElement { + let btn_id = ElementId::Name("sftp-transfers-toggle".into()); // Resting bg: transparent (alpha 0) so the toolbar background reads // through. The `selected` state swaps in `surface_hover()` with full diff --git a/crabport-ui/src/views/sftp/transfer_center.rs b/crabport-ui/src/views/sftp/transfer_center.rs new file mode 100644 index 0000000..e832c8f --- /dev/null +++ b/crabport-ui/src/views/sftp/transfer_center.rs @@ -0,0 +1,794 @@ +//! SFTP transfer panel — live jobs (with pause / cancel) plus recent +//! history. +//! +//! Like the global tooltip / context-menu controllers, this is an `Entity` +//! held by the app root and rendered as a top-level overlay (not inside the +//! `SftpTabView` view tree). It opens from either of the SFTP tab's toolbar +//! affordances: +//! +//! - the **transfer-history** button, and +//! - the **in-flight progress chip** (clicking it expands the same panel). +//! +//! ## Jobs vs. records +//! +//! A [`TransferJob`] is one transfer the user started from a UI surface that +//! went through this controller. The job owns the transfer's +//! [`TransferControl`], so the panel can +//! +//! - render live byte progress (the backend mirrors `done` / `total` and the +//! current stage into the control on every chunk), and +//! - pause / resume / cancel it from the row's buttons. +//! +//! When the backend reports the transfer finished it calls +//! [`TransferControl::finish`]. The next render retires the job into +//! [`TransferRecord`] history (see [`TransferCenter::retire_finished`]) — +//! that is what keeps the panel honest even if it missed the broadcast +//! event. Non-transfer operations (rename / delete / mkdir / edit) push +//! records directly via [`TransferCenter::push`]. + +use std::rc::Rc; +use std::sync::Arc; + +use gpui::prelude::FluentBuilder; +use gpui::*; +use gpui_animation::animation::TransitionExt; +use gpui_component::scroll::{Scrollbar, ScrollbarShow}; +use gpui_component::{VirtualListScrollHandle, v_virtual_list}; +use rust_i18n::t; + +use crate::color::*; +use crate::layouts::toolbar::color_accent; +use crate::motion::{EASE_STANDARD, RADIUS_LG, RADIUS_SM, duration_base, duration_fast}; +use crabport_sftp::TransferControl; +use crabport_terminal::terminal::SftpTransferKind; + +/// Maximum history records kept in memory. Older entries are dropped (FIFO). +const MAX_RECORDS: usize = 200; +/// Hard cap on simultaneous job rows — a runaway caller can't grow the panel +/// without bound. Transfers past the cap still run; they just aren't listed. +const MAX_JOBS: usize = 32; +/// Pop-in/out animation duration. Must match the `transition_when_else` +/// duration in `render_panel` so the dismiss timer clears state at the right +/// moment. +const DISMISS_MS: u64 = 180; + +/// Panel width in px. Wide enough for a two-line job row with two trailing +/// buttons, narrow enough to read as a popover anchored to the toolbar. +const PANEL_W: f32 = 420.0; +/// Panel height in px. Fixed so the popover doesn't jump as jobs start and +/// finish; the list inside scrolls instead. +const PANEL_H: f32 = 380.0; + +/// Row heights. The list is virtualized (`v_virtual_list`), which needs a +/// height per item up front; active jobs are two-line rows with buttons, +/// history rows are single-line. +const JOB_ROW_HEIGHT: f32 = 52.0; +const RECORD_ROW_HEIGHT: f32 = 30.0; + +/// One row of the merged transfer list: an in-flight job or a finished +/// record. Both share one virtualized scroll area so the history stays +/// visible while a transfer runs. +#[derive(Clone)] +enum TransferRow { + Job(TransferJob), + Record(TransferRecord), +} + +/// A completed SFTP transfer, captured for the history section. +/// +/// Records are kept in-memory only (one `Vec` per controller), most- +/// recent-first. We don't persist them to the Store — the history is meant +/// as a "what just happened" aid within a session, not a permanent log. +#[derive(Clone, Debug)] +pub struct TransferRecord { + pub kind: SftpTransferKind, + pub success: bool, + /// The backend-supplied detail string — typically the path of the file + /// that was processed. Kept verbatim so the user sees exactly what the + /// backend reported. + pub message: String, + /// When the transfer finished (local Unix timestamp), for display. + pub finished_at: i64, +} + +/// One in-flight transfer the user can pause / cancel. +#[derive(Clone)] +pub struct TransferJob { + /// Monotonic id, unique within this controller. + pub id: u64, + pub kind: SftpTransferKind, + /// Short, human-readable subject: the file name (or "N files" for a + /// batch), not the full path — the panel is narrow. + pub label: String, + /// The transfer's control handle. Shared with the backend task. + pub control: Arc, + /// When the job started (local Unix timestamp), for display. + pub started_at: i64, +} + +/// Global SFTP transfer panel state. +pub struct TransferCenter { + /// Most-recent-first. Capped at [`MAX_RECORDS`]. + records: Vec, + /// In-flight jobs, most-recent-first. + jobs: Vec, + /// Scroll position for the virtualized list. Persisted across renders so + /// reopening the panel lands where the user left off. + scroll_handle: VirtualListScrollHandle, + /// Where to anchor the panel (button's window-relative position). + anchor: Option>, + open: bool, + /// Monotonic counter bumped on every show/hide so stale dismiss tasks + /// don't clobber a freshly-shown panel. + generation: u64, + /// Id source for [`TransferJob`]s. + next_id: u64, +} + +impl TransferCenter { + pub fn new() -> Self { + Self { + records: Vec::new(), + jobs: Vec::new(), + scroll_handle: VirtualListScrollHandle::new(), + anchor: None, + open: false, + generation: 0, + next_id: 1, + } + } + + /// Append a history record (for operations that don't run as jobs — + /// rename / delete / mkdir / edit, or transfers started outside the UI + /// surfaces that create jobs). + pub fn push(&mut self, record: TransferRecord, cx: &mut Context) { + self.records.insert(0, record); + if self.records.len() > MAX_RECORDS { + self.records.truncate(MAX_RECORDS); + } + cx.notify(); + } + + /// Register a job and hand back its id. Called *before* the backend + /// transfer starts so the panel never shows a job that already completed. + pub fn start_job( + &mut self, + kind: SftpTransferKind, + label: impl Into, + control: Arc, + cx: &mut Context, + ) -> u64 { + let id = self.next_id; + self.next_id = self.next_id.wrapping_add(1); + if self.jobs.len() < MAX_JOBS { + self.jobs.insert( + 0, + TransferJob { + id, + kind, + label: label.into(), + control, + started_at: now_secs(), + }, + ); + } + cx.notify(); + id + } + + /// Reap jobs whose transfer has finished and file them as history. + /// + /// Safe to call every render: the work is proportional to the number of + /// active jobs (a handful) and no-ops when nothing finished. We + /// deliberately do **not** notify from here — the caller is already + /// inside a render. + fn retire_finished(&mut self) { + let mut kept: Vec = Vec::with_capacity(self.jobs.len()); + for job in self.jobs.drain(..) { + if !job.control.is_finished() { + kept.push(job); + continue; + } + // A cancelled job reports `success == false`; use a dedicated + // "Cancelled" label rather than the backend's echoed error text + // (which reads like a failure the user didn't ask for). Successful + // jobs keep their file name so the row doesn't change wording the + // moment it slides from the active block into history; failures + // keep the backend's error text because that is the useful part. + let message = if job.control.is_cancelled() { + t!("sftp.transfer_cancelled").to_string() + } else if job.control.success() { + job.label.clone() + } else { + job.control.message() + }; + self.records.insert( + 0, + TransferRecord { + kind: job.kind, + success: job.control.success(), + message, + finished_at: now_secs(), + }, + ); + } + self.jobs = kept; + if self.records.len() > MAX_RECORDS { + self.records.truncate(MAX_RECORDS); + } + } + + /// Toggle the panel open/closed at `anchor` (window-relative). + pub fn toggle(&mut self, anchor: Point, cx: &mut Context) { + if self.open { + self.hide(cx); + } else { + self.show(anchor, cx); + } + } + + /// Show the panel at `anchor`, replacing any currently-showing one. + pub fn show(&mut self, anchor: Point, cx: &mut Context) { + self.generation = self.generation.wrapping_add(1); + self.anchor = Some(anchor); + self.open = true; + gpui_animation::reset_transition(&ElementId::Name("sftp-transfer-panel".into())); + cx.notify(); + } + + /// Begin the dismiss animation. After [`DISMISS_MS`] the anchor is + /// dropped so the panel no longer captures renders. + pub fn hide(&mut self, cx: &mut Context) { + if !self.open { + return; + } + self.generation = self.generation.wrapping_add(1); + let dismiss_gen = self.generation; + self.open = false; + cx.notify(); + + let entity = cx.entity().downgrade(); + cx.spawn(async move |_this, cx| { + smol::Timer::after(std::time::Duration::from_millis(DISMISS_MS)).await; + let _ = entity.update(cx, |this, cx| { + if this.generation == dismiss_gen { + this.anchor = None; + cx.notify(); + } + }); + }) + .detach(); + } + + pub fn is_open(&self) -> bool { + self.open + } + + /// Number of records currently held. + pub fn len(&self) -> usize { + self.records.len() + } + + /// Number of transfers currently running or paused. + pub fn active_count(&self) -> usize { + self.jobs.len() + } +} + +impl Render for TransferCenter { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + // Retire completed jobs before the anchor check so a finished job is + // filed into history even while the panel is closed. + self.retire_finished(); + + let Some(anchor) = self.anchor else { + return div().into_any_element(); + }; + let open = self.open; + let viewport = _window.viewport_size(); + let entity = cx.entity().downgrade(); + let active = self.jobs.len(); + + // Snapshot the merged row list (active jobs first, then history) plus + // the per-item heights the virtual list needs. Copying handles here + // keeps the `Fn` render closure independent of `self`. + let mut rows: Vec = Vec::with_capacity(self.jobs.len() + self.records.len()); + let mut sizes: Vec> = Vec::with_capacity(self.jobs.len() + self.records.len()); + for job in &self.jobs { + rows.push(TransferRow::Job(job.clone())); + sizes.push(Size { + width: px(0.0), + height: px(JOB_ROW_HEIGHT), + }); + } + for record in &self.records { + rows.push(TransferRow::Record(record.clone())); + sizes.push(Size { + width: px(0.0), + height: px(RECORD_ROW_HEIGHT), + }); + } + let rows = Rc::new(rows); + + let body: AnyElement = if rows.is_empty() { + div() + .flex_1() + .min_h_0() + .flex() + .items_center() + .justify_center() + .text_xs() + .text_color(rgb(text_muted())) + .child(t!("sftp.history_empty").to_string()) + .into_any_element() + } else { + let scroll_handle = self.scroll_handle.clone(); + let list = v_virtual_list(cx.entity(), "sftp-transfer-list", Rc::new(sizes), { + let rows = rows.clone(); + move |_this, range, _window, cx| { + let entity = cx.entity().downgrade(); + range + .map(|i| match &rows[i] { + TransferRow::Job(job) => render_job_row(job.clone(), entity.clone()), + TransferRow::Record(record) => { + render_history_row(i, record.clone()).into_any_element() + } + }) + .collect::>() + } + }) + .track_scroll(&scroll_handle); + div() + .relative() + .flex_1() + .min_h_0() + .child(list) + .child( + div() + .absolute() + .top_0() + .right_0() + .bottom_0() + .w(px(10.0)) + .child( + Scrollbar::vertical(&scroll_handle) + .scrollbar_show(ScrollbarShow::Hover), + ), + ) + .into_any_element() + }; + + render_panel(anchor, open, body, active, viewport, entity).into_any_element() + } +} + +/// Render the panel. Anchored to `anchor` (the trigger's position), clamped +/// to stay inside the window. +fn render_panel( + anchor: Point, + open: bool, + body: AnyElement, + active: usize, + viewport: Size, + entity: WeakEntity, +) -> impl IntoElement { + let overlay_id = ElementId::Name("sftp-transfer-overlay".into()); + let panel_id = ElementId::Name("sftp-transfer-panel".into()); + + let mut x = f32::from(anchor.x); + let mut y = f32::from(anchor.y) + 28.0; // below the trigger + // Flip left when the panel would overflow the right edge. + if x + PANEL_W > f32::from(viewport.width) { + x = (f32::from(anchor.x) - PANEL_W).max(0.0); + } + // Flip up when it would overflow the bottom edge. + if y + PANEL_H > f32::from(viewport.height) { + y = (f32::from(anchor.y) - PANEL_H - 4.0).max(0.0); + } + + div() + .id(overlay_id.clone()) + .absolute() + .top_0() + .left_0() + .size_full() + .when(open, { + let entity = entity.clone(); + move |el| { + el.occlude().on_click(move |_e, _w, cx| { + let _ = entity.update(cx, |this, cx| this.hide(cx)); + }) + } + }) + .with_transition(overlay_id) + .transition_when_else( + open, + duration_base(), + EASE_STANDARD, + |el| el.bg(rgba(0x00000000)), + |el| el.bg(rgba(0x00000000)), + ) + .child( + div() + .id(panel_id.clone()) + .absolute() + .top(px(y)) + .left(px(x)) + .w(px(PANEL_W)) + .h(px(PANEL_H)) + .flex() + .flex_col() + .bg(rgb(bg_base())) + .border_1() + .border_color(rgb(border())) + .rounded(RADIUS_LG) + .shadow_lg() + .overflow_hidden() + .opacity(0.0) + .mt(px(-4.0)) + .with_transition(panel_id) + .transition_when_else( + open, + duration_base(), + EASE_STANDARD, + |el| el.opacity(1.0).mt_0(), + |el| el.opacity(0.0).mt(px(-4.0)), + ) + .when(open, |el| { + el.on_click(|_e, _w, cx| { + cx.stop_propagation(); + }) + }) + .child(render_header(active, entity.clone())) + // One virtualized list, not two sections: in-flight jobs sit on + // top of the recent records so a transfer stays visible next to + // the history it is about to join. + .child(body), + ) +} + +fn render_header(active: usize, entity: WeakEntity) -> impl IntoElement { + div() + .flex() + .flex_row() + .items_center() + .justify_between() + .px_3() + .py_2() + .border_b_1() + .border_color(rgb(border())) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap_2() + .child( + div() + .text_sm() + .font_weight(FontWeight::SEMIBOLD) + .text_color(rgb(text_primary())) + .child(t!("sftp.transfers_title").to_string()), + ) + .when(active > 0, |el| { + el.child( + div() + .px_1p5() + .py_0p5() + .rounded_full() + .bg(rgba((color_accent() << 8) | 0x33)) + .text_xs() + .text_color(rgb(color_accent())) + .child(active.to_string()), + ) + }), + ) + .child( + div() + .id("sftp-transfer-close") + .flex() + .items_center() + .justify_center() + .size(px(20.0)) + .rounded(RADIUS_SM) + .cursor_pointer() + .on_click(move |_e, _w, cx| { + let _ = entity.update(cx, |this, cx| this.hide(cx)); + }) + .child( + svg() + .path("icons/close.svg") + .size(px(12.0)) + .text_color(rgb(text_muted())), + ), + ) +} + +/// One active transfer: icon + label + state/progress on the left, pause and +/// cancel buttons on the right, and the progress fill riding on the row's +/// bottom rule. +fn render_job_row(job: TransferJob, entity: WeakEntity) -> AnyElement { + let (icon_path, kind_color) = kind_icon(job.kind); + let paused = job.control.is_paused(); + let cancelled = job.control.is_cancelled(); + let (done, total) = job.control.progress(); + let ratio = if total == 0 { + 0.0 + } else { + (done as f64 / total as f64).clamp(0.0, 1.0) + }; + + // What the row says under the file name. Cancelled wins over paused so a + // paused-then-cancelled job reads as "cancelling", not "paused". + let state_label = if cancelled { + t!("sftp.transfer_cancelling").to_string() + } else if paused { + t!("sftp.transfer_paused").to_string() + } else { + stage_label(job.control.stage()) + }; + let percent_label = if total > 0 { + format!( + "{} · {}%", + crate::layouts::toolbar::format_byte_ratio(done, total), + (ratio * 100.0).round() as u32 + ) + } else { + String::new() + }; + + div() + .relative() + .h(px(JOB_ROW_HEIGHT)) + .px_3() + .border_b_1() + .border_color(rgb(border())) + .flex() + .flex_col() + .justify_center() + .child( + div() + .flex() + .flex_row() + .items_center() + .gap_2() + .child( + svg() + .path(icon_path) + .size(px(14.0)) + .flex_shrink_0() + .text_color(rgb(kind_color)), + ) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .gap_0p5() + .child( + div() + .text_xs() + .text_color(rgb(text_primary())) + .whitespace_nowrap() + .overflow_hidden() + .text_ellipsis() + .child(job.label.clone()), + ) + .child( + div() + .text_xs() + .text_color(rgb(if paused { term_yellow() } else { text_muted() })) + .child(if percent_label.is_empty() { + state_label + } else { + format!("{state_label} · {percent_label}") + }), + ), + ) + // Pause / resume — hidden once cancelled (the transfer is + // already on its way out). + .when(!cancelled, |el| { + let control = job.control.clone(); + let entity = entity.clone(); + el.child(action_button( + format!("sftp-job-pause-{}", job.id), + if paused { + "icons/play.svg" + } else { + "icons/pause.svg" + }, + if paused { term_yellow() } else { text_muted() }, + move |_e, _w, cx| { + control.toggle_pause(); + let _ = entity.update(cx, |_, cx| cx.notify()); + }, + )) + }) + .when(!cancelled, |el| { + let control = job.control.clone(); + let entity = entity.clone(); + el.child(action_button( + format!("sftp-job-cancel-{}", job.id), + "icons/close.svg", + text_muted(), + move |_e, _w, cx| { + control.cancel(); + let _ = entity.update(cx, |_, cx| cx.notify()); + }, + )) + }), + ) + // Progress rides *on* the row's bottom rule: a 2px fill that grows + // from the left edge, flush with the row's full width. The 1px + // `border_b` underneath acts as the empty track, so there is no + // separate bar geometry to align. + .child( + div() + .absolute() + .left_0() + // `-1px` so the 2px fill sits *on* the 1px bottom rule + // (0 would place it just above it, leaving the muted line + // visible underneath). + .bottom(px(-1.0)) + .h(px(2.0)) + .w(DefiniteLength::Fraction(ratio as f32)) + .bg(rgb(if cancelled { + term_red() + } else if paused { + term_yellow() + } else { + kind_color + })), + ) + .into_any_element() +} + +/// Small ghost icon button used by job rows. Sized for a popover (18px), not +/// the 24px toolbar variant. +fn action_button( + id: String, + icon: &'static str, + color: u32, + on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static, +) -> AnyElement { + let btn_id = ElementId::Name(id.into()); + div() + .id(btn_id.clone()) + .flex() + .items_center() + .justify_center() + .size(px(18.0)) + .flex_shrink_0() + .rounded(RADIUS_SM) + .cursor_pointer() + .bg(rgba(0x00000000)) + .with_transition(btn_id) + .transition_on_hover(duration_fast(), EASE_STANDARD, |hovered, el| { + if *hovered { + el.bg(rgb(surface_hover())) + } else { + el.bg(rgba(0x00000000)) + } + }) + .on_click(on_click) + .child(svg().path(icon).size(px(12.0)).text_color(rgb(color))) + .into_any_element() +} + +fn render_history_row(idx: usize, record: TransferRecord) -> impl IntoElement { + let (icon_path, kind_color) = kind_icon(record.kind); + // Status is conveyed by icon + color only, so a mixed-locale / narrow + // panel stays readable and the row doesn't spend width on a word. + let (status_icon, status_color) = if record.success { + ("icons/check.svg", term_green()) + } else { + ("icons/close.svg", term_red()) + }; + let message = crate::layouts::toolbar::truncate_path_middle(&record.message, 44); + let time_label = format_local_time(record.finished_at); + + div() + .id(ElementId::Name(format!("history-row-{}", idx).into())) + .h(px(RECORD_ROW_HEIGHT)) + .flex() + .flex_row() + .items_center() + .gap_2() + .px_3() + .border_b_1() + .border_color(rgb(border())) + // Leading affordance: direction icon only (no "Download" / "Upload" + // label) so the eye lands on the file name. + .child( + svg() + .path(icon_path) + .size(px(14.0)) + .flex_shrink_0() + .text_color(rgb(kind_color)), + ) + .child( + div() + .text_xs() + .text_color(rgb(text_muted())) + .min_w_0() + .flex_1() + .truncate() + .child(message), + ) + .child( + div() + .text_xs() + .flex_shrink_0() + .text_color(rgb(text_muted())) + .child(time_label), + ) + // Trailing status: check / cross icon instead of "Success" / "Failed". + .child( + svg() + .path(status_icon) + .size(px(13.0)) + .flex_shrink_0() + .text_color(rgb(status_color)), + ) +} + +fn kind_icon(kind: SftpTransferKind) -> (&'static str, u32) { + match kind { + SftpTransferKind::Download => { + ("icons/terminal-toolbar/arrow-down-to-line.svg", term_blue()) + } + SftpTransferKind::Upload => ("icons/terminal-toolbar/arrow-up-to-line.svg", term_green()), + SftpTransferKind::Rename => ("icons/terminal-toolbar/edit.svg", term_yellow()), + SftpTransferKind::Edit => ("icons/terminal-toolbar/arrow-up-to-line.svg", term_green()), + SftpTransferKind::Delete => ("icons/terminal-toolbar/arrow-up-to-line.svg", term_red()), + SftpTransferKind::Mkdir => ("icons/terminal-toolbar/arrow-up-to-line.svg", term_yellow()), + } +} + +/// Human-readable label for the control's stage id. +fn stage_label(stage: u8) -> String { + match stage { + crabport_sftp::STAGE_COMPRESS => t!("sftp.progress.compress").to_string(), + crabport_sftp::STAGE_TRANSFER => t!("sftp.progress.transfer").to_string(), + crabport_sftp::STAGE_DECOMPRESS => t!("sftp.progress.decompress").to_string(), + crabport_sftp::STAGE_CLEANUP => t!("sftp.progress.cleanup").to_string(), + // `STAGE_NONE` and anything unknown: the transfer is queued but hasn't + // reported a stage yet. + _ => t!("sftp.transfer_waiting").to_string(), + } +} + +fn now_secs() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or(0) +} + +/// Human-readable subject for a job row: the path's final component, so the +/// panel reads as a list of file *names* rather than full paths. Falls back +/// to the whole path when it has no file name (e.g. a bare `/`). +/// +/// Public so the surfaces that start transfers (the SFTP tab's panel +/// callbacks and the terminal tab's right-hand SFTP panel) label jobs the +/// same way. +pub fn transfer_label(path: &str) -> String { + std::path::Path::new(path) + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_else(|| path.to_string()) +} + +/// Format a Unix timestamp as a short local-time string (HH:MM:SS). +/// Uses `chrono` so the user's timezone + DST are respected. +fn format_local_time(secs: i64) -> String { + use chrono::TimeZone; + if secs <= 0 { + return "--:--:--".to_string(); + } + match chrono::Local.timestamp_opt(secs, 0) { + chrono::LocalResult::Single(t) => t.format("%H:%M:%S").to_string(), + _ => "--:--:--".to_string(), + } +} diff --git a/crabport-ui/src/views/sftp/transfer_history.rs b/crabport-ui/src/views/sftp/transfer_history.rs deleted file mode 100644 index 70fb7d1..0000000 --- a/crabport-ui/src/views/sftp/transfer_history.rs +++ /dev/null @@ -1,384 +0,0 @@ -//! Toggleable SFTP transfer-history popover. -//! -//! Like the global tooltip / context-menu controllers, this is an -//! `Entity` held by the app root and rendered as a top-level overlay -//! (not inside the `SftpTabView` view tree). The SFTP toolbar's history -//! button calls `toggle` on click; the popover anchors to the button's -//! position and shows the most recent completed transfers. -//! -//! Records are pushed by `SftpTabView` via [`TransferHistoryController::push`] -//! whenever an `on_sftp_transfer_finished` callback fires. They live in -//! memory only — see `TransferRecord` for details. - -use gpui::prelude::FluentBuilder; -use gpui::*; -use gpui_animation::animation::TransitionExt; -use gpui_component::scroll::ScrollableElement as _; -use rust_i18n::t; - -use crate::color::*; -use crate::motion::{EASE_STANDARD, RADIUS_MD, duration_base}; -use crabport_terminal::terminal::SftpTransferKind; - -/// Maximum records kept in memory. Older entries are dropped (FIFO). -const MAX_RECORDS: usize = 200; -/// Pop-in/out animation duration. Must match the `transition_when_else` -/// duration in `render_transfer_history` so the dismiss timer clears -/// state at the right moment. -const DISMISS_MS: u64 = 180; - -/// A completed SFTP transfer, captured for the history popover. -/// -/// Records are kept in-memory only (one `Vec` per controller), most- -/// recent-first. We don't persist them to the Store — the history is -/// meant as a "what just happened" aid within a session, not a -/// permanent log. -#[derive(Clone, Debug)] -pub struct TransferRecord { - pub kind: SftpTransferKind, - pub success: bool, - /// The backend-supplied detail string — typically the path of the - /// file that was processed. Kept verbatim so the user sees exactly - /// what the backend reported. - pub message: String, - /// When the transfer finished (local Unix timestamp), for display. - pub finished_at: i64, -} - -pub struct TransferHistoryController { - /// Most-recent-first. Capped at [`MAX_RECORDS`]. - records: Vec, - /// Where to anchor the popover (button's window-relative position). - anchor: Option>, - open: bool, - /// Monotonic counter bumped on every show/hide so stale dismiss - /// tasks don't clobber a freshly-shown popover (mirrors the - /// context-menu controller's `generation` pattern). - generation: u64, -} - -impl TransferHistoryController { - pub fn new() -> Self { - Self { - records: Vec::new(), - anchor: None, - open: false, - generation: 0, - } - } - - /// Append a record. Most-recent-first ordering; oldest entries are - /// evicted past `MAX_RECORDS`. If the popover is currently open, it - /// re-renders to show the new entry. - pub fn push(&mut self, record: TransferRecord, cx: &mut Context) { - self.records.insert(0, record); - if self.records.len() > MAX_RECORDS { - self.records.truncate(MAX_RECORDS); - } - cx.notify(); - } - - /// Toggle the popover open/closed at `anchor` (window-relative). - pub fn toggle(&mut self, anchor: Point, cx: &mut Context) { - if self.open { - self.hide(cx); - } else { - self.show(anchor, cx); - } - } - - /// Show the popover at `anchor`. Replaces any currently-showing - /// popover (re-anchors it). - pub fn show(&mut self, anchor: Point, cx: &mut Context) { - self.generation = self.generation.wrapping_add(1); - self.anchor = Some(anchor); - self.open = true; - // Reset the animation so a re-show after a dismiss animates in - // from scratch (mirrors the context-menu controller). - gpui_animation::reset_transition(&ElementId::Name("sftp-transfer-history-popover".into())); - cx.notify(); - } - - /// Begin the dismiss animation. After [`DISMISS_MS`] the state is - /// dropped so the popover no longer captures renders. - pub fn hide(&mut self, cx: &mut Context) { - if !self.open { - return; - } - self.generation = self.generation.wrapping_add(1); - let dismiss_gen = self.generation; - self.open = false; - cx.notify(); - - let entity = cx.entity().downgrade(); - cx.spawn(async move |_this, cx| { - smol::Timer::after(std::time::Duration::from_millis(DISMISS_MS)).await; - let _ = entity.update(cx, |this, cx| { - if this.generation == dismiss_gen { - this.anchor = None; - cx.notify(); - } - }); - }) - .detach(); - } - - pub fn is_open(&self) -> bool { - self.open - } - - /// Number of records currently held (for badge display, etc.). - pub fn len(&self) -> usize { - self.records.len() - } -} - -impl Render for TransferHistoryController { - fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { - let Some(anchor) = self.anchor else { - return div().into_any_element(); - }; - let open = self.open; - let records = self.records.clone(); - let viewport = _window.viewport_size(); - let entity = cx.entity().downgrade(); - - render_transfer_history(anchor, open, records, viewport, entity).into_any_element() - } -} - -/// Render the popover. Anchored to `anchor` (the toggle button's -/// position), clamped to stay inside the window. -fn render_transfer_history( - anchor: Point, - open: bool, - records: Vec, - viewport: Size, - entity: WeakEntity, -) -> impl IntoElement { - let overlay_id = ElementId::Name("sftp-transfer-history-overlay".into()); - let popover_id = ElementId::Name("sftp-transfer-history-popover".into()); - - // Clamp the popover so it stays inside the window. Fixed height - // so the popover doesn't resize as records come in — the list - // inside scrolls instead. Width is fixed at 360px. - const POPOVER_W: f32 = 360.0; - const POPOVER_H: f32 = 240.0; - let mut x = f32::from(anchor.x); - let mut y = f32::from(anchor.y) + 28.0; // below the button - // Flip left: if the popover would overflow the right edge, place it - // to the left of the anchor so its right edge aligns with the button. - if x + POPOVER_W > f32::from(viewport.width) { - x = (f32::from(anchor.x) - POPOVER_W).max(0.0); - } - // Flip up: if the popover would overflow the bottom edge, place it - // above the anchor so its bottom edge aligns with the button. - if y + POPOVER_H > f32::from(viewport.height) { - y = (f32::from(anchor.y) - POPOVER_H - 4.0).max(0.0); - } - - div() - .id(overlay_id.clone()) - .absolute() - .top_0() - .left_0() - .size_full() - // Only capture clicks while open so the overlay doesn't block - // the app while animating out. - .when(open, |el| { - el.occlude().on_click(move |_e, _w, cx| { - let _ = entity.update(cx, |this, cx| this.hide(cx)); - }) - }) - .with_transition(overlay_id) - .transition_when_else( - open, - duration_base(), - EASE_STANDARD, - |el| el.bg(rgba(0x00000000)), - |el| el.bg(rgba(0x00000000)), - ) - .child( - div() - .id(popover_id.clone()) - .absolute() - .top(px(y)) - .left(px(x)) - .w(px(POPOVER_W)) - .h(px(POPOVER_H)) - .flex() - .flex_col() - .bg(rgb(bg_base())) - .border_1() - .border_color(rgb(border())) - .rounded(RADIUS_MD) - .shadow_lg() - .overflow_hidden() - .opacity(0.0) - .mt(px(-4.0)) - .with_transition(popover_id) - .transition_when_else( - open, - duration_base(), - EASE_STANDARD, - |el| el.opacity(1.0).mt_0(), - |el| el.opacity(0.0).mt(px(-4.0)), - ) - // Stop clicks on the popover from bubbling to the - // backdrop (which would dismiss it). - .when(open, |el| { - el.on_click(|_e, _w, cx| { - cx.stop_propagation(); - }) - }) - .child(render_header(records.len())) - .child(render_list(records)), - ) -} - -fn render_header(count: usize) -> impl IntoElement { - div() - .flex() - .flex_row() - .items_center() - .justify_between() - .px_3() - .py_1p5() - .border_b_1() - .border_color(rgb(border())) - .child( - div() - .text_xs() - .font_weight(FontWeight::SEMIBOLD) - .text_color(rgb(text_primary())) - .child(t!("sftp.history_title").to_string()), - ) - .child( - div() - .text_xs() - .text_color(rgb(text_muted())) - .child(format!("{}", count)), - ) -} - -fn render_list(records: Vec) -> impl IntoElement { - div() - .flex_1() - .min_h_0() - .overflow_y_scrollbar() - .when(records.is_empty(), |el| { - el.child( - div() - .h(px(80.0)) - .flex() - .items_center() - .justify_center() - .text_xs() - .text_color(rgb(text_muted())) - .child(t!("sftp.history_empty").to_string()), - ) - }) - .children( - records - .into_iter() - .enumerate() - .map(|(i, r)| render_history_row(i, r)), - ) -} - -fn render_history_row(idx: usize, record: TransferRecord) -> impl IntoElement { - let (icon_path, kind_color) = match record.kind { - SftpTransferKind::Download => { - ("icons/terminal-toolbar/arrow-down-to-line.svg", term_blue()) - } - SftpTransferKind::Upload => ("icons/terminal-toolbar/arrow-up-to-line.svg", term_green()), - SftpTransferKind::Rename => ("icons/terminal-toolbar/edit.svg", term_yellow()), - SftpTransferKind::Edit => ("icons/terminal-toolbar/arrow-up-to-line.svg", term_green()), - SftpTransferKind::Delete => ("icons/terminal-toolbar/arrow-up-to-line.svg", term_red()), - SftpTransferKind::Mkdir => ("icons/terminal-toolbar/arrow-up-to-line.svg", term_yellow()), - }; - let status_color = if record.success { - term_green() - } else { - term_red() - }; - let status_label = if record.success { - t!("sftp.history_status_success").to_string() - } else { - t!("sftp.history_status_failed").to_string() - }; - let message = crate::layouts::toolbar::truncate_path_middle(&record.message, 40); - let time_label = format_local_time(record.finished_at); - - div() - .id(ElementId::Name(format!("history-row-{}", idx).into())) - .flex() - .flex_row() - .items_center() - .gap_2() - .px_3() - .py_1p5() - .border_b_1() - .border_color(rgb(border())) - .child( - svg() - .path(icon_path) - .size(px(12.0)) - .flex_shrink_0() - .text_color(rgb(kind_color)), - ) - .child( - div() - .text_xs() - .min_w(px(50.0)) - .text_color(rgb(kind_color)) - .child(kind_label(record.kind)), - ) - .child( - div() - .text_xs() - .text_color(rgb(text_muted())) - .min_w_0() - .flex_1() - .truncate() - .child(message), - ) - .child( - div() - .text_xs() - .flex_shrink_0() - .text_color(rgb(text_muted())) - .child(time_label), - ) - .child( - div() - .text_xs() - .flex_shrink_0() - .text_color(rgb(status_color)) - .child(status_label), - ) -} - -fn kind_label(kind: SftpTransferKind) -> String { - match kind { - SftpTransferKind::Download => t!("sftp.progress.download").to_string(), - SftpTransferKind::Upload => t!("sftp.progress.upload").to_string(), - SftpTransferKind::Rename => t!("sftp.rename").to_string(), - SftpTransferKind::Edit => t!("sftp.progress.upload").to_string(), - SftpTransferKind::Delete => t!("sftp.delete").to_string(), - SftpTransferKind::Mkdir => t!("sftp.mkdir").to_string(), - } -} - -/// Format a Unix timestamp as a short local-time string (HH:MM:SS). -/// Uses `chrono` so the user's timezone + DST are respected. -fn format_local_time(secs: i64) -> String { - use chrono::TimeZone; - if secs <= 0 { - return "--:--:--".to_string(); - } - match chrono::Local.timestamp_opt(secs, 0) { - chrono::LocalResult::Single(t) => t.format("%H:%M:%S").to_string(), - _ => "--:--:--".to_string(), - } -} diff --git a/crabport-ui/src/views/sftp/view.rs b/crabport-ui/src/views/sftp/view.rs index 76e6900..8ac969f 100644 --- a/crabport-ui/src/views/sftp/view.rs +++ b/crabport-ui/src/views/sftp/view.rs @@ -162,7 +162,7 @@ pub struct SftpTabView { pub(super) context_menu: Option>, pub(super) alert_controller: Option>, pub(super) tooltip: Option>, - pub(super) transfer_history: Option>, + pub(super) transfers: Option>, // --- Host selector overlay --- pub(super) host_selector: Option>, @@ -179,7 +179,7 @@ impl SftpTabView { context_menu: None, alert_controller: None, tooltip: None, - transfer_history: None, + transfers: None, host_selector: None, host_selector_open_for: None, hosts: Vec::new(), @@ -328,7 +328,7 @@ impl SftpTabView { context_menu: Entity, alert_controller: Entity, tooltip: Entity, - transfer_history: Entity, + transfers: Entity, hosts: Vec, app: Entity, window: &mut Window, @@ -380,7 +380,7 @@ impl SftpTabView { } self.hosts = hosts; self.app = Some(app); - self.transfer_history = Some(transfer_history); + self.transfers = Some(transfers); // Keep the overlay's host list in sync. if let Some(ref overlay) = self.host_selector { overlay.update(cx, |o, cx| { @@ -873,35 +873,58 @@ impl SftpTabView { // Wire callbacks for SFTP progress + transfer notifications. let app_handle = self.app.clone().map(|e| e.downgrade()); + let transfers_for_progress = self.transfers.clone(); terminal_view.update(cx, |view, _cx| { view.set_on_sftp_progress_changed(move |cx| { if let Some(ref ah) = app_handle { let _ = ah.update(cx, |_, cx| cx.notify()); } + // Repaint the open transfer panel so its job rows animate with + // the backend's byte counters (the panel reads the control + // directly rather than the broadcast snapshot). + if let Some(ref tc) = transfers_for_progress { + let _ = tc.update(cx, |c, cx| { + if c.is_open() { + cx.notify(); + } + }); + } }); }); let app_handle = self.app.clone().map(|e| e.downgrade()); - let transfer_history_ctrl = self.transfer_history.clone(); + let transfers_ctrl = self.transfers.clone(); terminal_view.update(cx, |view, _cx| { view.set_on_sftp_transfer_finished(move |kind, success, message, cx| { - // Append to the global transfer-history controller so - // the popover can display it. Done before the early-return - // arms below (Rename/Edit on success skip the toast but - // should still be logged in history). - let record = crate::views::sftp::TransferRecord { - kind, - success, - message: message.clone(), - finished_at: std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_secs() as i64) - .unwrap_or(0), - }; - if let Some(ref ctrl) = transfer_history_ctrl { - let _ = ctrl.update(cx, |c, cx| { - c.push(record, cx); - }); + // Repaint the panel so a finished job is retired into history + // on the next render (its control carries the outcome). Also + // handled by the progress callback at the end of a transfer, + // but a cancelled transfer may never emit a final progress + // event. + if let Some(ref ctrl) = transfers_ctrl { + let _ = ctrl.update(cx, |_, cx| cx.notify()); + } + // Uploads and downloads are already recorded by the transfer + // center when it retires their job (it owns the control and + // therefore the outcome). Pushing them here too would + // duplicate every row. The remaining kinds don't run as jobs + // (`Rename` / `Edit` / `Delete` / `Mkdir`), so record them + // directly. + if !matches!(kind, SftpTransferKind::Upload | SftpTransferKind::Download) { + let record = crate::views::sftp::TransferRecord { + kind, + success, + message: message.clone(), + finished_at: std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or(0), + }; + if let Some(ref ctrl) = transfers_ctrl { + let _ = ctrl.update(cx, |c, cx| { + c.push(record, cx); + }); + } } let Some(ref ah) = app_handle else { return }; let _ = ah.update(cx, |app, cx| { @@ -992,7 +1015,10 @@ impl SftpTabView { }); }); - // Wire SFTP callbacks for this panel. + // Wire SFTP callbacks for this panel. Downloads / uploads are + // registered with the global transfer center first, so the panel can + // show them immediately and offer pause / cancel; the backend then + // runs the transfer against the job's control handle. let term = terminal_view.clone(); let on_navigate: Rc = Rc::new({ let term = term.clone(); @@ -1004,25 +1030,55 @@ impl SftpTabView { }); let on_download: Rc = Rc::new({ let term = term.clone(); + let transfers = self.transfers.clone(); move |remote_path: String, local_path: String, cx: &mut App| { + let control = crabport_sftp::TransferControl::new(); + let label = crate::views::sftp::transfer_label(&remote_path); + if let Some(ref tc) = transfers { + let job_control = control.clone(); + let _ = tc.update(cx, |center, cx| { + center.start_job(SftpTransferKind::Download, label, job_control, cx); + }); + } term.read_with(cx, |view, _cx| { - view.sftp_download(&remote_path, &local_path); + view.sftp_download_controlled(&remote_path, &local_path, control); }); } }); let on_upload: Rc = Rc::new({ let term = term.clone(); + let transfers = self.transfers.clone(); move |local_path: String, remote_path: String, cx: &mut App| { + let control = crabport_sftp::TransferControl::new(); + let label = crate::views::sftp::transfer_label(&local_path); + if let Some(ref tc) = transfers { + let job_control = control.clone(); + let _ = tc.update(cx, |center, cx| { + center.start_job(SftpTransferKind::Upload, label, job_control, cx); + }); + } term.read_with(cx, |view, _cx| { - view.sftp_upload(&local_path, &remote_path); + view.sftp_upload_controlled(&local_path, &remote_path, control); }); } }); let on_upload_batch: Rc, &mut App)> = Rc::new({ let term = term.clone(); + let transfers = self.transfers.clone(); move |items: Vec<(String, String)>, cx: &mut App| { + if items.is_empty() { + return; + } + let control = crabport_sftp::TransferControl::new(); + let label = t!("sftp.upload_n", count = items.len()).to_string(); + if let Some(ref tc) = transfers { + let job_control = control.clone(); + let _ = tc.update(cx, |center, cx| { + center.start_job(SftpTransferKind::Upload, label, job_control, cx); + }); + } term.read_with(cx, |view, _cx| { - view.sftp_upload_batch(&items); + view.sftp_upload_batch_controlled(&items, control); }); } }); diff --git a/crabport-ui/src/views/terminal.rs b/crabport-ui/src/views/terminal.rs index c5a7707..4a2dc5f 100644 --- a/crabport-ui/src/views/terminal.rs +++ b/crabport-ui/src/views/terminal.rs @@ -1131,6 +1131,41 @@ impl TerminalView { self.backend.sftp_upload_batch(items); } + /// Controlled variants: the transfer observes `control`, so the transfer + /// panel can pause / resume / cancel it and read live byte progress. + /// + /// See [`crabport_sftp::TransferControl`] and + /// [`crabport_terminal::terminal::CrabPortTerminal::sftp_download_controlled`]. + pub fn sftp_download_controlled( + &self, + remote_path: &str, + local_path: &str, + control: std::sync::Arc, + ) { + self.session + .sftp_download_controlled(remote_path, local_path, control); + } + + /// See [`Self::sftp_download_controlled`]. + pub fn sftp_upload_controlled( + &self, + local_path: &str, + remote_path: &str, + control: std::sync::Arc, + ) { + self.session + .sftp_upload_controlled(local_path, remote_path, control); + } + + /// See [`Self::sftp_download_controlled`]. + pub fn sftp_upload_batch_controlled( + &self, + items: &[(String, String)], + control: std::sync::Arc, + ) { + self.session.sftp_upload_batch_controlled(items, control); + } + /// Snapshot of this session's command history, most-recent-first. /// Returns an empty vec for local terminals or sessions without a /// backend that tracks history. diff --git a/crabport-ui/src/views/terminal/toolbar.rs b/crabport-ui/src/views/terminal/toolbar.rs index 315272f..0c0c66f 100644 --- a/crabport-ui/src/views/terminal/toolbar.rs +++ b/crabport-ui/src/views/terminal/toolbar.rs @@ -101,6 +101,10 @@ pub fn render_terminal_toolbar( input: TerminalToolbarInput, context_menu: Option>, trailing: Vec, + // Invoked when the user clicks the in-flight transfer chip. The caller + // opens the transfer panel anchored at the click position. `None` keeps + // the chip read-only. + on_progress_click: Option, &mut App)>>, on_toggle: impl Fn(&str, &mut App) + 'static, ) -> impl IntoElement { // Read the current per-slot visibility from config so the ctxmenu @@ -143,6 +147,7 @@ pub fn render_terminal_toolbar( props = props.slot(sftp_progress_slot( input.sftp_progress.clone(), vis.sftp_progress, + on_progress_click, )); crate::layouts::toolbar::render_toolbar(props) @@ -474,7 +479,11 @@ impl SftpProgressDisplay { } } -fn sftp_progress_slot(progress: Option, visible: bool) -> ToolbarSlot { +fn sftp_progress_slot( + progress: Option, + visible: bool, + on_click: Option, &mut App)>>, +) -> ToolbarSlot { ToolbarSlot::new( "sftp_progress", t!("toolbar.sftp_progress").to_string(), @@ -483,47 +492,53 @@ fn sftp_progress_slot(progress: Option, visible: bool) -> ToolbarS let p = progress.clone()?; let d = SftpProgressDisplay::new(&p); let bar = render_progress_bar(p.bytes, d.stage_color, "sftp-progress-bar-fill"); - Some( - div() - .flex() - .flex_row() - .items_center() - .gap_1p5() - .min_w_0() - .child( - svg() - .path(d.icon_path) - .size(px(12.0)) - .flex_shrink_0() - .text_color(rgb(d.stage_color)), - ) - .child( - div() - .text_xs() - .text_color(rgb(d.stage_color)) - .child(d.stage_label), - ) - .child( + let mut chip = div() + .id("sftp-progress-chip") + .flex() + .flex_row() + .items_center() + .gap_1p5() + .min_w_0() + // Clicking the chip expands the transfer panel, which is + // where pause / cancel live. The row is a plain div (not a + // Button) because it's built by the toolbar slot framework. + .when_some(on_click.clone(), |el, cb| { + el.cursor_pointer() + .on_click(move |e, _w, cx| cb(e.position(), cx)) + }) + .child( + svg() + .path(d.icon_path) + .size(px(12.0)) + .flex_shrink_0() + .text_color(rgb(d.stage_color)), + ) + .child( + div() + .text_xs() + .text_color(rgb(d.stage_color)) + .child(d.stage_label), + ) + .child( + div() + .text_xs() + .text_color(rgb(text_muted())) + .min_w_0() + .truncate() + .child(format!("{}: {}", d.kind_label, d.detail)), + ); + chip = chip.when_some(bar, |el, bar| { + el.child(bar).when_some(p.bytes, |el, b| { + el.child( div() .text_xs() .text_color(rgb(text_muted())) - .min_w_0() - .truncate() - .child(format!("{}: {}", d.kind_label, d.detail)), + .flex_shrink_0() + .child(format_byte_ratio(b.done, b.total)), ) - .when_some(bar, |el, bar| { - el.child(bar).when_some(p.bytes, |el, b| { - el.child( - div() - .text_xs() - .text_color(rgb(text_muted())) - .flex_shrink_0() - .child(format_byte_ratio(b.done, b.total)), - ) - }) - }) - .into_any_element(), - ) + }) + }); + Some(chip.into_any_element()) }, ) } From 49b6bc1084ac17abad5241efc8ebd0742dafe720 Mon Sep 17 00:00:00 2001 From: w33d Date: Sun, 25 Oct 2026 12:37:18 +0800 Subject: [PATCH 3/3] style(panel): flatten list chrome and loosen tunnel rows - panel_shell no longer wraps the list in its own bordered card. The panel already has a divider on the side facing the terminal and the tab strip supplies the top edge, so the third border read as a box inside a box and ate usable width. The search row is separated by a hairline instead. - Segmented control: derive the hover wash from the theme (it was a hardcoded purple-gray that ignored the active palette on Tokyo Night / custom themes) and soften the track from surface_active to surface_hover. - Tunnels panel: rows 36 -> 52px, name 12 -> 14px with a gap before the address, kind badge 16 -> 20px. Two 12px lines in 36px read as a dense wall of text in the narrow panel. - Snippets / history panel rows: 28 -> 32px to match the new shell padding, and shared row radius 4 -> 6px. --- .../src/components/segmented_control.rs | 14 ++-- .../src/views/panel/history_command_panel.rs | 2 +- crabport-ui/src/views/panel/scaffold.rs | 65 ++++++++++++------- crabport-ui/src/views/panel/snippets_panel.rs | 2 +- crabport-ui/src/views/panel/tunnels_panel.rs | 14 ++-- 5 files changed, 64 insertions(+), 33 deletions(-) diff --git a/crabport-ui/src/components/segmented_control.rs b/crabport-ui/src/components/segmented_control.rs index b065c72..b023ffe 100644 --- a/crabport-ui/src/components/segmented_control.rs +++ b/crabport-ui/src/components/segmented_control.rs @@ -198,13 +198,16 @@ impl RenderOnce for SegmentedControl { } else { inactive_color })) - .bg(rgba(0x24273a00)) + .bg(rgba(0x00000000)) .with_transition(tab_id) .transition_on_hover(duration_base(), EASE_STANDARD, move |hovered, state| { if *hovered { - state.bg(rgba(0x24273a80)) + // Theme-derived wash (was a hardcoded purple-gray that + // ignored the active palette — it looked wrong on + // Tokyo Night / custom themes). + state.bg(rgba((surface_hover() << 8) | 0x80)) } else { - state.bg(rgba(0x24273a00)) + state.bg(rgba(0x00000000)) } }) .transition_when_else( @@ -261,7 +264,10 @@ impl RenderOnce for SegmentedControl { let mut root = div() .id(self.id) - .bg(rgb(surface_active())) + // Softer than `surface_active`: the strip is chrome, not a control + // the user presses. The sliding `bg_base` indicator supplies the + // contrast for the selected tab. + .bg(rgb(surface_hover())) .rounded(RADIUS_MD) .p_0p5() .child(inner); diff --git a/crabport-ui/src/views/panel/history_command_panel.rs b/crabport-ui/src/views/panel/history_command_panel.rs index a5d1d0f..212c4ca 100644 --- a/crabport-ui/src/views/panel/history_command_panel.rs +++ b/crabport-ui/src/views/panel/history_command_panel.rs @@ -117,7 +117,7 @@ impl HistoryCommandPanel { /// Fixed height of each history row. The virtual list requires uniform /// item sizes. -const ROW_HEIGHT: f32 = 28.0; +const ROW_HEIGHT: f32 = 32.0; impl Render for HistoryCommandPanel { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { diff --git a/crabport-ui/src/views/panel/scaffold.rs b/crabport-ui/src/views/panel/scaffold.rs index 037552c..193ed3d 100644 --- a/crabport-ui/src/views/panel/scaffold.rs +++ b/crabport-ui/src/views/panel/scaffold.rs @@ -146,8 +146,14 @@ pub enum SearchRow { } /// The shared panel body: full-size column with the search row on top and, -/// below it, either the empty-state placeholder or the bordered list -/// container with its hover-scrollbar overlay. +/// below it, either the empty-state placeholder or the list itself. +/// +/// The list is **not** wrapped in its own bordered card. The panel already +/// has a divider on the side facing the terminal, and the tab strip above it +/// supplies the top edge; a third nested border made the panel read as a box +/// inside a box (and cost usable width on every side). Instead the search row +/// is separated by a hairline and the rows sit directly on the panel surface, +/// the way a shadcn sidebar/list reads. pub fn panel_shell( search_id: &'static str, search_input: Option>, @@ -165,9 +171,9 @@ pub fn panel_shell( .overflow_hidden() .flex() .flex_col() - .pt_1() - .px_1() - // Search input + .px_2() + // Search input, separated from the list by a hairline so the two + // regions read as one surface with a rule — not two stacked cards. .when_some(search_input, |el, input| { let field = StyledInput::new(search_id, input).xsmall().prefix( svg() @@ -175,19 +181,27 @@ pub fn panel_shell( .size(px(12.0)) .text_color(rgb(text_muted())), ); - el.child(match search_row { - SearchRow::Bare => div().mb_1().child(field), - SearchRow::WithSuffix(suffix) => div() - .mb_1() - .flex() - .flex_row() - .items_center() - .gap_1() - .child(div().flex_1().min_w_0().child(field)) - .when_some(suffix, |el, suffix| el.child(suffix)), - }) + el.child( + div() + .pt_2() + .pb_2() + .border_b_1() + .border_color(rgb(border())) + .child(match search_row { + SearchRow::Bare => field.into_any_element(), + SearchRow::WithSuffix(suffix) => div() + .flex() + .flex_row() + .items_center() + .gap_1() + .child(div().flex_1().min_w_0().child(field)) + .when_some(suffix, |el, suffix| el.child(suffix)) + .into_any_element(), + }), + ) }) - // List + scrollbar, or empty-state placeholder. + // List + scrollbar, or empty-state placeholder. The scrollbar floats + // over the list area instead of belonging to a bordered container. .when_else( is_empty, |el| { @@ -196,8 +210,17 @@ pub fn panel_shell( .flex_1() .min_h_0() .flex() + .flex_col() .items_center() .justify_center() + .gap_2() + .child( + svg() + .path("icons/folder.svg") + .size(px(16.0)) + .text_color(rgb(text_muted())) + .opacity(0.5), + ) .child( div() .text_color(rgb(text_muted())) @@ -212,11 +235,7 @@ pub fn panel_shell( .relative() .flex_1() .min_h_0() - .border_1() - .border_color(rgb(border())) - .bg(rgb(bg_tab_bar())) - .rounded(RADIUS_MD) - .overflow_hidden() + .pt_1() .child(list) .child( div() @@ -253,7 +272,7 @@ pub fn row_base(row_id: ElementId, row_height: f32) -> Stateful
{ .items_center() .gap_1p5() .px_2() - .rounded(px(4.0)) + .rounded(RADIUS_MD) } /// Wrap a row in its transition, wire hover tracking into the panel's diff --git a/crabport-ui/src/views/panel/snippets_panel.rs b/crabport-ui/src/views/panel/snippets_panel.rs index 9480e49..c78dbe4 100644 --- a/crabport-ui/src/views/panel/snippets_panel.rs +++ b/crabport-ui/src/views/panel/snippets_panel.rs @@ -116,7 +116,7 @@ impl SnippetsPanel { /// Fixed height of each snippet row. The virtual list requires uniform /// item sizes. -const ROW_HEIGHT: f32 = 28.0; +const ROW_HEIGHT: f32 = 32.0; impl Render for SnippetsPanel { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { diff --git a/crabport-ui/src/views/panel/tunnels_panel.rs b/crabport-ui/src/views/panel/tunnels_panel.rs index c44baa5..072e5e9 100644 --- a/crabport-ui/src/views/panel/tunnels_panel.rs +++ b/crabport-ui/src/views/panel/tunnels_panel.rs @@ -210,7 +210,11 @@ impl TunnelsPanel { /// Fixed height of each tunnel row. The virtual list requires uniform /// item sizes. -const ROW_HEIGHT: f32 = 36.0; +/// +/// 52px fits the two-line layout (name + address) with real breathing room. +/// The previous 36px packed two 12px lines edge to edge, which read as a +/// dense wall of text in the narrow side panel. +const ROW_HEIGHT: f32 = 52.0; impl Render for TunnelsPanel { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { @@ -414,13 +418,14 @@ impl Render for TunnelsPanel { Some(&mut view.tab_states.entry(id).or_default().hovered_row) }, ) - // Kind badge (single letter, color-coded). + // Kind badge (single letter, color-coded). Sized to + // match the taller 52px row so it doesn't look lost. .child( div() .flex() .items_center() .justify_center() - .size_4() + .size_5() .rounded(px(3.0)) .bg(rgba((kind_color << 8) | 0x22)) .text_xs() @@ -435,9 +440,10 @@ impl Render for TunnelsPanel { .min_w_0() .flex() .flex_col() + .gap_0p5() .child( div() - .text_xs() + .text_sm() .font_weight(FontWeight::SEMIBOLD) .text_color(rgb(text_primary())) .whitespace_nowrap()