Skip to main content

egui_pop_api/notices/
view.rs

1//! The Notices panel's content: filters, actions, the list and the notice
2//! selected.
3
4use egui::{RichText, Ui};
5use egui_pop_core::icon::{Icon, Size, Tone as IconTone};
6use egui_pop_core::input::Input;
7use egui_pop_core::note::{Note, Severity as NoteSeverity};
8use egui_pop_core::state::Slot;
9use egui_pop_core::strings;
10use egui_pop_core::ui::UiPop as _;
11use egui_pop_core::widgets;
12use egui_pop_model::ids::CommandId;
13use egui_pop_model::notice::{Kept, NoticeId, Origin, Severity};
14
15use crate::app::AppHandle;
16use crate::strings as txt;
17
18/// What the panel lists: the notices that match every part set.
19#[derive(Clone, Debug, Default, PartialEq)]
20#[non_exhaustive]
21pub struct Filter {
22    /// Only this severity.
23    pub severity: Option<Severity>,
24    /// Only this origin.
25    pub origin: Option<Origin>,
26    /// Only the notices of this node.
27    pub node: Option<String>,
28    /// Only the notices whose texts hold it (case ignored): headline,
29    /// reason, hint, details, node.
30    pub search: String,
31}
32
33impl Filter {
34    /// Whether a notice kept matches it.
35    pub fn matches(&self, k: &Kept) -> bool {
36        let n = &k.notice;
37        if self.severity.is_some_and(|s| s != n.severity)
38            || self.origin.is_some_and(|o| o != n.origin)
39            || self
40                .node
41                .as_ref()
42                .is_some_and(|node| n.node.as_ref() != Some(node))
43        {
44            return false;
45        }
46        let q = self.search.trim().to_lowercase();
47        q.is_empty()
48            || [
49                Some(&n.headline),
50                n.reason.as_ref(),
51                n.hint.as_ref(),
52                n.details.as_ref(),
53                n.node.as_ref(),
54            ]
55            .into_iter()
56            .flatten()
57            .any(|t| t.to_lowercase().contains(&q))
58    }
59}
60
61/// The panel's filter.
62const FILTER: Slot<Filter> = Slot::new("egui_pop.notices.filter");
63
64/// The notice selected in the panel.
65const SELECTED: Slot<NoticeId> = Slot::new("egui_pop.notices.selected");
66
67/// The panel's filter now.
68pub(crate) fn filter_of(ctx: &egui::Context) -> Filter {
69    FILTER.get(ctx).unwrap_or_default()
70}
71
72/// The notices a filter lists, in the panel's order: the unresolved
73/// ones first, newest first within each.
74pub fn listed(app: &AppHandle, filter: &Filter) -> Vec<Kept> {
75    let mut kept: Vec<(usize, Kept)> = app
76        .notices()
77        .into_iter()
78        .enumerate()
79        .filter(|(_, k)| filter.matches(k))
80        .collect();
81    kept.sort_by(|(i, a), (j, b)| {
82        a.resolved
83            .cmp(&b.resolved)
84            .then(b.notice.at_ms.cmp(&a.notice.at_ms))
85            .then(j.cmp(i))
86    });
87    kept.into_iter().map(|(_, k)| k).collect()
88}
89
90/// What Copy all puts on the clipboard: each notice listed as its note
91/// copies it (headline, reason, hint, details, time), in the panel's
92/// order, separated by a line of `=`.
93pub fn copy_all_text(kept: &[Kept]) -> String {
94    kept.iter()
95        .map(|k| Note::from_notice(&k.notice).copy_text())
96        .collect::<Vec<_>>()
97        .join("\n\n=====\n\n")
98}
99
100fn origin_word(ctx: &egui::Context, origin: Origin) -> String {
101    strings::tr(
102        ctx,
103        match origin {
104            Origin::User => &txt::NOTICES_ORIGIN_USER,
105            Origin::Background => &txt::NOTICES_ORIGIN_BACKGROUND,
106            Origin::Node => &txt::NOTICES_ORIGIN_NODE,
107            Origin::System => &txt::NOTICES_ORIGIN_SYSTEM,
108        },
109    )
110}
111
112fn severity_word(ctx: &egui::Context, s: Severity) -> String {
113    strings::tr(ctx, NoteSeverity::from(s).word())
114}
115
116/// A notice's time in the list: its date and minute, in UTC.
117fn row_time(k: &Kept) -> String {
118    Note::from_notice(&k.notice)
119        .time
120        .map(|t| t.get(..16).unwrap_or(&t).to_string())
121        .unwrap_or_default()
122}
123
124pub(super) fn show(ui: &mut Ui, app: &AppHandle, see: bool) {
125    let ctx = ui.ctx().clone();
126    let mut filter = filter_of(&ctx);
127    let all = app.notices();
128    filters(ui, &all, &mut filter);
129    FILTER.set(&ctx, filter.clone());
130    let kept = listed(app, &filter);
131    actions(ui, app, &all, &kept);
132    ui.separator();
133    // What the panel lists is read.
134    if see {
135        app.see_notices(kept.iter().filter(|k| !k.seen).map(|k| k.notice.id.clone()));
136    }
137    if all.is_empty() {
138        ui.weak(strings::tr(&ctx, &txt::NOTICES_EMPTY));
139        return;
140    }
141    if kept.is_empty() {
142        ui.weak(strings::tr(&ctx, &txt::NOTHING_MATCHES));
143        return;
144    }
145    let mut selected = SELECTED.get(&ctx);
146    ui.scroll_area(
147        egui::ScrollArea::vertical().auto_shrink([false, false]),
148        |ui| {
149            for k in &kept {
150                row(ui, app, k, &mut selected);
151            }
152        },
153    );
154    match selected {
155        Some(id) => SELECTED.set(&ctx, id),
156        None => {
157            SELECTED.remove(&ctx);
158        }
159    }
160}
161
162/// The filters: severity, origin, node (when notices come from nodes)
163/// and the search.
164fn filters(ui: &mut Ui, all: &[Kept], filter: &mut Filter) {
165    let ctx = ui.ctx().clone();
166    ui.horizontal_wrapped(|ui| {
167        let any = strings::tr(&ctx, &txt::NOTICES_ALL_SEVERITIES);
168        let shown = filter
169            .severity
170            .map_or(any.clone(), |s| severity_word(&ctx, s));
171        widgets::combo_box_labelled(
172            "egui_pop.notices.severity",
173            strings::tr(&ctx, &txt::NOTICES_SEVERITY),
174        )
175        .selected_text(shown)
176        .show_ui(ui, |ui| {
177            widgets::selectable_value(ui, &mut filter.severity, None, any);
178            for s in [
179                Severity::Error,
180                Severity::Warning,
181                Severity::Success,
182                Severity::Info,
183            ] {
184                widgets::selectable_value(
185                    ui,
186                    &mut filter.severity,
187                    Some(s),
188                    severity_word(&ctx, s),
189                );
190            }
191        });
192        let any = strings::tr(&ctx, &txt::NOTICES_ALL_ORIGINS);
193        let shown = filter.origin.map_or(any.clone(), |o| origin_word(&ctx, o));
194        widgets::combo_box_labelled(
195            "egui_pop.notices.origin",
196            strings::tr(&ctx, &txt::NOTICES_ORIGIN),
197        )
198        .selected_text(shown)
199        .show_ui(ui, |ui| {
200            widgets::selectable_value(ui, &mut filter.origin, None, any);
201            for o in [
202                Origin::User,
203                Origin::Background,
204                Origin::Node,
205                Origin::System,
206            ] {
207                widgets::selectable_value(ui, &mut filter.origin, Some(o), origin_word(&ctx, o));
208            }
209        });
210        let mut nodes: Vec<&String> = all.iter().filter_map(|k| k.notice.node.as_ref()).collect();
211        nodes.sort();
212        nodes.dedup();
213        if !nodes.is_empty() || filter.node.is_some() {
214            let any = strings::tr(&ctx, &txt::NOTICES_ALL_NODES);
215            let shown = filter.node.clone().unwrap_or_else(|| any.clone());
216            widgets::combo_box_labelled(
217                "egui_pop.notices.node",
218                strings::tr(&ctx, &txt::NOTICES_NODE),
219            )
220            .selected_text(shown)
221            .show_ui(ui, |ui| {
222                widgets::selectable_value(ui, &mut filter.node, None, any);
223                for n in nodes {
224                    widgets::selectable_value(ui, &mut filter.node, Some(n.clone()), n.as_str());
225                }
226            });
227        }
228        let label = strings::tr(&ctx, &txt::NOTICES_SEARCH);
229        Input::search(&mut filter.search, &label)
230            .placeholder(&label)
231            .show(ui);
232    });
233}
234
235/// Mark all seen, Copy all (what is listed), Clear seen.
236fn actions(ui: &mut Ui, app: &AppHandle, all: &[Kept], kept: &[Kept]) {
237    let ctx = ui.ctx().clone();
238    ui.horizontal_wrapped(|ui| {
239        let unseen: Vec<NoticeId> = all
240            .iter()
241            .filter(|k| !k.seen)
242            .map(|k| k.notice.id.clone())
243            .collect();
244        if ui
245            .add_enabled(
246                !unseen.is_empty(),
247                egui::Button::new(strings::tr(&ctx, &txt::NOTICES_MARK_SEEN)),
248            )
249            .clicked()
250        {
251            app.see_notices(unseen);
252        }
253        if ui
254            .add_enabled(
255                !kept.is_empty(),
256                egui::Button::new(strings::tr(&ctx, &txt::NOTICES_COPY_ALL)),
257            )
258            .clicked()
259        {
260            ctx.copy_text(copy_all_text(kept));
261        }
262        // A condition still going on stays: it is not over.
263        let seen: Vec<NoticeId> = all
264            .iter()
265            .filter(|k| {
266                k.seen && (k.resolved || k.notice.kind != egui_pop_model::notice::Kind::Condition)
267            })
268            .map(|k| k.notice.id.clone())
269            .collect();
270        if ui
271            .add_enabled(
272                !seen.is_empty(),
273                egui::Button::new(strings::tr(&ctx, &txt::NOTICES_CLEAR_SEEN)),
274            )
275            .clicked()
276        {
277            app.dismiss_notices(seen);
278        }
279    });
280}
281
282/// A notice's row: its severity's symbol, time, origin (the node's name
283/// for a remote one) and headline, a resolved condition dimmed with its
284/// symbol, and a dismiss button; selected, its note in full under it.
285fn row(ui: &mut Ui, app: &AppHandle, k: &Kept, selected: &mut Option<NoticeId>) {
286    let ctx = ui.ctx().clone();
287    let n = &k.notice;
288    let sev = NoteSeverity::from(n.severity);
289    let is_selected = selected.as_ref() == Some(&n.id);
290    let mut dismiss = false;
291    ui.horizontal(|ui| {
292        if k.resolved {
293            ui.multiply_opacity(0.6);
294        }
295        ui.add(
296            sev.icon()
297                .size(Size::Inline)
298                .tone(sev.icon_tone())
299                .label(&strings::tr(&ctx, sev.word())),
300        );
301        ui.weak(row_time(k));
302        let origin = match &n.node {
303            Some(node) => node.clone(),
304            None => origin_word(&ctx, n.origin),
305        };
306        ui.weak(origin);
307        if k.resolved {
308            ui.add(
309                Icon::Success
310                    .size(Size::Inline)
311                    .tone(IconTone::Muted)
312                    .label(&strings::tr(&ctx, &txt::NOTICES_RESOLVED)),
313            );
314        }
315        let text = if k.seen {
316            RichText::new(&n.headline)
317        } else {
318            RichText::new(&n.headline).strong()
319        };
320        if widgets::selectable_label(ui, is_selected, text).clicked() {
321            *selected = if is_selected {
322                None
323            } else {
324                Some(n.id.clone())
325            };
326        }
327        let name = strings::tr_args(&ctx, &txt::NOTICES_DISMISS, &[("text", &n.headline)]);
328        dismiss = ui
329            .add(Icon::Close.size(Size::Inline).label(&name).sense_click())
330            .clicked();
331    });
332    if selected.as_ref() == Some(&n.id) {
333        let r = Note::from_notice(n).announced(false).show(ui);
334        if let Some(a) = r.action.and_then(|i| n.actions.get(i))
335            && let Ok(command) = CommandId::new(&a.id)
336        {
337            app.run(command, a.args.clone());
338        }
339    }
340    if dismiss {
341        if selected.as_ref() == Some(&n.id) {
342            *selected = None;
343        }
344        app.dismiss_notice(n.id.clone());
345    }
346}