|
| 1 | +//! App-lifetime clipboard ownership keeps copied content available on Linux. |
| 2 | +use std::sync::Mutex; |
| 3 | + |
| 4 | +use tauri::Manager as _; |
| 5 | + |
| 6 | +#[derive(Default)] |
| 7 | +pub(crate) struct Clipboard(Mutex<Option<arboard::Clipboard>>); |
| 8 | + |
| 9 | +impl Clipboard { |
| 10 | + pub(crate) fn release(&self) { |
| 11 | + if let Ok(mut clipboard) = self.0.lock() { |
| 12 | + clipboard.take(); |
| 13 | + } |
| 14 | + } |
| 15 | +} |
| 16 | + |
| 17 | +async fn write<R: tauri::Runtime>( |
| 18 | + app: &tauri::AppHandle<R>, |
| 19 | + set: impl FnOnce(&mut arboard::Clipboard) -> Result<(), String> + Send + 'static, |
| 20 | +) -> Result<(), String> { |
| 21 | + let (send, receive) = tokio::sync::oneshot::channel(); |
| 22 | + let handle = app.clone(); |
| 23 | + app.run_on_main_thread(move || { |
| 24 | + let result = (|| { |
| 25 | + let state = handle.state::<Clipboard>(); |
| 26 | + let mut stored = state |
| 27 | + .0 |
| 28 | + .lock() |
| 29 | + .map_err(|_| "Clipboard unavailable".to_owned())?; |
| 30 | + if stored.is_none() { |
| 31 | + *stored = Some( |
| 32 | + arboard::Clipboard::new().map_err(|_| "Clipboard unavailable".to_owned())?, |
| 33 | + ); |
| 34 | + } |
| 35 | + set(stored.as_mut().expect("clipboard initialized")) |
| 36 | + })(); |
| 37 | + let _ = send.send(result); |
| 38 | + }) |
| 39 | + .map_err(|_| "Clipboard unavailable".to_owned())?; |
| 40 | + receive |
| 41 | + .await |
| 42 | + .map_err(|_| "Clipboard unavailable".to_owned())? |
| 43 | +} |
| 44 | + |
| 45 | +pub(crate) async fn write_image<R: tauri::Runtime>( |
| 46 | + app: &tauri::AppHandle<R>, |
| 47 | + width: usize, |
| 48 | + height: usize, |
| 49 | + bytes: Vec<u8>, |
| 50 | +) -> Result<(), String> { |
| 51 | + write(app, move |clipboard| { |
| 52 | + clipboard |
| 53 | + .set_image(arboard::ImageData { |
| 54 | + width, |
| 55 | + height, |
| 56 | + bytes: std::borrow::Cow::Owned(bytes), |
| 57 | + }) |
| 58 | + .map_err(|_| "Could not copy image".to_owned()) |
| 59 | + }) |
| 60 | + .await |
| 61 | +} |
| 62 | + |
| 63 | +/// WebKit rejects `navigator.clipboard` writes without transient user |
| 64 | +/// activation, and each host script evaluation (how Tauri delivers events and |
| 65 | +/// channel messages) clears it. A click that races host traffic then fails to |
| 66 | +/// copy, so macOS text copies go through the host clipboard instead. |
| 67 | +#[tauri::command] |
| 68 | +pub(crate) async fn clipboard_write_text<R: tauri::Runtime>( |
| 69 | + app: tauri::AppHandle<R>, |
| 70 | + text: String, |
| 71 | +) -> Result<(), String> { |
| 72 | + write(&app, move |clipboard| { |
| 73 | + clipboard |
| 74 | + .set_text(text) |
| 75 | + .map_err(|_| "Could not copy text".to_owned()) |
| 76 | + }) |
| 77 | + .await |
| 78 | +} |
0 commit comments