Skip to content

A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.

Expand sidebar transfers with folders, retries, and local copies

RoversX23acdc2f4328
diff --git a/wezterm-gui/src/native_settings.rs b/wezterm-gui/src/native_settings.rs
index a6b81f58..e8e94ea5 100644
--- a/wezterm-gui/src/native_settings.rs
+++ b/wezterm-gui/src/native_settings.rs
@@ -291,12 +291,17 @@ pub(crate) const DEFAULT_REMOTE_SFTP_IDLE_MINUTES: u32 = 15;
#[serde(default)]
pub(crate) struct NativeWorkspaceSettings {
pub(crate) remote_sftp_idle_minutes: u32,
+ /// Where downloaded remote files land. Empty means "wherever this system
+ /// puts downloads", which is what most people want and what keeps the
+ /// setting meaningful after moving between machines.
+ pub(crate) remote_download_directory: String,
}
impl Default for NativeWorkspaceSettings {
fn default() -> Self {
Self {
remote_sftp_idle_minutes: DEFAULT_REMOTE_SFTP_IDLE_MINUTES,
+ remote_download_directory: String::new(),
}
}
}
@@ -335,6 +340,38 @@ pub(crate) fn remote_sftp_idle_minutes() -> u32 {
load().workspaces.remote_sftp_idle_minutes.clamp(1, 120)
}
+/// Where remote downloads should land, or `None` to use the system's own
+/// Downloads folder.
+///
+/// A configured path that no longer exists returns `None` rather than an
+/// error: falling back to the system folder gets the file saved, whereas
+/// failing the download over a stale setting does not.
+pub(crate) fn remote_download_directory() -> Option<PathBuf> {
+ let configured = load().workspaces.remote_download_directory;
+ let trimmed = configured.trim();
+ if trimmed.is_empty() {
+ return None;
+ }
+ let path = PathBuf::from(trimmed);
+ path.is_dir().then_some(path)
+}
+
+/// The folder downloads will actually use, for display and for saving into.
+pub(crate) fn effective_remote_download_directory() -> Option<PathBuf> {
+ remote_download_directory().or_else(|| {
+ dirs_next::download_dir()
+ .or_else(|| dirs_next::home_dir().map(|home| home.join("Downloads")))
+ })
+}
+
+pub(crate) fn set_remote_download_directory(path: Option<PathBuf>) -> anyhow::Result<()> {
+ let mut settings = load();
+ settings.workspaces.remote_download_directory = path
+ .map(|path| path.to_string_lossy().to_string())
+ .unwrap_or_default();
+ save(&settings)
+}
+
pub(crate) fn settings_path() -> PathBuf {
config::HOME_DIR
.join(".config")
@@ -672,6 +709,29 @@ mod tests {
assert_eq!(settings.onboarding.seen_version, ONBOARDING_VERSION);
}
+ #[test]
+ fn an_unset_download_directory_defers_to_the_system() {
+ let settings: ThinkTermNativeSettings = serde_json::from_str(r#"{"version":1}"#).unwrap();
+ assert_eq!(settings.workspaces.remote_download_directory, "");
+ }
+
+ /// A folder that has since been deleted or unmounted must not fail every
+ /// download; falling back to the system folder still saves the file.
+ #[test]
+ fn a_missing_download_directory_is_treated_as_unset() {
+ let dir = tempfile::tempdir().unwrap();
+ let gone = dir.path().join("no-such-folder");
+ assert!(!gone.is_dir());
+ assert_eq!(gone.is_dir().then_some(gone.clone()), None);
+
+ // An existing folder is used as given.
+ let present = dir.path().to_path_buf();
+ assert_eq!(
+ present.is_dir().then_some(present.clone()),
+ Some(present.clone())
+ );
+ }
+
#[test]
fn older_settings_default_remote_sftp_idle_timeout() {
let settings: ThinkTermNativeSettings = serde_json::from_str(r#"{"version":1}"#).unwrap();
diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rs
index 915b927a..e7dc611d 100644
--- a/wezterm-gui/src/settings_window.rs
+++ b/wezterm-gui/src/settings_window.rs
@@ -27,10 +27,10 @@ use wezterm_font::{FontConfiguration, LoadedFont};
use window::bitmaps::atlas::OutOfTextureSpace;
use window::color::LinearRgba;
use window::{
- Appearance, Clipboard, Connection, ConnectionOps, Dimensions, IntegratedTitleButton,
- IntegratedTitleButtonStyle, KeyCode, KeyEvent, Modifiers, MouseButtons, MouseCursor,
- MouseEvent, MouseEventKind, MousePress, RequestedWindowGeometry, Window, WindowDecorations,
- WindowEvent, WindowOps, WindowState,
+ Appearance, Clipboard, Connection, ConnectionOps, Dimensions, FolderPickerOptions,
+ IntegratedTitleButton, IntegratedTitleButtonStyle, KeyCode, KeyEvent, Modifiers, MouseButtons,
+ MouseCursor, MouseEvent, MouseEventKind, MousePress, RequestedWindowGeometry, Window,
+ WindowDecorations, WindowEvent, WindowOps, WindowState,
};
use crate::native_settings::{
@@ -348,6 +348,8 @@ enum SettingsAction {
DecreaseRemoteSftpIdle,
IncreaseRemoteSftpIdle,
ResetRemoteSftpIdle,
+ ChooseRemoteDownloadDirectory,
+ ResetRemoteDownloadDirectory,
OpenBottomQuotesJson,
ResetBottomQuotesJson,
SearchInput,
@@ -2229,6 +2231,71 @@ impl SettingsWindow {
}
}
+ /// What the download row shows: the chosen folder, or where the system
+ /// would put it, so the row never reads as "unset" when it is in fact
+ /// working.
+ fn remote_download_directory_label(&self) -> String {
+ let configured = self
+ .native_settings
+ .workspaces
+ .remote_download_directory
+ .trim();
+ if !configured.is_empty() {
+ return configured.to_string();
+ }
+ match crate::native_settings::effective_remote_download_directory() {
+ Some(path) => format!("{} (system default)", path.display()),
+ None => "No Downloads folder found".to_string(),
+ }
+ }
+
+ fn choose_remote_download_directory(&mut self) {
+ self.ui.open_dropdown = None;
+ let Some(window) = self.window.clone() else {
+ return;
+ };
+ let instance_id = self.instance_id;
+ let notify = window.clone();
+ window.pick_folder_async_with_options(
+ FolderPickerOptions {
+ title: "Choose a download folder".to_string(),
+ prompt: "Choose".to_string(),
+ },
+ Box::new(move |path| {
+ // Cancelling the picker must leave the setting alone, so only
+ // a real selection reaches the store.
+ let Some(path) = path else {
+ return;
+ };
+ promise::spawn::spawn_into_main_thread(async move {
+ if let Some(settings) = settings_window_for_instance(instance_id) {
+ settings
+ .borrow_mut()
+ .set_remote_download_directory(Some(path));
+ notify.invalidate();
+ }
+ })
+ .detach();
+ }),
+ );
+ }
+
+ fn set_remote_download_directory(&mut self, path: Option<PathBuf>) {
+ self.ui.open_dropdown = None;
+ match crate::native_settings::set_remote_download_directory(path) {
+ Ok(()) => {
+ self.native_settings = crate::native_settings::load();
+ self.status = format!(
+ "Downloads are saved to {}",
+ self.remote_download_directory_label()
+ );
+ }
+ Err(err) => {
+ self.status = format!("Unable to save the download folder: {err:#}");
+ }
+ }
+ }
+
fn format_bottom_quote_interval(minutes: u32) -> String {
if minutes < 60 {
format!("{minutes} min")
@@ -2770,6 +2837,12 @@ impl SettingsWindow {
SettingsAction::DecreaseRemoteSftpIdle => self.step_remote_sftp_idle(-5),
SettingsAction::IncreaseRemoteSftpIdle => self.step_remote_sftp_idle(5),
SettingsAction::ResetRemoteSftpIdle => self.reset_remote_sftp_idle(),
+ SettingsAction::ChooseRemoteDownloadDirectory => {
+ self.choose_remote_download_directory()
+ }
+ SettingsAction::ResetRemoteDownloadDirectory => {
+ self.set_remote_download_directory(None)
+ }
SettingsAction::OpenBottomQuotesJson => {
self.ui.open_dropdown = None;
match crate::bottom_quotes::ensure_quotes_file() {
@@ -3916,7 +3989,8 @@ impl SettingsWindow {
let ui_font = Rc::clone(&self.ui_font);
let scroll = self.ui.content_scroll.offset;
let section_y = self.ui_px(CONTENT_SECTION_Y) - scroll;
- let row_count = 1;
+ // Idle timeout, download folder, and the reset beside it.
+ let row_count = 3;
let (card_y, first_row_y) = self.settings_card_geometry(section_y, row_count);
let card_height = self.settings_card_height(row_count);
self.ui.content_scroll.set_extents(
@@ -3952,6 +4026,31 @@ impl SettingsWindow {
SettingsAction::DecreaseRemoteSftpIdle,
SettingsAction::IncreaseRemoteSftpIdle,
false,
+ )?;
+
+ let row_step = self.settings_row_step();
+ let download_label = self.remote_download_directory_label();
+ self.paint_action_setting_row(
+ layers,
+ row_x,
+ first_row_y + row_step,
+ row_width,
+ "Download Folder",
+ &download_label,
+ "Choose...",
+ SettingsAction::ChooseRemoteDownloadDirectory,
+ true,
+ )?;
+ self.paint_action_setting_row(
+ layers,
+ row_x,
+ first_row_y + row_step * 2.0,
+ row_width,
+ "Use the System Downloads Folder",
+ "Clears the chosen folder so downloads follow this computer's own setting.",
+ "Reset",
+ SettingsAction::ResetRemoteDownloadDirectory,
+ true,
)
}
diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs
index 92bdbad0..63b8f53c 100644
--- a/wezterm-gui/src/termwindow/mod.rs
+++ b/wezterm-gui/src/termwindow/mod.rs
@@ -103,6 +103,7 @@ pub mod resize;
mod selection;
pub mod spawn;
pub mod ssh_hosts_view;
+pub(crate) mod transfer_walk;
pub mod ui;
pub mod webgpu;
@@ -298,6 +299,11 @@ pub(crate) enum ContextMenuApplicationAction {
ToggleWorkspaceStatusFilter(crate::workspace_threads::WorkspaceThreadWorkStatus),
/// Fetch a file from the remote Files panel into the Downloads folder.
DownloadRemoteFile(remote_files::RemotePath),
+ /// Copy the remote preview's selected text, or the whole buffer.
+ CopyRemotePreviewSelection,
+ CopyRemotePreviewAll,
+ /// Answer to "these files already exist" for a queued local copy.
+ ResolveLocalCopyConflict(transfer_walk::ConflictChoice),
}
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -595,6 +601,22 @@ struct FileDragState {
active: bool,
}
+/// A planned local copy held back until the user says what to do about files
+/// that already exist at the destination.
+pub(crate) struct PendingLocalCopy {
+ pub plans: Vec<(PathBuf, transfer_walk::TransferPlan)>,
+ pub directory: PathBuf,
+ /// Destination-relative paths that already exist.
+ pub conflicts: std::collections::HashSet<PathBuf>,
+ /// Where the drop landed, so the prompt appears there rather than at some
+ /// default corner — the walk is asynchronous, so the pointer has moved on
+ /// by the time we can ask.
+ pub anchor: ::window::Point,
+ /// What the walk left out, carried through so the finished row can say so
+ /// rather than reporting a clean success over silently omitted data.
+ pub note: Option<String>,
+}
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PaneDropZone {
Center,
@@ -1395,6 +1417,16 @@ pub struct TermWindow {
/// The directory a file drag is currently hovering over, so the row can be
/// highlighted and the drop knows where it would land.
right_sidebar_remote_drop_target: Option<remote_files::RemotePath>,
+ right_sidebar_local_drop_target: Option<PathBuf>,
+ /// A local copy waiting on the user's answer about existing files.
+ pending_local_copy: Option<PendingLocalCopy>,
+ /// Bumped by every drop. A preflight walk that comes back carrying an old
+ /// value has been superseded — two walks can finish out of order, and the
+ /// slower, older one must not replace the newer prompt.
+ local_copy_generation: u64,
+ /// How many destinations clashed, kept separately so the prompt can be
+ /// worded without borrowing the queued plan.
+ pending_local_copy_conflict_count: usize,
right_sidebar_remote_file_tree_scroll_offset: f32,
// Bumped to invalidate a pending periodic-rescan timer tick.
right_sidebar_file_rescan_token: u64,
@@ -2045,6 +2077,10 @@ impl TermWindow {
right_sidebar_remote_transfers: Vec::new(),
right_sidebar_remote_transfer_next_id: 0,
right_sidebar_remote_drop_target: None,
+ right_sidebar_local_drop_target: None,
+ pending_local_copy: None,
+ local_copy_generation: 0,
+ pending_local_copy_conflict_count: 0,
right_sidebar_remote_file_tree_scroll_offset: 0.0,
right_sidebar_file_rescan_token: 0,
right_sidebar_file_refreshing: false,
@@ -2443,11 +2479,17 @@ impl TermWindow {
.detach();
return Ok(true);
}
- // Aimed at the remote Files tree: upload rather than paste the
- // local paths into a shell that cannot see them.
+ // Aimed at the Files tree: transfer rather than paste the
+ // paths into a shell. Remote uploads over SFTP, local copies
+ // straight into the hovered directory.
if self.upload_dropped_files_to_remote(&paths, coords) {
return Ok(true);
}
+ // The walk runs on a worker, so any conflict prompt is raised
+ // when it comes back rather than here.
+ if self.copy_dropped_files_into_local_panel(&paths, coords) {
+ return Ok(true);
+ }
let pane = match self.get_active_pane_or_overlay() {
Some(pane) => pane,
None => return Ok(true),
@@ -2467,10 +2509,12 @@ impl TermWindow {
}
WindowEvent::DraggedFile { coords, .. } => {
self.update_right_sidebar_remote_drop_target(coords);
+ self.update_right_sidebar_local_drop_target(coords);
Ok(true)
}
WindowEvent::DragLeave => {
self.clear_right_sidebar_remote_drop_target();
+ self.clear_right_sidebar_local_drop_target();
Ok(true)
}
}
diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rs
index ba67bb16..e707d940 100644
--- a/wezterm-gui/src/termwindow/mouseevent.rs
+++ b/wezterm-gui/src/termwindow/mouseevent.rs
@@ -3350,9 +3350,15 @@ impl super::TermWindow {
self.dragging.replace((item, event));
context.invalidate();
}
+ // A remote preview has no local file to hand to another
+ // application, so "Open With" is meaningless there; it gets its
+ // own menu of things that do apply instead.
WMEK::Press(MousePress::Right)
- if self.right_sidebar_remote_files.selected.is_none() =>
+ if self.right_sidebar_remote_files.selected.is_some() =>
{
+ self.show_right_sidebar_remote_file_preview_context_menu(context, event.coords);
+ }
+ WMEK::Press(MousePress::Right) => {
self.show_right_sidebar_file_open_with_menu(context, event.coords);
}
_ => {}
diff --git a/wezterm-gui/src/termwindow/remote_files.rs b/wezterm-gui/src/termwindow/remote_files.rs
index 47de3847..076771a9 100644
--- a/wezterm-gui/src/termwindow/remote_files.rs
+++ b/wezterm-gui/src/termwindow/remote_files.rs
@@ -235,10 +235,17 @@ const TRANSFER_TOTAL_UNKNOWN: u64 = u64::MAX;
/// Shared, lock-free view of one transfer: the worker publishes progress, the
/// UI reads it every paint, and either side can ask to stop.
+///
+/// Tracks two scales at once. A single file reports bytes; a folder reports
+/// items, because a thousand-file tree's byte total says nothing useful about
+/// how far along it looks, and because the per-file byte counter would have to
+/// be reset constantly. Whichever scale is populated is the one the UI shows.
#[derive(Clone, Debug)]
pub(crate) struct RemoteTransferProgress {
transferred: Arc<AtomicU64>,
total: Arc<AtomicU64>,
+ items_done: Arc<AtomicU64>,
+ items_total: Arc<AtomicU64>,
cancel: Arc<AtomicBool>,
}
@@ -247,6 +254,8 @@ impl Default for RemoteTransferProgress {
Self {
transferred: Arc::new(AtomicU64::new(0)),
total: Arc::new(AtomicU64::new(TRANSFER_TOTAL_UNKNOWN)),
+ items_done: Arc::new(AtomicU64::new(0)),
+ items_total: Arc::new(AtomicU64::new(TRANSFER_TOTAL_UNKNOWN)),
cancel: Arc::new(AtomicBool::new(false)),
}
}
@@ -274,6 +283,31 @@ impl RemoteTransferProgress {
self.transferred.fetch_add(bytes, Ordering::Relaxed);
}
+ pub(crate) fn items(&self) -> Option<(u64, u64)> {
+ match self.items_total.load(Ordering::Relaxed) {
+ TRANSFER_TOTAL_UNKNOWN => None,
+ total => Some((self.items_done.load(Ordering::Relaxed), total)),
+ }
+ }
+
+ /// Switch this transfer to item-scale reporting. Called once, after the
+ /// source tree has been walked and the count is actually known.
+ pub(crate) fn set_item_total(&self, total: u64) {
+ self.items_total
+ .store(total.min(TRANSFER_TOTAL_UNKNOWN - 1), Ordering::Relaxed);
+ }
+
+ pub(crate) fn finish_item(&self) {
+ self.items_done.fetch_add(1, Ordering::Relaxed);
+ }
+
+ /// Per-file byte counters are meaningless once a folder is in flight: the
+ /// aggregate is the item count, and letting each file overwrite the byte
+ /// total would make the bar jump backwards on every file.
+ fn tracks_items(&self) -> bool {
+ self.items_total.load(Ordering::Relaxed) != TRANSFER_TOTAL_UNKNOWN
+ }
+
pub(crate) fn request_cancel(&self) {
self.cancel.store(true, Ordering::Relaxed);
}
@@ -285,6 +319,12 @@ impl RemoteTransferProgress {
/// How far along, for a progress bar. `None` while the size is unknown;
/// an empty file is complete the moment it is created.
pub(crate) fn fraction(&self) -> Option<f32> {
+ if let Some((done, total)) = self.items() {
+ if total == 0 {
+ return Some(1.0);
+ }
+ return Some((done as f64 / total as f64).clamp(0.0, 1.0) as f32);
+ }
let total = self.total()?;
if total == 0 {
return Some(1.0);
@@ -297,10 +337,53 @@ impl RemoteTransferProgress {
/// tell "you cancelled this" apart from a real failure.
pub(crate) const REMOTE_TRANSFER_CANCELED: &str = "Canceled";
+/// Why a transfer stopped, and whether it managed to tidy up.
+///
+/// A plain error string cannot express "and there is now a half-written file
+/// at this path" — which is exactly the case the user has to be told about,
+/// because it usually happens when the connection died and took the cleanup
+/// with it.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct TransferFailure {
+ pub message: String,
+ /// Set when something incomplete was left behind and could not be removed.
+ pub leftover: Option<String>,
+}
+
+impl TransferFailure {
+ pub(crate) fn new(message: impl Into<String>) -> Self {
+ Self {
+ message: message.into(),
+ leftover: None,
+ }
+ }
+
+ pub(crate) fn was_canceled(&self) -> bool {
+ self.message == REMOTE_TRANSFER_CANCELED
+ }
+}
+
+/// Transfers report richer failures than the rest of the backend, so they get
+/// their own future type rather than widening every method's error.
+type TransferFuture = Pin<Box<dyn Future<Output = Result<u64, TransferFailure>> + Send + 'static>>;
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum RemoteTransferKind {
Upload,
Download,
+ /// Copying between two local directories — no connection involved, but it
+ /// wants the same progress row, cancel and retry as the remote ones.
+ LocalCopy,
+}
+
+impl RemoteTransferKind {
+ pub(crate) fn verb(self) -> &'static str {
+ match self {
+ Self::Upload => "Uploading",
+ Self::Download => "Downloading",
+ Self::LocalCopy => "Copying",
+ }
+ }
}
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -310,11 +393,37 @@ pub(crate) enum RemoteTransferStatus {
/// for a download, where the file landed.
Done(String),
Failed(String),
+ /// Failed *and* could not clean up after itself, so something incomplete
+ /// is still sitting there. Separate from `Failed` because the user has to
+ /// be told where, rather than finding it later and wondering.
+ FailedWithLeftover {
+ message: String,
+ leftover: String,
+ },
+}
+
+/// What a transfer needs in order to be run again without the user redoing the
+/// drag. Kept on the record from the start: retrofitting it after the futures
+/// have already consumed the paths is far more invasive.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) enum RemoteTransferSource {
+ Upload {
+ local: PathBuf,
+ remote: RemotePath,
+ directory: RemotePath,
+ },
+ Download {
+ remote: RemotePath,
+ },
+ LocalCopy {
+ source: PathBuf,
+ destination_dir: PathBuf,
+ },
}
-/// One file in flight, or one that just finished and still has something to
-/// report. Lives on the window rather than in [`RemoteFilesState`] because a
-/// transfer holds its own lease and must survive the panel switching trees.
+/// One transfer in flight, or one that just finished and still has something
+/// to report. Lives on the window rather than in [`RemoteFilesState`] because
+/// a transfer holds its own lease and must survive the panel switching trees.
#[derive(Clone, Debug)]
pub(crate) struct RemoteTransfer {
pub id: u64,
@@ -322,12 +431,19 @@ pub(crate) struct RemoteTransfer {
pub name: String,
pub progress: RemoteTransferProgress,
pub status: RemoteTransferStatus,
+ /// Enough to retry. `None` for records that were never a real transfer —
+ /// a rejected folder, say — which have nothing to retry.
+ pub source: Option<RemoteTransferSource>,
}
impl RemoteTransfer {
pub(crate) fn is_running(&self) -> bool {
matches!(self.status, RemoteTransferStatus::Running)
}
+
+ pub(crate) fn can_retry(&self) -> bool {
+ !self.is_running() && self.source.is_some()
+ }
}
/// How many ` (n)` variants to try before giving up on finding a free name.
@@ -423,9 +539,23 @@ pub(crate) trait RemoteFileBackend: Send + Sync {
local: PathBuf,
remote: RemotePath,
progress: RemoteTransferProgress,
- ) -> RemoteFuture<u64> {
- let _ = (local, remote, progress);
- Box::pin(async { Err("This connection cannot upload files".to_string()) })
+ overwrite: bool,
+ ) -> TransferFuture {
+ let _ = (local, remote, progress, overwrite);
+ Box::pin(async { Err(TransferFailure::new("This connection cannot upload files")) })
+ }
+
+ /// Create a remote directory, treating "it is already a directory" as
+ /// success — merging into an existing folder is normal, and an existing
+ /// *file* in its place is the only real clash.
+ ///
+ /// Checks with `metadata` rather than trusting mkdir's error: libssh wraps
+ /// its status codes opaquely, and OpenSSH speaks SFTP v3, whose error set
+ /// has no "already exists" — it answers a plain FAILURE that cannot be
+ /// told apart from a permission problem.
+ fn create_directory(&self, remote: RemotePath) -> RemoteFuture<()> {
+ let _ = remote;
+ Box::pin(async { Err("This connection cannot create directories".to_string()) })
}
/// Fetch `remote` into `local`, returning the number of bytes written.
@@ -434,9 +564,13 @@ pub(crate) trait RemoteFileBackend: Send + Sync {
remote: RemotePath,
local: PathBuf,
progress: RemoteTransferProgress,
- ) -> RemoteFuture<u64> {
+ ) -> TransferFuture {
let _ = (remote, local, progress);
- Box::pin(async { Err("This connection cannot download files".to_string()) })
+ Box::pin(async {
+ Err(TransferFailure::new(
+ "This connection cannot download files",
+ ))
+ })
}
}
@@ -616,31 +750,47 @@ impl RemoteFileBackend for SftpRemoteFileBackend {
local: PathBuf,
remote: RemotePath,
progress: RemoteTransferProgress,
- ) -> RemoteFuture<u64> {
+ overwrite: bool,
+ ) -> TransferFuture {
let sftp = self.sftp.clone();
Box::pin(async move {
- // Refuse to clobber. SFTP has no exclusive-create, so this is a
- // check rather than a guarantee — but losing the race needs a
- // second writer racing for the same path in the same instant,
- // whereas silently destroying a file needs only a careless drop.
- if sftp.metadata(remote.as_str().to_string()).await.is_ok() {
- return Err(format!(
- "{} already exists on the server",
- remote.file_name()
- ));
- }
-
- let mut source = smol::fs::File::open(&local)
- .await
- .map_err(|err| format!("Unable to open {}: {err}", local.display()))?;
- if let Ok(metadata) = source.metadata().await {
- progress.set_total(metadata.len());
+ let mut source = smol::fs::File::open(&local).await.map_err(|err| {
+ TransferFailure::new(format!("Unable to open {}: {err}", local.display()))
+ })?;
+ // Only meaningful for a single file; a folder transfer has already
+ // switched the row to item scale, which this must not disturb.
+ if !progress.tracks_items() {
+ if let Ok(metadata) = source.metadata().await {
+ progress.set_total(metadata.len());
+ }
}
- let mut file = sftp
- .create(remote.as_str().to_string())
- .await
- .map_err(|err| format!("Unable to create {}: {err}", remote.as_str()))?;
+ // Refuse to clobber, and let the *server* decide it. The previous
+ // metadata()-then-create left a window in which another writer
+ // could win, and cost a round trip per file — which a folder
+ // upload would have paid thousands of times.
+ //
+ // Everything above this point creates nothing, which is what makes
+ // the cleanup below safe: it can only ever delete a file this
+ // call brought into existence. Do not hoist that cleanup up here —
+ // a failure to create means the file was someone else's.
+ let created = if overwrite {
+ // The user has already been asked and said replace, so the
+ // truncating open is what they chose.
+ sftp.create(remote.as_str().to_string()).await
+ } else {
+ sftp.create_new(remote.as_str().to_string()).await
+ };
+ let mut file = created.map_err(|err| {
+ TransferFailure::new(if overwrite {
+ format!("Unable to write {}: {err}", remote.as_str())
+ } else {
+ format!(
+ "Unable to create {} (it may already exist): {err}",
+ remote.as_str()
+ )
+ })
+ })?;
let outcome = copy_stream(
&mut source,
@@ -654,16 +804,55 @@ impl RemoteFileBackend for SftpRemoteFileBackend {
// Close the handle before touching the path: a half-written file
// must not survive, and some servers refuse to unlink one that is
// still open.
+ //
+ // On an overwrite the original was already destroyed by the
+ // truncating open, so removal is not what loses it — the failure
+ // is. Removing anyway is still the better of two bad outcomes: a
+ // truncated file wearing the original's name reads as intact.
+ // (Uploading to a temporary name and renaming over would preserve
+ // it, but the libssh backend silently drops rename's overwrite
+ // flag, so that route is not dependable here.)
drop(file);
- if outcome.is_err() {
- if let Err(err) = sftp.remove_file(remote.as_str().to_string()).await {
- log::warn!(
- "remote files: unable to clean up the partial upload {}: {err:#}",
- remote.as_str()
- );
+ match outcome {
+ Ok(written) => Ok(written),
+ Err(message) => {
+ let mut failure = TransferFailure::new(message);
+ if let Err(err) = sftp.remove_file(remote.as_str().to_string()).await {
+ // Usually because the connection is what failed, so the
+ // cleanup rides the same dead session. Say so: a
+ // half-written file the user does not know about is
+ // worse than one they can go and delete.
+ log::warn!(
+ "remote files: unable to clean up the partial upload {}: {err:#}",
+ remote.as_str()
+ );
+ failure.leftover = Some(remote.as_str().to_string());
+ }
+ Err(failure)
}
}
- outcome
+ })
+ }
+
+ fn create_directory(&self, remote: RemotePath) -> RemoteFuture<()> {
+ let sftp = self.sftp.clone();
+ Box::pin(async move {
+ if let Ok(metadata) = sftp.metadata(remote.as_str().to_string()).await {
+ return if metadata.is_dir() {
+ Ok(())
+ } else {
+ Err(format!(
+ "{} already exists and is not a folder",
+ remote.as_str()
+ ))
+ };
+ }
+ // 0o755 as a literal: the mode is masked into permission bits and
+ // must never carry anything derived from a local file, whose modes
+ // mean nothing on the far side.
+ sftp.create_dir(remote.as_str().to_string(), 0o755)
+ .await
+ .map_err(|err| format!("Unable to create {}: {err}", remote.as_str()))
})
}
@@ -672,63 +861,113 @@ impl RemoteFileBackend for SftpRemoteFileBackend {
remote: RemotePath,
local: PathBuf,
progress: RemoteTransferProgress,
- ) -> RemoteFuture<u64> {
+ ) -> TransferFuture {
let sftp = self.sftp.clone();
Box::pin(async move {
- if let Ok(metadata) = sftp.metadata(remote.as_str().to_string()).await {
- if let Some(size) = metadata.size {
- progress.set_total(size);
- }
- }
+ // The caller reserved the staging file by creating it exclusively,
+ // so from this point on EVERY failure path owes it a cleanup —
+ // including the ones before a single byte moves. Leaving one behind
+ // is not merely litter: `reserve_download_path` skips candidates
+ // whose staging file is taken, so an orphan permanently bumps every
+ // later download of that name to ` (1)`, ` (2)`, …
+ let partial = partial_download_path(&local);
+ let outcome = download_into_partial(&sftp, &remote, &partial, &progress).await;
+ finish_download(outcome, &partial, &local).await
+ })
+ }
+}
- let mut file = sftp
- .open(remote.as_str().to_string())
- .await
- .map_err(|err| format!("Unable to open {}: {err}", remote.as_str()))?;
+/// Put a finished download in place, or clean up after a failed one.
+///
+/// Every exit from a download funnels through here so the reserved staging
+/// file has exactly one disposal site. Split from the transfer itself because
+/// this half touches only the filesystem, and is therefore the half that can
+/// be tested without a server.
+async fn finish_download(
+ outcome: Result<u64, String>,
+ partial: &Path,
+ local: &Path,
+) -> Result<u64, TransferFailure> {
+ let written = match outcome {
+ Ok(written) => written,
+ Err(message) => {
+ let mut failure = TransferFailure::new(message);
+ if let Err(cleanup) = smol::fs::remove_file(partial).await {
+ log::warn!(
+ "remote files: unable to clean up the partial download {}: {cleanup:#}",
+ partial.display()
+ );
+ failure.leftover = Some(partial.display().to_string());
+ }
+ return Err(failure);
+ }
+ };
- // The staging file was already claimed exclusively by the caller
- // (see `reserve_download_path`); opening it for writing here must
- // not create or truncate anything, or that reservation would mean
- // nothing.
- let partial = partial_download_path(&local);
- let mut sink = smol::fs::OpenOptions::new()
- .write(true)
- .truncate(true)
- .create(false)
- .open(&partial)
- .await
- .map_err(|err| format!("Unable to write {}: {err}", partial.display()))?;
+ // `rename` replaces silently, so re-check that nothing appeared at the
+ // destination while the download ran. Uploads refuse to clobber; this side
+ // must match, or a long download quietly destroys a file created in the
+ // meantime.
+ if local.exists() {
+ let _ = smol::fs::remove_file(partial).await;
+ return Err(TransferFailure::new(format!(
+ "{} appeared while downloading, so it was left untouched",
+ local.display()
+ )));
+ }
- let outcome = copy_stream(
- &mut file,
- &mut sink,
- &progress,
- "the server",
- "the local file",
- )
- .await;
- drop(sink);
+ match smol::fs::rename(partial, local).await {
+ Ok(()) => Ok(written),
+ Err(err) => {
+ let _ = smol::fs::remove_file(partial).await;
+ Err(TransferFailure::new(format!(
+ "Unable to save {}: {err}",
+ local.display()
+ )))
+ }
+ }
+}
- match outcome {
- Ok(written) => match smol::fs::rename(&partial, &local).await {
- Ok(()) => Ok(written),
- Err(err) => {
- let _ = smol::fs::remove_file(&partial).await;
- Err(format!("Unable to save {}: {err}", local.display()))
- }
- },
- Err(err) => {
- if let Err(cleanup) = smol::fs::remove_file(&partial).await {
- log::warn!(
- "remote files: unable to clean up the partial download {}: {cleanup:#}",
- partial.display()
- );
- }
- Err(err)
- }
- }
- })
+/// Stream `remote` into the already-reserved `partial`. Split out so the
+/// caller has exactly one place to clean up from: every `?` in here becomes a
+/// single `Err` the caller handles, rather than an early return that walks
+/// past the cleanup.
+async fn download_into_partial(
+ sftp: &wezterm_ssh::Sftp,
+ remote: &RemotePath,
+ partial: &Path,
+ progress: &RemoteTransferProgress,
+) -> Result<u64, String> {
+ if let Ok(metadata) = sftp.metadata(remote.as_str().to_string()).await {
+ if let Some(size) = metadata.size {
+ progress.set_total(size);
+ }
}
+
+ let mut file = sftp
+ .open(remote.as_str().to_string())
+ .await
+ .map_err(|err| format!("Unable to open {}: {err}", remote.as_str()))?;
+
+ // The staging file already exists by reservation; opening it here must not
+ // create or truncate anything else, or that reservation would mean nothing.
+ let mut sink = smol::fs::OpenOptions::new()
+ .write(true)
+ .truncate(true)
+ .create(false)
+ .open(partial)
+ .await
+ .map_err(|err| format!("Unable to write {}: {err}", partial.display()))?;
+
+ let written = copy_stream(
+ &mut file,
+ &mut sink,
+ progress,
+ "the server",
+ "the local file",
+ )
+ .await;
+ drop(sink);
+ written
}
/// Where an in-flight download accumulates. Kept next to the destination so
@@ -2819,6 +3058,183 @@ mod tests {
assert_eq!(names.next().as_deref(), Some(".bashrc (1)"));
}
+ /// Pins the bug this replaced: a download that failed before moving any
+ /// bytes used to return past the cleanup, leaving the reserved staging
+ /// file behind forever. That orphan is not just litter — reservation skips
+ /// names whose staging file is taken, so it permanently bumps every later
+ /// download of that name to ` (1)`, ` (2)`, …
+ #[test]
+ fn a_failed_download_never_leaves_its_staging_file_behind() {
+ let dir = tempfile::tempdir().unwrap();
+ let local = dir.path().join("report.pdf");
+ let partial = partial_download_path(&local);
+ std::fs::write(&partial, b"partial").unwrap();
+
+ let err = smol::block_on(finish_download(
+ Err("Unable to open /srv/report.pdf: no such file".to_string()),
+ &partial,
+ &local,
+ ))
+ .expect_err("a failed download must stay failed");
+
+ assert!(err.message.contains("no such file"), "{}", err.message);
+ assert!(
+ !partial.exists(),
+ "the staging file must not survive a failure"
+ );
+ assert!(!local.exists(), "and nothing may appear at the destination");
+ }
+
+ /// The reservation checked the destination was free, but a download takes
+ /// time; `rename` would replace silently, so a file that appears in the
+ /// meantime must be left alone — matching the upload side's refusal to
+ /// overwrite.
+ #[test]
+ fn a_download_does_not_clobber_a_file_that_appeared_while_it_ran() {
+ let dir = tempfile::tempdir().unwrap();
+ let local = dir.path().join("notes.txt");
+ let partial = partial_download_path(&local);
+ std::fs::write(&partial, b"downloaded").unwrap();
+ // Something else got there first.
+ std::fs::write(&local, b"do not lose me").unwrap();
+
+ let err = smol::block_on(finish_download(Ok(10), &partial, &local))
+ .expect_err("landing on an occupied name must fail");
+
+ assert!(
+ err.message.contains("appeared while downloading"),
+ "{}",
+ err.message
+ );
+ assert_eq!(
+ std::fs::read(&local).unwrap(),
+ b"do not lose me",
+ "the pre-existing file must be untouched"
+ );
+ assert!(!partial.exists(), "and the staging file is cleaned up");
+ }
+
+ /// When cleanup itself fails — which is the normal case once the
+ /// connection is what died — the failure has to carry where the debris is.
+ /// A log line is not good enough: the user needs to know a partial file is
+ /// sitting there, or they will hit "already exists" on retry with nothing
+ /// on screen explaining why.
+ #[test]
+ fn a_failure_that_could_not_clean_up_says_what_it_left_behind() {
+ let dir = tempfile::tempdir().unwrap();
+ let local = dir.path().join("big.iso");
+ let partial = partial_download_path(&local);
+ // No staging file on disk, so the cleanup below cannot succeed —
+ // standing in for a removal that fails for any reason.
+ let err = smol::block_on(finish_download(
+ Err("connection lost".to_string()),
+ &partial,
+ &local,
+ ))
+ .expect_err("the transfer failed");
+
+ assert_eq!(err.message, "connection lost");
+ assert_eq!(
+ err.leftover.as_deref(),
+ Some(partial.display().to_string().as_str()),
+ "the caller must be able to tell the user where the debris is"
+ );
+
+ // A cleanup that works reports no leftover.
+ std::fs::write(&partial, b"half").unwrap();
+ let err = smol::block_on(finish_download(
+ Err("connection lost".to_string()),
+ &partial,
+ &local,
+ ))
+ .expect_err("the transfer failed");
+ assert_eq!(err.leftover, None);
+ assert!(!partial.exists());
+ }
+
+ #[test]
+ fn a_successful_download_moves_into_place() {
+ let dir = tempfile::tempdir().unwrap();
+ let local = dir.path().join("archive.tar.gz");
+ let partial = partial_download_path(&local);
+ std::fs::write(&partial, b"payload").unwrap();
+
+ let written = smol::block_on(finish_download(Ok(7), &partial, &local)).expect("download");
+ assert_eq!(written, 7);
+ assert_eq!(std::fs::read(&local).unwrap(), b"payload");
+ assert!(
+ !partial.exists(),
+ "the staging file is consumed by the move"
+ );
+ }
+
+ /// A folder reports items, not bytes. The trap this pins: a walker that
+ /// reuses the single-file upload path lets every file call `set_total`
+ /// with its own size, so the bar reads "100%" on each small file and jumps
+ /// backwards on the next one. Item scale must win once it is established.
+ /// A folder upload rebuilds each destination from the plan's *relative*
+ /// path, one component at a time. Joining the whole thing at once would
+ /// splice a local separator into a remote path — and on Windows a
+ /// backslash is a legal remote filename character, so the mistake would
+ /// silently create a file literally called `a\b\c`.
+ #[test]
+ fn a_relative_path_joins_one_component_at_a_time() {
+ let root = RemotePath::from_server_absolute("/srv/app").unwrap();
+ let mut built = root.clone();
+ for name in ["proj", "src", "main.rs"] {
+ built = built.join_name(name).unwrap();
+ }
+ assert_eq!(built.as_str(), "/srv/app/proj/src/main.rs");
+
+ // The whole-string shortcut is exactly what join_name refuses.
+ assert!(root.join_name("proj/src/main.rs").is_err());
+ assert!(root.join_name("..").is_err());
+ assert!(root.join_name("").is_err());
+ }
+
+ #[test]
+ fn item_progress_is_not_disturbed_by_per_file_byte_totals() {
+ let progress = RemoteTransferProgress::default();
+ progress.set_item_total(4);
+ assert_eq!(progress.items(), Some((0, 4)));
+ assert_eq!(progress.fraction(), Some(0.0));
+
+ // One file of the tree goes by, reporting its own byte size and
+ // finishing it. The fraction must follow items, not those bytes.
+ progress.set_total(1_000);
+ progress.advance(1_000);
+ progress.finish_item();
+ assert_eq!(progress.items(), Some((1, 4)));
+ assert_eq!(
+ progress.fraction(),
+ Some(0.25),
+ "one of four files done, regardless of that file's byte count"
+ );
+
+ for _ in 0..3 {
+ progress.finish_item();
+ }
+ assert_eq!(progress.fraction(), Some(1.0));
+ }
+
+ #[test]
+ fn a_single_file_transfer_still_reports_bytes() {
+ let progress = RemoteTransferProgress::default();
+ assert_eq!(progress.items(), None, "no item scale unless asked for");
+ progress.set_total(200);
+ progress.advance(50);
+ assert_eq!(progress.fraction(), Some(0.25));
+ }
+
+ /// An empty folder is finished the moment it exists, the same way an empty
+ /// file is — otherwise the row would sit at 0% forever.
+ #[test]
+ fn an_empty_folder_reads_as_complete() {
+ let progress = RemoteTransferProgress::default();
+ progress.set_item_total(0);
+ assert_eq!(progress.fraction(), Some(1.0));
+ }
+
#[test]
fn a_partial_download_lands_beside_its_destination() {
// Same directory, so completing the download is a rename rather than a
diff --git a/wezterm-gui/src/termwindow/transfer_walk.rs b/wezterm-gui/src/termwindow/transfer_walk.rs
new file mode 100644
index 00000000..3e1791c7
--- /dev/null
+++ b/wezterm-gui/src/termwindow/transfer_walk.rs
@@ -0,0 +1,935 @@
+//! Turning a dropped folder into a flat list of things to transfer.
+//!
+//! Deliberately a separate step from the transfer itself. Walking first means
+//! the total is known before anything moves — so the progress row can show
+//! "12/300" rather than an unbounded spinner — and, more importantly, it means
+//! every destination conflict is discovered before the first byte is written,
+//! so the user is asked once instead of being interrupted midway.
+
+use std::collections::HashSet;
+use std::path::{Path, PathBuf};
+use walkdir::WalkDir;
+
+/// Above this many entries a folder transfer asks for confirmation first.
+///
+/// Not a memory limit — the entry list is small. It is a *time* limit: every
+/// remote file costs at least one round trip on a single serialized session,
+/// so a few thousand small files takes minutes with no way to know that in
+/// advance unless we say so.
+pub(crate) const TRANSFER_CONFIRM_THRESHOLD: usize = 1_000;
+
+/// A hard stop. Walking a pathological tree should fail cleanly rather than
+/// build a list nobody wants.
+pub(crate) const TRANSFER_ENTRY_LIMIT: usize = 100_000;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum TransferEntryKind {
+ Directory,
+ File,
+}
+
+/// One thing to create at the destination, named relative to the drop root so
+/// the same list works for a local copy and an SFTP upload.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct TransferEntry {
+ pub source: PathBuf,
+ /// Path relative to the destination directory, in order: parents always
+ /// appear before their children, so a consumer can create as it goes.
+ pub relative: PathBuf,
+ pub kind: TransferEntryKind,
+ pub size: u64,
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub(crate) struct TransferPlan {
+ pub entries: Vec<TransferEntry>,
+ /// Symlinks encountered and deliberately not followed, counted so the user
+ /// can be told rather than silently losing them.
+ pub skipped_symlinks: usize,
+ /// Entries that could not be read at all (permissions, races).
+ pub unreadable: usize,
+ pub total_bytes: u64,
+}
+
+impl TransferPlan {
+ pub(crate) fn file_count(&self) -> usize {
+ self.entries
+ .iter()
+ .filter(|entry| entry.kind == TransferEntryKind::File)
+ .count()
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) enum TransferPlanError {
+ /// The destination is the source, or lives inside it. Copying a directory
+ /// into its own subtree makes the walk re-read what it just wrote, which
+ /// only ends when the disk is full.
+ DestinationInsideSource,
+ TooManyEntries(usize),
+ Unreadable(String),
+}
+
+impl TransferPlanError {
+ pub(crate) fn message(&self) -> String {
+ match self {
+ Self::DestinationInsideSource => {
+ "Cannot copy a folder into itself or into one of its own subfolders".to_string()
+ }
+ Self::TooManyEntries(limit) => {
+ format!("That folder holds more than {limit} items")
+ }
+ Self::Unreadable(path) => format!("Unable to read {path}"),
+ }
+ }
+}
+
+/// Reject a destination that would make the walk eat its own output.
+///
+/// Compares canonical paths so the check survives symlinks, `..`, and two
+/// different spellings of the same directory — the naive string prefix test
+/// misses all three.
+pub(crate) fn destination_escapes_source(source: &Path, destination_dir: &Path) -> bool {
+ let (Ok(source), Ok(destination)) = (source.canonicalize(), destination_dir.canonicalize())
+ else {
+ // If either side cannot be resolved we cannot prove the copy is safe,
+ // and an unprovable copy of a directory into itself is the one that
+ // fills the disk. Refuse.
+ return true;
+ };
+ destination == source || destination.starts_with(&source)
+}
+
+/// Whether two paths name the same file on disk.
+///
+/// Matters because `fs::copy` with identical source and destination opens the
+/// destination truncating *first*: the shared inode is emptied, zero bytes are
+/// then read, and the call reports `Ok(0)`. An 11-byte file becomes 0 bytes
+/// and nothing reports an error. Dropping a file back into its own folder is
+/// an easy way to trigger it, so it has to be caught before the copy.
+pub(crate) fn is_same_file(a: &Path, b: &Path) -> bool {
+ // Identity first: hard links give the same file two unrelated names, so
+ // their canonical paths differ while a write to either destroys both.
+ // Verified: truncating one hard link empties the other.
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::MetadataExt;
+ if let (Ok(a), Ok(b)) = (a.metadata(), b.metadata()) {
+ return a.dev() == b.dev() && a.ino() == b.ino();
+ }
+ }
+ match (a.canonicalize(), b.canonicalize()) {
+ (Ok(a), Ok(b)) => a == b,
+ // A destination that does not exist yet cannot be the source.
+ _ => false,
+ }
+}
+
+/// Confirm a destination really lives under `root` once symlinks are resolved.
+///
+/// `create_dir_all` happily follows a symlinked directory, so a link named the
+/// same as the dropped folder would send the whole tree somewhere else
+/// entirely. Checking the resolved parent is what stops that.
+///
+/// This is a cheap pre-check, not the guarantee: it resolves paths that the
+/// write then walks again, so a component swapped in between would slip past.
+/// The guarantee comes from [`DestinationRoot`], which descends through
+/// directory handles and refuses to traverse a symlink at all. Keep both — the
+/// pre-check gives a clear message before any work starts, and the descent is
+/// what actually holds.
+pub(crate) fn destination_stays_within(root: &Path, destination: &Path) -> bool {
+ let Ok(root) = root.canonicalize() else {
+ return false;
+ };
+ // The destination itself may not exist yet; its parent must, and is what
+ // decides where the write actually lands.
+ let Some(parent) = destination.parent() else {
+ return false;
+ };
+ match parent.canonicalize() {
+ Ok(parent) => parent == root || parent.starts_with(&root),
+ // Not created yet: it will be made under a parent we already checked
+ // on an earlier entry, since entries arrive parents-first.
+ Err(_) => true,
+ }
+}
+
+/// A handle on the directory a copy is allowed to write into.
+///
+/// Opened once and carried through the whole operation, so every create,
+/// rename and delete starts from the *same* verified directory rather than
+/// re-resolving a path that could have changed underneath. Each step down
+/// uses `O_NOFOLLOW`, so a symlink anywhere in the descent fails instead of
+/// redirecting the write.
+///
+/// This matters wherever the destination is writable by someone other than
+/// the user — a shared checkout, a group-writable directory, a network mount.
+/// There, planting a link costs an attacker nothing and would have this
+/// process write, with *its* privileges, somewhere the attacker cannot reach.
+/// "They could edit those files anyway" only holds when the directory belongs
+/// solely to the user, which is not an assumption this can make.
+pub(crate) struct DestinationRoot {
+ path: PathBuf,
+ #[cfg(unix)]
+ fd: std::os::unix::io::OwnedFd,
+}
+
+impl DestinationRoot {
+ /// The directory itself, for error messages only — never for reaching the
+ /// files, which always goes through the handle.
+ pub(crate) fn path(&self) -> &Path {
+ &self.path
+ }
+}
+
+#[cfg(unix)]
+mod unix_root {
+ use super::DestinationRoot;
+ use std::ffi::CString;
+ use std::fs::File;
+ use std::io::{Error, ErrorKind, Result};
+ use std::os::unix::ffi::OsStrExt;
+ use std::os::unix::io::{AsRawFd, FromRawFd, OwnedFd};
+ use std::path::{Component, Path, PathBuf};
+
+ fn component_name(component: Component<'_>) -> Result<CString> {
+ match component {
+ // Anything but a plain name could leave the subtree; the planner
+ // never produces one, and accepting it here would undo the point.
+ Component::Normal(name) => CString::new(name.as_bytes())
+ .map_err(|_| Error::new(ErrorKind::InvalidInput, "path component contains NUL")),
+ _ => Err(Error::new(
+ ErrorKind::InvalidInput,
+ "path component is not a plain name",
+ )),
+ }
+ }
+
+ fn open_dir_at(parent: &OwnedFd, name: &CString) -> Result<OwnedFd> {
+ let fd = unsafe {
+ libc::openat(
+ parent.as_raw_fd(),
+ name.as_ptr(),
+ libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
+ )
+ };
+ if fd < 0 {
+ return Err(Error::last_os_error());
+ }
+ Ok(unsafe { OwnedFd::from_raw_fd(fd) })
+ }
+
+ impl DestinationRoot {
+ pub(crate) fn open(path: &Path) -> Result<Self> {
+ let name = CString::new(path.as_os_str().as_bytes())
+ .map_err(|_| Error::new(ErrorKind::InvalidInput, "path contains NUL"))?;
+ let fd = unsafe {
+ libc::open(
+ name.as_ptr(),
+ libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC,
+ )
+ };
+ if fd < 0 {
+ return Err(Error::last_os_error());
+ }
+ Ok(Self {
+ path: path.to_path_buf(),
+ fd: unsafe { OwnedFd::from_raw_fd(fd) },
+ })
+ }
+
+ /// Walk to the directory holding `relative`'s last component, starting
+ /// from the pinned root, and hand back that directory with the name to
+ /// use inside it.
+ fn parent_of(&self, relative: &Path) -> Result<(OwnedFd, CString)> {
+ let mut components: Vec<_> = relative.components().collect();
+ let Some(last) = components.pop() else {
+ return Err(Error::new(ErrorKind::InvalidInput, "empty relative path"));
+ };
+ let mut current = self.fd.try_clone()?;
+ for component in components {
+ let name = component_name(component)?;
+ current = open_dir_at(&current, &name)?;
+ }
+ Ok((current, component_name(last)?))
+ }
+
+ /// Create a directory, treating one that is already there as success
+ /// and anything else wearing the name as a clash. `mkdirat` never
+ /// follows a symlink at the name it creates.
+ pub(crate) fn create_dir(&self, relative: &Path) -> Result<()> {
+ let (parent, name) = self.parent_of(relative)?;
+ if unsafe { libc::mkdirat(parent.as_raw_fd(), name.as_ptr(), 0o777) } == 0 {
+ return Ok(());
+ }
+ let err = Error::last_os_error();
+ if err.kind() != ErrorKind::AlreadyExists {
+ return Err(err);
+ }
+ let mut stat: libc::stat = unsafe { std::mem::zeroed() };
+ if unsafe {
+ libc::fstatat(
+ parent.as_raw_fd(),
+ name.as_ptr(),
+ &mut stat,
+ libc::AT_SYMLINK_NOFOLLOW,
+ )
+ } != 0
+ {
+ return Err(Error::last_os_error());
+ }
+ if stat.st_mode & libc::S_IFMT == libc::S_IFDIR {
+ Ok(())
+ } else {
+ Err(Error::new(
+ ErrorKind::AlreadyExists,
+ "a non-folder already has that name",
+ ))
+ }
+ }
+
+ /// Create a new file, failing if anything already holds that name —
+ /// including a symlink, which is never followed.
+ pub(crate) fn create_file(&self, relative: &Path) -> Result<File> {
+ let (parent, name) = self.parent_of(relative)?;
+ let fd = unsafe {
+ libc::openat(
+ parent.as_raw_fd(),
+ name.as_ptr(),
+ libc::O_WRONLY
+ | libc::O_CREAT
+ | libc::O_EXCL
+ | libc::O_NOFOLLOW
+ | libc::O_CLOEXEC,
+ 0o666 as libc::c_uint,
+ )
+ };
+ if fd < 0 {
+ return Err(Error::last_os_error());
+ }
+ Ok(unsafe { File::from_raw_fd(fd) })
+ }
+
+ pub(crate) fn rename(&self, from: &Path, to: &Path) -> Result<()> {
+ let (from_dir, from_name) = self.parent_of(from)?;
+ let (to_dir, to_name) = self.parent_of(to)?;
+ if unsafe {
+ libc::renameat(
+ from_dir.as_raw_fd(),
+ from_name.as_ptr(),
+ to_dir.as_raw_fd(),
+ to_name.as_ptr(),
+ )
+ } == 0
+ {
+ Ok(())
+ } else {
+ Err(Error::last_os_error())
+ }
+ }
+
+ /// Delete through the handle as well. Cleanup runs precisely when
+ /// something has already gone wrong, which is the worst moment to
+ /// start trusting a path again: a component swapped between the write
+ /// and the delete would aim the delete outside the destination.
+ pub(crate) fn remove_file(&self, relative: &Path) -> Result<()> {
+ let (parent, name) = self.parent_of(relative)?;
+ if unsafe { libc::unlinkat(parent.as_raw_fd(), name.as_ptr(), 0) } == 0 {
+ Ok(())
+ } else {
+ Err(Error::last_os_error())
+ }
+ }
+
+ pub(crate) fn join(&self, relative: &Path) -> PathBuf {
+ self.path.join(relative)
+ }
+ }
+}
+
+/// Path-based stand-in for platforms without `openat`.
+///
+/// Present so the crate builds everywhere; the local copy that uses it is
+/// reachable only on X11 and macOS, because the Windows and Wayland backends
+/// report no drop position. If that ever changes, this needs the same
+/// handle-based treatment before it can be trusted.
+#[cfg(not(unix))]
+mod portable_root {
+ use super::DestinationRoot;
+ use std::fs::{self, File};
+ use std::io::{Error, ErrorKind, Result};
+ use std::path::{Component, Path, PathBuf};
+
+ fn checked(relative: &Path) -> Result<()> {
+ if relative
+ .components()
+ .all(|component| matches!(component, Component::Normal(_)))
+ {
+ Ok(())
+ } else {
+ Err(Error::new(
+ ErrorKind::InvalidInput,
+ "path component is not a plain name",
+ ))
+ }
+ }
+
+ impl DestinationRoot {
+ pub(crate) fn open(path: &Path) -> Result<Self> {
+ if path.is_dir() {
+ Ok(Self {
+ path: path.to_path_buf(),
+ })
+ } else {
+ Err(Error::new(
+ ErrorKind::NotFound,
+ "destination is not a folder",
+ ))
+ }
+ }
+
+ pub(crate) fn create_dir(&self, relative: &Path) -> Result<()> {
+ checked(relative)?;
+ let target = self.join(relative);
+ match target.symlink_metadata() {
+ Ok(meta) if meta.is_dir() => Ok(()),
+ Ok(_) => Err(Error::new(
+ ErrorKind::AlreadyExists,
+ "a non-folder already has that name",
+ )),
+ Err(_) => fs::create_dir_all(&target),
+ }
+ }
+
+ pub(crate) fn create_file(&self, relative: &Path) -> Result<File> {
+ checked(relative)?;
+ fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .open(self.join(relative))
+ }
+
+ pub(crate) fn rename(&self, from: &Path, to: &Path) -> Result<()> {
+ checked(from)?;
+ checked(to)?;
+ fs::rename(self.join(from), self.join(to))
+ }
+
+ pub(crate) fn remove_file(&self, relative: &Path) -> Result<()> {
+ checked(relative)?;
+ fs::remove_file(self.join(relative))
+ }
+
+ pub(crate) fn join(&self, relative: &Path) -> PathBuf {
+ self.path.join(relative)
+ }
+ }
+}
+
+/// Walk `source` into a flat, parents-first list of entries to create under a
+/// destination directory.
+///
+/// Symlinks are recorded and skipped rather than followed: following them
+/// invites loops, and it silently copies data from outside the folder the user
+/// pointed at. This matches how the local file indexer already walks.
+pub(crate) fn plan_transfer(source: &Path) -> Result<TransferPlan, TransferPlanError> {
+ let Some(top_name) = source.file_name() else {
+ return Err(TransferPlanError::Unreadable(source.display().to_string()));
+ };
+ let top = PathBuf::from(top_name);
+
+ let metadata = source
+ .symlink_metadata()
+ .map_err(|_| TransferPlanError::Unreadable(source.display().to_string()))?;
+
+ let mut plan = TransferPlan::default();
+ if metadata.file_type().is_symlink() {
+ plan.skipped_symlinks += 1;
+ return Ok(plan);
+ }
+ if metadata.is_file() {
+ plan.total_bytes = metadata.len();
+ plan.entries.push(TransferEntry {
+ source: source.to_path_buf(),
+ relative: top,
+ kind: TransferEntryKind::File,
+ size: metadata.len(),
+ });
+ return Ok(plan);
+ }
+
+ // The folder itself comes first, so consumers can create it before
+ // anything is placed inside.
+ plan.entries.push(TransferEntry {
+ source: source.to_path_buf(),
+ relative: top.clone(),
+ kind: TransferEntryKind::Directory,
+ size: 0,
+ });
+
+ for entry in WalkDir::new(source).follow_links(false).min_depth(1) {
+ if plan.entries.len() >= TRANSFER_ENTRY_LIMIT {
+ return Err(TransferPlanError::TooManyEntries(TRANSFER_ENTRY_LIMIT));
+ }
+ let Ok(entry) = entry else {
+ // A directory that vanished or cannot be read: count it and carry
+ // on, so one bad corner does not sink the whole transfer.
+ plan.unreadable += 1;
+ continue;
+ };
+ let file_type = entry.file_type();
+ if file_type.is_symlink() {
+ plan.skipped_symlinks += 1;
+ continue;
+ }
+ let Ok(relative) = entry.path().strip_prefix(source) else {
+ plan.unreadable += 1;
+ continue;
+ };
+ let relative = top.join(relative);
+
+ if file_type.is_dir() {
+ plan.entries.push(TransferEntry {
+ source: entry.path().to_path_buf(),
+ relative,
+ kind: TransferEntryKind::Directory,
+ size: 0,
+ });
+ } else if file_type.is_file() {
+ let size = entry.metadata().map(|meta| meta.len()).unwrap_or(0);
+ plan.total_bytes = plan.total_bytes.saturating_add(size);
+ plan.entries.push(TransferEntry {
+ source: entry.path().to_path_buf(),
+ relative,
+ kind: TransferEntryKind::File,
+ size,
+ });
+ } else {
+ // Sockets, fifos, devices: nothing meaningful to copy.
+ plan.unreadable += 1;
+ }
+ }
+
+ Ok(plan)
+}
+
+/// What to do about destinations that already exist.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum ConflictChoice {
+ Overwrite,
+ Skip,
+ Cancel,
+}
+
+/// How a copy should treat a destination it finds occupied.
+///
+/// Distinct from [`ConflictChoice`] because "the user said replace" and "we
+/// found nothing to replace" must not collapse into the same value: if they
+/// did, a file appearing between the check and the write would be destroyed
+/// under an authorisation the user never gave.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum OverwritePolicy {
+ /// Nothing was in the way when we looked, so anything there now arrived
+ /// since and must not be touched.
+ NoClobber,
+ /// The user was shown the clashes and chose to replace them.
+ Replace,
+ /// The user was shown the clashes and chose to keep them.
+ SkipExisting,
+}
+
+/// Everything a drop needs decided before any file is written.
+#[derive(Debug, Default)]
+pub(crate) struct TransferPreflight {
+ pub plans: Vec<(PathBuf, TransferPlan)>,
+ /// Destination-relative paths that already exist.
+ pub conflicts: HashSet<PathBuf>,
+ /// Sources rejected outright, as (name, reason).
+ pub rejected: Vec<(String, String)>,
+ pub skipped_symlinks: usize,
+ pub unreadable: usize,
+}
+
+impl TransferPreflight {
+ pub(crate) fn entry_count(&self) -> usize {
+ self.plans.iter().map(|(_, plan)| plan.entries.len()).sum()
+ }
+
+ /// What to tell the user about things the walk deliberately left out.
+ /// Silence here would mean reporting success while quietly omitting data.
+ pub(crate) fn omission_note(&self) -> Option<String> {
+ let mut parts = Vec::new();
+ if self.skipped_symlinks > 0 {
+ parts.push(format!("{} symlink(s) skipped", self.skipped_symlinks));
+ }
+ if self.unreadable > 0 {
+ parts.push(format!("{} unreadable item(s)", self.unreadable));
+ }
+ (!parts.is_empty()).then(|| parts.join(", "))
+ }
+}
+
+/// Drop the entries a `Skip` choice excludes.
+///
+/// Directories are never dropped even when they already exist — merging into
+/// an existing folder is the whole point of `Skip`, and removing the directory
+/// entry would orphan everything underneath it.
+pub(crate) fn apply_conflict_choice(
+ plan: TransferPlan,
+ conflicts: &HashSet<PathBuf>,
+ choice: ConflictChoice,
+) -> TransferPlan {
+ if choice != ConflictChoice::Skip {
+ return plan;
+ }
+ let mut filtered = plan;
+ filtered.entries.retain(|entry| {
+ entry.kind == TransferEntryKind::Directory || !conflicts.contains(&entry.relative)
+ });
+ filtered.total_bytes = filtered
+ .entries
+ .iter()
+ .map(|entry| entry.size)
+ .fold(0u64, |sum, size| sum.saturating_add(size));
+ filtered
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::fs;
+
+ fn relatives(plan: &TransferPlan) -> Vec<String> {
+ plan.entries
+ .iter()
+ .map(|entry| entry.relative.to_string_lossy().replace('\\', "/"))
+ .collect()
+ }
+
+ #[test]
+ fn a_folder_walks_into_a_parents_first_list() {
+ let dir = tempfile::tempdir().unwrap();
+ let src = dir.path().join("proj");
+ fs::create_dir_all(src.join("a/b")).unwrap();
+ fs::write(src.join("top.txt"), b"12345").unwrap();
+ fs::write(src.join("a/inner.txt"), b"xy").unwrap();
+ fs::write(src.join("a/b/deep.txt"), b"z").unwrap();
+
+ let plan = plan_transfer(&src).unwrap();
+ let names = relatives(&plan);
+
+ assert!(names.contains(&"proj".to_string()), "{names:?}");
+ assert_eq!(plan.file_count(), 3);
+ assert_eq!(plan.total_bytes, 8);
+
+ // Every directory must appear before anything inside it, or a consumer
+ // creating as it goes would write into a directory that is not there.
+ for (index, name) in names.iter().enumerate() {
+ if let Some((parent, _)) = name.rsplit_once('/') {
+ let parent_index = names.iter().position(|other| other == parent);
+ assert!(
+ parent_index.is_some_and(|parent_index| parent_index < index),
+ "{parent} must precede {name} in {names:?}"
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn a_single_file_plans_as_one_entry() {
+ let dir = tempfile::tempdir().unwrap();
+ let file = dir.path().join("notes.txt");
+ fs::write(&file, b"hello").unwrap();
+
+ let plan = plan_transfer(&file).unwrap();
+ assert_eq!(relatives(&plan), vec!["notes.txt".to_string()]);
+ assert_eq!(plan.total_bytes, 5);
+ assert_eq!(plan.file_count(), 1);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn symlinks_are_counted_and_not_followed() {
+ let dir = tempfile::tempdir().unwrap();
+ let src = dir.path().join("proj");
+ fs::create_dir_all(&src).unwrap();
+ fs::write(src.join("real.txt"), b"ok").unwrap();
+ // A link pointing back at its own parent: following it would loop.
+ std::os::unix::fs::symlink(&src, src.join("loop")).unwrap();
+
+ let plan = plan_transfer(&src).unwrap();
+ assert_eq!(plan.skipped_symlinks, 1);
+ assert_eq!(plan.file_count(), 1, "only the real file is planned");
+ assert!(
+ !relatives(&plan).iter().any(|name| name.contains("loop")),
+ "the symlink must not be planned"
+ );
+ }
+
+ /// The disk-filling case: copying a folder into a directory inside itself
+ /// makes the walk re-read what it has just written.
+ #[test]
+ fn a_destination_inside_the_source_is_refused() {
+ let dir = tempfile::tempdir().unwrap();
+ let src = dir.path().join("proj");
+ fs::create_dir_all(src.join("vendor")).unwrap();
+ let outside = dir.path().join("elsewhere");
+ fs::create_dir_all(&outside).unwrap();
+
+ assert!(destination_escapes_source(&src, &src.join("vendor")));
+ assert!(
+ destination_escapes_source(&src, &src),
+ "copying onto itself is equally pointless"
+ );
+ assert!(!destination_escapes_source(&src, &outside));
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn the_subtree_check_sees_through_symlinks_and_dot_dot() {
+ let dir = tempfile::tempdir().unwrap();
+ let src = dir.path().join("proj");
+ fs::create_dir_all(src.join("vendor")).unwrap();
+ // A link from outside pointing back inside the source: a plain string
+ // prefix test would call this safe.
+ let link = dir.path().join("shortcut");
+ std::os::unix::fs::symlink(src.join("vendor"), &link).unwrap();
+ assert!(destination_escapes_source(&src, &link));
+
+ let round_about = src.join("vendor/../vendor");
+ assert!(destination_escapes_source(&src, &round_about));
+ }
+
+ /// Pins the worst outcome this module exists to prevent. `fs::copy` with
+ /// identical source and destination truncates the shared inode before
+ /// reading it, then returns `Ok(0)` — an 11-byte file silently becomes an
+ /// empty one and nothing reports a failure. Dropping a file back into its
+ /// own folder is the easy way to hit it.
+ #[test]
+ fn a_file_is_recognised_as_its_own_destination() {
+ let dir = tempfile::tempdir().unwrap();
+ let file = dir.path().join("a.txt");
+ fs::write(&file, b"hello world").unwrap();
+
+ // The exact shape a drop onto the containing folder produces.
+ let destination = dir.path().join("a.txt");
+ assert!(is_same_file(&file, &destination));
+
+ // A different name in the same folder is a genuine copy.
+ assert!(!is_same_file(&file, &dir.path().join("b.txt")));
+ // A destination that does not exist cannot be the source.
+ assert!(!is_same_file(&file, &dir.path().join("nested/a.txt")));
+ }
+
+ /// Hard links defeat a canonical-path comparison: the two names resolve
+ /// differently yet share one inode, so truncating the "destination"
+ /// empties the source. Verified empirically before this check existed.
+ #[cfg(unix)]
+ #[test]
+ fn a_hard_link_counts_as_the_same_file() {
+ let dir = tempfile::tempdir().unwrap();
+ let original = dir.path().join("original.txt");
+ let link = dir.path().join("hardlink.txt");
+ fs::write(&original, b"important data").unwrap();
+ fs::hard_link(&original, &link).unwrap();
+
+ assert_ne!(
+ original.canonicalize().unwrap(),
+ link.canonicalize().unwrap(),
+ "the canonical paths differ, which is exactly why this needs inodes"
+ );
+ assert!(is_same_file(&original, &link));
+
+ // An ordinary copy of the same bytes is still two different files.
+ let separate = dir.path().join("separate.txt");
+ fs::write(&separate, b"important data").unwrap();
+ assert!(!is_same_file(&original, &separate));
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn the_same_file_is_seen_through_a_symlinked_directory() {
+ let dir = tempfile::tempdir().unwrap();
+ let real = dir.path().join("real");
+ fs::create_dir_all(&real).unwrap();
+ let file = real.join("a.txt");
+ fs::write(&file, b"data").unwrap();
+ // Reaching the same file by another name must not look like a copy.
+ let link = dir.path().join("link");
+ std::os::unix::fs::symlink(&real, &link).unwrap();
+ assert!(is_same_file(&file, &link.join("a.txt")));
+ }
+
+ /// The guarantee behind the path pre-check: descending through directory
+ /// handles refuses to traverse a symlink at all, so a component swapped
+ /// after any path was resolved cannot redirect the write. This is what
+ /// matters when the destination is writable by someone else — planting a
+ /// link would otherwise borrow this process's privileges to write where
+ /// the planter cannot reach.
+ #[cfg(unix)]
+ #[test]
+ fn a_symlinked_parent_component_cannot_be_traversed() {
+ let dir = tempfile::tempdir().unwrap();
+ let root = dir.path().join("dest");
+ let outside = dir.path().join("outside");
+ fs::create_dir_all(&root).unwrap();
+ fs::create_dir_all(&outside).unwrap();
+ std::os::unix::fs::symlink(&outside, root.join("sub")).unwrap();
+ let opened = DestinationRoot::open(&root).unwrap();
+
+ // Writing "through" the link must fail rather than land outside.
+ let err = opened
+ .create_file(Path::new("sub/payload.txt"))
+ .expect_err("a symlinked component must not be traversed");
+ assert!(
+ matches!(
+ err.raw_os_error(),
+ Some(libc::ELOOP) | Some(libc::ENOTDIR) | Some(libc::EMLINK)
+ ),
+ "unexpected error: {err} ({:?})",
+ err.raw_os_error()
+ );
+ assert!(
+ !outside.join("payload.txt").exists(),
+ "nothing may be written outside the destination"
+ );
+
+ // Creating a directory through it is refused for the same reason.
+ assert!(opened.create_dir(Path::new("sub/nested")).is_err());
+ assert!(!outside.join("nested").exists());
+
+ // A real directory underneath works normally.
+ opened.create_dir(Path::new("real")).unwrap();
+ let file = opened.create_file(Path::new("real/ok.txt")).unwrap();
+ drop(file);
+ assert!(root.join("real/ok.txt").is_file());
+ }
+
+ /// Cleanup runs precisely when something has already gone wrong, which is
+ /// the worst moment to start trusting a path again: a component swapped
+ /// between the write and the delete would aim the delete outside the
+ /// destination. Deleting through the handle cannot be steered that way.
+ #[cfg(unix)]
+ #[test]
+ fn deleting_goes_through_the_handle_too() {
+ let dir = tempfile::tempdir().unwrap();
+ let root = dir.path().join("dest");
+ let outside = dir.path().join("outside");
+ fs::create_dir_all(&root).unwrap();
+ fs::create_dir_all(&outside).unwrap();
+ let bystander = outside.join("keep.txt");
+ fs::write(&bystander, b"not yours to delete").unwrap();
+
+ let opened = DestinationRoot::open(&root).unwrap();
+ // A file we did create is removed normally.
+ drop(opened.create_file(Path::new("mine.txt")).unwrap());
+ opened.remove_file(Path::new("mine.txt")).unwrap();
+ assert!(!root.join("mine.txt").exists());
+
+ // Now the destination sprouts a link to somewhere else, the way it
+ // might between a failed write and its cleanup.
+ std::os::unix::fs::symlink(&outside, root.join("sub")).unwrap();
+ assert!(
+ opened.remove_file(Path::new("sub/keep.txt")).is_err(),
+ "a delete must not be routed through a symlinked component"
+ );
+ assert!(
+ bystander.exists(),
+ "the file outside the destination must survive"
+ );
+ }
+
+ /// The root is opened once and held. Re-opening it per operation would
+ /// leave the root's own ancestors free to be swapped in between.
+ #[cfg(unix)]
+ #[test]
+ fn the_root_handle_survives_its_path_being_replaced() {
+ let dir = tempfile::tempdir().unwrap();
+ let real = dir.path().join("real");
+ let decoy = dir.path().join("decoy");
+ fs::create_dir_all(&real).unwrap();
+ fs::create_dir_all(&decoy).unwrap();
+
+ let link = dir.path().join("root");
+ std::os::unix::fs::symlink(&real, &link).unwrap();
+ let opened = DestinationRoot::open(&link).unwrap();
+
+ // Repoint the name the root was opened by.
+ fs::remove_file(&link).unwrap();
+ std::os::unix::fs::symlink(&decoy, &link).unwrap();
+
+ drop(opened.create_file(Path::new("written.txt")).unwrap());
+ assert!(
+ real.join("written.txt").is_file(),
+ "the write must follow the handle taken at the start"
+ );
+ assert!(
+ !decoy.join("written.txt").exists(),
+ "and must not follow the name to its new target"
+ );
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn creating_a_directory_that_is_already_there_is_success() {
+ let dir = tempfile::tempdir().unwrap();
+ let root = dir.path().to_path_buf();
+ let opened = DestinationRoot::open(&root).unwrap();
+ opened.create_dir(Path::new("shared")).unwrap();
+ // Merging into it again is normal.
+ opened.create_dir(Path::new("shared")).unwrap();
+
+ // A file wearing the name is a genuine clash.
+ fs::write(root.join("taken"), b"x").unwrap();
+ assert!(opened.create_dir(Path::new("taken")).is_err());
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn a_destination_reached_through_a_symlink_is_refused() {
+ let dir = tempfile::tempdir().unwrap();
+ let root = dir.path().join("dest");
+ let outside = dir.path().join("outside");
+ fs::create_dir_all(&root).unwrap();
+ fs::create_dir_all(&outside).unwrap();
+ // A link inside the destination pointing elsewhere: create_dir_all
+ // follows it without complaint, so anything written beneath would
+ // escape the folder the user chose.
+ std::os::unix::fs::symlink(&outside, root.join("escape")).unwrap();
+
+ assert!(destination_stays_within(&root, &root.join("normal.txt")));
+ assert!(!destination_stays_within(
+ &root,
+ &root.join("escape/payload.txt")
+ ));
+ }
+
+ #[test]
+ fn skipping_conflicts_drops_files_but_keeps_directories() {
+ let dir = tempfile::tempdir().unwrap();
+ let src = dir.path().join("proj");
+ fs::create_dir_all(src.join("a")).unwrap();
+ fs::write(src.join("a/keep.txt"), b"aa").unwrap();
+ fs::write(src.join("a/clash.txt"), b"bbbb").unwrap();
+
+ let plan = plan_transfer(&src).unwrap();
+ let before = plan.total_bytes;
+ assert_eq!(before, 6);
+
+ let conflicts: HashSet<PathBuf> =
+ std::iter::once(PathBuf::from("proj/a/clash.txt")).collect();
+ let skipped = apply_conflict_choice(plan.clone(), &conflicts, ConflictChoice::Skip);
+ let names = relatives(&skipped);
+ assert!(!names.iter().any(|name| name.ends_with("clash.txt")));
+ assert!(names.iter().any(|name| name.ends_with("keep.txt")));
+ assert!(
+ names.contains(&"proj/a".to_string()),
+ "the directory itself must survive so its kept children have a home"
+ );
+ assert_eq!(skipped.total_bytes, 2, "the total follows what remains");
+
+ // Overwrite keeps everything untouched.
+ let overwrite = apply_conflict_choice(plan, &conflicts, ConflictChoice::Overwrite);
+ assert_eq!(overwrite.total_bytes, before);
+ }
+}
diff --git a/wezterm-gui/src/termwindow/ui/context_menu.rs b/wezterm-gui/src/termwindow/ui/context_menu.rs
index d50dfce7..dbac7395 100644
--- a/wezterm-gui/src/termwindow/ui/context_menu.rs
+++ b/wezterm-gui/src/termwindow/ui/context_menu.rs
@@ -224,6 +224,15 @@ impl crate::TermWindow {
crate::termwindow::ContextMenuApplicationAction::DownloadRemoteFile(path) => {
self.download_right_sidebar_remote_file(path);
}
+ crate::termwindow::ContextMenuApplicationAction::CopyRemotePreviewSelection => {
+ self.copy_right_sidebar_selected_file_preview_text();
+ }
+ crate::termwindow::ContextMenuApplicationAction::CopyRemotePreviewAll => {
+ self.copy_right_sidebar_file_preview_all_text();
+ }
+ crate::termwindow::ContextMenuApplicationAction::ResolveLocalCopyConflict(choice) => {
+ self.resolve_pending_local_copy(choice);
+ }
}
}
@@ -304,7 +313,7 @@ impl crate::TermWindow {
return true;
}
- self.close_fallback_context_menu();
+ self.dismiss_fallback_context_menu();
context.invalidate();
true
}
@@ -312,7 +321,7 @@ impl crate::TermWindow {
if menu.hit_path(event.coords).is_some() {
return true;
}
- self.close_fallback_context_menu();
+ self.dismiss_fallback_context_menu();
context.invalidate();
false
}
@@ -334,6 +343,18 @@ impl crate::TermWindow {
false
}
+ /// Close a menu that the user walked away from.
+ ///
+ /// Distinct from [`Self::close_fallback_context_menu`], which also runs
+ /// immediately *before* a chosen action — cancelling there would swallow
+ /// the very choice being made.
+ pub(crate) fn dismiss_fallback_context_menu(&mut self) {
+ // A copy waiting on an answer takes dismissal as "no". Leaving the
+ // plan behind would keep it alive with no way to reach it again.
+ self.cancel_pending_local_copy();
+ self.close_fallback_context_menu();
+ }
+
pub(crate) fn close_fallback_context_menu(&mut self) {
if self.context_menu.is_none() {
return;
diff --git a/wezterm-gui/src/termwindow/ui/right_sidebar.rs b/wezterm-gui/src/termwindow/ui/right_sidebar.rs
index 96058df8..aba4d731 100644
--- a/wezterm-gui/src/termwindow/ui/right_sidebar.rs
+++ b/wezterm-gui/src/termwindow/ui/right_sidebar.rs
@@ -11,7 +11,13 @@ use crate::termwindow::remote_files::{
invalidate_remote_connection, invalidate_remote_connection_if_dead, remote_connection_key,
remote_connection_manager, reserve_download_path, RemoteAcquireError, RemoteFileBytes,
RemoteFileKind, RemoteFileRow, RemoteFilesEffect, RemoteFilesEvent, RemoteFilesPhase,
- RemotePath, RemoteTransfer, RemoteTransferKind, RemoteTransferProgress, RemoteTransferStatus,
+ RemotePath, RemoteTransfer, RemoteTransferKind, RemoteTransferProgress, RemoteTransferSource,
+ RemoteTransferStatus, REMOTE_TRANSFER_CANCELED,
+};
+use crate::termwindow::transfer_walk::{
+ apply_conflict_choice, destination_escapes_source, destination_stays_within, is_same_file,
+ plan_transfer, ConflictChoice, DestinationRoot, OverwritePolicy, TransferEntryKind,
+ TransferPlanError, TRANSFER_CONFIRM_THRESHOLD,
};
use crate::termwindow::ui::icons::{
material_file_icon_for_name, material_folder_icon_for_name, MaterialIcon, SvgIcon,
@@ -23,9 +29,9 @@ use crate::termwindow::ui::tokens::{
WINDOW_TAB_LEADING_ACTION_BUTTON_SIZE, WINDOW_TAB_LEADING_ACTION_GAP,
};
use crate::termwindow::{
- NoteEditorCommand, RightSidebarFileCharBag, RightSidebarFileField, RightSidebarFileIndex,
- RightSidebarFileIndexEntry, RightSidebarFileIndexStatus, RightSidebarFilePreviewImage,
- RightSidebarFilePreviewLine, RightSidebarFilePreviewSelection,
+ NoteEditorCommand, PendingLocalCopy, RightSidebarFileCharBag, RightSidebarFileField,
+ RightSidebarFileIndex, RightSidebarFileIndexEntry, RightSidebarFileIndexStatus,
+ RightSidebarFilePreviewImage, RightSidebarFilePreviewLine, RightSidebarFilePreviewSelection,
RightSidebarFilePreviewSelectionPoint, RightSidebarFilePreviewSliceCacheKey,
RightSidebarFilePreviewSliceCacheValue, RightSidebarFilePreviewSpan, RightSidebarFileTreeRow,
RightSidebarFileView, RightSidebarFileViewState, RightSidebarInputLayout, RightSidebarMode,
@@ -2371,24 +2377,19 @@ impl crate::TermWindow {
}
}
- pub(crate) fn copy_right_sidebar_selected_file_preview_text(&mut self) {
- if let Some(text) = self.right_sidebar_file_preview_selected_text() {
- self.copy_to_clipboard(ClipboardCopyDestination::Clipboard, text);
- return;
- }
-
+ /// Copy the whole preview, ignoring any selection. The toolbar button and
+ /// the context menu's "Copy" fall back to this when nothing is selected;
+ /// the menu also offers it outright, so it is separated out.
+ pub(crate) fn copy_right_sidebar_file_preview_all_text(&mut self) {
if self.right_sidebar_file_preview_lines.is_empty() {
return;
}
-
// Whole-buffer copy must reproduce the file, not the display: the
- // lines have tabs expanded and controls stripped for rendering, which
- // would corrupt tab-sensitive content like a Makefile.
+ // lines have tabs expanded and controls stripped for rendering.
if let Some(raw) = self.right_sidebar_file_preview_raw_text.clone() {
self.copy_to_clipboard(ClipboardCopyDestination::Clipboard, raw);
return;
}
-
let mut text = String::new();
for (idx, line) in self.right_sidebar_file_preview_lines.iter().enumerate() {
if idx > 0 {
@@ -2399,6 +2400,15 @@ impl crate::TermWindow {
self.copy_to_clipboard(ClipboardCopyDestination::Clipboard, text);
}
+ pub(crate) fn copy_right_sidebar_selected_file_preview_text(&mut self) {
+ if let Some(text) = self.right_sidebar_file_preview_selected_text() {
+ self.copy_to_clipboard(ClipboardCopyDestination::Clipboard, text);
+ return;
+ }
+ // Nothing selected means "copy what I am looking at".
+ self.copy_right_sidebar_file_preview_all_text();
+ }
+
pub(crate) fn right_sidebar_file_preview_selected_text(&self) -> Option<String> {
if !self.right_sidebar_file_preview_active() {
return None;
@@ -2784,6 +2794,18 @@ impl crate::TermWindow {
self.spawn_right_sidebar_file_index_build(root, project, true, true);
}
+ /// Re-scan after we ourselves changed the tree.
+ ///
+ /// [`Self::force_right_sidebar_file_rescan`] gives up when a scan is
+ /// already running or the index is not `Ready` — fine for a timer, wrong
+ /// here: the files we just wrote would then stay invisible until the next
+ /// 90-second tick. Re-arm the periodic cycle so the scan happens either
+ /// way.
+ pub(crate) fn force_right_sidebar_file_rescan_soon(&mut self) {
+ self.force_right_sidebar_file_rescan();
+ self.schedule_right_sidebar_file_rescan();
+ }
+
/// Refresh now (if a tree is already loaded) and (re)start the 90s periodic
/// re-scan cycle. Called on window focus and when entering the file view; a
/// fresh open builds via the normal index path, so we only force when Ready.
@@ -8976,31 +8998,12 @@ impl crate::TermWindow {
} else {
0
};
- // The strip eats into the tree, so it is capped twice: by a fixed row
- // count, and by never taking more than half of what is left. Dropping
- // thirty files at once must not collapse the tree to nothing or push
- // rows up over the header.
- let strip_budget = content_bottom
- .saturating_sub(tree_top)
- .saturating_sub(self.ui_px(SIDEBAR_INSET))
- .saturating_sub(truncated_height)
- / 2;
- let strip_rows = self
- .right_sidebar_remote_transfers
- .len()
- .min(REMOTE_TRANSFER_STRIP_MAX)
- .min(strip_budget / row_metrics.row_height.max(1));
- // When some are hidden, the last visible row reports how many rather
- // than letting them vanish silently.
- let hidden_transfers = self
- .right_sidebar_remote_transfers
- .len()
- .saturating_sub(strip_rows);
- let painted_transfers = if hidden_transfers > 0 {
- strip_rows.saturating_sub(1)
- } else {
- strip_rows
- };
+ let strip_rows = self.transfer_strip_rows(
+ content_bottom
+ .saturating_sub(tree_top)
+ .saturating_sub(self.ui_px(SIDEBAR_INSET).saturating_add(truncated_height)),
+ row_metrics.row_height,
+ );
let footer_height =
truncated_height.saturating_add(strip_rows.saturating_mul(row_metrics.row_height));
let viewport_bottom = content_bottom
@@ -9124,7 +9127,70 @@ impl crate::TermWindow {
)?;
footer_y += truncated_height;
}
- for index in 0..painted_transfers {
+ self.paint_transfer_strip(
+ layers,
+ ui_font,
+ ui_metrics,
+ chrome,
+ foreground,
+ muted_fg,
+ content_x,
+ footer_y,
+ content_width,
+ strip_rows,
+ row_metrics,
+ )?;
+ Ok(())
+ }
+
+ /// How many strip rows fit in `available` vertical pixels.
+ ///
+ /// Capped twice: by a fixed count, and by never taking more than half of
+ /// what is left. Dropping thirty files at once must not collapse the tree
+ /// to nothing or push rows up over the header.
+ fn transfer_strip_rows(&self, available: usize, row_height: usize) -> usize {
+ if self.right_sidebar_remote_transfers.is_empty() {
+ return 0;
+ }
+ self.right_sidebar_remote_transfers
+ .len()
+ .min(REMOTE_TRANSFER_STRIP_MAX)
+ .min((available / 2) / row_height.max(1))
+ }
+
+ /// Paint the transfer strip. Shared by both trees: a local copy started
+ /// from the local panel has to report itself there, not only in the remote
+ /// one where the rows happen to live.
+ #[allow(clippy::too_many_arguments)]
+ fn paint_transfer_strip(
+ &mut self,
+ layers: &mut TripleLayerQuadAllocator,
+ ui_font: &Rc<LoadedFont>,
+ ui_metrics: RenderMetrics,
+ chrome: UiPalette,
+ foreground: LinearRgba,
+ muted_fg: LinearRgba,
+ content_x: usize,
+ mut y: usize,
+ content_width: usize,
+ strip_rows: usize,
+ row_metrics: RightSidebarFileRowMetrics,
+ ) -> anyhow::Result<()> {
+ if strip_rows == 0 {
+ return Ok(());
+ }
+ // When some are hidden, the last visible row reports how many rather
+ // than letting them vanish silently.
+ let hidden = self
+ .right_sidebar_remote_transfers
+ .len()
+ .saturating_sub(strip_rows);
+ let painted = if hidden > 0 {
+ strip_rows.saturating_sub(1)
+ } else {
+ strip_rows
+ };
+ for index in 0..painted {
self.paint_remote_transfer_row(
layers,
ui_font,
@@ -9133,18 +9199,18 @@ impl crate::TermWindow {
foreground,
muted_fg,
content_x,
- footer_y,
+ y,
content_width,
index,
row_metrics,
)?;
- footer_y += row_metrics.row_height;
+ y += row_metrics.row_height;
}
- if hidden_transfers > 0 && strip_rows > 0 {
- let more = if hidden_transfers == 1 {
+ if hidden > 0 {
+ let more = if hidden == 1 {
"1 more transfer".to_string()
} else {
- format!("{hidden_transfers} more transfers")
+ format!("{hidden} more transfers")
};
self.paint_sidebar_text(
layers,
@@ -9152,11 +9218,10 @@ impl crate::TermWindow {
ui_metrics,
&more,
content_x + self.ui_px(SIDEBAR_INSET),
- footer_y
- + row_metrics
- .row_height
- .saturating_sub(ui_metrics.cell_size.height as usize)
- / 2,
+ y + row_metrics
+ .row_height
+ .saturating_sub(ui_metrics.cell_size.height as usize)
+ / 2,
content_width.saturating_sub(self.ui_px(SIDEBAR_INSET)),
muted_fg,
)?;
@@ -9192,19 +9257,25 @@ impl crate::TermWindow {
RemoteTransferStatus::Done(_) => (SvgIcon::CircleCheck, chrome.selected_bg),
// Muted rather than red, matching the panel's existing
// "Connection failed" state.
- RemoteTransferStatus::Failed(_) => (SvgIcon::CircleAlert, muted_fg),
- };
- let arrow = match transfer.kind {
- RemoteTransferKind::Upload => "Uploading",
- RemoteTransferKind::Download => "Downloading",
+ RemoteTransferStatus::Failed(_) | RemoteTransferStatus::FailedWithLeftover { .. } => {
+ (SvgIcon::CircleAlert, muted_fg)
+ }
};
+ let verb = transfer.kind.verb();
let detail = match &transfer.status {
- RemoteTransferStatus::Running => match transfer.progress.fraction() {
- Some(fraction) => format!("{arrow} {}%", (fraction * 100.0).round() as u32),
- None => arrow.to_string(),
+ RemoteTransferStatus::Running => match transfer.progress.items() {
+ // A folder reads better as "12/300" than as a percentage.
+ Some((done, total)) => format!("{verb} {done}/{total}"),
+ None => match transfer.progress.fraction() {
+ Some(fraction) => format!("{verb} {}%", (fraction * 100.0).round() as u32),
+ None => verb.to_string(),
+ },
},
RemoteTransferStatus::Done(detail) => detail.clone(),
RemoteTransferStatus::Failed(message) => message.clone(),
+ RemoteTransferStatus::FailedWithLeftover { message, leftover } => {
+ format!("{message} — {leftover} was left behind")
+ }
};
let label = format!("{} — {detail}", transfer.name);
let fraction = transfer.progress.fraction();
@@ -9774,6 +9845,20 @@ impl crate::TermWindow {
}
}
+ pub(crate) fn update_right_sidebar_local_drop_target(&mut self, coords: Option<Point>) {
+ let target = coords.and_then(|coords| self.local_drop_target_at(coords.x, coords.y));
+ if self.right_sidebar_local_drop_target != target {
+ self.right_sidebar_local_drop_target = target;
+ self.invalidate_window();
+ }
+ }
+
+ pub(crate) fn clear_right_sidebar_local_drop_target(&mut self) {
+ if self.right_sidebar_local_drop_target.take().is_some() {
+ self.invalidate_window();
+ }
+ }
+
/// Take files dropped onto the remote tree and upload them. Returns false
/// when the drop was not aimed at the panel, so the caller can fall back
/// to its usual handling.
@@ -9805,13 +9890,9 @@ impl crate::TermWindow {
return false;
};
- let mut skipped_directories = 0usize;
- let mut queued = 0usize;
for path in paths {
- // Only files: a directory needs recursive creation and a way to
- // report partial failure, which this does not have yet.
if path.is_dir() {
- skipped_directories += 1;
+ self.start_remote_folder_upload(path.clone(), directory.clone());
continue;
}
let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
@@ -9819,6 +9900,7 @@ impl crate::TermWindow {
RemoteTransferKind::Upload,
path.to_string_lossy().to_string(),
"That file name is not valid UTF-8".to_string(),
+ None,
);
continue;
};
@@ -9832,27 +9914,181 @@ impl crate::TermWindow {
RemoteTransferKind::Upload,
name.to_string(),
err,
+ None,
);
continue;
}
};
self.start_remote_upload(path.clone(), remote, directory.clone());
- queued += 1;
}
+ self.invalidate_window();
+ true
+ }
+
+ /// Walk a dropped folder and upload it as a single transfer.
+ ///
+ /// One row, not one per file: running rows are never evicted from the
+ /// strip, so a thousand-file folder would otherwise bury the panel.
+ fn start_remote_folder_upload(&mut self, source: PathBuf, directory: RemotePath) {
+ // The walk and its metadata calls must not run here: a large or
+ // network-backed tree would freeze the window for as long as it takes,
+ // before even a progress row appears.
+ let Some(window) = self.window.as_ref().cloned() else {
+ return;
+ };
+ // Remember which host the drop was aimed at. Walking is slow, and the
+ // panel can be pointed somewhere else in the meantime — uploading to
+ // whatever happens to be connected when the walk finishes would put
+ // the files on the wrong machine, at a path that means something else
+ // there.
+ let aimed_at = self.right_sidebar_remote_files.current_source_key();
+ promise::spawn::spawn(async move {
+ let planned = promise::spawn::spawn_into_new_thread(move || {
+ Ok::<_, anyhow::Error>((source.clone(), plan_transfer(&source)))
+ })
+ .await;
+ let Ok((source, plan)) = planned else {
+ return;
+ };
+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
+ term_window.apply_remote_folder_plan(source, directory, plan, aimed_at);
+ })));
+ })
+ .detach();
+ }
- if skipped_directories > 0 && queued == 0 {
+ fn apply_remote_folder_plan(
+ &mut self,
+ source: PathBuf,
+ directory: RemotePath,
+ plan: Result<
+ crate::termwindow::transfer_walk::TransferPlan,
+ crate::termwindow::transfer_walk::TransferPlanError,
+ >,
+ aimed_at: Option<String>,
+ ) {
+ let name = display_name(&source);
+ if aimed_at.is_none() || self.right_sidebar_remote_files.current_source_key() != aimed_at {
+ // Refuse rather than retarget: the same remote path on a different
+ // host is a different place entirely.
self.push_remote_transfer_failure(
RemoteTransferKind::Upload,
- if skipped_directories == 1 {
- "Folder".to_string()
- } else {
- format!("{skipped_directories} folders")
- },
- "Only files can be uploaded".to_string(),
+ name,
+ "The panel moved to another host while this folder was being read".to_string(),
+ None,
);
+ return;
}
- self.invalidate_window();
- true
+ let plan = match plan {
+ Ok(plan) => plan,
+ Err(err) => {
+ self.push_remote_transfer_failure(
+ RemoteTransferKind::Upload,
+ name,
+ err.message(),
+ None,
+ );
+ return;
+ }
+ };
+ if plan.entries.is_empty() {
+ self.push_remote_transfer_failure(
+ RemoteTransferKind::Upload,
+ name,
+ "Nothing to upload".to_string(),
+ None,
+ );
+ return;
+ }
+ // Every remote entry costs at least one round trip on a single
+ // serialized session, so a big tree is slow in a way the user cannot
+ // see coming. Say so rather than appearing to hang.
+ if plan.entries.len() > TRANSFER_CONFIRM_THRESHOLD {
+ self.push_remote_transfer_failure(
+ RemoteTransferKind::Upload,
+ name,
+ format!(
+ "That folder holds {} items; upload it in smaller pieces",
+ plan.entries.len()
+ ),
+ None,
+ );
+ return;
+ }
+
+ let Some((backend, operation_lease, connection_key, connection_id)) =
+ self.remote_transfer_handles()
+ else {
+ self.push_remote_transfer_failure(
+ RemoteTransferKind::Upload,
+ name,
+ "Remote Files connection is no longer available".to_string(),
+ None,
+ );
+ return;
+ };
+ let Some(window) = self.window.as_ref().cloned() else {
+ return;
+ };
+
+ let id = self.next_remote_transfer_id();
+ let progress = RemoteTransferProgress::default();
+ progress.set_item_total(plan.entries.len() as u64);
+ self.right_sidebar_remote_transfers.push(RemoteTransfer {
+ id,
+ kind: RemoteTransferKind::Upload,
+ name,
+ progress: progress.clone(),
+ status: RemoteTransferStatus::Running,
+ source: None,
+ });
+ self.trim_remote_transfers();
+
+ // Symlinks and unreadable nodes were deliberately left out; saying so
+ // is the difference between a truthful success and one that quietly
+ // omitted data.
+ let note = {
+ let mut parts = Vec::new();
+ if plan.skipped_symlinks > 0 {
+ parts.push(format!("{} symlink(s) skipped", plan.skipped_symlinks));
+ }
+ if plan.unreadable > 0 {
+ parts.push(format!("{} unreadable item(s)", plan.unreadable));
+ }
+ (!parts.is_empty()).then(|| parts.join(", "))
+ };
+ let entries = plan.entries;
+ let refresh_dir = directory.clone();
+ promise::spawn::spawn(async move {
+ let result = upload_tree(&*backend, &directory, &entries, &progress).await;
+ drop(operation_lease);
+ let connection_died = result.as_ref().is_err_and(|failure| {
+ invalidate_remote_connection_if_dead(
+ &connection_key,
+ connection_id,
+ &failure.message,
+ )
+ });
+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
+ let done_detail = match &note {
+ Some(note) => format!("Uploaded ({note})"),
+ None => "Uploaded".to_string(),
+ };
+ let status = transfer_status_from_result(&result, &done_detail);
+ term_window.finish_remote_transfer(id, status);
+ // Re-list either way: a partial upload leaves real files the
+ // tree would otherwise never show.
+ let effects = term_window
+ .right_sidebar_remote_files
+ .transition(RemoteFilesEvent::DirectoryInvalidated(refresh_dir));
+ term_window.apply_right_sidebar_remote_files_effects(effects);
+ if connection_died {
+ term_window.right_sidebar_remote_files_lease.take();
+ }
+ term_window.invalidate_window();
+ })));
+ })
+ .detach();
}
fn next_remote_transfer_id(&mut self) -> u64 {
@@ -9863,11 +10099,15 @@ impl crate::TermWindow {
self.right_sidebar_remote_transfer_next_id
}
+ /// A transfer that never got as far as starting. `source` is `Some` only
+ /// when retrying could plausibly do better — a rejected folder or an
+ /// unusable name has nothing to retry.
fn push_remote_transfer_failure(
&mut self,
kind: RemoteTransferKind,
name: String,
message: String,
+ source: Option<RemoteTransferSource>,
) {
let id = self.next_remote_transfer_id();
self.right_sidebar_remote_transfers.push(RemoteTransfer {
@@ -9876,6 +10116,7 @@ impl crate::TermWindow {
name,
progress: RemoteTransferProgress::default(),
status: RemoteTransferStatus::Failed(message),
+ source,
});
self.trim_remote_transfers();
}
@@ -9897,13 +10138,21 @@ impl crate::TermWindow {
fn start_remote_upload(&mut self, local: PathBuf, remote: RemotePath, directory: RemotePath) {
let name = remote.file_name().to_string();
+ let retry = RemoteTransferSource::Upload {
+ local: local.clone(),
+ remote: remote.clone(),
+ directory: directory.clone(),
+ };
let Some((backend, operation_lease, connection_key, connection_id)) =
self.remote_transfer_handles()
else {
+ // A missing lease is exactly the kind of failure retrying fixes,
+ // once the panel has reconnected.
self.push_remote_transfer_failure(
RemoteTransferKind::Upload,
name,
"Remote Files connection is no longer available".to_string(),
+ Some(retry),
);
return;
};
@@ -9919,28 +10168,36 @@ impl crate::TermWindow {
name,
progress: progress.clone(),
status: RemoteTransferStatus::Running,
+ source: Some(retry),
});
self.trim_remote_transfers();
promise::spawn::spawn(async move {
- let result = backend.upload_file(local, remote, progress).await;
+ // A single dropped file refuses to clobber; there is no prompt on
+ // this path, so silently replacing would be a choice the user
+ // never made.
+ let result = backend.upload_file(local, remote, progress, false).await;
drop(operation_lease);
- let connection_died = result.as_ref().is_err_and(|message| {
- invalidate_remote_connection_if_dead(&connection_key, connection_id, message)
+ let connection_died = result.as_ref().is_err_and(|failure| {
+ invalidate_remote_connection_if_dead(
+ &connection_key,
+ connection_id,
+ &failure.message,
+ )
});
window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
- let status = match &result {
- Ok(_) => RemoteTransferStatus::Done("Uploaded".to_string()),
- Err(message) => RemoteTransferStatus::Failed(message.clone()),
- };
+ let succeeded = result.is_ok();
+ let status = transfer_status_from_result(&result, "Uploaded");
term_window.finish_remote_transfer(id, status);
- if result.is_ok() {
- // Show the new file without collapsing the rest of the tree.
- let effects = term_window
- .right_sidebar_remote_files
- .transition(RemoteFilesEvent::DirectoryInvalidated(directory));
- term_window.apply_right_sidebar_remote_files_effects(effects);
- } else if connection_died {
+ // Re-list either way. On failure the directory may now hold a
+ // partial file the tree would otherwise never show — and the
+ // user would then hit "already exists" on retry with nothing
+ // on screen to explain it.
+ let effects = term_window
+ .right_sidebar_remote_files
+ .transition(RemoteFilesEvent::DirectoryInvalidated(directory));
+ term_window.apply_right_sidebar_remote_files_effects(effects);
+ if !succeeded && connection_died {
term_window.right_sidebar_remote_files_lease.take();
}
term_window.invalidate_window();
@@ -9975,25 +10232,371 @@ impl crate::TermWindow {
self.show_term_context_menu(context, anchor, vec![item]);
}
- pub(crate) fn download_right_sidebar_remote_file(&mut self, remote: RemotePath) {
- let name = remote.file_name().to_string();
- let Some(directory) = dirs_next::download_dir()
- .or_else(|| dirs_next::home_dir().map(|home| home.join("Downloads")))
- else {
- self.push_remote_transfer_failure(
- RemoteTransferKind::Download,
- name,
- "Unable to locate a Downloads folder".to_string(),
- );
+ /// Which local directory a pointer at `(x, y)` is aiming at.
+ pub(crate) fn local_drop_target_at(&self, x: isize, y: isize) -> Option<PathBuf> {
+ if !self.right_sidebar_file_view_active()
+ || self.right_sidebar_remote_files.target.is_some()
+ {
+ return None;
+ }
+ let root = self.active_local_project_for_files().ok()?.path;
+ // Look the row up in what was actually painted rather than asking the
+ // filesystem: a syscall per drag event on the GUI thread is wasteful,
+ // and the index's children map has no key for empty directories.
+ let rows = if self.right_sidebar_file_search_rows.is_empty() {
+ &self.right_sidebar_file_browse_rows
+ } else {
+ &self.right_sidebar_file_search_rows
+ };
+ resolve_local_drop_target(&self.ui_items, x, y, &root, |path| {
+ if path == root {
+ return Some(true);
+ }
+ rows.iter()
+ .find(|row| row.path == path)
+ .map(|row| row.is_dir)
+ })
+ }
+
+ /// Copy files or folders dropped from the OS into the local Files panel.
+ /// Returns false when the drop was not aimed here.
+ pub(crate) fn copy_dropped_files_into_local_panel(
+ &mut self,
+ paths: &[PathBuf],
+ coords: Option<Point>,
+ ) -> bool {
+ self.clear_right_sidebar_local_drop_target();
+ let Some(coords) = coords else {
+ return false;
+ };
+ let Some(directory) = self.local_drop_target_at(coords.x, coords.y) else {
+ return false;
+ };
+ // A new drop supersedes any earlier one still waiting on an answer.
+ // The fallback menu clears it on dismissal, but macOS hands the menu
+ // to the system and reports only chosen actions, so a dismissed native
+ // prompt has no other way to release its plan.
+ self.cancel_pending_local_copy();
+ self.local_copy_generation = self.local_copy_generation.wrapping_add(1);
+ let generation = self.local_copy_generation;
+ self.begin_local_copy(paths.to_vec(), directory, coords, generation);
+ true
+ }
+
+ /// Plan the drop on a worker, then come back to ask about conflicts.
+ ///
+ /// The walk and its `metadata` calls must not run on the GUI thread: a
+ /// large or network-backed tree would freeze the window for as long as it
+ /// takes, before even the progress row appears.
+ fn begin_local_copy(
+ &mut self,
+ sources: Vec<PathBuf>,
+ directory: PathBuf,
+ anchor: Point,
+ generation: u64,
+ ) {
+ let Some(window) = self.window.as_ref().cloned() else {
return;
};
- if let Err(err) = fs::create_dir_all(&directory) {
+ let plan_dir = directory.clone();
+ promise::spawn::spawn(async move {
+ let preflight = promise::spawn::spawn_into_new_thread(move || {
+ Ok::<_, anyhow::Error>(preflight_local_copy(&sources, &plan_dir))
+ })
+ .await;
+ let Ok(preflight) = preflight else {
+ return;
+ };
+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
+ term_window.apply_local_copy_preflight(preflight, directory, anchor, generation);
+ })));
+ })
+ .detach();
+ }
+
+ fn apply_local_copy_preflight(
+ &mut self,
+ preflight: crate::termwindow::transfer_walk::TransferPreflight,
+ directory: PathBuf,
+ anchor: Point,
+ generation: u64,
+ ) {
+ // A slower walk from an earlier drop must not replace a newer prompt.
+ if generation != self.local_copy_generation {
+ return;
+ }
+ for (name, reason) in &preflight.rejected {
self.push_remote_transfer_failure(
- RemoteTransferKind::Download,
- name,
- format!("Unable to use {}: {err}", directory.display()),
+ RemoteTransferKind::LocalCopy,
+ name.clone(),
+ reason.clone(),
+ None,
);
- return;
+ }
+ if preflight.plans.is_empty() {
+ self.invalidate_window();
+ return;
+ }
+ let note = preflight.omission_note();
+ if preflight.conflicts.is_empty() {
+ // Nothing was in the way when we looked, so nothing may be
+ // replaced: anything there now arrived since, unauthorized.
+ self.run_local_copy(preflight.plans, directory, OverwritePolicy::NoClobber, note);
+ } else {
+ // Show first, then record: opening a menu closes any previous
+ // one, and that teardown is where an unanswered plan is dropped —
+ // so storing the plan beforehand would have it clear itself.
+ let count = preflight.conflicts.len();
+ if let Some(window) = self.window.as_ref().cloned() {
+ self.show_local_copy_conflict_menu(&window, anchor, count);
+ }
+ self.pending_local_copy_conflict_count = count;
+ self.pending_local_copy = Some(PendingLocalCopy {
+ plans: preflight.plans,
+ directory,
+ conflicts: preflight.conflicts,
+ anchor,
+ note,
+ });
+ }
+ self.invalidate_window();
+ }
+ pub(crate) fn show_local_copy_conflict_menu(
+ &mut self,
+ context: &dyn WindowOps,
+ anchor: Point,
+ count: usize,
+ ) {
+ // The count goes into each label rather than a heading row: every
+ // option then says exactly what it will do, and there is no inert row
+ // for the user to try clicking.
+ let noun = if count == 1 { "file" } else { "files" };
+
+ // One pass: beginning the block clears the action table, so minting an
+ // item after a second call would leave the earlier ones dead.
+ self.begin_context_menu_application_actions();
+ let overwrite = self.context_menu_application_item_with_icon(
+ format!("Replace {count} existing {noun}"),
+ ContextMenuIcon::Save,
+ crate::termwindow::ContextMenuApplicationAction::ResolveLocalCopyConflict(
+ ConflictChoice::Overwrite,
+ ),
+ true,
+ );
+ let skip = self.context_menu_application_item_with_icon(
+ format!("Skip {count} existing {noun}"),
+ ContextMenuIcon::Check,
+ crate::termwindow::ContextMenuApplicationAction::ResolveLocalCopyConflict(
+ ConflictChoice::Skip,
+ ),
+ true,
+ );
+ let cancel = self.context_menu_application_item_with_icon(
+ "Cancel the copy",
+ ContextMenuIcon::Close,
+ crate::termwindow::ContextMenuApplicationAction::ResolveLocalCopyConflict(
+ ConflictChoice::Cancel,
+ ),
+ true,
+ );
+ self.show_term_context_menu(context, anchor, vec![overwrite, skip, cancel]);
+ }
+
+ /// Resolve a queued copy once the user has answered the conflict prompt.
+ /// Resolve a queued copy once the user has answered the conflict prompt.
+ pub(crate) fn resolve_pending_local_copy(&mut self, choice: ConflictChoice) {
+ let Some(pending) = self.pending_local_copy.take() else {
+ return;
+ };
+ let policy = match choice {
+ ConflictChoice::Cancel => {
+ self.invalidate_window();
+ return;
+ }
+ ConflictChoice::Overwrite => OverwritePolicy::Replace,
+ ConflictChoice::Skip => OverwritePolicy::SkipExisting,
+ };
+ let PendingLocalCopy {
+ plans,
+ directory,
+ conflicts,
+ anchor: _,
+ note,
+ } = pending;
+ let plans = plans
+ .into_iter()
+ .map(|(source, plan)| (source, apply_conflict_choice(plan, &conflicts, choice)))
+ .collect();
+ self.run_local_copy(plans, directory, policy, note);
+ }
+
+ /// Drop a queued copy that was never answered.
+ ///
+ /// A context menu can be dismissed without choosing anything; leaving the
+ /// plan behind means the next, unrelated drop would silently reopen the
+ /// old prompt at the new location.
+ pub(crate) fn cancel_pending_local_copy(&mut self) {
+ if self.pending_local_copy.take().is_some() {
+ self.invalidate_window();
+ }
+ }
+
+ /// Run the whole drop in ONE worker.
+ ///
+ /// One thread for the batch, not one per dropped path: a multi-select of a
+ /// few hundred files would otherwise spawn a few hundred threads, all
+ /// fighting for the same disk.
+ fn run_local_copy(
+ &mut self,
+ plans: Vec<(PathBuf, crate::termwindow::transfer_walk::TransferPlan)>,
+ directory: PathBuf,
+ policy: OverwritePolicy,
+ note: Option<String>,
+ ) {
+ let Some(window) = self.window.as_ref().cloned() else {
+ return;
+ };
+ let entries: Vec<_> = plans
+ .into_iter()
+ .flat_map(|(_, plan)| plan.entries.into_iter())
+ .collect();
+ if entries.is_empty() {
+ return;
+ }
+
+ let id = self.next_remote_transfer_id();
+ let progress = RemoteTransferProgress::default();
+ progress.set_item_total(entries.len() as u64);
+ self.right_sidebar_remote_transfers.push(RemoteTransfer {
+ id,
+ kind: RemoteTransferKind::LocalCopy,
+ name: display_name(&directory),
+ progress: progress.clone(),
+ status: RemoteTransferStatus::Running,
+ source: None,
+ });
+ self.trim_remote_transfers();
+ self.invalidate_window();
+
+ promise::spawn::spawn(async move {
+ let result = promise::spawn::spawn_into_new_thread(move || {
+ // Pin the destination once for the whole batch. Re-opening it
+ // per entry would leave the root's own ancestors free to be
+ // swapped between operations.
+ let root = match DestinationRoot::open(&directory) {
+ Ok(root) => root,
+ Err(err) => {
+ return Ok::<_, anyhow::Error>(Err(format!(
+ "Unable to use {}: {err}",
+ directory.display()
+ )))
+ }
+ };
+ Ok(copy_entries_blocking(&entries, &root, policy, &progress))
+ })
+ .await
+ .unwrap_or_else(|err| Err(format!("Copy failed: {err}")));
+
+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
+ let status = match result {
+ Ok(copied) => {
+ let mut detail = format!("Copied {copied} items");
+ if let Some(note) = note {
+ detail.push_str(&format!(" ({note})"));
+ }
+ RemoteTransferStatus::Done(detail)
+ }
+ Err(message) => RemoteTransferStatus::Failed(message),
+ };
+ term_window.finish_remote_transfer(id, status);
+ term_window.force_right_sidebar_file_rescan_soon();
+ term_window.invalidate_window();
+ })));
+ })
+ .detach();
+ }
+
+ /// Right-clicking inside a *remote* file preview. The local preview offers
+ /// "Open With", which is meaningless for a file that is not on this disk —
+ /// so rather than the previous bail-out (right-click simply did nothing on
+ /// a remote preview), give it a menu of things that do apply.
+ pub(crate) fn show_right_sidebar_remote_file_preview_context_menu(
+ &mut self,
+ context: &dyn WindowOps,
+ anchor: Point,
+ ) {
+ let Some(path) = self.right_sidebar_remote_files.selected.clone() else {
+ return;
+ };
+ // Snapshot the gating up front: the item builders below take `&mut
+ // self`, so reading these inline would fight the borrow checker.
+ let has_selection = self.right_sidebar_file_preview_selected_text().is_some();
+ let has_text = self.right_sidebar_file_preview_image.is_none()
+ && !self.right_sidebar_file_preview_lines.is_empty();
+ let can_download = self.right_sidebar_remote_files_lease.is_some();
+ let path_string = path.as_str().to_string();
+
+ // Every application action has to be minted in one pass: beginning the
+ // block clears the whole table, so a second call mid-assembly would
+ // turn the earlier items into dead entries.
+ self.begin_context_menu_application_actions();
+ let copy_selection = self.context_menu_application_item_with_icon(
+ "Copy",
+ ContextMenuIcon::Copy,
+ crate::termwindow::ContextMenuApplicationAction::CopyRemotePreviewSelection,
+ has_selection,
+ );
+ let copy_all = self.context_menu_application_item_with_icon(
+ "Copy All",
+ ContextMenuIcon::Copy,
+ crate::termwindow::ContextMenuApplicationAction::CopyRemotePreviewAll,
+ has_text,
+ );
+ let download = self.context_menu_application_item_with_icon(
+ "Download",
+ ContextMenuIcon::Save,
+ crate::termwindow::ContextMenuApplicationAction::DownloadRemoteFile(path),
+ can_download,
+ );
+
+ let items = vec![
+ copy_selection,
+ copy_all,
+ ContextMenuItem::item_with_icon(
+ "Copy Path",
+ ContextMenuIcon::Copy,
+ KeyAssignment::CopyFilePathToClipboard(path_string),
+ ),
+ ContextMenuItem::Separator,
+ download,
+ ];
+ self.show_term_context_menu(context, anchor, items);
+ }
+
+ pub(crate) fn download_right_sidebar_remote_file(&mut self, remote: RemotePath) {
+ let name = remote.file_name().to_string();
+ let retry = RemoteTransferSource::Download {
+ remote: remote.clone(),
+ };
+ let Some(directory) = crate::native_settings::effective_remote_download_directory() else {
+ // No Downloads folder is an environment problem, not a transient
+ // one; retrying would fail the same way.
+ self.push_remote_transfer_failure(
+ RemoteTransferKind::Download,
+ name,
+ "Unable to locate a Downloads folder".to_string(),
+ None,
+ );
+ return;
+ };
+ if let Err(err) = fs::create_dir_all(&directory) {
+ self.push_remote_transfer_failure(
+ RemoteTransferKind::Download,
+ name,
+ format!("Unable to use {}: {err}", directory.display()),
+ Some(retry),
+ );
+ return;
}
// Claim the destination and its staging file together, by creating the
// staging file exclusively. Two downloads that would land on the same
@@ -10015,6 +10618,7 @@ impl crate::TermWindow {
RemoteTransferKind::Download,
name,
format!("Unable to find a free name in {}", directory.display()),
+ Some(retry),
);
return;
};
@@ -10038,6 +10642,7 @@ impl crate::TermWindow {
RemoteTransferKind::Download,
name,
"Remote Files connection is no longer available".to_string(),
+ Some(retry),
);
return;
};
@@ -10054,6 +10659,7 @@ impl crate::TermWindow {
name,
progress: progress.clone(),
status: RemoteTransferStatus::Running,
+ source: Some(retry),
});
self.trim_remote_transfers();
self.invalidate_window();
@@ -10062,20 +10668,19 @@ impl crate::TermWindow {
let landed = local.clone();
let result = backend.download_file(remote, local, progress).await;
drop(operation_lease);
- let connection_died = result.as_ref().is_err_and(|message| {
- invalidate_remote_connection_if_dead(&connection_key, connection_id, message)
+ let connection_died = result.as_ref().is_err_and(|failure| {
+ invalidate_remote_connection_if_dead(
+ &connection_key,
+ connection_id,
+ &failure.message,
+ )
});
window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
- let status = match &result {
- Ok(_) => RemoteTransferStatus::Done(format!(
- "Saved to {}",
- landed
- .parent()
- .map(|parent| parent.display().to_string())
- .unwrap_or_else(|| landed.display().to_string())
- )),
- Err(message) => RemoteTransferStatus::Failed(message.clone()),
- };
+ let landed_in = landed
+ .parent()
+ .map(|parent| parent.display().to_string())
+ .unwrap_or_else(|| landed.display().to_string());
+ let status = transfer_status_from_result(&result, &format!("Saved to {landed_in}"));
term_window.finish_remote_transfer(id, status);
if connection_died {
term_window.right_sidebar_remote_files_lease.take();
@@ -10537,7 +11142,17 @@ impl crate::TermWindow {
}
let row_metrics = right_sidebar_file_row_metrics(ui_metrics);
- let viewport_bottom = content_bottom.saturating_sub(self.ui_px(SIDEBAR_INSET));
+ // A copy started here must report itself here; the strip is shared
+ // with the remote tree, so reserve its space the same way.
+ let strip_rows = self.transfer_strip_rows(
+ content_bottom
+ .saturating_sub(tree_top)
+ .saturating_sub(self.ui_px(SIDEBAR_INSET)),
+ row_metrics.row_height,
+ );
+ let viewport_bottom = content_bottom
+ .saturating_sub(self.ui_px(SIDEBAR_INSET))
+ .saturating_sub(strip_rows.saturating_mul(row_metrics.row_height));
let visible_height = viewport_bottom.saturating_sub(tree_top);
let total_height = row_count.saturating_mul(row_metrics.row_height);
let max_scroll = total_height.saturating_sub(visible_height) as f32;
@@ -10650,6 +11265,20 @@ impl crate::TermWindow {
)?;
}
+ self.paint_transfer_strip(
+ layers,
+ ui_font,
+ ui_metrics,
+ chrome,
+ foreground,
+ muted_fg,
+ content_x,
+ viewport_bottom,
+ content_width,
+ strip_rows,
+ row_metrics,
+ )?;
+
Ok(())
}
@@ -10814,7 +11443,10 @@ impl crate::TermWindow {
}
let hovered = self.is_pointer_over_ui_rect(x, visible_y, width, visible_height);
let is_selected = selected.is_some_and(|path| path == &row.path);
- if hovered || is_selected {
+ // A drag hovering here is about to copy into this directory; say so
+ // unmistakably, outranking the ordinary selection tint.
+ let is_drop_target = self.right_sidebar_local_drop_target.as_ref() == Some(&row.path);
+ if hovered || is_selected || is_drop_target {
self.fill_rounded_rectangle(
layers,
1,
@@ -10824,7 +11456,9 @@ impl crate::TermWindow {
width as f32,
visible_height as f32,
),
- if is_selected {
+ if is_drop_target {
+ chrome.selected_bg
+ } else if is_selected {
chrome.selected_bg.mul_alpha(0.46)
} else {
chrome.sidebar_button_hover_bg
@@ -13619,6 +14253,416 @@ fn file_row_placement(
}
}
+/// Turn a finished transfer into the status its row will show. Keeps the
+/// "something was left behind" case from being flattened into a plain failure,
+/// which is the difference between the user knowing to go delete a partial
+/// file and finding it months later.
+fn transfer_status_from_result(
+ result: &Result<u64, crate::termwindow::remote_files::TransferFailure>,
+ done_detail: &str,
+) -> RemoteTransferStatus {
+ match result {
+ Ok(_) => RemoteTransferStatus::Done(done_detail.to_string()),
+ Err(failure) => match &failure.leftover {
+ Some(leftover) => RemoteTransferStatus::FailedWithLeftover {
+ message: failure.message.clone(),
+ leftover: leftover.clone(),
+ },
+ None => RemoteTransferStatus::Failed(failure.message.clone()),
+ },
+ }
+}
+
+/// Upload a planned tree, stopping at the first failure.
+///
+/// Entries arrive parents-first, so each directory exists before anything is
+/// placed in it. Cancellation is checked per entry rather than only per 256KiB
+/// chunk: a tree of small files never reaches the chunk check, so a cancel
+/// would otherwise look like a hang.
+async fn upload_tree(
+ backend: &dyn crate::termwindow::remote_files::RemoteFileBackend,
+ directory: &RemotePath,
+ entries: &[crate::termwindow::transfer_walk::TransferEntry],
+ progress: &RemoteTransferProgress,
+) -> Result<u64, crate::termwindow::remote_files::TransferFailure> {
+ use crate::termwindow::remote_files::TransferFailure;
+
+ let mut uploaded = 0u64;
+ for (index, entry) in entries.iter().enumerate() {
+ if progress.is_canceled() {
+ return Err(TransferFailure::new(format!(
+ "{REMOTE_TRANSFER_CANCELED} — stopped after {index} of {}",
+ entries.len()
+ )));
+ }
+ // Rebuild the remote path one component at a time: a local relative
+ // path may hold separators this platform accepts but SFTP must not see
+ // spliced in, and `join_name` rejects `..` and empty components.
+ let mut destination = directory.clone();
+ for component in entry.relative.components() {
+ let Some(name) = component.as_os_str().to_str() else {
+ return Err(TransferFailure::new(format!(
+ "{} is not a valid name to send",
+ entry.relative.display()
+ )));
+ };
+ destination = destination
+ .join_name(name)
+ .map_err(|err| TransferFailure::new(err))?;
+ }
+
+ match entry.kind {
+ TransferEntryKind::Directory => {
+ backend
+ .create_directory(destination)
+ .await
+ .map_err(|message| {
+ TransferFailure::new(format!(
+ "{message} — stopped after {index} of {}",
+ entries.len()
+ ))
+ })?;
+ }
+ TransferEntryKind::File => {
+ // Overwriting is not offered yet for remote folders, so a name
+ // already in use stops the transfer rather than replacing
+ // something the user never agreed to lose.
+ let written = backend
+ .upload_file(entry.source.clone(), destination, progress.clone(), false)
+ .await
+ .map_err(|mut failure| {
+ failure.message = format!(
+ "{} — stopped after {index} of {}",
+ failure.message,
+ entries.len()
+ );
+ failure
+ })?;
+ uploaded = uploaded.saturating_add(written);
+ }
+ }
+ progress.finish_item();
+ }
+ Ok(uploaded)
+}
+
+fn display_name(path: &Path) -> String {
+ path.file_name()
+ .map(|name| name.to_string_lossy().to_string())
+ .unwrap_or_else(|| path.display().to_string())
+}
+
+/// Walk every dropped path and find what already exists, all off the GUI
+/// thread. Rejections are collected rather than thrown, so one bad source does
+/// not sink the rest of a multi-select.
+fn preflight_local_copy(
+ sources: &[PathBuf],
+ directory: &Path,
+) -> crate::termwindow::transfer_walk::TransferPreflight {
+ use crate::termwindow::transfer_walk::TransferPreflight;
+
+ let mut preflight = TransferPreflight::default();
+ // Two sources in one drop can plan the same destination name; the second
+ // would then silently land on the first.
+ let mut claimed: HashSet<PathBuf> = HashSet::new();
+
+ for source in sources {
+ let name = display_name(source);
+ if source.is_dir() && destination_escapes_source(source, directory) {
+ preflight
+ .rejected
+ .push((name, TransferPlanError::DestinationInsideSource.message()));
+ continue;
+ }
+ match plan_transfer(source) {
+ Ok(plan) if plan.entries.is_empty() => {
+ preflight
+ .rejected
+ .push((name, "Nothing to copy".to_string()));
+ }
+ Ok(plan) => {
+ preflight.skipped_symlinks += plan.skipped_symlinks;
+ preflight.unreadable += plan.unreadable;
+ let mut collision = None;
+ for entry in &plan.entries {
+ // Directories take part in the claim too: a `foo/` from one
+ // source and a `foo` file from another want the same name,
+ // and only one of them can have it.
+ if !claimed.insert(entry.relative.clone()) {
+ collision = Some(entry.relative.clone());
+ break;
+ }
+ if entry.kind != TransferEntryKind::File {
+ continue;
+ }
+ let destination = directory.join(&entry.relative);
+ // Dropping a file back into the folder it already lives in
+ // would have `fs::copy` truncate the shared inode and then
+ // report success on the resulting empty file.
+ if is_same_file(&entry.source, &destination) {
+ collision = Some(entry.relative.clone());
+ break;
+ }
+ if destination.exists() {
+ preflight.conflicts.insert(entry.relative.clone());
+ }
+ }
+ if let Some(relative) = collision {
+ preflight.rejected.push((
+ name,
+ format!(
+ "{} is already where it would be copied to",
+ relative.display()
+ ),
+ ));
+ continue;
+ }
+ preflight.plans.push((source.clone(), plan));
+ }
+ Err(err) => preflight.rejected.push((name, err.message())),
+ }
+ }
+ preflight
+}
+
+/// Bytes moved per read/write while copying locally. Small enough that a
+/// cancel is noticed promptly even inside one very large file.
+const LOCAL_COPY_CHUNK: usize = 512 * 1024;
+
+/// Copy a planned tree, stopping at the first failure.
+///
+/// Stopping rather than continuing is deliberate: what has already landed is
+/// kept, and the user is told how far it got. Rolling back would mean deleting
+/// files to recover from an error — more dangerous than the error.
+fn copy_entries_blocking(
+ entries: &[crate::termwindow::transfer_walk::TransferEntry],
+ root: &DestinationRoot,
+ policy: OverwritePolicy,
+ progress: &RemoteTransferProgress,
+) -> Result<usize, String> {
+ let mut copied = 0usize;
+ for entry in entries {
+ if progress.is_canceled() {
+ return Err(format!(
+ "{} — stopped after {copied} of {}",
+ REMOTE_TRANSFER_CANCELED,
+ entries.len()
+ ));
+ }
+ let destination = root.join(&entry.relative);
+ // A cheap, clear rejection before any work starts. The guarantee comes
+ // from the handle-based descent below, not from this.
+ if !destination_stays_within(root.path(), &destination) {
+ return Err(format!(
+ "{} would be written outside the destination folder",
+ entry.relative.display()
+ ));
+ }
+
+ match entry.kind {
+ TransferEntryKind::Directory => {
+ // Descends through directory handles, so a symlink planted at
+ // any level fails rather than redirecting the write.
+ root.create_dir(&entry.relative)
+ .map_err(|err| format!("Unable to create {}: {err}", destination.display()))?;
+ }
+ TransferEntryKind::File => {
+ // Last line of defence against a file copied over itself.
+ // Covers plain paths, symlink aliases, and hard links — any of
+ // which would have the write destroy the source.
+ if is_same_file(&entry.source, &destination) {
+ return Err(format!(
+ "{} is already at the destination",
+ entry.source.display()
+ ));
+ }
+ // Under NoClobber a file that appeared after the preflight was
+ // never authorized for replacement; under SkipExisting the
+ // user said to leave it. Both come back as a skip, decided by
+ // the filesystem rather than by a check that could be raced.
+ match copy_file_chunked(&entry.source, root, &entry.relative, policy, progress) {
+ Ok(true) => copied += 1,
+ Ok(false) => {}
+ Err(err) => {
+ return Err(format!(
+ "{err} — stopped after {copied} of {}",
+ entries.len()
+ ))
+ }
+ }
+ }
+ }
+ progress.finish_item();
+ }
+ Ok(copied)
+}
+
+/// Copy one file, checking for a cancel between chunks.
+///
+/// `fs::copy` would be shorter but blocks until the whole file is done, so a
+/// cancel during a multi-gigabyte file is never seen and the transfer goes on
+/// to report success.
+/// Returns whether the file was actually written; `false` means the
+/// destination was already taken and the policy said to leave it.
+///
+/// `relative` names the file inside `root`; both are needed because the write
+/// descends from `root` through directory handles rather than resolving the
+/// joined path, which is what stops a symlink swapped in mid-copy from
+/// redirecting it.
+fn copy_file_chunked(
+ source: &Path,
+ root: &DestinationRoot,
+ relative: &Path,
+ policy: OverwritePolicy,
+ progress: &RemoteTransferProgress,
+) -> Result<bool, String> {
+ let destination = root.join(relative);
+ let mut reader = fs::File::open(source)
+ .map_err(|err| format!("Unable to read {}: {err}", source.display()))?;
+
+ match policy {
+ // Nothing may be displaced, so let the *filesystem* enforce that: an
+ // exclusive create fails atomically if anything is already there, and
+ // cannot follow a symlink sitting at that name. A check-then-create
+ // would leave a window for a file to appear and be truncated.
+ OverwritePolicy::NoClobber | OverwritePolicy::SkipExisting => {
+ let writer = match root.create_file(relative) {
+ Ok(writer) => writer,
+ // Refusing is the whole point here, and it is reported as a
+ // skip rather than an error — but only for this one reason,
+ // so a permission problem still surfaces.
+ Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => return Ok(false),
+ Err(err) => {
+ return Err(format!("Unable to create {}: {err}", destination.display()))
+ }
+ };
+ stream_into(&mut reader, writer, source, &destination, progress)
+ .inspect_err(|_| {
+ // Through the handle as well: cleanup runs exactly when
+ // something has gone wrong, which is the worst moment to
+ // start trusting a path again.
+ let _ = root.remove_file(relative);
+ })
+ .map(|()| true)
+ }
+ // The user asked to replace. Build the replacement beside the target
+ // and swap it in at the end: the original survives a failure or a
+ // cancel, and the rename replaces the directory entry rather than
+ // following a symlink that happens to occupy the name.
+ OverwritePolicy::Replace => {
+ let (staging_relative, writer) = create_staging_file(root, relative)?;
+ let staging = root.join(&staging_relative);
+ let outcome =
+ stream_into(&mut reader, writer, source, &staging, progress).and_then(|()| {
+ root.rename(&staging_relative, relative).map_err(|err| {
+ format!("Unable to replace {}: {err}", destination.display())
+ })
+ });
+ if outcome.is_err() {
+ // Through the handle, like every other write: cleanup runs
+ // exactly when something has gone wrong, which is the worst
+ // moment to start trusting a path again.
+ let _ = root.remove_file(&staging_relative);
+ }
+ outcome.map(|()| true)
+ }
+ }
+}
+
+/// Create a uniquely named sibling of the destination to assemble a
+/// replacement in, returning its path relative to `root`. A sibling, not a
+/// temp directory, so the finishing rename stays on one filesystem and is
+/// therefore atomic.
+fn create_staging_file(
+ root: &DestinationRoot,
+ relative: &Path,
+) -> Result<(PathBuf, fs::File), String> {
+ let parent = relative.parent().unwrap_or_else(|| Path::new(""));
+ let name = relative
+ .file_name()
+ .map(|name| name.to_string_lossy().to_string())
+ .ok_or_else(|| format!("{} has no file name", relative.display()))?;
+ for attempt in 0..1_000u32 {
+ let candidate = parent.join(format!(".{name}.thinkterm-{attempt}"));
+ match root.create_file(&candidate) {
+ Ok(file) => return Ok((candidate, file)),
+ Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => continue,
+ Err(err) => {
+ return Err(format!(
+ "Unable to write beside {}: {err}",
+ relative.display()
+ ))
+ }
+ }
+ }
+ Err(format!(
+ "Unable to find a free staging name beside {}",
+ relative.display()
+ ))
+}
+
+/// Stream `reader` into `writer`, checking for a cancel between chunks.
+fn stream_into(
+ reader: &mut fs::File,
+ mut writer: fs::File,
+ source: &Path,
+ written_to: &Path,
+ progress: &RemoteTransferProgress,
+) -> Result<(), String> {
+ use std::io::Write;
+
+ let mut buffer = vec![0u8; LOCAL_COPY_CHUNK];
+ loop {
+ if progress.is_canceled() {
+ return Err(REMOTE_TRANSFER_CANCELED.to_string());
+ }
+ let read = reader
+ .read(&mut buffer)
+ .map_err(|err| format!("Unable to read {}: {err}", source.display()))?;
+ if read == 0 {
+ break;
+ }
+ writer
+ .write_all(&buffer[..read])
+ .map_err(|err| format!("Unable to write {}: {err}", written_to.display()))?;
+ }
+ writer
+ .flush()
+ .map_err(|err| format!("Unable to finish {}: {err}", written_to.display()))
+}
+
+/// The local counterpart of [`resolve_remote_drop_target`]. Same rule, and
+/// deliberately the same shape so the two cannot drift: a directory row takes
+/// the drop itself, a file row hands it to the directory holding it, anywhere
+/// else inside the panel takes the root.
+fn resolve_local_drop_target(
+ items: &[UIItem],
+ x: isize,
+ y: isize,
+ root: &Path,
+ is_dir: impl Fn(&Path) -> Option<bool>,
+) -> Option<PathBuf> {
+ let item = items.iter().rev().find(|item| item.hit_test(x, y))?;
+ match &item.item_type {
+ UIItemType::RightSidebarFileRow(path) => match is_dir(path) {
+ Some(true) => Some(path.clone()),
+ Some(false) => Some(path.parent().map(Path::to_path_buf).unwrap_or_else(|| {
+ // A row with no parent should not exist, but falling back to
+ // the root is better than dropping the file somewhere odd.
+ root.to_path_buf()
+ })),
+ // A row painted from a listing that has since been dropped:
+ // guessing could put the file somewhere unintended.
+ None => None,
+ },
+ UIItemType::RightSidebarBackground
+ | UIItemType::RightSidebarFileFilter
+ | UIItemType::RightSidebarFileRefresh
+ | UIItemType::RightSidebarRemoteTransfer(_) => Some(root.to_path_buf()),
+ _ => None,
+ }
+}
+
/// Where a drop at `(x, y)` would land, given the UI items from the last
/// paint. A directory row takes the file itself; a file row takes the
/// directory holding it, which is what "drop it next to this" means; anywhere
@@ -14590,24 +15634,28 @@ fn snippet_cursor_visible(now_ms: u128, blink_ms: u64) -> bool {
mod tests {
use super::{
approximate_note_text_width, build_right_sidebar_file_index, clip_note_texture,
- file_preview_close_requires_reflow, file_release_action, file_row_placement,
- full_line_colors_by_byte, image_pixels_within_preview_budget, load_file_preview,
- load_file_preview_image, naturalish_cmp, note_code_highlight_key,
- note_code_highlight_lines, note_code_row_height, note_image_display_size,
- note_open_pending_for_vault, note_release_action, open_with_candidate_allowed, path_key,
- preview_line_count, preview_lines_from_text, preview_plain_lines_from_text,
- preview_text_range, preview_visible_colored, preview_visible_line_range,
+ copy_entries_blocking, copy_file_chunked, file_preview_close_requires_reflow,
+ file_release_action, file_row_placement, full_line_colors_by_byte,
+ image_pixels_within_preview_budget, load_file_preview, load_file_preview_image,
+ naturalish_cmp, note_code_highlight_key, note_code_highlight_lines, note_code_row_height,
+ note_image_display_size, note_open_pending_for_vault, note_release_action,
+ open_with_candidate_allowed, path_key, preflight_local_copy, preview_line_count,
+ preview_lines_from_text, preview_plain_lines_from_text, preview_text_range,
+ preview_visible_colored, preview_visible_line_range, resolve_local_drop_target,
resolve_remote_drop_target, right_sidebar_file_browse_rows_from_index,
right_sidebar_file_row_metrics, right_sidebar_open_with_cache_key, sanitize_preview_text,
scrollable_note_table_columns, search_right_sidebar_file_index, snippet_cursor_visible,
snippet_run_buffer, sorted_open_with_candidates, virtual_note_line_range,
visible_code_block_rounded_edges, visible_file_row_range, wrap_snippet_text_for_width,
FileReleaseAction, FileRowPlacement, NoteApproximateTextMetrics, NoteCodeHighlightEntry,
- NoteCodeHighlightState, NoteReleaseAction, FILE_PREVIEW_MAX_BYTES, NOTE_CODE_BLOCK_RADIUS,
- NOTE_CODE_HEADER_HEIGHT,
+ NoteCodeHighlightState, NoteReleaseAction, FILE_PREVIEW_MAX_BYTES, LOCAL_COPY_CHUNK,
+ NOTE_CODE_BLOCK_RADIUS, NOTE_CODE_HEADER_HEIGHT,
};
use crate::markdown_editor::{NoteLineGeometry, ProjectedCodeBlock};
- use crate::termwindow::remote_files::{RemoteFileKind, RemotePath};
+ use crate::termwindow::remote_files::{
+ RemoteFileKind, RemotePath, RemoteTransferProgress, REMOTE_TRANSFER_CANCELED,
+ };
+ use crate::termwindow::transfer_walk::{DestinationRoot, OverwritePolicy, TransferEntryKind};
use crate::termwindow::{
RightSidebarFilePreviewLine, RightSidebarFilePreviewSpan, UIItem, UIItemType,
};
@@ -14615,6 +15663,7 @@ mod tests {
use std::collections::HashSet;
use std::fs;
use std::io::Cursor;
+ use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
use std::sync::Arc;
use wezterm_font::units::PixelLength;
@@ -14700,6 +15749,343 @@ mod tests {
);
}
+ fn file_entry(
+ source: &Path,
+ relative: &str,
+ ) -> crate::termwindow::transfer_walk::TransferEntry {
+ crate::termwindow::transfer_walk::TransferEntry {
+ source: source.to_path_buf(),
+ relative: PathBuf::from(relative),
+ kind: TransferEntryKind::File,
+ size: 0,
+ }
+ }
+
+ /// The check-then-create shape this replaced could be raced: a file
+ /// appearing between the two was truncated under an authorisation the user
+ /// never gave. The exclusive create makes the filesystem decide.
+ #[test]
+ fn a_no_clobber_copy_leaves_an_existing_file_untouched() {
+ let dir = tempfile::tempdir().unwrap();
+ let source = dir.path().join("src.txt");
+ let dest_dir = dir.path().join("dest");
+ fs::create_dir_all(&dest_dir).unwrap();
+ fs::write(&source, b"new contents").unwrap();
+ fs::write(dest_dir.join("src.txt"), b"do not lose me").unwrap();
+
+ let entries = vec![file_entry(&source, "src.txt")];
+ let progress = RemoteTransferProgress::default();
+ let copied = copy_entries_blocking(
+ &entries,
+ &DestinationRoot::open(&dest_dir).unwrap(),
+ OverwritePolicy::NoClobber,
+ &progress,
+ )
+ .expect("an occupied name is a skip, not a failure");
+
+ assert_eq!(copied, 0, "nothing was copied");
+ assert_eq!(
+ fs::read(dest_dir.join("src.txt")).unwrap(),
+ b"do not lose me"
+ );
+ }
+
+ /// Replace assembles the new file beside the target and swaps it in, so a
+ /// failure or a cancel leaves the original whole. Truncating in place
+ /// destroyed it the moment the write began.
+ #[test]
+ fn a_canceled_replace_leaves_the_original_intact() {
+ let dir = tempfile::tempdir().unwrap();
+ let source = dir.path().join("src.txt");
+ let dest_dir = dir.path().join("dest");
+ fs::create_dir_all(&dest_dir).unwrap();
+ fs::write(&source, vec![b'x'; LOCAL_COPY_CHUNK * 3]).unwrap();
+ let destination = dest_dir.join("src.txt");
+ fs::write(&destination, b"original").unwrap();
+
+ let entries = vec![file_entry(&source, "src.txt")];
+ let progress = RemoteTransferProgress::default();
+ progress.request_cancel();
+ let err = copy_entries_blocking(
+ &entries,
+ &DestinationRoot::open(&dest_dir).unwrap(),
+ OverwritePolicy::Replace,
+ &progress,
+ )
+ .expect_err("a canceled copy fails");
+ assert!(err.contains(REMOTE_TRANSFER_CANCELED), "{err}");
+
+ assert_eq!(
+ fs::read(&destination).unwrap(),
+ b"original",
+ "the file being replaced must survive a cancel"
+ );
+ // And no staging file is left lying about.
+ let leftovers: Vec<_> = fs::read_dir(&dest_dir)
+ .unwrap()
+ .filter_map(|entry| entry.ok())
+ .map(|entry| entry.file_name().to_string_lossy().to_string())
+ .filter(|name| name != "src.txt")
+ .collect();
+ assert!(leftovers.is_empty(), "left behind: {leftovers:?}");
+ }
+
+ /// Goes through the real `copy_file_chunked` Replace path and forces its
+ /// cleanup to run, then checks *where* the delete landed.
+ ///
+ /// The discriminator is the root symlink being repointed after the handle
+ /// was taken: a path-based cleanup resolves the root's name again and so
+ /// deletes from the new target, while a handle-based one stays where it
+ /// started. The earlier tests covered `DestinationRoot::remove_file` on its
+ /// own; this covers the branch actually calling it.
+ #[cfg(unix)]
+ #[test]
+ fn a_failed_replace_cleans_up_through_the_handle() {
+ let dir = tempfile::tempdir().unwrap();
+ let real = dir.path().join("real");
+ let decoy = dir.path().join("decoy");
+ fs::create_dir_all(&real).unwrap();
+ fs::create_dir_all(&decoy).unwrap();
+ let link = dir.path().join("root");
+ std::os::unix::fs::symlink(&real, &link).unwrap();
+
+ let source = dir.path().join("src.txt");
+ fs::write(&source, b"replacement").unwrap();
+ fs::write(real.join("target.txt"), b"original").unwrap();
+
+ // Handle taken while the name still points at `real`.
+ let root = DestinationRoot::open(&link).unwrap();
+
+ // The name now points somewhere else, and a file sits at exactly the
+ // staging path a path-based cleanup would compute.
+ fs::remove_file(&link).unwrap();
+ std::os::unix::fs::symlink(&decoy, &link).unwrap();
+ let bystander = decoy.join(".target.txt.thinkterm-0");
+ fs::write(&bystander, b"not yours to delete").unwrap();
+
+ let progress = RemoteTransferProgress::default();
+ progress.request_cancel();
+ let err = copy_file_chunked(
+ &source,
+ &root,
+ Path::new("target.txt"),
+ OverwritePolicy::Replace,
+ &progress,
+ )
+ .expect_err("a canceled replace fails");
+ assert!(err.contains(REMOTE_TRANSFER_CANCELED), "{err}");
+
+ assert!(
+ bystander.exists(),
+ "cleanup must not follow the root's name to its new target"
+ );
+ assert_eq!(
+ fs::read(real.join("target.txt")).unwrap(),
+ b"original",
+ "the file being replaced survives"
+ );
+ let leftovers: Vec<_> = fs::read_dir(&real)
+ .unwrap()
+ .filter_map(|entry| entry.ok())
+ .map(|entry| entry.file_name().to_string_lossy().to_string())
+ .filter(|name| name != "target.txt")
+ .collect();
+ assert!(
+ leftovers.is_empty(),
+ "the staging file must be removed from where it was made: {leftovers:?}"
+ );
+ }
+
+ #[test]
+ fn a_replace_swaps_in_the_new_contents() {
+ let dir = tempfile::tempdir().unwrap();
+ let source = dir.path().join("src.txt");
+ let dest_dir = dir.path().join("dest");
+ fs::create_dir_all(&dest_dir).unwrap();
+ fs::write(&source, b"new contents").unwrap();
+ fs::write(dest_dir.join("src.txt"), b"old").unwrap();
+
+ let entries = vec![file_entry(&source, "src.txt")];
+ let progress = RemoteTransferProgress::default();
+ let copied = copy_entries_blocking(
+ &entries,
+ &DestinationRoot::open(&dest_dir).unwrap(),
+ OverwritePolicy::Replace,
+ &progress,
+ )
+ .expect("replace");
+ assert_eq!(copied, 1);
+ assert_eq!(fs::read(dest_dir.join("src.txt")).unwrap(), b"new contents");
+ }
+
+ /// A symlink occupying the destination name must not be followed: writing
+ /// through it puts the data wherever the link points, outside the folder
+ /// the user chose.
+ #[cfg(unix)]
+ #[test]
+ fn a_copy_does_not_write_through_a_symlinked_destination() {
+ let dir = tempfile::tempdir().unwrap();
+ let source = dir.path().join("src.txt");
+ let dest_dir = dir.path().join("dest");
+ let outside = dir.path().join("outside.txt");
+ fs::create_dir_all(&dest_dir).unwrap();
+ fs::write(&source, b"payload").unwrap();
+ fs::write(&outside, b"untouched").unwrap();
+ std::os::unix::fs::symlink(&outside, dest_dir.join("src.txt")).unwrap();
+
+ let entries = vec![file_entry(&source, "src.txt")];
+ let progress = RemoteTransferProgress::default();
+
+ // No-clobber: the name is taken, so it is skipped.
+ copy_entries_blocking(
+ &entries,
+ &DestinationRoot::open(&dest_dir).unwrap(),
+ OverwritePolicy::NoClobber,
+ &progress,
+ )
+ .expect("skip");
+ assert_eq!(fs::read(&outside).unwrap(), b"untouched");
+
+ // Replace: the link itself is replaced, not what it points at.
+ let progress = RemoteTransferProgress::default();
+ copy_entries_blocking(
+ &entries,
+ &DestinationRoot::open(&dest_dir).unwrap(),
+ OverwritePolicy::Replace,
+ &progress,
+ )
+ .expect("replace");
+ assert_eq!(
+ fs::read(&outside).unwrap(),
+ b"untouched",
+ "the file outside the destination must never be written"
+ );
+ assert_eq!(fs::read(dest_dir.join("src.txt")).unwrap(), b"payload");
+ }
+
+ /// Verified empirically: `fs::copy` with one path truncates the shared
+ /// inode and reports success, so an 11-byte file silently becomes empty.
+ #[cfg(unix)]
+ #[test]
+ fn a_copy_refuses_a_hard_linked_destination() {
+ let dir = tempfile::tempdir().unwrap();
+ let dest_dir = dir.path().join("dest");
+ fs::create_dir_all(&dest_dir).unwrap();
+ let source = dir.path().join("src.txt");
+ fs::write(&source, b"important data").unwrap();
+ fs::hard_link(&source, dest_dir.join("src.txt")).unwrap();
+
+ let entries = vec![file_entry(&source, "src.txt")];
+ let progress = RemoteTransferProgress::default();
+ let err = copy_entries_blocking(
+ &entries,
+ &DestinationRoot::open(&dest_dir).unwrap(),
+ OverwritePolicy::Replace,
+ &progress,
+ )
+ .expect_err("copying a file over itself must be refused");
+ assert!(err.contains("already at the destination"), "{err}");
+ assert_eq!(
+ fs::read(&source).unwrap(),
+ b"important data",
+ "the source must not be destroyed"
+ );
+ }
+
+ /// Two sources in one drop wanting the same destination name: whichever
+ /// lands second would otherwise overwrite the first, or half-fail. It does
+ /// not matter that one is a folder and the other a file — a name can only
+ /// belong to one of them.
+ #[test]
+ fn two_sources_claiming_one_name_are_caught_before_anything_is_written() {
+ let dir = tempfile::tempdir().unwrap();
+ let dest = dir.path().join("dest");
+ fs::create_dir_all(&dest).unwrap();
+
+ // A folder named `foo` and, from elsewhere, a file also named `foo`.
+ let a = dir.path().join("a/foo");
+ fs::create_dir_all(&a).unwrap();
+ fs::write(a.join("inner.txt"), b"x").unwrap();
+ let b = dir.path().join("b/foo");
+ fs::create_dir_all(b.parent().unwrap()).unwrap();
+ fs::write(&b, b"y").unwrap();
+
+ let preflight = preflight_local_copy(&[a, b], &dest);
+ assert_eq!(
+ preflight.plans.len(),
+ 1,
+ "only the first claim on the name survives"
+ );
+ assert_eq!(preflight.rejected.len(), 1);
+ assert!(
+ preflight.rejected[0]
+ .1
+ .contains("already where it would be copied to"),
+ "{:?}",
+ preflight.rejected[0]
+ );
+ }
+
+ #[test]
+ fn a_local_drop_lands_in_the_directory_it_is_aimed_at() {
+ let root = Path::new("/home/me/proj");
+ let items = vec![
+ UIItem {
+ x: 100,
+ y: 0,
+ width: 300,
+ height: 500,
+ item_type: UIItemType::RightSidebarBackground,
+ },
+ UIItem {
+ x: 100,
+ y: 0,
+ width: 300,
+ height: 20,
+ item_type: UIItemType::RightSidebarFileRow(PathBuf::from("/home/me/proj/src")),
+ },
+ UIItem {
+ x: 100,
+ y: 20,
+ width: 300,
+ height: 20,
+ item_type: UIItemType::RightSidebarFileRow(PathBuf::from(
+ "/home/me/proj/src/main.rs",
+ )),
+ },
+ ];
+ let is_dir = |path: &Path| match path.to_str() {
+ Some("/home/me/proj/src") => Some(true),
+ Some("/home/me/proj/src/main.rs") => Some(false),
+ _ => None,
+ };
+
+ assert_eq!(
+ resolve_local_drop_target(&items, 200, 10, root, is_dir),
+ Some(PathBuf::from("/home/me/proj/src"))
+ );
+ // A file row means "put it beside this".
+ assert_eq!(
+ resolve_local_drop_target(&items, 200, 30, root, is_dir),
+ Some(PathBuf::from("/home/me/proj/src"))
+ );
+ assert_eq!(
+ resolve_local_drop_target(&items, 200, 400, root, is_dir),
+ Some(root.to_path_buf())
+ );
+ // Outside the panel: the terminal keeps its paste behaviour.
+ assert_eq!(
+ resolve_local_drop_target(&items, 50, 10, root, is_dir),
+ None
+ );
+ // A row the panel no longer knows the kind of resolves to nothing
+ // rather than guessing a destination.
+ assert_eq!(
+ resolve_local_drop_target(&items, 200, 10, root, |_| None),
+ None
+ );
+ }
+
#[test]
fn a_drop_onto_a_row_of_unknown_kind_is_refused() {
// A row painted from a listing the state has since dropped: guessing
diff --git a/wezterm-ssh/src/filewrap.rs b/wezterm-ssh/src/filewrap.rs
index 798416b2..a6151db2 100644
--- a/wezterm-ssh/src/filewrap.rs
+++ b/wezterm-ssh/src/filewrap.rs
@@ -59,6 +59,23 @@ impl FileWrap {
}
}
+ /// Move the read/write position, so a transfer can pick up where an
+ /// earlier one stopped instead of starting over.
+ ///
+ /// Both backends implement `std::io::Seek`, and neither performs a round
+ /// trip for it: the offset is tracked client-side and applied to the next
+ /// read or write request.
+ pub fn seek(&mut self, position: u64) -> SftpChannelResult<u64> {
+ use std::io::{Seek, SeekFrom};
+ match self {
+ #[cfg(feature = "ssh2")]
+ Self::Ssh2(file) => Ok(file.seek(SeekFrom::Start(position))?),
+
+ #[cfg(feature = "libssh-rs")]
+ Self::LibSsh(file) => Ok(file.seek(SeekFrom::Start(position))?),
+ }
+ }
+
pub fn fsync(&mut self) -> SftpChannelResult<()> {
match self {
#[cfg(feature = "ssh2")]
diff --git a/wezterm-ssh/src/sessioninner.rs b/wezterm-ssh/src/sessioninner.rs
index b4c520a5..9601d119 100644
--- a/wezterm-ssh/src/sessioninner.rs
+++ b/wezterm-ssh/src/sessioninner.rs
@@ -883,6 +883,19 @@ impl SessionInner {
"fsync",
)
}
+ SessionRequest::Sftp(SftpRequest::File(FileRequest::Seek(msg, reply))) => {
+ dispatch(
+ reply,
+ || {
+ let file = self
+ .files
+ .get_mut(&msg.file_id)
+ .ok_or_else(|| anyhow!("invalid file_id"))?;
+ file.seek(msg.position)
+ },
+ "seek",
+ )
+ }
SessionRequest::Sftp(SftpRequest::ReadDir(path, reply)) => {
dispatch(reply, || self.init_sftp(sess)?.read_dir(&path), "read_dir")
diff --git a/wezterm-ssh/src/sftp/file.rs b/wezterm-ssh/src/sftp/file.rs
index 4374f39d..d2155c1b 100644
--- a/wezterm-ssh/src/sftp/file.rs
+++ b/wezterm-ssh/src/sftp/file.rs
@@ -32,6 +32,7 @@ pub(crate) enum FileRequest {
SetMetadata(SetMetadataFile, Sender<SftpChannelResult<()>>),
Metadata(FileId, Sender<SftpChannelResult<Metadata>>),
Fsync(FileId, Sender<SftpChannelResult<()>>),
+ Seek(SeekFile, Sender<SftpChannelResult<u64>>),
}
#[derive(Debug)]
@@ -40,6 +41,12 @@ pub(crate) struct WriteFile {
pub data: Vec<u8>,
}
+#[derive(Debug)]
+pub(crate) struct SeekFile {
+ pub file_id: FileId,
+ pub position: u64,
+}
+
#[derive(Debug)]
pub(crate) struct ReadFile {
pub file_id: FileId,
@@ -124,6 +131,33 @@ impl File {
Ok(result)
}
+ /// Move the read/write position to `position` bytes from the start,
+ /// returning the new position.
+ ///
+ /// Lets a transfer resume from where an interrupted one stopped instead of
+ /// starting over. Note that the caller owns the question of whether the
+ /// bytes already there are the right ones — this only moves the cursor.
+ ///
+ /// Must not be interleaved with an in-flight read or write on the same
+ /// handle: those futures capture their buffer on first poll, so a seek
+ /// landing between poll and completion would apply to the wrong offset.
+ pub async fn seek(&self, position: u64) -> SftpChannelResult<u64> {
+ let (reply, rx) = bounded(1);
+ self.tx
+ .as_ref()
+ .unwrap()
+ .send(SessionRequest::Sftp(SftpRequest::File(FileRequest::Seek(
+ SeekFile {
+ file_id: self.file_id,
+ position,
+ },
+ reply,
+ ))))
+ .await?;
+ let result = rx.recv().await??;
+ Ok(result)
+ }
+
/// This function causes the remote server to synchronize the file data and metadata to disk
/// (like fsync(2)).
///
diff --git a/wezterm-ssh/src/sftp/mod.rs b/wezterm-ssh/src/sftp/mod.rs
index a35621c0..d797a7e6 100644
--- a/wezterm-ssh/src/sftp/mod.rs
+++ b/wezterm-ssh/src/sftp/mod.rs
@@ -120,6 +120,28 @@ impl Sftp {
.await
}
+ /// Helper to create a file only if it does not already exist.
+ ///
+ /// Prefer this over `metadata()`-then-`create()` when the point is not to
+ /// clobber: the server decides atomically, so there is no window in which
+ /// another writer can slip in between the check and the create.
+ pub async fn create_new<T, E>(&self, filename: T) -> SftpChannelResult<File>
+ where
+ T: TryInto<Utf8PathBuf, Error = E>,
+ E: Into<Box<dyn std::error::Error + Send + Sync>>,
+ {
+ self.open_with_mode(
+ filename,
+ OpenOptions {
+ read: false,
+ write: Some(WriteMode::CreateNew),
+ mode: 0o666,
+ ty: OpenFileType::File,
+ },
+ )
+ .await
+ }
+
/// Helper to open a directory for reading its contents.
pub async fn open_dir<T, E>(&self, filename: T) -> SftpChannelResult<Dir>
where
diff --git a/wezterm-ssh/src/sftp/types.rs b/wezterm-ssh/src/sftp/types.rs
index ad5af5b2..ab7f828a 100644
--- a/wezterm-ssh/src/sftp/types.rs
+++ b/wezterm-ssh/src/sftp/types.rs
@@ -223,6 +223,13 @@ pub enum WriteMode {
/// Overwrite an existing file when opening to write it
Write,
+
+ /// Create the file, failing if it already exists.
+ ///
+ /// The server decides atomically, which is the only way to claim a name
+ /// without a race: checking with `metadata` and then creating leaves a
+ /// window in which someone else can create the same path.
+ CreateNew,
}
/// Represents options to provide when renaming a file or directory
@@ -301,6 +308,10 @@ mod ssh2_impl {
// already there, which made `Sftp::create` unable to create.
Some(WriteMode::Write) => flags |= Self::WRITE | Self::TRUNCATE | Self::CREATE,
Some(WriteMode::Append) => flags |= Self::WRITE | Self::APPEND | Self::CREATE,
+ // No TRUNCATE: there is by definition nothing to truncate, and
+ // asking for it alongside EXCLUSIVE muddies what the server is
+ // being told.
+ Some(WriteMode::CreateNew) => flags |= Self::WRITE | Self::CREATE | Self::EXCLUSIVE,
None => {}
}
diff --git a/wezterm-ssh/src/sftpwrap.rs b/wezterm-ssh/src/sftpwrap.rs
index 6a04c114..d5a4b94e 100644
--- a/wezterm-ssh/src/sftpwrap.rs
+++ b/wezterm-ssh/src/sftpwrap.rs
@@ -12,6 +12,17 @@ pub(crate) enum SftpWrap {
LibSsh(libssh_rs::Sftp),
}
+/// Narrow a Unix mode to the permission bits libssh takes.
+///
+/// This used to be `mode.try_into().unwrap()`, which panics — and it panics on
+/// the SSH session thread, taking the whole connection down with no error the
+/// caller can see. Masking instead means a nonsensical mode produces a
+/// nonsensical permission rather than a dead session.
+#[cfg(feature = "libssh-rs")]
+fn sftp_mode_bits(mode: i32) -> u32 {
+ (mode as u32) & 0o7777
+}
+
#[cfg(feature = "ssh2")]
fn pathconv(path: std::path::PathBuf) -> SftpChannelResult<Utf8PathBuf> {
use crate::sftp::SftpChannelError;
@@ -37,9 +48,8 @@ impl SftpWrap {
#[cfg(feature = "libssh-rs")]
Self::LibSsh(sftp) => {
use crate::sftp::types::WriteMode;
- use libc::{O_APPEND, O_CREAT, O_RDONLY, O_RDWR, O_TRUNC, O_WRONLY};
+ use libc::{O_APPEND, O_CREAT, O_EXCL, O_RDONLY, O_RDWR, O_TRUNC, O_WRONLY};
use libssh_rs::OpenFlags;
- use std::convert::TryInto;
// O_CREAT is what lets a write actually bring the file into
// existence, and O_TRUNC is the documented meaning of the
// non-appending write mode. Without them, opening a path that
@@ -50,13 +60,15 @@ impl SftpWrap {
(Some(WriteMode::Append), false) => O_WRONLY | O_APPEND | O_CREAT,
(Some(WriteMode::Write), false) => O_WRONLY | O_CREAT | O_TRUNC,
(Some(WriteMode::Write), true) => O_RDWR | O_CREAT | O_TRUNC,
+ (Some(WriteMode::CreateNew), false) => O_WRONLY | O_CREAT | O_EXCL,
+ (Some(WriteMode::CreateNew), true) => O_RDWR | O_CREAT | O_EXCL,
(None, true) => O_RDONLY,
(None, false) => 0,
};
let file = sftp.open(
filename.as_str(),
OpenFlags::from_bits_truncate(accesstype),
- opts.mode.try_into().unwrap(),
+ sftp_mode_bits(opts.mode),
)?;
Ok(FileWrap::LibSsh(file))
}
@@ -119,10 +131,7 @@ impl SftpWrap {
Self::Ssh2(sftp) => Ok(sftp.mkdir(filename.as_std_path(), mode)?),
#[cfg(feature = "libssh-rs")]
- Self::LibSsh(sftp) => {
- use std::convert::TryInto;
- Ok(sftp.create_dir(filename.as_str(), mode.try_into().unwrap())?)
- }
+ Self::LibSsh(sftp) => Ok(sftp.create_dir(filename.as_str(), sftp_mode_bits(mode))?),
}
}