|
| 1 | +// Copyright 2019-2021 Tauri Programme within The Commons Conservancy |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | +// SPDX-License-Identifier: MIT |
| 4 | + |
| 5 | +//! Clipboard implementation. |
| 6 | +
|
| 7 | +use crate::{getter, Context, Message}; |
| 8 | + |
| 9 | +use std::sync::{ |
| 10 | + mpsc::{channel, Sender}, |
| 11 | + Arc, Mutex, |
| 12 | +}; |
| 13 | + |
| 14 | +use tauri_runtime::{ClipboardManager, Result, UserEvent}; |
| 15 | +pub use wry::application::clipboard::Clipboard; |
| 16 | + |
| 17 | +#[derive(Debug, Clone)] |
| 18 | +pub enum ClipboardMessage { |
| 19 | + WriteText(String, Sender<()>), |
| 20 | + ReadText(Sender<Option<String>>), |
| 21 | +} |
| 22 | + |
| 23 | +#[derive(Debug, Clone)] |
| 24 | +pub struct ClipboardManagerWrapper<T: UserEvent> { |
| 25 | + pub context: Context<T>, |
| 26 | +} |
| 27 | + |
| 28 | +// SAFETY: this is safe since the `Context` usage is guarded on `send_user_message`. |
| 29 | +#[allow(clippy::non_send_fields_in_send_ty)] |
| 30 | +unsafe impl<T: UserEvent> Sync for ClipboardManagerWrapper<T> {} |
| 31 | + |
| 32 | +impl<T: UserEvent> ClipboardManager for ClipboardManagerWrapper<T> { |
| 33 | + fn read_text(&self) -> Result<Option<String>> { |
| 34 | + let (tx, rx) = channel(); |
| 35 | + getter!(self, rx, Message::Clipboard(ClipboardMessage::ReadText(tx))) |
| 36 | + } |
| 37 | + |
| 38 | + fn write_text<V: Into<String>>(&mut self, text: V) -> Result<()> { |
| 39 | + let (tx, rx) = channel(); |
| 40 | + getter!( |
| 41 | + self, |
| 42 | + rx, |
| 43 | + Message::Clipboard(ClipboardMessage::WriteText(text.into(), tx)) |
| 44 | + )?; |
| 45 | + Ok(()) |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +pub fn handle_clipboard_message( |
| 50 | + message: ClipboardMessage, |
| 51 | + clipboard_manager: &Arc<Mutex<Clipboard>>, |
| 52 | +) { |
| 53 | + match message { |
| 54 | + ClipboardMessage::WriteText(text, tx) => { |
| 55 | + clipboard_manager.lock().unwrap().write_text(text); |
| 56 | + tx.send(()).unwrap(); |
| 57 | + } |
| 58 | + ClipboardMessage::ReadText(tx) => tx |
| 59 | + .send(clipboard_manager.lock().unwrap().read_text()) |
| 60 | + .unwrap(), |
| 61 | + } |
| 62 | +} |
0 commit comments