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), ¤t_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}
157
158/// The launches waiting, and the task waiting for one.
159#[derive(Default)]
160struct Arrivals(Mutex<(VecDeque<Launch>, Option<Waker>)>);
161
162impl Arrivals {
163 /// A later launch passed `arguments` on, from `current_dir`.
164 #[cfg_attr(
165 not(any(target_os = "linux", target_os = "windows")),
166 allow(
167 dead_code,
168 reason = "no later launch reaches this system's first instance"
169 )
170 )]
171 fn arrive(&self, arguments: Vec<OsString>, current_dir: PathBuf) {
172 let waker = {
173 let mut arrivals = self.locked();
174 arrivals.0.push_back(Launch {
175 arguments,
176 current_dir,
177 });
178 arrivals.1.take()
179 };
180 if let Some(waker) = waker {
181 waker.wake();
182 }
183 }
184
185 fn locked(&self) -> MutexGuard<'_, (VecDeque<Launch>, Option<Waker>)> {
186 self.0.lock().unwrap_or_else(PoisonError::into_inner)
187 }
188}
189
190struct NextLaunch<'a> {
191 arrivals: &'a Arrivals,
192}
193
194impl Future for NextLaunch<'_> {
195 type Output = Launch;
196
197 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Launch> {
198 let mut arrivals = self.arrivals.locked();
199 match arrivals.0.pop_front() {
200 Some(launch) => Poll::Ready(launch),
201 None => {
202 arrivals.1 = Some(cx.waker().clone());
203 Poll::Pending
204 }
205 }
206 }
207}
208
209/// This launch's arguments, and the folder it was started in.
210#[cfg_attr(
211 not(any(target_os = "linux", target_os = "windows")),
212 allow(
213 dead_code,
214 reason = "no later launch reaches this system's first instance"
215 )
216)]
217fn this_launch() -> (Vec<OsString>, PathBuf) {
218 (
219 std::env::args_os().skip(1).collect(),
220 std::env::current_dir().unwrap_or_default(),
221 )
222}
223
224#[cfg(test)]
225mod tests {
226 use super::*;
227
228 pub(crate) fn now<T>(future: impl Future<Output = T>) -> Option<T> {
229 let mut future = std::pin::pin!(future);
230 match future
231 .as_mut()
232 .poll(&mut Context::from_waker(Waker::noop()))
233 {
234 Poll::Ready(output) => Some(output),
235 Poll::Pending => None,
236 }
237 }
238
239 #[test]
240 fn a_later_launchs_arguments_arrive_unread() {
241 let arrivals = Arc::new(Arrivals::default());
242 let first = FirstInstance::new(Arc::clone(&arrivals), Box::new(()));
243 let mut launches = first.launches();
244 assert!(now(launches.next_launch()).is_none(), "nothing yet");
245 let arguments = ["phone", "--verbose", "notes.txt"]
246 .map(OsString::from)
247 .to_vec();
248 arrivals.arrive(arguments.clone(), PathBuf::from("/home/me"));
249 assert_eq!(
250 now(launches.next_launch()),
251 Some(Launch {
252 arguments,
253 current_dir: PathBuf::from("/home/me"),
254 })
255 );
256 }
257}