Skip to content

armgit / muxin

Public Imported from GitHub
0

All your machines, one app. For you and your AI agents: agent sessions, desktops, files, logs and GitHub across your Macs, Linux and Windows machines, with an MCP server.

Shared clipboard: an old copy no longer bounces back over a new one

Adib Hanna6905f90e37ae
diff --git a/agent/src/clipboard.rs b/agent/src/clipboard.rs
index 6f210e0..c337fa0 100644
--- a/agent/src/clipboard.rs
+++ b/agent/src/clipboard.rs
@@ -2,12 +2,13 @@
//! on stdin set it (text); frames on stdout say it changed (text copied here).
//! Linux: owns and watches the X clipboard (needs a desktop session). macOS:
//! pbcopy and pbpaste. A password manager's copies aren't sent (each system
-//! has its own way of marking them).
+//! has its own way of marking them). A copy made here that hasn't been sent
+//! yet wins over text arriving from the app at the same time: the app's text
+//! isn't pasted over it, and the copy goes out instead.
use std::io::{self, Write};
use std::sync::mpsc;
use std::thread;
-#[cfg(unix)]
use std::time::Duration;
/// A clipboard's text (the frame kind on the link and on stdin/stdout).
@@ -59,72 +60,155 @@ pub fn run() -> i32 {
}
}
-#[cfg(target_os = "macos")]
-mod mac {
- use super::*;
- use std::process::{Command, Stdio};
+/// A clipboard that numbers its changes: a Mac's pasteboard, Windows'.
+#[cfg(any(target_os = "macos", windows, test))]
+pub trait Board {
+ /// The number of its last change, and whether a password manager marked
+ /// what's there private.
+ fn state(&mut self) -> (i64, bool);
+ /// Its text, if it has some (Windows: not a password manager's).
+ fn text(&mut self) -> Option<String>;
+ /// Puts text there; whether that worked.
+ fn set(&mut self, text: &str) -> bool;
+}
- fn paste() -> Option<String> {
- let out = Command::new("pbpaste").stdin(Stdio::null()).stderr(Stdio::null()).output().ok()?;
- out.status.success().then(|| String::from_utf8_lossy(&out.stdout).into_owned())
+/// Shares a clipboard that numbers its changes: every `every` (or as soon as
+/// the app sends something) it looks for a copy made here, and pastes what
+/// the app sent unless a newer copy was made here or it's there already.
+#[cfg(any(target_os = "macos", windows, test))]
+pub fn share(board: &mut impl Board, rx: mpsc::Receiver<String>, every: Duration, changed: impl Fn(&str) -> bool) {
+ let mut sharing = Sharing::new(board);
+ loop {
+ let from_app = match rx.recv_timeout(every) {
+ Ok(text) => Some(text),
+ Err(mpsc::RecvTimeoutError::Timeout) => None,
+ Err(mpsc::RecvTimeoutError::Disconnected) => return,
+ };
+ if let Some(text) = sharing.turn(board, from_app)
+ && !changed(&text)
+ {
+ return;
+ }
}
+}
+
+/// What `share` knows about the clipboard.
+#[cfg(any(target_os = "macos", windows, test))]
+struct Sharing {
+ /// The number of the last change looked at.
+ seen: i64,
+ /// What's there as of that change, when it's text (not a password manager's).
+ holds: Option<String>,
+ /// The text last sent to the app or pasted from it (so nothing echoes back).
+ last: String,
+}
- fn copy(text: &str) {
- if let Ok(mut child) = Command::new("pbcopy").stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::null()).spawn() {
- if let Some(mut stdin) = child.stdin.take() {
- let _ = stdin.write_all(text.as_bytes());
+#[cfg(any(target_os = "macos", windows, test))]
+impl Sharing {
+ fn new(board: &mut impl Board) -> Sharing {
+ // What's there now is old news; only copies from here on count.
+ let (seen, private) = board.state();
+ Sharing { seen, holds: if private { None } else { board.text() }, last: String::new() }
+ }
+
+ /// A look at the clipboard, with the text the app sent meanwhile: that's
+ /// pasted unless a newer copy was made here. Returns a copy made here to
+ /// send.
+ fn turn(&mut self, board: &mut impl Board, from_app: Option<String>) -> Option<String> {
+ let (newer, copied) = self.look(board);
+ if let Some(text) = from_app
+ && !newer
+ {
+ self.paste(board, text);
+ }
+ copied
+ }
+
+ /// Looks for a copy made here since the last look: whether there's one
+ /// (newer than anything the app sends now), and its text when that's to
+ /// be sent. A password manager's copy, one that isn't text, and the same
+ /// text again aren't sent.
+ fn look(&mut self, board: &mut impl Board) -> (bool, Option<String>) {
+ let (count, private) = board.state();
+ if count == self.seen {
+ return (false, None);
+ }
+ let text = if private { None } else { board.text() };
+ // Copied again while reading: that copy is looked at next time.
+ if board.state().0 != count {
+ return (true, None);
+ }
+ self.seen = count;
+ self.holds = text.clone();
+ match text {
+ Some(t) if t == self.last => (false, None),
+ Some(t) if !t.is_empty() && t.len() <= MAX => {
+ self.last = t.clone();
+ (true, Some(t))
}
- let _ = child.wait();
+ _ => (true, None),
}
}
+ /// Pastes text from the app, unless it's there already.
+ fn paste(&mut self, board: &mut impl Board, text: String) {
+ if self.holds.as_ref() != Some(&text) && board.set(&text) {
+ self.seen = board.state().0;
+ self.holds = Some(text.clone());
+ }
+ self.last = text;
+ }
+}
+
+#[cfg(target_os = "macos")]
+mod mac {
+ use super::*;
+ use std::process::{Command, Stdio};
+
unsafe extern "C" {
fn muxen_pasteboard(concealed: *mut i32) -> i64;
}
- /// The pasteboard's change count, and whether a password manager marked
- /// what's there private (see mac_screen.m).
- fn pasteboard() -> (i64, bool) {
- let mut concealed = 0;
- let count = unsafe { muxen_pasteboard(&mut concealed) };
- (count, concealed != 0)
+ /// pbcopy or pbpaste, reading and writing UTF-8. Without a locale (as
+ /// under launchd, for direct connections) they'd take it for Mac Roman.
+ pub(super) fn pb(program: &str) -> Command {
+ let mut cmd = Command::new(program);
+ cmd.env_remove("LC_ALL").env("LC_CTYPE", "UTF-8").stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
+ cmd
}
- pub fn run(rx: mpsc::Receiver<String>, changed: impl Fn(&str) -> bool) {
- // What's there now is old news; only copies from here on count.
- let mut seen = pasteboard().0;
- loop {
- match rx.recv_timeout(Duration::from_millis(600)) {
- Ok(text) => {
- copy(&text);
- seen = pasteboard().0;
- }
- Err(mpsc::RecvTimeoutError::Disconnected) => return,
- Err(mpsc::RecvTimeoutError::Timeout) => {}
- }
- let (count, private) = pasteboard();
- if count == seen {
- continue;
- }
- // A password manager's copy stays on this Mac.
- let text = if private { None } else { paste() };
- // Copied again while reading: that copy is looked at next time.
- if pasteboard().0 != count {
- continue;
- }
- seen = count;
- if let Some(now) = text.filter(|t| !t.is_empty() && t.len() <= MAX)
- && !changed(&now)
- {
- return;
- }
+ struct Pasteboard;
+
+ impl Board for Pasteboard {
+ /// The change count, and whether a password manager marked what's
+ /// there private (see mac_screen.m).
+ fn state(&mut self) -> (i64, bool) {
+ let mut concealed = 0;
+ let count = unsafe { muxen_pasteboard(&mut concealed) };
+ (count, concealed != 0)
+ }
+
+ fn text(&mut self) -> Option<String> {
+ let out = pb("pbpaste").stdout(Stdio::piped()).output().ok()?;
+ out.status.success().then(|| String::from_utf8_lossy(&out.stdout).into_owned())
+ }
+
+ fn set(&mut self, text: &str) -> bool {
+ let Ok(mut child) = pb("pbcopy").stdin(Stdio::piped()).spawn() else { return false };
+ let wrote = child.stdin.take().is_some_and(|mut stdin| stdin.write_all(text.as_bytes()).is_ok());
+ child.wait().is_ok_and(|s| s.success()) && wrote
}
}
+
+ pub fn run(rx: mpsc::Receiver<String>, changed: impl Fn(&str) -> bool) {
+ share(&mut Pasteboard, rx, Duration::from_millis(600), changed);
+ }
}
#[cfg(target_os = "linux")]
mod x11 {
use super::*;
+ use std::time::Instant;
use x11rb::connection::Connection;
use x11rb::protocol::Event;
use x11rb::protocol::xfixes::{self, ConnectionExt as _};
@@ -151,6 +235,11 @@ mod x11 {
// text either way (so nothing echoes back).
let mut owned: Option<Vec<u8>> = None;
let mut last = String::new();
+ // The clipboard's text when that's known: ours, or read from the
+ // program that copied it.
+ let mut holds: Option<String> = None;
+ // Since when a copy made here is being read (its targets, then its text).
+ let mut reading: Option<Instant> = None;
// When the copy being asked about was made (answers about an older one are dropped).
let mut asked_at = x11rb::CURRENT_TIME;
let ask = |target: u32, at: u32| {
@@ -161,21 +250,32 @@ mod x11 {
while let Some(event) = conn.poll_for_event().map_err(|e| e.to_string())? {
match event {
// Something else took the clipboard: ask what it offers
- // first, since a password manager marks its copies.
- Event::XfixesSelectionNotify(e) if e.owner != win && e.owner != NONE => {
- asked_at = e.selection_timestamp;
- ask(targets, asked_at);
+ // first, since a password manager marks its copies. (No
+ // owner: the program that had it quit; it's empty.)
+ Event::XfixesSelectionNotify(e) if e.owner != win => {
+ holds = None;
+ reading = None;
+ if e.owner != NONE {
+ asked_at = e.selection_timestamp;
+ reading = Some(Instant::now());
+ ask(targets, asked_at);
+ }
}
- Event::SelectionNotify(e) if e.requestor == win && (e.time == asked_at || e.time == x11rb::CURRENT_TIME) => {
+ Event::SelectionNotify(e) if reading.is_some() && e.requestor == win && (e.time == asked_at || e.time == x11rb::CURRENT_TIME) => {
if e.property == NONE {
// It doesn't list what it offers: just the text.
if e.target == targets {
ask(utf8, asked_at);
+ } else {
+ reading = None;
}
continue;
}
- let Ok(cookie) = conn.get_property(true, win, prop, AtomEnum::ANY, 0, (MAX / 4) as u32 + 1) else { continue };
- let Ok(reply) = cookie.reply() else { continue };
+ let reply = conn.get_property(true, win, prop, AtomEnum::ANY, 0, (MAX / 4) as u32 + 1).ok().and_then(|cookie| cookie.reply().ok());
+ let Some(reply) = reply else {
+ reading = None;
+ continue;
+ };
if e.target == targets {
let offered: Vec<u32> = reply.value32().map(|atoms| atoms.collect()).unwrap_or_default();
ask(if offered.contains(&hint) { hint } else { utf8 }, asked_at);
@@ -183,15 +283,19 @@ mod x11 {
}
if e.target == hint {
// A password manager's copy stays on this machine.
- if !super::secret(&reply.value) {
+ if super::secret(&reply.value) {
+ reading = None;
+ } else {
ask(utf8, asked_at);
}
continue;
}
+ reading = None;
if reply.type_ == incr || reply.value.len() > MAX {
continue;
}
let text = String::from_utf8_lossy(&reply.value).into_owned();
+ holds = Some(text.clone());
if text != last && !text.is_empty() {
if !changed(&text) {
return Ok(());
@@ -230,11 +334,18 @@ mod x11 {
}
loop {
match rx.try_recv() {
+ // A copy made here that's still being read is newer: it
+ // goes out instead (a program that doesn't answer gets a second).
+ Ok(_) if reading.is_some_and(|at| at.elapsed() < Duration::from_secs(1)) => {}
Ok(text) => {
- owned = Some(text.clone().into_bytes());
+ reading = None;
+ if holds.as_ref() != Some(&text) {
+ owned = Some(text.clone().into_bytes());
+ holds = Some(text.clone());
+ let _ = conn.set_selection_owner(win, clipboard, x11rb::CURRENT_TIME);
+ let _ = conn.flush();
+ }
last = text;
- let _ = conn.set_selection_owner(win, clipboard, x11rb::CURRENT_TIME);
- let _ = conn.flush();
}
Err(mpsc::TryRecvError::Empty) => break,
// The app let go.
@@ -248,6 +359,8 @@ mod x11 {
#[cfg(test)]
mod tests {
+ use super::*;
+
#[test]
fn a_password_managers_copy_says_secret() {
assert!(super::secret(b"secret"));
@@ -255,4 +368,151 @@ mod tests {
assert!(!super::secret(b""));
assert!(!super::secret(b"public"));
}
+
+ /// A clipboard in memory that numbers its changes, like a Mac's.
+ #[derive(Default)]
+ struct Fake {
+ count: i64,
+ text: Option<String>,
+ private: bool,
+ /// Texts pasted from the app.
+ pasted: Vec<String>,
+ }
+
+ impl Fake {
+ /// A copy made on this machine.
+ fn copy(&mut self, text: Option<&str>, private: bool) {
+ self.count += 1;
+ self.text = text.map(str::to_string);
+ self.private = private;
+ }
+ }
+
+ impl Board for Fake {
+ fn state(&mut self) -> (i64, bool) {
+ (self.count, self.private)
+ }
+ fn text(&mut self) -> Option<String> {
+ self.text.clone()
+ }
+ fn set(&mut self, text: &str) -> bool {
+ self.pasted.push(text.to_string());
+ self.copy(Some(text), false);
+ true
+ }
+ }
+
+ fn turn(sharing: &mut Sharing, board: &mut Fake, from_app: &str) -> Option<String> {
+ sharing.turn(board, Some(from_app.to_string()))
+ }
+
+ #[test]
+ fn a_newer_copy_here_wins_over_the_apps_text() {
+ let mut board = Fake::default();
+ board.copy(Some("old news"), false);
+ let mut sharing = Sharing::new(&mut board);
+ // Nothing copied here since the last look: the app's text is pasted,
+ // and doesn't come back.
+ assert_eq!(turn(&mut sharing, &mut board, "from the app"), None);
+ assert_eq!(board.text.as_deref(), Some("from the app"));
+ assert_eq!(sharing.turn(&mut board, None), None);
+ // Copied here after that, before the app's next text arrived: the
+ // copy goes out and stays here.
+ board.copy(Some("copied here"), false);
+ assert_eq!(turn(&mut sharing, &mut board, "from the app, later"), Some("copied here".into()));
+ assert_eq!(board.text.as_deref(), Some("copied here"));
+ // The app's text after that is pasted as usual.
+ assert_eq!(turn(&mut sharing, &mut board, "newest"), None);
+ assert_eq!(board.text.as_deref(), Some("newest"));
+ assert_eq!(board.pasted, ["from the app", "newest"]);
+ }
+
+ #[test]
+ fn a_copy_that_stays_here_isnt_pasted_over_either() {
+ for (text, private) in [(Some("hunter2"), true), (None, false)] {
+ let mut board = Fake::default();
+ let mut sharing = Sharing::new(&mut board);
+ // A password manager's copy, or an image: not sent, not replaced.
+ board.copy(text, private);
+ assert_eq!(turn(&mut sharing, &mut board, "from the app"), None);
+ assert_eq!((board.text.as_deref(), board.pasted.len()), (text, 0));
+ // Once it's been looked at, the app's next text replaces it.
+ assert_eq!(turn(&mut sharing, &mut board, "from the app"), None);
+ assert_eq!(board.text.as_deref(), Some("from the app"));
+ }
+ }
+
+ #[test]
+ fn the_same_text_copied_again_doesnt_count() {
+ let mut board = Fake::default();
+ let mut sharing = Sharing::new(&mut board);
+ turn(&mut sharing, &mut board, "from the app");
+ // Copied again here (or a clipboard manager took it over): it isn't
+ // sent back, and doesn't keep the app's next text out.
+ board.copy(Some("from the app"), false);
+ assert_eq!(turn(&mut sharing, &mut board, "next"), None);
+ assert_eq!(board.text.as_deref(), Some("next"));
+ }
+
+ #[test]
+ fn text_thats_there_already_isnt_pasted_again() {
+ let mut board = Fake::default();
+ board.copy(Some("same"), false);
+ let mut sharing = Sharing::new(&mut board);
+ let count = board.count;
+ assert_eq!(turn(&mut sharing, &mut board, "same"), None);
+ assert_eq!((board.count, board.pasted.len()), (count, 0));
+ // And copying it here afterwards isn't news for the app.
+ board.copy(Some("same"), false);
+ assert_eq!(sharing.turn(&mut board, None), None);
+ }
+
+ #[test]
+ fn a_copy_made_while_reading_is_looked_at_next_time() {
+ /// Copies "second" here while the first copy's text is being read.
+ struct Racing(Fake);
+ impl Board for Racing {
+ fn state(&mut self) -> (i64, bool) {
+ self.0.state()
+ }
+ fn text(&mut self) -> Option<String> {
+ let first = self.0.text();
+ if first.as_deref() == Some("first") {
+ self.0.copy(Some("second"), false);
+ }
+ first
+ }
+ fn set(&mut self, text: &str) -> bool {
+ self.0.set(text)
+ }
+ }
+ let mut board = Racing(Fake::default());
+ let mut sharing = Sharing::new(&mut board);
+ board.0.copy(Some("first"), false);
+ // Something newer is here, so the app's text waits; the next look sends it.
+ assert_eq!(sharing.turn(&mut board, Some("from the app".into())), None);
+ assert_eq!(sharing.turn(&mut board, None), Some("second".into()));
+ assert!(board.0.pasted.is_empty());
+ }
+
+ #[test]
+ fn sharing_pastes_what_the_app_sends_until_it_lets_go() {
+ let mut board = Fake::default();
+ let (to_agent, from_app) = mpsc::channel();
+ for text in ["one", "two"] {
+ to_agent.send(text.to_string()).unwrap();
+ }
+ drop(to_agent);
+ share(&mut board, from_app, Duration::from_secs(5), |_| panic!("nothing was copied here"));
+ assert_eq!(board.pasted, ["one", "two"]);
+ }
+
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn pbcopy_and_pbpaste_use_utf8() {
+ let cmd = mac::pb("pbcopy");
+ let envs: Vec<_> = cmd.get_envs().map(|(k, v)| (k.to_string_lossy().into_owned(), v.map(|v| v.to_string_lossy().into_owned()))).collect();
+ assert!(envs.contains(&("LC_CTYPE".into(), Some("UTF-8".into()))));
+ assert!(envs.contains(&("LC_ALL".into(), None)));
+ }
}
diff --git a/agent/src/win_screen.rs b/agent/src/win_screen.rs
index fbf29c7..96f66b0 100644
--- a/agent/src/win_screen.rs
+++ b/agent/src/win_screen.rs
@@ -429,33 +429,29 @@ fn set_clipboard_text(text: &str) -> bool {
}
}
+/// Windows' clipboard, for `muxen-agent clip`: Windows numbers its changes.
+struct Clipboard;
+
+impl super::clipboard::Board for Clipboard {
+ /// (A password manager's copy shows as no text: see `clipboard_text`.)
+ fn state(&mut self) -> (i64, bool) {
+ (unsafe { windows_sys::Win32::System::DataExchange::GetClipboardSequenceNumber() } as i64, false)
+ }
+
+ fn text(&mut self) -> Option<String> {
+ clipboard_text()
+ }
+
+ fn set(&mut self, text: &str) -> bool {
+ set_clipboard_text(text)
+ }
+}
+
/// `muxen-agent clip` on Windows: what's copied here goes out; what the app
-/// sends is put on the clipboard. Windows numbers clipboard changes, so a
-/// look every few hundred milliseconds sees each one.
+/// sends is put on the clipboard (see clipboard.rs). A look every few hundred
+/// milliseconds sees each change.
pub fn clip(rx: std::sync::mpsc::Receiver<String>, changed: impl Fn(&str) -> bool) {
- use windows_sys::Win32::System::DataExchange::GetClipboardSequenceNumber;
- let mut seen = unsafe { GetClipboardSequenceNumber() };
- loop {
- match rx.recv_timeout(Duration::from_millis(300)) {
- Ok(text) => {
- let text: String = text.chars().take(super::clipboard::MAX).collect();
- if set_clipboard_text(&text) {
- seen = unsafe { GetClipboardSequenceNumber() };
- }
- }
- Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => return,
- Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
- }
- let now = unsafe { GetClipboardSequenceNumber() };
- if now != seen {
- seen = now;
- if let Some(text) = clipboard_text().filter(|t| !t.is_empty() && t.len() <= super::clipboard::MAX)
- && !changed(&text)
- {
- return;
- }
- }
- }
+ super::clipboard::share(&mut Clipboard, rx, Duration::from_millis(300), changed);
}
// --- Running in the signed-in user's desktop session ------------------------
diff --git a/src/fleet/clipboard.rs b/src/fleet/clipboard.rs
index 509b929..1cc1ec8 100644
--- a/src/fleet/clipboard.rs
+++ b/src/fleet/clipboard.rs
@@ -6,7 +6,7 @@
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock};
-use std::time::Duration;
+use std::time::{Duration, Instant};
use serde_json::json;
use tokio::sync::broadcast;
@@ -17,10 +17,12 @@ use super::link::{self, Link};
const CLIP: u8 = 40;
/// Bigger text isn't shared.
const MAX: usize = 256 * 1024;
+/// How long a replaced text coming back counts as an old copy (see `History`).
+const BOUNCE: Duration = Duration::from_secs(3);
struct Shared {
- /// The text last copied anywhere (so nothing echoes back).
- last: Mutex<String>,
+ /// The last copies (so nothing echoes or bounces back).
+ history: Mutex<History>,
/// What a program in a terminal here last put on the clipboard (see `keep_here`).
kept: Mutex<Option<String>>,
/// Machines sharing the clipboard: their link and channel.
@@ -31,7 +33,40 @@ struct Shared {
fn shared() -> &'static Shared {
static SHARED: OnceLock<Shared> = OnceLock::new();
- SHARED.get_or_init(|| Shared { last: Mutex::new(String::new()), kept: Mutex::new(None), peers: Mutex::new(HashMap::new()), incoming: broadcast::channel(16).0 })
+ SHARED.get_or_init(|| Shared { history: Mutex::new(History::default()), kept: Mutex::new(None), peers: Mutex::new(HashMap::new()), incoming: broadcast::channel(16).0 })
+}
+
+/// The text last copied anywhere, and the texts it replaced moments ago.
+#[derive(Default)]
+struct History {
+ last: String,
+ /// Each with where the copy that replaced it was made (None: this
+ /// computer) and when.
+ replaced: Vec<(String, Option<String>, Instant)>,
+}
+
+impl History {
+ /// Whether text copied `from` this computer (None) or a machine is a new
+ /// copy; it then becomes the last one. Not when it's the last one again,
+ /// nor when a copy made elsewhere replaced it moments ago: that's a
+ /// clipboard that hadn't caught up, offering its old text (#20: Wayland
+ /// doesn't let an unfocused window set or read the clipboard).
+ fn copied(&mut self, from: Option<&str>, text: &str, now: Instant) -> bool {
+ self.replaced.retain(|(_, _, at)| now.duration_since(*at) < BOUNCE);
+ if self.last == text || self.replaced.iter().any(|(old, by, _)| old == text && by.as_deref() != from) {
+ return false;
+ }
+ // It's the last one now: when it was replaced before no longer matters.
+ self.replaced.retain(|(old, _, _)| old != text);
+ let old = std::mem::replace(&mut self.last, text.to_string());
+ if !old.is_empty() {
+ if self.replaced.len() >= 8 {
+ self.replaced.remove(0);
+ }
+ self.replaced.push((old, from.map(str::to_string), now));
+ }
+ true
+ }
}
/// Text copied on a machine, to put on this computer's clipboard.
@@ -43,16 +78,9 @@ pub fn subscribe() -> broadcast::Receiver<String> {
/// Something new was copied on this computer: offer it to every machine.
#[cfg_attr(not(feature = "gui"), allow(dead_code))]
pub fn local_changed(text: &str) {
- if text.is_empty() || text.len() > MAX || kept(text) {
+ if text.is_empty() || text.len() > MAX || kept(text) || !shared().history.lock().unwrap().copied(None, text, Instant::now()) {
return;
}
- {
- let mut last = shared().last.lock().unwrap();
- if *last == text {
- return;
- }
- *last = text.to_string();
- }
for (link, channel) in shared().peers.lock().unwrap().values() {
link.send(*channel, CLIP, text.as_bytes());
}
@@ -78,16 +106,9 @@ fn kept(text: &str) -> bool {
/// Something new was copied on a machine: here, and the other machines.
fn remote_changed(from: &str, text: String) {
- if text.is_empty() || text.len() > MAX {
+ if text.is_empty() || text.len() > MAX || !shared().history.lock().unwrap().copied(Some(from), &text, Instant::now()) {
return;
}
- {
- let mut last = shared().last.lock().unwrap();
- if *last == text {
- return;
- }
- *last = text.clone();
- }
for (id, (link, channel)) in shared().peers.lock().unwrap().iter() {
if id != from {
link.send(*channel, CLIP, text.as_bytes());
@@ -157,4 +178,48 @@ mod tests {
keep_here("osc 52");
assert!(!kept("something else"));
}
+
+ #[test]
+ fn an_old_copy_coming_back_moments_later_isnt_shared() {
+ let t0 = Instant::now();
+ let at = |ms: u64| t0 + Duration::from_millis(ms);
+ let mut h = History::default();
+ assert!(h.copied(None, "old path", at(0)));
+ // Copied on the Mac; a second later this computer's clipboard, which
+ // didn't take the Mac's copy, still offers the old text (#20).
+ assert!(h.copied(Some("mac"), "from the mac", at(10_000)));
+ assert!(!h.copied(None, "old path", at(11_000)));
+ // So does another machine that hadn't caught up.
+ assert!(!h.copied(Some("linux"), "old path", at(12_000)));
+ assert_eq!(h.last, "from the mac");
+ // Long after, copying it again is a new copy.
+ assert!(h.copied(None, "old path", at(13_500)));
+ assert_eq!(h.last, "old path");
+ }
+
+ #[test]
+ fn copying_back_and_forth_on_one_machine_isnt_a_bounce() {
+ let t0 = Instant::now();
+ let mut h = History::default();
+ assert!(h.copied(Some("mac"), "a", t0));
+ assert!(h.copied(Some("mac"), "b", t0));
+ assert!(h.copied(Some("mac"), "a", t0));
+ assert!(h.copied(None, "c", t0));
+ assert!(h.copied(None, "a", t0));
+ // The last text again is an echo, from anywhere.
+ assert!(!h.copied(None, "a", t0));
+ assert!(!h.copied(Some("mac"), "a", t0));
+ }
+
+ #[test]
+ fn replaced_texts_are_kept_briefly() {
+ let t0 = Instant::now();
+ let mut h = History::default();
+ for i in 0..100 {
+ assert!(h.copied(None, &i.to_string(), t0));
+ }
+ assert!(h.replaced.len() <= 8);
+ h.copied(Some("mac"), "later", t0 + BOUNCE);
+ assert_eq!(h.replaced.len(), 1);
+ }
}
diff --git a/src/ui/hosted.rs b/src/ui/hosted.rs
index 46b8b3a..eae5ee8 100644
--- a/src/ui/hosted.rs
+++ b/src/ui/hosted.rs
@@ -52,6 +52,8 @@ impl Root {
.tooltip("Its Windows account's password (Muxin made it; it's kept in your Keychain)")
.on_click(cx.listener(move |this, _, _, cx| match this.engine.vm_password(&mid) {
Some(p) => {
+ // It stays on this computer: the shared clipboard doesn't pass it on.
+ crate::fleet::clipboard::keep_here(&p);
cx.write_to_clipboard(gpui::ClipboardItem::new_string(p));
this.notify_user("Copied its password".to_string(), false, cx);
}
diff --git a/src/ui/root.rs b/src/ui/root.rs
index 2a6b05a..e501996 100644
--- a/src/ui/root.rs
+++ b/src/ui/root.rs
@@ -286,6 +286,18 @@ pub struct PulseSample {
pub online: usize,
}
+/// This computer's clipboard as the shared clipboard last saw it.
+#[derive(Default)]
+struct ClipboardSeen {
+ /// Its change number (see pasteboard_state; 0 on Linux).
+ count: i64,
+ /// Its text.
+ text: String,
+ /// Text from the machines written there last, until a copy made here
+ /// goes out. Wayland takes it a moment later, which isn't a new copy.
+ written: Option<String>,
+}
+
pub struct Root {
pub(super) engine: Arc<Engine>,
pub(super) snapshot: Arc<Snapshot>,
@@ -389,7 +401,7 @@ pub struct Root {
window_active: bool,
pub(super) ws_ui: WorkspaceUi,
/// This computer's clipboard as last seen (see watch_clipboard).
- clipboard_seen: (i64, String),
+ clipboard_seen: ClipboardSeen,
_tasks: Vec<Task<()>>,
pub(super) _subscriptions: Vec<Subscription>,
}
@@ -442,11 +454,7 @@ impl Root {
loop {
match copied_there.recv().await {
Ok(text) => {
- let alive = this.update(cx, |this, cx| {
- cx.write_to_clipboard(gpui::ClipboardItem::new_string(text.clone()));
- this.clipboard_seen = (super::pasteboard_state().map(|s| s.0).unwrap_or(0), text);
- });
- if alive.is_err() {
+ if this.update(cx, |this, cx| this.paste_copied_there(text, cx)).is_err() {
break;
}
}
@@ -562,7 +570,7 @@ impl Root {
palette: None,
window_active: false,
ws_ui: WorkspaceUi::default(),
- clipboard_seen: (super::pasteboard_state().map(|s| s.0).unwrap_or(0), String::new()),
+ clipboard_seen: ClipboardSeen { count: super::pasteboard_state().map(|s| s.0).unwrap_or(0), ..Default::default() },
_tasks: vec![updates, ticker, clipboard_out, clipboard_in],
_subscriptions: subscriptions,
};
@@ -1188,34 +1196,70 @@ impl Root {
}
/// Offers what was just copied on this computer to the machines sharing
- /// the clipboard (not a password manager's copies).
- fn watch_clipboard(&mut self, cx: &mut Context<Self>) {
+ /// the clipboard (not a password manager's copies). Whether something
+ /// new was copied here since the last look, text or not.
+ fn watch_clipboard(&mut self, cx: &mut Context<Self>) -> bool {
if self.engine.is_demo() || !self.engine.settings().share_clipboard {
- return;
+ return false;
+ }
+ // Wayland says what's on the clipboard only to the program with the
+ // keyboard: with no Muxin window focused, GPUI reads an old copy.
+ if cx.compositor_name() == "Wayland" && cx.active_window().is_none() {
+ return false;
}
// Without a change counter (Linux), the text is compared; a password
// manager's copies can't be told apart there (see pasteboard_state).
let state = super::pasteboard_state();
if let Some((count, private)) = state {
- if count == self.clipboard_seen.0 {
- return;
+ if count == self.clipboard_seen.count {
+ return false;
}
- self.clipboard_seen.0 = count;
+ // A copy made here: a write from the machines is counted as soon
+ // as it's made (see paste_copied_there).
+ self.clipboard_seen.count = count;
+ self.clipboard_seen.written = None;
if private {
- return;
+ return true;
}
}
- let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) else { return };
+ let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) else { return state.is_some() };
// Copied again while reading: that copy is looked at next time.
if let Some((count, _)) = state
&& super::pasteboard_state().map(|s| s.0) != Some(count)
{
+ return true;
+ }
+ let seen = &mut self.clipboard_seen;
+ if text == seen.text {
+ return false;
+ }
+ // What was written from the machines, set a moment later (Wayland).
+ if seen.written.as_ref() == Some(&text) {
+ seen.text = text;
+ seen.written = None;
+ return false;
+ }
+ crate::fleet::clipboard::local_changed(&text);
+ seen.text = text;
+ seen.written = None;
+ true
+ }
+
+ /// Puts text copied on a machine on this computer's clipboard: not when
+ /// a newer copy was made here (that one goes to the machines instead),
+ /// nor when it's there already. Then notes what the clipboard really
+ /// holds, which isn't always the text: Wayland ignores the write while no
+ /// Muxin window has focus, and the old text still there isn't a new copy
+ /// to offer the machines (#20).
+ fn paste_copied_there(&mut self, text: String, cx: &mut Context<Self>) {
+ if !self.engine.settings().share_clipboard || self.watch_clipboard(cx) {
return;
}
- if text != self.clipboard_seen.1 {
- crate::fleet::clipboard::local_changed(&text);
- self.clipboard_seen.1 = text;
+ let holds = |cx: &Context<Self>| cx.read_from_clipboard().and_then(|item| item.text());
+ if holds(cx).as_ref() != Some(&text) {
+ cx.write_to_clipboard(gpui::ClipboardItem::new_string(text.clone()));
}
+ self.clipboard_seen = ClipboardSeen { count: super::pasteboard_state().map(|s| s.0).unwrap_or(0), text: holds(cx).unwrap_or_default(), written: Some(text) };
}
/// Powers a cloud machine on or off.