rustdesk/src/server/clipboard_service.rs

72 lines
1.7 KiB
Rust
Raw Normal View History

2021-10-22 16:02:01 +08:00
use std::sync::mpsc::Sender;
use clipboard_master::{CallbackResult, ClipboardHandler, Master};
2021-03-29 15:59:14 +08:00
use super::*;
pub use crate::common::{
check_clipboard, ClipboardContext, CLIPBOARD_INTERVAL as INTERVAL, CLIPBOARD_NAME as NAME,
CONTENT,
};
struct State {
ctx: Option<ClipboardContext>,
}
impl Default for State {
fn default() -> Self {
let ctx = match ClipboardContext::new() {
Ok(ctx) => Some(ctx),
Err(err) => {
log::error!("Failed to start {}: {}", NAME, err);
None
}
};
Self { ctx }
2021-03-29 15:59:14 +08:00
}
}
impl super::service::Reset for State {
fn reset(&mut self) {
*CONTENT.lock().unwrap() = Default::default();
}
}
2021-10-22 16:02:01 +08:00
struct ClipHandle {
tx: Sender<bool>,
}
impl ClipboardHandler for ClipHandle {
fn on_clipboard_change(&mut self) -> CallbackResult {
let _ = self.tx.send(true);
CallbackResult::Next
}
}
2021-03-29 15:59:14 +08:00
pub fn new() -> GenericService {
let sp = GenericService::new(NAME, true);
2021-10-22 16:02:01 +08:00
sp.listen::<State, _, _>(notify, run);
2021-03-29 15:59:14 +08:00
sp
}
2021-10-22 16:02:01 +08:00
fn notify(tx: Sender<bool>) -> ResultType<()> {
Master::new(ClipHandle { tx }).run()?;
Ok(())
}
2021-03-29 15:59:14 +08:00
fn run(sp: GenericService, state: &mut State) -> ResultType<()> {
if let Some(ctx) = state.ctx.as_mut() {
if let Some(msg) = check_clipboard(ctx, None) {
sp.send(msg);
}
sp.snapshot(|sps| {
let txt = crate::CONTENT.lock().unwrap().clone();
if !txt.is_empty() {
let msg_out = crate::create_clipboard_msg(txt);
sps.send_shared(Arc::new(msg_out));
}
Ok(())
})?;
2021-03-29 15:59:14 +08:00
}
Ok(())
}