use std::collections::VecDeque;
use std::ffi::OsString;
use std::future::Future;
use std::io;
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::task::{Context, Poll, Waker};
#[cfg(target_os = "linux")]
mod dbus;
#[cfg(target_os = "windows")]
mod windows;
pub enum SingleInstance {
First(FirstInstance),
Second,
}
pub fn single_instance(id: &str) -> io::Result<SingleInstance> {
#[cfg(target_os = "linux")]
return dbus::claim(id);
#[cfg(target_os = "windows")]
return windows::claim(id);
#[cfg(not(any(target_os = "linux", target_os = "windows")))]
{
let _ = id;
Ok(SingleInstance::First(FirstInstance::new(
Arc::default(),
Box::new(()),
)))
}
}
pub struct FirstInstance {
arrivals: Arc<Arrivals>,
_claim: Box<dyn Send>,
}
impl FirstInstance {
fn new(arrivals: Arc<Arrivals>, claim: Box<dyn Send>) -> FirstInstance {
FirstInstance {
arrivals,
_claim: claim,
}
}
pub fn launches(self) -> LaterLaunches {
LaterLaunches { first: self }
}
}
pub struct LaterLaunches {
first: FirstInstance,
}
impl LaterLaunches {
pub fn next_launch(&mut self) -> impl Future<Output = Launch> + '_ {
NextLaunch {
arrivals: &self.first.arrivals,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Launch {
pub arguments: Vec<OsString>,
pub current_dir: PathBuf,
}
#[derive(Default)]
struct Arrivals(Mutex<(VecDeque<Launch>, Option<Waker>)>);
impl Arrivals {
#[cfg_attr(
not(any(target_os = "linux", target_os = "windows")),
allow(
dead_code,
reason = "no later launch reaches this system's first instance"
)
)]
fn arrive(&self, arguments: Vec<OsString>, current_dir: PathBuf) {
let waker = {
let mut arrivals = self.locked();
arrivals.0.push_back(Launch {
arguments,
current_dir,
});
arrivals.1.take()
};
if let Some(waker) = waker {
waker.wake();
}
}
fn locked(&self) -> MutexGuard<'_, (VecDeque<Launch>, Option<Waker>)> {
self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
}
struct NextLaunch<'a> {
arrivals: &'a Arrivals,
}
impl Future for NextLaunch<'_> {
type Output = Launch;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Launch> {
let mut arrivals = self.arrivals.locked();
match arrivals.0.pop_front() {
Some(launch) => Poll::Ready(launch),
None => {
arrivals.1 = Some(cx.waker().clone());
Poll::Pending
}
}
}
}
#[cfg_attr(
not(any(target_os = "linux", target_os = "windows")),
allow(
dead_code,
reason = "no later launch reaches this system's first instance"
)
)]
fn this_launch() -> (Vec<OsString>, PathBuf) {
(
std::env::args_os().skip(1).collect(),
std::env::current_dir().unwrap_or_default(),
)
}
#[cfg(test)]
mod tests {
use super::*;
pub(crate) fn now<T>(future: impl Future<Output = T>) -> Option<T> {
let mut future = std::pin::pin!(future);
match future
.as_mut()
.poll(&mut Context::from_waker(Waker::noop()))
{
Poll::Ready(output) => Some(output),
Poll::Pending => None,
}
}
#[test]
fn a_later_launchs_arguments_arrive_unread() {
let arrivals = Arc::new(Arrivals::default());
let first = FirstInstance::new(Arc::clone(&arrivals), Box::new(()));
let mut launches = first.launches();
assert!(now(launches.next_launch()).is_none(), "nothing yet");
let arguments = ["phone", "--verbose", "notes.txt"]
.map(OsString::from)
.to_vec();
arrivals.arrive(arguments.clone(), PathBuf::from("/home/me"));
assert_eq!(
now(launches.next_launch()),
Some(Launch {
arguments,
current_dir: PathBuf::from("/home/me"),
})
);
}
}