use crate::store::History;
use crate::types::{Content, EntryId};
use crate::write::ClipboardWriter;
use serde::{Deserialize, Serialize};
use std::io::{BufRead, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::{UnixListener, UnixStream};
use tokio::sync::Mutex;
const IDLE_TIMEOUT: Duration = Duration::from_secs(300);
#[derive(Debug, thiserror::Error)]
pub enum IpcError {
#[error("$XDG_RUNTIME_DIR is not set; cannot determine the clipboard control socket path")]
NoRuntimeDir,
#[error("failed to bind clipboard control socket at {path}: {source}")]
Bind {
path: PathBuf,
#[source]
source: std::io::Error,
},
}
pub fn socket_path() -> Result<PathBuf, IpcError> {
let runtime_dir = std::env::var_os("XDG_RUNTIME_DIR").ok_or(IpcError::NoRuntimeDir)?;
Ok(PathBuf::from(runtime_dir).join("clipd.sock"))
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(tag = "cmd", rename_all = "kebab-case")]
pub enum Request {
Pin { id: String },
Unpin { id: String },
Remove { id: String },
SetClipboard { id: String },
SetClipboardText { text: String },
List,
Status,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct EntrySummary {
pub id: String,
pub pinned: bool,
pub copied_at: u64,
pub kind: &'static str,
pub preview: String,
pub size: usize,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct StatusInfo {
pub entries: usize,
pub total_bytes: u64,
pub can_save: bool,
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(untagged)]
pub enum Response {
Ok,
Err {
ok: bool,
error: String,
},
Entries {
ok: bool,
entries: Vec<EntrySummary>,
},
Status {
ok: bool,
status: StatusInfo,
},
}
fn to_json(response: &Response) -> String {
match response {
Response::Ok => r#"{"ok":true}"#.to_string(),
other => serde_json::to_string(other)
.unwrap_or_else(|_| r#"{"ok":false,"error":"internal serialization error"}"#.into()),
}
}
fn err(message: impl Into<String>) -> Response {
Response::Err {
ok: false,
error: message.into(),
}
}
pub fn handle_line<W: ClipboardWriter>(
history: &mut History,
can_save: bool,
writer: &W,
selection: &mut Option<W::Guard>,
line: &str,
) -> (String, bool) {
let request: Result<Request, _> = serde_json::from_str(line);
let (response, mutated) = match request {
Err(e) => (err(format!("malformed request: {e}")), false),
Ok(request) => dispatch(history, can_save, writer, selection, request),
};
(to_json(&response), mutated)
}
fn dispatch<W: ClipboardWriter>(
history: &mut History,
can_save: bool,
writer: &W,
selection: &mut Option<W::Guard>,
request: Request,
) -> (Response, bool) {
match request {
Request::Pin { id } => apply_pin(history, can_save, id, true),
Request::Unpin { id } => apply_pin(history, can_save, id, false),
Request::Remove { id } => remove(history, can_save, id),
Request::SetClipboard { id } => apply_set_clipboard(history, writer, selection, id),
Request::SetClipboardText { text } => apply_set_clipboard_text(writer, selection, text),
Request::List => (
Response::Entries {
ok: true,
entries: history.entries().iter().map(summarize).collect(),
},
false,
),
Request::Status => (
Response::Status {
ok: true,
status: StatusInfo {
entries: history.entries().len(),
total_bytes: history.total_bytes(),
can_save,
},
},
false,
),
}
}
fn find_content(history: &History, id: &str) -> Result<Content, Response> {
let entry_id = EntryId::from_raw(id);
history
.entries()
.iter()
.find(|e| e.id == entry_id)
.map(|e| e.content.clone())
.ok_or_else(|| err(format!("no clipboard entry with id {id}")))
}
fn apply_set_clipboard<W: ClipboardWriter>(
history: &History,
writer: &W,
selection: &mut Option<W::Guard>,
id: String,
) -> (Response, bool) {
match find_content(history, &id) {
Err(response) => (response, false),
Ok(content) => match writer.set_selection(content) {
Ok(guard) => {
*selection = Some(guard);
(Response::Ok, false)
}
Err(e) => (err(format!("failed to set the clipboard: {e}")), false),
},
}
}
fn apply_set_clipboard_text<W: ClipboardWriter>(
writer: &W,
selection: &mut Option<W::Guard>,
text: String,
) -> (Response, bool) {
match writer.set_selection(Content::Text(text)) {
Ok(guard) => {
*selection = Some(guard);
(Response::Ok, false)
}
Err(e) => (err(format!("failed to set the clipboard: {e}")), false),
}
}
fn apply_pin(history: &mut History, can_save: bool, id: String, pinned: bool) -> (Response, bool) {
if !can_save {
return (err(unsavable_message()), false);
}
let entry_id = EntryId::from_raw(id.clone());
if history.set_pinned(&entry_id, pinned) {
(Response::Ok, true)
} else {
(err(format!("no clipboard entry with id {id}")), false)
}
}
fn remove(history: &mut History, can_save: bool, id: String) -> (Response, bool) {
if !can_save {
return (err(unsavable_message()), false);
}
let entry_id = EntryId::from_raw(id.clone());
if history.remove(&entry_id) {
(Response::Ok, true)
} else {
(err(format!("no clipboard entry with id {id}")), false)
}
}
fn unsavable_message() -> String {
"clipboard history could not be parsed at startup and is not being saved; fix the file by \
hand and restart hyprforge-clipd before changing pin state"
.to_string()
}
fn summarize(entry: &crate::types::Entry) -> EntrySummary {
let kind = match entry.content {
crate::types::Content::Text(_) => "text",
crate::types::Content::Image { .. } => "image",
};
EntrySummary {
id: entry.id.as_str().to_string(),
pinned: entry.pinned,
copied_at: entry.copied_at,
kind,
preview: entry.content.preview(120),
size: entry.content.size(),
}
}
pub const CLIENT_TIMEOUT: Duration = Duration::from_millis(500);
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ClientError {
#[error("$XDG_RUNTIME_DIR is not set")]
NoRuntimeDir,
#[error("couldn't reach hyprforge-clipd: {0}")]
Unreachable(String),
#[error("hyprforge-clipd did not respond in time")]
Timeout,
#[error("hyprforge-clipd sent a response this client could not understand")]
Malformed,
#[error("{0}")]
Refused(String),
}
fn client_socket_error(error: std::io::Error) -> ClientError {
match error.kind() {
std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock => ClientError::Timeout,
_ => ClientError::Unreachable(error.to_string()),
}
}
fn request_at(path: &Path, request: &Request, timeout: Duration) -> Result<(), ClientError> {
let mut stream = std::os::unix::net::UnixStream::connect(path).map_err(client_socket_error)?;
stream.set_read_timeout(Some(timeout)).ok();
stream.set_write_timeout(Some(timeout)).ok();
let line = serde_json::to_string(request).expect("Request always serialises");
stream
.write_all(format!("{line}\n").as_bytes())
.map_err(client_socket_error)?;
let mut reader = std::io::BufReader::new(stream);
let mut response_line = String::new();
let read = reader.read_line(&mut response_line).map_err(client_socket_error)?;
if read == 0 {
return Err(ClientError::Unreachable(
"connection closed with no response".to_string(),
));
}
let value: serde_json::Value =
serde_json::from_str(response_line.trim()).map_err(|_| ClientError::Malformed)?;
match value.get("ok").and_then(|v| v.as_bool()) {
Some(true) => Ok(()),
Some(false) => {
let message = value
.get("error")
.and_then(|v| v.as_str())
.unwrap_or("request refused")
.to_string();
Err(ClientError::Refused(message))
}
None => Err(ClientError::Malformed),
}
}
pub fn set_pinned(id: &str, pinned: bool) -> Result<(), ClientError> {
let path = socket_path().map_err(|_| ClientError::NoRuntimeDir)?;
set_pinned_at(&path, id, pinned, CLIENT_TIMEOUT)
}
pub fn set_pinned_at(path: &Path, id: &str, pinned: bool, timeout: Duration) -> Result<(), ClientError> {
let request = if pinned {
Request::Pin { id: id.to_string() }
} else {
Request::Unpin { id: id.to_string() }
};
request_at(path, &request, timeout)
}
pub fn remove_entry(id: &str) -> Result<(), ClientError> {
let path = socket_path().map_err(|_| ClientError::NoRuntimeDir)?;
remove_entry_at(&path, id, CLIENT_TIMEOUT)
}
pub fn remove_entry_at(path: &Path, id: &str, timeout: Duration) -> Result<(), ClientError> {
request_at(path, &Request::Remove { id: id.to_string() }, timeout)
}
pub fn set_clipboard(id: &str) -> Result<(), ClientError> {
let path = socket_path().map_err(|_| ClientError::NoRuntimeDir)?;
set_clipboard_at(&path, id, CLIENT_TIMEOUT)
}
pub fn set_clipboard_at(path: &Path, id: &str, timeout: Duration) -> Result<(), ClientError> {
request_at(path, &Request::SetClipboard { id: id.to_string() }, timeout)
}
pub fn set_clipboard_text(text: &str) -> Result<(), ClientError> {
let path = socket_path().map_err(|_| ClientError::NoRuntimeDir)?;
set_clipboard_text_at(&path, text, CLIENT_TIMEOUT)
}
pub fn set_clipboard_text_at(path: &Path, text: &str, timeout: Duration) -> Result<(), ClientError> {
request_at(path, &Request::SetClipboardText { text: text.to_string() }, timeout)
}
pub struct Shared<W: ClipboardWriter> {
pub history: Mutex<History>,
pub can_save: bool,
pub writer: W,
pub selection: Mutex<Option<W::Guard>>,
}
pub async fn run<W: ClipboardWriter + 'static>(shared: Arc<Shared<W>>) -> Result<(), IpcError>
where
W::Guard: 'static,
{
run_at(&socket_path()?, shared).await
}
pub async fn run_at<W: ClipboardWriter + 'static>(
path: &Path,
shared: Arc<Shared<W>>,
) -> Result<(), IpcError>
where
W::Guard: 'static,
{
struct SocketGuard(PathBuf);
impl Drop for SocketGuard {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
let _ = std::fs::remove_file(path);
let listener = UnixListener::bind(path).map_err(|source| IpcError::Bind {
path: path.to_path_buf(),
source,
})?;
let _guard = SocketGuard(path.to_path_buf());
tracing::info!(path = %path.display(), "listening for clipboard control connections");
loop {
match listener.accept().await {
Ok((stream, _addr)) => {
let shared = Arc::clone(&shared);
tokio::spawn(async move {
handle_connection(stream, shared).await;
});
}
Err(e) => {
tracing::warn!(error = %e, "accept error on clipboard control socket");
}
}
}
}
async fn handle_connection<W: ClipboardWriter + 'static>(stream: UnixStream, shared: Arc<Shared<W>>)
where
W::Guard: 'static,
{
let (reader, mut writer) = stream.into_split();
let mut reader = BufReader::new(reader);
let mut line = String::new();
loop {
line.clear();
let read = tokio::time::timeout(IDLE_TIMEOUT, reader.read_line(&mut line)).await;
let n = match read {
Ok(Ok(n)) => n,
Ok(Err(_)) => return, Err(_) => {
tracing::debug!("clipboard control connection idle too long; closing");
return;
}
};
if n == 0 {
return; }
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
let response_json = process_line(&shared, trimmed).await;
if writer
.write_all(format!("{response_json}\n").as_bytes())
.await
.is_err()
{
return; }
}
}
async fn process_line<W: ClipboardWriter + 'static>(shared: &Arc<Shared<W>>, line: &str) -> String
where
W::Guard: 'static,
{
match serde_json::from_str::<Request>(line) {
Err(e) => to_json(&err(format!("malformed request: {e}"))),
Ok(Request::SetClipboard { id }) => {
to_json(&set_clipboard_on_daemon(Arc::clone(shared), id).await)
}
Ok(Request::SetClipboardText { text }) => {
to_json(&set_clipboard_text_on_daemon(Arc::clone(shared), text).await)
}
Ok(request) => {
let mut history = shared.history.lock().await;
let mut no_writer_needed = None; let (response, mutated) = dispatch(
&mut history,
shared.can_save,
&shared.writer,
&mut no_writer_needed,
request,
);
if mutated {
if let Err(e) = history.save() {
tracing::error!(error = %e, "failed to save clipboard history after a control request");
}
}
to_json(&response)
}
}
}
async fn set_clipboard_on_daemon<W: ClipboardWriter + 'static>(
shared: Arc<Shared<W>>,
id: String,
) -> Response
where
W::Guard: 'static,
{
let content = {
let history = shared.history.lock().await;
match find_content(&history, &id) {
Ok(content) => content,
Err(response) => return response,
}
};
let blocking_shared = Arc::clone(&shared);
let result = tokio::task::spawn_blocking(move || blocking_shared.writer.set_selection(content))
.await;
match result {
Ok(Ok(guard)) => {
let mut selection = shared.selection.lock().await;
*selection = Some(guard);
Response::Ok
}
Ok(Err(e)) => err(format!("failed to set the clipboard: {e}")),
Err(_join_error) => {
err("internal error setting the clipboard".to_string())
}
}
}
async fn set_clipboard_text_on_daemon<W: ClipboardWriter + 'static>(shared: Arc<Shared<W>>, text: String) -> Response
where
W::Guard: 'static,
{
let blocking_shared = Arc::clone(&shared);
let result =
tokio::task::spawn_blocking(move || blocking_shared.writer.set_selection(Content::Text(text))).await;
match result {
Ok(Ok(guard)) => {
let mut selection = shared.selection.lock().await;
*selection = Some(guard);
Response::Ok
}
Ok(Err(e)) => err(format!("failed to set the clipboard: {e}")),
Err(_join_error) => err("internal error setting the clipboard".to_string()),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::store::Recordable;
use crate::types::{Content, Sensitivity};
fn history_with_one_entry() -> (History, EntryId) {
let mut history = History::new();
history.record(
Recordable::new(Content::Text("hello".into()), Sensitivity::Recordable).unwrap(),
1,
);
let id = history.entries()[0].id.clone();
(history, id)
}
fn handle_line_test(history: &mut History, can_save: bool, line: &str) -> (String, bool) {
let writer = crate::write::mock::MockWriter::new();
let mut selection = None;
handle_line(history, can_save, &writer, &mut selection, line)
}
fn test_shared(history: History, can_save: bool) -> Arc<Shared<crate::write::mock::MockWriter>> {
Arc::new(Shared {
history: Mutex::new(history),
can_save,
writer: crate::write::mock::MockWriter::new(),
selection: Mutex::new(None),
})
}
#[test]
fn ok_response_is_exactly_ok_true_with_no_other_fields() {
let (mut history, id) = history_with_one_entry();
let line = format!(r#"{{"cmd":"pin","id":"{}"}}"#, id.as_str());
let (response, mutated) = handle_line_test(&mut history, true, &line);
assert_eq!(response, r#"{"ok":true}"#);
assert!(mutated);
}
#[test]
fn pin_happy_path_sets_pinned_and_reports_mutated() {
let (mut history, id) = history_with_one_entry();
let line = format!(r#"{{"cmd":"pin","id":"{}"}}"#, id.as_str());
let (_response, mutated) = handle_line_test(&mut history, true, &line);
assert!(mutated);
assert!(history.entries()[0].pinned);
}
#[test]
fn unpin_happy_path_clears_pinned() {
let (mut history, id) = history_with_one_entry();
history.set_pinned(&id, true);
let line = format!(r#"{{"cmd":"unpin","id":"{}"}}"#, id.as_str());
let (_response, mutated) = handle_line_test(&mut history, true, &line);
assert!(mutated);
assert!(!history.entries()[0].pinned);
}
#[test]
fn remove_happy_path_deletes_the_entry_and_reports_mutated() {
let (mut history, id) = history_with_one_entry();
let line = format!(r#"{{"cmd":"remove","id":"{}"}}"#, id.as_str());
let (_response, mutated) = handle_line_test(&mut history, true, &line);
assert!(mutated);
assert!(history.entries().is_empty());
}
#[test]
fn list_returns_every_entry_without_leaking_raw_content_fields() {
let (mut history, id) = history_with_one_entry();
let (response, mutated) = handle_line_test(&mut history, true, r#"{"cmd":"list"}"#);
assert!(!mutated, "reading history is never itself a mutation");
let value: serde_json::Value = serde_json::from_str(&response).unwrap();
assert_eq!(value["ok"], true);
let entries = value["entries"].as_array().unwrap();
assert_eq!(entries.len(), 1);
assert_eq!(entries[0]["id"], id.as_str());
assert_eq!(entries[0]["preview"], "hello");
assert_eq!(entries[0]["kind"], "text");
let keys: std::collections::BTreeSet<_> =
entries[0].as_object().unwrap().keys().cloned().collect();
assert_eq!(
keys,
["id", "pinned", "copied_at", "kind", "preview", "size"]
.into_iter()
.map(String::from)
.collect()
);
}
#[test]
fn status_reports_counts_and_whether_saving_is_possible() {
let (mut history, _id) = history_with_one_entry();
let (response, mutated) = handle_line_test(&mut history, false, r#"{"cmd":"status"}"#);
assert!(!mutated);
let value: serde_json::Value = serde_json::from_str(&response).unwrap();
assert_eq!(value["ok"], true);
assert_eq!(value["status"]["entries"], 1);
assert_eq!(value["status"]["can_save"], false);
}
#[test]
fn an_unknown_command_is_an_error_not_a_closed_connection() {
let mut history = History::new();
let (response, mutated) = handle_line_test(&mut history, true, r#"{"cmd":"frobnicate"}"#);
assert!(!mutated);
let value: serde_json::Value = serde_json::from_str(&response).unwrap();
assert_eq!(value["ok"], false);
assert!(value["error"].as_str().is_some());
}
#[test]
fn malformed_json_is_an_error_not_a_panic() {
let mut history = History::new();
let (response, mutated) = handle_line_test(&mut history, true, "not json at all { { {");
assert!(!mutated);
let value: serde_json::Value = serde_json::from_str(&response).unwrap();
assert_eq!(value["ok"], false);
}
#[test]
fn an_id_that_does_not_exist_is_an_error_and_never_mutates() {
let (mut history, _id) = history_with_one_entry();
let (response, mutated) =
handle_line_test(&mut history, true, r#"{"cmd":"pin","id":"not-a-real-id"}"#);
assert!(!mutated);
let value: serde_json::Value = serde_json::from_str(&response).unwrap();
assert_eq!(value["ok"], false);
assert!(value["error"].as_str().unwrap().contains("not-a-real-id"));
}
#[test]
fn pin_is_refused_without_mutating_when_the_history_could_not_be_saved() {
let (mut history, id) = history_with_one_entry();
let before = history.entries()[0].pinned;
let line = format!(r#"{{"cmd":"pin","id":"{}"}}"#, id.as_str());
let (response, mutated) = handle_line_test(&mut history, false, &line);
assert!(
!mutated,
"a request must not be applied in memory when it can never be saved"
);
assert_eq!(
history.entries()[0].pinned,
before,
"pin state must be untouched"
);
let value: serde_json::Value = serde_json::from_str(&response).unwrap();
assert_eq!(value["ok"], false);
}
#[test]
fn remove_is_refused_without_mutating_when_the_history_could_not_be_saved() {
let (mut history, id) = history_with_one_entry();
let line = format!(r#"{{"cmd":"remove","id":"{}"}}"#, id.as_str());
let (response, mutated) = handle_line_test(&mut history, false, &line);
assert!(!mutated);
assert_eq!(history.entries().len(), 1, "entry must still be present");
let value: serde_json::Value = serde_json::from_str(&response).unwrap();
assert_eq!(value["ok"], false);
}
#[test]
fn list_and_status_still_work_when_the_history_could_not_be_saved() {
let (mut history, _id) = history_with_one_entry();
let (response, _) = handle_line_test(&mut history, false, r#"{"cmd":"list"}"#);
let value: serde_json::Value = serde_json::from_str(&response).unwrap();
assert_eq!(value["ok"], true, "reading must not be blocked by can_save");
}
#[tokio::test]
async fn a_stale_socket_file_does_not_block_binding_and_a_real_request_round_trips() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("clipd-test.sock");
std::fs::write(&path, b"not a socket").unwrap();
let (history, id) = history_with_one_entry();
let shared = test_shared(history, true);
let serve_path = path.clone();
let serve_shared = Arc::clone(&shared);
let server = tokio::spawn(async move {
let _ = run_at(&serve_path, serve_shared).await;
});
tokio::time::sleep(Duration::from_millis(50)).await;
assert!(path.exists(), "socket file must exist once bound");
let stream = UnixStream::connect(&path).await.unwrap();
let (reader, mut writer) = stream.into_split();
let mut reader = BufReader::new(reader);
writer
.write_all(format!("{{\"cmd\":\"pin\",\"id\":\"{}\"}}\n", id.as_str()).as_bytes())
.await
.unwrap();
let mut line = String::new();
reader.read_line(&mut line).await.unwrap();
assert_eq!(line.trim(), r#"{"ok":true}"#);
{
let history = shared.history.lock().await;
assert!(
history.entries()[0].pinned,
"the shared History was mutated"
);
}
server.abort();
}
#[tokio::test]
async fn the_client_pins_an_entry_against_a_real_daemon() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("clipd-client-test.sock");
let (history, id) = history_with_one_entry();
let shared = test_shared(history, true);
let serve_path = path.clone();
let serve_shared = Arc::clone(&shared);
let server = tokio::spawn(async move {
let _ = run_at(&serve_path, serve_shared).await;
});
tokio::time::sleep(Duration::from_millis(50)).await;
let client_path = path.clone();
let client_id = id.as_str().to_string();
tokio::task::spawn_blocking(move || {
set_pinned_at(&client_path, &client_id, true, Duration::from_secs(2))
})
.await
.unwrap()
.expect("pin must succeed against a running daemon");
{
let history = shared.history.lock().await;
assert!(history.entries()[0].pinned, "the daemon's own History was mutated");
}
server.abort();
}
#[tokio::test]
async fn the_client_removes_an_entry_against_a_real_daemon() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("clipd-remove-test.sock");
let (history, id) = history_with_one_entry();
let shared = test_shared(history, true);
let serve_path = path.clone();
let serve_shared = Arc::clone(&shared);
let server = tokio::spawn(async move {
let _ = run_at(&serve_path, serve_shared).await;
});
tokio::time::sleep(Duration::from_millis(50)).await;
let client_path = path.clone();
let client_id = id.as_str().to_string();
tokio::task::spawn_blocking(move || remove_entry_at(&client_path, &client_id, Duration::from_secs(2)))
.await
.unwrap()
.expect("remove must succeed against a running daemon");
{
let history = shared.history.lock().await;
assert!(history.entries().is_empty(), "the entry must be gone from the daemon's own History");
}
server.abort();
}
#[test]
fn pinning_with_no_daemon_running_fails_fast_and_names_the_problem() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("nobody-home.sock");
let started = std::time::Instant::now();
let result = set_pinned_at(&path, "some-id", true, Duration::from_secs(2));
assert!(
started.elapsed() < Duration::from_secs(1),
"a refused connection must fail immediately, not wait out the timeout"
);
assert!(
matches!(result, Err(ClientError::Unreachable(_))),
"got {result:?}"
);
}
#[test]
fn a_daemon_that_never_answers_times_out_rather_than_hanging_forever() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("silent.sock");
let listener = std::os::unix::net::UnixListener::bind(&path).unwrap();
let accept_thread = std::thread::spawn(move || {
let _kept_alive = listener.accept();
std::thread::sleep(Duration::from_secs(5));
});
let started = std::time::Instant::now();
let result = set_pinned_at(&path, "some-id", true, Duration::from_millis(200));
assert!(
started.elapsed() < Duration::from_secs(2),
"must give up within roughly the requested timeout, not wait for the peer"
);
assert!(matches!(result, Err(ClientError::Timeout)), "got {result:?}");
drop(accept_thread); }
#[tokio::test]
async fn a_refusal_from_the_daemon_is_reported_not_swallowed() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("clipd-refuse-test.sock");
let (history, id) = history_with_one_entry();
let shared = test_shared(history, false);
let serve_path = path.clone();
let serve_shared = Arc::clone(&shared);
let server = tokio::spawn(async move {
let _ = run_at(&serve_path, serve_shared).await;
});
tokio::time::sleep(Duration::from_millis(50)).await;
let client_path = path.clone();
let client_id = id.as_str().to_string();
let result = tokio::task::spawn_blocking(move || {
set_pinned_at(&client_path, &client_id, true, Duration::from_secs(2))
})
.await
.unwrap();
match result {
Err(ClientError::Refused(message)) => {
assert!(message.contains("could not be parsed"), "got {message:?}");
}
other => panic!("expected a Refused error, got {other:?}"),
}
server.abort();
}
#[test]
fn set_clipboard_happy_path_hands_the_entrys_content_to_the_writer_and_keeps_the_guard() {
let (mut history, id) = history_with_one_entry();
let writer = crate::write::mock::MockWriter::new();
let mut selection = None;
let line = format!(r#"{{"cmd":"set-clipboard","id":"{}"}}"#, id.as_str());
let (response, mutated) = handle_line(&mut history, true, &writer, &mut selection, &line);
assert_eq!(response, r#"{"ok":true}"#);
assert!(
!mutated,
"set-clipboard never writes the index file, so it must never ask the caller to save"
);
assert_eq!(writer.calls(), vec![Content::Text("hello".into())]);
assert!(
selection.is_some(),
"the guard from set_selection must be kept, not dropped"
);
}
#[test]
fn setting_the_clipboard_a_second_time_replaces_rather_than_accumulates_the_guard() {
let mut history = History::new();
history.record(
Recordable::new(Content::Text("first".into()), Sensitivity::Recordable).unwrap(),
1,
);
history.record(
Recordable::new(Content::Text("second".into()), Sensitivity::Recordable).unwrap(),
2,
);
let first_id = history
.entries()
.iter()
.find(|e| e.content == Content::Text("first".into()))
.unwrap()
.id
.clone();
let second_id = history
.entries()
.iter()
.find(|e| e.content == Content::Text("second".into()))
.unwrap()
.id
.clone();
let writer = crate::write::mock::MockWriter::new();
let mut selection = None;
let line_one = format!(r#"{{"cmd":"set-clipboard","id":"{}"}}"#, first_id.as_str());
handle_line(&mut history, true, &writer, &mut selection, &line_one);
assert!(selection.is_some());
let line_two = format!(r#"{{"cmd":"set-clipboard","id":"{}"}}"#, second_id.as_str());
handle_line(&mut history, true, &writer, &mut selection, &line_two);
assert!(selection.is_some());
assert_eq!(
writer.calls(),
vec![Content::Text("first".into()), Content::Text("second".into())]
);
}
#[test]
fn set_clipboard_with_an_unknown_id_is_refused_and_never_touches_the_writer() {
let (mut history, _id) = history_with_one_entry();
let writer = crate::write::mock::MockWriter::new();
let mut selection = None;
let (response, mutated) = handle_line(
&mut history,
true,
&writer,
&mut selection,
r#"{"cmd":"set-clipboard","id":"not-a-real-id"}"#,
);
assert!(!mutated);
let value: serde_json::Value = serde_json::from_str(&response).unwrap();
assert_eq!(value["ok"], false);
assert!(value["error"].as_str().unwrap().contains("not-a-real-id"));
assert!(writer.calls().is_empty());
assert!(selection.is_none());
}
#[test]
fn set_clipboard_works_even_when_the_history_could_not_be_saved() {
let (mut history, id) = history_with_one_entry();
let writer = crate::write::mock::MockWriter::new();
let mut selection = None;
let line = format!(r#"{{"cmd":"set-clipboard","id":"{}"}}"#, id.as_str());
let (response, mutated) =
handle_line(&mut history, false, &writer, &mut selection, &line);
assert!(!mutated);
let value: serde_json::Value = serde_json::from_str(&response).unwrap();
assert_eq!(
value["ok"], true,
"a broken index file must not block putting an in-memory entry back on the clipboard"
);
assert!(selection.is_some());
}
#[test]
fn a_writer_failure_is_reported_and_leaves_no_guard() {
struct FailingWriter;
impl ClipboardWriter for FailingWriter {
type Guard = crate::write::mock::MockGuard;
fn set_selection(&self, _content: Content) -> anyhow::Result<Self::Guard> {
anyhow::bail!("no clipboard protocol available")
}
}
let (mut history, id) = history_with_one_entry();
let writer = FailingWriter;
let mut selection = None;
let line = format!(r#"{{"cmd":"set-clipboard","id":"{}"}}"#, id.as_str());
let (response, mutated) = handle_line(&mut history, true, &writer, &mut selection, &line);
assert!(!mutated);
let value: serde_json::Value = serde_json::from_str(&response).unwrap();
assert_eq!(value["ok"], false);
assert!(selection.is_none());
}
#[test]
fn set_clipboard_text_hands_the_text_to_the_writer_with_no_history_entry_needed() {
let mut history = History::new();
let writer = crate::write::mock::MockWriter::new();
let mut selection = None;
let (response, mutated) =
handle_line(&mut history, true, &writer, &mut selection, r#"{"cmd":"set-clipboard-text","text":"👋"}"#);
assert_eq!(response, r#"{"ok":true}"#);
assert!(!mutated, "set-clipboard-text never touches the index file either");
assert_eq!(writer.calls(), vec![Content::Text("👋".into())]);
assert!(selection.is_some(), "the guard must be kept, exactly like set-clipboard");
}
#[test]
fn setting_clipboard_text_a_second_time_replaces_rather_than_accumulates_the_guard() {
let mut history = History::new();
let writer = crate::write::mock::MockWriter::new();
let mut selection = None;
handle_line(&mut history, true, &writer, &mut selection, r#"{"cmd":"set-clipboard-text","text":"🔥"}"#);
assert!(selection.is_some());
handle_line(&mut history, true, &writer, &mut selection, r#"{"cmd":"set-clipboard-text","text":"❤️"}"#);
assert!(selection.is_some());
assert_eq!(writer.calls(), vec![Content::Text("🔥".into()), Content::Text("❤️".into())]);
}
#[test]
fn set_clipboard_text_works_even_when_the_history_could_not_be_saved() {
let mut history = History::new();
let writer = crate::write::mock::MockWriter::new();
let mut selection = None;
let (response, mutated) = handle_line(
&mut history,
false,
&writer,
&mut selection,
r#"{"cmd":"set-clipboard-text","text":"🎉"}"#,
);
assert!(!mutated);
let value: serde_json::Value = serde_json::from_str(&response).unwrap();
assert_eq!(value["ok"], true);
assert!(selection.is_some());
}
#[test]
fn a_writer_failure_setting_clipboard_text_is_reported_and_leaves_no_guard() {
struct FailingWriter;
impl ClipboardWriter for FailingWriter {
type Guard = crate::write::mock::MockGuard;
fn set_selection(&self, _content: Content) -> anyhow::Result<Self::Guard> {
anyhow::bail!("no clipboard protocol available")
}
}
let mut history = History::new();
let writer = FailingWriter;
let mut selection = None;
let (response, mutated) =
handle_line(&mut history, true, &writer, &mut selection, r#"{"cmd":"set-clipboard-text","text":"🎉"}"#);
assert!(!mutated);
let value: serde_json::Value = serde_json::from_str(&response).unwrap();
assert_eq!(value["ok"], false);
assert!(selection.is_none());
}
#[test]
fn the_watcher_seeing_its_own_set_clipboard_change_moves_the_entry_up_without_duplicating_or_looping(
) {
let mut history = History::new();
history.record(
Recordable::new(Content::Text("older".into()), Sensitivity::Recordable).unwrap(),
1,
);
history.record(
Recordable::new(Content::Text("chosen".into()), Sensitivity::Recordable).unwrap(),
2,
);
let writer = crate::write::mock::MockWriter::new();
let mut selection = None;
let older_id = history
.entries()
.iter()
.find(|e| e.content == Content::Text("older".into()))
.unwrap()
.id
.clone();
let line = format!(r#"{{"cmd":"set-clipboard","id":"{}"}}"#, older_id.as_str());
let (_response, mutated) = handle_line(&mut history, true, &writer, &mut selection, &line);
assert!(!mutated, "set-clipboard itself never touches History::save");
let recorded_again = history.record(
Recordable::new(Content::Text("older".into()), Sensitivity::Recordable).unwrap(),
3,
);
assert!(recorded_again, "the same content is still a valid record");
assert_eq!(
history.entries().len(),
2,
"recognised as the same entry, not appended as a duplicate"
);
assert_eq!(
history.entries()[0].content,
Content::Text("older".into()),
"choosing it moved it back to the top, same as any other re-copy"
);
assert_eq!(history.entries()[0].copied_at, 3);
assert_eq!(writer.calls(), vec![Content::Text("older".into())]);
}
#[tokio::test]
async fn the_client_sets_the_clipboard_against_a_real_daemon() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("clipd-set-clipboard-test.sock");
let (history, id) = history_with_one_entry();
let shared = test_shared(history, true);
let serve_path = path.clone();
let serve_shared = Arc::clone(&shared);
let server = tokio::spawn(async move {
let _ = run_at(&serve_path, serve_shared).await;
});
tokio::time::sleep(Duration::from_millis(50)).await;
let client_path = path.clone();
let client_id = id.as_str().to_string();
tokio::task::spawn_blocking(move || {
set_clipboard_at(&client_path, &client_id, Duration::from_secs(2))
})
.await
.unwrap()
.expect("set-clipboard must succeed against a running daemon");
{
let selection = shared.selection.lock().await;
assert!(
selection.is_some(),
"the daemon must have kept the guard from its own set_selection call"
);
}
server.abort();
}
#[tokio::test]
async fn the_client_sees_a_refusal_for_an_unknown_id_over_the_real_socket() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("clipd-set-clipboard-unknown-test.sock");
let (history, _id) = history_with_one_entry();
let shared = test_shared(history, true);
let serve_path = path.clone();
let serve_shared = Arc::clone(&shared);
let server = tokio::spawn(async move {
let _ = run_at(&serve_path, serve_shared).await;
});
tokio::time::sleep(Duration::from_millis(50)).await;
let client_path = path.clone();
let result = tokio::task::spawn_blocking(move || {
set_clipboard_at(&client_path, "not-a-real-id", Duration::from_secs(2))
})
.await
.unwrap();
assert!(matches!(result, Err(ClientError::Refused(_))), "got {result:?}");
server.abort();
}
}