Skip to content

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

Fix palette ownership and typed clipboard races

RoversX3bff44eae27b
diff --git a/Cargo.lock b/Cargo.lock
index c3b7262f..a666558f 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -779,11 +779,11 @@ checksum = "a1d728cc89cf3aee9ff92b05e62b19ee65a02b5702cff7d5a377e32c6ae29d8d"
[[package]]
name = "clipboard-win"
-version = "2.2.0"
+version = "5.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e3a093d6fed558e5fe24c3dfc85a68bb68f1c824f440d3ba5aca189e2998786b"
+checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4"
dependencies = [
- "winapi",
+ "error-code",
]
[[package]]
@@ -1588,6 +1588,12 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "error-code"
+version = "3.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dea2df4cf52843e0452895c455a1a2cfbb842a1e7329671acf418fdc53ed4c59"
+
[[package]]
name = "euclid"
version = "0.22.11"
diff --git a/Cargo.toml b/Cargo.toml
index 257d09dd..76d90677 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -64,7 +64,7 @@ chrono = {version="0.4", default-features=false, features=["unstable-locales", "
clap = {version="4.0", features=["derive"]}
clap_complete = "4.4"
clap_complete_fig = "4.0"
-clipboard-win = "2.2"
+clipboard-win = "5"
cocoa = "=0.25.0"
codec = { path = "codec" }
color-funcs = { path = "lua-api-crates/color-funcs" }
diff --git a/codec/src/lib.rs b/codec/src/lib.rs
index 2ea649a8..8c5c17de 100644
--- a/codec/src/lib.rs
+++ b/codec/src/lib.rs
@@ -443,7 +443,9 @@ macro_rules! pdu {
/// are made to the types and protocol.
/// 47: PaneStackEntry gained pane_stack_id; stack operation PDUs.
/// 48: MovePaneToStack moves an existing pane into another pane stack.
-pub const CODEC_VERSION: usize = 48;
+/// 49: Palette advisories are client-only, application palette state is
+/// explicit, and SetFocusedPane carries the focusing client's palette.
+pub const CODEC_VERSION: usize = 49;
// Defines the Pdu enum.
// Each struct has an explicit identifying number.
@@ -507,6 +509,7 @@ pdu! {
SpawnPaneInStack: 63,
ActivatePaneInStack: 64,
MovePaneToStack: 65,
+ SetApplicationPalette: 66,
}
impl Pdu {
@@ -600,6 +603,7 @@ impl Pdu {
match self {
Pdu::GetPaneRenderChangesResponse(GetPaneRenderChangesResponse { pane_id, .. })
| Pdu::SetPalette(SetPalette { pane_id, .. })
+ | Pdu::SetApplicationPalette(SetApplicationPalette { pane_id, .. })
| Pdu::NotifyAlert(NotifyAlert { pane_id, .. })
| Pdu::SetClipboard(SetClipboard { pane_id, .. })
| Pdu::PaneFocused(PaneFocused { pane_id })
@@ -815,15 +819,24 @@ pub struct RenameWorkspace {
pub new_workspace: String,
}
-/// This is used both as a notification from server->client
-/// and as a configuration request from client->server when
-/// the client's preferred configuration changes
+/// A client-to-server advisory carrying that client's configured palette.
+/// The server uses this as the base for OSC color queries while that client
+/// owns the pane's palette, but must never broadcast it as application state.
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct SetPalette {
pub pane_id: PaneId,
pub palette: ColorPalette,
}
+/// Server-to-client state of the palette override owned by the application
+/// running in the pane. `None` means that the client must render using its own
+/// configured palette; `Some` is authoritative until a later reset.
+#[derive(Deserialize, Serialize, PartialEq, Debug)]
+pub struct SetApplicationPalette {
+ pub pane_id: PaneId,
+ pub palette: Option<ColorPalette>,
+}
+
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct NotifyAlert {
pub pane_id: PaneId,
@@ -873,6 +886,9 @@ pub struct SetClientId {
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct SetFocusedPane {
pub pane_id: PaneId,
+ /// GUI mux clients include their configured palette so that focus and OSC
+ /// palette ownership change atomically. Non-rendering CLI clients use None.
+ pub configured_palette: Option<ColorPalette>,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
@@ -1243,6 +1259,50 @@ mod test {
);
}
+ #[test]
+ fn application_palette_state_round_trip() {
+ for palette in [None, Some(ColorPalette::default())] {
+ let mut encoded = Vec::new();
+ Pdu::SetApplicationPalette(SetApplicationPalette {
+ pane_id: 17,
+ palette: palette.clone(),
+ })
+ .encode(&mut encoded, 0x42)
+ .unwrap();
+ assert_eq!(
+ Pdu::decode(encoded.as_slice()).unwrap(),
+ DecodedPdu {
+ serial: 0x42,
+ pdu: Pdu::SetApplicationPalette(SetApplicationPalette {
+ pane_id: 17,
+ palette,
+ }),
+ }
+ );
+ }
+ }
+
+ #[test]
+ fn focused_pane_palette_round_trip() {
+ let mut encoded = Vec::new();
+ Pdu::SetFocusedPane(SetFocusedPane {
+ pane_id: 29,
+ configured_palette: Some(ColorPalette::default()),
+ })
+ .encode(&mut encoded, 0x43)
+ .unwrap();
+ assert_eq!(
+ Pdu::decode(encoded.as_slice()).unwrap(),
+ DecodedPdu {
+ serial: 0x43,
+ pdu: Pdu::SetFocusedPane(SetFocusedPane {
+ pane_id: 29,
+ configured_palette: Some(ColorPalette::default()),
+ }),
+ }
+ );
+ }
+
#[test]
fn stream_decode() {
let mut encoded = Vec::new();
diff --git a/config/src/terminal.rs b/config/src/terminal.rs
index 8ff78206..81e6b513 100644
--- a/config/src/terminal.rs
+++ b/config/src/terminal.rs
@@ -35,6 +35,10 @@ impl TermConfig {
self.client_palette.lock().unwrap().replace(palette);
}
+ pub fn clear_client_palette(&self) {
+ self.client_palette.lock().unwrap().take();
+ }
+
fn configuration(&self) -> ConfigHandle {
match self.config.lock().unwrap().as_ref() {
Some(h) => h.clone(),
diff --git a/mux/src/lib.rs b/mux/src/lib.rs
index 2e882a2e..04412cb7 100644
--- a/mux/src/lib.rs
+++ b/mux/src/lib.rs
@@ -29,6 +29,7 @@ use std::time::{Duration, Instant};
use termwiz::escape::csi::{DecPrivateMode, DecPrivateModeCode, Device, Mode};
use termwiz::escape::{Action, CSI};
use thiserror::*;
+use wezterm_term::color::ColorPalette;
use wezterm_term::{
Clipboard, ClipboardSelection, DownloadHandler, TerminalConfiguration, TerminalSize,
};
@@ -100,6 +101,118 @@ pub enum MuxNotification {
}
static SUB_ID: AtomicUsize = AtomicUsize::new(0);
+static PALETTE_SESSION_ID: AtomicUsize = AtomicUsize::new(1);
+
+/// A single mux-server transport connection. `ClientId` identifies the GUI
+/// process and can be reused when that process reconnects, so it is not
+/// sufficient to reject work queued by an older, disconnected transport.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub struct PaletteSessionId(usize);
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct PaletteSelectionChange {
+ pub pane_id: PaneId,
+ pub palette: Option<ColorPalette>,
+}
+
+/// Server-side palette advice is scoped to the client that supplied it.
+/// Merely attaching records advice; focus or real input activates it for OSC
+/// queries. Application palette overrides are tracked by the terminal and are
+/// intentionally not represented here.
+#[derive(Default)]
+struct PaletteAdvisoryState {
+ sessions: HashMap<PaletteSessionId, ClientId>,
+ advised: HashMap<(PaletteSessionId, PaneId), ColorPalette>,
+ activity: HashMap<(PaletteSessionId, PaneId), u64>,
+ owners: HashMap<PaneId, PaletteSessionId>,
+ next_activity: u64,
+}
+
+impl PaletteAdvisoryState {
+ fn register(&mut self, client_id: &ClientId) -> PaletteSessionId {
+ let session_id = PaletteSessionId(PALETTE_SESSION_ID.fetch_add(1, Ordering::Relaxed));
+ self.sessions.insert(session_id, client_id.clone());
+ session_id
+ }
+
+ fn advise(
+ &mut self,
+ session_id: PaletteSessionId,
+ pane_id: PaneId,
+ palette: ColorPalette,
+ ) -> Option<ColorPalette> {
+ if !self.sessions.contains_key(&session_id) {
+ return None;
+ }
+ self.advised.insert((session_id, pane_id), palette.clone());
+ (self.owners.get(&pane_id) == Some(&session_id)).then_some(palette)
+ }
+
+ fn activate(&mut self, session_id: PaletteSessionId, pane_id: PaneId) -> Option<ColorPalette> {
+ if !self.sessions.contains_key(&session_id) {
+ return None;
+ }
+ let key = (session_id, pane_id);
+ let palette = self.advised.get(&key)?.clone();
+ self.next_activity = self.next_activity.saturating_add(1).max(1);
+ self.activity.insert(key, self.next_activity);
+
+ if self.owners.get(&pane_id) == Some(&session_id) {
+ return None;
+ }
+ self.owners.insert(pane_id, session_id);
+ Some(palette)
+ }
+
+ fn remove_session(&mut self, session_id: PaletteSessionId) -> Vec<PaletteSelectionChange> {
+ self.sessions.remove(&session_id);
+ self.advised.retain(|(id, _), _| *id != session_id);
+ self.activity.retain(|(id, _), _| *id != session_id);
+
+ let affected: Vec<PaneId> = self
+ .owners
+ .iter()
+ .filter_map(|(pane_id, owner)| (*owner == session_id).then_some(*pane_id))
+ .collect();
+ let mut changes = Vec::with_capacity(affected.len());
+
+ for pane_id in affected {
+ let replacement = self
+ .activity
+ .iter()
+ .filter(|((candidate_session, candidate_pane), _)| {
+ *candidate_pane == pane_id
+ && self.sessions.contains_key(candidate_session)
+ && self.advised.contains_key(&(*candidate_session, pane_id))
+ })
+ .max_by_key(|(_, activity)| **activity)
+ .map(|((id, _), _)| *id);
+
+ let palette = match replacement {
+ Some(id) => {
+ self.owners.insert(pane_id, id);
+ self.advised.get(&(id, pane_id)).cloned()
+ }
+ None => {
+ self.owners.remove(&pane_id);
+ None
+ }
+ };
+ changes.push(PaletteSelectionChange { pane_id, palette });
+ }
+ changes
+ }
+
+ fn deactivate_session(&mut self, session_id: PaletteSessionId) -> bool {
+ self.sessions.remove(&session_id).is_some()
+ }
+
+ fn remove_pane(&mut self, pane_id: PaneId) {
+ self.advised.retain(|(_, pane), _| *pane != pane_id);
+ self.activity.retain(|(_, pane), _| *pane != pane_id);
+ self.owners.remove(&pane_id);
+ }
+}
pub struct Mux {
tabs: RwLock<HashMap<TabId, Arc<Tab>>>,
@@ -111,6 +224,7 @@ pub struct Mux {
subscribers: RwLock<HashMap<usize, Box<dyn Fn(MuxNotification) -> bool + Send + Sync>>>,
banner: RwLock<Option<String>>,
clients: RwLock<HashMap<ClientId, ClientInfo>>,
+ palette_advisories: Mutex<PaletteAdvisoryState>,
identity: RwLock<Option<Arc<ClientId>>>,
num_panes_by_workspace: RwLock<HashMap<String, usize>>,
main_thread_id: std::thread::ThreadId,
@@ -451,6 +565,7 @@ impl Mux {
subscribers: RwLock::new(HashMap::new()),
banner: RwLock::new(None),
clients: RwLock::new(HashMap::new()),
+ palette_advisories: Mutex::new(PaletteAdvisoryState::default()),
identity: RwLock::new(None),
num_panes_by_workspace: RwLock::new(HashMap::new()),
main_thread_id: std::thread::current().id(),
@@ -692,10 +807,61 @@ impl Mux {
self.identity.read().clone()
}
+ /// Remove a client from the ordinary mux client list.
+ /// Palette ownership is connection-scoped and is cleaned independently.
pub fn unregister_client(&self, client_id: &ClientId) {
self.clients.write().remove(client_id);
}
+ /// Register one transport connection for palette advice. The returned
+ /// token must be captured by queued handlers so work from a disconnected
+ /// connection cannot be mistaken for a later connection with the same
+ /// `ClientId`.
+ pub fn register_palette_session(&self, client_id: &ClientId) -> PaletteSessionId {
+ self.palette_advisories.lock().register(client_id)
+ }
+
+ /// Remove exactly one transport connection and return any pane palette
+ /// selections that need to be applied as a result of owner fallback.
+ pub fn unregister_palette_session(
+ &self,
+ session_id: PaletteSessionId,
+ ) -> Vec<PaletteSelectionChange> {
+ self.palette_advisories.lock().remove_session(session_id)
+ }
+
+ /// Immediately reject further queued work from a disconnected transport.
+ /// Final removal and pane fallback are deliberately a separate operation
+ /// so the caller can serialize their application on the mux main thread.
+ pub fn deactivate_palette_session(&self, session_id: PaletteSessionId) -> bool {
+ self.palette_advisories
+ .lock()
+ .deactivate_session(session_id)
+ }
+
+ /// Store a client's configured palette. A return value means that client
+ /// currently owns this pane and the server's OSC query base must update.
+ pub fn advise_client_palette(
+ &self,
+ session_id: PaletteSessionId,
+ pane_id: PaneId,
+ palette: ColorPalette,
+ ) -> Option<ColorPalette> {
+ self.palette_advisories
+ .lock()
+ .advise(session_id, pane_id, palette)
+ }
+
+ /// Mark focus or input from a palette-capable client. Background clients
+ /// that have not supplied advice cannot take ownership.
+ pub fn activate_client_palette(
+ &self,
+ session_id: PaletteSessionId,
+ pane_id: PaneId,
+ ) -> Option<ColorPalette> {
+ self.palette_advisories.lock().activate(session_id, pane_id)
+ }
+
pub fn subscribe<F>(&self, subscriber: F)
where
F: Fn(MuxNotification) -> bool + 'static + Send + Sync,
@@ -818,6 +984,7 @@ impl Mux {
fn remove_pane_internal(&self, pane_id: PaneId) {
log::debug!("removing pane {}", pane_id);
+ self.palette_advisories.lock().remove_pane(pane_id);
let mut changed = false;
if let Some(pane) = self.panes.write().remove(&pane_id).clone() {
log::debug!("killing pane {}", pane_id);
@@ -1749,6 +1916,169 @@ impl wezterm_term::DownloadHandler for MuxDownloader {
mod tests {
use super::*;
+ fn client_id(id: usize) -> ClientId {
+ ClientId {
+ hostname: "test-host".to_string(),
+ username: "test-user".to_string(),
+ pid: id as u32,
+ epoch: 1,
+ id,
+ ssh_auth_sock: None,
+ }
+ }
+
+ fn palette(foreground: f32) -> ColorPalette {
+ let mut palette = ColorPalette::default();
+ palette.foreground = (foreground, foreground, foreground, 1.0).into();
+ palette
+ }
+
+ #[test]
+ fn palette_advice_requires_interaction_to_take_ownership() {
+ let mut state = PaletteAdvisoryState::default();
+ let white_client = client_id(1);
+ let gray_client = client_id(2);
+ let white_session = state.register(&white_client);
+ let gray_session = state.register(&gray_client);
+ let white = palette(1.0);
+ let gray = palette(0.7);
+
+ assert_eq!(state.advise(white_session, 9, white.clone()), None);
+ assert_eq!(state.activate(white_session, 9), Some(white.clone()));
+
+ // A background attach records its preference but cannot replace the
+ // active client's OSC query base.
+ assert_eq!(state.advise(gray_session, 9, gray.clone()), None);
+ assert_eq!(state.owners.get(&9), Some(&white_session));
+
+ assert_eq!(state.activate(gray_session, 9), Some(gray));
+ assert_eq!(state.owners.get(&9), Some(&gray_session));
+
+ // A config reload by the inactive client is stored without stealing.
+ let warmer_white = palette(0.95);
+ assert_eq!(state.advise(white_session, 9, warmer_white.clone()), None);
+ assert_eq!(state.owners.get(&9), Some(&gray_session));
+
+ // Removing the current owner falls back to the most recently active
+ // surviving client and its latest advice.
+ assert_eq!(
+ state.remove_session(gray_session),
+ vec![PaletteSelectionChange {
+ pane_id: 9,
+ palette: Some(warmer_white),
+ }]
+ );
+ assert_eq!(state.owners.get(&9), Some(&white_session));
+ }
+
+ #[test]
+ fn disconnect_does_not_promote_a_background_only_advisor() {
+ let mut state = PaletteAdvisoryState::default();
+ let active = client_id(1);
+ let background = client_id(2);
+ let active_session = state.register(&active);
+ let background_session = state.register(&background);
+ assert_eq!(state.advise(active_session, 7, palette(1.0)), None);
+ assert!(state.activate(active_session, 7).is_some());
+ assert_eq!(state.advise(background_session, 7, palette(0.7)), None);
+
+ assert_eq!(
+ state.remove_session(active_session),
+ vec![PaletteSelectionChange {
+ pane_id: 7,
+ palette: None,
+ }]
+ );
+ assert!(!state.owners.contains_key(&7));
+ }
+
+ #[test]
+ fn active_palette_reload_updates_without_new_interaction() {
+ let mut state = PaletteAdvisoryState::default();
+ let client = client_id(1);
+ let session = state.register(&client);
+ assert_eq!(state.advise(session, 4, palette(0.8)), None);
+ assert!(state.activate(session, 4).is_some());
+
+ let updated = palette(1.0);
+ assert_eq!(state.advise(session, 4, updated.clone()), Some(updated));
+ assert_eq!(state.activate(session, 4), None);
+ }
+
+ #[test]
+ fn late_palette_updates_from_a_disconnected_client_are_rejected() {
+ let mut state = PaletteAdvisoryState::default();
+ let client = client_id(1);
+ let session = state.register(&client);
+
+ assert_eq!(state.advise(session, 4, palette(0.8)), None);
+ assert!(state.activate(session, 4).is_some());
+ assert!(state.deactivate_session(session));
+
+ // A SessionHandler can already have this work queued when Drop runs.
+ // Once disconnect cleanup has happened, that stale work must not be
+ // able to recreate advice or ownership for the dead connection.
+ assert_eq!(state.advise(session, 4, palette(0.6)), None);
+ assert_eq!(state.activate(session, 4), None);
+ assert_eq!(state.advised.get(&(session, 4)), Some(&palette(0.8)));
+ assert_eq!(state.owners.get(&4), Some(&session));
+
+ state.remove_session(session);
+ assert!(!state.owners.contains_key(&4));
+ }
+
+ #[test]
+ fn old_disconnect_cannot_remove_or_overwrite_a_reconnected_session() {
+ let mut state = PaletteAdvisoryState::default();
+ let client = client_id(1);
+ let old_session = state.register(&client);
+ assert_eq!(state.advise(old_session, 4, palette(0.6)), None);
+ assert!(state.activate(old_session, 4).is_some());
+
+ // A reconnect legitimately reuses ClientId, but is a distinct
+ // transport whose ownership must survive cleanup of the old one.
+ let new_session = state.register(&client);
+ let new_palette = palette(1.0);
+ assert_eq!(state.advise(new_session, 4, new_palette.clone()), None);
+ assert_eq!(state.activate(new_session, 4), Some(new_palette.clone()));
+
+ assert!(state.deactivate_session(old_session));
+ assert_eq!(state.advise(old_session, 4, palette(0.2)), None);
+ assert_eq!(state.owners.get(&4), Some(&new_session));
+
+ // Final cleanup happens later on the mux thread; it must observe that
+ // the reconnect has already become owner and leave it untouched.
+ assert_eq!(state.remove_session(old_session), vec![]);
+ assert_eq!(state.owners.get(&4), Some(&new_session));
+ assert_eq!(state.advised.get(&(new_session, 4)), Some(&new_palette));
+ }
+
+ #[test]
+ fn fallback_never_promotes_an_already_disconnected_session() {
+ let mut state = PaletteAdvisoryState::default();
+ let first = state.register(&client_id(1));
+ let owner = state.register(&client_id(2));
+
+ assert_eq!(state.advise(first, 4, palette(0.6)), None);
+ assert!(state.activate(first, 4).is_some());
+ assert_eq!(state.advise(owner, 4, palette(1.0)), None);
+ assert!(state.activate(owner, 4).is_some());
+
+ // Both drops can deactivate synchronously before either queued final
+ // cleanup runs. Removing the owner must not temporarily promote the
+ // other disconnected session as the pane's OSC query base.
+ assert!(state.deactivate_session(owner));
+ assert!(state.deactivate_session(first));
+ assert_eq!(
+ state.remove_session(owner),
+ vec![PaletteSelectionChange {
+ pane_id: 4,
+ palette: None,
+ }]
+ );
+ assert!(!state.owners.contains_key(&4));
+ }
+
#[test]
fn window_ui_surfaces_are_distinct_prune_anchors() {
let mux = Mux::new(None);
diff --git a/mux/src/localpane.rs b/mux/src/localpane.rs
index 1313f5bd..03b5fe6c 100644
--- a/mux/src/localpane.rs
+++ b/mux/src/localpane.rs
@@ -486,6 +486,10 @@ impl Pane for LocalPane {
self.terminal.lock().palette()
}
+ fn palette_override(&self) -> Option<ColorPalette> {
+ self.terminal.lock().palette_override()
+ }
+
fn domain_id(&self) -> DomainId {
self.domain_id
}
diff --git a/mux/src/pane.rs b/mux/src/pane.rs
index a0826492..edf19cb2 100644
--- a/mux/src/pane.rs
+++ b/mux/src/pane.rs
@@ -252,6 +252,11 @@ pub trait Pane: Downcast + Send + Sync {
fn is_dead(&self) -> bool;
fn kill(&self) {}
fn palette(&self) -> ColorPalette;
+ /// Palette state explicitly established by the application. `None`
+ /// means that consumers should use their configured palette.
+ fn palette_override(&self) -> Option<ColorPalette> {
+ None
+ }
fn domain_id(&self) -> DomainId;
fn get_keyboard_encoding(&self) -> KeyboardEncoding {
diff --git a/mux/src/tab.rs b/mux/src/tab.rs
index 8de716ba..e2ef625b 100644
--- a/mux/src/tab.rs
+++ b/mux/src/tab.rs
@@ -2945,15 +2945,13 @@ impl TabInner {
}
}
- let src_pane = src_pane
- .ok_or_else(|| anyhow::anyhow!("pane {src_pane_id} not found in tab"))?;
+ let src_pane =
+ src_pane.ok_or_else(|| anyhow::anyhow!("pane {src_pane_id} not found in tab"))?;
if !target_found {
anyhow::bail!("pane {target_pane_id} not found in tab");
}
if same_stack {
- anyhow::bail!(
- "panes {src_pane_id} and {target_pane_id} are already in the same stack"
- );
+ anyhow::bail!("panes {src_pane_id} and {target_pane_id} are already in the same stack");
}
// The only fallible step happens before the tree is touched: if the
@@ -2979,9 +2977,8 @@ impl TabInner {
if cursor.is_leaf() {
let stack = cursor.leaf_mut().unwrap();
if stack.contains_pane(target_pane_id) {
- if let Some(base) = stack
- .active_pane()
- .filter(|_| !removed.is_remote_mirror())
+ if let Some(base) =
+ stack.active_pane().filter(|_| !removed.is_remote_mirror())
{
let dims = base.get_dimensions();
if let Err(err) = removed.resize(TerminalSize {
@@ -3059,7 +3056,10 @@ impl TabInner {
let mut cursor = tree.cursor();
loop {
if cursor.is_leaf() {
- cursor.leaf_mut().unwrap().push_and_activate(Arc::clone(pane));
+ cursor
+ .leaf_mut()
+ .unwrap()
+ .push_and_activate(Arc::clone(pane));
done = true;
}
match cursor.preorder_next() {
@@ -3978,11 +3978,13 @@ mod test {
let size = test_size();
let tab = Tab::new(&size);
tab.assign_pane(&FakePane::new(1, size));
- let horz_size = tab
- .compute_split_size(0, SplitRequest::default())
- .unwrap();
- tab.split_and_insert(0, SplitRequest::default(), FakePane::new(2, horz_size.second))
- .unwrap();
+ let horz_size = tab.compute_split_size(0, SplitRequest::default()).unwrap();
+ tab.split_and_insert(
+ 0,
+ SplitRequest::default(),
+ FakePane::new(2, horz_size.second),
+ )
+ .unwrap();
tab.add_pane_to_stack(1, FakePane::new(3, size)).unwrap();
assert_eq!(tab.count_panes(), Some(3));
@@ -4012,11 +4014,13 @@ mod test {
let size = test_size();
let tab = Tab::new(&size);
tab.assign_pane(&FakePane::new(1, size));
- let horz_size = tab
- .compute_split_size(0, SplitRequest::default())
- .unwrap();
- tab.split_and_insert(0, SplitRequest::default(), FakePane::new(2, horz_size.second))
- .unwrap();
+ let horz_size = tab.compute_split_size(0, SplitRequest::default()).unwrap();
+ tab.split_and_insert(
+ 0,
+ SplitRequest::default(),
+ FakePane::new(2, horz_size.second),
+ )
+ .unwrap();
tab.move_pane_to_stack(1, 2).unwrap();
@@ -4266,7 +4270,8 @@ mod test {
size: Default::default(),
};
let target_index = tab.pane_index_for_pane(1).unwrap();
- tab.split_and_insert(target_index, request, removed).unwrap();
+ tab.split_and_insert(target_index, request, removed)
+ .unwrap();
assert_eq!(tab.count_panes(), Some(2));
assert!(tab.pane_index_for_pane(1).is_some());
diff --git a/mux/src/termwiztermtab.rs b/mux/src/termwiztermtab.rs
index 908e6c8a..07ebaedb 100644
--- a/mux/src/termwiztermtab.rs
+++ b/mux/src/termwiztermtab.rs
@@ -278,6 +278,10 @@ impl Pane for TermWizTerminalPane {
self.terminal.lock().palette()
}
+ fn palette_override(&self) -> Option<ColorPalette> {
+ self.terminal.lock().palette_override()
+ }
+
fn domain_id(&self) -> DomainId {
self.domain_id
}
diff --git a/term/src/terminalstate/mod.rs b/term/src/terminalstate/mod.rs
index 83c67f79..45fbf303 100644
--- a/term/src/terminalstate/mod.rs
+++ b/term/src/terminalstate/mod.rs
@@ -667,6 +667,15 @@ impl TerminalState {
.unwrap_or_else(|| self.config.color_palette())
}
+ /// Returns only the palette state established by terminal escape
+ /// sequences. Unlike [`Self::palette`], this does not fall back to the
+ /// configured palette. Remote mux clients use the distinction to decide
+ /// whether application state is authoritative or local configuration
+ /// should be used.
+ pub fn palette_override(&self) -> Option<ColorPalette> {
+ self.palette.clone()
+ }
+
/// Called in response to dynamic color scheme escape sequences.
/// Will make a copy of the palette from the config file if this
/// is the first of these escapes we've seen.
diff --git a/term/src/test/mod.rs b/term/src/test/mod.rs
index 2edf634c..1069fe87 100644
--- a/term/src/test/mod.rs
+++ b/term/src/test/mod.rs
@@ -198,6 +198,29 @@ impl DerefMut for TestTerm {
}
}
+#[test]
+fn application_palette_override_tracks_osc_set_query_and_reset() {
+ let mut term = TestTerm::new(4, 8, 0);
+ assert!(term.palette_override().is_none());
+
+ // A query is observational and must not make the configured palette
+ // authoritative on remote renderers.
+ term.print("\x1b]10;?\x07");
+ assert!(term.palette_override().is_none());
+
+ term.print("\x1b]10;#ffffff\x07");
+ let override_palette = term.palette_override().expect("OSC 10 override");
+ assert_eq!(override_palette.foreground, (1.0, 1.0, 1.0, 1.0).into());
+
+ term.print("\x1b]110\x07");
+ assert!(term.palette_override().is_none());
+
+ term.print("\x1b]10;#ffffff\x07");
+ assert!(term.palette_override().is_some());
+ term.print("\x1bc");
+ assert!(term.palette_override().is_none());
+}
+
/// Asserts that both line slices match according to the
/// selected flags.
fn assert_lines_equal(
diff --git a/wezterm-client/src/pane/clientpane.rs b/wezterm-client/src/pane/clientpane.rs
index 40779fff..047164fa 100644
--- a/wezterm-client/src/pane/clientpane.rs
+++ b/wezterm-client/src/pane/clientpane.rs
@@ -6,6 +6,7 @@ use async_trait::async_trait;
use codec::*;
use config::configuration;
use config::keyassignment::ScrollbackEraseMode;
+use futures::lock::Mutex as AsyncMutex;
use mux::domain::DomainId;
use mux::pane::{
alloc_pane_id, CachePolicy, CloseReason, ForEachPaneLogicalLine, LogicalLine, Pane, PaneId,
@@ -38,6 +39,32 @@ struct ResizeDecision {
send_rpc: bool,
}
+#[derive(Debug, PartialEq)]
+struct ApplicationPaletteTransition {
+ palette: ColorPalette,
+ application_palette: bool,
+ palette_changed: bool,
+ provenance_changed: bool,
+}
+
+fn application_palette_transition(
+ current: &ColorPalette,
+ configured: &ColorPalette,
+ was_application_palette: bool,
+ update: Option<ColorPalette>,
+) -> ApplicationPaletteTransition {
+ let (palette, application_palette) = match update {
+ Some(palette) => (palette, true),
+ None => (configured.clone(), false),
+ };
+ ApplicationPaletteTransition {
+ palette_changed: current != &palette,
+ provenance_changed: was_application_palette != application_palette,
+ palette,
+ application_palette,
+ }
+}
+
fn render_dimensions_match_size(dimensions: RenderableDimensions, size: TerminalSize) -> bool {
dimensions.cols == size.cols
&& dimensions.viewport_rows == size.rows
@@ -135,11 +162,15 @@ pub struct ClientPane {
pub remote_pane_id: PaneId,
remote_tab_id: AtomicUsize,
pub renderable: Mutex<RenderableState>,
- configured_palette: Mutex<ColorPalette>,
+ configured_palette: Arc<Mutex<ColorPalette>>,
/// Delivery state for the palette advisory: what we want the server to
/// hold and what it last confirmed. A single worker task drains it; see
/// [`PaletteDelivery`].
delivered_palette: Arc<Mutex<PaletteDelivery>>,
+ /// Serializes the two RPCs that can mutate this client's advisory on the
+ /// server: SetPalette and the palette-bearing SetFocusedPane. Without
+ /// this, an older focus task can race a config reload and land last.
+ palette_rpc_lock: Arc<AsyncMutex<()>>,
palette: Mutex<ColorPalette>,
application_palette: Mutex<bool>,
writer: Mutex<PaneWriter>,
@@ -164,6 +195,7 @@ impl ClientPane {
remote_pane_id: PaneId,
palette: ColorPalette,
delivery: Arc<Mutex<PaletteDelivery>>,
+ rpc_lock: Arc<AsyncMutex<()>>,
) {
if !delivery.lock().adopt_target(palette) {
return;
@@ -176,13 +208,16 @@ impl ClientPane {
// Delivered everything we wanted; the slot is released.
return;
};
- let result = client
- .client
- .set_configured_palette_for_pane(SetPalette {
- pane_id: remote_pane_id,
- palette: target.clone(),
- })
- .await;
+ let result = {
+ let _guard = rpc_lock.lock().await;
+ client
+ .client
+ .set_configured_palette_for_pane(SetPalette {
+ pane_id: remote_pane_id,
+ palette: target.clone(),
+ })
+ .await
+ };
match result {
Ok(_) => {
failures = 0;
@@ -239,6 +274,7 @@ impl ClientPane {
self.remote_pane_id,
palette,
Arc::clone(&self.delivered_palette),
+ Arc::clone(&self.palette_rpc_lock),
);
}
@@ -293,11 +329,13 @@ impl ClientPane {
// defaults forever — and an application that queries-then-restores
// the foreground would then paint the pane in those defaults.
let delivered_palette = Arc::new(Mutex::new(PaletteDelivery::default()));
+ let palette_rpc_lock = Arc::new(AsyncMutex::new(()));
Self::advise_server_palette(
Arc::clone(client),
remote_pane_id,
palette.clone(),
Arc::clone(&delivered_palette),
+ Arc::clone(&palette_rpc_lock),
);
Self {
@@ -309,8 +347,9 @@ impl ClientPane {
application_palette: Mutex::new(false),
renderable: Mutex::new(render),
writer: Mutex::new(writer),
- configured_palette: Mutex::new(palette.clone()),
+ configured_palette: Arc::new(Mutex::new(palette.clone())),
delivered_palette,
+ palette_rpc_lock,
palette: Mutex::new(palette),
clipboard: Mutex::new(None),
mouse_grabbed: Mutex::new(false),
@@ -357,16 +396,28 @@ impl ClientPane {
log::error!("ClientPane: Ignoring SetClipboard request {:?}", clipboard);
}
},
- Pdu::SetPalette(SetPalette { palette, .. }) => {
- // A redundant advisory must not invalidate the whole
- // render surface (make_all_stale forces a refetch of every
- // visible line, which flashes the pane contents).
- if palette != *self.palette.lock() {
- *self.application_palette.lock() = palette != *self.configured_palette.lock();
-
- *self.palette.lock() = palette;
- let mux = Mux::get();
+ Pdu::SetApplicationPalette(SetApplicationPalette { palette, .. }) => {
+ let current = self.palette.lock().clone();
+ let configured = self.configured_palette.lock().clone();
+ let was_application_palette = *self.application_palette.lock();
+ let transition = application_palette_transition(
+ &current,
+ &configured,
+ was_application_palette,
+ palette,
+ );
+
+ *self.application_palette.lock() = transition.application_palette;
+ if transition.palette_changed {
+ *self.palette.lock() = transition.palette;
self.renderable.lock().inner.borrow_mut().make_all_stale();
+ }
+
+ // Provenance changes must propagate through chained muxes even
+ // when the effective colors happen to be identical. Only an
+ // actual color change invalidates the render surface above.
+ if transition.palette_changed || transition.provenance_changed {
+ let mux = Mux::get();
mux.notify(MuxNotification::Alert {
pane_id: self.local_pane_id,
alert: Alert::PaletteChanged,
@@ -801,6 +852,14 @@ impl Pane for ClientPane {
self.palette.lock().clone()
}
+ fn palette_override(&self) -> Option<ColorPalette> {
+ if *self.application_palette.lock() {
+ Some(self.palette.lock().clone())
+ } else {
+ None
+ }
+ }
+
fn domain_id(&self) -> DomainId {
self.client.local_domain_id
}
@@ -855,11 +914,20 @@ impl Pane for ClientPane {
.replace(std::time::Instant::now());
let client = Arc::clone(&self.client);
let remote_pane_id = self.remote_pane_id;
+ let configured_palette = Arc::clone(&self.configured_palette);
+ let palette_rpc_lock = Arc::clone(&self.palette_rpc_lock);
promise::spawn::spawn(async move {
+ // SetPalette and this palette-bearing focus request both
+ // mutate the same server-side advisory. Serialize them and
+ // sample the palette only after acquiring the lock so an old
+ // focus task cannot overwrite a newer config reload.
+ let _guard = palette_rpc_lock.lock().await;
+ let configured_palette = configured_palette.lock().clone();
client
.client
.set_focused_pane_id(SetFocusedPane {
pane_id: remote_pane_id,
+ configured_palette: Some(configured_palette),
})
.await
})
@@ -909,6 +977,7 @@ impl Pane for ClientPane {
self.remote_pane_id,
palette,
Arc::clone(&self.delivered_palette),
+ Arc::clone(&self.palette_rpc_lock),
);
}
self.config.lock().replace(config);
@@ -1021,7 +1090,7 @@ mod test {
#[cfg(test)]
mod palette_delivery_tests {
- use super::PaletteDelivery;
+ use super::{application_palette_transition, PaletteDelivery};
use wezterm_term::color::ColorPalette;
fn palette(fg: f32) -> ColorPalette {
@@ -1128,4 +1197,41 @@ mod palette_delivery_tests {
);
assert_eq!(state.next_to_send(), Some(palette(0.5)));
}
+
+ #[test]
+ fn explicit_no_override_restores_the_configured_palette() {
+ let configured = palette(1.0);
+ let transition = application_palette_transition(&palette(0.7), &configured, true, None);
+ assert_eq!(transition.palette, configured);
+ assert!(!transition.application_palette);
+ assert!(transition.palette_changed);
+ assert!(transition.provenance_changed);
+ }
+
+ #[test]
+ fn default_gray_is_honored_when_it_is_explicit_application_state() {
+ let configured = palette(1.0);
+ let gray = ColorPalette::default();
+ let transition =
+ application_palette_transition(&configured, &configured, false, Some(gray.clone()));
+ assert_eq!(transition.palette, gray);
+ assert!(transition.application_palette);
+ assert!(transition.palette_changed);
+ assert!(transition.provenance_changed);
+ }
+
+ #[test]
+ fn equal_colors_still_preserve_application_provenance_without_repaint() {
+ let configured = palette(1.0);
+ let transition = application_palette_transition(
+ &configured,
+ &configured,
+ false,
+ Some(configured.clone()),
+ );
+ assert_eq!(transition.palette, configured);
+ assert!(transition.application_palette);
+ assert!(!transition.palette_changed);
+ assert!(transition.provenance_changed);
+ }
}
diff --git a/wezterm-gui/src/termwindow/clipboard.rs b/wezterm-gui/src/termwindow/clipboard.rs
index d1ca7f81..2b44cc13 100644
--- a/wezterm-gui/src/termwindow/clipboard.rs
+++ b/wezterm-gui/src/termwindow/clipboard.rs
@@ -1,10 +1,10 @@
use crate::termwindow::TermWindowNotif;
use crate::TermWindow;
use config::keyassignment::{ClipboardCopyDestination, ClipboardPasteSource};
-use mux::pane::Pane;
+use mux::pane::{Pane, PaneId};
use mux::Mux;
use std::sync::Arc;
-use window::{Clipboard, WindowOps};
+use window::{Clipboard, ClipboardContents, WindowOps};
impl TermWindow {
pub fn copy_to_clipboard(&self, clipboard: ClipboardCopyDestination, text: String) {
@@ -31,30 +31,79 @@ impl TermWindow {
clipboard
);
let window = self.window.as_ref().unwrap().clone();
- let clipboard = match clipboard {
- ClipboardPasteSource::Clipboard => Clipboard::Clipboard,
- ClipboardPasteSource::PrimarySelection => Clipboard::PrimarySelection,
- };
- let future = window.get_clipboard(clipboard);
- promise::spawn::spawn(async move {
- if let Ok(clip) = future.await {
- window.notify(TermWindowNotif::Apply(Box::new(move |myself| {
- if let Some(pane) = myself
- .pane_state(pane_id)
- .overlay
- .as_ref()
- .map(|overlay| overlay.pane.clone())
- .or_else(|| {
- let mux = Mux::get();
- mux.get_pane(pane_id)
- })
- {
- pane.send_paste(&clip).ok();
+ match clipboard {
+ ClipboardPasteSource::Clipboard => {
+ // The regular clipboard is read typed: files and images can
+ // do better than a textual paste when the pane is a remote
+ // session (they upload). Text behaves exactly as before.
+ let paste_target = self.capture_terminal_paste_target(pane);
+ let future = window.get_clipboard_contents(Clipboard::Clipboard);
+ promise::spawn::spawn(async move {
+ if let Ok(contents) = future.await {
+ window.notify(TermWindowNotif::Apply(Box::new(move |myself| {
+ myself.dispatch_pasted_clipboard_contents(paste_target, contents);
+ })));
+ }
+ })
+ .detach();
+ }
+ ClipboardPasteSource::PrimarySelection => {
+ // Middle-click territory: text only, the historical path.
+ let future = window.get_clipboard(Clipboard::PrimarySelection);
+ promise::spawn::spawn(async move {
+ if let Ok(clip) = future.await {
+ window.notify(TermWindowNotif::Apply(Box::new(move |myself| {
+ myself.paste_text_to_pane(pane_id, &clip);
+ })));
}
- })));
+ })
+ .detach();
}
- })
- .detach();
+ }
self.maybe_scroll_to_bottom_for_input(&pane);
}
+
+ fn dispatch_pasted_clipboard_contents(
+ &mut self,
+ paste_target: crate::termwindow::ui::right_sidebar::TerminalPasteTarget,
+ contents: ClipboardContents,
+ ) {
+ let pane_id = paste_target.pane_id();
+ match contents {
+ ClipboardContents::Text(text) => {
+ self.paste_text_to_pane(pane_id, &text);
+ }
+ ClipboardContents::FilePaths(paths) => {
+ if !self.upload_files_to_terminal_paste_target(&paths, None, paste_target) {
+ // Not a remote session (or not this host's pane): paste
+ // the quoted local paths, the historical behavior.
+ let text = ClipboardContents::FilePaths(paths).to_text();
+ self.paste_text_to_pane(pane_id, &text);
+ }
+ }
+ ClipboardContents::Image { format, bytes } => {
+ // Pasting an image into a LOCAL shell has never done
+ // anything; only remote sessions gain an upload.
+ self.upload_pasted_image_to_remote_terminal(paste_target, format, bytes);
+ }
+ }
+ }
+
+ pub(crate) fn paste_text_to_pane(&mut self, pane_id: PaneId, text: &str) {
+ if text.is_empty() {
+ return;
+ }
+ if let Some(pane) = self
+ .pane_state(pane_id)
+ .overlay
+ .as_ref()
+ .map(|overlay| overlay.pane.clone())
+ .or_else(|| {
+ let mux = Mux::get();
+ mux.get_pane(pane_id)
+ })
+ {
+ pane.send_paste(text).ok();
+ }
+ }
}
diff --git a/wezterm-gui/src/termwindow/ui/right_sidebar.rs b/wezterm-gui/src/termwindow/ui/right_sidebar.rs
index 8efa0cc8..25f59ce2 100644
--- a/wezterm-gui/src/termwindow/ui/right_sidebar.rs
+++ b/wezterm-gui/src/termwindow/ui/right_sidebar.rs
@@ -49,14 +49,14 @@ use crate::utilsprites::RenderMetrics;
use crate::workspace_threads;
use anyhow::Context;
use config::keyassignment::{ClipboardCopyDestination, ClipboardPasteSource, KeyAssignment};
-use mux::pane::PaneId;
+use mux::pane::{Pane, PaneId};
use mux::Mux;
use std::borrow::Cow;
use std::cmp::Ordering;
use std::collections::{BTreeSet, HashMap, HashSet, VecDeque};
-use std::fs;
+use std::fs::{self, OpenOptions};
use std::hash::{DefaultHasher, Hash, Hasher};
-use std::io::Read;
+use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering as AtomicOrdering};
@@ -162,6 +162,73 @@ const FILE_PREVIEW_HEADER_HEIGHT: usize = 64;
/// 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;
+
+#[derive(Clone)]
+pub(crate) struct TerminalPasteTarget {
+ pane_id: PaneId,
+ remote: Option<Result<RemoteTerminalPasteTarget, String>>,
+}
+
+#[derive(Clone)]
+struct RemoteTerminalPasteTarget {
+ space_id: String,
+ target: workspace_threads::RemoteFilesTarget,
+ source_key: String,
+ connection_key: String,
+ config: config::SshDomain,
+ destination: String,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum TerminalPasteSnapshotMismatch {
+ Space,
+ Project,
+ Connection,
+ Pane,
+}
+
+fn terminal_paste_snapshot_mismatch(
+ captured_space: &str,
+ current_space: &str,
+ captured_target: &workspace_threads::RemoteFilesTarget,
+ current_target: Option<&workspace_threads::RemoteFilesTarget>,
+ captured_connection_key: &str,
+ current_connection_key: Option<&str>,
+ pane_matches_host: bool,
+) -> Option<TerminalPasteSnapshotMismatch> {
+ if captured_space != current_space {
+ Some(TerminalPasteSnapshotMismatch::Space)
+ } else if current_target != Some(captured_target) {
+ Some(TerminalPasteSnapshotMismatch::Project)
+ } else if current_connection_key != Some(captured_connection_key) {
+ Some(TerminalPasteSnapshotMismatch::Connection)
+ } else if !pane_matches_host {
+ Some(TerminalPasteSnapshotMismatch::Pane)
+ } else {
+ None
+ }
+}
+
+impl TerminalPasteTarget {
+ pub(crate) fn pane_id(&self) -> PaneId {
+ self.pane_id
+ }
+}
+
+struct StagedPastedImage {
+ directory: tempfile::TempDir,
+ path: PathBuf,
+ #[cfg(test)]
+ worker_thread_id: std::thread::ThreadId,
+}
+
+impl StagedPastedImage {
+ fn keep(self) -> PathBuf {
+ let path = self.path;
+ let _ = self.directory.keep();
+ path
+ }
+}
/// Thickness of the progress track under a running transfer's label. Five
/// design pixels remains compact while being visible at a glance.
const REMOTE_TRANSFER_PROGRESS_HEIGHT: usize = 5;
@@ -10024,12 +10091,27 @@ impl crate::TermWindow {
paths: &[PathBuf],
coords: Option<Point>,
) -> bool {
- let Ok(Some(target)) = self.active_remote_project_for_files() else {
- return false;
- };
let Some(pane) = self.get_active_pane_or_overlay() else {
return false;
};
+ let paste_target = self.capture_terminal_paste_target(&pane);
+ self.upload_files_to_terminal_paste_target(paths, coords, paste_target)
+ }
+
+ /// Resolve everything an asynchronous typed paste is allowed to use while
+ /// the initiating pane and Space are still authoritative. Later callbacks
+ /// carry this snapshot instead of consulting whichever pane is active then.
+ pub(crate) fn capture_terminal_paste_target(
+ &self,
+ pane: &Arc<dyn Pane>,
+ ) -> TerminalPasteTarget {
+ let pane_id = pane.pane_id();
+ let Ok(Some(target)) = self.active_remote_project_for_files() else {
+ return TerminalPasteTarget {
+ pane_id,
+ remote: None,
+ };
+ };
// The paste target must live on the SAME host the upload goes to.
// The Space being remote is not enough: the active pane can be a
// local overlay (the debug pane), or in principle belong to another
@@ -10038,32 +10120,20 @@ impl crate::TermWindow {
// (A mosh thread's pane is a local domain running mosh-client, so
// mosh Spaces deliberately keep the old behavior for now.)
if !pane_domain_matches_remote_source(pane.domain_id(), &target.source) {
- return false;
+ return TerminalPasteTarget {
+ pane_id,
+ remote: None,
+ };
}
- let pane_id = pane.pane_id();
- // Align the panel's state machine with this Space's target (idempotent
- // when it already matches): every origin check downstream reads the
- // state machine's source key, which is unset until someone sets it.
- let effects = self
- .right_sidebar_remote_files
- .transition(RemoteFilesEvent::TargetChanged(Some(target.clone())));
- self.apply_right_sidebar_remote_files_effects(effects);
-
let source_key =
crate::termwindow::remote_files::RemoteFilesState::source_key(&target.source);
let config = match Self::ssh_config_for_remote_files_target(&target) {
Ok(config) => config,
Err(message) => {
- for path in paths {
- self.push_remote_transfer_failure(
- RemoteTransferKind::Upload,
- display_name(path),
- message.clone(),
- None,
- );
- }
- self.invalidate_window();
- return true;
+ return TerminalPasteTarget {
+ pane_id,
+ remote: Some(Err(message)),
+ };
}
};
@@ -10083,6 +10153,105 @@ impl crate::TermWindow {
})
.flatten();
let destination = resolve_drop_destination(&setting, cwd.as_deref());
+ let connection_key = remote_connection_key(&source_key, &config);
+ TerminalPasteTarget {
+ pane_id,
+ remote: Some(Ok(RemoteTerminalPasteTarget {
+ space_id: self.active_space_id.clone(),
+ target,
+ source_key,
+ connection_key,
+ config,
+ destination,
+ })),
+ }
+ }
+
+ fn validate_terminal_paste_target(
+ &self,
+ paste_target: &TerminalPasteTarget,
+ ) -> Result<(), String> {
+ let Some(remote) = paste_target.remote.as_ref() else {
+ return Err("The paste did not originate in a remote terminal".to_string());
+ };
+ let remote = remote.as_ref().map_err(Clone::clone)?;
+ let current_target = self
+ .active_remote_project_for_files()
+ .map_err(|message| format!("Paste canceled: {message}"))?;
+ let current_config = Self::ssh_config_for_remote_files_target(&remote.target)
+ .map_err(|message| format!("Paste canceled: {message}"))?;
+ let current_key = remote_connection_key(&remote.source_key, &current_config);
+ let pane = Mux::get()
+ .get_pane(paste_target.pane_id)
+ .ok_or_else(|| "Paste canceled because its pane was closed".to_string())?;
+ let mismatch = terminal_paste_snapshot_mismatch(
+ &remote.space_id,
+ &self.active_space_id,
+ &remote.target,
+ current_target.as_ref(),
+ &remote.connection_key,
+ Some(&current_key),
+ pane_domain_matches_remote_source(pane.domain_id(), &remote.target.source),
+ );
+ if let Some(mismatch) = mismatch {
+ return Err(match mismatch {
+ TerminalPasteSnapshotMismatch::Space => {
+ "Paste canceled because the window switched Spaces".to_string()
+ }
+ TerminalPasteSnapshotMismatch::Project => {
+ "Paste canceled because the remote project changed".to_string()
+ }
+ TerminalPasteSnapshotMismatch::Connection => {
+ "Paste canceled because the remote connection changed".to_string()
+ }
+ TerminalPasteSnapshotMismatch::Pane => {
+ "Paste canceled because its pane no longer belongs to that host".to_string()
+ }
+ });
+ }
+ Ok(())
+ }
+
+ fn push_terminal_paste_failures(&mut self, paths: &[PathBuf], message: String) {
+ for path in paths {
+ self.push_remote_transfer_failure(
+ RemoteTransferKind::Upload,
+ display_name(path),
+ message.clone(),
+ None,
+ );
+ }
+ self.invalidate_window();
+ }
+
+ pub(crate) fn upload_files_to_terminal_paste_target(
+ &mut self,
+ paths: &[PathBuf],
+ coords: Option<Point>,
+ paste_target: TerminalPasteTarget,
+ ) -> bool {
+ let Some(remote) = paste_target.remote.as_ref() else {
+ return false;
+ };
+ let remote = match remote {
+ Ok(remote) => remote.clone(),
+ Err(message) => {
+ self.push_terminal_paste_failures(paths, message.clone());
+ return true;
+ }
+ };
+ if let Err(message) = self.validate_terminal_paste_target(&paste_target) {
+ self.push_terminal_paste_failures(paths, message);
+ return true;
+ }
+
+ // Align the panel's state machine with the captured Space's target
+ // only after revalidation. A delayed clipboard read must never point
+ // the panel (and its connection lease) at a different host.
+ let effects = self
+ .right_sidebar_remote_files
+ .transition(RemoteFilesEvent::TargetChanged(Some(remote.target.clone())));
+ self.apply_right_sidebar_remote_files_effects(effects);
let Some(window) = self.window.as_ref().cloned() else {
return true;
@@ -10090,15 +10259,18 @@ impl crate::TermWindow {
// A drop is an explicit ask, so dialing is allowed — and a successful
// dial authorizes the source exactly as the panel's Connect click
// would (the session credentials are the same either way).
- let connection_key = remote_connection_key(&source_key, &config);
let batch: Vec<PathBuf> = paths.to_vec();
let anchor = coords.unwrap_or_else(|| Point::new(0, 0));
+ let dispatch_target = paste_target.clone();
promise::spawn::spawn(async move {
let manager = remote_connection_manager();
- let prepared = match manager.acquire(connection_key, config, true).await {
+ let prepared = match manager
+ .acquire(remote.connection_key, remote.config, true)
+ .await
+ {
Ok(lease) => {
let backend = lease.backend();
- match backend.resolve_root(destination).await {
+ match backend.resolve_root(remote.destination).await {
// Merge-tolerant creation: the folder existing already
// is the normal case after the first drop.
Ok(directory) => match backend.create_directory(directory.clone()).await {
@@ -10114,13 +10286,91 @@ impl crate::TermWindow {
}
};
window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
- term_window.dispatch_terminal_drop(prepared, batch, source_key, pane_id, anchor);
+ term_window.dispatch_terminal_drop(prepared, batch, dispatch_target, anchor);
})));
})
.detach();
true
}
+ /// An image pasted from the clipboard: encode to PNG, park it in the
+ /// session's temp folder under a screenshot-style name, and hand it to
+ /// the ordinary terminal-drop upload (which pastes the remote path).
+ ///
+ /// The temp file deliberately outlives the upload: the transfer row's
+ /// Retry re-reads the local path, so deleting on completion would break
+ /// it. The OS reaps the temp dir between sessions.
+ pub(crate) fn upload_pasted_image_to_remote_terminal(
+ &mut self,
+ paste_target: TerminalPasteTarget,
+ format: window::ClipboardImageFormat,
+ bytes: Vec<u8>,
+ ) {
+ let Some(remote) = paste_target.remote.as_ref() else {
+ return;
+ };
+ let name = pasted_image_file_name(chrono::Local::now());
+ if let Err(message) = remote {
+ self.push_remote_transfer_failure(
+ RemoteTransferKind::Upload,
+ name,
+ message.clone(),
+ None,
+ );
+ self.invalidate_window();
+ return;
+ }
+ if let Err(message) = self.validate_terminal_paste_target(&paste_target) {
+ self.push_remote_transfer_failure(RemoteTransferKind::Upload, name, message, None);
+ self.invalidate_window();
+ return;
+ }
+ let Some(window) = self.window.as_ref().cloned() else {
+ return;
+ };
+ promise::spawn::spawn(async move {
+ let worker_name = name.clone();
+ let staged = spawn_pasted_image_staging(format, bytes, worker_name).await;
+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
+ match staged {
+ Ok(staged) => {
+ // Revalidate after potentially expensive transcoding.
+ // Dropping `staged` on failure removes the private temp
+ // directory before any path can be retained for Retry.
+ if let Err(message) =
+ term_window.validate_terminal_paste_target(&paste_target)
+ {
+ term_window.push_remote_transfer_failure(
+ RemoteTransferKind::Upload,
+ name,
+ message,
+ None,
+ );
+ term_window.invalidate_window();
+ return;
+ }
+ let path = staged.keep();
+ term_window.upload_files_to_terminal_paste_target(
+ &[path],
+ None,
+ paste_target,
+ );
+ }
+ Err(err) => {
+ term_window.push_remote_transfer_failure(
+ RemoteTransferKind::Upload,
+ name,
+ format!("Could not stage the pasted image: {err}"),
+ None,
+ );
+ term_window.invalidate_window();
+ }
+ }
+ })));
+ })
+ .detach();
+ }
+
/// The prepared half of a terminal drop, back on the window thread: adopt
/// the connection, then hand every dropped path to the ordinary upload
/// machinery with the pane recorded as the paste target.
@@ -10134,10 +10384,22 @@ impl crate::TermWindow {
String,
>,
paths: Vec<PathBuf>,
- source_key: String,
- pane_id: PaneId,
+ paste_target: TerminalPasteTarget,
anchor: Point,
) {
+ if let Err(message) = self.validate_terminal_paste_target(&paste_target) {
+ self.push_terminal_paste_failures(&paths, message);
+ return;
+ }
+ let remote = match paste_target.remote.as_ref() {
+ Some(Ok(remote)) => remote.clone(),
+ Some(Err(message)) => {
+ self.push_terminal_paste_failures(&paths, message.clone());
+ return;
+ }
+ None => return,
+ };
+ let pane_id = paste_target.pane_id;
let (lease, directory) = match prepared {
Ok(prepared) => prepared,
Err(message) => {
@@ -10153,8 +10415,10 @@ impl crate::TermWindow {
return;
}
};
- let origin =
- RemoteOperationOrigin::new(source_key.clone(), lease.connection_key().to_string());
+ let origin = RemoteOperationOrigin::new(
+ remote.source_key.clone(),
+ lease.connection_key().to_string(),
+ );
if !self.remote_operation_origin_matches(&origin) {
for path in &paths {
self.push_remote_transfer_failure(
@@ -10167,7 +10431,7 @@ impl crate::TermWindow {
self.invalidate_window();
return;
}
- crate::termwindow::remote_files::authorize_remote_source(&source_key);
+ crate::termwindow::remote_files::authorize_remote_source(&remote.source_key);
// Lend the fresh connection to the panel's lease slot unless the slot
// already holds this exact connection: `remote_transfer_handles` reads
// that slot, so every upload below — and the Files panel itself — uses
@@ -16069,6 +16333,87 @@ fn pane_domain_matches_remote_source(
/// setting asks for it) the pane's reported working directory. Pure, so the
/// fallback rules stay testable: `cwd` without a usable cwd must degrade to
/// the default folder, never fail the drop.
+/// Screenshot-style name for an image pasted from the clipboard. The dots in
+/// the timestamp are why the collision logic splits extensions on the LAST
+/// dot; a pasted image re-pasted lands as `… (1).png` like any other file.
+fn pasted_image_file_name(now: chrono::DateTime<chrono::Local>) -> String {
+ format!("Pasted {}.png", now.format("%Y-%m-%d at %H.%M.%S"))
+}
+
+/// Bring a pasted clipboard image to PNG. PNG passes through untouched;
+/// Windows hands us BMP and macOS can hand us TIFF, both of which decode
+/// and re-encode here.
+fn encode_pasted_image_png(
+ format: window::ClipboardImageFormat,
+ bytes: Vec<u8>,
+) -> Result<Vec<u8>, String> {
+ match format {
+ window::ClipboardImageFormat::Png => Ok(bytes),
+ window::ClipboardImageFormat::Bmp | window::ClipboardImageFormat::Tiff => {
+ let decoded = image::load_from_memory(&bytes)
+ .map_err(|err| format!("Could not decode the pasted image: {err}"))?;
+ let mut png = std::io::Cursor::new(Vec::new());
+ decoded
+ .write_to(&mut png, image::ImageFormat::Png)
+ .map_err(|err| format!("Could not convert the pasted image to PNG: {err}"))?;
+ Ok(png.into_inner())
+ }
+ }
+}
+
+fn stage_pasted_image(
+ format: window::ClipboardImageFormat,
+ bytes: Vec<u8>,
+ name: &str,
+) -> Result<StagedPastedImage, String> {
+ let png = encode_pasted_image_png(format, bytes)?;
+ let directory = tempfile::Builder::new()
+ .prefix("thinkterm-pasted-image-")
+ .tempdir()
+ .map_err(|err| format!("Could not create a private staging directory: {err}"))?;
+
+ #[cfg(unix)]
+ fs::set_permissions(
+ directory.path(),
+ std::os::unix::fs::PermissionsExt::from_mode(0o700),
+ )
+ .map_err(|err| format!("Could not protect the staging directory: {err}"))?;
+
+ let path = directory.path().join(name);
+ let mut options = OpenOptions::new();
+ options.write(true).create_new(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ options.mode(0o600);
+ }
+ let mut file = options
+ .open(&path)
+ .map_err(|err| format!("Could not create the private staged image: {err}"))?;
+ file.write_all(&png)
+ .map_err(|err| format!("Could not write the staged image: {err}"))?;
+ #[cfg(unix)]
+ fs::set_permissions(&path, std::os::unix::fs::PermissionsExt::from_mode(0o600))
+ .map_err(|err| format!("Could not protect the staged image: {err}"))?;
+
+ Ok(StagedPastedImage {
+ directory,
+ path,
+ #[cfg(test)]
+ worker_thread_id: std::thread::current().id(),
+ })
+}
+
+fn spawn_pasted_image_staging(
+ format: window::ClipboardImageFormat,
+ bytes: Vec<u8>,
+ name: String,
+) -> promise::spawn::Task<anyhow::Result<StagedPastedImage>> {
+ promise::spawn::spawn_into_new_thread(move || {
+ stage_pasted_image(format, bytes, &name).map_err(anyhow::Error::msg)
+ })
+}
+
fn resolve_drop_destination(setting: &str, cwd: Option<&str>) -> String {
if setting == crate::native_settings::REMOTE_DROP_DESTINATION_CWD {
match cwd {
@@ -17564,24 +17909,27 @@ 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,
- copy_entries_blocking, copy_file_chunked, failed_folder_download,
- 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,
- pick_free_remote_name, preflight_local_copy, preview_line_count, preview_lines_from_text,
+ copy_entries_blocking, copy_file_chunked, download_name_candidates,
+ encode_pasted_image_png, failed_folder_download, 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, pasted_image_file_name, path_key, pick_free_remote_name,
+ preflight_local_copy, preview_line_count, preview_lines_from_text,
preview_plain_lines_from_text, preview_text_range, preview_visible_colored,
preview_visible_line_range, remote_lease_failure_disposition, resolve_drop_destination,
resolve_local_drop_target, resolve_remote_drop_target,
right_sidebar_file_browse_rows_from_index, right_sidebar_file_row_metrics,
right_sidebar_open_with_cache_key, sanitize_preview_text, scrollable_note_table_columns,
search_right_sidebar_file_index, snippet_cursor_visible, snippet_run_buffer,
- sorted_open_with_candidates, virtual_note_line_range, visible_code_block_rounded_edges,
- visible_file_row_range, wrap_snippet_text_for_width, FileReleaseAction, FileRowPlacement,
- NoteApproximateTextMetrics, NoteCodeHighlightEntry, NoteCodeHighlightState,
- NoteReleaseAction, RemoteLeaseFailureDisposition, FILE_PREVIEW_MAX_BYTES, LOCAL_COPY_CHUNK,
- NOTE_CODE_BLOCK_RADIUS, NOTE_CODE_HEADER_HEIGHT,
+ sorted_open_with_candidates, spawn_pasted_image_staging, stage_pasted_image,
+ terminal_paste_snapshot_mismatch, virtual_note_line_range,
+ visible_code_block_rounded_edges, visible_file_row_range, wrap_snippet_text_for_width,
+ FileReleaseAction, FileRowPlacement, NoteApproximateTextMetrics, NoteCodeHighlightEntry,
+ NoteCodeHighlightState, NoteReleaseAction, RemoteLeaseFailureDisposition,
+ TerminalPasteSnapshotMismatch, TerminalPasteTarget, FILE_PREVIEW_MAX_BYTES,
+ LOCAL_COPY_CHUNK, NOTE_CODE_BLOCK_RADIUS, NOTE_CODE_HEADER_HEIGHT,
};
use crate::markdown_editor::{NoteLineGeometry, ProjectedCodeBlock};
use crate::termwindow::remote_files::{
@@ -17708,6 +18056,194 @@ mod tests {
);
}
+ /// The timestamp uses dots, like macOS screenshots, so this name is also
+ /// a regression canary for the last-dot extension split: a re-paste must
+ /// collide into `… (1).png`, not `Pasted 2026-08-01 at 14 (1).30.00.png`.
+ #[test]
+ fn a_pasted_image_is_named_like_a_screenshot() {
+ use chrono::TimeZone;
+ let when = chrono::Local
+ .with_ymd_and_hms(2026, 8, 1, 14, 30, 0)
+ .unwrap();
+ let name = pasted_image_file_name(when);
+ assert_eq!(name, "Pasted 2026-08-01 at 14.30.00.png");
+ assert_eq!(
+ download_name_candidates(&name).nth(1).unwrap(),
+ "Pasted 2026-08-01 at 14.30.00 (1).png"
+ );
+ }
+
+ #[test]
+ fn a_pasted_bmp_is_reencoded_as_png_and_png_passes_through() {
+ // A real 1x1 BMP, produced by the same crate that decodes it.
+ let mut bmp = std::io::Cursor::new(Vec::new());
+ image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(
+ 1,
+ 1,
+ image::Rgba([255, 0, 0, 255]),
+ ))
+ .write_to(&mut bmp, image::ImageFormat::Bmp)
+ .unwrap();
+ let png = encode_pasted_image_png(window::ClipboardImageFormat::Bmp, bmp.into_inner())
+ .expect("bmp converts");
+ assert_eq!(&png[1..4], b"PNG", "the conversion output must be PNG");
+
+ let passthrough =
+ encode_pasted_image_png(window::ClipboardImageFormat::Png, png.clone()).unwrap();
+ assert_eq!(passthrough, png, "png bytes must pass through untouched");
+
+ assert!(
+ encode_pasted_image_png(window::ClipboardImageFormat::Tiff, b"not an image".to_vec())
+ .is_err(),
+ "garbage must surface as an error, not a bogus upload"
+ );
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn pasted_image_staging_is_private_and_cleans_up_until_retained() {
+ use std::os::unix::fs::PermissionsExt;
+
+ let staged = stage_pasted_image(
+ window::ClipboardImageFormat::Png,
+ b"\x89PNG\r\n\x1a\nprivate".to_vec(),
+ "Pasted test.png",
+ )
+ .expect("stage image");
+ let path = staged.path.clone();
+ let directory = path.parent().unwrap().to_path_buf();
+ assert_ne!(
+ directory,
+ std::env::temp_dir().join("thinkterm-pasted-images"),
+ "the staging directory must be randomized per image"
+ );
+ assert_eq!(
+ fs::metadata(&directory).unwrap().permissions().mode() & 0o777,
+ 0o700
+ );
+ assert_eq!(
+ fs::metadata(&path).unwrap().permissions().mode() & 0o777,
+ 0o600
+ );
+
+ drop(staged);
+ assert!(!directory.exists(), "unaccepted staging must be cleaned up");
+ }
+
+ #[test]
+ fn pasted_image_staging_runs_off_the_calling_thread() {
+ let caller = std::thread::current().id();
+ let mut bmp = std::io::Cursor::new(Vec::new());
+ image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(
+ 1,
+ 1,
+ image::Rgba([0, 255, 0, 255]),
+ ))
+ .write_to(&mut bmp, image::ImageFormat::Bmp)
+ .unwrap();
+ let executor = promise::spawn::ScopedExecutor::new();
+ let staged = smol::block_on(executor.run(async {
+ spawn_pasted_image_staging(
+ window::ClipboardImageFormat::Bmp,
+ bmp.into_inner(),
+ "Pasted worker.png".to_string(),
+ )
+ .await
+ }))
+ .expect("worker staging");
+ assert_ne!(staged.worker_thread_id, caller);
+ assert_eq!(&fs::read(&staged.path).unwrap()[1..4], b"PNG");
+ }
+
+ #[test]
+ fn typed_paste_keeps_its_originating_pane_when_focus_changes() {
+ let captured = TerminalPasteTarget {
+ pane_id: 17,
+ remote: None,
+ };
+ let active_after_clipboard_read = 29;
+
+ assert_ne!(captured.pane_id(), active_after_clipboard_read);
+ assert_eq!(captured.pane_id(), 17);
+ }
+
+ #[test]
+ fn typed_paste_rejects_space_host_connection_and_pane_changes() {
+ let host_a = crate::workspace_threads::RemoteFilesTarget {
+ project_id: "project-a".to_string(),
+ project_name: "A".to_string(),
+ source: crate::workspace_threads::RemoteFilesSource::SshHost("host-a".to_string()),
+ requested_root: "~".to_string(),
+ };
+ let host_b = crate::workspace_threads::RemoteFilesTarget {
+ project_id: "project-b".to_string(),
+ project_name: "B".to_string(),
+ source: crate::workspace_threads::RemoteFilesSource::SshHost("host-b".to_string()),
+ requested_root: "~".to_string(),
+ };
+
+ assert_eq!(
+ terminal_paste_snapshot_mismatch(
+ "space-a",
+ "space-a",
+ &host_a,
+ Some(&host_a),
+ "connection-a",
+ Some("connection-a"),
+ true,
+ ),
+ None
+ );
+ assert_eq!(
+ terminal_paste_snapshot_mismatch(
+ "space-a",
+ "space-b",
+ &host_a,
+ Some(&host_a),
+ "connection-a",
+ Some("connection-a"),
+ true,
+ ),
+ Some(TerminalPasteSnapshotMismatch::Space)
+ );
+ assert_eq!(
+ terminal_paste_snapshot_mismatch(
+ "space-a",
+ "space-a",
+ &host_a,
+ Some(&host_b),
+ "connection-a",
+ Some("connection-a"),
+ true,
+ ),
+ Some(TerminalPasteSnapshotMismatch::Project)
+ );
+ assert_eq!(
+ terminal_paste_snapshot_mismatch(
+ "space-a",
+ "space-a",
+ &host_a,
+ Some(&host_a),
+ "connection-a",
+ Some("connection-b"),
+ true,
+ ),
+ Some(TerminalPasteSnapshotMismatch::Connection)
+ );
+ assert_eq!(
+ terminal_paste_snapshot_mismatch(
+ "space-a",
+ "space-a",
+ &host_a,
+ Some(&host_a),
+ "connection-a",
+ Some("connection-a"),
+ false,
+ ),
+ Some(TerminalPasteSnapshotMismatch::Pane)
+ );
+ }
+
/// Backend double whose `exists` answers from a fixed set of taken names.
struct TakenNamesBackend {
taken: std::collections::HashSet<String>,
diff --git a/wezterm-mux-server-impl/src/sessionhandler.rs b/wezterm-mux-server-impl/src/sessionhandler.rs
index fec34d09..29f05af7 100644
--- a/wezterm-mux-server-impl/src/sessionhandler.rs
+++ b/wezterm-mux-server-impl/src/sessionhandler.rs
@@ -7,7 +7,7 @@ use mux::domain::SplitSource;
use mux::pane::{CachePolicy, Pane, PaneId};
use mux::renderable::{RenderableDimensions, StableCursorPosition};
use mux::tab::TabId;
-use mux::{Mux, MuxNotification};
+use mux::{Mux, PaletteSessionId};
use promise::spawn::spawn_into_main_thread;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
@@ -43,14 +43,23 @@ pub(crate) struct PerPane {
working_dir: Option<Url>,
dimensions: RenderableDimensions,
mouse_grabbed: bool,
- sent_initial_palette: bool,
- last_sent_palette: Option<ColorPalette>,
+ /// Outer None means that this connection has never received application
+ /// palette state for the pane. Inner None is an explicit reset to the
+ /// client's own configured palette.
+ last_sent_application_palette: Option<Option<ColorPalette>>,
seqno: SequenceNo,
- config_generation: usize,
pub(crate) notifications: Vec<Alert>,
}
impl PerPane {
+ fn needs_application_palette(&self, palette: &Option<ColorPalette>) -> bool {
+ self.last_sent_application_palette.as_ref() != Some(palette)
+ }
+
+ fn record_application_palette(&mut self, palette: Option<ColorPalette>) {
+ self.last_sent_application_palette = Some(palette);
+ }
+
fn compute_changes(
&mut self,
pane: &Arc<dyn Pane>,
@@ -151,49 +160,36 @@ fn maybe_push_pane_changes(
per_pane: Arc<Mutex<PerPane>>,
) -> anyhow::Result<()> {
let mut per_pane = per_pane.lock().unwrap();
- if let Some(resp) = per_pane.compute_changes(pane, None) {
+
+ // Application palette provenance must arrive even when the state is
+ // `None`: that explicit reset prevents a server's configured/advisory
+ // palette from taking over client rendering. Send it before line changes
+ // so a real application override is installed before those lines paint.
+ let application_palette = pane.palette_override();
+ if per_pane.needs_application_palette(&application_palette) {
sender.send(DecodedPdu {
- pdu: Pdu::GetPaneRenderChangesResponse(resp),
+ pdu: Pdu::SetApplicationPalette(SetApplicationPalette {
+ pane_id: pane.pane_id(),
+ palette: application_palette.clone(),
+ }),
serial: 0,
})?;
+ per_pane.record_application_palette(application_palette);
}
- let config = config::configuration();
- if per_pane.config_generation != config.generation() {
- per_pane.config_generation = config.generation();
- // If the config changed, it may have changed colors
- // in the palette that we need to push down, so we
- // synthesize a palette change notification to let
- // the client know
- per_pane.notifications.push(Alert::PaletteChanged);
- per_pane.sent_initial_palette = true;
+ if let Some(resp) = per_pane.compute_changes(pane, None) {
+ sender.send(DecodedPdu {
+ pdu: Pdu::GetPaneRenderChangesResponse(resp),
+ serial: 0,
+ })?;
}
- if !per_pane.sent_initial_palette {
- per_pane.notifications.push(Alert::PaletteChanged);
- per_pane.sent_initial_palette = true;
- }
let notifications: Vec<Alert> = per_pane.notifications.drain(..).collect();
for alert in notifications {
match alert {
- Alert::PaletteChanged => {
- let palette = pane.palette();
- // Config generation bumps synthesize PaletteChanged even
- // when the effective palette is unchanged; pushing those
- // makes every attached client invalidate its entire render
- // surface for this pane. Only push real changes.
- if per_pane.last_sent_palette.as_ref() == Some(&palette) {
- continue;
- }
- per_pane.last_sent_palette = Some(palette.clone());
- sender.send(DecodedPdu {
- pdu: Pdu::SetPalette(SetPalette {
- pane_id: pane.pane_id(),
- palette,
- }),
- serial: 0,
- })?;
- }
+ // The current application state was sent (and de-duplicated)
+ // above. Never forward this alert as a configured palette.
+ Alert::PaletteChanged => {}
alert => {
sender.send(DecodedPdu {
pdu: Pdu::NotifyAlert(NotifyAlert {
@@ -208,18 +204,84 @@ fn maybe_push_pane_changes(
Ok(())
}
+fn apply_client_palette(pane: &Arc<dyn Pane>, palette: Option<ColorPalette>) -> anyhow::Result<()> {
+ match pane.get_config() {
+ Some(config) => match config.downcast_ref::<TermConfig>() {
+ Some(tc) => match palette {
+ Some(palette) => tc.set_client_palette(palette),
+ None => tc.clear_client_palette(),
+ },
+ None => {
+ log::error!(
+ "pane {} doesn't have TermConfig as its config; ignoring client palette update",
+ pane.pane_id()
+ );
+ }
+ },
+ None => {
+ if let Some(palette) = palette {
+ let config = TermConfig::new();
+ config.set_client_palette(palette);
+ pane.set_config(Arc::new(config));
+ }
+ }
+ }
+ Ok(())
+}
+
+fn activate_client_palette(
+ mux: &Mux,
+ pane: &Arc<dyn Pane>,
+ palette_session_id: Option<PaletteSessionId>,
+) -> anyhow::Result<()> {
+ if let Some(palette_session_id) = palette_session_id {
+ if let Some(palette) = mux.activate_client_palette(palette_session_id, pane.pane_id()) {
+ apply_client_palette(pane, Some(palette))?;
+ }
+ }
+ Ok(())
+}
+
+fn schedule_palette_session_cleanup(session_id: PaletteSessionId, reason: &'static str) {
+ let mux = Mux::get();
+ if !mux.deactivate_palette_session(session_id) {
+ return;
+ }
+ // Deactivation above closes the stale-handler gate immediately. Applying
+ // fallback here, behind work already queued by this connection, closes the
+ // TOCTOU where a handler had fetched its palette just before disconnect
+ // and would otherwise apply it after synchronous cleanup.
+ spawn_into_main_thread(async move {
+ let mux = Mux::get();
+ for change in mux.unregister_palette_session(session_id) {
+ if let Some(pane) = mux.get_pane(change.pane_id) {
+ if let Err(err) = apply_client_palette(&pane, change.palette) {
+ log::error!(
+ "applying palette fallback for pane {} after {reason}: {err:#}",
+ change.pane_id
+ );
+ }
+ }
+ }
+ })
+ .detach();
+}
+
pub struct SessionHandler {
to_write_tx: PduSender,
per_pane: HashMap<TabId, Arc<Mutex<PerPane>>>,
client_id: Option<Arc<ClientId>>,
+ palette_session_id: Option<PaletteSessionId>,
proxy_client_id: Option<ClientId>,
}
impl Drop for SessionHandler {
fn drop(&mut self) {
+ if let Some(session_id) = self.palette_session_id.take() {
+ schedule_palette_session_cleanup(session_id, "client disconnect");
+ }
if let Some(client_id) = self.client_id.take() {
- let mux = Mux::get();
- mux.unregister_client(&client_id);
+ Mux::get().unregister_client(&client_id);
}
}
}
@@ -230,6 +292,7 @@ impl SessionHandler {
to_write_tx,
per_pane: HashMap::new(),
client_id: None,
+ palette_session_id: None,
proxy_client_id: None,
}
}
@@ -260,6 +323,7 @@ impl SessionHandler {
let start = Instant::now();
let sender = self.to_write_tx.clone();
let serial = decoded.serial;
+ let palette_session_id = self.palette_session_id;
log::trace!("recv {} {}", serial, decoded.pdu.pdu_name());
if let Some(client_id) = &self.client_id {
@@ -332,6 +396,11 @@ impl SessionHandler {
}
let client_id = Arc::new(client_id);
+ if let Some(old_session_id) = self.palette_session_id.take() {
+ schedule_palette_session_cleanup(old_session_id, "client identity change");
+ }
+ self.palette_session_id =
+ Some(Mux::get().register_palette_session(client_id.as_ref()));
self.client_id.replace(client_id.clone());
spawn_into_main_thread(async move {
let mux = Mux::get();
@@ -341,18 +410,38 @@ impl SessionHandler {
}
send_response(Ok(Pdu::UnitResponse(UnitResponse {})))
}
- Pdu::SetFocusedPane(SetFocusedPane { pane_id }) => {
+ Pdu::SetFocusedPane(SetFocusedPane {
+ pane_id,
+ configured_palette,
+ }) => {
let client_id = self.client_id.clone();
spawn_into_main_thread(async move {
catch(
move || {
let mux = Mux::get();
- let _identity = mux.with_identity(client_id);
+ let _identity = mux.with_identity(client_id.clone());
let pane = mux
.get_pane(pane_id)
.ok_or_else(|| anyhow::anyhow!("pane {pane_id} not found"))?;
+ if let Some(palette) = configured_palette {
+ if let Some(palette) = mux.advise_client_palette(
+ palette_session_id.ok_or_else(|| {
+ anyhow!(
+ "palette-bearing focus requires a live client session"
+ )
+ })?,
+ pane_id,
+ palette,
+ ) {
+ apply_client_palette(&pane, Some(palette))?;
+ }
+ }
+ // Switch the OSC query base before focus reporting
+ // can provoke an immediate query from the app.
+ activate_client_palette(&mux, &pane, palette_session_id)?;
+
let (_domain_id, window_id, tab_id) = mux
.resolve_pane_id(pane_id)
.ok_or_else(|| anyhow::anyhow!("pane {pane_id} not found"))?;
@@ -454,6 +543,7 @@ impl SessionHandler {
let pane = mux
.get_pane(pane_id)
.ok_or_else(|| anyhow!("no such pane {}", pane_id))?;
+ activate_client_palette(&mux, &pane, palette_session_id)?;
pane.writer().write_all(&data)?;
maybe_push_pane_changes(&pane, sender, per_pane)?;
Ok(Pdu::UnitResponse(UnitResponse {}))
@@ -512,6 +602,7 @@ impl SessionHandler {
let pane = mux
.get_pane(pane_id)
.ok_or_else(|| anyhow!("no such pane {}", pane_id))?;
+ activate_client_palette(&mux, &pane, palette_session_id)?;
pane.send_paste(&data)?;
maybe_push_pane_changes(&pane, sender, per_pane)?;
Ok(Pdu::UnitResponse(UnitResponse {}))
@@ -571,6 +662,7 @@ impl SessionHandler {
let tab = mux
.get_tab(containing_tab_id)
.ok_or_else(|| anyhow!("no such tab {}", containing_tab_id))?;
+ activate_client_palette(&mux, &pane, palette_session_id)?;
match tab.get_zoomed_pane() {
Some(p) => {
let is_zoomed = p.pane_id() == pane_id;
@@ -634,6 +726,19 @@ impl SessionHandler {
let tab = mux
.get_tab(tab_id)
.ok_or_else(|| anyhow!("no such tab {}", tab_id))?;
+ // A direction request is a no-op while zoomed when
+ // the configured policy forbids unzooming. Do not
+ // transfer ownership to a pane that won't receive
+ // focus in that case.
+ if tab.get_zoomed_pane().is_none()
+ || config::configuration().unzoom_on_switch_pane
+ {
+ let panes = tab.iter_panes_ignoring_zoom();
+ if let Some(pane_index) = tab.get_pane_direction(direction, true) {
+ let target = &panes[pane_index].pane;
+ activate_client_palette(&mux, target, palette_session_id)?;
+ }
+ }
tab.activate_pane_direction(direction);
Ok(Pdu::UnitResponse(UnitResponse {}))
},
@@ -682,6 +787,7 @@ impl SessionHandler {
let pane = mux
.get_pane(pane_id)
.ok_or_else(|| anyhow!("no such pane {}", pane_id))?;
+ activate_client_palette(&mux, &pane, palette_session_id)?;
pane.key_down(event.key, event.modifiers)?;
// For a key press, we want to always send back the
@@ -712,6 +818,7 @@ impl SessionHandler {
let pane = mux
.get_pane(pane_id)
.ok_or_else(|| anyhow!("no such pane {}", pane_id))?;
+ activate_client_palette(&mux, &pane, palette_session_id)?;
// The client coalesces rapid wheel motion into a single
// event with an accumulated amount, but the terminal
// emits one report per event regardless of the amount;
@@ -772,11 +879,28 @@ impl SessionHandler {
let client_id = self.client_id.clone();
spawn_into_main_thread(async move {
let mux = Mux::get();
- let _identity = mux.with_identity(client_id);
- send_response(
+ let _identity = mux.with_identity(client_id.clone());
+ let result = (|| {
+ let pane = mux
+ .get_pane(request.pane_id)
+ .ok_or_else(|| anyhow!("no such pane {}", request.pane_id))?;
+ let (_domain_id, _window_id, tab_id) = mux
+ .resolve_pane_id(request.pane_id)
+ .ok_or_else(|| anyhow!("no such pane {}", request.pane_id))?;
+ let tab = mux
+ .get_tab(tab_id)
+ .ok_or_else(|| anyhow!("no such tab {}", tab_id))?;
+ if let Some(zoomed) = tab.get_zoomed_pane() {
+ let zoomed_stack = tab.pane_stack_id(zoomed.pane_id());
+ let target_stack = tab.pane_stack_id(request.pane_id);
+ if zoomed_stack.is_none() || zoomed_stack != target_stack {
+ anyhow::bail!("cannot switch pane tab while zoomed");
+ }
+ }
+ activate_client_palette(&mux, &pane, palette_session_id)?;
mux.activate_pane_in_stack(request.pane_id)
- .map(|()| Pdu::UnitResponse(UnitResponse {})),
- );
+ })();
+ send_response(result.map(|()| Pdu::UnitResponse(UnitResponse {})));
})
.detach();
}
@@ -987,30 +1111,19 @@ impl SessionHandler {
let pane = mux
.get_pane(pane_id)
.ok_or_else(|| anyhow!("no such pane {}", pane_id))?;
-
- match pane.get_config() {
- Some(config) => match config.downcast_ref::<TermConfig>() {
- Some(tc) => tc.set_client_palette(palette),
- None => {
- log::error!(
- "pane {pane_id} doesn't \
- have TermConfig as its config! \
- Ignoring client palette update"
- );
- }
- },
- None => {
- let config = TermConfig::new();
- config.set_client_palette(palette);
- pane.set_config(Arc::new(config));
- }
+ let palette_session_id = palette_session_id.ok_or_else(|| {
+ anyhow!("palette advisory requires a live client session")
+ })?;
+
+ // Advice from a background client is stored only.
+ // If this client already owns the pane, a config
+ // reload updates the OSC query base immediately.
+ if let Some(palette) =
+ mux.advise_client_palette(palette_session_id, pane_id, palette)
+ {
+ apply_client_palette(&pane, Some(palette))?;
}
- mux.notify(MuxNotification::Alert {
- pane_id,
- alert: Alert::PaletteChanged,
- });
-
Ok(Pdu::UnitResponse(UnitResponse {}))
},
send_response,
@@ -1054,6 +1167,7 @@ impl SessionHandler {
Pdu::Invalid { .. } => send_response(Err(anyhow!("invalid PDU {:?}", decoded.pdu))),
Pdu::Pong { .. }
| Pdu::ListPanesResponse { .. }
+ | Pdu::SetApplicationPalette { .. }
| Pdu::SetClipboard { .. }
| Pdu::NotifyAlert { .. }
| Pdu::SpawnResponse { .. }
@@ -1264,3 +1378,25 @@ async fn move_pane(
window_id,
}))
}
+
+#[cfg(test)]
+mod tests {
+ use super::PerPane;
+ use wezterm_term::color::ColorPalette;
+
+ #[test]
+ fn application_palette_delivery_distinguishes_unsent_from_reset() {
+ let mut state = PerPane::default();
+ assert!(state.needs_application_palette(&None));
+
+ state.record_application_palette(None);
+ assert!(!state.needs_application_palette(&None));
+
+ let palette = Some(ColorPalette::default());
+ assert!(state.needs_application_palette(&palette));
+ state.record_application_palette(palette.clone());
+ assert!(!state.needs_application_palette(&palette));
+
+ assert!(state.needs_application_palette(&None));
+ }
+}
diff --git a/wezterm/src/cli/activate_pane.rs b/wezterm/src/cli/activate_pane.rs
index 86e827af..0de9abc2 100644
--- a/wezterm/src/cli/activate_pane.rs
+++ b/wezterm/src/cli/activate_pane.rs
@@ -15,7 +15,10 @@ impl ActivatePane {
pub async fn run(&self, client: Client) -> anyhow::Result<()> {
let pane_id = client.resolve_pane_id(self.pane_id).await?;
client
- .set_focused_pane_id(codec::SetFocusedPane { pane_id })
+ .set_focused_pane_id(codec::SetFocusedPane {
+ pane_id,
+ configured_palette: None,
+ })
.await?;
Ok(())
}
diff --git a/wezterm/src/cli/activate_tab.rs b/wezterm/src/cli/activate_tab.rs
index 1c4694fa..f58085ea 100644
--- a/wezterm/src/cli/activate_tab.rs
+++ b/wezterm/src/cli/activate_tab.rs
@@ -154,6 +154,7 @@ impl ActivateTab {
client
.set_focused_pane_id(codec::SetFocusedPane {
pane_id: target_pane,
+ configured_palette: None,
})
.await?;
Ok(())
diff --git a/window/Cargo.toml b/window/Cargo.toml
index 3ef5cb95..50250c89 100644
--- a/window/Cargo.toml
+++ b/window/Cargo.toml
@@ -42,6 +42,7 @@ resize.workspace = true
serde = {workspace=true, features = ["rc", "derive"]}
tiny-skia.workspace = true
glium.workspace = true
+shlex.workspace = true
url.workspace = true
wezterm-bidi.workspace = true
wezterm-color-types.workspace = true
@@ -105,4 +106,3 @@ objc.workspace = true
objc2.workspace = true
objc2-core-graphics.workspace = true
plist.workspace = true
-shlex.workspace = true
diff --git a/window/src/lib.rs b/window/src/lib.rs
index 93c4d6b2..36217061 100644
--- a/window/src/lib.rs
+++ b/window/src/lib.rs
@@ -51,6 +51,83 @@ impl Default for Clipboard {
}
}
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ClipboardImageFormat {
+ Png,
+ Bmp,
+ Tiff,
+}
+
+/// What the clipboard actually holds, with the type information the
+/// platform gave us. `get_clipboard` collapses everything to text at the
+/// window layer; consumers that can do better with files or images (like
+/// uploading them to a remote session) use `get_clipboard_contents` and
+/// receive them un-flattened.
+///
+/// Priority when a platform offers several representations:
+/// files > text > image. Files usually travel with a text rendition
+/// (Finder adds one) and the files are the intent; spreadsheets offer
+/// text plus a bitmap of the cells and the text is the intent; images
+/// with no text rendition (screenshots) can only be the image.
+#[derive(Debug, Clone, PartialEq)]
+pub enum ClipboardContents {
+ Text(String),
+ FilePaths(Vec<PathBuf>),
+ Image {
+ format: ClipboardImageFormat,
+ bytes: Vec<u8>,
+ },
+}
+
+#[cfg(all(unix, not(target_os = "macos")))]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum ClipboardRepresentation {
+ UriList,
+ Text,
+ Png,
+}
+
+#[cfg(all(unix, not(target_os = "macos")))]
+pub(crate) fn preferred_clipboard_representation(
+ has_uri_list: bool,
+ has_text: bool,
+ has_png: bool,
+) -> ClipboardRepresentation {
+ if has_uri_list {
+ ClipboardRepresentation::UriList
+ } else if has_text {
+ ClipboardRepresentation::Text
+ } else if has_png {
+ ClipboardRepresentation::Png
+ } else {
+ // Preserve the historical behavior for an unusual offer with none of
+ // the recognized MIME types: ask for text and let the compositor
+ // report that it cannot provide it.
+ ClipboardRepresentation::Text
+ }
+}
+
+impl ClipboardContents {
+ /// The textual rendition used by the legacy `get_clipboard` path:
+ /// files become a shell-quoted list (the historical macOS behavior),
+ /// an image has no text form.
+ pub fn to_text(&self) -> String {
+ match self {
+ Self::Text(text) => text.clone(),
+ Self::FilePaths(paths) => paths
+ .iter()
+ .map(|path| {
+ shlex::try_quote(&path.to_string_lossy())
+ .map(|quoted| quoted.into_owned())
+ .unwrap_or_default()
+ })
+ .collect::<Vec<_>>()
+ .join(" "),
+ Self::Image { .. } => String::new(),
+ }
+ }
+}
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Dimensions {
pub pixel_width: usize,
@@ -721,6 +798,20 @@ pub trait WindowOps {
/// Initiate textual transfer from the clipboard
fn get_clipboard(&self, clipboard: Clipboard) -> Future<String>;
+ /// Initiate typed transfer from the clipboard: file lists and images
+ /// survive as such instead of being flattened to text. Backends that
+ /// don't implement this yet degrade to the textual read.
+ fn get_clipboard_contents(&self, clipboard: Clipboard) -> Future<ClipboardContents> {
+ let mut promise = promise::Promise::new();
+ let future = promise.get_future().unwrap();
+ let text = self.get_clipboard(clipboard);
+ promise::spawn::spawn(async move {
+ promise.result(text.await.map(ClipboardContents::Text));
+ })
+ .detach();
+ future
+ }
+
/// Set some text in the clipboard
fn set_clipboard(&self, clipboard: Clipboard, text: String);
@@ -798,3 +889,50 @@ impl ResizeIncrement {
}
}
}
+
+#[cfg(test)]
+mod clipboard_contents_tests {
+ use super::*;
+
+ /// The textual degrade keeps the historical macOS behavior on every
+ /// platform: a copied file pastes as its shell-quoted path.
+ #[test]
+ fn contents_flatten_to_text_the_way_the_old_reader_did() {
+ assert_eq!(
+ ClipboardContents::FilePaths(vec![
+ PathBuf::from("/tmp/plain.txt"),
+ PathBuf::from("/tmp/with space (1).png"),
+ ])
+ .to_text(),
+ "/tmp/plain.txt '/tmp/with space (1).png'"
+ );
+ assert_eq!(ClipboardContents::Text("hi".into()).to_text(), "hi");
+ assert_eq!(
+ ClipboardContents::Image {
+ format: ClipboardImageFormat::Png,
+ bytes: vec![1, 2, 3],
+ }
+ .to_text(),
+ "",
+ "an image has no textual rendition"
+ );
+ }
+
+ #[test]
+ #[cfg(all(unix, not(target_os = "macos")))]
+ fn typed_offer_prefers_files_then_text_then_image() {
+ assert_eq!(
+ preferred_clipboard_representation(true, true, true),
+ ClipboardRepresentation::UriList
+ );
+ assert_eq!(
+ preferred_clipboard_representation(false, true, true),
+ ClipboardRepresentation::Text,
+ "a spreadsheet-style text+image offer must paste text"
+ );
+ assert_eq!(
+ preferred_clipboard_representation(false, false, true),
+ ClipboardRepresentation::Png
+ );
+ }
+}
diff --git a/window/src/os/macos/clipboard.rs b/window/src/os/macos/clipboard.rs
index b401a25c..47914a05 100644
--- a/window/src/os/macos/clipboard.rs
+++ b/window/src/os/macos/clipboard.rs
@@ -1,7 +1,9 @@
use crate::macos::{nsstring, nsstring_to_str};
+use crate::{ClipboardContents, ClipboardImageFormat};
use cocoa::appkit::{NSFilenamesPboardType, NSPasteboard, NSStringPboardType};
use cocoa::base::*;
-use cocoa::foundation::NSArray;
+use cocoa::foundation::{NSArray, NSData};
+use std::path::PathBuf;
pub struct Clipboard {
pasteboard: id,
@@ -17,22 +19,39 @@ impl Clipboard {
}
pub fn read(&self) -> anyhow::Result<String> {
+ // Historical textual behavior: files flatten to a shell-quoted list.
+ Ok(self.read_contents()?.to_text())
+ }
+
+ /// Files > text > image; see [`ClipboardContents`] for the rationale.
+ pub fn read_contents(&self) -> anyhow::Result<ClipboardContents> {
unsafe {
let plist = self.pasteboard.propertyListForType(NSFilenamesPboardType);
if !plist.is_null() {
- let mut filenames = vec![];
+ let mut paths = vec![];
for i in 0..plist.count() {
- filenames.push(
- shlex::try_quote(nsstring_to_str(plist.objectAtIndex(i)))
- .unwrap_or_else(|_| "".into()),
- );
+ paths.push(PathBuf::from(nsstring_to_str(plist.objectAtIndex(i))));
}
- return Ok(filenames.join(" "));
+ return Ok(ClipboardContents::FilePaths(paths));
}
let s = self.pasteboard.stringForType(NSStringPboardType);
if !s.is_null() {
- let str = nsstring_to_str(s);
- return Ok(str.to_string());
+ return Ok(ClipboardContents::Text(nsstring_to_str(s).to_string()));
+ }
+ for (uti, format) in [
+ ("public.png", ClipboardImageFormat::Png),
+ ("public.tiff", ClipboardImageFormat::Tiff),
+ ] {
+ let data = self.pasteboard.dataForType(*nsstring(uti));
+ if data.is_null() {
+ continue;
+ }
+ let len = data.length() as usize;
+ if len == 0 {
+ continue;
+ }
+ let bytes = std::slice::from_raw_parts(data.bytes() as *const u8, len).to_vec();
+ return Ok(ClipboardContents::Image { format, bytes });
}
}
anyhow::bail!("pasteboard read returned empty");
diff --git a/window/src/os/macos/menu.rs b/window/src/os/macos/menu.rs
index cd8e11a7..d0d7c5b8 100644
--- a/window/src/os/macos/menu.rs
+++ b/window/src/os/macos/menu.rs
@@ -1,6 +1,5 @@
use crate::macos::{nsstring, nsstring_to_str};
-use crate::superclass;
-use crate::{ContextMenuAction, ContextMenuIcon};
+use crate::{superclass, ContextMenuAction, ContextMenuIcon};
pub use cocoa::appkit::NSEventModifierFlags;
use cocoa::appkit::{NSApp, NSApplication, NSMenu, NSMenuItem};
pub use cocoa::base::SEL;
diff --git a/window/src/os/macos/window.rs b/window/src/os/macos/window.rs
index 80130035..e355057f 100644
--- a/window/src/os/macos/window.rs
+++ b/window/src/os/macos/window.rs
@@ -9,12 +9,12 @@ use crate::connection::ConnectionOps;
use crate::os::macos::menu::{Menu, MenuItem, RepresentedItem};
use crate::parameters::{Border, Parameters, TitleBar};
use crate::{
- Clipboard, Connection, ContextMenuItem, DeadKeyStatus, Dimensions, FolderPickerOptions,
- Handled, Image, KeyCode, KeyEvent, Modifiers, MouseButtons, MouseCursor, MouseEvent,
- MouseEventKind, MousePress, NativeTextInputSnapshot, Point, PreciseScrollDelta, RawKeyEvent,
- Rect, RequestedWindowGeometry, ResizeIncrement, ResolvedGeometry, ScreenPoint, ScrollPhase,
- Size, TextCheckCapabilities, TextCheckIssue, TextCheckRequest, TextCheckResponse, ULength,
- WindowDecorations, WindowEvent, WindowEventSender, WindowOps, WindowState,
+ Clipboard, ClipboardContents, Connection, ContextMenuItem, DeadKeyStatus, Dimensions,
+ FolderPickerOptions, Handled, Image, KeyCode, KeyEvent, Modifiers, MouseButtons, MouseCursor,
+ MouseEvent, MouseEventKind, MousePress, NativeTextInputSnapshot, Point, PreciseScrollDelta,
+ RawKeyEvent, Rect, RequestedWindowGeometry, ResizeIncrement, ResolvedGeometry, ScreenPoint,
+ ScrollPhase, Size, TextCheckCapabilities, TextCheckIssue, TextCheckRequest, TextCheckResponse,
+ ULength, WindowDecorations, WindowEvent, WindowEventSender, WindowOps, WindowState,
};
use anyhow::{anyhow, bail, ensure};
use async_trait::async_trait;
@@ -1218,6 +1218,14 @@ impl WindowOps for Window {
)
}
+ fn get_clipboard_contents(&self, _clipboard: Clipboard) -> Future<ClipboardContents> {
+ Future::result(
+ ClipboardContext::new()
+ .read_contents()
+ .map_err(|e| anyhow!("Failed to get clipboard:{}", e)),
+ )
+ }
+
fn set_clipboard(&self, _clipboard: Clipboard, text: String) {
ClipboardContext::new().write(text).ok();
}
diff --git a/window/src/os/mod.rs b/window/src/os/mod.rs
index 21c6b018..8901cef9 100644
--- a/window/src/os/mod.rs
+++ b/window/src/os/mod.rs
@@ -19,3 +19,4 @@ pub mod macos;
pub use self::macos::*;
pub mod parameters;
+pub mod uri_list;
diff --git a/window/src/os/uri_list.rs b/window/src/os/uri_list.rs
new file mode 100644
index 00000000..dfd6b162
--- /dev/null
+++ b/window/src/os/uri_list.rs
@@ -0,0 +1,100 @@
+//! text/uri-list decoding, shared by drag-and-drop (XDND) and clipboard
+//! reads on the X11 and Wayland backends.
+use std::path::PathBuf;
+use url::Url;
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ParsedUriList {
+ pub paths: Vec<PathBuf>,
+ /// A normalized textual rendition for non-file URI lists. Comments and
+ /// blank lines are omitted so this can safely become the paste fallback.
+ pub fallback_text: String,
+}
+
+pub fn decode_texturi_list(url_list: &[u8]) -> ParsedUriList {
+ let mut paths = Vec::new();
+ let mut uri_lines = Vec::new();
+
+ for line in String::from_utf8_lossy(url_list).lines() {
+ let line = line.trim();
+ if line.starts_with('#') || line.is_empty() {
+ // text/uri-list: comment and empty lines carry no payload.
+ continue;
+ }
+ uri_lines.push(line.to_string());
+ let Ok(url) = Url::parse(line).map_err(|err| {
+ log::error!("Error parsing dropped file line {line} as url: {err:#}");
+ }) else {
+ continue;
+ };
+ if let Ok(path) = url.to_file_path().map_err(|_| {
+ log::debug!("URI-list entry {url:?} is not a local file");
+ }) {
+ paths.push(path);
+ }
+ }
+
+ ParsedUriList {
+ paths,
+ fallback_text: uri_lines.join("\n"),
+ }
+}
+
+pub fn parse_texturi_list(url_list: &[u8]) -> Vec<PathBuf> {
+ decode_texturi_list(url_list).paths
+}
+
+pub fn clipboard_contents_from_uri_list(
+ uri_list: &[u8],
+ advertised_text: Option<&[u8]>,
+) -> crate::ClipboardContents {
+ let parsed = decode_texturi_list(uri_list);
+ if !parsed.paths.is_empty() {
+ crate::ClipboardContents::FilePaths(parsed.paths)
+ } else if let Some(text) = advertised_text {
+ crate::ClipboardContents::Text(String::from_utf8_lossy(text).replace("\r\n", "\n"))
+ } else {
+ crate::ClipboardContents::Text(parsed.fallback_text)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_uri_list_decodes_paths_and_skips_noise() {
+ let list = b"# comment line\r\nfile:///home/x/a%20b.txt\r\n\r\nhttps://example.com/nope\r\nfile:///tmp/plain.png\r\n";
+ assert_eq!(
+ parse_texturi_list(list),
+ vec![
+ PathBuf::from("/home/x/a b.txt"),
+ PathBuf::from("/tmp/plain.png"),
+ ]
+ );
+ }
+
+ #[test]
+ fn uri_without_files_uses_advertised_text() {
+ assert_eq!(
+ clipboard_contents_from_uri_list(
+ b"https://example.com/report\r\n",
+ Some(b"Quarterly report\r\n")
+ ),
+ crate::ClipboardContents::Text("Quarterly report\n".to_string())
+ );
+ }
+
+ #[test]
+ fn uri_without_text_preserves_normalized_uri_text() {
+ assert_eq!(
+ clipboard_contents_from_uri_list(
+ b"# generated\r\nhttps://example.com/a\r\nhttps://example.com/b\r\n",
+ None,
+ ),
+ crate::ClipboardContents::Text(
+ "https://example.com/a\nhttps://example.com/b".to_string()
+ )
+ );
+ }
+}
diff --git a/window/src/os/wayland/copy_and_paste.rs b/window/src/os/wayland/copy_and_paste.rs
index ce309fbd..3ca2be92 100644
--- a/window/src/os/wayland/copy_and_paste.rs
+++ b/window/src/os/wayland/copy_and_paste.rs
@@ -10,11 +10,21 @@ use toolkit::primary_selection::selection::PrimarySelectionSourceHandler;
use wayland_protocols::wp::primary_selection::zv1::client::zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1;
use wayland_protocols::wp::primary_selection::zv1::client::zwp_primary_selection_source_v1::ZwpPrimarySelectionSourceV1;
-use crate::{Clipboard, ConnectionOps};
+use crate::{
+ preferred_clipboard_representation, Clipboard, ClipboardRepresentation, ConnectionOps,
+};
-use super::data_device::TEXT_MIME_TYPE;
+use super::data_device::{PNG_MIME_TYPE, TEXT_MIME_TYPE, URI_MIME_TYPE};
use super::state::WaylandState;
+/// Which representation of the clipboard a read pipe carries.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(super) enum ClipboardOfferKind {
+ Text,
+ UriList,
+ Png,
+}
+
#[derive(Default)]
pub struct CopyAndPaste {
data_offer: Option<SelectionOffer>,
@@ -34,6 +44,18 @@ impl CopyAndPaste {
}
pub(super) fn get_clipboard_data(&mut self, clipboard: Clipboard) -> anyhow::Result<ReadPipe> {
+ Ok(self.get_clipboard_contents_pipe(clipboard, false)?.1)
+ }
+
+ /// Open a read pipe for the best representation the offer has. With
+ /// `typed` set, files (text/uri-list), text, and images (image/png) are
+ /// negotiated in that order; otherwise text is the only representation
+ /// considered, matching the historical behavior.
+ pub(super) fn get_clipboard_contents_pipe(
+ &mut self,
+ clipboard: Clipboard,
+ typed: bool,
+ ) -> anyhow::Result<(ClipboardOfferKind, ReadPipe, Option<ReadPipe>)> {
let conn = crate::Connection::get().unwrap().wayland();
let wayland_state = conn.wayland_state.borrow();
let primary_selection = if let Clipboard::PrimarySelection = clipboard {
@@ -44,20 +66,47 @@ impl CopyAndPaste {
match primary_selection {
Some(primary_selection) => {
+ // The primary selection is middle-click text territory;
+ // files and images stay on the regular clipboard.
let offer = primary_selection
.data()
.selection_offer()
.ok_or_else(|| anyhow!("no primary selection offer"))?;
let pipe = offer.receive(TEXT_MIME_TYPE.to_string())?;
- Ok(pipe)
+ Ok((ClipboardOfferKind::Text, pipe, None))
}
None => {
let offer = self
.data_offer
.as_ref()
.ok_or_else(|| anyhow!("no data offer"))?;
- let pipe = offer.receive(TEXT_MIME_TYPE.to_string())?;
- Ok(pipe)
+ let (kind, has_text) = if typed {
+ offer.with_mime_types(|mimes| {
+ let has_text = mimes.iter().any(|mime| mime == TEXT_MIME_TYPE);
+ let kind = match preferred_clipboard_representation(
+ mimes.iter().any(|mime| mime == URI_MIME_TYPE),
+ has_text,
+ mimes.iter().any(|mime| mime == PNG_MIME_TYPE),
+ ) {
+ ClipboardRepresentation::UriList => ClipboardOfferKind::UriList,
+ ClipboardRepresentation::Text => ClipboardOfferKind::Text,
+ ClipboardRepresentation::Png => ClipboardOfferKind::Png,
+ };
+ (kind, has_text)
+ })
+ } else {
+ (ClipboardOfferKind::Text, true)
+ };
+ let mime = match kind {
+ ClipboardOfferKind::UriList => URI_MIME_TYPE,
+ ClipboardOfferKind::Png => PNG_MIME_TYPE,
+ ClipboardOfferKind::Text => TEXT_MIME_TYPE,
+ };
+ let pipe = offer.receive(mime.to_string())?;
+ let text_fallback = (kind == ClipboardOfferKind::UriList && has_text)
+ .then(|| offer.receive(TEXT_MIME_TYPE.to_string()))
+ .transpose()?;
+ Ok((kind, pipe, text_fallback))
}
}
}
@@ -97,6 +146,10 @@ impl CopyAndPaste {
pub(super) fn confirm_selection(&mut self, offer: SelectionOffer) {
self.data_offer.replace(offer);
}
+
+ pub(super) fn clear_selection(&mut self) {
+ self.data_offer.take();
+ }
}
impl WaylandState {
diff --git a/window/src/os/wayland/data_device.rs b/window/src/os/wayland/data_device.rs
index 338280e0..bf957a2c 100644
--- a/window/src/os/wayland/data_device.rs
+++ b/window/src/os/wayland/data_device.rs
@@ -17,6 +17,11 @@ use super::state::WaylandState;
pub(super) const TEXT_MIME_TYPE: &str = "text/plain;charset=utf-8";
pub(super) const URI_MIME_TYPE: &str = "text/uri-list";
+pub(super) const PNG_MIME_TYPE: &str = "image/png";
+
+fn is_supported_clipboard_mime(mime: &str) -> bool {
+ matches!(mime, TEXT_MIME_TYPE | URI_MIME_TYPE | PNG_MIME_TYPE)
+}
impl DataDeviceHandler for WaylandState {
fn enter(
@@ -107,13 +112,18 @@ impl DataDeviceHandler for WaylandState {
return;
}
};
- if let Some(offer) = offer {
- if !offer.with_mime_types(|mime_types| mime_types.iter().any(|s| s == TEXT_MIME_TYPE)) {
- return;
- }
-
- if let Some(copy_and_paste) = self.resolve_copy_and_paste() {
+ let supported = offer.as_ref().map_or(false, |offer| {
+ offer.with_mime_types(|mime_types| {
+ mime_types
+ .iter()
+ .any(|mime| is_supported_clipboard_mime(mime))
+ })
+ });
+ if let Some(copy_and_paste) = self.resolve_copy_and_paste() {
+ if let (true, Some(offer)) = (supported, offer) {
copy_and_paste.lock().unwrap().confirm_selection(offer);
+ } else {
+ copy_and_paste.lock().unwrap().clear_selection();
}
}
}
@@ -144,6 +154,19 @@ impl DataDeviceHandler for WaylandState {
}
}
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn typed_selection_keeps_every_supported_offer_kind() {
+ assert!(is_supported_clipboard_mime(TEXT_MIME_TYPE));
+ assert!(is_supported_clipboard_mime(URI_MIME_TYPE));
+ assert!(is_supported_clipboard_mime(PNG_MIME_TYPE));
+ assert!(!is_supported_clipboard_mime("application/octet-stream"));
+ }
+}
+
impl DataOfferHandler for WaylandState {
// Ignore drag and drop events
fn source_actions(
diff --git a/window/src/os/wayland/window.rs b/window/src/os/wayland/window.rs
index 086ebedf..df34ca78 100644
--- a/window/src/os/wayland/window.rs
+++ b/window/src/os/wayland/window.rs
@@ -53,8 +53,8 @@ use wezterm_input_types::{
use crate::wayland::WaylandConnection;
use crate::x11::KeyboardWithFallback;
use crate::{
- Appearance, Clipboard, Connection, ConnectionOps, Dimensions, MouseCursor, Point, Rect,
- RequestedWindowGeometry, ResizeIncrement, ResolvedGeometry, Window, WindowEvent,
+ Appearance, Clipboard, ClipboardContents, Connection, ConnectionOps, Dimensions, MouseCursor,
+ Point, Rect, RequestedWindowGeometry, ResizeIncrement, ResolvedGeometry, Window, WindowEvent,
WindowEventSender, WindowKeyEvent, WindowOps, WindowState,
};
@@ -83,9 +83,7 @@ impl WaylandDimensions for Dimensions {
const WAYLAND_RESIZE_EDGE_LOGICAL_PIXELS: f64 = 6.0;
-fn requested_wayland_decoration_mode(
- decorations: WindowDecorations,
-) -> Option<DecorationMode> {
+fn requested_wayland_decoration_mode(decorations: WindowDecorations) -> Option<DecorationMode> {
if decorations == WindowDecorations::NONE {
None
} else if decorations.contains(WindowDecorations::INTEGRATED_BUTTONS) {
@@ -147,8 +145,7 @@ fn wayland_surface_resize_edge_at(
height: usize,
edge_pixels: usize,
) -> Option<WaylandSurfaceResizeEdge> {
- if x < 0 || y < 0 || x as usize >= width || y as usize >= height || width == 0 || height == 0
- {
+ if x < 0 || y < 0 || x as usize >= width || y as usize >= height || width == 0 || height == 0 {
return None;
}
@@ -174,7 +171,7 @@ fn wayland_surface_resize_edge_at(
}
}
-use super::copy_and_paste::CopyAndPaste;
+use super::copy_and_paste::{ClipboardOfferKind, CopyAndPaste};
use super::pointer::{PendingMouse, PointerUserData};
use super::state::WaylandState;
@@ -568,6 +565,67 @@ impl WindowOps for WaylandWindow {
future
}
+ fn get_clipboard_contents(&self, clipboard: Clipboard) -> Future<ClipboardContents> {
+ let mut promise = Promise::new();
+ let future = promise.get_future().unwrap();
+ let promise = Arc::new(Mutex::new(promise));
+ let request = WaylandConnection::with_window_inner(self.0, move |inner| {
+ inner
+ .copy_and_paste
+ .lock()
+ .unwrap()
+ .get_clipboard_contents_pipe(clipboard, true)
+ });
+ promise::spawn::spawn(async move {
+ let result = match request.await {
+ Ok((kind, read, text_fallback)) => {
+ promise::spawn::spawn_into_new_thread(move || {
+ // Drain an advertised text fallback concurrently. Some
+ // clipboard owners do not write the second pipe until the
+ // first has a reader, and either pipe may be large.
+ let fallback_reader = text_fallback.map(|read| {
+ std::thread::spawn(move || read_pipe_bytes_with_timeout(read))
+ });
+ match read_pipe_bytes_with_timeout(read) {
+ Ok(bytes) => {
+ let contents = match kind {
+ ClipboardOfferKind::UriList => {
+ let fallback = fallback_reader
+ .and_then(|reader| reader.join().ok())
+ .and_then(Result::ok);
+ crate::os::uri_list::clipboard_contents_from_uri_list(
+ &bytes,
+ fallback.as_deref(),
+ )
+ }
+ ClipboardOfferKind::Png => ClipboardContents::Image {
+ format: crate::ClipboardImageFormat::Png,
+ bytes,
+ },
+ ClipboardOfferKind::Text => ClipboardContents::Text(
+ // Same unix line-ending normalization as the
+ // textual read.
+ String::from_utf8_lossy(&bytes).replace("\r\n", "\n"),
+ ),
+ };
+ Ok(contents)
+ }
+ Err(e) => {
+ log::error!("while reading clipboard: {}", e);
+ Err(anyhow!("{}", e))
+ }
+ }
+ })
+ .await
+ }
+ Err(err) => Err(err),
+ };
+ promise.lock().unwrap().result(result);
+ })
+ .detach();
+ future
+ }
+
fn set_clipboard(&self, clipboard: Clipboard, text: String) {
WaylandConnection::with_window_inner(self.0, move |inner| {
inner
@@ -619,7 +677,11 @@ pub(crate) struct PendingEvent {
pub(crate) window_state: Option<WindowState>,
}
-pub(crate) fn read_pipe_with_timeout(mut file: ReadPipe) -> anyhow::Result<String> {
+pub(crate) fn read_pipe_with_timeout(file: ReadPipe) -> anyhow::Result<String> {
+ Ok(String::from_utf8(read_pipe_bytes_with_timeout(file)?)?)
+}
+
+pub(crate) fn read_pipe_bytes_with_timeout(mut file: ReadPipe) -> anyhow::Result<Vec<u8>> {
let mut result = Vec::new();
// set non-blocking I/O on the pipe
@@ -655,7 +717,7 @@ pub(crate) fn read_pipe_with_timeout(mut file: ReadPipe) -> anyhow::Result<Strin
}
}
- Ok(String::from_utf8(result)?)
+ Ok(result)
}
pub struct WaylandWindowInner {
@@ -762,9 +824,9 @@ impl WaylandWindowInner {
return None;
}
- let edge_pixels =
- (WAYLAND_RESIZE_EDGE_LOGICAL_PIXELS * self.dimensions.dpi as f64 / crate::DEFAULT_DPI)
- .round() as usize;
+ let edge_pixels = (WAYLAND_RESIZE_EDGE_LOGICAL_PIXELS * self.dimensions.dpi as f64
+ / crate::DEFAULT_DPI)
+ .round() as usize;
wayland_surface_resize_edge_at(
coords.x,
coords.y,
diff --git a/window/src/os/windows/window.rs b/window/src/os/windows/window.rs
index 1dd9de06..d9887eb4 100644
--- a/window/src/os/windows/window.rs
+++ b/window/src/os/windows/window.rs
@@ -2,12 +2,12 @@ use super::*;
use crate::connection::ConnectionOps;
use crate::parameters::{self, Parameters};
use crate::{
- Appearance, Clipboard, DeadKeyStatus, Dimensions, FolderPickerOptions, Handled, KeyCode,
- KeyEvent, Modifiers, MouseButtons, MouseCursor, MouseEvent, MouseEventKind, MousePress, Point,
- RawKeyEvent, Rect, RequestedWindowGeometry, ResolvedGeometry, ScreenPoint, ScreenRect, ULength,
- WindowDecorations, WindowEvent, WindowEventSender, WindowOps, WindowState,
+ Appearance, Clipboard, ClipboardContents, DeadKeyStatus, Dimensions, FolderPickerOptions,
+ Handled, KeyCode, KeyEvent, Modifiers, MouseButtons, MouseCursor, MouseEvent, MouseEventKind,
+ MousePress, Point, RawKeyEvent, Rect, RequestedWindowGeometry, ResolvedGeometry, ScreenPoint,
+ ScreenRect, ULength, WindowDecorations, WindowEvent, WindowEventSender, WindowOps, WindowState,
};
-use anyhow::{bail, Context};
+use anyhow::{anyhow, bail};
use async_trait::async_trait;
use config::{ConfigHandle, ImePreeditRendering, SystemBackdrop};
use lazy_static::lazy_static;
@@ -1348,10 +1348,57 @@ impl WindowOps for Window {
Future::result(
clipboard_win::get_clipboard_string()
.map(|s| s.replace("\r\n", "\n"))
- .context("Error getting clipboard"),
+ .map_err(|e| anyhow!("Error getting clipboard: {e}")),
)
}
+ fn get_clipboard_contents(&self, _clipboard: Clipboard) -> Future<ClipboardContents> {
+ // Files > text > image: files often travel with a text rendition
+ // and are the intent; spreadsheets offer text plus a bitmap of the
+ // cells and the text is the intent; screenshots are image-only.
+ fn read_contents() -> anyhow::Result<ClipboardContents> {
+ use clipboard_win::Getter;
+
+ // Hold the clipboard open across format negotiation so its owner
+ // cannot change between the files, text, and bitmap probes.
+ let _clipboard = clipboard_win::Clipboard::new_attempts(10)
+ .map_err(|err| anyhow!("Error opening clipboard: {err}"))?;
+
+ let mut files = Vec::<String>::new();
+ if clipboard_win::formats::FileList
+ .read_clipboard(&mut files)
+ .is_ok()
+ && !files.is_empty()
+ {
+ return Ok(ClipboardContents::FilePaths(
+ files.into_iter().map(PathBuf::from).collect(),
+ ));
+ }
+
+ let mut text = String::new();
+ if clipboard_win::formats::Unicode
+ .read_clipboard(&mut text)
+ .is_ok()
+ {
+ return Ok(ClipboardContents::Text(text.replace("\r\n", "\n")));
+ }
+
+ let mut bytes = Vec::new();
+ if clipboard_win::formats::Bitmap
+ .read_clipboard(&mut bytes)
+ .is_ok()
+ {
+ return Ok(ClipboardContents::Image {
+ format: crate::ClipboardImageFormat::Bmp,
+ bytes,
+ });
+ }
+
+ Err(anyhow!("Clipboard has no supported files, text, or bitmap"))
+ }
+ Future::result(read_contents())
+ }
+
fn set_clipboard(&self, _clipboard: Clipboard, text: String) {
clipboard_win::set_clipboard_string(&text).ok();
}
diff --git a/window/src/os/x11/connection.rs b/window/src/os/x11/connection.rs
index 22c3f53b..a9a5b535 100644
--- a/window/src/os/x11/connection.rs
+++ b/window/src/os/x11/connection.rs
@@ -60,6 +60,9 @@ pub struct XConnection {
pub atom_delete: Atom,
pub atom_utf8_string: Atom,
pub atom_xsel_data: Atom,
+ pub atom_xsel_contents: Atom,
+ pub atom_incr: Atom,
+ pub atom_image_png: Atom,
pub atom_targets: Atom,
pub atom_clipboard: Atom,
pub atom_texturilist: Atom,
@@ -679,6 +682,11 @@ impl XConnection {
let atom_delete = Self::intern_atom(&conn, "WM_DELETE_WINDOW")?;
let atom_utf8_string = Self::intern_atom(&conn, "UTF8_STRING")?;
let atom_xsel_data = Self::intern_atom(&conn, "XSEL_DATA")?;
+ // Typed clipboard reads (files/images) land in their own property so
+ // they can never race a concurrent legacy text read on XSEL_DATA.
+ let atom_xsel_contents = Self::intern_atom(&conn, "_THINKTERM_SEL_CONTENTS")?;
+ let atom_incr = Self::intern_atom(&conn, "INCR")?;
+ let atom_image_png = Self::intern_atom(&conn, "image/png")?;
let atom_targets = Self::intern_atom(&conn, "TARGETS")?;
let atom_clipboard = Self::intern_atom(&conn, "CLIPBOARD")?;
let atom_texturilist = Self::intern_atom(&conn, "text/uri-list")?;
@@ -861,6 +869,9 @@ impl XConnection {
kbd_ev,
atom_utf8_string,
atom_xsel_data,
+ atom_xsel_contents,
+ atom_incr,
+ atom_image_png,
atom_targets,
windows: RefCell::new(HashMap::new()),
child_to_parent_id: RefCell::new(HashMap::new()),
diff --git a/window/src/os/x11/window.rs b/window/src/os/x11/window.rs
index ae159666..b654e135 100644
--- a/window/src/os/x11/window.rs
+++ b/window/src/os/x11/window.rs
@@ -3,7 +3,8 @@ use crate::bitmaps::*;
use crate::connection::ConnectionOps;
use crate::os::{xkeysyms, Connection, Window};
use crate::{
- Appearance, Clipboard, DeadKeyStatus, Dimensions, MouseButtons, MouseCursor, MouseEvent,
+ preferred_clipboard_representation, Appearance, Clipboard, ClipboardContents,
+ ClipboardRepresentation, DeadKeyStatus, Dimensions, MouseButtons, MouseCursor, MouseEvent,
MouseEventKind, MousePress, Point, Rect, RequestedWindowGeometry, ResizeIncrement,
ResolvedGeometry, ScreenPoint, ScreenRect, WindowDecorations, WindowEvent, WindowEventSender,
WindowOps, WindowState,
@@ -19,7 +20,6 @@ use raw_window_handle::{
use std::any::Any;
use std::convert::TryInto;
use std::num::NonZeroU32;
-use std::path::PathBuf;
use std::ptr::NonNull;
use std::rc::{Rc, Weak};
use std::sync::{Arc, Mutex};
@@ -35,9 +35,101 @@ struct CopyAndPaste {
primary_selection_owned: Option<String>,
clipboard_request: Option<Promise<String>>,
selection_request: Option<Promise<String>>,
+ /// A typed (files/image/text) read in flight. Runs on its own property
+ /// (`atom_xsel_contents`), independent of the legacy text requests.
+ contents_request: Option<ContentsRequest>,
+ /// The newest typed read requested while an older X11 conversion is still
+ /// outstanding. We do not reuse the property until the old reply (or INCR
+ /// terminator) has been consumed.
+ pending_contents_request: Option<PendingContentsRequest>,
+ /// An INCR transfer feeding the typed read, chunk by chunk.
+ incr_contents: Option<IncrContents>,
time: u32,
}
+/// How to decode the property bytes once the transfer completes.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum ContentsKind {
+ UriList,
+ Png,
+ Utf8Text,
+ Latin1Text,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum ContentsStage {
+ /// We asked the owner which targets it supports.
+ AwaitingTargets,
+ /// We asked for the actual data as `kind`.
+ AwaitingData { kind: ContentsKind },
+}
+
+struct ContentsRequest {
+ clipboard: Clipboard,
+ stage: ContentsStage,
+ /// The conversion target of the outstanding ConvertSelection; a refusal
+ /// (SelectionNotify with property None) is matched against this, since a
+ /// refusal doesn't name the property it was destined for.
+ last_target: Atom,
+ promise: Option<Promise<ClipboardContents>>,
+ canceled: bool,
+ targets_known: bool,
+ utf8_text_available: bool,
+ latin1_text_available: bool,
+ uri_fallback_text: Option<String>,
+}
+
+struct PendingContentsRequest {
+ clipboard: Clipboard,
+ promise: Promise<ClipboardContents>,
+}
+
+struct IncrContents {
+ kind: ContentsKind,
+ buf: Vec<u8>,
+}
+
+fn successful_contents_notify_matches(
+ expected_target: Atom,
+ notification_target: Atom,
+ notification_property: Atom,
+ contents_property: Atom,
+) -> bool {
+ notification_property == contents_property && notification_target == expected_target
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum SupersededContentsReply {
+ Retire,
+ DrainIncr,
+}
+
+fn superseded_contents_reply(stage: ContentsStage, is_incr: bool) -> SupersededContentsReply {
+ if is_incr && matches!(stage, ContentsStage::AwaitingData { .. }) {
+ SupersededContentsReply::DrainIncr
+ } else {
+ SupersededContentsReply::Retire
+ }
+}
+
+fn latin1_to_string(s: &[u8]) -> String {
+ s.iter().map(|&c| c as char).collect()
+}
+
+fn decode_contents(kind: ContentsKind, bytes: &[u8]) -> ClipboardContents {
+ match kind {
+ ContentsKind::UriList => crate::os::uri_list::clipboard_contents_from_uri_list(bytes, None),
+ ContentsKind::Png => ClipboardContents::Image {
+ format: crate::ClipboardImageFormat::Png,
+ bytes: bytes.to_vec(),
+ },
+ ContentsKind::Utf8Text => {
+ ClipboardContents::Text(String::from_utf8_lossy(bytes).to_string())
+ }
+ ContentsKind::Latin1Text => ClipboardContents::Text(latin1_to_string(bytes)),
+ }
+}
+
impl CopyAndPaste {
fn clipboard(&self, clipboard: Clipboard) -> &Option<String> {
match clipboard {
@@ -1054,6 +1146,12 @@ impl XWindowInner {
let atom_name = conn.atom_name(msg.atom());
log::trace!("PropertyNotifyEvent {atom_name}");
+ if msg.atom() == conn.atom_xsel_contents
+ && msg.state() == xcb::x::Property::NewValue
+ {
+ self.continue_incr_contents()?;
+ }
+
if msg.atom() == conn.atom_gtk_edge_constraints {
// "_GTK_EDGE_CONSTRAINTS" property is changed when the
// accessibility settings change the text size and thus
@@ -1288,6 +1386,376 @@ impl XWindowInner {
Ok(())
}
+ /// Begin a typed clipboard read: ask the owner which targets it offers,
+ /// then fetch files (text/uri-list), text, or an image (image/png) in
+ /// that order of preference. A newer request supersedes an unfinished
+ /// one — the old promise resolves to an error.
+ fn request_clipboard_contents(
+ &mut self,
+ clipboard: Clipboard,
+ promise: Promise<ClipboardContents>,
+ ) {
+ if let Some(active) = self.copy_and_paste.contents_request.as_mut() {
+ if let Some(mut old_promise) = active.promise.take() {
+ old_promise.err(anyhow!("clipboard contents request superseded"));
+ }
+ active.canceled = true;
+ if let Some(mut pending) = self.copy_and_paste.pending_contents_request.take() {
+ pending
+ .promise
+ .err(anyhow!("clipboard contents request superseded"));
+ }
+ self.copy_and_paste.pending_contents_request =
+ Some(PendingContentsRequest { clipboard, promise });
+ return;
+ }
+
+ self.start_clipboard_contents_request(PendingContentsRequest { clipboard, promise });
+ }
+
+ fn start_clipboard_contents_request(&mut self, request: PendingContentsRequest) {
+ debug_assert!(self.copy_and_paste.contents_request.is_none());
+ let conn = self.conn();
+ let clipboard = request.clipboard;
+ self.copy_and_paste.incr_contents = None;
+ self.copy_and_paste.contents_request = Some(ContentsRequest {
+ clipboard,
+ stage: ContentsStage::AwaitingTargets,
+ last_target: conn.atom_targets,
+ promise: Some(request.promise),
+ canceled: false,
+ targets_known: false,
+ utf8_text_available: false,
+ latin1_text_available: false,
+ uri_fallback_text: None,
+ });
+ conn.send_request_no_reply_log(&xcb::x::ConvertSelection {
+ requestor: self.window_id,
+ selection: match clipboard {
+ Clipboard::Clipboard => conn.atom_clipboard,
+ Clipboard::PrimarySelection => xcb::x::ATOM_PRIMARY,
+ },
+ target: conn.atom_targets,
+ property: conn.atom_xsel_contents,
+ time: self.copy_and_paste.time,
+ });
+ }
+
+ /// Ask for the selection converted to `target`, to be decoded as `kind`.
+ fn convert_contents_target(&mut self, target: Atom, kind: ContentsKind) {
+ let conn = self.conn();
+ let Some(req) = self.copy_and_paste.contents_request.as_mut() else {
+ return;
+ };
+ req.stage = ContentsStage::AwaitingData { kind };
+ req.last_target = target;
+ let selection = match req.clipboard {
+ Clipboard::Clipboard => conn.atom_clipboard,
+ Clipboard::PrimarySelection => xcb::x::ATOM_PRIMARY,
+ };
+ conn.send_request_no_reply_log(&xcb::x::ConvertSelection {
+ requestor: self.window_id,
+ selection,
+ target,
+ property: conn.atom_xsel_contents,
+ time: self.copy_and_paste.time,
+ });
+ }
+
+ fn retire_contents_request(&mut self, contents: Option<ClipboardContents>) {
+ self.copy_and_paste.incr_contents = None;
+ if let Some(mut req) = self.copy_and_paste.contents_request.take() {
+ if !req.canceled {
+ if let Some(mut promise) = req.promise.take() {
+ match contents {
+ Some(contents) => promise.ok(contents),
+ None => promise.err(anyhow!("clipboard contents request canceled")),
+ };
+ }
+ }
+ }
+ if let Some(pending) = self.copy_and_paste.pending_contents_request.take() {
+ self.start_clipboard_contents_request(pending);
+ }
+ }
+
+ fn finish_contents_request(&mut self, contents: ClipboardContents) {
+ self.retire_contents_request(Some(contents));
+ }
+
+ fn finish_contents_with_uri_fallback(&mut self) {
+ let fallback = self
+ .copy_and_paste
+ .contents_request
+ .as_mut()
+ .and_then(|req| req.uri_fallback_text.take())
+ .unwrap_or_default();
+ self.finish_contents_request(ClipboardContents::Text(fallback));
+ }
+
+ fn finish_contents_text_failure(&mut self) {
+ if self
+ .copy_and_paste
+ .contents_request
+ .as_ref()
+ .is_some_and(|req| req.uri_fallback_text.is_some())
+ {
+ self.finish_contents_with_uri_fallback();
+ } else {
+ self.finish_contents_request(ClipboardContents::Text(String::new()));
+ }
+ }
+
+ fn complete_contents_payload(&mut self, kind: ContentsKind, bytes: &[u8]) {
+ let contents = decode_contents(kind, bytes);
+ if kind == ContentsKind::UriList {
+ if let ClipboardContents::Text(fallback) = contents {
+ let text_target = {
+ let Some(req) = self.copy_and_paste.contents_request.as_mut() else {
+ return;
+ };
+ req.uri_fallback_text = Some(fallback);
+ if req.utf8_text_available {
+ Some((self.conn().atom_utf8_string, ContentsKind::Utf8Text))
+ } else if req.latin1_text_available {
+ Some((xcb::x::ATOM_STRING, ContentsKind::Latin1Text))
+ } else {
+ None
+ }
+ };
+ if let Some((target, kind)) = text_target {
+ self.convert_contents_target(target, kind);
+ } else {
+ self.finish_contents_with_uri_fallback();
+ }
+ return;
+ }
+ }
+ self.finish_contents_request(contents);
+ }
+
+ /// Handle a SelectionNotify belonging to the typed read, if there is
+ /// one in flight and this event is for it. Returns false to let the
+ /// legacy text path have the event.
+ fn try_handle_contents_notify(
+ &mut self,
+ selection: &xcb::x::SelectionNotifyEvent,
+ ) -> anyhow::Result<bool> {
+ let conn = self.conn();
+ let refused = selection.property() == xcb::x::ATOM_NONE;
+ if !refused && selection.property() == conn.atom_xsel_contents {
+ let matches_active = self
+ .copy_and_paste
+ .contents_request
+ .as_ref()
+ .is_some_and(|req| {
+ self.selection_atom_to_clipboard(selection.selection()) == Some(req.clipboard)
+ && successful_contents_notify_matches(
+ req.last_target,
+ selection.target(),
+ selection.property(),
+ conn.atom_xsel_contents,
+ )
+ });
+ if !matches_active {
+ // A completed request can leave a SelectionNotify queued even
+ // after its promise was superseded. Never let the event advance
+ // a different request or fall through to the legacy text path.
+ conn.send_request_no_reply(&xcb::x::DeleteProperty {
+ window: selection.requestor(),
+ property: selection.property(),
+ })?;
+ return Ok(true);
+ }
+ }
+ let Some(req) = self.copy_and_paste.contents_request.as_ref() else {
+ return Ok(false);
+ };
+ if self.selection_atom_to_clipboard(selection.selection()) != Some(req.clipboard) {
+ return Ok(false);
+ }
+ // Success notifies name our dedicated property. A refusal names no
+ // property at all, so match it against the target we asked for —
+ // the legacy path never asks for TARGETS/uri-list/png, and a text
+ // target refusal is matched here first only while a typed request
+ // is actually outstanding.
+ if !refused && selection.property() != conn.atom_xsel_contents {
+ return Ok(false);
+ }
+ if selection.target() != req.last_target {
+ return Ok(false);
+ }
+ let stage = req.stage;
+ let canceled = req.canceled;
+
+ if refused {
+ if canceled {
+ self.retire_contents_request(None);
+ return Ok(true);
+ }
+ match stage {
+ ContentsStage::AwaitingTargets => {
+ // Owner doesn't answer TARGETS; assume plain text.
+ self.convert_contents_target(conn.atom_utf8_string, ContentsKind::Utf8Text);
+ }
+ ContentsStage::AwaitingData { kind } => match kind {
+ ContentsKind::UriList | ContentsKind::Png => {
+ let text_target =
+ self.copy_and_paste
+ .contents_request
+ .as_ref()
+ .and_then(|req| {
+ if !req.targets_known || req.utf8_text_available {
+ Some((conn.atom_utf8_string, ContentsKind::Utf8Text))
+ } else if req.latin1_text_available {
+ Some((xcb::x::ATOM_STRING, ContentsKind::Latin1Text))
+ } else {
+ None
+ }
+ });
+ if let Some((target, kind)) = text_target {
+ self.convert_contents_target(target, kind);
+ } else {
+ self.finish_contents_text_failure();
+ }
+ }
+ ContentsKind::Utf8Text => {
+ let try_latin1 = self
+ .copy_and_paste
+ .contents_request
+ .as_ref()
+ .is_some_and(|req| !req.targets_known || req.latin1_text_available);
+ if try_latin1 {
+ self.convert_contents_target(
+ xcb::x::ATOM_STRING,
+ ContentsKind::Latin1Text,
+ );
+ } else {
+ self.finish_contents_text_failure();
+ }
+ }
+ ContentsKind::Latin1Text => {
+ self.finish_contents_text_failure();
+ }
+ },
+ }
+ return Ok(true);
+ }
+
+ let prop = conn
+ .send_and_wait_request(&xcb::x::GetProperty {
+ // Deleting is both our cleanup and, for an INCR
+ // announcement, the signal that we are ready for chunks.
+ delete: true,
+ window: selection.requestor(),
+ property: selection.property(),
+ r#type: xcb::x::ATOM_NONE, // AnyPropertyType: INCR must be visible
+ long_offset: 0,
+ long_length: u32::max_value(),
+ })
+ .context("GetProperty for typed clipboard read")?;
+
+ if canceled {
+ if superseded_contents_reply(stage, prop.r#type() == conn.atom_incr)
+ == SupersededContentsReply::DrainIncr
+ {
+ let ContentsStage::AwaitingData { kind } = stage else {
+ unreachable!()
+ };
+ // The owner is already in the INCR handshake. Drain its
+ // chunks before reusing the property for the replacement.
+ self.copy_and_paste.incr_contents = Some(IncrContents { kind, buf: vec![] });
+ } else {
+ self.retire_contents_request(None);
+ }
+ return Ok(true);
+ }
+
+ match stage {
+ ContentsStage::AwaitingTargets => {
+ let targets: Vec<Atom> = prop.value::<Atom>().to_vec();
+ let has_utf8 = targets.contains(&conn.atom_utf8_string);
+ let has_latin1 = targets.contains(&xcb::x::ATOM_STRING);
+ if let Some(req) = self.copy_and_paste.contents_request.as_mut() {
+ req.targets_known = true;
+ req.utf8_text_available = has_utf8;
+ req.latin1_text_available = has_latin1;
+ }
+ match preferred_clipboard_representation(
+ targets.contains(&conn.atom_texturilist),
+ has_utf8 || has_latin1,
+ targets.contains(&conn.atom_image_png),
+ ) {
+ ClipboardRepresentation::UriList => {
+ self.convert_contents_target(conn.atom_texturilist, ContentsKind::UriList)
+ }
+ ClipboardRepresentation::Text if has_utf8 => {
+ self.convert_contents_target(conn.atom_utf8_string, ContentsKind::Utf8Text)
+ }
+ ClipboardRepresentation::Text if has_latin1 => {
+ self.convert_contents_target(xcb::x::ATOM_STRING, ContentsKind::Latin1Text)
+ }
+ ClipboardRepresentation::Text => {
+ self.convert_contents_target(conn.atom_utf8_string, ContentsKind::Utf8Text)
+ }
+ ClipboardRepresentation::Png => {
+ self.convert_contents_target(conn.atom_image_png, ContentsKind::Png)
+ }
+ }
+ }
+ ContentsStage::AwaitingData { kind } => {
+ if prop.r#type() == conn.atom_incr {
+ // INCR transfer: the real data arrives in chunks via
+ // PropertyNotify on our property; the delete above told
+ // the owner to start.
+ self.copy_and_paste.incr_contents = Some(IncrContents { kind, buf: vec![] });
+ } else {
+ self.complete_contents_payload(kind, prop.value());
+ }
+ }
+ }
+ Ok(true)
+ }
+
+ /// An INCR chunk (or its terminator) landed on our property.
+ fn continue_incr_contents(&mut self) -> anyhow::Result<()> {
+ let conn = self.conn();
+ if self.copy_and_paste.incr_contents.is_none() {
+ return Ok(());
+ }
+ let prop = conn
+ .send_and_wait_request(&xcb::x::GetProperty {
+ // Deleting each chunk asks the owner for the next one.
+ delete: true,
+ window: self.window_id,
+ property: conn.atom_xsel_contents,
+ r#type: xcb::x::ATOM_NONE,
+ long_offset: 0,
+ long_length: u32::max_value(),
+ })
+ .context("GetProperty for INCR chunk")?;
+ let value = prop.value::<u8>();
+ let Some(incr) = self.copy_and_paste.incr_contents.as_mut() else {
+ return Ok(());
+ };
+ if value.is_empty() {
+ let done = self.copy_and_paste.incr_contents.take().unwrap();
+ let canceled = self
+ .copy_and_paste
+ .contents_request
+ .as_ref()
+ .is_some_and(|req| req.canceled);
+ if canceled {
+ self.retire_contents_request(None);
+ } else {
+ self.complete_contents_payload(done.kind, &done.buf);
+ }
+ } else {
+ incr.buf.extend_from_slice(value);
+ }
+ Ok(())
+ }
+
fn selection_notify(&mut self, selection: &xcb::x::SelectionNotifyEvent) -> anyhow::Result<()> {
let conn = self.conn();
let window_id = self.window_id;
@@ -1299,6 +1767,10 @@ impl XWindowInner {
selection.selection={selection_name} selection.target={target_name}"
);
+ if self.try_handle_contents_notify(selection)? {
+ return Ok(());
+ }
+
if let Some(clipboard) = self.selection_atom_to_clipboard(selection.selection()) {
if selection.property() == xcb::x::ATOM_NONE {
if selection.target() == conn.atom_utf8_string {
@@ -1342,10 +1814,6 @@ impl XWindowInner {
}) {
Ok(prop) => {
if let Some(mut promise) = self.copy_and_paste.request_mut(clipboard).take() {
- fn latin1_to_string(s: &[u8]) -> String {
- s.iter().map(|&c| c as char).collect()
- }
-
let data = if selection.target() == xcb::x::ATOM_STRING {
latin1_to_string(prop.value())
} else {
@@ -1954,13 +2422,7 @@ impl XWindowInner {
}
}
- fn net_wm_moveresize(
- &mut self,
- x_root: u32,
- y_root: u32,
- direction: u32,
- button: u32,
- ) -> bool {
+ fn net_wm_moveresize(&mut self, x_root: u32, y_root: u32, direction: u32, button: u32) -> bool {
let source_indication = 1;
let conn = self.conn();
@@ -2408,6 +2870,20 @@ impl WindowOps for XWindow {
future
}
+ /// Initiate typed transfer from the clipboard: negotiate TARGETS so
+ /// file lists and images survive as such.
+ fn get_clipboard_contents(&self, clipboard: Clipboard) -> Future<ClipboardContents> {
+ let window_id = self.0;
+ let mut promise = Promise::new();
+ let future = promise.get_future().unwrap();
+ let mut promise = Some(promise);
+ XConnection::with_window_inner(window_id, move |inner| {
+ inner.request_clipboard_contents(clipboard, promise.take().unwrap());
+ Ok(())
+ });
+ future
+ }
+
/// Set some text in the clipboard
fn set_clipboard(&self, clipboard: Clipboard, text: String) {
let window_id = self.0;
@@ -2426,28 +2902,7 @@ impl WindowOps for XWindow {
}
}
-fn parse_texturi_list(url_list: &[u8]) -> Vec<PathBuf> {
- String::from_utf8_lossy(url_list)
- .lines()
- .filter_map(|line| {
- if line.starts_with('#') || line.trim().is_empty() {
- // text/uri-list: Any lines beginning with the '#' character
- // are comment lines and are ignored during processing
- return None;
- }
- let url = Url::parse(line)
- .map_err(|err| {
- log::error!("Error parsing dropped file line {line} as url: {err:#}");
- })
- .ok()?;
- url.to_file_path()
- .map_err(|_| {
- log::error!("Error converting url {url:?} from line {line} to pathbuf");
- })
- .ok()
- })
- .collect()
-}
+use crate::os::uri_list::parse_texturi_list;
fn parse_xmozurl_list(url_list: &str) -> Vec<Url> {
url_list
@@ -2509,6 +2964,47 @@ impl NetWmStateAction {
#[cfg(test)]
mod tests {
use super::*;
+ use xcb::XidNew;
+
+ #[test]
+ fn stale_typed_selection_notification_does_not_match_replacement_request() {
+ let targets = unsafe { Atom::new(10) };
+ let utf8 = unsafe { Atom::new(11) };
+ let property = unsafe { Atom::new(12) };
+
+ assert!(!successful_contents_notify_matches(
+ utf8, targets, property, property
+ ));
+ assert!(successful_contents_notify_matches(
+ utf8, utf8, property, property
+ ));
+ }
+
+ #[test]
+ fn superseded_x11_incr_is_drained_before_the_property_is_reused() {
+ assert_eq!(
+ superseded_contents_reply(
+ ContentsStage::AwaitingData {
+ kind: ContentsKind::Png,
+ },
+ true,
+ ),
+ SupersededContentsReply::DrainIncr
+ );
+ assert_eq!(
+ superseded_contents_reply(
+ ContentsStage::AwaitingData {
+ kind: ContentsKind::Png,
+ },
+ false,
+ ),
+ SupersededContentsReply::Retire
+ );
+ assert_eq!(
+ superseded_contents_reply(ContentsStage::AwaitingTargets, false),
+ SupersededContentsReply::Retire
+ );
+ }
#[test]
fn integrated_buttons_never_request_a_native_title_bar() {
diff --git a/window/src/os/x_and_wayland.rs b/window/src/os/x_and_wayland.rs
index 795368c4..6d477dbe 100644
--- a/window/src/os/x_and_wayland.rs
+++ b/window/src/os/x_and_wayland.rs
@@ -9,8 +9,8 @@ use crate::os::x11::connection::XConnection;
use crate::os::x11::window::XWindow;
use crate::screen::Screens;
use crate::{
- Appearance, Clipboard, FolderPickerOptions, MouseCursor, Rect, RequestedWindowGeometry,
- ResizeIncrement, ScreenPoint, WindowEvent, WindowOps,
+ Appearance, Clipboard, ClipboardContents, FolderPickerOptions, MouseCursor, Rect,
+ RequestedWindowGeometry, ResizeIncrement, ScreenPoint, WindowEvent, WindowOps,
};
use async_trait::async_trait;
use config::ConfigHandle;
@@ -418,6 +418,13 @@ impl WindowOps for Window {
Self::Wayland(w) => w.get_clipboard(clipboard),
}
}
+ fn get_clipboard_contents(&self, clipboard: Clipboard) -> Future<ClipboardContents> {
+ match self {
+ Self::X11(x) => x.get_clipboard_contents(clipboard),
+ #[cfg(feature = "wayland")]
+ Self::Wayland(w) => w.get_clipboard_contents(clipboard),
+ }
+ }
fn set_clipboard(&self, clipboard: Clipboard, text: String) {
match self {
Self::X11(x) => x.set_clipboard(clipboard, text),