tauri_plugin_clipboard_manager/
lib.rs

1// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2// SPDX-License-Identifier: Apache-2.0
3// SPDX-License-Identifier: MIT
4
5//! Read and write to the system clipboard.
6
7#![doc(
8    html_logo_url = "https://github.com/tauri-apps/tauri/raw/dev/app-icon.png",
9    html_favicon_url = "https://github.com/tauri-apps/tauri/raw/dev/app-icon.png"
10)]
11
12use tauri::{
13    plugin::{Builder, TauriPlugin},
14    Manager, RunEvent, Runtime,
15};
16
17#[cfg(desktop)]
18mod desktop;
19#[cfg(mobile)]
20mod mobile;
21
22mod commands;
23mod error;
24
25pub use error::{Error, Result};
26
27#[cfg(desktop)]
28pub use desktop::Clipboard;
29#[cfg(mobile)]
30pub use mobile::Clipboard;
31
32/// Extensions to [`tauri::App`], [`tauri::AppHandle`], [`tauri::WebviewWindow`], [`tauri::Webview`] and [`tauri::Window`] to access the clipboard APIs.
33pub trait ClipboardExt<R: Runtime> {
34    fn clipboard(&self) -> &Clipboard<R>;
35}
36
37impl<R: Runtime, T: Manager<R>> crate::ClipboardExt<R> for T {
38    fn clipboard(&self) -> &Clipboard<R> {
39        self.state::<Clipboard<R>>().inner()
40    }
41}
42
43/// Initializes the plugin.
44pub fn init<R: Runtime>() -> TauriPlugin<R> {
45    Builder::new("clipboard-manager")
46        .invoke_handler(tauri::generate_handler![
47            commands::write_text,
48            commands::read_text,
49            commands::read_image,
50            commands::write_image,
51            commands::write_html,
52            commands::clear
53        ])
54        .setup(|app, api| {
55            #[cfg(mobile)]
56            let clipboard = mobile::init(app, api)?;
57            #[cfg(desktop)]
58            let clipboard = desktop::init(app, api)?;
59            app.manage(clipboard);
60            Ok(())
61        })
62        .on_event(|_app, _event| {
63            #[cfg(desktop)]
64            if let RunEvent::Exit = _event {
65                _app.clipboard().cleanup();
66            }
67        })
68        .build()
69}