use hyprforge_clipboard::ipc;
pub trait Editor {
fn set_pinned(&self, id: &str, pinned: bool) -> Result<(), String>;
fn remove(&self, id: &str) -> Result<(), String>;
}
pub struct Wired;
impl Editor for Wired {
fn set_pinned(&self, id: &str, pinned: bool) -> Result<(), String> {
ipc::set_pinned(id, pinned).map_err(|e| describe(e, "pinning"))
}
fn remove(&self, id: &str) -> Result<(), String> {
ipc::remove_entry(id).map_err(|e| describe(e, "deleting"))
}
}
fn describe(err: ipc::ClientError, doing: &str) -> String {
match err {
ipc::ClientError::NoRuntimeDir | ipc::ClientError::Unreachable(_) | ipc::ClientError::Timeout => {
format!("hyprforge-clipd isn't running, so {doing} isn't available right now")
}
ipc::ClientError::Malformed => {
"hyprforge-clipd sent a response this popup couldn't understand".to_string()
}
ipc::ClientError::Refused(message) => message,
}
}
#[cfg(test)]
pub mod mock {
use super::*;
use std::cell::RefCell;
pub struct MockEditor {
pub calls: RefCell<Vec<(String, bool)>>,
pub removed: RefCell<Vec<String>>,
pub result: Result<(), String>,
}
impl MockEditor {
pub fn succeeding() -> Self {
MockEditor { calls: RefCell::new(Vec::new()), removed: RefCell::new(Vec::new()), result: Ok(()) }
}
pub fn no_daemon() -> Self {
MockEditor {
calls: RefCell::new(Vec::new()),
removed: RefCell::new(Vec::new()),
result: Err("hyprforge-clipd isn't running, so pinning isn't available right now".to_string()),
}
}
pub fn failing(message: &str) -> Self {
MockEditor {
calls: RefCell::new(Vec::new()),
removed: RefCell::new(Vec::new()),
result: Err(message.to_string()),
}
}
}
impl Editor for MockEditor {
fn set_pinned(&self, id: &str, pinned: bool) -> Result<(), String> {
self.calls.borrow_mut().push((id.to_string(), pinned));
self.result.clone()
}
fn remove(&self, id: &str) -> Result<(), String> {
self.removed.borrow_mut().push(id.to_string());
self.result.clone()
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_way_of_not_reaching_the_daemon_reads_as_not_running() {
for err in [
ipc::ClientError::NoRuntimeDir,
ipc::ClientError::Unreachable("connection refused".to_string()),
ipc::ClientError::Timeout,
] {
assert_eq!(describe(err, "pinning"), "hyprforge-clipd isn't running, so pinning isn't available right now");
}
}
#[test]
fn the_message_names_what_could_not_happen() {
let message = describe(ipc::ClientError::Timeout, "deleting");
assert_eq!(message, "hyprforge-clipd isn't running, so deleting isn't available right now");
}
#[test]
fn a_refusal_from_the_daemon_is_passed_through_verbatim() {
let message = "no clipboard entry with id abc123".to_string();
assert_eq!(describe(ipc::ClientError::Refused(message.clone()), "pinning"), message);
}
#[test]
fn a_malformed_response_says_so_rather_than_naming_the_daemon_as_down() {
assert_eq!(
describe(ipc::ClientError::Malformed, "pinning"),
"hyprforge-clipd sent a response this popup couldn't understand"
);
}
}