Skip to main content

egui_pop_api/bus/
panel_state.rs

1//! A panel's state on the bus (ADR 0029): whether what it shows is
2//! current.
3//!
4//! A panel whose content follows something it does not hold (the photo
5//! selected, a document, a source) may show content that no longer
6//! matches it: stale until its work starts, updating while it runs,
7//! failed when it could not. Whoever knows asks `pop.panel.state`
8//! ([`PanelStateSet`], a [`PanelStateAsk`] naming the panel), from any
9//! thread; the workbench's listener ([`PANEL_CHROME`]) keeps it, and the
10//! panel's chrome shows it: never the panel itself.
11//!
12//! - **Stale** and **updating**: the content is dimmed and a busy pip
13//!   shows in the panel's corner and on its tab, both only once the
14//!   state has lasted `motion.spinner.delay` (a fast update shows
15//!   nothing), then for at least `motion.spinner.min`.
16//! - **Failed**: the content is dimmed at once and a failed pip shows,
17//!   the reason in its name and its tip.
18//! - **Ready**: nothing; the state is forgotten.
19//!
20//! The tab holds one mark ([`TabMark`]): when a panel has more than one
21//! to show, the one of the highest rank wins, the busy mark first, then a
22//! failure, then the "edits" mark of a control or mixed panel
23//! ([`PanelKind`]), which shows while nothing else does. A floating
24//! palette's band holds the same mark after its title.
25
26use std::collections::BTreeMap;
27use std::sync::{Arc, Mutex};
28
29use bus_contract::{Bus, ListenOpts, Point, PointId, PointKind};
30use egui::{Context, Id, Rect, Response, Ui, UiBuilder};
31use egui_pop_core::icon::Icon;
32use egui_pop_core::indicator::{Anchor, Indicator, Pip, Size};
33use egui_pop_core::{lock, motion, strings};
34use egui_pop_model::panels::PanelKind;
35use serde::{Deserialize, Serialize};
36
37use super::OWNER;
38use crate::strings as txt;
39
40/// Whether what a panel shows is current.
41#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
42#[serde(tag = "state", rename_all = "kebab-case")]
43#[non_exhaustive]
44pub enum PanelState {
45    /// Current: nothing shown.
46    #[default]
47    Ready,
48    /// It shows what no longer matches (the photo changed); its work has
49    /// not started yet.
50    Stale,
51    /// Its work runs.
52    Updating,
53    /// Its work failed: why, in the person's words.
54    Failed { reason: String },
55}
56
57impl PanelState {
58    /// The state as the journal writes it (`updating`).
59    pub fn as_str(&self) -> &'static str {
60        match self {
61            PanelState::Ready => "ready",
62            PanelState::Stale => "stale",
63            PanelState::Updating => "updating",
64            PanelState::Failed { .. } => "failed",
65        }
66    }
67
68    /// Whether its work is still to come or runs (stale or updating).
69    pub fn is_busy(&self) -> bool {
70        matches!(self, PanelState::Stale | PanelState::Updating)
71    }
72}
73
74/// A panel's state asked: which panel, its state, who asks, and the
75/// event that caused it.
76#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
77#[non_exhaustive]
78pub struct PanelStateAsk {
79    /// The panel's id.
80    pub panel: String,
81    pub state: PanelState,
82    /// Who asks: a plugin's id, a module's.
83    pub owner: String,
84    /// The journal sequence number of the event that caused it.
85    #[serde(default, skip_serializing_if = "Option::is_none")]
86    pub cause: Option<u64>,
87}
88
89impl PanelStateAsk {
90    pub fn new(panel: impl Into<String>, state: PanelState, owner: impl Into<String>) -> Self {
91        Self {
92            panel: panel.into(),
93            state,
94            owner: owner.into(),
95            cause: None,
96        }
97    }
98
99    /// The journal event that caused it.
100    pub fn cause(mut self, seq: u64) -> Self {
101        self.cause = Some(seq);
102        self
103    }
104}
105
106/// A panel's state is asked (`pop.panel.state`); its listeners say what they
107/// did, one line each, in the value.
108#[derive(Debug)]
109pub struct PanelStateSet;
110impl Point for PanelStateSet {
111    const KIND: PointKind = PointKind::Request;
112    const ID: PointId = PointId::new("pop.panel.state");
113    type Input = PanelStateAsk;
114    type Value = Vec<String>;
115}
116
117/// The panel state points, in the order [`super::order_dump`] prints them.
118pub const PANEL_STATE_POINTS: [&str; 1] = [PanelStateSet::ID.as_str()];
119
120/// The workbench's listener of `pop.panel.state`: keeps each panel's state
121/// for its chrome.
122pub const PANEL_CHROME: &str = "pop.workbench.panel_state";
123
124/// The mark a panel's tab holds, one at a time: the highest rank wins
125/// ([`TabMark::rank`]).
126#[derive(Clone, Debug, PartialEq, Eq)]
127#[non_exhaustive]
128pub enum TabMark {
129    /// Its content is stale or updating (shown after the delay).
130    Busy,
131    /// Its work failed: why.
132    Failed(String),
133    /// It edits, wholly ([`PanelKind::Control`]) or in part
134    /// ([`PanelKind::Mixed`]): declared with the panel, shown while no
135    /// state is.
136    Edits(PanelKind),
137}
138
139impl TabMark {
140    /// Its rank: the busy mark first, then a failure, then the edits
141    /// mark.
142    pub fn rank(&self) -> u8 {
143        match self {
144            TabMark::Busy => 3,
145            TabMark::Failed(_) => 2,
146            TabMark::Edits(_) => 1,
147        }
148    }
149
150    /// The edits mark of a panel of `kind`: none for a view.
151    pub fn of_kind(kind: PanelKind) -> Option<TabMark> {
152        kind.edits().then_some(TabMark::Edits(kind))
153    }
154
155    /// Of the marks a tab may show, the one it shows.
156    pub fn winner(marks: impl IntoIterator<Item = TabMark>) -> Option<TabMark> {
157        marks.into_iter().max_by_key(TabMark::rank)
158    }
159}
160
161/// A panel's state as kept: the state, and its episode: a new one
162/// starts when a wait starts (stale or updating after neither) or a
163/// failure is said, and restarts the delay. Ready ends a wait without
164/// starting one, so a busy mark shown is kept for its minimum.
165#[derive(Clone, Debug, PartialEq)]
166pub(crate) struct Kept {
167    pub(crate) state: PanelState,
168    pub(crate) episode: u64,
169    /// When this episode was asked, or else first drawn (motion clock
170    /// seconds).
171    pub(crate) since: Option<f64>,
172}
173
174/// Every panel's state asked, by panel id.
175pub(crate) type States = Arc<Mutex<BTreeMap<String, Kept>>>;
176
177/// Registers the workbench's listener of `pop.panel.state`; `wake` repaints
178/// the interface (the state may be asked from another thread).
179pub(super) fn install(kernel: &dyn Bus, states: &States, wake: Arc<Mutex<Option<egui::Context>>>) {
180    let states = states.clone();
181    let listened = kernel.listen::<PanelStateSet>(
182        PANEL_CHROME,
183        ListenOpts::new().owner(OWNER),
184        move |ask, did| {
185            let ctx = lock(&wake).clone();
186            // When it was asked, by the motion clock: its delay counts
187            // from there (from its first pass when no pass ran yet).
188            let now = ctx.as_ref().map(motion::now);
189            {
190                let mut states = lock(&states);
191                let entry = states.entry(ask.panel.clone()).or_insert(Kept {
192                    state: PanelState::Ready,
193                    episode: 0,
194                    since: None,
195                });
196                if entry.state != ask.state {
197                    // Stale then updating is one wait: its delay goes on.
198                    let starts = match &ask.state {
199                        PanelState::Ready => false,
200                        PanelState::Failed { .. } => true,
201                        _ => !entry.state.is_busy(),
202                    };
203                    if starts {
204                        entry.episode += 1;
205                        entry.since = now;
206                    }
207                    entry.state = ask.state.clone();
208                    did.push(format!(
209                        "{PANEL_CHROME}: {} {}",
210                        ask.panel,
211                        ask.state.as_str()
212                    ));
213                }
214            }
215            if let Some(ctx) = ctx {
216                ctx.request_repaint();
217            }
218            Ok(())
219        },
220    );
221    debug_assert!(listened.is_ok(), "{listened:?}");
222}
223
224/// What a panel's chrome shows now.
225#[derive(Clone, Debug, PartialEq)]
226pub(crate) enum Shown {
227    Nothing,
228    Busy,
229    Failed(String),
230}
231
232impl Shown {
233    fn mark(self) -> Option<TabMark> {
234        match self {
235            Shown::Nothing => None,
236            Shown::Busy => Some(TabMark::Busy),
237            Shown::Failed(why) => Some(TabMark::Failed(why)),
238        }
239    }
240}
241
242/// What `panel`'s chrome shows now: a busy state only once it has lasted
243/// the delay, and for the minimum once shown ([`motion::Busy`]); a
244/// failure at once.
245pub(crate) fn shown(states: &States, ctx: &Context, panel: &str) -> Shown {
246    let now = motion::now(ctx);
247    let (state, episode, since) = {
248        let mut states = lock(states);
249        match states.get_mut(panel) {
250            Some(k) => (k.state.clone(), k.episode, *k.since.get_or_insert(now)),
251            None => return Shown::Nothing,
252        }
253    };
254    let busy = motion::Busy::new(Id::unique(("egui_pop.panel_state", panel, episode)), since)
255        .visible(ctx, state.is_busy());
256    match state {
257        PanelState::Failed { reason } => Shown::Failed(reason),
258        _ if busy => Shown::Busy,
259        _ => Shown::Nothing,
260    }
261}
262
263/// The mark `panel`'s chrome shows, in `ui`'s language, by the indicator
264/// id given.
265fn indicator(ctx: &Context, mark: &TabMark, id: String) -> Indicator {
266    match mark {
267        TabMark::Busy => Indicator::pip(Pip::Busy)
268            .id(id)
269            .name(strings::tr(ctx, &txt::PANEL_STATE_UPDATING)),
270        TabMark::Failed(why) => Indicator::pip(Pip::Failed).id(id).name(strings::tr_args(
271            ctx,
272            &txt::PANEL_STATE_FAILED,
273            &[("reason", why)],
274        )),
275        TabMark::Edits(kind) => {
276            let key = match kind {
277                PanelKind::Mixed => &txt::PANEL_KIND_MIXED,
278                _ => &txt::PANEL_KIND_CONTROL,
279            };
280            Indicator::icon(Icon::Edit)
281                .size(Size::Small)
282                .id(id)
283                .name(strings::tr(ctx, key))
284        }
285    }
286}
287
288/// The one mark `panel`'s tab or palette band shows: the highest rank of
289/// its state's and its kind's.
290pub(crate) fn tab_mark(
291    states: &States,
292    ctx: &Context,
293    panel: &str,
294    kind: PanelKind,
295) -> Option<TabMark> {
296    TabMark::winner(
297        shown(states, ctx, panel)
298            .mark()
299            .into_iter()
300            .chain(TabMark::of_kind(kind)),
301    )
302}
303
304/// The indicator id of a panel's mark on its content (`panel-state:<id>`)
305/// and on its tab or palette band (`panel-state-tab:<id>`, its one mark
306/// slot: the busy, failed or edits mark), for tests and agents.
307pub fn mark_id(panel: &str, on_tab: bool) -> String {
308    if on_tab {
309        format!("panel-state-tab:{panel}")
310    } else {
311        format!("panel-state:{panel}")
312    }
313}
314
315/// Over a panel's content just drawn in `rect`: dimmed, and its mark in
316/// the top end corner, while it is not current.
317pub(crate) fn paint_content(states: &States, ui: &mut Ui, panel: &str, rect: Rect) {
318    let ctx = ui.ctx().clone();
319    let Some(mark) = shown(states, &ctx, panel).mark() else {
320        return;
321    };
322    let veil = ui.visuals().panel_fill.gamma_multiply(0.6);
323    ui.painter_at(rect).rect_filled(rect, 0.0, veil);
324    indicator(&ctx, &mark, mark_id(panel, false)).paint_at(ui, rect, Anchor::TopEnd);
325}
326
327/// On a panel's tab button: its one mark (the highest rank of those it
328/// has), on the tab's top end corner, its meaning added to the tab's
329/// name.
330pub(crate) fn paint_tab(states: &States, tab: &Response, panel: &str, kind: PanelKind) {
331    let ctx = tab.ctx.clone();
332    let Some(mark) = tab_mark(states, &ctx, panel, kind) else {
333        return;
334    };
335    let mut ui = Ui::new(
336        ctx.clone(),
337        tab.id.with("egui_pop.panel_state"),
338        UiBuilder::new().layer_id(tab.layer_id).max_rect(tab.rect),
339    );
340    indicator(&ctx, &mark, mark_id(panel, true))
341        .overhang(true)
342        .on(&mut ui, tab, Anchor::TopEnd);
343}
344
345/// In a floating palette's band, after its title: its one mark, inline.
346pub(crate) fn add_inline(states: &States, ui: &mut Ui, panel: &str, kind: PanelKind) {
347    let ctx = ui.ctx().clone();
348    if let Some(mark) = tab_mark(states, &ctx, panel, kind) {
349        ui.add(indicator(&ctx, &mark, mark_id(panel, true)));
350    }
351}
352
353#[cfg(test)]
354mod tests {
355    use super::*;
356
357    #[test]
358    fn the_busy_mark_wins_the_tab() {
359        let shown = TabMark::winner([TabMark::Failed("no data".into()), TabMark::Busy]);
360        assert_eq!(shown, Some(TabMark::Busy));
361        assert_eq!(TabMark::winner([]), None);
362        let edits = TabMark::of_kind(PanelKind::Control);
363        assert_eq!(edits, Some(TabMark::Edits(PanelKind::Control)));
364        assert_eq!(TabMark::of_kind(PanelKind::View), None);
365        let shown = TabMark::winner(edits.clone().into_iter().chain([TabMark::Busy]));
366        assert_eq!(shown, Some(TabMark::Busy));
367        let shown = TabMark::winner(edits.into_iter().chain([TabMark::Failed("x".into())]));
368        assert_eq!(shown, Some(TabMark::Failed("x".into())));
369    }
370
371    #[test]
372    fn a_state_reads_as_the_journal_writes_it() {
373        let ask = PanelStateAsk::new(
374            "scopes.histogram",
375            PanelState::Failed {
376                reason: "no pixels".into(),
377            },
378            "helios",
379        );
380        let json = serde_json::to_value(&ask).unwrap();
381        assert_eq!(json["state"]["state"], "failed");
382        assert_eq!(json["state"]["reason"], "no pixels");
383        assert_eq!(serde_json::from_value::<PanelStateAsk>(json).unwrap(), ask);
384    }
385}