1use 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#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
42#[serde(tag = "state", rename_all = "kebab-case")]
43#[non_exhaustive]
44pub enum PanelState {
45 #[default]
47 Ready,
48 Stale,
51 Updating,
53 Failed { reason: String },
55}
56
57impl PanelState {
58 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 pub fn is_busy(&self) -> bool {
70 matches!(self, PanelState::Stale | PanelState::Updating)
71 }
72}
73
74#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
77#[non_exhaustive]
78pub struct PanelStateAsk {
79 pub panel: String,
81 pub state: PanelState,
82 pub owner: String,
84 #[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 pub fn cause(mut self, seq: u64) -> Self {
101 self.cause = Some(seq);
102 self
103 }
104}
105
106#[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
117pub const PANEL_STATE_POINTS: [&str; 1] = [PanelStateSet::ID.as_str()];
119
120pub const PANEL_CHROME: &str = "pop.workbench.panel_state";
123
124#[derive(Clone, Debug, PartialEq, Eq)]
127#[non_exhaustive]
128pub enum TabMark {
129 Busy,
131 Failed(String),
133 Edits(PanelKind),
137}
138
139impl TabMark {
140 pub fn rank(&self) -> u8 {
143 match self {
144 TabMark::Busy => 3,
145 TabMark::Failed(_) => 2,
146 TabMark::Edits(_) => 1,
147 }
148 }
149
150 pub fn of_kind(kind: PanelKind) -> Option<TabMark> {
152 kind.edits().then_some(TabMark::Edits(kind))
153 }
154
155 pub fn winner(marks: impl IntoIterator<Item = TabMark>) -> Option<TabMark> {
157 marks.into_iter().max_by_key(TabMark::rank)
158 }
159}
160
161#[derive(Clone, Debug, PartialEq)]
166pub(crate) struct Kept {
167 pub(crate) state: PanelState,
168 pub(crate) episode: u64,
169 pub(crate) since: Option<f64>,
172}
173
174pub(crate) type States = Arc<Mutex<BTreeMap<String, Kept>>>;
176
177pub(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 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 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#[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
242pub(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
263fn 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
288pub(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
304pub 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
315pub(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
327pub(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
345pub(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}