Skip to main content

egui_pop_api/
jobs_centre.rs

1//! The jobs centre: every job the host runs, as a panel (`Jobs`, closed
2//! until asked for) and as a popover from the status bar's jobs item,
3//! the same list in both.
4//!
5//! <div class="warning">Experimental: may change in any release
6//! (docs/stability.md).</div>
7//!
8//! Each job shows its badge (a registry symbol, its tooltip its
9//! accessible name), its title, its state, a bar of its estimated overall
10//! percentage (stacked with its failed and skipped items), "n of m",
11//! the current step and item, the time left, the reason it failed, and
12//! buttons that ask the host (pause, resume, cancel, retry) or forget it
13//! (dismiss). A batch's children fold under it. Finished jobs go to the
14//! history, cleared by hand.
15//!
16//! An application adds rows of its own as **row sources** (promises it
17//! waits on, links to other machines; [`egui_pop_model::job_rows`]),
18//! kept on the bus (`pop.jobs.rows`, [`crate::jobs`]): each source's rows
19//! show under its title, by group, each with its symbol, state, bar,
20//! detail and actions (cancel, retry, open, each a command). Once a
21//! source is declared, a filter bar shows or hides each source (egui-pop's
22//! own jobs among them) and picks the states shown (all, active, done,
23//! failed). Each row is a list item named "title, state", each action a
24//! button named "action: title".
25//!
26//! A small chevron before each job opens its **log console**: the
27//! lines of its `job.log` events. The state is remembered per job
28//! (`JobsService::expanded`), so the panel, the popover and the toast
29//! agree. egui-pop's application layer draws the lines as plain text;
30//! `egui-pop-editors` gives a pseudo-terminal console (its `Terminal`
31//! over a `Console` source: colours, scrollback, selection, copy) by
32//! providing [`JOB_LOG_VIEW`] (`JobConsolesPlugin`, which the facade
33//! offers with its `editors` feature). The layering keeps the
34//! application API below the editors: the console is a service the
35//! upper layer provides, not a dependency.
36
37use egui::{RichText, Ui};
38use egui_pop_core::a11y;
39use egui_pop_core::icon::{Icon, Size};
40use egui_pop_core::kit::{Kit, State};
41use egui_pop_core::progress::{ProgressBar, Tone};
42use egui_pop_core::strings;
43use egui_pop_core::theme::Tokens;
44use egui_pop_core::ui::UiPop;
45use egui_pop_model::ids::PanelId;
46use egui_pop_model::job_rows::{
47    JobRow, OWN_SOURCE, RowAction, RowActionKind, RowFilter, RowSource, RowState, StateFilter,
48};
49use egui_pop_model::jobs::{Job, JobBadge, JobState, Request};
50
51use crate::app::AppHandle;
52use crate::jobs::{self, JOBS, JobsService};
53use crate::services::ServiceToken;
54use crate::strings as txt;
55
56/// The jobs panel.
57pub const PANEL_JOBS: PanelId = PanelId::from_static("egui_pop.jobs");
58
59/// Draws a job's log console: `f(ui, app, job)`.
60pub type DrawLog = Box<dyn Fn(&mut Ui, &AppHandle, &Job) + Send + Sync>;
61
62/// How a job's log console is drawn.
63pub struct JobLogView(DrawLog);
64
65impl JobLogView {
66    pub fn new(f: impl Fn(&mut Ui, &AppHandle, &Job) + Send + Sync + 'static) -> Self {
67        Self(Box::new(f))
68    }
69
70    pub fn show(&self, ui: &mut Ui, app: &AppHandle, job: &Job) {
71        (self.0)(ui, app, job);
72    }
73}
74
75impl std::fmt::Debug for JobLogView {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        f.write_str("JobLogView")
78    }
79}
80
81/// The log console, provided by an upper layer (`egui-pop-editors`'s
82/// pseudo-terminal); without it, plain lines.
83pub const JOB_LOG_VIEW: ServiceToken<JobLogView> = ServiceToken::new("egui_pop.jobs.log_view");
84
85/// How tall a log console is, in points.
86pub const LOG_HEIGHT: f32 = 160.0;
87
88/// The tone a job's bar takes.
89pub fn tone(job: &Job) -> Tone {
90    match job.state {
91        JobState::Running => Tone::Accent,
92        JobState::Paused | JobState::Cancelling | JobState::Cancelled => Tone::Muted,
93        JobState::Done if job.failed > 0 => Tone::Warning,
94        JobState::Done => Tone::Success,
95        JobState::Failed => Tone::Danger,
96    }
97}
98
99/// A job's state as words.
100pub fn state_text(ctx: &egui::Context, job: &Job) -> String {
101    let key = match job.state {
102        JobState::Running => &txt::JOB_RUNNING,
103        JobState::Paused => &txt::JOB_PAUSED,
104        JobState::Cancelling => &txt::JOB_CANCELLING,
105        JobState::Done => &txt::JOB_DONE,
106        JobState::Failed => &txt::JOB_FAILED,
107        JobState::Cancelled => &txt::JOB_CANCELLED,
108    };
109    let mut text = strings::tr(ctx, key);
110    if job.requested.is_some() {
111        text = strings::tr_args(ctx, &txt::JOB_ASKED, &[("state", &text)]);
112    }
113    // Left by a plugin now disconnected (ADR 0028): it goes on, and
114    // nothing may ever end it.
115    if let Some(plugin) = &job.orphaned {
116        text = strings::tr_args(
117            ctx,
118            &txt::JOB_ORPHANED,
119            &[("state", &text), ("plugin", plugin)],
120        );
121    }
122    text
123}
124
125/// Time left as people say it: seconds under a minute (by fives),
126/// minutes otherwise.
127pub fn eta_text(ctx: &egui::Context, seconds: f64) -> String {
128    if seconds < 60.0 {
129        let n = ((seconds / 5.0).ceil() * 5.0).max(5.0);
130        strings::tr_args(
131            ctx,
132            &txt::JOB_ETA_SECONDS,
133            &[("n", &strings::number(ctx, n, 0))],
134        )
135    } else {
136        strings::tr_args(
137            ctx,
138            &txt::JOB_ETA_MINUTES,
139            &[("n", &strings::number(ctx, (seconds / 60.0).round(), 0))],
140        )
141    }
142}
143
144/// What a job's line under its bar says: n of m, the step, the item,
145/// the time left.
146pub fn detail_text(ctx: &egui::Context, job: &Job, now: f64) -> String {
147    let mut parts = Vec::new();
148    if let Some(p) = job.percent() {
149        parts.push(format!("{}%", strings::number(ctx, p.round(), 0)));
150    }
151    if let Some(total) = job.total {
152        parts.push(strings::tr_args(
153            ctx,
154            &txt::JOB_OF,
155            &[
156                ("done", &strings::number(ctx, job.done as f64, 0)),
157                ("total", &strings::number(ctx, total as f64, 0)),
158            ],
159        ));
160    }
161    if job.active() {
162        if let Some(step) = job
163            .step
164            .as_ref()
165            .and_then(|s| job.steps.iter().find(|x| &x.id == s))
166        {
167            parts.push(step.title.clone());
168        }
169        if let Some(item) = &job.item {
170            parts.push(item.clone());
171        }
172        if let Some(eta) = job.eta(now) {
173            parts.push(eta_text(ctx, eta));
174        }
175    }
176    parts.join(" · ")
177}
178
179/// One of a row's actions, gathered before the row is laid out: drawn
180/// as a button when the row has room for them, else as an entry of the
181/// row's "…" menu.
182struct Act<'a> {
183    /// What the button says.
184    label: String,
185    /// Its accessible name, "action: title".
186    name: String,
187    /// Whether it can be used now.
188    enabled: bool,
189    /// What a click does.
190    run: Box<dyn FnOnce() + 'a>,
191}
192
193impl<'a> Act<'a> {
194    /// An action named with its row's title.
195    fn new(
196        ctx: &egui::Context,
197        label: String,
198        title: &str,
199        enabled: bool,
200        run: impl FnOnce() + 'a,
201    ) -> Self {
202        let name = strings::tr_args(
203            ctx,
204            &txt::JOB_ACTION_NAME,
205            &[("action", &label), ("job", title)],
206        );
207        Self {
208            label,
209            name,
210            enabled,
211            run: Box::new(run),
212        }
213    }
214}
215
216/// An action asking something of the host, named with the job.
217fn ask_act<'a>(ctx: &egui::Context, app: &'a AppHandle, job: &'a Job, request: Request) -> Act<'a> {
218    let label = strings::tr(
219        ctx,
220        match request {
221            Request::Pause => &txt::JOB_PAUSE,
222            Request::Resume => &txt::JOB_RESUME,
223            Request::Cancel => &strings::CANCEL,
224            Request::Retry => &strings::RETRY,
225        },
226    );
227    let asked = job.requested.is_some() || app.running(&jobs::command_of(request));
228    Act::new(ctx, label, &job.title, !asked, move || {
229        jobs::ask(app, &job.id, request);
230    })
231}
232
233/// A button asking something of the host, named with the job.
234fn ask_button(ui: &mut Ui, app: &AppHandle, job: &Job, request: Request) {
235    let ctx = ui.ctx().clone();
236    act_button(ui, ask_act(&ctx, app, job, request));
237}
238
239/// An action as a small button.
240fn act_button(ui: &mut Ui, act: Act<'_>) {
241    let r = ui.add_enabled(act.enabled, egui::Button::new(&act.label).small());
242    a11y::name(&r, egui::Role::Button, &act.name);
243    if r.clicked() {
244        (act.run)();
245    }
246}
247
248/// The room a row leaves its title and state, below which its actions
249/// fold into one "…" menu (VS Code's and the menu bar's overflow).
250const MIN_TEXT: f32 = 96.0;
251
252/// A row's head after its leading symbols: its actions first, at its
253/// end, then its title and state in the room they leave, each cut with
254/// an ellipsis and whole in its tooltip (and its accessible name). The
255/// actions are buttons while the title and state keep [`MIN_TEXT`],
256/// else one "…" menu named "Actions: title" holding them. `tip` is a
257/// tooltip of the title's own.
258fn row_head(
259    ui: &mut Ui,
260    title: &str,
261    tip: Option<&str>,
262    state: &str,
263    color: egui::Color32,
264    acts: Vec<Act<'_>>,
265) {
266    use egui::{Align, Layout, Rect, UiBuilder, pos2, vec2};
267    let ctx = ui.ctx().clone();
268    let gap = ui.spacing().item_spacing.x;
269    let height = ui.spacing().interact_size.y;
270    let row = Rect::from_min_size(ui.cursor().min, vec2(ui.available_width().max(0.0), height));
271    // The buttons' width, as the text they hold and their padding make it.
272    let font = egui::TextStyle::Body.resolve(ui.style());
273    let pad = ui.spacing().button_padding.x * 2.0;
274    let buttons: f32 = acts
275        .iter()
276        .map(|a| {
277            ctx.fonts_mut(|f| {
278                f.layout_no_wrap(a.label.clone(), font.clone(), egui::Color32::PLACEHOLDER)
279                    .size()
280                    .x
281            }) + pad
282        })
283        .sum::<f32>()
284        + gap * acts.len().saturating_sub(1) as f32;
285    let fold = !acts.is_empty() && row.width() - buttons - gap < MIN_TEXT;
286    let mut end = row.right();
287    if !acts.is_empty() {
288        let drawn = ui.scope_builder(
289            UiBuilder::new()
290                .max_rect(row)
291                .layout(Layout::right_to_left(Align::Center)),
292            |ui| {
293                if fold {
294                    more_menu(ui, title, acts);
295                } else {
296                    // Right to left: the first declared ends up rightmost.
297                    for act in acts {
298                        act_button(ui, act);
299                    }
300                }
301            },
302        );
303        end = drawn.response.rect.left() - gap;
304    }
305    let room = Rect::from_min_max(row.min, pos2(end.max(row.left()), row.bottom()));
306    ui.scope_builder(
307        UiBuilder::new()
308            .max_rect(room)
309            .layout(Layout::left_to_right(Align::Center)),
310        |ui| {
311            let state = RichText::new(state).small().color(color);
312            let state_width = egui::WidgetText::from(state.clone())
313                .into_galley(
314                    ui,
315                    Some(egui::TextWrapMode::Extend),
316                    f32::INFINITY,
317                    egui::TextStyle::Body,
318                )
319                .size()
320                .x;
321            // The state keeps its words while the title keeps half the room.
322            let width = room.width();
323            let for_title = (width - state_width - gap).max(width * 0.5).max(0.0);
324            let shown = ui
325                .allocate_ui(vec2(for_title, height), |ui| {
326                    ui.add(egui::Label::new(RichText::new(title).strong()).truncate())
327                })
328                .inner;
329            if let Some(tip) = tip {
330                shown.on_hover_text(tip);
331            }
332            ui.add(egui::Label::new(state).truncate());
333        },
334    );
335}
336
337/// A row's actions folded into one "…" button, its menu holding them.
338fn more_menu(ui: &mut Ui, title: &str, acts: Vec<Act<'_>>) {
339    let name = strings::tr_args(ui.ctx(), &txt::JOB_ACTIONS_NAME, &[("job", title)]);
340    let r = ui.add(Icon::More.size(Size::Inline).label(&name).sense_click());
341    egui::Popup::menu(&r).show(|ui| {
342        for act in acts {
343            let b = ui.add_enabled(act.enabled, egui::Button::new(&act.label));
344            a11y::name(&b, egui::Role::Button, &act.name);
345            if b.clicked() {
346                (act.run)();
347                ui.close();
348            }
349        }
350    });
351    egui_pop_core::overlay::follow_menu(&r, "jobs row menu");
352}
353
354/// Lines without their ANSI escapes, for the plain console.
355fn plain(line: &str) -> String {
356    let mut out = String::with_capacity(line.len());
357    let mut chars = line.chars().peekable();
358    while let Some(c) = chars.next() {
359        if c == '\x1b' {
360            if chars.peek() == Some(&'[') {
361                chars.next();
362                for d in chars.by_ref() {
363                    if ('@'..='~').contains(&d) {
364                        break;
365                    }
366                }
367            }
368            continue;
369        }
370        out.push(c);
371    }
372    out
373}
374
375/// The log console as plain lines (no pseudo-terminal provided).
376fn plain_log(ui: &mut Ui, jobs: &JobsService, job: &Job) {
377    let ctx = ui.ctx().clone();
378    let lines = jobs.log_from(&job.id, 0);
379    Kit::of(&ctx)
380        .job_log
381        .show(ui, State::REST, egui::Shadow::NONE, |ui| {
382            ui.scroll_area(
383                egui::ScrollArea::vertical()
384                    .id_salt(("egui_pop_job_log", &job.id))
385                    .max_height(LOG_HEIGHT)
386                    .stick_to_bottom(true)
387                    .auto_shrink([false, true]),
388                |ui| {
389                    if lines.is_empty() {
390                        ui.weak(strings::tr(&ctx, &txt::JOB_NO_LOG));
391                    }
392                    for l in &lines {
393                        ui.label(RichText::new(plain(l)).monospace());
394                    }
395                },
396            );
397        });
398}
399
400/// A job's badge ([`JobBadge`]): its registry icon in its tone, its tip
401/// in a tooltip and as its accessible name. A name the registry does not
402/// know draws the placeholder and is logged once
403/// ([`registry::resolve`](egui_pop_core::icon::registry::resolve)).
404fn badge_icon(ui: &mut Ui, badge: &JobBadge) {
405    use egui_pop_core::icon::{IconWidget, Source, Tone as IconTone, registry};
406    use egui_pop_model::admin::Tone as BadgeTone;
407    const SURFACE: &str = "jobs centre badge";
408    registry::record(ui.ctx(), SURFACE, &badge.tip, &badge.icon);
409    let tone = match badge.tone {
410        Some(BadgeTone::Info) => IconTone::Info,
411        Some(BadgeTone::Success) => IconTone::Success,
412        Some(BadgeTone::Warning) => IconTone::Warning,
413        Some(BadgeTone::Danger) => IconTone::Danger,
414        Some(BadgeTone::Muted) => IconTone::Muted,
415        None => IconTone::Default,
416    };
417    let r = ui.add(
418        IconWidget::new(Source::named(&badge.icon, SURFACE))
419            .size(Size::Inline)
420            .tone(tone)
421            .label(&badge.tip),
422    );
423    if !badge.tip.is_empty() {
424        r.on_hover_text(&badge.tip);
425    }
426}
427
428/// A job's actions, the first declared rightmost: while it goes on,
429/// cancel, pause or resume (and dismiss once nothing may end it); once
430/// ended, dismiss, retry and its own.
431fn job_acts<'a>(
432    ctx: &egui::Context,
433    app: &'a AppHandle,
434    jobs: &'a JobsService,
435    job: &'a Job,
436) -> Vec<Act<'a>> {
437    let mut acts = Vec::new();
438    let dismiss = |acts: &mut Vec<Act<'a>>| {
439        let label = strings::tr(ctx, &txt::JOB_DISMISS);
440        acts.push(Act::new(ctx, label, &job.title, true, move || {
441            jobs.dismiss(&job.id);
442        }));
443    };
444    if job.active() {
445        if job.cancellable && job.state != JobState::Cancelling {
446            acts.push(ask_act(ctx, app, job, Request::Cancel));
447        }
448        if job.pausable && job.state == JobState::Running {
449            acts.push(ask_act(ctx, app, job, Request::Pause));
450        }
451        if job.state == JobState::Paused {
452            acts.push(ask_act(ctx, app, job, Request::Resume));
453        }
454        if job.orphaned.is_some() {
455            // Nothing may ever end it: it can be forgotten.
456            dismiss(&mut acts);
457        }
458    } else {
459        dismiss(&mut acts);
460        if job.retryable && job.state != JobState::Done {
461            acts.push(ask_act(ctx, app, job, Request::Retry));
462        }
463        for a in &job.actions {
464            let command = egui_pop_model::ids::CommandId::new(&a.command).ok();
465            let enabled = command.is_some();
466            acts.push(Act::new(
467                ctx,
468                a.title.clone(),
469                &job.title,
470                enabled,
471                move || {
472                    if let Some(id) = command {
473                        app.run(id, a.args.clone());
474                    }
475                },
476            ));
477        }
478    }
479    acts
480}
481
482/// Draws one job, its log console when open, and its children.
483pub fn job_row(ui: &mut Ui, app: &AppHandle, jobs: &JobsService, job: &Job, depth: usize) {
484    let ctx = ui.ctx().clone();
485    let t = Tokens::of(&ctx);
486    let now = jobs.now();
487    let indent = t.space.l * depth as f32;
488    let open = jobs.expanded(&job.id);
489    ui.horizontal(|ui| {
490        ui.add_space(indent);
491        let (icon, key) = if open {
492            (Icon::ChevronDown, &txt::JOB_HIDE_LOG)
493        } else {
494            (Icon::ChevronRight, &txt::JOB_SHOW_LOG)
495        };
496        let name = strings::tr_args(&ctx, key, &[("job", &job.title)]);
497        let chevron = ui.add(icon.size(Size::Inline).label(&name).sense_click());
498        if chevron.clicked() {
499            jobs.set_expanded(&job.id, !open);
500        }
501        if let Some(badge) = &job.badge {
502            badge_icon(ui, badge);
503        }
504        let color = match job.state {
505            JobState::Failed => t.status.danger,
506            JobState::Done if job.failed > 0 => t.status.warning,
507            JobState::Done => t.status.success,
508            _ => t.text.muted,
509        };
510        let acts = if job.parent.is_some() {
511            Vec::new()
512        } else {
513            job_acts(&ctx, app, jobs, job)
514        };
515        row_head(ui, &job.title, None, &state_text(&ctx, job), color, acts);
516    });
517    let inset = indent + t.size.icon_inline + t.space.s;
518    ui.horizontal(|ui| {
519        ui.add_space(inset);
520        ui.vertical(|ui| {
521            let mut bar = ProgressBar::new(job.fraction.map(|f| f as f32))
522                .tone(tone(job))
523                .label(&job.title);
524            if let Some(total) = job.total.filter(|t| *t > 0) {
525                let share = |n: u64| (n as f64 / total as f64) as f32;
526                if job.failed > 0 {
527                    bar = bar.section(share(job.failed), Tone::Danger, "failed");
528                }
529                if job.skipped > 0 {
530                    bar = bar.section(share(job.skipped), Tone::Muted, "skipped");
531                }
532            }
533            let detail = detail_text(&ctx, job, now);
534            if !detail.is_empty() {
535                bar = bar.text(&detail);
536            }
537            ui.add(bar);
538            if !detail.is_empty() {
539                ui.meta(&detail);
540            }
541            if let Some(e) = &job.error
542                && !e.is_empty()
543            {
544                ui.label(RichText::new(e).small().color(t.status.danger));
545            }
546            if job.failed > 0 && !job.errors.is_empty() {
547                let failed =
548                    strings::tr_with(&ctx, &txt::JOBS_FAILED, &[("count", job.failed.into())]);
549                egui::CollapsingHeader::new(RichText::new(failed).small().color(t.status.warning))
550                    .id_salt(("egui_pop_job_errors", &job.id))
551                    .show(ui, |ui| {
552                        for e in job.errors.iter().rev().take(20) {
553                            ui.label(RichText::new(format!("{}: {}", e.item, e.error)).small());
554                        }
555                    });
556            }
557            if let Some(e) = &job.request_error {
558                ui.label(
559                    RichText::new(strings::tr_args(&ctx, &txt::JOB_REFUSED, &[("error", e)]))
560                        .small()
561                        .color(t.status.danger),
562                );
563            }
564            if open {
565                match app.service(&JOB_LOG_VIEW) {
566                    Some(view) => view.show(ui, app, job),
567                    None => plain_log(ui, jobs, job),
568                }
569            }
570        });
571    });
572    for child in jobs.children(&job.id) {
573        job_row(ui, app, jobs, &child, depth + 1);
574    }
575}
576
577/// An application row's state as words.
578pub fn row_state_text(ctx: &egui::Context, state: RowState) -> String {
579    strings::tr(
580        ctx,
581        match state {
582            RowState::Queued => &txt::JOB_QUEUED,
583            RowState::Running => &txt::JOB_RUNNING,
584            RowState::Waiting => &txt::JOB_WAITING,
585            RowState::Done => &txt::JOB_DONE,
586            RowState::Failed => &txt::JOB_FAILED,
587        },
588    )
589}
590
591/// The tone an application row's bar takes.
592fn row_tone(state: RowState) -> Tone {
593    match state {
594        RowState::Running => Tone::Accent,
595        RowState::Queued | RowState::Waiting => Tone::Muted,
596        RowState::Done => Tone::Success,
597        RowState::Failed => Tone::Danger,
598    }
599}
600
601/// An application row's action: its label (the kind's, or its own),
602/// named with the row; a click runs its command.
603fn row_act<'a>(
604    ctx: &egui::Context,
605    app: &'a AppHandle,
606    row: &JobRow,
607    action: &'a RowAction,
608) -> Act<'a> {
609    let label = action.title.clone().unwrap_or_else(|| {
610        strings::tr(
611            ctx,
612            match action.kind {
613                RowActionKind::Cancel => &strings::CANCEL,
614                RowActionKind::Retry => &strings::RETRY,
615                RowActionKind::Open => &txt::JOB_OPEN,
616            },
617        )
618    });
619    let command = egui_pop_model::ids::CommandId::new(&action.command).ok();
620    let busy = command.as_ref().is_some_and(|c| app.running(c));
621    let enabled = command.is_some() && !busy;
622    Act::new(ctx, label, &row.title, enabled, move || {
623        if let Some(command) = command {
624            app.run(command, action.args.clone());
625        }
626    })
627}
628
629/// Draws one row of an application's source: its symbol, title, state
630/// and actions, then its bar (when it knows its progress) and its
631/// detail, also its tooltip. A list item named "title, state".
632pub fn source_row(ui: &mut Ui, app: &AppHandle, row: &JobRow) {
633    let ctx = ui.ctx().clone();
634    let t = Tokens::of(&ctx);
635    let state = row_state_text(&ctx, row.state);
636    let item = ui.vertical(|ui| {
637        ui.horizontal(|ui| {
638            if let Some(badge) = &row.badge {
639                badge_icon(ui, badge);
640            }
641            let color = match row.state {
642                RowState::Failed => t.status.danger,
643                RowState::Done => t.status.success,
644                _ => t.text.muted,
645            };
646            let acts = row
647                .actions
648                .iter()
649                .map(|a| row_act(&ctx, app, row, a))
650                .collect();
651            row_head(ui, &row.title, row.detail.as_deref(), &state, color, acts);
652        });
653        let inset = if row.badge.is_some() {
654            t.size.icon_inline + t.space.s
655        } else {
656            0.0
657        };
658        ui.horizontal(|ui| {
659            ui.add_space(inset);
660            ui.vertical(|ui| {
661                if let Some(p) = row.progress {
662                    let mut bar = ProgressBar::new(Some(p as f32))
663                        .tone(row_tone(row.state))
664                        .label(&row.title);
665                    if let Some(detail) = &row.detail {
666                        bar = bar.text(detail);
667                    }
668                    ui.add(bar);
669                }
670                if let Some(detail) = row.detail.as_ref().filter(|d| !d.is_empty()) {
671                    ui.meta(detail);
672                }
673            });
674        });
675    });
676    a11y::name(
677        &item.response,
678        egui::Role::ListItem,
679        &strings::tr_args(
680            &ctx,
681            &txt::JOB_ROW_NAME,
682            &[("job", &row.title), ("state", &state)],
683        ),
684    );
685}
686
687/// A source's rows that the filter admits, under its title, by group
688/// (rows without a group first). Whether it drew any.
689fn source_rows(ui: &mut Ui, app: &AppHandle, source: &RowSource, filter: &RowFilter) -> bool {
690    let rows: Vec<&JobRow> = source
691        .rows
692        .iter()
693        .filter(|r| filter.admits(&source.id, r.state))
694        .collect();
695    if rows.is_empty() {
696        return false;
697    }
698    let t = Tokens::of(ui.ctx());
699    let mut groups: Vec<Option<&str>> = Vec::new();
700    for r in &rows {
701        let g = r.group.as_deref();
702        if !groups.contains(&g) {
703            groups.push(g);
704        }
705    }
706    groups.sort_by_key(Option::is_some);
707    ui.section_title(&source.title);
708    let list = ui.vertical(|ui| {
709        for group in groups {
710            if let Some(g) = group {
711                ui.weak(g);
712            }
713            for row in rows.iter().filter(|r| r.group.as_deref() == group) {
714                source_row(ui, app, row);
715                ui.add_space(t.space.s);
716            }
717        }
718    });
719    a11y::name(&list.response, egui::Role::List, &source.title);
720    true
721}
722
723/// The filter bar, when an application declared a source: a toggle per
724/// source (egui-pop's jobs first), then the states shown.
725fn filter_bar(ui: &mut Ui, jobs: &JobsService, sources: &[RowSource]) {
726    let ctx = ui.ctx().clone();
727    let mut filter = jobs.filter();
728    let before = filter.clone();
729    let bar = ui.horizontal_wrapped(|ui| {
730        let own = strings::tr(&ctx, &txt::JOBS_TITLE);
731        let all = std::iter::once((OWN_SOURCE, own.as_str()))
732            .chain(sources.iter().map(|s| (s.id.as_str(), s.title.as_str())));
733        for (id, title) in all {
734            let shown = filter.shows(id);
735            let r = ui.selectable_label(shown, title);
736            let name = strings::tr_args(&ctx, &txt::JOBS_FILTER_SOURCE, &[("source", title)]);
737            r.widget_info(move || {
738                egui::WidgetInfo::selected(egui::Role::CheckBox, true, shown, &name)
739            });
740            if r.clicked() {
741                filter.set_shown(id, !shown);
742            }
743        }
744        ui.separator();
745        for state in StateFilter::ALL {
746            let label = strings::tr(
747                &ctx,
748                match state {
749                    StateFilter::All => &txt::JOBS_STATE_ALL,
750                    StateFilter::Active => &txt::JOBS_STATE_ACTIVE,
751                    StateFilter::Done => &txt::JOBS_STATE_DONE,
752                    StateFilter::Failed => &txt::JOBS_STATE_FAILED,
753                },
754            );
755            let on = filter.state == state;
756            let r = ui.selectable_label(on, &label);
757            let name = strings::tr_args(&ctx, &txt::JOBS_FILTER_STATE, &[("state", &label)]);
758            r.widget_info(move || {
759                egui::WidgetInfo::selected(egui::Role::RadioButton, true, on, &name)
760            });
761            if r.clicked() {
762                filter.state = state;
763            }
764        }
765    });
766    a11y::name(
767        &bar.response,
768        egui::Role::Toolbar,
769        &strings::tr(&ctx, &txt::JOBS_FILTER),
770    );
771    if filter != before {
772        jobs.set_filter(filter);
773    }
774}
775
776/// The list: the filter bar (when an application declared a row
777/// source), the jobs going on, each source's rows, then the history.
778/// Without a source it is the jobs alone, unfiltered.
779pub fn show(ui: &mut Ui, app: &AppHandle) {
780    let ctx = ui.ctx().clone();
781    let t = Tokens::of(&ctx);
782    let Some(jobs) = app.service(&JOBS) else {
783        return;
784    };
785    let sources = jobs.sources();
786    let filter = if sources.is_empty() {
787        RowFilter::default()
788    } else {
789        filter_bar(ui, &jobs, &sources);
790        ui.add_space(t.space.s);
791        jobs.filter()
792    };
793    let roots: Vec<Job> = jobs
794        .roots()
795        .into_iter()
796        .filter(|j| filter.admits_job(j))
797        .collect();
798    let (active, ended): (Vec<&Job>, Vec<&Job>) = roots.iter().partition(|j| j.active());
799    for job in &active {
800        job_row(ui, app, &jobs, job, 0);
801        ui.add_space(t.space.s);
802    }
803    let mut drawn = !roots.is_empty();
804    for source in &sources {
805        drawn |= source_rows(ui, app, source, &filter);
806    }
807    if !drawn {
808        ui.weak(strings::tr(&ctx, &txt::JOBS_NONE));
809        return;
810    }
811    if !ended.is_empty() {
812        ui.add_space(t.space.s);
813        ui.horizontal(|ui| {
814            ui.section_title(strings::tr(&ctx, &txt::JOBS_HISTORY));
815            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
816                if ui
817                    .small_button(strings::tr(&ctx, &txt::JOBS_CLEAR))
818                    .clicked()
819                {
820                    jobs.clear_finished();
821                }
822            });
823        });
824        for job in ended.iter().rev() {
825            job_row(ui, app, &jobs, job, 0);
826            ui.add_space(t.space.s);
827        }
828    }
829}
830
831/// The popover from the status bar's jobs item: the list, and a way to
832/// the panel.
833pub(crate) fn popover(ui: &mut Ui, app: &AppHandle, response: &egui::Response) {
834    let ctx = ui.ctx().clone();
835    let t = Tokens::of(&ctx);
836    egui::Popup::from_toggle_button_response(response)
837        .id(popover_id())
838        .kind(egui::PopupKind::Popup)
839        .align(egui::RectAlign::TOP_START)
840        .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
841        .show(|ui| {
842            ui.set_width(t.size.dialog_width.min(420.0));
843            ui.horizontal(|ui| {
844                ui.section_title(strings::tr(&ctx, &txt::JOBS_TITLE));
845                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
846                    if app.panels().iter().any(|p| p.id == PANEL_JOBS)
847                        && ui
848                            .small_button(strings::tr(&ctx, &txt::JOBS_OPEN_PANEL))
849                            .clicked()
850                    {
851                        app.focus_panel(&PANEL_JOBS);
852                        egui::Popup::close_id(&ctx, popover_id());
853                    }
854                });
855            });
856            ui.separator();
857            ui.scroll_area(
858                egui::ScrollArea::vertical()
859                    .max_height(360.0)
860                    .auto_shrink([false, true]),
861                |ui| show(ui, app),
862            );
863            egui_pop_core::focus::keep_tab(ui);
864        });
865    // On the bus (ADR 0029): opened, closed and how.
866    egui_pop_core::overlay::follow_popup(
867        &ctx,
868        popover_id(),
869        "jobs popover",
870        popover_open(&ctx),
871        None,
872    );
873}
874
875/// The popover's id.
876pub fn popover_id() -> egui::Id {
877    egui::Id::unique("egui_pop.jobs.popover")
878}
879
880/// Whether the jobs popover is open.
881pub fn popover_open(ctx: &egui::Context) -> bool {
882    egui::Popup::is_id_open(ctx, popover_id())
883}
884
885/// Opens or closes the jobs popover.
886pub fn toggle_popover(ctx: &egui::Context) {
887    egui::Popup::toggle_id(ctx, popover_id());
888}
889
890/// A job's progress as a toast draws it: its bar and, while it goes
891/// on, a button to cancel it; once ended, its first action.
892pub(crate) fn toast_part(ui: &mut Ui, app: &AppHandle, id: &str) -> Option<bool> {
893    let jobs = app.service(&JOBS)?;
894    let job = jobs.job(id)?;
895    let ctx = ui.ctx().clone();
896    ui.add(
897        ProgressBar::new(job.fraction.map(|f| f as f32))
898            .tone(tone(&job))
899            .label(&job.title)
900            .text(detail_text(&ctx, &job, jobs.now())),
901    );
902    ui.horizontal(|ui| {
903        ui.label(RichText::new(state_text(&ctx, &job)).small());
904        if job.active() && job.cancellable && job.state != JobState::Cancelling {
905            ask_button(ui, app, &job, Request::Cancel);
906        } else if let Some(a) = job.actions.first()
907            && ui.small_button(&a.title).clicked()
908            && let Ok(command) = egui_pop_model::ids::CommandId::new(&a.command)
909        {
910            app.run(command, a.args.clone());
911        }
912    });
913    Some(job.active())
914}
915
916#[cfg(test)]
917mod tests {
918    use super::plain;
919
920    #[test]
921    fn the_plain_console_drops_ansi_escapes() {
922        assert_eq!(plain("\x1b[1;32mok\x1b[0m done"), "ok done");
923    }
924}