Skip to content

Commit

Permalink
Add support for x11 primary selection.
Browse files Browse the repository at this point in the history
  • Loading branch information
tkerber committed Sep 5, 2017
1 parent 5ab4062 commit 31699de
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 18 deletions.
17 changes: 17 additions & 0 deletions examples/primary_selection.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
extern crate clipboard;

use clipboard::ClipboardProvider;
#[cfg(target_os = "linux")]
use clipboard::x11_clipboard::{X11ClipboardContext, Primary};

fn main() {
if cfg!(not(target_os = "linux")) {
println!("Primary selection is only available under linux!");
return;
}
let mut ctx: X11ClipboardContext<Primary> = ClipboardProvider::new().unwrap();

let the_string = "Hello, world!";

ctx.set_contents(the_string.to_owned()).unwrap();
}
59 changes: 41 additions & 18 deletions src/x11_clipboard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,35 +16,58 @@ limitations under the License.

use std::error::Error;
use std::time::Duration;
use std::marker::PhantomData;
use common::*;
use x11_clipboard_crate::Clipboard;
use x11_clipboard_crate::Atoms;
use x11_clipboard_crate::Clipboard as X11Clipboard;
use x11_clipboard_crate::xcb::xproto::Atom;

pub struct X11ClipboardContext(Clipboard);
pub trait Selection {
fn atom(atoms: &Atoms) -> Atom;
}

pub struct Primary;

impl Selection for Primary {
fn atom(atoms: &Atoms) -> Atom {
atoms.primary
}
}

pub struct Clipboard;

impl Selection for Clipboard {
fn atom(atoms: &Atoms) -> Atom {
atoms.clipboard
}
}

pub struct X11ClipboardContext<S = Clipboard>(X11Clipboard, PhantomData<S>)
where
S: Selection;

impl ClipboardProvider for X11ClipboardContext {
fn new() -> Result<X11ClipboardContext, Box<Error>> {
Clipboard::new()
.map(X11ClipboardContext)
.map_err(Into::into)
impl<S> ClipboardProvider for X11ClipboardContext<S>
where
S: Selection,
{
fn new() -> Result<X11ClipboardContext<S>, Box<Error>> {
Ok(X11ClipboardContext(X11Clipboard::new()?, PhantomData))
}

fn get_contents(&mut self) -> Result<String, Box<Error>> {
self.0.load(
self.0.getter.atoms.clipboard,
Ok(String::from_utf8(self.0.load(
S::atom(&self.0.getter.atoms),
self.0.getter.atoms.utf8_string,
self.0.getter.atoms.property,
Duration::from_secs(3)
)
.map_err(Into::into)
.and_then(|vec| String::from_utf8(vec).map_err(Into::into))
Duration::from_secs(3),
)?)?)
}

fn set_contents(&mut self, data: String) -> Result<(), Box<Error>> {
self.0.store(
self.0.setter.atoms.clipboard,
Ok(self.0.store(
S::atom(&self.0.setter.atoms),
self.0.setter.atoms.utf8_string,
data
)
.map_err(Into::into)
data,
)?)
}
}

0 comments on commit 31699de

Please sign in to comment.