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.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
Add remote file uploads and downloads
RoversXe43d6ff53917
diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rsindex d0abeeac..92bdbad0 100644--- a/wezterm-gui/src/termwindow/mod.rs+++ b/wezterm-gui/src/termwindow/mod.rs@@ -296,6 +296,8 @@ pub(crate) enum ContextMenuApplicationAction {},/// Sidebar view-options: show/hide threads with this work status.ToggleWorkspaceStatusFilter(crate::workspace_threads::WorkspaceThreadWorkStatus),+ /// Fetch a file from the remote Files panel into the Downloads folder.+ DownloadRemoteFile(remote_files::RemotePath),}#[derive(Clone, Debug, PartialEq, Eq)]@@ -375,6 +377,9 @@ pub enum UIItemType {RightSidebarRemoteFileRow(remote_files::RemotePath),RightSidebarRemoteFileBack,RightSidebarRemoteFileCopyText,+ /// A row in the transfer strip. Clicking cancels it while it runs and+ /// dismisses it once it has finished.+ RightSidebarRemoteTransfer(u64),ContextMenuBackdrop,ContextMenuItem(Vec<usize>),AboveScrollThumb,@@ -1382,6 +1387,14 @@ pub struct TermWindow {right_sidebar_file_view_state_order: VecDeque<(PathBuf, String)>,right_sidebar_remote_files: remote_files::RemoteFilesState,right_sidebar_remote_files_lease: Option<remote_files::RemoteConnectionLease>,+ /// Transfers in flight, plus recently finished ones still worth showing.+ /// Deliberately not part of `right_sidebar_remote_files`: a transfer holds+ /// its own lease and must outlive the panel switching between trees.+ right_sidebar_remote_transfers: Vec<remote_files::RemoteTransfer>,+ right_sidebar_remote_transfer_next_id: u64,+ /// 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_remote_file_tree_scroll_offset: f32,// Bumped to invalidate a pending periodic-rescan timer tick.right_sidebar_file_rescan_token: u64,@@ -2029,6 +2042,9 @@ impl TermWindow {right_sidebar_file_view_state_order: VecDeque::new(),right_sidebar_remote_files: remote_files::RemoteFilesState::default(),right_sidebar_remote_files_lease: None,+ right_sidebar_remote_transfers: Vec::new(),+ right_sidebar_remote_transfer_next_id: 0,+ right_sidebar_remote_drop_target: None,right_sidebar_remote_file_tree_scroll_offset: 0.0,right_sidebar_file_rescan_token: 0,right_sidebar_file_refreshing: false,@@ -2372,7 +2388,7 @@ impl TermWindow {pane.send_paste(urls.as_str())?;Ok(true)}- WindowEvent::DroppedFile(paths) => {+ WindowEvent::DroppedFile { paths, coords } => {if self.right_sidebar_mode == RightSidebarMode::Tasks&& self.right_sidebar_note.view.focused{@@ -2427,6 +2443,11 @@ 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.+ if self.upload_dropped_files_to_remote(&paths, coords) {+ return Ok(true);+ }let pane = match self.get_active_pane_or_overlay() {Some(pane) => pane,None => return Ok(true),@@ -2444,7 +2465,14 @@ impl TermWindow {pane.send_paste(&paths)?;Ok(true)}- WindowEvent::DraggedFile(_) => Ok(true),+ WindowEvent::DraggedFile { coords, .. } => {+ self.update_right_sidebar_remote_drop_target(coords);+ Ok(true)+ }+ WindowEvent::DragLeave => {+ self.clear_right_sidebar_remote_drop_target();+ Ok(true)+ }}}diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rsindex 3979e997..ba67bb16 100644--- a/wezterm-gui/src/termwindow/mouseevent.rs+++ b/wezterm-gui/src/termwindow/mouseevent.rs@@ -1009,6 +1009,7 @@ impl super::TermWindow {| UIItemType::RightSidebarRemoteFileRow(_)| UIItemType::RightSidebarRemoteFileBack| UIItemType::RightSidebarRemoteFileCopyText+ | UIItemType::RightSidebarRemoteTransfer(_)| UIItemType::ContextMenuBackdrop| UIItemType::ContextMenuItem(_)| UIItemType::AboveScrollThumb@@ -1089,6 +1090,7 @@ impl super::TermWindow {| UIItemType::RightSidebarRemoteFileRow(_)| UIItemType::RightSidebarRemoteFileBack| UIItemType::RightSidebarRemoteFileCopyText+ | UIItemType::RightSidebarRemoteTransfer(_)| UIItemType::ContextMenuBackdrop| UIItemType::ContextMenuItem(_)| UIItemType::AboveScrollThumb@@ -2583,7 +2585,8 @@ impl super::TermWindow {| UIItemType::RightSidebarRemoteFileRefresh| UIItemType::RightSidebarRemoteFileRow(_)| UIItemType::RightSidebarRemoteFileBack- | UIItemType::RightSidebarRemoteFileCopyText => {+ | UIItemType::RightSidebarRemoteFileCopyText+ | UIItemType::RightSidebarRemoteTransfer(_) => {self.mouse_event_right_sidebar_remote_file(item.clone(), event, context);}UIItemType::WorkspaceSidebarSettings => {@@ -3078,7 +3081,8 @@ impl super::TermWindow {| UIItemType::RightSidebarRemoteFileRefresh| UIItemType::RightSidebarRemoteFileRow(_)| UIItemType::RightSidebarRemoteFileBack- | UIItemType::RightSidebarRemoteFileCopyText => {+ | UIItemType::RightSidebarRemoteFileCopyText+ | UIItemType::RightSidebarRemoteTransfer(_) => {self.mouse_event_right_sidebar_remote_file(item.clone(), event, context);}UIItemType::ContentViewClose(id) => {@@ -3584,6 +3588,12 @@ impl super::TermWindow {context: &dyn WindowOps,) {context.set_cursor(Some(MouseCursor::Hand));+ if let (UIItemType::RightSidebarRemoteFileRow(path), WMEK::Press(MousePress::Right)) =+ (&item.item_type, &event.kind)+ {+ self.show_right_sidebar_remote_file_context_menu(context, event.coords, path.clone());+ return;+ }if event.kind != WMEK::Press(MousePress::Left) {return;}@@ -3592,6 +3602,9 @@ impl super::TermWindow {UIItemType::RightSidebarRemoteFileConnect => {self.request_right_sidebar_remote_files_connect(true);}+ UIItemType::RightSidebarRemoteTransfer(id) => {+ self.dismiss_or_cancel_remote_transfer(id);+ }UIItemType::RightSidebarRemoteFileRefresh => {self.refresh_right_sidebar_remote_files();}diff --git a/wezterm-gui/src/termwindow/remote_files.rs b/wezterm-gui/src/termwindow/remote_files.rsindex 27cdb21c..47de3847 100644--- a/wezterm-gui/src/termwindow/remote_files.rs+++ b/wezterm-gui/src/termwindow/remote_files.rs@@ -1,11 +1,13 @@use crate::workspace_threads::{RemoteFilesSource, RemoteFilesTarget};use config::SshDomain;use smol::channel::Sender;-use smol::io::AsyncReadExt;+use smol::io::{AsyncReadExt, AsyncWriteExt};use std::collections::{HashMap, HashSet, VecDeque};use std::future::Future;use std::hash::{DefaultHasher, Hash, Hasher};+use std::path::{Path, PathBuf};use std::pin::Pin;+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};use std::sync::{Arc, Mutex, OnceLock, Weak};use std::time::{Duration, Instant};use wezterm_ssh::{Session, SessionEvent, SftpChannelError, SftpError};@@ -43,6 +45,20 @@ impl RemotePath {self.0.rsplit('/').next().unwrap_or(&self.0)}+ /// The directory holding this path, or `None` at the root — which has no+ /// parent rather than being its own.+ pub(crate) fn parent(&self) -> Option<Self> {+ if self.0 == "/" {+ return None;+ }+ let (parent, _) = self.0.rsplit_once('/')?;+ Some(Self(if parent.is_empty() {+ "/".to_string()+ } else {+ parent.to_string()+ }))+ }+pub(crate) fn extension(&self) -> Option<&str> {let name = self.file_name();let (stem, extension) = name.rsplit_once('.')?;@@ -207,6 +223,176 @@ pub(crate) struct RemoteFileBytes {pub truncated: bool,}+/// Bytes moved per round trip. SFTP is request/response over a single+/// channel, so a bigger chunk means fewer round trips; this matches the read+/// path's buffer and still leaves a cancel responsive on a slow link.+pub(crate) const REMOTE_TRANSFER_CHUNK: usize = 256 * 1024;++/// Stands in for "we do not know the size yet". A real file cannot be this+/// large, and it keeps an empty file (a genuine total of 0) distinguishable+/// from a size that has not been established.+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.+#[derive(Clone, Debug)]+pub(crate) struct RemoteTransferProgress {+ transferred: Arc<AtomicU64>,+ total: Arc<AtomicU64>,+ cancel: Arc<AtomicBool>,+}++impl Default for RemoteTransferProgress {+ fn default() -> Self {+ Self {+ transferred: Arc::new(AtomicU64::new(0)),+ total: Arc::new(AtomicU64::new(TRANSFER_TOTAL_UNKNOWN)),+ cancel: Arc::new(AtomicBool::new(false)),+ }+ }+}++impl RemoteTransferProgress {+ pub(crate) fn transferred(&self) -> u64 {+ self.transferred.load(Ordering::Relaxed)+ }++ pub(crate) fn total(&self) -> Option<u64> {+ match self.total.load(Ordering::Relaxed) {+ TRANSFER_TOTAL_UNKNOWN => None,+ total => Some(total),+ }+ }++ fn set_total(&self, total: u64) {+ // Clamp so a pathological size cannot be mistaken for "unknown".+ self.total+ .store(total.min(TRANSFER_TOTAL_UNKNOWN - 1), Ordering::Relaxed);+ }++ fn advance(&self, bytes: u64) {+ self.transferred.fetch_add(bytes, Ordering::Relaxed);+ }++ pub(crate) fn request_cancel(&self) {+ self.cancel.store(true, Ordering::Relaxed);+ }++ pub(crate) fn is_canceled(&self) -> bool {+ self.cancel.load(Ordering::Relaxed)+ }++ /// 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> {+ let total = self.total()?;+ if total == 0 {+ return Some(1.0);+ }+ Some((self.transferred() as f64 / total as f64).clamp(0.0, 1.0) as f32)+ }+}++/// Reported when a transfer stops because the user asked it to, so callers can+/// tell "you cancelled this" apart from a real failure.+pub(crate) const REMOTE_TRANSFER_CANCELED: &str = "Canceled";++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum RemoteTransferKind {+ Upload,+ Download,+}++#[derive(Clone, Debug, PartialEq, Eq)]+pub(crate) enum RemoteTransferStatus {+ Running,+ /// Finished, carrying whatever is worth telling the user afterwards —+ /// for a download, where the file landed.+ Done(String),+ Failed(String),+}++/// 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.+#[derive(Clone, Debug)]+pub(crate) struct RemoteTransfer {+ pub id: u64,+ pub kind: RemoteTransferKind,+ pub name: String,+ pub progress: RemoteTransferProgress,+ pub status: RemoteTransferStatus,+}++impl RemoteTransfer {+ pub(crate) fn is_running(&self) -> bool {+ matches!(self.status, RemoteTransferStatus::Running)+ }+}++/// How many ` (n)` variants to try before giving up on finding a free name.+const DOWNLOAD_NAME_ATTEMPTS: u32 = 1_000;++/// Reduce a server-supplied name to something that can only ever name a file+/// *inside* the download directory.+///+/// Uses `Path::file_name` rather than splitting on separators by hand, so the+/// host's own path rules apply — which is what catches a Windows drive-+/// relative name like `C:evil.txt`, where there is no separator to split on+/// but `directory.join(..)` would still escape.+fn sanitized_download_name(file_name: &str) -> &str {+ Path::new(file_name)+ .file_name()+ .and_then(|name| name.to_str())+ // `.`/`..`/`/` yield no file name at all; anything else that survives+ // is a single component by construction.+ .filter(|name| !name.is_empty())+ .unwrap_or("download")+}++/// The names a download will try, in order: the file's own name, then+/// ` (1)`, ` (2)`… inserted before the extension the way a browser does.+///+/// Pure, so the naming rule is testable without a filesystem.+pub(crate) fn download_name_candidates(file_name: &str) -> impl Iterator<Item = String> + '_ {+ let sanitized = sanitized_download_name(file_name);+ // Split at the *first* dot after the stem so `tar.gz` survives whole; a+ // leading dot is a hidden file, not an extension.+ let (stem, extension) = match sanitized.find('.') {+ Some(0) | None => (sanitized, ""),+ Some(index) => (&sanitized[..index], &sanitized[index..]),+ };+ std::iter::once(sanitized.to_string()).chain(+ (1..=DOWNLOAD_NAME_ATTEMPTS).map(move |suffix| format!("{stem} ({suffix}){extension}")),+ )+}++/// Claim a destination and its staging file together.+///+/// `reserve` must create the staging path *exclusively* and report whether it+/// won the race; a candidate is only taken when its destination is free and+/// its staging file did not already exist. Doing both in one step is what+/// stops two downloads of the same name from sharing a `.part` and stops a+/// pre-existing `X.part` from being truncated and then deleted on cleanup.+pub(crate) fn reserve_download_path(+ directory: &Path,+ file_name: &str,+ exists: impl Fn(&Path) -> bool,+ mut reserve: impl FnMut(&Path) -> bool,+) -> Option<(PathBuf, PathBuf)> {+ for name in download_name_candidates(file_name) {+ let destination = directory.join(&name);+ if exists(&destination) {+ continue;+ }+ let partial = partial_download_path(&destination);+ if reserve(&partial) {+ return Some((destination, partial));+ }+ }+ None+}+pub(crate) trait RemoteFileBackend: Send + Sync {fn resolve_root(&self, requested: String) -> RemoteFuture<RemotePath>;fn list_directory(@@ -222,6 +408,36 @@ pub(crate) trait RemoteFileBackend: Send + Sync {fn probe(&self) -> RemoteFuture<()> {Box::pin(async { Ok(()) })}++ /// Send `local` to `remote`, returning the number of bytes written.+ /// Refuses rather than overwriting an existing remote file, and tries to+ /// remove the partial file if it fails or is cancelled — best effort,+ /// since a transfer that died with the connection has no way to clean up+ /// after itself.+ ///+ /// The default refuses: only a backend that can actually write should+ /// claim to, and every test double that does not care about transfers+ /// inherits an honest answer.+ fn upload_file(+ &self,+ local: PathBuf,+ remote: RemotePath,+ progress: RemoteTransferProgress,+ ) -> RemoteFuture<u64> {+ let _ = (local, remote, progress);+ Box::pin(async { Err("This connection cannot upload files".to_string()) })+ }++ /// Fetch `remote` into `local`, returning the number of bytes written.+ fn download_file(+ &self,+ remote: RemotePath,+ local: PathBuf,+ progress: RemoteTransferProgress,+ ) -> RemoteFuture<u64> {+ let _ = (remote, local, progress);+ Box::pin(async { Err("This connection cannot download files".to_string()) })+ }}pub(crate) trait RemoteFileConnector: Send + Sync {@@ -394,6 +610,173 @@ impl RemoteFileBackend for SftpRemoteFileBackend {Ok(RemoteFileBytes { bytes, truncated })})}++ fn upload_file(+ &self,+ local: PathBuf,+ remote: RemotePath,+ progress: RemoteTransferProgress,+ ) -> RemoteFuture<u64> {+ 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 file = sftp+ .create(remote.as_str().to_string())+ .await+ .map_err(|err| format!("Unable to create {}: {err}", remote.as_str()))?;++ let outcome = copy_stream(+ &mut source,+ &mut file,+ &progress,+ "the local file",+ "the server",+ )+ .await;++ // 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.+ 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()+ );+ }+ }+ outcome+ })+ }++ fn download_file(+ &self,+ remote: RemotePath,+ local: PathBuf,+ progress: RemoteTransferProgress,+ ) -> RemoteFuture<u64> {+ 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);+ }+ }++ 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 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()))?;++ let outcome = copy_stream(+ &mut file,+ &mut sink,+ &progress,+ "the server",+ "the local file",+ )+ .await;+ drop(sink);++ 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)+ }+ }+ })+ }+}++/// Where an in-flight download accumulates. Kept next to the destination so+/// the rename that completes it stays on one filesystem.+fn partial_download_path(local: &Path) -> PathBuf {+ let mut name = local.file_name().unwrap_or_default().to_os_string();+ name.push(".part");+ local.with_file_name(name)+}++/// Stream `source` into `sink`, publishing progress and honouring a cancel+/// between chunks. Generic in both directions because the SFTP file type is+/// private to `wezterm-ssh` and cannot be named here — which is just as well,+/// since upload and download differ only in which end is which.+async fn copy_stream<R, W>(+ source: &mut R,+ sink: &mut W,+ progress: &RemoteTransferProgress,+ source_label: &str,+ sink_label: &str,+) -> Result<u64, String>+where+ R: smol::io::AsyncRead + Unpin,+ W: smol::io::AsyncWrite + Unpin,+{+ let mut buffer = vec![0u8; REMOTE_TRANSFER_CHUNK];+ let mut written = 0u64;+ loop {+ if progress.is_canceled() {+ return Err(REMOTE_TRANSFER_CANCELED.to_string());+ }+ let read = source+ .read(&mut buffer)+ .await+ .map_err(|err| format!("Unable to read from {source_label}: {err}"))?;+ if read == 0 {+ break;+ }+ sink.write_all(&buffer[..read])+ .await+ .map_err(|err| format!("Unable to write to {sink_label}: {err}"))?;+ written += read as u64;+ progress.advance(read as u64);+ }+ sink.flush()+ .await+ .map_err(|err| format!("Unable to finish writing to {sink_label}: {err}"))?;+ Ok(written)}fn is_sftp_directory_eof(err: &anyhow::Error) -> bool {@@ -1128,6 +1511,10 @@ pub(crate) enum RemoteFilesEvent {generation: u64,},ToggleDirectory(RemotePath),+ /// A directory's contents changed underneath us (an upload landed there),+ /// so re-list just that directory. Unlike [`RemoteFilesEvent::Refresh`]+ /// this keeps the rest of the tree and its expansion state intact.+ DirectoryInvalidated(RemotePath),DirectoryLoaded {generation: u64,path: RemotePath,@@ -1318,6 +1705,27 @@ impl RemoteFilesState {}self.list_directory_effect(path)}+ RemoteFilesEvent::DirectoryInvalidated(path) => {+ if !matches!(self.phase, RemoteFilesPhase::Connected)+ || !self.expanded.contains(&path)+ {+ // Not on screen: whatever changed will be read fresh+ // whenever this directory is expanded next.+ return Vec::new();+ }+ // Drop the stale listing first so the re-list is budgeted+ // against the rows that actually remain.+ self.directories.remove(&path);+ if !self.loading_directories.insert(path.clone()) {+ // Already being fetched; that request will bring the new+ // contents with it.+ return Vec::new();+ }+ if self.awaiting_lease {+ return Vec::new();+ }+ self.list_directory_effect(path)+ }RemoteFilesEvent::DirectoryLoaded {generation,path,@@ -2126,6 +2534,301 @@ mod tests {assert_eq!(error_summary(&err), "Permission denied");}+ /// Yields at most `chunk` bytes per poll, so a test can control how many+ /// times the copy loop goes round.+ struct ChunkReader {+ data: Vec<u8>,+ pos: usize,+ chunk: usize,+ }++ impl smol::io::AsyncRead for ChunkReader {+ fn poll_read(+ mut self: Pin<&mut Self>,+ _cx: &mut std::task::Context<'_>,+ buf: &mut [u8],+ ) -> std::task::Poll<std::io::Result<usize>> {+ let remaining = self.data.len() - self.pos;+ let n = remaining.min(self.chunk).min(buf.len());+ let pos = self.pos;+ buf[..n].copy_from_slice(&self.data[pos..pos + n]);+ self.pos += n;+ std::task::Poll::Ready(Ok(n))+ }+ }++ /// Collects everything written, and can trip a cancel after a chosen+ /// number of writes so the abort lands mid-transfer.+ struct VecSink {+ data: Vec<u8>,+ writes: usize,+ flushes: usize,+ cancel_after: Option<(usize, RemoteTransferProgress)>,+ }++ impl VecSink {+ fn new() -> Self {+ Self {+ data: Vec::new(),+ writes: 0,+ flushes: 0,+ cancel_after: None,+ }+ }+ }++ impl smol::io::AsyncWrite for VecSink {+ fn poll_write(+ mut self: Pin<&mut Self>,+ _cx: &mut std::task::Context<'_>,+ buf: &[u8],+ ) -> std::task::Poll<std::io::Result<usize>> {+ self.data.extend_from_slice(buf);+ self.writes += 1;+ if let Some((after, progress)) = self.cancel_after.clone() {+ if self.writes >= after {+ progress.request_cancel();+ }+ }+ std::task::Poll::Ready(Ok(buf.len()))+ }++ fn poll_flush(+ mut self: Pin<&mut Self>,+ _cx: &mut std::task::Context<'_>,+ ) -> std::task::Poll<std::io::Result<()>> {+ self.flushes += 1;+ std::task::Poll::Ready(Ok(()))+ }++ fn poll_close(+ self: Pin<&mut Self>,+ _cx: &mut std::task::Context<'_>,+ ) -> std::task::Poll<std::io::Result<()>> {+ std::task::Poll::Ready(Ok(()))+ }+ }++ #[test]+ fn a_transfer_moves_every_byte_and_reports_progress() {+ let data: Vec<u8> = (0..10_000u32).map(|index| index as u8).collect();+ let mut source = ChunkReader {+ data: data.clone(),+ pos: 0,+ chunk: 1_000,+ };+ let mut sink = VecSink::new();+ let progress = RemoteTransferProgress::default();+ progress.set_total(data.len() as u64);++ let written = smol::block_on(copy_stream(+ &mut source,+ &mut sink,+ &progress,+ "source",+ "sink",+ ))+ .expect("transfer");++ assert_eq!(written, data.len() as u64);+ assert_eq!(sink.data, data, "the bytes must arrive unchanged");+ assert_eq!(progress.transferred(), data.len() as u64);+ assert_eq!(progress.fraction(), Some(1.0));+ assert_eq!(sink.flushes, 1, "the sink must be flushed exactly once");+ }++ #[test]+ fn canceling_before_the_first_chunk_writes_nothing() {+ let mut source = ChunkReader {+ data: vec![7u8; 4_096],+ pos: 0,+ chunk: 1_024,+ };+ let mut sink = VecSink::new();+ let progress = RemoteTransferProgress::default();+ progress.request_cancel();++ let err = smol::block_on(copy_stream(+ &mut source,+ &mut sink,+ &progress,+ "source",+ "sink",+ ))+ .expect_err("a canceled transfer must fail");++ assert_eq!(err, REMOTE_TRANSFER_CANCELED);+ assert!(sink.data.is_empty(), "nothing may be sent after a cancel");+ assert_eq!(progress.transferred(), 0);+ }++ #[test]+ fn canceling_mid_transfer_stops_at_the_next_chunk() {+ let progress = RemoteTransferProgress::default();+ let mut source = ChunkReader {+ data: vec![3u8; 4_096],+ pos: 0,+ chunk: 1_024,+ };+ let mut sink = VecSink::new();+ // Trip the cancel as the first chunk lands, so the loop aborts on its+ // next pass rather than running to completion.+ sink.cancel_after = Some((1, progress.clone()));++ let err = smol::block_on(copy_stream(+ &mut source,+ &mut sink,+ &progress,+ "source",+ "sink",+ ))+ .expect_err("a canceled transfer must fail");++ assert_eq!(err, REMOTE_TRANSFER_CANCELED);+ assert_eq!(+ sink.data.len(),+ 1_024,+ "the chunk already in flight completes, and no more follow"+ );+ assert_eq!(progress.transferred(), 1_024);+ assert_eq!(sink.flushes, 0, "an aborted transfer is never flushed");+ }++ #[test]+ fn transfer_progress_reports_a_usable_fraction() {+ let progress = RemoteTransferProgress::default();+ assert_eq!(progress.total(), None);+ assert_eq!(+ progress.fraction(),+ None,+ "no fraction before the size is known"+ );++ progress.set_total(0);+ assert_eq!(+ progress.fraction(),+ Some(1.0),+ "an empty file is complete once it exists"+ );++ let progress = RemoteTransferProgress::default();+ progress.set_total(200);+ progress.advance(50);+ assert_eq!(progress.fraction(), Some(0.25));+ // A server that reported a stale size must not push the bar past full.+ progress.advance(1_000);+ assert_eq!(progress.fraction(), Some(1.0));+ }++ /// Reserve helper for tests: `taken` stands in for names already on disk,+ /// and every reservation attempt succeeds unless the staging file is one+ /// of them.+ fn reserve_against(taken: &HashSet<PathBuf>) -> impl Fn(&Path) -> bool + '_ {+ move |partial: &Path| !taken.contains(partial)+ }++ #[test]+ fn a_download_never_overwrites_an_existing_file() {+ let dir = Path::new("/home/ada/Downloads");+ let taken: HashSet<PathBuf> = [+ "/home/ada/Downloads/notes.tar.gz",+ "/home/ada/Downloads/notes (1).tar.gz",+ "/home/ada/Downloads/report.pdf",+ ]+ .iter()+ .map(PathBuf::from)+ .collect();+ let exists = |path: &Path| taken.contains(path);+ let taken_path = |dir: &Path, name: &str| dir.join(name);+ // Free name: used as-is.+ assert_eq!(+ reserve_download_path(dir, "fresh.txt", exists, reserve_against(&taken)),+ Some((+ taken_path(dir, "fresh.txt"),+ taken_path(dir, "fresh.txt.part")+ ))+ );+ // Taken once: the first free suffix wins, and a two-part extension+ // stays whole rather than becoming "notes.tar (1).gz".+ assert_eq!(+ reserve_download_path(dir, "notes.tar.gz", exists, reserve_against(&taken))+ .map(|(dest, _)| dest),+ Some(taken_path(dir, "notes (2).tar.gz"))+ );+ assert_eq!(+ reserve_download_path(dir, "report.pdf", exists, reserve_against(&taken))+ .map(|(dest, _)| dest),+ Some(taken_path(dir, "report (1).pdf"))+ );+ }++ /// The staging file is claimed exclusively, so a `.part` that is already+ /// there — another download in flight, or just a file with that name — is+ /// never truncated and never deleted by our cleanup.+ #[test]+ fn a_download_skips_a_name_whose_staging_file_is_taken() {+ let dir = Path::new("/home/ada/Downloads");+ let taken: HashSet<PathBuf> =+ std::iter::once(PathBuf::from("/home/ada/Downloads/ubuntu.iso.part")).collect();+ // The destination itself is free; only its staging file is taken.+ let (destination, partial) =+ reserve_download_path(dir, "ubuntu.iso", |_| false, reserve_against(&taken))+ .expect("a free name exists");+ assert_eq!(destination, dir.join("ubuntu (1).iso"));+ assert_eq!(partial, dir.join("ubuntu (1).iso.part"));+ assert_ne!(+ partial,+ PathBuf::from("/home/ada/Downloads/ubuntu.iso.part"),+ "the pre-existing staging file must be left alone"+ );++ // Nothing free at all: refuse rather than clobber something.+ assert_eq!(+ reserve_download_path(dir, "x.bin", |_| true, |_| true),+ None+ );+ }++ #[test]+ fn a_download_name_cannot_escape_the_download_directory() {+ let dir = Path::new("/home/ada/Downloads");+ // A server controls these names, so a separator, `..`, or a Windows+ // drive prefix must not be able to steer the write anywhere else.+ for hostile in [+ "../../etc/passwd",+ "/etc/passwd",+ "..",+ ".",+ "",+ "C:evil.txt",+ "a/b/c.txt",+ ] {+ let (destination, partial) =+ reserve_download_path(dir, hostile, |_| false, |_| true).expect("a name");+ assert_eq!(+ destination.parent(),+ Some(dir),+ "{hostile:?} escaped to {}",+ destination.display()+ );+ assert_eq!(partial.parent(), Some(dir));+ }+ // A dotfile keeps its leading dot instead of being read as extension.+ let mut names = download_name_candidates(".bashrc");+ assert_eq!(names.next().as_deref(), Some(".bashrc"));+ assert_eq!(names.next().as_deref(), Some(".bashrc (1)"));+ }++ #[test]+ fn a_partial_download_lands_beside_its_destination() {+ // Same directory, so completing the download is a rename rather than a+ // cross-filesystem copy.+ let destination = Path::new("/home/ada/Downloads/notes.tar.gz");+ let path = partial_download_path(destination);+ assert_eq!(path, PathBuf::from("/home/ada/Downloads/notes.tar.gz.part"));+ assert_eq!(path.parent(), destination.parent());+ }+/// Authorization is a process-wide registry, so tests sharing a source name/// would inherit each other's authorization (and race, since they run in/// parallel). Every test that cares about the authorized/unauthorized@@ -2764,6 +3467,75 @@ mod tests {/// Two projects can share one host while browsing different roots; the/// cache is keyed by (source, requested root) so project B must never be/// shown project A's rows just because the connection is the same.+ /// An upload lands in one directory, so only that directory is re-read.+ /// A full `Refresh` would collapse the whole tree the user had opened.+ #[test]+ fn invalidating_a_directory_relists_only_that_directory() {+ let source = unique_source("invalidate");+ let root = RemotePath::from_server_absolute("/home/me").unwrap();+ let dir = root.join_name("src").unwrap();+ let other = root.join_name("docs").unwrap();+ let mut state = RemoteFilesState::default();++ state.transition(RemoteFilesEvent::TargetChanged(Some(target(&source))));+ let generation = match state+ .transition(RemoteFilesEvent::ConnectRequested)+ .as_slice()+ {+ [RemoteFilesEffect::Connect { generation, .. }] => *generation,+ other => panic!("expected Connect, got {:?}", other),+ };+ state.transition(RemoteFilesEvent::Connected {+ generation,+ root: root.clone(),+ listing: listing(+ &root,+ &[+ ("src", RemoteFileKind::Directory),+ ("docs", RemoteFileKind::Directory),+ ],+ ),+ });+ for path in [dir.clone(), other.clone()] {+ state.transition(RemoteFilesEvent::ToggleDirectory(path.clone()));+ state.transition(RemoteFilesEvent::DirectoryLoaded {+ generation,+ path: path.clone(),+ listing: listing(&path, &[("old", RemoteFileKind::File)]),+ });+ }+ assert_eq!(state.rows().len(), 5, "root + 2 dirs + 2 files");++ let effects = state.transition(RemoteFilesEvent::DirectoryInvalidated(dir.clone()));+ assert!(+ matches!(+ effects.as_slice(),+ [RemoteFilesEffect::ListDirectory { path, .. }] if *path == dir+ ),+ "expected a re-list of just that directory, got {:?}",+ effects+ );+ // The sibling keeps both its expansion and its rows.+ assert!(state.expanded.contains(&other));+ assert!(state.directories.contains_key(&other));++ state.transition(RemoteFilesEvent::DirectoryLoaded {+ generation,+ path: dir.clone(),+ listing: listing(+ &dir,+ &[("old", RemoteFileKind::File), ("new", RemoteFileKind::File)],+ ),+ });+ assert_eq!(state.rows().len(), 6, "the uploaded file shows up");++ // A directory that is not open has nothing to re-read.+ state.transition(RemoteFilesEvent::ToggleDirectory(other.clone()));+ assert!(state+ .transition(RemoteFilesEvent::DirectoryInvalidated(other))+ .is_empty());+ }+#[test]fn trees_are_cached_per_root_not_per_source() {let source = unique_source("per-root");diff --git a/wezterm-gui/src/termwindow/ui/context_menu.rs b/wezterm-gui/src/termwindow/ui/context_menu.rsindex a48c1b14..d50dfce7 100644--- a/wezterm-gui/src/termwindow/ui/context_menu.rs+++ b/wezterm-gui/src/termwindow/ui/context_menu.rs@@ -221,6 +221,9 @@ impl crate::TermWindow {) => {self.toggle_workspace_sidebar_status_filter(status);}+ crate::termwindow::ContextMenuApplicationAction::DownloadRemoteFile(path) => {+ self.download_right_sidebar_remote_file(path);+ }}}diff --git a/wezterm-gui/src/termwindow/ui/right_sidebar.rs b/wezterm-gui/src/termwindow/ui/right_sidebar.rsindex ffd8a635..96058df8 100644--- a/wezterm-gui/src/termwindow/ui/right_sidebar.rs+++ b/wezterm-gui/src/termwindow/ui/right_sidebar.rs@@ -9,8 +9,9 @@ use crate::markdown_editor::{use crate::quad::{QuadTrait, TripleLayerQuadAllocator, TripleLayerQuadAllocatorTrait};use crate::termwindow::remote_files::{invalidate_remote_connection, invalidate_remote_connection_if_dead, remote_connection_key,- remote_connection_manager, RemoteAcquireError, RemoteFileBytes, RemoteFileKind, RemoteFileRow,- RemoteFilesEffect, RemoteFilesEvent, RemoteFilesPhase, RemotePath,+ remote_connection_manager, reserve_download_path, RemoteAcquireError, RemoteFileBytes,+ RemoteFileKind, RemoteFileRow, RemoteFilesEffect, RemoteFilesEvent, RemoteFilesPhase,+ RemotePath, RemoteTransfer, RemoteTransferKind, RemoteTransferProgress, RemoteTransferStatus,};use crate::termwindow::ui::icons::{material_file_icon_for_name, material_folder_icon_for_name, MaterialIcon, SvgIcon,@@ -145,6 +146,12 @@ const FILE_FILTER_HEIGHT: usize = 66;const FILE_TREE_TOP_GAP: usize = 14;const FILE_SCROLL_FADE_HEIGHT: usize = 32;const FILE_PREVIEW_HEADER_HEIGHT: usize = 64;+/// How many transfer rows the strip shows before it starts dropping the+/// oldest finished ones. The strip eats into the tree, so it stays small;+/// running transfers are never dropped, however many there are.+const REMOTE_TRANSFER_STRIP_MAX: usize = 3;+/// Thickness of the progress line under a running transfer's label.+const REMOTE_TRANSFER_PROGRESS_HEIGHT: usize = 3;const FILE_PREVIEW_MAX_BYTES: usize = 256 * 1024;const FILE_PREVIEW_TRUNCATED_LABEL: &str = "Preview truncated to 256 KiB";const FILE_PREVIEW_IMAGE_MAX_BYTES: usize = 16 * 1024 * 1024;@@ -956,6 +963,14 @@ pub fn right_sidebar_note_pane_width_for_dpi(dpi: usize) -> usize {.max(min_width)}+fn file_preview_close_requires_reflow(+ preview_was_visible: bool,+ previous_width: usize,+ current_width: usize,+) -> bool {+ preview_was_visible || previous_width != current_width+}+impl crate::TermWindow {fn right_sidebar_file_preview_active(&self) -> bool {!self.right_sidebar_collapsed@@ -1725,9 +1740,21 @@ impl crate::TermWindow {/// only two remembered to do it, and the ones that forgot were exactly the/// remote paths — hence the pane's width surviving a workspace switch.pub(crate) fn close_right_sidebar_file_preview(&mut self) {+ // RemoteFilesState::TargetChanged clears its selection before the+ // ReleaseLease effect reaches this method. In that interval+ // right_sidebar_width() already reports the narrow tree-only width,+ // even though the terminal is still laid out for the Preview view.+ // Preserve the view marker so closing still forces a reflow.+ let preview_was_visible = !self.right_sidebar_collapsed+ && self.right_sidebar_mode == RightSidebarMode::Chat+ && self.right_sidebar_file_view == RightSidebarFileView::Preview;let previous_width = self.right_sidebar_width();self.close_right_sidebar_file_preview_without_reflow();- if self.right_sidebar_width() != previous_width {+ if file_preview_close_requires_reflow(+ preview_was_visible,+ previous_width,+ self.right_sidebar_width(),+ ) {self.schedule_right_sidebar_reflow();}}@@ -8602,6 +8629,11 @@ impl crate::TermWindow {.target.as_ref().map(|target| target.project_name.clone());+ // Anything the panel needs to say while it has no tree — such as a file+ // being dropped on it before it is connected — has to ride in as the+ // detail line, since only the tree view paints `error_message`.+ let notice = self.right_sidebar_remote_files.error_message.clone();+ let disconnected_detail = notice.as_deref().or(target_label.as_deref());match phase {RemoteFilesPhase::Disconnected => self.paint_remote_files_empty_state(layers,@@ -8617,7 +8649,7 @@ impl crate::TermWindow {SvgIcon::Server,false,"Not connected",- target_label.as_deref(),+ disconnected_detail,Some(("Connect", true)),),RemoteFilesPhase::Connecting => self.paint_remote_files_empty_state(@@ -8939,11 +8971,38 @@ impl crate::TermWindow {}let row_metrics = right_sidebar_file_row_metrics(ui_metrics);- let footer_height = if self.right_sidebar_remote_files.has_truncated_directory() {+ let truncated_height = if self.right_sidebar_remote_files.has_truncated_directory() {row_metrics.row_height} 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 footer_height =+ truncated_height.saturating_add(strip_rows.saturating_mul(row_metrics.row_height));let viewport_bottom = content_bottom.saturating_sub(self.ui_px(SIDEBAR_INSET)).saturating_sub(footer_height);@@ -9051,21 +9110,195 @@ impl crate::TermWindow {fade_height,)?;}- if footer_height > 0 {+ let mut footer_y = viewport_bottom;+ if truncated_height > 0 {self.paint_sidebar_text(layers,ui_font,ui_metrics,"More entries are not shown",content_x,- viewport_bottom,+ footer_y,+ content_width,+ muted_fg,+ )?;+ footer_y += truncated_height;+ }+ for index in 0..painted_transfers {+ self.paint_remote_transfer_row(+ layers,+ ui_font,+ ui_metrics,+ chrome,+ foreground,+ muted_fg,+ content_x,+ footer_y,content_width,+ index,+ row_metrics,+ )?;+ footer_y += row_metrics.row_height;+ }+ if hidden_transfers > 0 && strip_rows > 0 {+ let more = if hidden_transfers == 1 {+ "1 more transfer".to_string()+ } else {+ format!("{hidden_transfers} more transfers")+ };+ self.paint_sidebar_text(+ layers,+ ui_font,+ 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,+ content_width.saturating_sub(self.ui_px(SIDEBAR_INSET)),muted_fg,)?;}Ok(())}+ /// One line in the transfer strip: an icon telling running from finished+ /// from failed, the file name, a short status, and — while it runs — a+ /// progress line beneath.+ #[allow(clippy::too_many_arguments)]+ fn paint_remote_transfer_row(+ &mut self,+ layers: &mut TripleLayerQuadAllocator,+ ui_font: &Rc<LoadedFont>,+ ui_metrics: RenderMetrics,+ chrome: UiPalette,+ foreground: LinearRgba,+ muted_fg: LinearRgba,+ x: usize,+ y: usize,+ width: usize,+ index: usize,+ row_metrics: RightSidebarFileRowMetrics,+ ) -> anyhow::Result<()> {+ let Some(transfer) = self.right_sidebar_remote_transfers.get(index) else {+ return Ok(());+ };+ let id = transfer.id;+ let running = transfer.is_running();+ let (icon, tint) = match &transfer.status {+ RemoteTransferStatus::Running => (SvgIcon::LoaderCircle, foreground),+ 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",+ };+ 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::Done(detail) => detail.clone(),+ RemoteTransferStatus::Failed(message) => message.clone(),+ };+ let label = format!("{} — {detail}", transfer.name);+ let fraction = transfer.progress.fraction();++ let hovered = self.is_pointer_over_ui_rect(x, y, width, row_metrics.row_height);+ if hovered {+ self.fill_rounded_rectangle(+ layers,+ 1,+ euclid::rect(+ x as f32,+ y as f32,+ width as f32,+ row_metrics.row_height as f32,+ ),+ chrome.sidebar_button_hover_bg,+ self.ui_f32(SIDEBAR_ROW_RADIUS),+ )+ .context("remote transfer row hover")?;+ }+ self.ui_items.push(UIItem {+ x,+ y,+ width,+ height: row_metrics.row_height,+ item_type: UIItemType::RightSidebarRemoteTransfer(id),+ });++ let icon_x = x + self.ui_px(SIDEBAR_INSET);+ let icon_y = y + row_metrics.row_height.saturating_sub(row_metrics.icon_size) / 2;+ if running {+ self.paint_spinning_ui_icon(+ layers,+ 1,+ icon,+ icon_x,+ icon_y,+ row_metrics.icon_size,+ tint,+ )?;+ } else {+ self.paint_ui_icon(layers, 1, icon, icon_x, icon_y, row_metrics.icon_size, tint)?;+ }++ let text_x = icon_x + row_metrics.icon_size + row_metrics.icon_gap;+ let text_width = width.saturating_sub(text_x.saturating_sub(x));+ let text_y = y + row_metrics+ .row_height+ .saturating_sub(ui_metrics.cell_size.height as usize)+ / 2;+ self.paint_sidebar_text(+ layers,+ ui_font,+ ui_metrics,+ &label,+ text_x,+ text_y,+ text_width,+ if running { foreground } else { muted_fg },+ )?;++ if let (true, Some(fraction)) = (running, fraction) {+ let bar_height = self.ui_px(REMOTE_TRANSFER_PROGRESS_HEIGHT).max(1);+ let bar_y = y + row_metrics.row_height.saturating_sub(bar_height);+ let radius = (bar_height as f32) / 2.0;+ self.fill_rounded_rectangle(+ layers,+ 1,+ euclid::rect(+ text_x as f32,+ bar_y as f32,+ text_width as f32,+ bar_height as f32,+ ),+ chrome.sidebar_button_hover_bg,+ radius,+ )+ .context("remote transfer progress track")?;+ let filled = (text_width as f32 * fraction).max(radius * 2.0);+ self.fill_rounded_rectangle(+ layers,+ 1,+ euclid::rect(text_x as f32, bar_y as f32, filled, bar_height as f32),+ chrome.selected_bg,+ radius,+ )+ .context("remote transfer progress fill")?;+ // A running transfer must keep repainting even when nothing else+ // changes, or the percentage freezes until the next event.+ self.update_next_frame_time(Some(Instant::now() + Duration::from_millis(100)));+ }+ Ok(())+ }+#[allow(clippy::too_many_arguments)]fn paint_remote_file_tree_row(&mut self,@@ -9093,7 +9326,11 @@ impl crate::TermWindow {}let hovered = self.is_pointer_over_ui_rect(x, visible_y, width, visible_height);let is_selected = selected == Some(&row.entry.path);- if hovered || is_selected {+ // A drag hovering here is about to drop into this directory; make that+ // unmistakable, and let it outrank the ordinary selection tint.+ let is_drop_target =+ self.right_sidebar_remote_drop_target.as_ref() == Some(&row.entry.path);+ if hovered || is_selected || is_drop_target {self.fill_rounded_rectangle(layers,1,@@ -9103,7 +9340,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@@ -9496,6 +9735,408 @@ impl crate::TermWindow {}}+ /// The right sidebar's background item spans the whole panel and is+ /// painted first, so anything inside the panel sits on top of it.+ fn pointer_is_over_right_sidebar(&self, x: isize, y: isize) -> bool {+ self.ui_items.iter().any(|item| {+ matches!(item.item_type, UIItemType::RightSidebarBackground) && item.hit_test(x, y)+ })+ }++ /// Which remote directory a pointer at `coords` is aiming at, if the+ /// remote Files panel is showing a connected tree there.+ pub(crate) fn remote_drop_target_at(&self, x: isize, y: isize) -> Option<RemotePath> {+ if !self.right_sidebar_file_view_active()+ || !matches!(+ self.right_sidebar_remote_files.phase,+ RemoteFilesPhase::Connected+ )+ {+ return None;+ }+ let root = self.right_sidebar_remote_files.root.as_ref()?;+ resolve_remote_drop_target(&self.ui_items, x, y, root, |path| {+ self.right_sidebar_remote_files.kind_for_path(path)+ })+ }++ pub(crate) fn update_right_sidebar_remote_drop_target(&mut self, coords: Option<Point>) {+ let target = coords.and_then(|coords| self.remote_drop_target_at(coords.x, coords.y));+ if self.right_sidebar_remote_drop_target != target {+ self.right_sidebar_remote_drop_target = target;+ self.invalidate_window();+ }+ }++ pub(crate) fn clear_right_sidebar_remote_drop_target(&mut self) {+ if self.right_sidebar_remote_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.+ pub(crate) fn upload_dropped_files_to_remote(+ &mut self,+ paths: &[PathBuf],+ coords: Option<Point>,+ ) -> bool {+ self.clear_right_sidebar_remote_drop_target();+ let Some(coords) = coords else {+ return false;+ };+ // Aimed at the panel but not usable: say so rather than silently+ // pasting the paths into the terminal behind it.+ if self.pointer_is_over_right_sidebar(coords.x, coords.y)+ && self.right_sidebar_file_view_active()+ && self.right_sidebar_remote_files.target.is_some()+ && !matches!(+ self.right_sidebar_remote_files.phase,+ RemoteFilesPhase::Connected+ )+ {+ self.right_sidebar_remote_files.error_message =+ Some("Connect before dropping files here".to_string());+ self.invalidate_window();+ return true;+ }+ let Some(directory) = self.remote_drop_target_at(coords.x, coords.y) else {+ 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;+ continue;+ }+ let Some(name) = path.file_name().and_then(|name| name.to_str()) else {+ self.push_remote_transfer_failure(+ RemoteTransferKind::Upload,+ path.to_string_lossy().to_string(),+ "That file name is not valid UTF-8".to_string(),+ );+ continue;+ };+ // Build the destination from the *name* only: a local path could+ // carry separators (or a drive letter) that must never be spliced+ // into a remote path.+ let remote = match directory.join_name(name) {+ Ok(remote) => remote,+ Err(err) => {+ self.push_remote_transfer_failure(+ RemoteTransferKind::Upload,+ name.to_string(),+ err,+ );+ continue;+ }+ };+ self.start_remote_upload(path.clone(), remote, directory.clone());+ queued += 1;+ }++ if skipped_directories > 0 && queued == 0 {+ 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(),+ );+ }+ self.invalidate_window();+ true+ }++ fn next_remote_transfer_id(&mut self) -> u64 {+ self.right_sidebar_remote_transfer_next_id = self+ .right_sidebar_remote_transfer_next_id+ .wrapping_add(1)+ .max(1);+ self.right_sidebar_remote_transfer_next_id+ }++ fn push_remote_transfer_failure(+ &mut self,+ kind: RemoteTransferKind,+ name: String,+ message: String,+ ) {+ let id = self.next_remote_transfer_id();+ self.right_sidebar_remote_transfers.push(RemoteTransfer {+ id,+ kind,+ name,+ progress: RemoteTransferProgress::default(),+ status: RemoteTransferStatus::Failed(message),+ });+ self.trim_remote_transfers();+ }++ /// Keep the strip from growing without bound: finished entries are the+ /// only ones ever dropped, and the oldest go first.+ fn trim_remote_transfers(&mut self) {+ while self.right_sidebar_remote_transfers.len() > REMOTE_TRANSFER_STRIP_MAX {+ let Some(index) = self+ .right_sidebar_remote_transfers+ .iter()+ .position(|transfer| !transfer.is_running())+ else {+ break;+ };+ self.right_sidebar_remote_transfers.remove(index);+ }+ }++ fn start_remote_upload(&mut self, local: PathBuf, remote: RemotePath, directory: RemotePath) {+ let name = remote.file_name().to_string();+ 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(),+ );+ return;+ };+ let Some(window) = self.window.as_ref().cloned() else {+ return;+ };++ let id = self.next_remote_transfer_id();+ let progress = RemoteTransferProgress::default();+ self.right_sidebar_remote_transfers.push(RemoteTransfer {+ id,+ kind: RemoteTransferKind::Upload,+ name,+ progress: progress.clone(),+ status: RemoteTransferStatus::Running,+ });+ self.trim_remote_transfers();++ promise::spawn::spawn(async move {+ let result = backend.upload_file(local, remote, 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)+ });+ 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()),+ };+ 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 {+ term_window.right_sidebar_remote_files_lease.take();+ }+ term_window.invalidate_window();+ })));+ })+ .detach();+ }++ /// Right-clicking a remote row. Only a file offers anything so far, so a+ /// directory gets no menu rather than an empty one.+ pub(crate) fn show_right_sidebar_remote_file_context_menu(+ &mut self,+ context: &dyn WindowOps,+ anchor: Point,+ path: RemotePath,+ ) {+ if self.right_sidebar_remote_files.kind_for_path(&path) != Some(RemoteFileKind::File) {+ return;+ }+ // A transfer needs a live lease; offering Download without one would+ // only produce a failure row.+ let enabled = self.right_sidebar_remote_files_lease.is_some();+ self.begin_context_menu_application_actions();+ let item = self.context_menu_application_item_with_icon(+ "Download",+ // No dedicated download glyph in the shared icon set; Save is the+ // closest fit and already maps on every platform.+ ContextMenuIcon::Save,+ crate::termwindow::ContextMenuApplicationAction::DownloadRemoteFile(path),+ enabled,+ );+ 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(),+ );+ 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()),+ );+ return;+ }+ // Claim the destination and its staging file together, by creating the+ // staging file exclusively. Two downloads that would land on the same+ // name therefore take different ones, and an unrelated `X.part` that+ // happens to be sitting there is never truncated or deleted.+ let Some((local, partial)) = reserve_download_path(+ &directory,+ &name,+ |path| path.exists(),+ |partial| {+ fs::OpenOptions::new()+ .write(true)+ .create_new(true)+ .open(partial)+ .is_ok()+ },+ ) else {+ self.push_remote_transfer_failure(+ RemoteTransferKind::Download,+ name,+ format!("Unable to find a free name in {}", directory.display()),+ );+ return;+ };++ // From here on the staging file exists, so every early return has to+ // take it back down.+ let release_reservation = |partial: &Path| {+ if let Err(err) = fs::remove_file(partial) {+ log::warn!(+ "remote files: unable to release the download reservation {}: {err:#}",+ partial.display()+ );+ }+ };++ let Some((backend, operation_lease, connection_key, connection_id)) =+ self.remote_transfer_handles()+ else {+ release_reservation(&partial);+ self.push_remote_transfer_failure(+ RemoteTransferKind::Download,+ name,+ "Remote Files connection is no longer available".to_string(),+ );+ return;+ };+ let Some(window) = self.window.as_ref().cloned() else {+ release_reservation(&partial);+ return;+ };++ let id = self.next_remote_transfer_id();+ let progress = RemoteTransferProgress::default();+ self.right_sidebar_remote_transfers.push(RemoteTransfer {+ id,+ kind: RemoteTransferKind::Download,+ name,+ progress: progress.clone(),+ status: RemoteTransferStatus::Running,+ });+ self.trim_remote_transfers();+ self.invalidate_window();++ promise::spawn::spawn(async move {+ 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)+ });+ 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()),+ };+ term_window.finish_remote_transfer(id, status);+ if connection_died {+ term_window.right_sidebar_remote_files_lease.take();+ }+ term_window.invalidate_window();+ })));+ })+ .detach();+ }++ /// Everything a transfer worker needs from the panel's lease. Takes an+ /// operation lease so the pooled connection cannot expire mid-transfer.+ fn remote_transfer_handles(+ &self,+ ) -> Option<(+ Arc<dyn crate::termwindow::remote_files::RemoteFileBackend>,+ crate::termwindow::remote_files::RemoteConnectionLease,+ String,+ u64,+ )> {+ let lease = self.right_sidebar_remote_files_lease.as_ref()?;+ let operation_lease = lease.operation_lease()?;+ Some((+ lease.backend(),+ operation_lease,+ lease.connection_key().to_string(),+ lease.connection_id(),+ ))+ }++ fn finish_remote_transfer(&mut self, id: u64, status: RemoteTransferStatus) {+ if let Some(transfer) = self+ .right_sidebar_remote_transfers+ .iter_mut()+ .find(|transfer| transfer.id == id)+ {+ transfer.status = status;+ }+ self.trim_remote_transfers();+ }++ /// Clicking a transfer row: stop it if it is still going, otherwise clear+ /// the notice away.+ pub(crate) fn dismiss_or_cancel_remote_transfer(&mut self, id: u64) {+ let Some(index) = self+ .right_sidebar_remote_transfers+ .iter()+ .position(|transfer| transfer.id == id)+ else {+ return;+ };+ if self.right_sidebar_remote_transfers[index].is_running() {+ self.right_sidebar_remote_transfers[index]+ .progress+ .request_cancel();+ } else {+ self.right_sidebar_remote_transfers.remove(index);+ }+ self.invalidate_window();+ }+pub(crate) fn request_right_sidebar_remote_files_connect(&mut self, explicit: bool) {let event = if explicit {RemoteFilesEvent::ConnectRequested@@ -12978,6 +13619,42 @@ fn file_row_placement(}}+/// 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+/// else inside the panel takes the root.+///+/// Split out from the window so the rule can be tested against a handful of+/// rectangles instead of a rendered frame.+fn resolve_remote_drop_target(+ items: &[UIItem],+ x: isize,+ y: isize,+ root: &RemotePath,+ kind_for_path: impl Fn(&RemotePath) -> Option<RemoteFileKind>,+) -> Option<RemotePath> {+ // Last painted wins, matching how a click resolves.+ let item = items.iter().rev().find(|item| item.hit_test(x, y))?;+ match &item.item_type {+ UIItemType::RightSidebarRemoteFileRow(path) => match kind_for_path(path) {+ Some(RemoteFileKind::Directory) => Some(path.clone()),+ // A symlink could point anywhere; treat it as an ordinary entry+ // and aim at the directory it is listed in.+ Some(_) => Some(path.parent().unwrap_or_else(|| root.clone())),+ None => None,+ },+ // Empty space inside the panel, or its chrome: the root is the only+ // directory the whole panel unambiguously refers to. The transfer+ // strip counts too — it sits inside the panel, so a drop landing on it+ // must not fall through and paste into the terminal behind.+ UIItemType::RightSidebarBackground+ | UIItemType::RightSidebarRemoteFileRefresh+ | UIItemType::RightSidebarRemoteFileConnect+ | UIItemType::RightSidebarRemoteTransfer(_) => Some(root.clone()),+ _ => None,+ }+}+fn visible_file_row_range(row_count: usize,scroll_offset: f32,@@ -13913,13 +14590,14 @@ 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_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, right_sidebar_file_browse_rows_from_index,+ 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,+ 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,@@ -13929,7 +14607,10 @@ mod tests {NOTE_CODE_HEADER_HEIGHT,};use crate::markdown_editor::{NoteLineGeometry, ProjectedCodeBlock};- use crate::termwindow::{RightSidebarFilePreviewLine, RightSidebarFilePreviewSpan};+ use crate::termwindow::remote_files::{RemoteFileKind, RemotePath};+ use crate::termwindow::{+ RightSidebarFilePreviewLine, RightSidebarFilePreviewSpan, UIItem, UIItemType,+ };use crate::utilsprites::RenderMetrics;use std::collections::HashSet;use std::fs;@@ -13940,6 +14621,97 @@ mod tests {use window::color::LinearRgba;use window::Size;+ #[test]+ fn preview_close_reflows_after_remote_selection_was_cleared() {+ // TargetChanged clears the remote selection before ReleaseLease closes+ // the pane, so both width reads are already tree-only. The Preview view+ // marker must still force the terminal to reclaim the old pane width.+ assert!(file_preview_close_requires_reflow(true, 320, 320));+ }++ #[test]+ fn preview_close_skips_a_tree_only_noop_but_tracks_width_changes() {+ assert!(!file_preview_close_requires_reflow(false, 320, 320));+ assert!(file_preview_close_requires_reflow(false, 640, 320));+ }++ fn drop_target_items() -> Vec<UIItem> {+ // Painted back to front, the way a frame builds up: the panel+ // background first, then the rows on top of it.+ 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::RightSidebarRemoteFileRow(+ RemotePath::from_server_absolute("/home/me/src").unwrap(),+ ),+ },+ UIItem {+ x: 100,+ y: 20,+ width: 300,+ height: 20,+ item_type: UIItemType::RightSidebarRemoteFileRow(+ RemotePath::from_server_absolute("/home/me/src/main.rs").unwrap(),+ ),+ },+ ]+ }++ #[test]+ fn a_drop_lands_in_the_directory_it_is_aimed_at() {+ let root = RemotePath::from_server_absolute("/home/me").unwrap();+ let items = drop_target_items();+ let kind = |path: &RemotePath| match path.as_str() {+ "/home/me/src" => Some(RemoteFileKind::Directory),+ "/home/me/src/main.rs" => Some(RemoteFileKind::File),+ _ => None,+ };++ // A directory row takes the upload itself.+ assert_eq!(+ resolve_remote_drop_target(&items, 200, 10, &root, kind).as_ref(),+ Some(&RemotePath::from_server_absolute("/home/me/src").unwrap())+ );+ // A file row means "next to this", i.e. the directory holding it.+ assert_eq!(+ resolve_remote_drop_target(&items, 200, 30, &root, kind).as_ref(),+ Some(&RemotePath::from_server_absolute("/home/me/src").unwrap())+ );+ // Empty space inside the panel falls back to the root.+ assert_eq!(+ resolve_remote_drop_target(&items, 200, 400, &root, kind).as_ref(),+ Some(&root)+ );+ // Outside the panel entirely: not ours, so the terminal keeps its+ // long-standing paste behaviour.+ assert_eq!(+ resolve_remote_drop_target(&items, 50, 10, &root, kind),+ 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+ // a destination here could put the file somewhere unintended.+ let root = RemotePath::from_server_absolute("/home/me").unwrap();+ let items = drop_target_items();+ assert_eq!(+ resolve_remote_drop_target(&items, 200, 10, &root, |_| None),+ None+ );+ }+fn test_render_metrics(cell_height: isize, cell_width: isize) -> RenderMetrics {RenderMetrics {descender: PixelLength::new(0.0),diff --git a/wezterm-ssh/src/sftp/types.rs b/wezterm-ssh/src/sftp/types.rsindex 00f6ed9c..ad5af5b2 100644--- a/wezterm-ssh/src/sftp/types.rs+++ b/wezterm-ssh/src/sftp/types.rs@@ -296,7 +296,10 @@ mod ssh2_impl {}match opts.write {- Some(WriteMode::Write) => flags |= Self::WRITE | Self::TRUNCATE,+ // CREATE is required for the file to come into existence:+ // WRITE|TRUNCATE alone fails outright on a path that is not+ // 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,None => {}}diff --git a/wezterm-ssh/src/sftpwrap.rs b/wezterm-ssh/src/sftpwrap.rsindex 4335479e..6a04c114 100644--- a/wezterm-ssh/src/sftpwrap.rs+++ b/wezterm-ssh/src/sftpwrap.rs@@ -37,14 +37,19 @@ impl SftpWrap {#[cfg(feature = "libssh-rs")]Self::LibSsh(sftp) => {use crate::sftp::types::WriteMode;- use libc::{O_APPEND, O_RDONLY, O_RDWR, O_WRONLY};+ use libc::{O_APPEND, O_CREAT, 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+ // is not already there simply fails, so `Sftp::create` could+ // never create anything.let accesstype = match (opts.write, opts.read) {- (Some(WriteMode::Append), true) => O_RDWR | O_APPEND,- (Some(WriteMode::Append), false) => O_WRONLY | O_APPEND,- (Some(WriteMode::Write), false) => O_WRONLY,- (Some(WriteMode::Write), true) => O_RDWR,+ (Some(WriteMode::Append), true) => O_RDWR | O_APPEND | O_CREAT,+ (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,(None, true) => O_RDONLY,(None, false) => 0,};diff --git a/window/examples/async.rs b/window/examples/async.rsindex eead961a..55e1d967 100644--- a/window/examples/async.rs+++ b/window/examples/async.rs@@ -83,8 +83,9 @@ impl MyWindow {| WindowEvent::AdviseModifiersLedStatus(_, _)| WindowEvent::Notification(_)| WindowEvent::FocusChanged(_)- | WindowEvent::DraggedFile(_)- | WindowEvent::DroppedFile(_)+ | WindowEvent::DraggedFile { .. }+ | WindowEvent::DragLeave+ | WindowEvent::DroppedFile { .. }| WindowEvent::DroppedUrl(_)| WindowEvent::DroppedString(_)| WindowEvent::PerformKeyAssignment(_)diff --git a/window/src/lib.rs b/window/src/lib.rsindex 91c5897b..2c3dd43b 100644--- a/window/src/lib.rs+++ b/window/src/lib.rs@@ -536,11 +536,31 @@ pub enum WindowEvent {Notification(Box<dyn Any + Send + Sync>),- // Called when the files are being dragged into the window- DraggedFile(Vec<PathBuf>),+ // Called while files are being dragged over the window.+ //+ // `coords` is window-relative, in the same space as `MouseEvent::coords`,+ // so a handler can hit-test it against whatever it painted. It is `None`+ // on platforms that do not report a position (Wayland, Windows), and a+ // handler that needs a position must fall back to its no-position+ // behaviour rather than guessing.+ //+ // `paths` may be empty here even when the drag does carry files: X11's+ // XDND only transfers the payload on drop, so the hover events know a+ // drag is happening without yet knowing what it holds.+ DraggedFile {+ paths: Vec<PathBuf>,+ coords: Option<Point>,+ },++ // Called when a file drag leaves the window or is cancelled, so any+ // drop-target affordance can be taken down.+ DragLeave,// Called when the files are dropped into the window- DroppedFile(Vec<PathBuf>),+ DroppedFile {+ paths: Vec<PathBuf>,+ coords: Option<Point>,+ },// Called when urls are dropped into the windowDroppedUrl(Vec<Url>),diff --git a/window/src/os/macos/window.rs b/window/src/os/macos/window.rsindex b576ea8d..58a55add 100644--- a/window/src/os/macos/window.rs+++ b/window/src/os/macos/window.rs@@ -70,6 +70,12 @@ const THINKTERM_TITLEBAR_SIDEBAR_BUTTON_GAP: f64 = 8.0;const THINKTERM_TITLEBAR_SIDEBAR_BUTTON_SIZE: f64 = 30.0;const THINKTERM_TITLEBAR_SIDEBAR_BUTTON_TAG: NSInteger = 0x7474_7362;+/// `NSDragOperation` values. The dragging entered/updated methods return this+/// mask, not a BOOL: the runtime reads a full word, so returning a byte-wide+/// BOOL leaves the rest of the value undefined.+const NS_DRAG_OPERATION_NONE: NSUInteger = 0;+const NS_DRAG_OPERATION_COPY: NSUInteger = 1;+static THINKTERM_PERF_ENABLED: OnceLock<bool> = OnceLock::new();fn thinkterm_perf_enabled() -> bool {@@ -4247,54 +4253,93 @@ impl WindowView {}}- extern "C" fn dragging_entered(this: &mut Object, _: Sel, sender: id) -> BOOL {+ /// Where the drag is, in the same window-relative backing pixels as+ /// `MouseEvent::coords`. `draggingLocation` is in window coordinates just+ /// like `locationInWindow`, so this mirrors `mouse_common` exactly; the+ /// view is flipped, so no y adjustment is needed.+ fn dragging_coords(this: &mut Object, sender: id) -> Point {+ let view = this as id;+ unsafe {+ let location: NSPoint = msg_send![sender, draggingLocation];+ let point = NSView::convertPoint_fromView_(view, location, nil);+ let rect = NSRect::new(NSPoint::new(0., 0.), NSSize::new(point.x, point.y));+ let backing_rect = NSView::convertRectToBacking(view, rect);+ // backing_rect computes abs() values, so restore the sign from+ // the original point.+ Point::new(+ f64::copysign(backing_rect.size.width, point.x) as isize,+ f64::copysign(backing_rect.size.height, point.y) as isize,+ )+ }+ }++ fn dragged_paths(sender: id) -> Option<Vec<PathBuf>> {+ let pb: id = unsafe { msg_send![sender, draggingPasteboard] };+ if pb.is_null() {+ return None;+ }+ let filenames =+ unsafe { NSPasteboard::propertyListForType(pb, appkit::NSFilenamesPboardType) };+ if filenames.is_null() {+ return None;+ }+ Some(+ unsafe { filenames.iter() }+ .map(|file| unsafe { PathBuf::from(nsstring_to_str(file)) })+ .collect(),+ )+ }++ fn dragging_hover(this: &mut Object, sender: id) -> NSUInteger {+ let Some(paths) = Self::dragged_paths(sender) else {+ return NS_DRAG_OPERATION_NONE;+ };+ let coords = Self::dragging_coords(this, sender);if let Some(this) = Self::get_this(this) {- let mut inner = this.inner.borrow_mut();+ this.inner+ .borrow_mut()+ .events+ .dispatch(WindowEvent::DraggedFile {+ paths,+ coords: Some(coords),+ });+ }+ NS_DRAG_OPERATION_COPY+ }- let pb: id = unsafe { msg_send![sender, draggingPasteboard] };- if pb.is_null() {- return NO;- }+ extern "C" fn dragging_entered(this: &mut Object, _: Sel, sender: id) -> NSUInteger {+ Self::dragging_hover(this, sender)+ }- let filenames =- unsafe { NSPasteboard::propertyListForType(pb, appkit::NSFilenamesPboardType) };- if filenames.is_null() {- return NO;- }+ /// Registered so the hover position keeps arriving as the pointer moves.+ /// Without it AppKit reuses `draggingEntered:`'s answer for the whole+ /// drag and never reports where the pointer went.+ extern "C" fn dragging_updated(this: &mut Object, _: Sel, sender: id) -> NSUInteger {+ Self::dragging_hover(this, sender)+ }- let paths = unsafe { filenames.iter() }- .map(|file| unsafe {- let path = nsstring_to_str(file);- PathBuf::from(path)- })- .collect::<Vec<_>>();- inner.events.dispatch(WindowEvent::DraggedFile(paths));+ extern "C" fn dragging_exited(this: &mut Object, _: Sel, _sender: id) {+ if let Some(this) = Self::get_this(this) {+ this.inner+ .borrow_mut()+ .events+ .dispatch(WindowEvent::DragLeave);}- YES}extern "C" fn perform_drag_operation(this: &mut Object, _: Sel, sender: id) -> BOOL {+ let Some(paths) = Self::dragged_paths(sender) else {+ return NO;+ };+ let coords = Self::dragging_coords(this, sender);if let Some(this) = Self::get_this(this) {- let mut inner = this.inner.borrow_mut();-- let pb: id = unsafe { msg_send![sender, draggingPasteboard] };- if pb.is_null() {- return NO;- }-- let filenames =- unsafe { NSPasteboard::propertyListForType(pb, appkit::NSFilenamesPboardType) };- if filenames.is_null() {- return NO;- }-- let paths = unsafe { filenames.iter() }- .map(|file| unsafe {- let path = nsstring_to_str(file);- PathBuf::from(path)- })- .collect::<Vec<_>>();- inner.events.dispatch(WindowEvent::DroppedFile(paths));+ this.inner+ .borrow_mut()+ .events+ .dispatch(WindowEvent::DroppedFile {+ paths,+ coords: Some(coords),+ });}YES}@@ -4603,7 +4648,15 @@ impl WindowView {);cls.add_method(sel!(draggingEntered:),- Self::dragging_entered as extern "C" fn(&mut Object, Sel, id) -> BOOL,+ Self::dragging_entered as extern "C" fn(&mut Object, Sel, id) -> NSUInteger,+ );+ cls.add_method(+ sel!(draggingUpdated:),+ Self::dragging_updated as extern "C" fn(&mut Object, Sel, id) -> NSUInteger,+ );+ cls.add_method(+ sel!(draggingExited:),+ Self::dragging_exited as extern "C" fn(&mut Object, Sel, id),);cls.add_method(sel!(performDragOperation:),diff --git a/window/src/os/wayland/window.rs b/window/src/os/wayland/window.rsindex 6e520198..086ebedf 100644--- a/window/src/os/wayland/window.rs+++ b/window/src/os/wayland/window.rs@@ -875,7 +875,13 @@ impl WaylandWindowInner {}pub(super) fn dispatch_dropped_files(&mut self, paths: Vec<PathBuf>) {- self.events.dispatch(WindowEvent::DroppedFile(paths));+ // The Wayland data-device plumbing here does not carry the drop+ // position through to this point, so the drop keeps its long-standing+ // behaviour of pasting the paths into the terminal.+ self.events.dispatch(WindowEvent::DroppedFile {+ paths,+ coords: None,+ });}pub(crate) fn dispatch_pending_mouse(&mut self) {diff --git a/window/src/os/windows/window.rs b/window/src/os/windows/window.rsindex 6f0540ac..de75c558 100644--- a/window/src/os/windows/window.rs+++ b/window/src/os/windows/window.rs@@ -3188,7 +3188,13 @@ unsafe fn drop_files(hwnd: HWND, _msg: UINT, wparam: WPARAM, _lparam: LPARAM) ->}let mut inner = inner.borrow_mut();- inner.events.dispatch(WindowEvent::DroppedFile(filenames));+ // WM_DROPFILES does carry a drop point (DragQueryPoint), but nothing here+ // is built or tested on Windows; reporting no position keeps the drop on+ // the long-standing "paste the paths into the terminal" path.+ inner.events.dispatch(WindowEvent::DroppedFile {+ paths: filenames,+ coords: None,+ });DragFinish(h_drop);Some(0)diff --git a/window/src/os/x11/window.rs b/window/src/os/x11/window.rsindex c7203448..ae159666 100644--- a/window/src/os/x11/window.rs+++ b/window/src/os/x11/window.rs@@ -68,6 +68,16 @@ struct DragAndDrop {time: u32,target_type: Atom,target_action: Atom,+ /// The window's origin in root coordinates, resolved once when the drag+ /// enters. XdndPosition reports root coordinates, but handlers hit-test+ /// against window coordinates; resolving this per position event would+ /// mean a synchronous round trip per mouse move, and a window does not+ /// move while the user is dragging files onto it.+ window_origin: Option<(i16, i16)>,+ /// Where the pointer was at the last XdndPosition, in window+ /// coordinates. XDND delivers the payload separately from the position,+ /// so the drop has to reuse the position reported just before it.+ last_coords: Option<Point>,}impl Default for DragAndDrop {@@ -79,6 +89,8 @@ impl Default for DragAndDrop {time: 0,target_type: xcb::x::ATOM_NONE,target_action: xcb::x::ATOM_NONE,+ window_origin: None,+ last_coords: None,}}}@@ -746,6 +758,22 @@ impl XWindowInner {let srcwin = unsafe { xcb::x::Window::new(data[0]) };if msgtype == conn.atom_xdndenter {self.drag_and_drop.src_window = Some(srcwin);+ self.drag_and_drop.last_coords = None;+ self.drag_and_drop.window_origin =+ match conn.send_and_wait_request(&xcb::x::TranslateCoordinates {+ src_window: self.window_id,+ dst_window: conn.root,+ src_x: 0,+ src_y: 0,+ }) {+ Ok(coords) => Some((coords.dst_x(), coords.dst_y())),+ Err(err) => {+ // Without an origin the drop still works, it just cannot+ // be aimed at anything in particular.+ log::warn!("xdnd: unable to resolve the window origin: {err:#}");+ None+ }+ };let moretypes = data[1] & 0x01 != 0;let xdndversion = data[1] >> 24 as u8;log::trace!(@@ -809,6 +837,26 @@ impl XWindowInner {self.drag_and_drop.time,conn.atom_name(self.drag_and_drop.src_action));+ self.drag_and_drop.last_coords =+ self.drag_and_drop+ .window_origin+ .map(|(origin_x, origin_y)| {+ Point::new(+ x as isize - origin_x as isize,+ y as isize - origin_y as isize,+ )+ });+ // XDND only transfers the payload on drop, so the hover event+ // reports the position without yet knowing what is being carried.+ // Only announce it for a drag that will actually arrive as files:+ // a text or URL drag ends in DroppedString/DroppedUrl, which no+ // drop target can accept, and advertising one would be a lie.+ if self.drag_and_drop.target_type == conn.atom_texturilist {+ self.events.dispatch(WindowEvent::DraggedFile {+ paths: Vec::new(),+ coords: self.drag_and_drop.last_coords,+ });+ }conn.send_request_no_reply_log(&xcb::x::SendEvent {propagate: false,destination: xcb::x::SendEventDest::Window(srcwin),@@ -827,7 +875,10 @@ impl XWindowInner {});} else if msgtype == conn.atom_xdndleave {self.drag_and_drop.src_window = None;+ self.drag_and_drop.window_origin = None;+ self.drag_and_drop.last_coords = None;log::trace!("ClientMessage {msgtype_name}");+ self.events.dispatch(WindowEvent::DragLeave);} else if msgtype == conn.atom_xdnddrop {self.drag_and_drop.time = data[2];log::trace!(@@ -844,6 +895,7 @@ impl XWindowInner {});} else {log::warn!("XdndDrop received, but no target type selected. Ignoring.");+ self.events.dispatch(WindowEvent::DragLeave);conn.send_request_no_reply_log(&xcb::x::SendEvent {propagate: false,destination: xcb::x::SendEventDest::Window(srcwin),@@ -1322,6 +1374,10 @@ impl XWindowInner {&& selection.property() == conn.atom_xsel_data{if let Some(srcwin) = self.drag_and_drop.src_window {+ // Where the pointer was at the last XdndPosition: the payload+ // arrives here, long after the position that aimed it.+ let coords = self.drag_and_drop.last_coords.take();+ self.drag_and_drop.window_origin = None;match conn.send_and_wait_request(&xcb::x::GetProperty {delete: true,window: selection.requestor(),@@ -1331,20 +1387,28 @@ impl XWindowInner {long_length: u32::max_value(),}) {Ok(prop) => {- if selection.target() == conn.atom_utf8_string {- let text = String::from_utf8_lossy(prop.value()).to_string();- self.events.dispatch(WindowEvent::DroppedString(text));- } else if selection.target() == conn.atom_xmozurl {- let data = decode_dropped_url_string(prop.value());- let urls = parse_xmozurl_list(&data);- self.events.dispatch(WindowEvent::DroppedUrl(urls));- } else if selection.target() == conn.atom_texturilist {+ if selection.target() == conn.atom_texturilist {let paths = parse_texturi_list(prop.value());- self.events.dispatch(WindowEvent::DroppedFile(paths));+ self.events+ .dispatch(WindowEvent::DroppedFile { paths, coords });+ } else {+ // Not files, so no drop target could have accepted+ // it: end the drag before delivering the payload so+ // nothing is left showing an armed target.+ self.events.dispatch(WindowEvent::DragLeave);+ if selection.target() == conn.atom_utf8_string {+ let text = String::from_utf8_lossy(prop.value()).to_string();+ self.events.dispatch(WindowEvent::DroppedString(text));+ } else if selection.target() == conn.atom_xmozurl {+ let data = decode_dropped_url_string(prop.value());+ let urls = parse_xmozurl_list(&data);+ self.events.dispatch(WindowEvent::DroppedUrl(urls));+ }}}Err(err) => {log::error!("clipboard: err while getting clipboard property: {err:#}");+ self.events.dispatch(WindowEvent::DragLeave);}}conn.send_request_no_reply_log(&xcb::x::SendEvent {