#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum LoginItemStatus {
Enabled,
Disabled,
RequiresApproval,
#[default]
Unavailable,
}
#[derive(Debug)]
#[non_exhaustive]
pub enum LaunchAtLoginError {
Unavailable,
System(std::io::Error),
Denied,
}
impl std::fmt::Display for LaunchAtLoginError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Unavailable => f.write_str(
"this run of the app cannot launch at login: only standalone desktop apps \
can, and not under `nsh run`",
),
Self::System(error) => write!(f, "launch at login could not be changed: {error}"),
Self::Denied => f.write_str(
"launching at login is not granted: add `\"application\": true` to \
capabilities in nsh.json",
),
}
}
}
impl std::error::Error for LaunchAtLoginError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::System(error) => Some(error),
Self::Unavailable | Self::Denied => None,
}
}
}
impl From<std::io::Error> for LaunchAtLoginError {
fn from(error: std::io::Error) -> Self {
Self::System(error)
}
}
pub trait LoginItemBackend: Send + Sync {
fn status(&self) -> std::io::Result<LoginItemStatus>;
fn set(&self, enabled: bool) -> std::io::Result<LoginItemStatus>;
}
pub(crate) struct LoginItems {
backend: std::sync::Arc<dyn LoginItemBackend>,
#[cfg(not(target_arch = "wasm32"))]
worker: Option<std::sync::mpsc::Sender<Call>>,
}
#[cfg(not(target_arch = "wasm32"))]
type Call = (
Option<bool>,
tokio::sync::oneshot::Sender<std::io::Result<LoginItemStatus>>,
);
impl LoginItems {
pub(crate) fn new(backend: std::sync::Arc<dyn LoginItemBackend>) -> Self {
Self {
backend,
#[cfg(not(target_arch = "wasm32"))]
worker: None,
}
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn call(
&mut self,
enabled: Option<bool>,
) -> impl Future<Output = std::io::Result<LoginItemStatus>> + 'static {
let (tx, rx) = tokio::sync::oneshot::channel();
let sent = self
.worker()
.is_some_and(|worker| worker.send((enabled, tx)).is_ok());
async move {
if !sent {
return Err(std::io::Error::other(
"cannot start the login item's thread",
));
}
rx.await.unwrap_or_else(|_| {
Err(std::io::Error::other(
"the login item's thread stopped before it answered",
))
})
}
}
#[cfg(target_arch = "wasm32")]
pub(crate) fn call(
&mut self,
enabled: Option<bool>,
) -> impl Future<Output = std::io::Result<LoginItemStatus>> + 'static {
let result = match enabled {
None => self.backend.status(),
Some(enabled) => self.backend.set(enabled),
};
std::future::ready(result)
}
#[cfg(not(target_arch = "wasm32"))]
fn worker(&mut self) -> Option<&std::sync::mpsc::Sender<Call>> {
if self.worker.is_none() {
let (tx, rx) = std::sync::mpsc::channel::<Call>();
let backend = self.backend.clone();
std::thread::Builder::new()
.name("nsh-login-item".into())
.spawn(move || {
for (enabled, reply) in rx {
let result =
std::panic::catch_unwind(std::panic::AssertUnwindSafe(
|| match enabled {
None => backend.status(),
Some(enabled) => backend.set(enabled),
},
))
.unwrap_or_else(|_| {
Err(std::io::Error::other("the login item's backend panicked"))
});
let _ = reply.send(result);
}
})
.map_err(|e| log::error!("cannot start the login item's thread: {e}"))
.ok()?;
self.worker = Some(tx);
}
self.worker.as_ref()
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use std::sync::{Arc, Mutex};
use super::*;
#[derive(Default)]
struct Fake {
calls: Mutex<Vec<Option<bool>>>,
enabled: Mutex<bool>,
}
impl LoginItemBackend for Fake {
fn status(&self) -> std::io::Result<LoginItemStatus> {
self.calls.lock().unwrap().push(None);
Ok(if *self.enabled.lock().unwrap() {
LoginItemStatus::Enabled
} else {
LoginItemStatus::Disabled
})
}
fn set(&self, enabled: bool) -> std::io::Result<LoginItemStatus> {
std::thread::sleep(std::time::Duration::from_millis(if enabled {
30
} else {
0
}));
self.calls.lock().unwrap().push(Some(enabled));
*self.enabled.lock().unwrap() = enabled;
self.status()
}
}
fn block_on<T>(future: impl Future<Output = T>) -> T {
tokio::runtime::Builder::new_current_thread()
.build()
.unwrap()
.block_on(future)
}
#[test]
fn calls_run_in_the_order_they_came_on_one_thread() {
let fake = Arc::new(Fake::default());
let mut items = LoginItems::new(fake.clone());
let on = items.call(Some(true));
let off = items.call(Some(false));
let read = items.call(None);
assert_eq!(block_on(read).unwrap(), LoginItemStatus::Disabled);
assert_eq!(block_on(on).unwrap(), LoginItemStatus::Enabled);
assert_eq!(block_on(off).unwrap(), LoginItemStatus::Disabled);
assert_eq!(
*fake.calls.lock().unwrap(),
[Some(true), None, Some(false), None, None]
);
}
struct Panicking(Mutex<bool>);
impl LoginItemBackend for Panicking {
fn status(&self) -> std::io::Result<LoginItemStatus> {
Ok(LoginItemStatus::Disabled)
}
fn set(&self, _: bool) -> std::io::Result<LoginItemStatus> {
if !std::mem::replace(&mut *self.0.lock().unwrap(), true) {
panic!("a backend's bug");
}
Ok(LoginItemStatus::Enabled)
}
}
#[test]
fn a_backend_that_panics_fails_that_call_only() {
let mut items = LoginItems::new(Arc::new(Panicking(Mutex::new(false))));
let first = items.call(Some(true));
let second = items.call(Some(true));
let error = block_on(first).unwrap_err();
assert!(error.to_string().contains("panicked"), "{error}");
assert_eq!(block_on(second).unwrap(), LoginItemStatus::Enabled);
assert_eq!(
block_on(items.call(None)).unwrap(),
LoginItemStatus::Disabled
);
}
}