1
0
Fork 0
mirror of https://github.com/icewind1991/clipboard-sync synced 2026-06-03 10:24:06 +02:00

don't resend received clipboard values

This commit is contained in:
Robin Appelman 2018-08-01 15:21:17 +02:00
commit 5fc5b52237

View file

@ -1,24 +1,27 @@
extern crate clipboard;
extern crate env_logger;
extern crate serde;
#[macro_use] extern crate serde_derive;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate ws;
extern crate env_logger;
use clipboard::{ClipboardContext, ClipboardProvider};
use common::ClipboardCommand;
use std::{thread, thread::JoinHandle, time};
use ws::{connect, Message, Sender};
use std::env;
use std::sync::{Arc, Mutex};
use ws::{connect, Message, Sender};
mod common;
fn handle_command(command: ClipboardCommand, ctx: &mut ClipboardContext) {
fn handle_command(command: ClipboardCommand, ctx: &mut ClipboardContext, current_clipboard: Arc<Mutex<String>>) {
match command {
ClipboardCommand::Set { value, session: _ } => {
let old_clipboard = ctx.get_contents().unwrap_or_default();
if value != old_clipboard {
let _ = ctx.set_contents(value);
let mut clip = current_clipboard.lock().unwrap();
if *clip != value {
let _ = ctx.set_contents(value.clone());
*clip = value;
}
}
_ => {}
@ -41,13 +44,14 @@ fn main() {
println!("connecting to {} on channel {}", url, session);
connect(url, |out| {
clipboard_thread(session.clone(), out);
let current_clipboard = Arc::new(Mutex::new(String::new()));
clipboard_thread(session.clone(), out, current_clipboard.clone());
move |msg: Message| {
let mut ctx: ClipboardContext = ClipboardProvider::new().unwrap();
let result: serde_json::Result<ClipboardCommand> = serde_json::from_str(msg.as_text().unwrap_or_default());
match result {
Ok(command) => handle_command(command, &mut ctx),
Ok(command) => handle_command(command, &mut ctx, current_clipboard.clone()),
Err(_) => {}
}
Ok(())
@ -55,11 +59,14 @@ fn main() {
}).unwrap();
}
fn clipboard_thread(session: String, out: Sender) -> JoinHandle<()> {
fn clipboard_thread(session: String, out: Sender, current_clipboard: Arc<Mutex<String>>) -> JoinHandle<()> {
thread::spawn(move || {
let mut ctx: ClipboardContext = ClipboardProvider::new().unwrap();
let hundred_millis = time::Duration::from_millis(100);
let mut old_clipboard = ctx.get_contents().unwrap_or_default();
{
let mut clip = current_clipboard.lock().unwrap();
*clip = ctx.get_contents().unwrap_or_default();
}
thread::sleep(hundred_millis);
@ -71,12 +78,13 @@ fn clipboard_thread(session: String, out: Sender) -> JoinHandle<()> {
loop {
thread::sleep(hundred_millis);
let new_clipboard = ctx.get_contents().unwrap_or_default();
if new_clipboard != old_clipboard {
old_clipboard = new_clipboard;
let mut clip = current_clipboard.lock().unwrap();
if *clip != new_clipboard {
send_to_server(&out, &ClipboardCommand::Set {
session: session.clone(),
value: old_clipboard.clone(),
value: new_clipboard.clone(),
});
*clip = new_clipboard;
}
}
})