Skip to main content

egui_kit/remote/
command.rs

1//! [`Command`]: async mutations.
2
3use core::cell::{Ref, RefCell};
4use core::fmt;
5use core::future::Future;
6use std::rc::Rc;
7use std::sync::{Arc, Mutex};
8
9use super::runtime::{self, MaybeSend};
10use super::{lock, request_repaint, shared_context, with_registry};
11
12/// Where a run puts its result.
13type Slot<T, E> = Arc<Mutex<Option<Result<T, E>>>>;
14
15struct State<T, E> {
16    running: Vec<Slot<T, E>>,
17    result: Option<Result<T, E>>,
18}
19
20/// An async mutation: [run](Self::run) it with a future, and see whether it's
21/// [pending](Self::is_pending) and how it ended.
22///
23/// Create one with [`command`] (or `Default`), keep it where the views can use it and run it
24/// as often as needed. Clones share its state. A run continues when the command is dropped.
25/// See the [module docs](crate::remote).
26///
27/// ```
28/// # use egui_kit::remote::Command;
29/// # async fn save(_text: String) -> Result<(), String> { Ok(()) }
30/// #[derive(Default)]
31/// struct Editor {
32///     text: String,
33///     save: Command<(), String>,
34/// }
35///
36/// fn ui(ui: &mut egui::Ui, editor: &mut Editor) {
37///     ui.text_edit_multiline(&mut editor.text);
38///     if ui.add_enabled(!editor.save.is_pending(), egui::Button::new("Save")).clicked() {
39///         editor.save.run(save(editor.text.clone()));
40///     }
41///     match editor.save.take_result() {
42///         Some(Ok(())) => { /* close the editor */ }
43///         Some(Err(error)) => { /* show the error in a toast */ }
44///         None => {}
45///     }
46/// }
47/// ```
48pub struct Command<T, E> {
49    state: Rc<RefCell<State<T, E>>>,
50    refreshes: Vec<String>,
51}
52
53/// A [`Command`].
54pub fn command<T: MaybeSend + 'static, E: MaybeSend + 'static>() -> Command<T, E> {
55    Command::default()
56}
57
58impl<T: MaybeSend + 'static, E: MaybeSend + 'static> Command<T, E> {
59    /// Once a run succeeded, invalidates the dependency `key`, like
60    /// [`Nav::invalidate`](crate::extract::Nav::invalidate): the queries that
61    /// [depend](super::Query::depends) on it refetch, and the loads that
62    /// [depend](crate::page::Page::depends) on it rerun. Call it once per dependency; a failed
63    /// run invalidates nothing. See [Keys, dependencies and refreshes](crate::remote#keys-dependencies-and-refreshes).
64    #[must_use]
65    pub fn refreshes(mut self, key: impl Into<String>) -> Self {
66        self.refreshes.push(key.into());
67        self
68    }
69
70    /// Runs `future`, forgetting how the last run ended.
71    pub fn run(&self, future: impl Future<Output = Result<T, E>> + MaybeSend + 'static) {
72        let slot: Slot<T, E> = Arc::default();
73        let refreshes = self.refreshes.clone();
74        let invalidated = with_registry(|registry| Arc::clone(&registry.invalidated));
75        let ctx = shared_context();
76        runtime::spawn_detached({
77            let slot = Arc::clone(&slot);
78            async move {
79                let result = future.await;
80                if result.is_ok() {
81                    lock(&invalidated).extend(refreshes);
82                }
83                *lock(&slot) = Some(result);
84                request_repaint(&ctx);
85            }
86        });
87        let mut state = self.state.borrow_mut();
88        state.result = None;
89        state.running.push(slot);
90    }
91
92    /// Whether a run is in progress.
93    pub fn is_pending(&self) -> bool {
94        !self.sync().running.is_empty()
95    }
96
97    /// How the last run ended, until the next one starts or it is [taken](Self::take_result).
98    ///
99    /// Borrows the command: drop it before running the command again.
100    pub fn result(&self) -> Option<Ref<'_, Result<T, E>>> {
101        Ref::filter_map(self.sync(), |state| state.result.as_ref()).ok()
102    }
103
104    /// What the last run returned, if it succeeded. See [`result`](Self::result).
105    pub fn output(&self) -> Option<Ref<'_, T>> {
106        Ref::filter_map(self.sync(), |state| state.result.as_ref()?.as_ref().ok()).ok()
107    }
108
109    /// Why the last run failed, if it did. See [`result`](Self::result).
110    pub fn error(&self) -> Option<Ref<'_, E>> {
111        Ref::filter_map(self.sync(), |state| state.result.as_ref()?.as_ref().err()).ok()
112    }
113
114    /// How the last run ended, taken: to act on it once (close a dialog, navigate to what it
115    /// created).
116    pub fn take_result(&self) -> Option<Result<T, E>> {
117        drop(self.sync());
118        self.state.borrow_mut().result.take()
119    }
120
121    /// Picks up the finished runs.
122    fn sync(&self) -> Ref<'_, State<T, E>> {
123        let mut state = self.state.borrow_mut();
124        let State { running, result } = &mut *state;
125        running.retain(|slot| match lock(slot).take() {
126            Some(done) => {
127                *result = Some(done);
128                false
129            }
130            None => true,
131        });
132        drop(state);
133        self.state.borrow()
134    }
135}
136
137impl<T, E> Default for Command<T, E> {
138    fn default() -> Self {
139        Self {
140            state: Rc::new(RefCell::new(State {
141                running: Vec::new(),
142                result: None,
143            })),
144            refreshes: Vec::new(),
145        }
146    }
147}
148
149impl<T, E> Clone for Command<T, E> {
150    fn clone(&self) -> Self {
151        Self {
152            state: Rc::clone(&self.state),
153            refreshes: self.refreshes.clone(),
154        }
155    }
156}
157
158impl<T: fmt::Debug, E: fmt::Debug> fmt::Debug for Command<T, E> {
159    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160        let state = self.state.borrow();
161        f.debug_struct("Command")
162            .field("pending", &!state.running.is_empty())
163            .field("result", &state.result)
164            .field("refreshes", &self.refreshes)
165            .finish()
166    }
167}