Skip to main content

tauri_plugin_single_instance/
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//! Ensure a single instance of your tauri app is running.
6//!
7//! ## Cargo features
8//!
9//! - **semver**: Allows the app with SemVer incompatible versions to run alongside each other.
10//! - **deep-link**: Trigger [`tauri-plugin-deep-link`](https://crates.io/crates/tauri-plugin-deep-link) event before invoking the single-instance callback.
11
12#![doc(
13    html_logo_url = "https://github.com/tauri-apps/tauri/raw/dev/app-icon.png",
14    html_favicon_url = "https://github.com/tauri-apps/tauri/raw/dev/app-icon.png"
15)]
16#![cfg(not(any(target_os = "android", target_os = "ios")))]
17
18use tauri::{AppHandle, Manager, Runtime, plugin::TauriPlugin};
19
20#[cfg(target_os = "windows")]
21#[path = "platform_impl/windows.rs"]
22mod platform_impl;
23#[cfg(target_os = "linux")]
24#[path = "platform_impl/linux.rs"]
25mod platform_impl;
26#[cfg(target_os = "macos")]
27#[path = "platform_impl/macos.rs"]
28mod platform_impl;
29
30#[cfg(feature = "semver")]
31mod semver_compat;
32
33pub(crate) type SingleInstanceCallback<R> =
34    dyn FnMut(&AppHandle<R>, Vec<String>, String) + Send + Sync + 'static;
35
36/// Initializes the plugin, calling `f` whenever a second instance of the app is started.
37///
38/// This is a shortcut for [`Builder::new`] with [`Builder::callback`] set to `f`, then
39/// [`Builder::build`]. Use [`Builder`] directly if you need to set a custom [`Builder::dbus_id`].
40///
41/// `f` is called with the app handle, the second instance's command line arguments
42/// (as collected by [`std::env::args_os`], so the first element is the executable path) and its
43/// current working directory. Arguments and the working directory that are not valid Unicode
44/// have their invalid parts replaced by U+FFFD. If the `deep-link` feature is enabled, the arguments are first
45/// forwarded to [`tauri-plugin-deep-link`](https://crates.io/crates/tauri-plugin-deep-link)
46/// before `f` runs.
47///
48/// The second instance never reaches [`tauri::Builder::run`]: it hands its arguments and working
49/// directory off to the first instance and exits immediately.
50pub fn init<R: Runtime, F: FnMut(&AppHandle<R>, Vec<String>, String) + Send + Sync + 'static>(
51    f: F,
52) -> TauriPlugin<R> {
53    Builder::new().callback(f).build()
54}
55
56/// Releases the resources this plugin uses to detect other instances (the named mutex on
57/// Windows, the D-Bus name on Linux or the Unix socket on macOS).
58///
59/// The plugin calls this automatically on [`tauri::RunEvent::Exit`], so you normally don't need
60/// to call it yourself. Call it manually before terminating the process through means that skip
61/// that event, such as [`std::process::exit`], so a future instance of the app isn't mistaken
62/// for a still-running one.
63pub fn destroy<R: Runtime, M: Manager<R>>(manager: &M) {
64    platform_impl::destroy(manager)
65}
66
67/// Builds the single-instance plugin.
68///
69/// Created with [`Builder::new`] and consumed by [`Builder::build`].
70pub struct Builder<R: Runtime> {
71    callback: Box<SingleInstanceCallback<R>>,
72    dbus_id: Option<String>,
73}
74
75impl<R: Runtime> Default for Builder<R> {
76    fn default() -> Self {
77        Self {
78            callback: Box::new(move |_app, _args, _| {
79                #[cfg(feature = "deep-link")]
80                if let Some(deep_link) = _app.try_state::<tauri_plugin_deep_link::DeepLink<R>>() {
81                    deep_link.handle_cli_arguments(_args.iter());
82                }
83            }),
84            dbus_id: None,
85        }
86    }
87}
88
89impl<R: Runtime> Builder<R> {
90    /// Creates a new builder with a no-op callback (or, when the `deep-link` feature is enabled,
91    /// a callback that only forwards the arguments to the deep-link plugin) and no custom D-Bus
92    /// ID. Use [`Builder::callback`] and [`Builder::dbus_id`] to configure it, then
93    /// [`Builder::build`] to create the plugin.
94    pub fn new() -> Self {
95        Default::default()
96    }
97
98    /// Function to call when a secondary instance was opened by the user and killed by the plugin.
99    /// If the `deep-link` feature is enabled, the plugin triggers the deep-link plugin before executing the callback.
100    pub fn callback<F: FnMut(&AppHandle<R>, Vec<String>, String) + Send + Sync + 'static>(
101        mut self,
102        mut f: F,
103    ) -> Self {
104        self.callback = Box::new(move |app, args, cwd| {
105            #[cfg(feature = "deep-link")]
106            if let Some(deep_link) = app.try_state::<tauri_plugin_deep_link::DeepLink<R>>() {
107                deep_link.handle_cli_arguments(args.iter());
108            }
109            f(app, args, cwd)
110        });
111        self
112    }
113
114    /// Set a custom D-Bus ID, used on Linux. The plugin will append a `.SingleInstance` subname.
115    /// For example `com.mycompany.myapp` will result in the plugin registering its D-Bus service on `com.mycompany.myapp.SingleInstance`.
116    /// Usually you want the same base ID across all components in your app.
117    ///
118    /// Defaults to the app's bundle identifier set in tauri.conf.json.
119    pub fn dbus_id(mut self, dbus_id: impl Into<String>) -> Self {
120        self.dbus_id = Some(dbus_id.into());
121        self
122    }
123
124    /// Builds the single-instance [`TauriPlugin`].
125    ///
126    /// Register it first among your app's plugins, since the plugins run in the order they were
127    /// added and a second instance must be detected before the rest of your setup runs.
128    pub fn build(self) -> TauriPlugin<R> {
129        platform_impl::init(
130            self.callback,
131            #[cfg(target_os = "linux")]
132            self.dbus_id,
133        )
134    }
135}