use hyprforge_clipboard::ipc::Shared;
use hyprforge_clipboard::{
ClipboardWatcher, Entry, History, Recordable, Sensitivity, WaylandWatcher, WaylandWriter,
};
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
const RECONNECT_INTERVAL: Duration = Duration::from_secs(3);
#[tokio::main]
async fn main() -> anyhow::Result<()> {
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
)
.init();
let (history, can_save) = load_history();
tracing::info!(
entries = history.entries().len(),
can_save,
"loaded clipboard history"
);
if !can_save {
tracing::error!(
"the on-disk clipboard history could not be parsed; new copies will still be \
recorded in memory and shown to the popup process is not this daemon's job, but \
NOTHING will be saved to disk until the file is fixed by hand and this daemon is \
restarted. Losing today's copies would be bad; overwriting a history that failed \
to parse would be worse."
);
}
let shared = Arc::new(Shared {
history: tokio::sync::Mutex::new(history),
can_save,
writer: WaylandWriter::new(),
selection: tokio::sync::Mutex::new(None),
});
let ipc_shared = Arc::clone(&shared);
tokio::spawn(async move {
if let Err(e) = hyprforge_clipboard::ipc::run(ipc_shared).await {
tracing::error!(error = %e, "clipboard control socket is not running");
}
});
loop {
match WaylandWatcher::connect() {
Ok(watcher) => {
tracing::info!("connected to the compositor's clipboard");
run_until_disconnected(&watcher, &shared).await;
tracing::warn!(
"clipboard watcher stopped delivering entries; the compositor connection \
likely died. Reconnecting."
);
}
Err(e) => {
tracing::warn!(error = %e, "could not connect to the compositor's clipboard; will retry");
}
}
tokio::time::sleep(RECONNECT_INTERVAL).await;
}
}
async fn run_until_disconnected(watcher: &WaylandWatcher, shared: &Shared<WaylandWriter>) {
let mut entries = watcher.subscribe();
while let Some(entry) = entries.recv().await {
let id = entry.id.clone();
let size = entry.content.size();
let now = now_unix();
let mut history = shared.history.lock().await;
if record(&mut history, entry, now) {
tracing::info!(id = ?id, size, "recorded a clipboard entry");
} else {
tracing::debug!(id = ?id, size, "clipboard entry was not recorded");
continue;
}
if shared.can_save {
if let Err(e) = history.save() {
tracing::error!(error = %e, "failed to save clipboard history; will retry on the next copy");
}
}
}
}
fn record(history: &mut History, entry: Entry, now: u64) -> bool {
let Some(recordable) = Recordable::new(entry.content, Sensitivity::Recordable) else {
unreachable!(
"Recordable::new only refuses Sensitivity::Secret, which is never passed here"
);
};
history.record(recordable, now)
}
fn now_unix() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
fn load_history() -> (History, bool) {
load_history_from(
&hyprforge_paths::clipboard_index_path(),
&hyprforge_paths::clipboard_images_dir(),
)
}
fn load_history_from(index_path: &Path, images_dir: &Path) -> (History, bool) {
match History::load_from(index_path, images_dir) {
Ok(history) => (history, true),
Err(e) => {
tracing::error!(
path = %index_path.display(),
error = %e,
"clipboard history exists but could not be parsed"
);
(History::new(), false)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use hyprforge_clipboard::{Content, EntryId};
fn entry(text: &str) -> Entry {
let content = Content::Text(text.to_string());
Entry {
id: EntryId::of(&content),
content,
copied_at: 0,
pinned: false,
}
}
#[test]
fn the_daemon_records_a_normal_entry() {
let mut history = History::new();
assert!(record(&mut history, entry("hello"), 1));
assert_eq!(history.entries().len(), 1);
assert_eq!(history.entries()[0].content, Content::Text("hello".into()));
}
#[test]
fn a_secret_can_never_be_recorded_through_this_daemons_own_constructor() {
assert!(Recordable::new(Content::Text("hunter2".into()), Sensitivity::Secret).is_none());
}
#[test]
fn a_blank_copy_is_not_recorded_and_does_not_panic() {
let mut history = History::new();
assert!(!record(&mut history, entry(" \n\t"), 1));
assert!(history.entries().is_empty());
}
#[test]
fn a_missing_index_yields_an_empty_savable_history() {
let dir = tempfile::tempdir().unwrap();
let index = dir.path().join("history.toml");
let images = dir.path().join("images");
let (history, can_save) = load_history_from(&index, &images);
assert!(history.entries().is_empty());
assert!(can_save);
}
#[test]
fn an_unreadable_history_is_not_overwritten_and_the_daemon_can_keep_going() {
let dir = tempfile::tempdir().unwrap();
let index = dir.path().join("history.toml");
let images = dir.path().join("images");
let broken = "entries = not a list at all\n";
std::fs::write(&index, broken).unwrap();
let (history, can_save) = load_history_from(&index, &images);
assert!(
history.entries().is_empty(),
"the daemon must still have something usable to watch and record into"
);
assert!(
!can_save,
"a history that failed to parse must never be saved over"
);
let mut history = history;
assert!(record(&mut history, entry("new copy"), 1));
if can_save {
history.save_to(&index, &images).unwrap();
}
assert_eq!(
std::fs::read_to_string(&index).unwrap(),
broken,
"the broken file must survive exactly as it was found"
);
}
}