sui_platform/
os_clipboard.rs1use sui_core::ClipboardBackend;
2
3pub struct OsClipboardBackend {
12 connection: Option<arboard::Clipboard>,
13 connection_failed: bool,
14 fallback: Option<String>,
15}
16
17impl OsClipboardBackend {
18 pub fn new() -> Self {
19 Self {
20 connection: None,
21 connection_failed: false,
22 fallback: None,
23 }
24 }
25
26 fn connection(&mut self) -> Option<&mut arboard::Clipboard> {
27 if self.connection.is_none() && !self.connection_failed {
28 match arboard::Clipboard::new() {
29 Ok(connection) => self.connection = Some(connection),
30 Err(_) => self.connection_failed = true,
31 }
32 }
33 self.connection.as_mut()
34 }
35}
36
37impl Default for OsClipboardBackend {
38 fn default() -> Self {
39 Self::new()
40 }
41}
42
43impl ClipboardBackend for OsClipboardBackend {
44 fn text(&mut self) -> Option<String> {
45 let Some(connection) = self.connection() else {
46 return self.fallback.clone();
47 };
48 connection.get_text().ok()
49 }
50
51 fn set_text(&mut self, text: &str) {
52 if let Some(connection) = self.connection()
53 && connection.set_text(text.to_string()).is_ok()
54 {
55 return;
56 }
57 self.fallback = Some(text.to_string());
58 }
59}
60
61#[cfg(test)]
62mod tests {
63 use super::*;
64
65 #[test]
68 #[ignore = "touches the real OS clipboard; run explicitly with --ignored"]
69 fn os_clipboard_round_trips_text() {
70 let mut backend = OsClipboardBackend::new();
71 backend.set_text("sui os clipboard smoke");
72 assert_eq!(
73 backend.text().as_deref(),
74 Some("sui os clipboard smoke"),
75 "OS clipboard (or the in-process fallback) should round-trip text"
76 );
77 }
78}