use crate::types::{Content, Mime};
use std::sync::{Arc, Condvar, Mutex};
use std::time::Duration;
pub trait ClipboardWriter: Send + Sync {
type Guard: SelectionGuard;
fn set_selection(&self, content: Content) -> anyhow::Result<Self::Guard>;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SelectionOutcome {
Served,
Superseded,
TimedOut,
}
pub trait SelectionGuard: Send {
fn wait(&self, timeout: Duration) -> SelectionOutcome;
}
#[derive(Default)]
pub struct Waiter {
outcome: Mutex<Option<SelectionOutcome>>,
condvar: Condvar,
}
impl Waiter {
pub(crate) fn new() -> Arc<Self> {
Arc::new(Self::default())
}
pub(crate) fn signal(&self, outcome: SelectionOutcome) {
let mut guard = self.outcome.lock().unwrap_or_else(|e| e.into_inner());
if guard.is_none() {
*guard = Some(outcome);
self.condvar.notify_all();
}
}
}
impl SelectionGuard for Arc<Waiter> {
fn wait(&self, timeout: Duration) -> SelectionOutcome {
let guard = self.outcome.lock().unwrap_or_else(|e| e.into_inner());
let (guard, _timed_out) = self
.condvar
.wait_timeout_while(guard, timeout, |outcome| outcome.is_none())
.unwrap_or_else(|e| e.into_inner());
guard.unwrap_or(SelectionOutcome::TimedOut)
}
}
pub fn mimes_to_offer(content: &Content) -> Vec<Mime> {
match content {
Content::Text(_) => vec![
Mime::new("text/plain;charset=utf-8"),
Mime::new("text/plain"),
],
Content::Image { mime, .. } => vec![mime.clone()],
}
}
pub fn bytes_for(content: &Content, requested: &Mime) -> Option<Vec<u8>> {
match content {
Content::Text(text) => mimes_to_offer(content)
.contains(requested)
.then(|| text.clone().into_bytes()),
Content::Image { bytes, mime } => (requested == mime).then(|| bytes.clone()),
}
}
#[derive(Clone, PartialEq, Eq, Default)]
pub struct Offers {
entries: Vec<(Mime, Vec<u8>)>,
}
impl Offers {
pub fn new(entries: Vec<(Mime, Vec<u8>)>) -> Self {
Offers { entries }
}
pub fn of(content: &Content) -> Self {
Offers::new(
mimes_to_offer(content)
.into_iter()
.map(|mime| {
let bytes = bytes_for(content, &mime).unwrap_or_default();
(mime, bytes)
})
.collect(),
)
}
pub fn mimes(&self) -> impl Iterator<Item = &Mime> {
self.entries.iter().map(|(mime, _)| mime)
}
pub fn bytes_for(&self, requested: &Mime) -> Vec<u8> {
self.entries
.iter()
.find(|(mime, _)| mime == requested)
.map(|(_, bytes)| bytes.clone())
.unwrap_or_default()
}
}
impl std::fmt::Debug for Offers {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_list()
.entries(self.entries.iter().map(|(mime, bytes)| format!("{} ({} bytes)", mime.as_str(), bytes.len())))
.finish()
}
}
#[cfg(any(test, feature = "mock"))]
pub mod mock {
use super::*;
pub struct MockWriter {
calls: Mutex<Vec<Content>>,
outcome: SelectionOutcome,
}
impl Default for MockWriter {
fn default() -> Self {
MockWriter {
calls: Mutex::new(Vec::new()),
outcome: SelectionOutcome::Served,
}
}
}
impl MockWriter {
pub fn new() -> Self {
Self::default()
}
pub fn with_outcome(outcome: SelectionOutcome) -> Self {
MockWriter {
calls: Mutex::new(Vec::new()),
outcome,
}
}
pub fn calls(&self) -> Vec<Content> {
self.calls.lock().unwrap_or_else(|e| e.into_inner()).clone()
}
pub fn last_offered(&self) -> Option<Vec<Mime>> {
self.calls
.lock()
.unwrap_or_else(|e| e.into_inner())
.last()
.map(mimes_to_offer)
}
}
pub struct MockGuard(SelectionOutcome);
impl SelectionGuard for MockGuard {
fn wait(&self, _timeout: Duration) -> SelectionOutcome {
self.0
}
}
impl ClipboardWriter for MockWriter {
type Guard = MockGuard;
fn set_selection(&self, content: Content) -> anyhow::Result<Self::Guard> {
self.calls
.lock()
.unwrap_or_else(|e| e.into_inner())
.push(content);
Ok(MockGuard(self.outcome))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn offers_for_text_are_what_set_selection_always_offered() {
let content = Content::Text("hello".into());
let offers = Offers::of(&content);
let mimes: Vec<Mime> = offers.mimes().cloned().collect();
assert_eq!(mimes, mimes_to_offer(&content));
for mime in &mimes {
assert_eq!(offers.bytes_for(mime), b"hello");
}
}
#[test]
fn a_type_that_was_not_offered_answers_with_nothing() {
let offers = Offers::new(vec![(Mime::new("text/uri-list"), b"file:///a".to_vec())]);
assert!(offers.bytes_for(&Mime::new("image/png")).is_empty());
}
#[test]
fn debugging_offers_shows_sizes_not_content() {
let offers = Offers::new(vec![(Mime::new("text/plain"), b"hunter2".to_vec())]);
let shown = format!("{offers:?}");
assert!(!shown.contains("hunter2"), "{shown}");
assert!(shown.contains("text/plain (7 bytes)"), "{shown}");
}
#[test]
fn setting_text_offers_both_plain_text_mime_types() {
let offered = mimes_to_offer(&Content::Text("hello".to_string()));
assert_eq!(
offered,
vec![
Mime::new("text/plain;charset=utf-8"),
Mime::new("text/plain"),
]
);
}
#[test]
fn setting_an_image_offers_only_the_type_it_was_stored_with() {
let offered = mimes_to_offer(&Content::Image {
bytes: vec![1, 2, 3],
mime: Mime::new("image/png"),
});
assert_eq!(offered, vec![Mime::new("image/png")]);
}
#[test]
fn bytes_for_answers_either_text_mime_with_the_same_bytes() {
let content = Content::Text("hello".to_string());
assert_eq!(
bytes_for(&content, &Mime::new("text/plain;charset=utf-8")),
Some(b"hello".to_vec())
);
assert_eq!(
bytes_for(&content, &Mime::new("text/plain")),
Some(b"hello".to_vec())
);
assert_eq!(bytes_for(&content, &Mime::new("text/html")), None);
}
#[test]
fn bytes_for_an_image_only_answers_its_own_mime() {
let content = Content::Image {
bytes: vec![9, 9, 9],
mime: Mime::new("image/png"),
};
assert_eq!(
bytes_for(&content, &Mime::new("image/png")),
Some(vec![9, 9, 9])
);
assert_eq!(bytes_for(&content, &Mime::new("image/jpeg")), None);
}
#[test]
fn the_mock_reports_what_the_last_call_would_have_offered() {
let writer = mock::MockWriter::new();
writer
.set_selection(Content::Text("first".to_string()))
.unwrap();
writer
.set_selection(Content::Image {
bytes: vec![1],
mime: Mime::new("image/png"),
})
.unwrap();
assert_eq!(writer.calls().len(), 2);
assert_eq!(writer.last_offered(), Some(vec![Mime::new("image/png")]));
}
#[test]
fn a_mock_writer_can_be_configured_to_report_timing_out() {
let writer = mock::MockWriter::with_outcome(SelectionOutcome::TimedOut);
let guard = writer
.set_selection(Content::Text("x".to_string()))
.unwrap();
assert_eq!(guard.wait(Duration::from_secs(0)), SelectionOutcome::TimedOut);
}
#[test]
fn a_waiter_wakes_as_soon_as_it_is_signalled() {
let waiter = Waiter::new();
let signaller = waiter.clone();
std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(20));
signaller.signal(SelectionOutcome::Served);
});
let started = std::time::Instant::now();
let outcome = waiter.wait(Duration::from_secs(10));
assert_eq!(outcome, SelectionOutcome::Served);
assert!(started.elapsed() < Duration::from_secs(2));
}
#[test]
fn an_unsignalled_waiter_times_out_rather_than_blocking_forever() {
let waiter = Waiter::new();
let outcome = waiter.wait(Duration::from_millis(20));
assert_eq!(outcome, SelectionOutcome::TimedOut);
}
#[test]
fn only_the_first_signal_is_kept() {
let waiter = Waiter::new();
waiter.signal(SelectionOutcome::Served);
waiter.signal(SelectionOutcome::Superseded);
assert_eq!(waiter.wait(Duration::from_millis(0)), SelectionOutcome::Served);
}
}