use core::cell::{Ref, RefCell};
use core::fmt;
use core::future::Future;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use super::runtime::{self, MaybeSend};
use super::{lock, with_registry};
type Slot<T, E> = Arc<Mutex<Option<Result<T, E>>>>;
struct State<T, E> {
running: Vec<Slot<T, E>>,
result: Option<Result<T, E>>,
}
pub struct Command<T, E> {
state: Rc<RefCell<State<T, E>>>,
refreshes: Vec<String>,
}
pub fn command<T: MaybeSend + 'static, E: MaybeSend + 'static>() -> Command<T, E> {
Command::default()
}
impl<T: MaybeSend + 'static, E: MaybeSend + 'static> Command<T, E> {
#[must_use]
pub fn refreshes(mut self, key: impl Into<String>) -> Self {
self.refreshes.push(key.into());
self
}
pub fn run(&self, future: impl Future<Output = Result<T, E>> + MaybeSend + 'static) {
let slot: Slot<T, E> = Arc::default();
let refreshes = self.refreshes.clone();
let (invalidated, ctx) =
with_registry(|registry| (Arc::clone(®istry.invalidated), registry.ctx.clone()));
runtime::spawn_detached({
let slot = Arc::clone(&slot);
async move {
let result = future.await;
if result.is_ok() {
lock(&invalidated).extend(refreshes);
}
*lock(&slot) = Some(result);
if let Some(ctx) = ctx {
ctx.request_repaint();
}
}
});
let mut state = self.state.borrow_mut();
state.result = None;
state.running.push(slot);
}
pub fn is_pending(&self) -> bool {
!self.sync().running.is_empty()
}
pub fn result(&self) -> Option<Ref<'_, Result<T, E>>> {
Ref::filter_map(self.sync(), |state| state.result.as_ref()).ok()
}
pub fn output(&self) -> Option<Ref<'_, T>> {
Ref::filter_map(self.sync(), |state| state.result.as_ref()?.as_ref().ok()).ok()
}
pub fn error(&self) -> Option<Ref<'_, E>> {
Ref::filter_map(self.sync(), |state| state.result.as_ref()?.as_ref().err()).ok()
}
pub fn take_result(&self) -> Option<Result<T, E>> {
drop(self.sync());
self.state.borrow_mut().result.take()
}
fn sync(&self) -> Ref<'_, State<T, E>> {
let mut state = self.state.borrow_mut();
let State { running, result } = &mut *state;
running.retain(|slot| match lock(slot).take() {
Some(done) => {
*result = Some(done);
false
}
None => true,
});
drop(state);
self.state.borrow()
}
}
impl<T, E> Default for Command<T, E> {
fn default() -> Self {
Self {
state: Rc::new(RefCell::new(State {
running: Vec::new(),
result: None,
})),
refreshes: Vec::new(),
}
}
}
impl<T, E> Clone for Command<T, E> {
fn clone(&self) -> Self {
Self {
state: Rc::clone(&self.state),
refreshes: self.refreshes.clone(),
}
}
}
impl<T: fmt::Debug, E: fmt::Debug> fmt::Debug for Command<T, E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let state = self.state.borrow();
f.debug_struct("Command")
.field("pending", &!state.running.is_empty())
.field("result", &state.result)
.field("refreshes", &self.refreshes)
.finish()
}
}