cli_clipboard/
x11_clipboard.rs

1/*
2Copyright 2017 Avraham Weinstock
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8   http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17use crate::common::*;
18use crate::Result;
19use std::marker::PhantomData;
20use std::time::Duration;
21use x11_clipboard_crate::Clipboard as X11Clipboard;
22use x11_clipboard_crate::{Atom, Atoms};
23
24pub trait Selection {
25    fn atom(atoms: &Atoms) -> Atom;
26}
27
28pub struct Primary;
29
30impl Selection for Primary {
31    fn atom(atoms: &Atoms) -> Atom {
32        atoms.primary
33    }
34}
35
36pub struct Clipboard;
37
38impl Selection for Clipboard {
39    fn atom(atoms: &Atoms) -> Atom {
40        atoms.clipboard
41    }
42}
43
44pub struct X11ClipboardContext<S = Clipboard>(X11Clipboard, PhantomData<S>)
45where
46    S: Selection;
47
48impl<S> ClipboardProvider for X11ClipboardContext<S>
49where
50    S: Selection,
51{
52    fn new() -> Result<X11ClipboardContext<S>> {
53        Ok(X11ClipboardContext(X11Clipboard::new()?, PhantomData))
54    }
55
56    fn get_contents(&mut self) -> Result<String> {
57        Ok(String::from_utf8(self.0.load(
58            S::atom(&self.0.getter.atoms),
59            self.0.getter.atoms.utf8_string,
60            self.0.getter.atoms.property,
61            Duration::from_secs(3),
62        )?)?)
63    }
64
65    fn set_contents(&mut self, data: String) -> Result<()> {
66        Ok(self.0.store(
67            S::atom(&self.0.setter.atoms),
68            self.0.setter.atoms.utf8_string,
69            data,
70        )?)
71    }
72
73    fn clear(&mut self) -> Result<()> {
74        Ok(self.0.store(
75            S::atom(&self.0.setter.atoms),
76            self.0.setter.atoms.utf8_string,
77            "".to_string(),
78        )?)
79    }
80}