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`], so the first element is the executable path) and its
43/// current working directory. If the `deep-link` feature is enabled, the arguments are first
44/// forwarded to [`tauri-plugin-deep-link`](https://crates.io/crates/tauri-plugin-deep-link)
45/// before `f` runs.
46///
47/// The second instance never reaches [`tauri::Builder::run`]: it hands its arguments and working
48/// directory off to the first instance and exits immediately.
49pub fn init<R: Runtime, F: FnMut(&AppHandle<R>, Vec<String>, String) + Send + Sync + 'static>(
50    f: F,
51) -> TauriPlugin<R> {
52    Builder::new().callback(f).build()
53}
54
55/// Releases the resources this plugin uses to detect other instances (the named mutex on
56/// Windows, the D-Bus name on Linux or the Unix socket on macOS).
57///
58/// The plugin calls this automatically on [`tauri::RunEvent::Exit`], so you normally don't need
59/// to call it yourself. Call it manually before terminating the process through means that skip
60/// that event, such as [`std::process::exit`], so a future instance of the app isn't mistaken
61/// for a still-running one.
62pub fn destroy<R: Runtime, M: Manager<R>>(manager: &M) {
63    platform_impl::destroy(manager)
64}
65
66/// Builds the single-instance plugin.
67///
68/// Created with [`Builder::new`] and consumed by [`Builder::build`].
69pub struct Builder<R: Runtime> {
70    callback: Box<SingleInstanceCallback<R>>,
71    dbus_id: Option<String>,
72}
73
74impl<R: Runtime> Default for Builder<R> {
75    fn default() -> Self {
76        Self {
77            callback: Box::new(move |_app, _args, _| {
78                #[cfg(feature = "deep-link")]
79                if let Some(deep_link) = _app.try_state::<tauri_plugin_deep_link::DeepLink<R>>() {
80                    deep_link.handle_cli_arguments(_args.iter());
81                }
82            }),
83            dbus_id: None,
84        }
85    }
86}
87
88impl<R: Runtime> Builder<R> {
89    /// Creates a new builder with a no-op callback (or, when the `deep-link` feature is enabled,
90    /// a callback that only forwards the arguments to the deep-link plugin) and no custom D-Bus
91    /// ID. Use [`Builder::callback`] and [`Builder::dbus_id`] to configure it, then
92    /// [`Builder::build`] to create the plugin.
93    pub fn new() -> Self {
94        Default::default()
95    }
96
97    /// Function to call when a secondary instance was opened by the user and killed by the plugin.
98    /// If the `deep-link` feature is enabled, the plugin triggers the deep-link plugin before executing the callback.
99    pub fn callback<F: FnMut(&AppHandle<R>, Vec<String>, String) + Send + Sync + 'static>(
100        mut self,
101        mut f: F,
102    ) -> Self {
103        self.callback = Box::new(move |app, args, cwd| {
104            #[cfg(feature = "deep-link")]
105            if let Some(deep_link) = app.try_state::<tauri_plugin_deep_link::DeepLink<R>>() {
106                deep_link.handle_cli_arguments(args.iter());
107            }
108            f(app, args, cwd)
109        });
110        self
111    }
112
113    /// Set a custom D-Bus ID, used on Linux. The plugin will append a `.SingleInstance` subname.
114    /// For example `com.mycompany.myapp` will result in the plugin registering its D-Bus service on `com.mycompany.myapp.SingleInstance`.
115    /// Usually you want the same base ID across all components in your app.
116    ///
117    /// Defaults to the app's bundle identifier set in tauri.conf.json.
118    pub fn dbus_id(mut self, dbus_id: impl Into<String>) -> Self {
119        self.dbus_id = Some(dbus_id.into());
120        self
121    }
122
123    /// Builds the single-instance [`TauriPlugin`].
124    ///
125    /// Register it first among your app's plugins, since the plugins run in the order they were
126    /// added and a second instance must be detected before the rest of your setup runs.
127    pub fn build(self) -> TauriPlugin<R> {
128        platform_impl::init(
129            self.callback,
130            #[cfg(target_os = "linux")]
131            self.dbus_id,
132        )
133    }
134}