refactor: use clipboard-master for events

This commit is contained in:
Harsh Shandilya 2022-04-26 22:18:21 +05:30
parent f252de7748
commit f0080559dd
No known key found for this signature in database
GPG key ID: 366D7BBAD1031E80
5 changed files with 164 additions and 86 deletions

53
src/clipboard.rs Normal file
View file

@ -0,0 +1,53 @@
use std::io;
use std::ops::Not;
use clipboard_master::{CallbackResult, ClipboardHandler, Master};
use copypasta::{ClipboardContext, ClipboardProvider};
use tracing::{debug, error};
use crate::config::{Act, Match, Replacements};
struct Handler<'a> {
ctx: ClipboardContext,
config: Replacements<'a>,
}
impl<'a> ClipboardHandler for Handler<'a> {
fn on_clipboard_change(&mut self) -> CallbackResult {
if let Ok(contents) = self.ctx.get_contents() {
if let Some(subst) = self
.config
.substitutors
.iter()
.find(|subst| subst.matcher.check_match(&contents))
{
if subst.name.is_empty().not() {
debug!("{}: matched on {}...", &subst.name, truncate(&contents, 40));
}
let result = subst.action.apply_action(&contents);
if let Err(e) = self.ctx.set_contents(result.to_owned()) {
error!("{e}");
}
};
}
CallbackResult::Next
}
fn on_clipboard_error(&mut self, error: io::Error) -> CallbackResult {
error!("Error: {}", error);
CallbackResult::Next
}
}
fn truncate(s: &str, max_chars: usize) -> &str {
match s.char_indices().nth(max_chars) {
None => s,
Some((idx, _)) => &s[..idx],
}
}
pub fn monitor_clipboard<'a>(config: Replacements<'a>) {
let ctx = ClipboardContext::new().expect("Failed to acquire clipboard");
let handler = Handler { ctx, config };
let _ = Master::new(handler).run();
}