strata_web_api/
clipboard.rs1use std::collections::HashMap;
4use std::fmt;
5use std::sync::{Arc, RwLock};
6
7#[derive(Debug, Clone, PartialEq, Eq)]
9pub enum ClipboardError {
10 Unavailable(String),
11 PermissionDenied(String),
12 InvalidData(String),
13 IoError(String),
14}
15
16impl fmt::Display for ClipboardError {
17 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18 match self {
19 Self::Unavailable(s) => write!(f, "Clipboard unavailable: {s}"),
20 Self::PermissionDenied(s) => write!(f, "Clipboard permission denied: {s}"),
21 Self::InvalidData(s) => write!(f, "Invalid clipboard data: {s}"),
22 Self::IoError(s) => write!(f, "Clipboard I/O error: {s}"),
23 }
24 }
25}
26
27impl std::error::Error for ClipboardError {}
28
29#[derive(Clone)]
31pub struct Clipboard {
32 text_buffer: Arc<RwLock<String>>,
33 data_buffer: Arc<RwLock<HashMap<String, Vec<u8>>>>,
34}
35
36impl Default for Clipboard {
37 fn default() -> Self {
38 Self::new()
39 }
40}
41
42impl Clipboard {
43 pub fn new() -> Self {
45 Self {
46 text_buffer: Arc::new(RwLock::new(String::new())),
47 data_buffer: Arc::new(RwLock::new(HashMap::new())),
48 }
49 }
50
51 pub fn write_text(&self, text: &str) -> Result<(), ClipboardError> {
53 let mut buf = self.text_buffer.write().map_err(|e| {
54 ClipboardError::IoError(format!("Failed to acquire text write lock: {e}"))
55 })?;
56 *buf = text.to_string();
57
58 let mut data = self.data_buffer.write().map_err(|e| {
59 ClipboardError::IoError(format!("Failed to acquire data write lock: {e}"))
60 })?;
61 data.insert("text/plain".to_string(), text.as_bytes().to_vec());
62 Ok(())
63 }
64
65 pub fn read_text(&self) -> Result<String, ClipboardError> {
67 let buf = self.text_buffer.read().map_err(|e| {
68 ClipboardError::IoError(format!("Failed to acquire text read lock: {e}"))
69 })?;
70 Ok(buf.clone())
71 }
72
73 pub fn write_data(&self, mime: &str, data: &[u8]) -> Result<(), ClipboardError> {
75 let mut map = self.data_buffer.write().map_err(|e| {
76 ClipboardError::IoError(format!("Failed to acquire data write lock: {e}"))
77 })?;
78 map.insert(mime.to_string(), data.to_vec());
79
80 if mime == "text/plain" {
81 if let Ok(text) = String::from_utf8(data.to_vec()) {
82 if let Ok(mut tbuf) = self.text_buffer.write() {
83 *tbuf = text;
84 }
85 }
86 }
87 Ok(())
88 }
89
90 pub fn read_data(&self, mime: &str) -> Result<Option<Vec<u8>>, ClipboardError> {
92 let map = self.data_buffer.read().map_err(|e| {
93 ClipboardError::IoError(format!("Failed to acquire data read lock: {e}"))
94 })?;
95 Ok(map.get(mime).cloned())
96 }
97
98 pub fn clear(&self) -> Result<(), ClipboardError> {
100 if let Ok(mut tbuf) = self.text_buffer.write() {
101 tbuf.clear();
102 }
103 if let Ok(mut dbuf) = self.data_buffer.write() {
104 dbuf.clear();
105 }
106 Ok(())
107 }
108}