Support PRIMARY selection in Wayland sessions (#64192)

## Why

The TUI disabled PRIMARY whenever `WAYLAND_DISPLAY` was set, so it
couldn't publish selected text to PRIMARY or paste from it with a middle
click in Wayland sessions.

## What changed

Probe Wayland PRIMARY support in the background and use the result for
selection copying and middle-click paste. If the compositor lacks the
Wayland data-control protocol, allow XWayland fallback only when the
Wayland and X11 sockets have matching listener credentials.

## Testing

Add a unit test covering native Wayland support, the same-session
XWayland fallback, remote X11 displays, and unsuccessful probes.

GitOrigin-RevId: 9b5c1536762383c0fe770dd86d58a49a1f3633a8
This commit is contained in:
Eric Traut
2026-11-26 17:55:06 +00:00
committed by copyberry
parent 58961aa3a2
commit 1f9549e265
18 changed files with 132 additions and 27 deletions
+2
View File
@@ -5465,6 +5465,7 @@ dependencies = [
"itertools 0.14.0",
"lazy_static",
"libc",
"nix 0.31.3",
"objc2",
"objc2-app-kit",
"objc2-foundation",
@@ -5514,6 +5515,7 @@ dependencies = [
"windows-sys 0.61.2",
"winsplit",
"wiremock",
"wl-clipboard-rs",
"zbus",
]
+1
View File
@@ -599,6 +599,7 @@ wildmatch = "2.6.1"
winapi-util = "0.1.11"
windows-sys = "0.61.2"
winreg = "0.55.0"
wl-clipboard-rs = "0.9.3"
# Keep the zip 2.x feature set. In zip 9, `bzip2-rs` selects the bzip2-sys
# backend we already build; the default selects libbz2-rs-sys instead.
zip = { version = "9.0.0", default-features = false, features = [
+2
View File
@@ -155,6 +155,8 @@ objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std"
objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "NSArray", "NSData", "NSDateFormatter", "NSEnumerator", "NSFormatter", "NSLocale", "NSString"] }
[target.'cfg(target_os = "linux")'.dependencies]
nix = { version = "0.31.3", features = ["socket"] }
wl-clipboard-rs = { workspace = true }
# Keep the same executor features as the credential store, which also uses zbus.
zbus = "4.4.0"
+1
View File
@@ -922,6 +922,7 @@ impl App {
}
_ => self.sidebar_press = None,
}
self.transcript_view.primary_selection = tui.primary_selection_available();
self.transcript_view.bidi_layout = tui.terminal.bidi_layout;
self.transcript_view.agent_links = self
.side_retention_enabled(tui)
+1 -1
View File
@@ -44,7 +44,7 @@ impl App {
selection.view.copy_on_select = self.local_settings.copy_on_select();
selection.view.copy_on_select_clear_selection =
self.local_settings.tui.copy_on_select_clear_selection;
selection.view.primary_selection = self.right_click_paste_environment.primary;
selection.view.primary_selection = tui.primary_selection_available();
selection.handle_event(event, tui.terminal.previous_buffer())
};
let Some(action) = action else {
+1 -2
View File
@@ -184,7 +184,7 @@ impl App {
) -> bool {
let selection_copy = crate::tui::SelectionCopy::on_select(
self.local_settings.copy_on_select(),
self.right_click_paste_environment.primary,
tui.primary_selection_available(),
// Editable selections remain visible so the next input can replace them.
/*clear_selection*/
false,
@@ -217,7 +217,6 @@ impl App {
let transcript_width = chat_widget.history_wrap_width(width);
let view = &mut self.transcript_view;
view.mouse_scroll_speed = self.local_settings.tui.mouse_scroll_speed.unwrap_or(1.0);
view.primary_selection = self.right_click_paste_environment.primary;
view.copy_on_select = self.local_settings.copy_on_select();
view.copy_on_select_clear_selection =
self.local_settings.tui.copy_on_select_clear_selection;
+2 -4
View File
@@ -1,4 +1,4 @@
//! Clipboard text paste from keyboard shortcuts, right-click, or X11 middle-click PRIMARY.
//! Clipboard text paste from keyboard shortcuts, right-click, or middle-click PRIMARY.
//! The policy also reports why a configured mode is unavailable in this terminal.
//! Existing selection handlers run first. Only a draw may deliver a read, so real input
//! invalidates pending paste before completion and is never replaced by clipboard text.
@@ -23,7 +23,6 @@ pub(super) struct PendingPaste {
}
pub(crate) struct PasteEnvironment {
pub(super) primary: bool,
pub(super) platform_default: bool,
pub(super) ssh: bool,
pub(super) wsl: bool,
@@ -33,7 +32,6 @@ pub(crate) struct PasteEnvironment {
impl PasteEnvironment {
pub(crate) fn detect() -> Self {
Self {
primary: crate::clipboard_copy::primary::available(),
platform_default: cfg!(any(target_os = "windows", target_os = "linux")),
ssh: crate::terminal_capabilities::is_ssh_session(),
wsl: crate::terminal_capabilities::is_wsl_session(),
@@ -100,7 +98,7 @@ impl App {
self.local_settings.transcript_mode,
)
}
PasteSource::Primary => self.right_click_paste_environment.primary,
PasteSource::Primary => tui.primary_selection_available(),
};
if (shortcut.is_none() && !tui.is_owned_screen())
|| self.overlay.is_some()
@@ -41,7 +41,6 @@ fn policy_preserves_explicit_modes_and_terminal_ownership() {
(true, false, true, Application, on, Ok(true)),
] {
let env = PasteEnvironment {
primary: false,
platform_default,
ssh,
wsl,
@@ -59,7 +58,6 @@ fn policy_preserves_explicit_modes_and_terminal_ownership() {
}
let env = PasteEnvironment {
primary: false,
platform_default: true,
ssh: false,
wsl: false,
-1
View File
@@ -120,7 +120,6 @@ pub(crate) async fn make_test_app() -> Box<App> {
app_server_backend_id: None,
pending_right_click_paste: None,
right_click_paste_environment: super::right_click_paste::PasteEnvironment {
primary: false,
platform_default: true,
ssh: false,
wsl: false,
-2
View File
@@ -9157,7 +9157,6 @@ async fn make_test_app() -> Box<App> {
reconnect: Default::default(),
pending_right_click_paste: None,
right_click_paste_environment: super::right_click_paste::PasteEnvironment {
primary: false,
platform_default: true,
ssh: false,
wsl: false,
@@ -9307,7 +9306,6 @@ pub(super) async fn make_test_app_with_channels() -> (
reconnect: Default::default(),
pending_right_click_paste: None,
right_click_paste_environment: super::right_click_paste::PasteEnvironment {
primary: false,
platform_default: true,
ssh: false,
wsl: false,
+2 -5
View File
@@ -1,13 +1,10 @@
//! Local X11 PRIMARY selection. Never forward PRIMARY over SSH or tmux, or
//! accidentally target a Wayland compositor or WSL host clipboard.
//! Local Linux PRIMARY selection. Never forward PRIMARY over SSH, tmux, or WSL.
#[cfg(target_os = "linux")]
use super::ClipboardLease;
use super::CopyOutcome;
use std::time::Instant;
pub(crate) use crate::terminal_capabilities::primary_selection_available as available;
#[cfg(target_os = "linux")]
pub(super) fn copy(
text: &str,
@@ -20,7 +17,7 @@ pub(super) fn copy(
.set()
.clipboard(arboard::LinuxClipboardKind::Primary)
.text(text)
.map_err(|err| format!("X11 primary selection: {err}"))?;
.map_err(|err| format!("primary selection: {err}"))?;
Ok(CopyOutcome::Copied(Some(ClipboardLease::native_linux(
clipboard,
))))
-1
View File
@@ -67,7 +67,6 @@ impl Overlay {
overlay.view.bidi_layout = bidi_layout;
overlay.view.copy_on_select = copy_on_select;
overlay.view.mouse_scroll_speed = mouse_scroll_speed;
overlay.view.primary_selection = crate::clipboard_copy::primary::available();
Self::Transcript(overlay)
}
@@ -225,6 +225,7 @@ impl TranscriptOverlay {
mouse.column = self.content_area.x;
mouse.row = self.content_area.bottom().saturating_sub(1);
}
self.view.primary_selection = tui.primary_selection_available();
self.view.handle_mouse(mouse, &self.cells)
}
TuiEvent::Paste(text) => {
+8 -8
View File
@@ -286,14 +286,14 @@ pub(crate) fn paste_owner() -> PasteOwner {
}
}
pub(crate) fn primary_selection_available() -> bool {
cfg!(target_os = "linux")
&& std::env::var_os("DISPLAY").is_some()
&& std::env::var_os("WAYLAND_DISPLAY").is_none()
&& !is_ssh_session()
&& !is_tmux_session()
&& !is_wsl_session()
&& !matches!(paste_owner(), PasteOwner::Terminal(_))
#[cfg(target_os = "linux")]
mod primary;
#[cfg(target_os = "linux")]
pub(crate) use primary::detect_primary_selection;
#[cfg(not(target_os = "linux"))]
pub(crate) fn detect_primary_selection() -> std::sync::Arc<std::sync::atomic::AtomicBool> {
Default::default()
}
pub(crate) fn title_encoding() -> crate::terminal_title::TitleEncoding {
@@ -0,0 +1,83 @@
//! Detect local Linux PRIMARY without blocking input or consuming an inherited Wayland socket.
use super::PasteOwner;
use nix::sys::socket::getsockopt;
use nix::sys::socket::sockopt::PeerCredentials;
use std::os::linux::net::SocketAddrExt;
use std::os::unix::net::SocketAddr;
use std::os::unix::net::UnixStream;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use wl_clipboard_rs::utils::PrimarySelectionCheckError;
use wl_clipboard_rs::utils::is_primary_selection_supported;
pub(crate) fn detect_primary_selection() -> Arc<AtomicBool> {
if super::is_ssh_session()
|| super::is_tmux_session()
|| super::is_wsl_session()
|| matches!(super::paste_owner(), PasteOwner::Terminal(_))
|| std::env::var_os("WAYLAND_SOCKET").is_some()
{
return Default::default();
}
let display = std::env::var_os("DISPLAY");
let Some(wayland) = std::env::var_os("WAYLAND_DISPLAY") else {
return Arc::new(AtomicBool::new(display.is_some()));
};
let available = Arc::new(AtomicBool::new(false));
let result = Arc::clone(&available);
let _ = std::thread::Builder::new().spawn(move || {
let supported = wayland_primary_available(
is_primary_selection_supported(),
display.as_deref(),
|number| same_listener(PathBuf::from(wayland), number).unwrap_or(false),
);
result.store(supported, Ordering::Relaxed);
});
available
}
fn wayland_primary_available(
probe: Result<bool, PrimarySelectionCheckError>,
display: Option<&std::ffi::OsStr>,
same_session: impl FnOnce(u16) -> bool,
) -> bool {
// Arboard may retry X11 on a later connection failure. Reject remote addresses.
let number = display.and_then(|display| {
let (host, suffix) = display.to_str()?.rsplit_once(':')?;
if !matches!(host, "" | "unix/") {
return None;
}
suffix.split('.').next()?.parse().ok()
});
match probe {
Ok(supported) => supported && (display.is_none() || number.is_some()),
Err(PrimarySelectionCheckError::MissingProtocol) => number.is_some_and(same_session),
Err(_) => false,
}
}
// Mutter opens both listeners and passes the X11 sockets to XWayland. Linux
// reports the listener's credentials even after the file descriptor is passed.
fn same_listener(mut wayland: PathBuf, number: u16) -> Option<bool> {
if !wayland.is_absolute() {
wayland = PathBuf::from(std::env::var_os("XDG_RUNTIME_DIR")?).join(wayland);
}
let compositor = UnixStream::connect(wayland).ok()?;
let path = format!("/tmp/.X11-unix/X{number}");
// Match x11rb's preference for the abstract socket over the filesystem socket.
let address = SocketAddr::from_abstract_name(path.as_bytes()).ok()?;
let x11 = UnixStream::connect_addr(&address)
.or_else(|_| UnixStream::connect(path))
.ok()?;
let owner = getsockopt(&compositor, PeerCredentials).ok()?;
// A peer outside our PID namespace can have an invisible (zero) PID.
Some(owner.pid() > 0 && owner == getsockopt(&x11, PeerCredentials).ok()?)
}
#[cfg(test)]
#[path = "primary_tests.rs"]
mod tests;
@@ -0,0 +1,21 @@
#![cfg(test)]
use super::wayland_primary_available;
use std::ffi::OsStr;
use wl_clipboard_rs::utils::PrimarySelectionCheckError::MissingProtocol;
use wl_clipboard_rs::utils::PrimarySelectionCheckError::NoSeats;
#[test]
fn missing_data_control_requires_the_compositors_own_x11_listener() {
let available = |probe, display: Option<&str>| {
wayland_primary_available(probe, display.map(OsStr::new), |number| number == 0)
};
assert!(available(Ok(true), None));
assert!(available(Err(MissingProtocol), Some(":0.0")));
assert!(!available(Err(MissingProtocol), Some(":99")));
assert!(!available(Err(MissingProtocol), None));
assert!(!available(Err(MissingProtocol), Some("localhost:0")));
assert!(!available(Ok(true), Some("localhost:0")));
assert!(!available(Ok(false), Some(":0")));
assert!(!available(Err(NoSeats), Some(":0")));
}
+6
View File
@@ -754,6 +754,7 @@ pub struct Tui {
owned_screen: bool,
pub(crate) mouse_capture: MouseCapture,
// Copies and native ownership survive closing an overlay or startup picker.
primary_selection: Arc<AtomicBool>,
pub(crate) clipboard: crate::clipboard_copy::worker::ClipboardWorker,
// Keeps unmanaged process stderr writes out of the inline viewport.
_stderr_guard: terminal_stderr::TerminalStderrGuard,
@@ -830,6 +831,7 @@ impl Tui {
alt_screen_enabled: true,
owned_screen: false,
mouse_capture: MouseCapture::Inherit,
primary_selection: terminal_capabilities::detect_primary_selection(),
clipboard: Default::default(),
_stderr_guard: stderr_guard,
}
@@ -905,6 +907,10 @@ impl Tui {
crate::transcript_mode::TranscriptMode::resolve(self.owned_screen, self.alt_screen_enabled)
}
pub(crate) fn primary_selection_available(&self) -> bool {
self.primary_selection.load(Ordering::Relaxed)
}
/// Retain the mouse capture policy across temporary editor, suspend and panic handoffs.
/// Actual terminal capture is tracked by AlternateScreen so partial writes remain cleanable.
pub(crate) fn set_mouse_capture(&mut self, mouse_capture: MouseCapture) -> Result<()> {
+1 -1
View File
@@ -44,7 +44,7 @@ impl SelectionCopy {
}
impl Tui {
/// Copy to CLIPBOARD and/or publish X11 PRIMARY under one selection policy.
/// Copy to CLIPBOARD and/or publish PRIMARY under one selection policy.
pub(crate) fn copy_selection(
&mut self,
text: &str,