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, 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, ctx) =
75            with_registry(|registry| (Arc::clone(&registry.invalidated), registry.ctx.clone()));
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                if let Some(ctx) = ctx {
85                    ctx.request_repaint();
86                }
87            }
88        });
89        let mut state = self.state.borrow_mut();
90        state.result = None;
91        state.running.push(slot);
92    }
93
94    /// Whether a run is in progress.
95    pub fn is_pending(&self) -> bool {
96        !self.sync().running.is_empty()
97    }
98
99    /// How the last run ended, until the next one starts or it is [taken](Self::take_result).
100    ///
101    /// Borrows the command: drop it before running the command again.
102    pub fn result(&self) -> Option<Ref<'_, Result<T, E>>> {
103        Ref::filter_map(self.sync(), |state| state.result.as_ref()).ok()
104    }
105
106    /// What the last run returned, if it succeeded. See [`result`](Self::result).
107    pub fn output(&self) -> Option<Ref<'_, T>> {
108        Ref::filter_map(self.sync(), |state| state.result.as_ref()?.as_ref().ok()).ok()
109    }
110
111    /// Why the last run failed, if it did. See [`result`](Self::result).
112    pub fn error(&self) -> Option<Ref<'_, E>> {
113        Ref::filter_map(self.sync(), |state| state.result.as_ref()?.as_ref().err()).ok()
114    }
115
116    /// How the last run ended, taken: to act on it once (close a dialog, navigate to what it
117    /// created).
118    pub fn take_result(&self) -> Option<Result<T, E>> {
119        drop(self.sync());
120        self.state.borrow_mut().result.take()
121    }
122
123    /// Picks up the finished runs.
124    fn sync(&self) -> Ref<'_, State<T, E>> {
125        let mut state = self.state.borrow_mut();
126        let State { running, result } = &mut *state;
127        running.retain(|slot| match lock(slot).take() {
128            Some(done) => {
129                *result = Some(done);
130                false
131            }
132            None => true,
133        });
134        drop(state);
135        self.state.borrow()
136    }
137}
138
139impl<T, E> Default for Command<T, E> {
140    fn default() -> Self {
141        Self {
142            state: Rc::new(RefCell::new(State {
143                running: Vec::new(),
144                result: None,
145            })),
146            refreshes: Vec::new(),
147        }
148    }
149}
150
151impl<T, E> Clone for Command<T, E> {
152    fn clone(&self) -> Self {
153        Self {
154            state: Rc::clone(&self.state),
155            refreshes: self.refreshes.clone(),
156        }
157    }
158}
159
160impl<T: fmt::Debug, E: fmt::Debug> fmt::Debug for Command<T, E> {
161    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162        let state = self.state.borrow();
163        f.debug_struct("Command")
164            .field("pending", &!state.running.is_empty())
165            .field("result", &state.result)
166            .field("refreshes", &self.refreshes)
167            .finish()
168    }
169}