use std::{
cell::{Cell, RefCell},
rc::{Rc, Weak},
};
use crate::{
Command, ROOT_ID,
desktop::DesktopCommand,
element::{
CallCx, Callback, JsHost, JsIn, JsObject, JsOwned, JsValue, Local, ModuleCx, PropEnum,
PropError, Ret, Stop, System, TsTypes, module, task::Action,
},
single_instance::SecondInstance,
};
fn desktop(cx: &mut ModuleCx, command: DesktopCommand) {
cx.act(Action::Command(
ROOT_ID,
Command::Desktop(Box::new(command)),
));
}
#[module]
pub(crate) struct Application;
#[module]
impl Application {
pub(crate) fn quit(cx: &mut ModuleCx) {
desktop(cx, DesktopCommand::Quit);
}
pub(crate) fn restart(cx: &mut ModuleCx) {
desktop(cx, DesktopCommand::Restart);
}
#[overload(fn(event: ApplicationSecondInstanceEvent, #[args(launch)] listener: Callback<ApplicationSecondInstance>) -> Stop)]
#[overload(fn(event: ApplicationOpenFilesEvent, #[args(files)] listener: Callback<ApplicationOpenFiles>) -> Stop)]
#[overload(fn(event: ApplicationQuitEvent, listener: Callback<()>) -> Stop)]
pub(crate) fn on(
event: ApplicationEvent,
#[args(payload)] listener: Callback<Payload>,
sys: System,
cx: CallCx<'_>,
) -> Stop {
match event {
ApplicationEvent::SecondInstance => second_instance(listener, &sys, cx),
ApplicationEvent::OpenFiles => open_files(listener, &sys, cx),
ApplicationEvent::Quit => quit(listener, &sys, cx),
}
}
}
fn second_instance(listener: Callback<Payload>, sys: &System, cx: CallCx<'_>) -> Stop {
let launches = sys.locals.get::<Launches>();
let id = launches.next.get();
launches.next.set(id.wrapping_add(1));
for launch in launches.unheard.take() {
listener.post(Payload::SecondInstance(launch.into()));
}
launches.listeners.borrow_mut().push((id, listener));
if !launches.started.replace(true) {
cx.start(deliver(Rc::downgrade(&launches)));
}
let launches = Rc::downgrade(&launches);
Stop::new(move || {
if let Some(launches) = launches.upgrade() {
launches.listeners.borrow_mut().retain(|(i, _)| *i != id);
}
})
}
fn open_files(listener: Callback<Payload>, sys: &System, cx: CallCx<'_>) -> Stop {
let files = sys.locals.get::<Files>();
let id = files.next.get();
files.next.set(id.wrapping_add(1));
let unheard = files.unheard.take();
if !unheard.is_empty() {
listener.post(Payload::OpenFiles(ApplicationOpenFiles::new(unheard)));
}
files.listeners.borrow_mut().push((id, listener));
if !files.started.replace(true) {
cx.start(deliver_files(Rc::downgrade(&files)));
}
let files = Rc::downgrade(&files);
Stop::new(move || {
if let Some(files) = files.upgrade() {
files.listeners.borrow_mut().retain(|(i, _)| *i != id);
}
})
}
fn quit(listener: Callback<Payload>, sys: &System, cx: CallCx<'_>) -> Stop {
let quits = sys.locals.get::<Quits>();
let id = quits.next.get();
quits.next.set(id.wrapping_add(1));
quits.listeners.borrow_mut().push((id, listener));
if !quits.started.replace(true) {
cx.start(hold(Rc::downgrade(&quits)));
}
let quits = Rc::downgrade(&quits);
Stop::new(move || {
if let Some(quits) = quits.upgrade() {
quits.listeners.borrow_mut().retain(|(i, _)| *i != id);
}
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
pub(crate) enum ApplicationEvent {
#[default]
SecondInstance,
OpenFiles,
Quit,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PropEnum)]
pub(crate) enum ApplicationSecondInstanceEvent {
SecondInstance,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PropEnum)]
pub(crate) enum ApplicationQuitEvent {
Quit,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
pub(crate) enum ApplicationOpenFilesEvent {
#[default]
OpenFiles,
}
#[derive(Debug, Clone)]
pub(crate) enum Payload {
SecondInstance(ApplicationSecondInstance),
OpenFiles(ApplicationOpenFiles),
Quit,
}
impl JsValue for Payload {
fn ts_type(types: &mut TsTypes) -> String {
<ApplicationSecondInstance as JsValue>::ts_type(types)
}
fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
Err(value.expected("no value (a payload goes to JS only)"))
}
fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
match self {
Payload::SecondInstance(launch) => launch.to_js(host),
Payload::OpenFiles(files) => files.to_js(host),
Payload::Quit => Ret::into_js((), host),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, JsObject)]
pub(crate) struct ApplicationSecondInstance {
args: Vec<String>,
cwd: String,
}
impl From<SecondInstance> for ApplicationSecondInstance {
fn from(launch: SecondInstance) -> Self {
Self {
args: launch.args,
cwd: launch.cwd,
}
}
}
#[derive(Default)]
struct Launches {
listeners: RefCell<Vec<(u32, Callback<Payload>)>>,
next: Cell<u32>,
started: Cell<bool>,
unheard: RefCell<Vec<SecondInstance>>,
}
impl Local for Launches {
fn close(&self) {
self.listeners.borrow_mut().clear();
}
}
async fn deliver(launches: Weak<Launches>) {
loop {
let launch = crate::prelude::next_second_instance().await;
let Some(launches) = launches.upgrade() else {
return;
};
let listeners = launches.listeners.borrow();
if listeners.is_empty() {
let mut unheard = launches.unheard.borrow_mut();
if unheard.len() == crate::single_instance::MAX_PENDING {
unheard.remove(0);
}
unheard.push(launch);
continue;
}
for (_, listener) in &*listeners {
listener.post(Payload::SecondInstance(launch.clone().into()));
}
}
}
#[derive(Debug, Clone, Default, PartialEq, JsObject)]
pub(crate) struct ApplicationOpenFiles {
paths: Vec<String>,
}
impl ApplicationOpenFiles {
fn new(paths: Vec<std::path::PathBuf>) -> Self {
Self {
paths: paths
.into_iter()
.map(|p| p.to_string_lossy().into_owned())
.collect(),
}
}
}
#[derive(Default)]
struct Files {
listeners: RefCell<Vec<(u32, Callback<Payload>)>>,
next: Cell<u32>,
started: Cell<bool>,
unheard: RefCell<Vec<std::path::PathBuf>>,
}
impl Local for Files {
fn close(&self) {
self.listeners.borrow_mut().clear();
}
}
async fn deliver_files(files: Weak<Files>) {
loop {
let paths = crate::prelude::next_open_files().await;
let Some(files) = files.upgrade() else {
return;
};
let listeners = files.listeners.borrow();
if listeners.is_empty() {
let mut unheard = files.unheard.borrow_mut();
unheard.extend(paths);
let excess = unheard.len().saturating_sub(crate::file_type::MAX_PENDING);
unheard.drain(..excess);
continue;
}
let payload = ApplicationOpenFiles::new(paths);
for (_, listener) in &*listeners {
listener.post(Payload::OpenFiles(payload.clone()));
}
}
}
#[derive(Default)]
struct Quits {
listeners: RefCell<Vec<(u32, Callback<Payload>)>>,
next: Cell<u32>,
started: Cell<bool>,
}
impl Local for Quits {
fn close(&self) {
self.listeners.borrow_mut().clear();
}
}
async fn hold(quits: Weak<Quits>) {
let _subscription = crate::element::desktop::add_quit_listener(Rc::new(move || {
let calls: Vec<_> = quits
.upgrade()
.map(|quits| {
let listeners = quits.listeners.borrow();
listeners
.iter()
.map(|(_, listener)| listener.call_async(Payload::Quit))
.collect()
})
.unwrap_or_default();
Box::pin(async move {
for call in calls {
if let Err(message) = call.await {
log::error!(target: "js", "a quit listener failed: {message}");
}
}
})
}));
std::future::pending::<()>().await;
}