use crate::types::{Content, Entry, EntryId, Mime, Sensitivity};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
const MAX_ENTRIES: usize = 500;
const MAX_TOTAL_BYTES: u64 = 64 * 1024 * 1024;
const MAX_SINGLE_ENTRY_BYTES: u64 = MAX_TOTAL_BYTES / 4;
pub struct Recordable(Content);
impl Recordable {
pub fn new(content: Content, sensitivity: Sensitivity) -> Option<Self> {
match sensitivity {
Sensitivity::Secret => None,
Sensitivity::Recordable => Some(Recordable(content)),
}
}
}
#[derive(Debug, Default)]
pub struct History {
entries: Vec<Entry>,
}
#[derive(Debug, thiserror::Error)]
pub enum HistoryError {
#[error("{path} could not be read as clipboard history: {source}")]
Unreadable {
path: PathBuf,
#[source]
source: toml::de::Error,
},
#[error("{path} could not be opened: {source}")]
Io {
path: PathBuf,
#[source]
source: std::io::Error,
},
#[error("{path} could not be written: {source}")]
Write {
path: PathBuf,
#[source]
source: std::io::Error,
},
}
impl History {
pub fn new() -> Self {
History::default()
}
pub fn entries(&self) -> &[Entry] {
&self.entries
}
pub fn record(&mut self, recordable: Recordable, now: u64) -> bool {
let content = recordable.0;
if content.is_empty() {
return false;
}
if content.size() as u64 > MAX_SINGLE_ENTRY_BYTES {
return false;
}
let id = EntryId::of(&content);
if let Some(existing) = self.entries.iter_mut().find(|e| e.id == id) {
existing.copied_at = now;
} else {
self.entries.push(Entry {
id,
content,
copied_at: now,
pinned: false,
});
}
self.sort();
self.enforce_caps();
true
}
pub fn set_pinned(&mut self, id: &EntryId, pinned: bool) -> bool {
let Some(entry) = self.entries.iter_mut().find(|e| &e.id == id) else {
return false;
};
entry.pinned = pinned;
self.sort();
true
}
pub fn remove(&mut self, id: &EntryId) -> bool {
let before = self.entries.len();
self.entries.retain(|e| &e.id != id);
self.entries.len() != before
}
fn sort(&mut self) {
self.entries.sort_by(|a, b| {
b.pinned
.cmp(&a.pinned)
.then(b.copied_at.cmp(&a.copied_at))
.then(a.id.cmp(&b.id))
});
}
pub fn total_bytes(&self) -> u64 {
self.entries.iter().map(|e| e.content.size() as u64).sum()
}
fn enforce_caps(&mut self) {
while self.entries.len() > MAX_ENTRIES {
match self.entries.iter().rposition(|e| !e.pinned) {
Some(idx) => {
self.entries.remove(idx);
}
None => break,
}
}
while self.total_bytes() > MAX_TOTAL_BYTES {
match self.entries.iter().rposition(|e| !e.pinned) {
Some(idx) => {
self.entries.remove(idx);
}
None => break,
}
}
}
pub fn load() -> Result<History, HistoryError> {
History::load_from(
&hyprforge_paths::clipboard_index_path(),
&hyprforge_paths::clipboard_images_dir(),
)
}
pub fn load_from(index_path: &Path, images_dir: &Path) -> Result<History, HistoryError> {
let text = match std::fs::read_to_string(index_path) {
Ok(text) => text,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(History::default()),
Err(source) => {
return Err(HistoryError::Io {
path: index_path.to_path_buf(),
source,
})
}
};
let index: IndexFile =
toml::from_str(&text).map_err(|source| HistoryError::Unreadable {
path: index_path.to_path_buf(),
source,
})?;
let mut entries = Vec::with_capacity(index.entries.len());
for row in index.entries {
let content = match row.content {
IndexContent::Text { text } => Content::Text(text),
IndexContent::Image { mime } => {
let image_path = images_dir.join(format!("{}.bin", row.id));
match std::fs::read(&image_path) {
Ok(bytes) => Content::Image {
bytes,
mime: Mime::new(mime),
},
Err(err) => {
tracing::warn!(
id = %row.id,
path = %image_path.display(),
error = %err,
"clipboard image file missing on disk; dropping entry from history"
);
continue;
}
}
}
};
let id = EntryId::of(&content);
entries.push(Entry {
id,
content,
copied_at: row.copied_at,
pinned: row.pinned,
});
}
let mut history = History { entries };
history.sort();
Ok(history)
}
pub fn save(&self) -> Result<(), HistoryError> {
self.save_to(
&hyprforge_paths::clipboard_index_path(),
&hyprforge_paths::clipboard_images_dir(),
)
}
pub fn save_to(&self, index_path: &Path, images_dir: &Path) -> Result<(), HistoryError> {
std::fs::create_dir_all(images_dir).map_err(|source| HistoryError::Write {
path: images_dir.to_path_buf(),
source,
})?;
let mut keep = std::collections::HashSet::new();
for entry in &self.entries {
if let Content::Image { bytes, .. } = &entry.content {
let path = images_dir.join(format!("{}.bin", entry.id.as_str()));
keep.insert(path.clone());
if !path.exists() {
hyprforge_paths::write_atomic_bytes(&path, bytes).map_err(|source| {
HistoryError::Write {
path: path.clone(),
source,
}
})?;
}
}
}
if let Ok(read_dir) = std::fs::read_dir(images_dir) {
for dir_entry in read_dir.flatten() {
let path = dir_entry.path();
if !keep.contains(&path) {
let _ = std::fs::remove_file(&path);
}
}
}
let index = IndexFile {
entries: self
.entries
.iter()
.map(|e| IndexEntry {
id: e.id.as_str().to_string(),
copied_at: e.copied_at,
pinned: e.pinned,
content: match &e.content {
Content::Text(text) => IndexContent::Text { text: text.clone() },
Content::Image { mime, .. } => IndexContent::Image {
mime: mime.as_str().to_string(),
},
},
})
.collect(),
};
let text = toml::to_string_pretty(&index)
.expect("clipboard index is plain data and always serialises");
hyprforge_paths::write_atomic(index_path, &text).map_err(|source| HistoryError::Write {
path: index_path.to_path_buf(),
source,
})
}
}
#[derive(Serialize, Deserialize)]
struct IndexFile {
#[serde(default)]
entries: Vec<IndexEntry>,
}
#[derive(Serialize, Deserialize)]
struct IndexEntry {
id: String,
copied_at: u64,
#[serde(default)]
pinned: bool,
#[serde(flatten)]
content: IndexContent,
}
#[derive(Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum IndexContent {
Text { text: String },
Image { mime: String },
}
#[cfg(test)]
mod tests {
use super::*;
fn text(s: &str) -> Recordable {
Recordable::new(Content::Text(s.to_string()), Sensitivity::Recordable).unwrap()
}
fn image(bytes: Vec<u8>) -> Recordable {
Recordable::new(
Content::Image {
bytes,
mime: Mime::new("image/png"),
},
Sensitivity::Recordable,
)
.unwrap()
}
#[test]
fn recording_a_secret_is_not_possible_at_all() {
assert!(Recordable::new(Content::Text("hunter2".into()), Sensitivity::Secret).is_none());
}
#[test]
fn an_entry_whose_content_is_empty_or_whitespace_only_is_not_stored() {
let mut history = History::new();
assert!(!history.record(text(""), 1));
assert!(!history.record(text(" \n\t"), 1));
assert!(history.entries().is_empty());
}
#[test]
fn recopying_an_existing_entry_moves_it_to_the_top_instead_of_duplicating() {
let mut history = History::new();
history.record(text("first"), 1);
history.record(text("second"), 2);
assert_eq!(history.entries().len(), 2);
assert_eq!(history.entries()[0].content, Content::Text("second".into()));
history.record(text("first"), 3);
assert_eq!(history.entries().len(), 2, "must not duplicate");
assert_eq!(history.entries()[0].content, Content::Text("first".into()));
assert_eq!(history.entries()[0].copied_at, 3);
}
#[test]
fn recopying_a_pinned_entry_keeps_it_pinned() {
let mut history = History::new();
history.record(text("keep me"), 1);
let id = history.entries()[0].id.clone();
history.set_pinned(&id, true);
history.record(text("something else"), 2);
history.record(text("keep me"), 3);
let entry = history.entries().iter().find(|e| e.id == id).unwrap();
assert!(entry.pinned, "pin must survive the re-copy");
assert_eq!(entry.copied_at, 3, "timestamp still updates");
}
#[test]
fn a_pinned_entry_is_never_evicted_by_the_count_cap() {
let mut history = History::new();
history.record(text("pin me"), 0);
let id = history.entries()[0].id.clone();
history.set_pinned(&id, true);
for i in 1..(MAX_ENTRIES as u64 + 50) {
history.record(text(&format!("entry {i}")), i);
}
assert!(
history.entries().iter().any(|e| e.id == id),
"pinned entry must survive even though the count cap was exceeded many times over"
);
assert!(history.entries().len() <= MAX_ENTRIES + 1);
}
#[test]
fn a_pinned_entry_is_never_evicted_by_the_byte_cap() {
let mut history = History::new();
history.record(image(vec![1u8; 1024]), 0);
let id = history.entries()[0].id.clone();
history.set_pinned(&id, true);
let chunk = (MAX_SINGLE_ENTRY_BYTES / 2) as usize;
for i in 1..20u64 {
history.record(image(vec![i as u8; chunk]), i);
}
assert!(
history.entries().iter().any(|e| e.id == id),
"pinned entry must survive even though the byte cap was exceeded"
);
}
#[test]
fn the_byte_cap_evicts_the_oldest_unpinned_entry_first_when_images_push_it_over() {
let mut history = History::new();
let chunk = MAX_SINGLE_ENTRY_BYTES as usize;
history.record(image(vec![1u8; chunk]), 1);
let oldest_id = history.entries()[0].id.clone();
history.record(image(vec![2u8; chunk]), 2);
history.record(image(vec![3u8; chunk]), 3);
history.record(image(vec![4u8; chunk]), 4);
history.record(image(vec![5u8; chunk]), 5);
assert!(
!history.entries().iter().any(|e| e.id == oldest_id),
"the oldest unpinned entry should have been evicted"
);
assert!(history.total_bytes() <= MAX_TOTAL_BYTES);
assert_eq!(
history.entries()[0].content,
Content::Image {
bytes: vec![5u8; chunk],
mime: Mime::new("image/png")
},
"the newest entry must still be present"
);
}
#[test]
fn a_single_entry_larger_than_the_cap_is_refused_rather_than_evicting_everything() {
let mut history = History::new();
history.record(text("keep me"), 1);
history.record(text("and me"), 2);
let huge = vec![0u8; (MAX_SINGLE_ENTRY_BYTES + 1) as usize];
assert!(
!history.record(image(huge), 3),
"an entry that alone exceeds the cap must be refused"
);
assert_eq!(
history.entries().len(),
2,
"existing history must be untouched by the refusal"
);
}
#[test]
fn a_missing_index_is_first_run_and_yields_an_empty_history() {
let dir = tempfile::tempdir().unwrap();
let index = dir.path().join("history.toml");
let images = dir.path().join("images");
let history = History::load_from(&index, &images).unwrap();
assert!(history.entries().is_empty());
}
#[test]
fn an_index_that_exists_and_will_not_parse_is_reported_not_overwritten() {
let dir = tempfile::tempdir().unwrap();
let index = dir.path().join("history.toml");
let images = dir.path().join("images");
std::fs::write(&index, "entries = not a list at all\n").unwrap();
let err = History::load_from(&index, &images)
.expect_err("a malformed index is an error, not an empty history");
assert!(matches!(err, HistoryError::Unreadable { .. }));
assert_eq!(
std::fs::read_to_string(&index).unwrap(),
"entries = not a list at all\n"
);
}
#[test]
fn an_image_file_missing_from_disk_does_not_fail_the_load_or_panic() {
let dir = tempfile::tempdir().unwrap();
let index = dir.path().join("history.toml");
let images = dir.path().join("images");
std::fs::create_dir_all(&images).unwrap();
let mut history = History::new();
history.record(text("survives"), 1);
history.record(image(vec![9u8; 32]), 2);
history.save_to(&index, &images).unwrap();
let missing_id = history
.entries()
.iter()
.find(|e| matches!(e.content, Content::Image { .. }))
.unwrap()
.id
.clone();
std::fs::remove_file(images.join(format!("{}.bin", missing_id.as_str()))).unwrap();
let loaded = History::load_from(&index, &images).unwrap();
assert_eq!(
loaded.entries().len(),
1,
"the broken entry is dropped, not the whole load"
);
assert_eq!(
loaded.entries()[0].content,
Content::Text("survives".into())
);
}
#[test]
fn what_is_saved_is_what_comes_back_including_pins_and_image_bytes() {
let dir = tempfile::tempdir().unwrap();
let index = dir.path().join("history.toml");
let images = dir.path().join("images");
let mut history = History::new();
history.record(text("plain text"), 10);
history.record(image(vec![7u8; 4096]), 20);
let image_id = history.entries()[0].id.clone();
history.set_pinned(&image_id, true);
history.save_to(&index, &images).unwrap();
let loaded = History::load_from(&index, &images).unwrap();
assert_eq!(loaded.entries().len(), 2);
let reloaded_image = loaded.entries().iter().find(|e| e.id == image_id).unwrap();
assert!(reloaded_image.pinned);
assert_eq!(
reloaded_image.content,
Content::Image {
bytes: vec![7u8; 4096],
mime: Mime::new("image/png")
}
);
let reloaded_text = loaded
.entries()
.iter()
.find(|e| e.content == Content::Text("plain text".into()))
.unwrap();
assert_eq!(reloaded_text.copied_at, 10);
}
#[test]
fn saving_removes_image_files_left_behind_by_evicted_entries() {
let dir = tempfile::tempdir().unwrap();
let index = dir.path().join("history.toml");
let images = dir.path().join("images");
let mut history = History::new();
history.record(image(vec![1u8; 16]), 1);
history.save_to(&index, &images).unwrap();
let files_before: Vec<_> = std::fs::read_dir(&images).unwrap().collect();
assert_eq!(files_before.len(), 1);
history.remove(&history.entries()[0].id.clone());
history.save_to(&index, &images).unwrap();
let files_after: Vec<_> = std::fs::read_dir(&images).unwrap().collect();
assert!(
files_after.is_empty(),
"orphaned image file must be cleaned up"
);
}
}