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
This commit is contained in:
1 parent
008b7f3796
commit
5c222cfcdc
13 files changed
+147
-8
No files matched your search
Generated
+1
@@ -4686,6 +4686,7 @@ dependencies = [
|
||||
"codec",
|
||||
"colorgrad",
|
||||
"config",
|
||||
"dirs-next",
|
||||
"downcast-rs",
|
||||
"embed-resource",
|
||||
"env-bootstrap",
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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<dyn DownloadHandler>) {
|
||||
self.terminal.borrow_mut().set_download_handler(handler);
|
||||
}
|
||||
|
||||
fn set_config(&self, config: Arc<dyn TerminalConfiguration>) {
|
||||
self.terminal.borrow_mut().set_config(config);
|
||||
}
|
||||
|
||||
+2
-1
@@ -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<dyn Clipboard>) {}
|
||||
fn set_download_handler(&self, _handler: &Arc<dyn DownloadHandler>) {}
|
||||
fn set_config(&self, _config: Arc<dyn TerminalConfiguration>) {}
|
||||
fn get_config(&self) -> Option<Arc<dyn TerminalConfiguration>> {
|
||||
None
|
||||
|
||||
@@ -56,6 +56,10 @@ pub trait AlertHandler {
|
||||
fn alert(&mut self, alert: Alert);
|
||||
}
|
||||
|
||||
pub trait DownloadHandler {
|
||||
fn save_to_downloads(&self, name: Option<String>, data: Vec<u8>);
|
||||
}
|
||||
|
||||
/// Represents an instance of a terminal emulator.
|
||||
pub struct Terminal {
|
||||
/// The terminal model/state
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -327,6 +327,7 @@ pub struct TerminalState {
|
||||
clipboard: Option<Arc<dyn Clipboard>>,
|
||||
device_control_handler: Option<Box<dyn DeviceControlHandler>>,
|
||||
alert_handler: Option<Box<dyn AlertHandler>>,
|
||||
download_handler: Option<Arc<dyn DownloadHandler>>,
|
||||
|
||||
current_dir: Option<Url>,
|
||||
|
||||
@@ -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<dyn DownloadHandler>) {
|
||||
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:
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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<String>,
|
||||
data: Vec<u8>,
|
||||
) -> 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<String>, data: Vec<u8>) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@ use wezterm_toast_notification::*;
|
||||
|
||||
mod cache;
|
||||
mod customglyph;
|
||||
mod download;
|
||||
mod frontend;
|
||||
mod glyphcache;
|
||||
mod markdown;
|
||||
|
||||
@@ -38,6 +38,8 @@ impl TermWindow {
|
||||
let clipboard: Arc<dyn wezterm_term::Clipboard> = Arc::new(ClipboardHelper {
|
||||
window: window.clone(),
|
||||
});
|
||||
let downloader: Arc<dyn wezterm_term::DownloadHandler> =
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -993,6 +993,11 @@ impl TermWindow {
|
||||
window: window.clone(),
|
||||
});
|
||||
pos.pane.set_clipboard(&clipboard);
|
||||
|
||||
let downloader: Arc<dyn wezterm_term::DownloadHandler> =
|
||||
Arc::new(crate::download::Downloader::new());
|
||||
pos.pane.set_download_handler(&downloader);
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -172,6 +172,8 @@ impl super::TermWindow {
|
||||
};
|
||||
|
||||
let clipboard: Arc<dyn wezterm_term::Clipboard> = Arc::new(clipboard);
|
||||
let downloader: Arc<dyn wezterm_term::DownloadHandler> =
|
||||
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!?"))?;
|
||||
|
||||
Reference in new issue
Block a user