Skip to main content

waft_single_instance/
lib.rs

1//! One instance of an app: a later launch hands its command line to the instance already running,
2//! and quits. An app's own pattern rather than the platform's, as Electron's
3//! `requestSingleInstanceLock` and Tauri's single-instance plugin are, and opt-in.
4//!
5//! A later launch's arguments arrive as the strings they are, unread, with the folder it was
6//! started in: which of them are files is the app's to say, as it says for its own launch's.
7//!
8//! Each system has its own way: Linux's session bus, where the first instance owns the app's id as
9//! its name and a later launch calls it; Windows' named mutex, which tells a later launch it is
10//! second, and a named pipe it writes its arguments to; macOS keeps one instance itself, handing a
11//! later open to the running app as an open request, so every launch there is the first, as on the
12//! phones and the web.
13//!
14//! An app reads its own launch's command line, hears the later launches' through
15//! [`FirstInstance::launches`], and hands the files it decides they name to
16//! `App::open_requested`, where the platform's own open requests also arrive
17//! (`App::set_open_requested_handler`): those bring the files the system itself hands over, and on
18//! macOS every later open. All of them reach the same code:
19//!
20//! ```ignore
21//! use std::ffi::OsString;
22//! use std::path::Path;
23//! use std::rc::Rc;
24//!
25//! use waft::ui::{OpenRequest, PickedFile};
26//! use waft::{App, run_app};
27//! use waft_single_instance::{SingleInstance, single_instance};
28//!
29//! #[waft::main]
30//! fn main(app: &mut App) {
31//!     let first = match single_instance("com.example.notes") {
32//!         Ok(SingleInstance::First(first)) => Some(first),
33//!         // The first instance has this launch's command line.
34//!         Ok(SingleInstance::Second) => std::process::exit(0),
35//!         Err(_) => None,
36//!     };
37//!     app.set_open_requested_handler(Some(Rc::new(open)));
38//!     let current_dir = std::env::current_dir().unwrap_or_default();
39//!     let launch = files_named(std::env::args_os().skip(1), &current_dir);
40//!     if !launch.is_empty() {
41//!         app.open_requested(launch);
42//!     }
43//!     if let Some(first) = first {
44//!         let mut launches = first.launches();
45//!         app.spawn(async move |cx| {
46//!             loop {
47//!                 let launch = launches.next_launch().await;
48//!                 let request = files_named(launch.arguments, &launch.current_dir);
49//!                 cx.update(|app| app.open_requested(request));
50//!             }
51//!         });
52//!     }
53//!     run_app(app, home());
54//! }
55//!
56//! /// The files this app's command line names: each of its arguments, in the folder it was
57//! /// started in.
58//! fn files_named(arguments: impl IntoIterator<Item = OsString>, current_dir: &Path) -> OpenRequest {
59//!     let files = arguments.into_iter().map(|argument| PickedFile::Path(current_dir.join(argument)));
60//!     OpenRequest { files: files.collect(), links: Vec::new() }
61//! }
62//!
63//! /// Shows the request's files and links; an empty request asks the app to show itself.
64//! fn open(app: &mut App, request: OpenRequest) {
65//!     // ...
66//! }
67//! ```
68//!
69//! The invariant: the first instance keeps its claim as long as its stream lives, so a launch
70//! while it runs is always second.
71
72use std::collections::VecDeque;
73use std::ffi::OsString;
74use std::future::Future;
75use std::io;
76use std::path::PathBuf;
77use std::pin::Pin;
78use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
79use std::task::{Context, Poll, Waker};
80
81#[cfg(target_os = "linux")]
82mod dbus;
83#[cfg(target_os = "windows")]
84mod windows;
85
86/// Whether this launch is the app's only instance.
87pub enum SingleInstance {
88    /// No other instance runs: this one is the app, and hears the later launches.
89    First(FirstInstance),
90    /// Another instance runs, and has been handed this launch's command line: this one should
91    /// quit.
92    Second,
93}
94
95/// Claims to be the one instance of the app `id`, a reverse-DNS name such as
96/// `com.example.notes`, or, where another instance holds the claim, hands it this launch's
97/// arguments. An error leaves the app to run as though alone.
98pub fn single_instance(id: &str) -> io::Result<SingleInstance> {
99    #[cfg(target_os = "linux")]
100    return dbus::claim(id);
101    #[cfg(target_os = "windows")]
102    return windows::claim(id);
103    #[cfg(not(any(target_os = "linux", target_os = "windows")))]
104    {
105        let _ = id;
106        Ok(SingleInstance::First(FirstInstance::new(
107            Arc::default(),
108            Box::new(()),
109        )))
110    }
111}
112
113/// The app's only instance, holding its claim.
114pub struct FirstInstance {
115    arrivals: Arc<Arrivals>,
116    /// What holds the claim: the mutex and the pipe's thread, or the name on the bus.
117    _claim: Box<dyn Send>,
118}
119
120impl FirstInstance {
121    /// The first instance, hearing later launches through `arrivals` while `claim` holds.
122    fn new(arrivals: Arc<Arrivals>, claim: Box<dyn Send>) -> FirstInstance {
123        FirstInstance {
124            arrivals,
125            _claim: claim,
126        }
127    }
128
129    /// The later launches, as they come, holding the claim as long as it lives.
130    pub fn launches(self) -> LaterLaunches {
131        LaterLaunches { first: self }
132    }
133}
134
135/// The launches after the first instance's, each passed on to it.
136pub struct LaterLaunches {
137    first: FirstInstance,
138}
139
140impl LaterLaunches {
141    /// The next launch passed on; it waits until one comes.
142    pub fn next_launch(&mut self) -> impl Future<Output = Launch> + '_ {
143        NextLaunch {
144            arrivals: &self.first.arrivals,
145        }
146    }
147}
148
149/// A later launch: its arguments, without the program's name, as the strings the system gave it,
150/// and the folder it was started in, which relative paths are in. A launch with no arguments asks
151/// the app to show itself again.
152#[derive(Clone, Debug, PartialEq, Eq)]
153pub struct Launch {
154    pub arguments: Vec<OsString>,
155    pub current_dir: PathBuf,
156    /// On Linux, the XDG activation token the desktop gave the launch (`XDG_ACTIVATION_TOKEN`,
157    /// or X11's `DESKTOP_STARTUP_ID`), with which the window the app shows for it may take the
158    /// focus: `LinuxWindowConfig::activation_token` for a window it opens, `Linux::activate` for
159    /// one already open. A desktop gives one only to a launch from a desktop entry with
160    /// `StartupNotify=true`. `None` elsewhere: on Windows the launch hands the first instance its
161    /// right to the foreground itself.
162    pub activation_token: Option<String>,
163}
164
165/// The launches waiting, and the task waiting for one.
166#[derive(Default)]
167struct Arrivals(Mutex<(VecDeque<Launch>, Option<Waker>)>);
168
169impl Arrivals {
170    /// A later launch passed itself on.
171    #[cfg_attr(
172        not(any(target_os = "linux", target_os = "windows")),
173        allow(
174            dead_code,
175            reason = "no later launch reaches this system's first instance"
176        )
177    )]
178    fn arrive(&self, launch: Launch) {
179        let waker = {
180            let mut arrivals = self.locked();
181            arrivals.0.push_back(launch);
182            arrivals.1.take()
183        };
184        if let Some(waker) = waker {
185            waker.wake();
186        }
187    }
188
189    fn locked(&self) -> MutexGuard<'_, (VecDeque<Launch>, Option<Waker>)> {
190        self.0.lock().unwrap_or_else(PoisonError::into_inner)
191    }
192}
193
194struct NextLaunch<'a> {
195    arrivals: &'a Arrivals,
196}
197
198impl Future for NextLaunch<'_> {
199    type Output = Launch;
200
201    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Launch> {
202        let mut arrivals = self.arrivals.locked();
203        match arrivals.0.pop_front() {
204            Some(launch) => Poll::Ready(launch),
205            None => {
206                arrivals.1 = Some(cx.waker().clone());
207                Poll::Pending
208            }
209        }
210    }
211}
212
213/// This launch's arguments, and the folder it was started in.
214#[cfg_attr(
215    not(any(target_os = "linux", target_os = "windows")),
216    allow(
217        dead_code,
218        reason = "no later launch reaches this system's first instance"
219    )
220)]
221fn this_launch() -> (Vec<OsString>, PathBuf) {
222    (
223        std::env::args_os().skip(1).collect(),
224        std::env::current_dir().unwrap_or_default(),
225    )
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231
232    pub(crate) fn now<T>(future: impl Future<Output = T>) -> Option<T> {
233        let mut future = std::pin::pin!(future);
234        match future
235            .as_mut()
236            .poll(&mut Context::from_waker(Waker::noop()))
237        {
238            Poll::Ready(output) => Some(output),
239            Poll::Pending => None,
240        }
241    }
242
243    #[test]
244    fn a_later_launchs_arguments_arrive_unread() {
245        let arrivals = Arc::new(Arrivals::default());
246        let first = FirstInstance::new(Arc::clone(&arrivals), Box::new(()));
247        let mut launches = first.launches();
248        assert!(now(launches.next_launch()).is_none(), "nothing yet");
249        let launch = Launch {
250            arguments: ["phone", "--verbose", "notes.txt"]
251                .map(OsString::from)
252                .to_vec(),
253            current_dir: PathBuf::from("/home/me"),
254            activation_token: Some("gnome-shell/Notes/2313-3_TIME121955272".to_owned()),
255        };
256        arrivals.arrive(launch.clone());
257        assert_eq!(now(launches.next_launch()), Some(launch));
258    }
259}