rat_text/
clipboard.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//!
//! There are too many clipboard crates.
//!

use crate::TextError;
use dyn_clone::DynClone;
use std::error::Error;
use std::fmt::{Debug, Display, Formatter};
use std::sync::{Arc, Mutex};

#[derive(Debug)]
pub struct ClipboardError;

impl Display for ClipboardError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self)
    }
}

impl Error for ClipboardError {}

impl From<ClipboardError> for TextError {
    fn from(_value: ClipboardError) -> Self {
        TextError::Clipboard
    }
}

/// Access some clipboard.
pub trait Clipboard: DynClone + Debug {
    /// Get text from the clipboard.
    fn get_string(&self) -> Result<String, ClipboardError>;

    /// Set text from the clipboard.
    fn set_string(&self, s: &str) -> Result<(), ClipboardError>;
}

/// Local clipboard.
/// A string in disguise.
#[derive(Debug, Default, Clone)]
pub struct LocalClipboard {
    text: Arc<Mutex<String>>,
}

impl LocalClipboard {
    pub fn new() -> Self {
        Self::default()
    }
}

impl Clipboard for LocalClipboard {
    fn get_string(&self) -> Result<String, ClipboardError> {
        match self.text.lock() {
            Ok(v) => Ok(v.clone()),
            Err(_) => Err(ClipboardError),
        }
    }

    fn set_string(&self, s: &str) -> Result<(), ClipboardError> {
        match self.text.lock() {
            Ok(mut v) => {
                *v = s.to_string();
                Ok(())
            }
            Err(_) => Err(ClipboardError),
        }
    }
}