Skip to main content

egui_pop_model/
job_rows.rs

1//! Rows an application adds to the jobs list: its own **row sources**.
2//!
3//! <div class="warning">Experimental: may change in any release
4//! (docs/stability.md).</div>
5//!
6//! egui-pop's jobs list shows the jobs the host publishes on
7//! `pop.job.event` ([`crate::jobs`]). An application whose background work
8//! is not a job of that kind (promises it waits on, links to other
9//! machines, things it keeps an eye on) declares a **row source**: a
10//! named set of rows it keeps up to date on the bus (`pop.jobs.rows`,
11//! the whole set each time; `pop.jobs.source.drop` to take it away).
12//! The list merges them with its own jobs, and a filter shows some
13//! sources and some states only ([`RowFilter`]).
14//!
15//! A row says what the list draws: its title, its state ([`RowState`]),
16//! its progress when it knows it, a detail line (also its tooltip), a
17//! registry symbol ([`JobBadge`]), the group it sits under, and its
18//! actions ([`RowAction`]: cancel, retry, open), each a command the
19//! list runs with the action's arguments.
20//!
21//! ```
22//! use egui_pop_model::job_rows::{JobRow, RowAction, RowActionKind, RowState};
23//! use serde_json::json;
24//!
25//! let row: JobRow = serde_json::from_value(json!({
26//!     "id": "sync-nas",
27//!     "title": "Sync with the NAS",
28//!     "state": "waiting",
29//!     "detail": "The NAS is asleep",
30//!     "badge": { "icon": "phosphor:hard-drives", "tip": "On the NAS" },
31//!     "group": "Nodes",
32//!     "actions": [{ "kind": "retry", "command": "nodes.wake", "args": { "node": "nas" } }],
33//! }))
34//! .unwrap();
35//! assert_eq!(row.state, RowState::Waiting);
36//! assert!(row.state.active());
37//! assert_eq!(row.actions[0], RowAction::new(RowActionKind::Retry, "nodes.wake").args(json!({ "node": "nas" })));
38//! ```
39
40use std::collections::BTreeSet;
41
42use serde::{Deserialize, Serialize};
43use serde_json::Value as Json;
44
45use crate::jobs::{Job, JobBadge, JobState};
46
47/// The source id of egui-pop's own jobs, the ones published on
48/// `pop.job.event`, as the filter names them.
49pub const OWN_SOURCE: &str = "egui_pop.jobs";
50
51/// Where a row is.
52#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
53#[serde(rename_all = "kebab-case")]
54pub enum RowState {
55    /// Not started yet.
56    Queued,
57    /// Going on.
58    #[default]
59    Running,
60    /// Started, but waiting on something else (a machine, a person).
61    Waiting,
62    /// Ended well.
63    Done,
64    /// Ended badly.
65    Failed,
66}
67
68impl RowState {
69    /// Whether it is still to end (queued, running, waiting).
70    pub fn active(self) -> bool {
71        matches!(
72            self,
73            RowState::Queued | RowState::Running | RowState::Waiting
74        )
75    }
76
77    /// Its name, as the bus and the debug bridge write it.
78    pub fn name(self) -> &'static str {
79        match self {
80            RowState::Queued => "queued",
81            RowState::Running => "running",
82            RowState::Waiting => "waiting",
83            RowState::Done => "done",
84            RowState::Failed => "failed",
85        }
86    }
87
88    /// The state an egui-pop job shows as: paused and cancelling are
89    /// waiting, cancelled is done.
90    pub fn of_job(state: JobState) -> RowState {
91        match state {
92            JobState::Running => RowState::Running,
93            JobState::Paused | JobState::Cancelling => RowState::Waiting,
94            JobState::Done | JobState::Cancelled => RowState::Done,
95            JobState::Failed => RowState::Failed,
96        }
97    }
98}
99
100/// What a row's action does, for its label and its order.
101#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
102#[serde(rename_all = "kebab-case")]
103pub enum RowActionKind {
104    Cancel,
105    Retry,
106    Open,
107}
108
109/// An action a row offers: a button that runs `command` with `args`.
110/// Its label is the kind's ("Cancel", "Retry", "Open") unless `title`
111/// says otherwise.
112#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
113#[non_exhaustive]
114pub struct RowAction {
115    pub kind: RowActionKind,
116    /// The command it runs.
117    pub command: String,
118    /// The command's arguments.
119    #[serde(default, skip_serializing_if = "Json::is_null")]
120    pub args: Json,
121    /// Its label, instead of the kind's.
122    #[serde(default, skip_serializing_if = "Option::is_none")]
123    pub title: Option<String>,
124}
125
126impl RowAction {
127    pub fn new(kind: RowActionKind, command: impl Into<String>) -> Self {
128        Self {
129            kind,
130            command: command.into(),
131            args: Json::Null,
132            title: None,
133        }
134    }
135
136    pub fn args(mut self, args: Json) -> Self {
137        self.args = args;
138        self
139    }
140
141    pub fn title(mut self, title: impl Into<String>) -> Self {
142        self.title = Some(title.into());
143        self
144    }
145}
146
147/// One row of a source.
148#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
149#[non_exhaustive]
150pub struct JobRow {
151    /// Unique within its source.
152    pub id: String,
153    pub title: String,
154    #[serde(default)]
155    pub state: RowState,
156    /// How far it is, 0 to 1; none when it cannot tell.
157    #[serde(default, skip_serializing_if = "Option::is_none")]
158    pub progress: Option<f64>,
159    /// A line under its bar, also its tooltip.
160    #[serde(default, skip_serializing_if = "Option::is_none")]
161    pub detail: Option<String>,
162    /// A registry symbol before its title, its tip its accessible name.
163    #[serde(default, skip_serializing_if = "Option::is_none")]
164    pub badge: Option<JobBadge>,
165    /// The group it sits under, within its source.
166    #[serde(default, skip_serializing_if = "Option::is_none")]
167    pub group: Option<String>,
168    #[serde(default, skip_serializing_if = "Vec::is_empty")]
169    pub actions: Vec<RowAction>,
170}
171
172impl JobRow {
173    pub fn new(id: impl Into<String>, title: impl Into<String>, state: RowState) -> Self {
174        Self {
175            id: id.into(),
176            title: title.into(),
177            state,
178            ..Self::default()
179        }
180    }
181
182    pub fn progress(mut self, fraction: f64) -> Self {
183        self.progress = Some(fraction.clamp(0.0, 1.0));
184        self
185    }
186
187    pub fn detail(mut self, detail: impl Into<String>) -> Self {
188        self.detail = Some(detail.into());
189        self
190    }
191
192    pub fn badge(mut self, badge: JobBadge) -> Self {
193        self.badge = Some(badge);
194        self
195    }
196
197    pub fn group(mut self, group: impl Into<String>) -> Self {
198        self.group = Some(group.into());
199        self
200    }
201
202    pub fn action(mut self, action: RowAction) -> Self {
203        self.actions.push(action);
204        self
205    }
206}
207
208/// A source as the list keeps it: its id, its title (the filter's
209/// label), who declared it, and its rows.
210#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
211#[non_exhaustive]
212pub struct RowSource {
213    pub id: String,
214    pub title: String,
215    /// Who declared it: a plugin's id, a module's. A plugin disconnected
216    /// takes its sources with it.
217    pub owner: String,
218    pub rows: Vec<JobRow>,
219}
220
221impl RowSource {
222    pub fn new(id: impl Into<String>, title: impl Into<String>, owner: impl Into<String>) -> Self {
223        Self {
224            id: id.into(),
225            title: title.into(),
226            owner: owner.into(),
227            rows: Vec::new(),
228        }
229    }
230}
231
232/// Which states the list shows.
233#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
234#[serde(rename_all = "kebab-case")]
235pub enum StateFilter {
236    #[default]
237    All,
238    /// Queued, running or waiting.
239    Active,
240    Done,
241    Failed,
242}
243
244impl StateFilter {
245    pub const ALL: [StateFilter; 4] = [
246        StateFilter::All,
247        StateFilter::Active,
248        StateFilter::Done,
249        StateFilter::Failed,
250    ];
251
252    pub fn admits(self, state: RowState) -> bool {
253        match self {
254            StateFilter::All => true,
255            StateFilter::Active => state.active(),
256            StateFilter::Done => state == RowState::Done,
257            StateFilter::Failed => state == RowState::Failed,
258        }
259    }
260}
261
262/// What the list shows: every source but the hidden ones, in the states
263/// the state filter admits.
264#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
265#[non_exhaustive]
266pub struct RowFilter {
267    /// The sources hidden, by id ([`OWN_SOURCE`] for egui-pop's jobs).
268    #[serde(default)]
269    pub hidden: BTreeSet<String>,
270    #[serde(default)]
271    pub state: StateFilter,
272}
273
274impl RowFilter {
275    /// Whether the source is shown.
276    pub fn shows(&self, source: &str) -> bool {
277        !self.hidden.contains(source)
278    }
279
280    /// Shows or hides a source.
281    pub fn set_shown(&mut self, source: &str, shown: bool) {
282        if shown {
283            self.hidden.remove(source);
284        } else {
285            self.hidden.insert(source.into());
286        }
287    }
288
289    /// Whether a row of `source` in `state` is shown.
290    pub fn admits(&self, source: &str, state: RowState) -> bool {
291        self.shows(source) && self.state.admits(state)
292    }
293
294    /// Whether an egui-pop job is shown.
295    pub fn admits_job(&self, job: &Job) -> bool {
296        self.admits(OWN_SOURCE, RowState::of_job(job.state))
297    }
298}
299
300#[cfg(test)]
301mod tests {
302    use super::*;
303    use serde_json::json;
304
305    #[test]
306    fn a_row_round_trips_and_takes_its_defaults() {
307        let row: JobRow = serde_json::from_value(json!({ "id": "a", "title": "A" })).unwrap();
308        assert_eq!(row.state, RowState::Running);
309        assert_eq!(
310            serde_json::to_value(&row).unwrap(),
311            json!({ "id": "a", "title": "A", "state": "running" })
312        );
313    }
314
315    #[test]
316    fn the_filter_hides_sources_and_states() {
317        let mut f = RowFilter::default();
318        assert!(f.admits("nodes", RowState::Queued));
319        f.set_shown("nodes", false);
320        assert!(!f.admits("nodes", RowState::Queued));
321        assert!(f.admits(OWN_SOURCE, RowState::Done));
322        f.state = StateFilter::Active;
323        assert!(!f.admits(OWN_SOURCE, RowState::Done));
324        assert!(f.admits(OWN_SOURCE, RowState::Waiting));
325        f.state = StateFilter::Failed;
326        assert!(f.admits(OWN_SOURCE, RowState::Failed));
327        assert_eq!(RowState::of_job(JobState::Cancelled), RowState::Done);
328    }
329}