From 5c222cfcdc758286b3b2766a613e610ada4beee8 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Wed, 22 Dec 2021 09:17:29 -0700 Subject: [PATCH] term: allow iterm2 file transfer protocol Adds some plumbing to allow the GUI to implement a download handler and connect that up for iterm2 image/file transfers that have their inline property set to false. Previously we'd just log an error. Now we will by default download the file to the user's download directory. This behavior can be turned off via the new `allow_download_protocols` configuration setting. File transfers can be initiated on a remote host via the https://iterm2.com/utilities/it2dl script. When the download completes, a toast notification is shown that will open the file when clicked. refs: https://github.com/wez/wezterm/discussions/1450 --- Cargo.lock | 1 + config/src/lib.rs | 3 + mux/src/localpane.rs | 8 +- mux/src/pane.rs | 3 +- term/src/terminal.rs | 4 + term/src/terminalstate/iterm.rs | 14 ++-- term/src/terminalstate/mod.rs | 6 ++ wezterm-gui/Cargo.toml | 1 + wezterm-gui/src/download.rs | 102 ++++++++++++++++++++++++ wezterm-gui/src/main.rs | 1 + wezterm-gui/src/termwindow/clipboard.rs | 3 + wezterm-gui/src/termwindow/mod.rs | 5 ++ wezterm-gui/src/termwindow/spawn.rs | 4 + 13 files changed, 147 insertions(+), 8 deletions(-) create mode 100644 wezterm-gui/src/download.rs diff --git a/Cargo.lock b/Cargo.lock index 932d8c8b3..1987cbdab 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4686,6 +4686,7 @@ dependencies = [ "codec", "colorgrad", "config", + "dirs-next", "downcast-rs", "embed-resource", "env-bootstrap", diff --git a/config/src/lib.rs b/config/src/lib.rs index 65fb512d0..7088bb3ed 100644 --- a/config/src/lib.rs +++ b/config/src/lib.rs @@ -1251,6 +1251,9 @@ pub struct Config { #[serde(default = "default_unicode_version")] pub unicode_version: u8, + + #[serde(default = "default_true")] + pub allow_download_protocols: bool, } impl_lua_conversion!(Config); diff --git a/mux/src/localpane.rs b/mux/src/localpane.rs index b3013d1af..8f1bcac33 100644 --- a/mux/src/localpane.rs +++ b/mux/src/localpane.rs @@ -22,8 +22,8 @@ use termwiz::surface::{Line, SequenceNo, SEQ_ZERO}; use url::Url; use wezterm_term::color::ColorPalette; use wezterm_term::{ - Alert, AlertHandler, CellAttributes, Clipboard, KeyCode, KeyModifiers, MouseEvent, - SemanticZone, StableRowIndex, Terminal, TerminalConfiguration, + Alert, AlertHandler, CellAttributes, Clipboard, DownloadHandler, KeyCode, KeyModifiers, + MouseEvent, SemanticZone, StableRowIndex, Terminal, TerminalConfiguration, }; #[derive(Debug)] @@ -210,6 +210,10 @@ impl Pane for LocalPane { self.terminal.borrow_mut().set_clipboard(clipboard); } + fn set_download_handler(&self, handler: &Arc) { + self.terminal.borrow_mut().set_download_handler(handler); + } + fn set_config(&self, config: Arc) { self.terminal.borrow_mut().set_config(config); } diff --git a/mux/src/pane.rs b/mux/src/pane.rs index 5fa997313..6c7720df3 100644 --- a/mux/src/pane.rs +++ b/mux/src/pane.rs @@ -16,7 +16,7 @@ use termwiz::surface::{Line, SequenceNo, SEQ_ZERO}; use url::Url; use wezterm_term::color::ColorPalette; use wezterm_term::{ - Clipboard, KeyCode, KeyModifiers, MouseEvent, SemanticZone, StableRowIndex, + Clipboard, DownloadHandler, KeyCode, KeyModifiers, MouseEvent, SemanticZone, StableRowIndex, TerminalConfiguration, }; @@ -363,6 +363,7 @@ pub trait Pane: Downcast { fn is_alt_screen_active(&self) -> bool; fn set_clipboard(&self, _clipboard: &Arc) {} + fn set_download_handler(&self, _handler: &Arc) {} fn set_config(&self, _config: Arc) {} fn get_config(&self) -> Option> { None diff --git a/term/src/terminal.rs b/term/src/terminal.rs index 4fb85833f..e753f90b4 100644 --- a/term/src/terminal.rs +++ b/term/src/terminal.rs @@ -56,6 +56,10 @@ pub trait AlertHandler { fn alert(&mut self, alert: Alert); } +pub trait DownloadHandler { + fn save_to_downloads(&self, name: Option, data: Vec); +} + /// Represents an instance of a terminal emulator. pub struct Terminal { /// The terminal model/state diff --git a/term/src/terminalstate/iterm.rs b/term/src/terminalstate/iterm.rs index d0e5db0c2..6d7cc398e 100644 --- a/term/src/terminalstate/iterm.rs +++ b/term/src/terminalstate/iterm.rs @@ -9,11 +9,15 @@ use termwiz::image::ImageDataType; impl TerminalState { pub(crate) fn set_image(&mut self, image: ITermFileData) { if !image.inline { - error!( - "Ignoring file download request name={:?} size={}", - image.name, - image.data.len() - ); + if let Some(handler) = &self.download_handler { + handler.save_to_downloads(image.name, image.data); + } else { + error!( + "Ignoring file download request name={:?} size={}", + image.name, + image.data.len() + ); + } return; } diff --git a/term/src/terminalstate/mod.rs b/term/src/terminalstate/mod.rs index 799bdbb6a..7b40b8daa 100644 --- a/term/src/terminalstate/mod.rs +++ b/term/src/terminalstate/mod.rs @@ -327,6 +327,7 @@ pub struct TerminalState { clipboard: Option>, device_control_handler: Option>, alert_handler: Option>, + download_handler: Option>, current_dir: Option, @@ -472,6 +473,7 @@ impl TerminalState { clipboard: None, device_control_handler: None, alert_handler: None, + download_handler: None, current_dir: None, term_program: term_program.to_string(), term_version: term_version.to_string(), @@ -513,6 +515,10 @@ impl TerminalState { self.alert_handler.replace(handler); } + pub fn set_download_handler(&mut self, handler: &Arc) { + self.download_handler.replace(handler.clone()); + } + /// Returns the title text associated with the terminal session. /// The title can be changed by the application using a number /// of escape sequences: diff --git a/wezterm-gui/Cargo.toml b/wezterm-gui/Cargo.toml index dbd4ec375..f128e5f6c 100644 --- a/wezterm-gui/Cargo.toml +++ b/wezterm-gui/Cargo.toml @@ -28,6 +28,7 @@ codec = { path = "../codec" } colorgrad = "0.5" config = { path = "../config" } downcast-rs = "1.0" +dirs-next = "2.0" env-bootstrap = { path = "../env-bootstrap" } euclid = "0.22" fastrand = "1.6" diff --git a/wezterm-gui/src/download.rs b/wezterm-gui/src/download.rs new file mode 100644 index 000000000..d79def9ca --- /dev/null +++ b/wezterm-gui/src/download.rs @@ -0,0 +1,102 @@ +use anyhow::Context; +use std::fs::{File, OpenOptions}; +use std::io::Write; +use std::path::PathBuf; + +pub struct Downloader {} + +/// Simple heuristics to try to avoid obvious trickery with +/// the name provided by the remote system +fn neuter_name(name: &str) -> Option<&str> { + let name = match name.rsplit_once(|c| c == '/' || c == '\\') { + Some((_, base)) => base, + None => name, + }; + + if name == "." || name == ".." { + return None; + } + + if name.contains(':') { + return None; + } + + Some(name) +} + +impl Downloader { + pub fn new() -> Self { + Self {} + } + + /// Given a suggested name, make a few attempts to derive a local name + /// in the user's download folder that doesn't conflict with any other + /// files in that folder. + /// Returns the selected name and the opened File on success. + fn resolve_file_name(&self, name: Option<&str>) -> anyhow::Result<(PathBuf, File)> { + let name = name + .and_then(neuter_name) + .unwrap_or("downloaded-via-wezterm"); + + let download_dir = dirs_next::download_dir() + .ok_or_else(|| anyhow::anyhow!("unable to locate download directory"))?; + + for n in 0..20 { + let candidate = if n == 0 { + download_dir.join(name) + } else { + download_dir.join(&format!("{}.{}", name, n)) + }; + + if let Ok(file) = OpenOptions::new() + .write(true) + .create_new(true) + .open(&candidate) + { + return Ok((candidate, file)); + } + } + + anyhow::bail!( + "Unable to find non-conflicting download name for {} in {}", + name, + download_dir.display() + ); + } + + fn save_to_downloads_impl( + &self, + orig_name: Option, + data: Vec, + ) -> anyhow::Result<()> { + let (name, mut file) = self.resolve_file_name(orig_name.as_deref())?; + file.write_all(&data) + .with_context(|| format!("writing {} of data to {}", data.len(), name.display()))?; + + let url = format!("file://{}", name.display()); + wezterm_toast_notification::persistent_toast_notification_with_click_to_open_url( + "Download completed", + &format!("Downloaded {}", name.display()), + &url, + ); + + log::info!("Downloaded {}", name.display()); + + Ok(()) + } +} + +impl wezterm_term::DownloadHandler for Downloader { + fn save_to_downloads(&self, name: Option, data: Vec) { + if !config::configuration().allow_download_protocols { + log::error!( + "Ignoring download request for {:?}, as allow_download_protocols=false", + name + ); + return; + } + if let Err(err) = self.save_to_downloads_impl(name, data) { + log::error!("failed to download: {:#}", err); + } + } +} diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rs index 4fc52aebe..ad208422d 100644 --- a/wezterm-gui/src/main.rs +++ b/wezterm-gui/src/main.rs @@ -23,6 +23,7 @@ use wezterm_toast_notification::*; mod cache; mod customglyph; +mod download; mod frontend; mod glyphcache; mod markdown; diff --git a/wezterm-gui/src/termwindow/clipboard.rs b/wezterm-gui/src/termwindow/clipboard.rs index b9e56ce92..92791b3b1 100644 --- a/wezterm-gui/src/termwindow/clipboard.rs +++ b/wezterm-gui/src/termwindow/clipboard.rs @@ -38,6 +38,8 @@ impl TermWindow { let clipboard: Arc = Arc::new(ClipboardHelper { window: window.clone(), }); + let downloader: Arc = + Arc::new(crate::download::Downloader::new()); let mux = Mux::get().unwrap(); let mut mux_window = mux.get_window_mut(mux_window_id).unwrap(); @@ -46,6 +48,7 @@ impl TermWindow { for tab in mux_window.iter() { for pos in tab.iter_panes() { pos.pane.set_clipboard(&clipboard); + pos.pane.set_download_handler(&downloader); } } } diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs index 99b5889cb..11671b1b2 100644 --- a/wezterm-gui/src/termwindow/mod.rs +++ b/wezterm-gui/src/termwindow/mod.rs @@ -993,6 +993,11 @@ impl TermWindow { window: window.clone(), }); pos.pane.set_clipboard(&clipboard); + + let downloader: Arc = + Arc::new(crate::download::Downloader::new()); + pos.pane.set_download_handler(&downloader); + break; } } diff --git a/wezterm-gui/src/termwindow/spawn.rs b/wezterm-gui/src/termwindow/spawn.rs index ea06097c4..2d4ea58aa 100644 --- a/wezterm-gui/src/termwindow/spawn.rs +++ b/wezterm-gui/src/termwindow/spawn.rs @@ -172,6 +172,8 @@ impl super::TermWindow { }; let clipboard: Arc = Arc::new(clipboard); + let downloader: Arc = + Arc::new(crate::download::Downloader::new()); match spawn_where { SpawnWhere::SplitPane(direction) => { @@ -187,6 +189,7 @@ impl super::TermWindow { .await?; pane.set_config(term_config); pane.set_clipboard(&clipboard); + pane.set_download_handler(&downloader); } else { bail!("there is no active tab while splitting pane!?"); } @@ -203,6 +206,7 @@ impl super::TermWindow { if spawn_where != SpawnWhere::NewWindow { pane.set_clipboard(&clipboard); + pane.set_download_handler(&downloader); let mut window = mux .get_window_mut(target_window_id) .ok_or_else(|| anyhow!("no such window!?"))?;