Skip to main content

egui_pop_api/
jobs.rs

1//! Jobs, as a plugin ([`JobsPlugin`], opt-in): the host's background
2//! work, followed on the bus ([ADR 0029](crate::bus)). The host publishes
3//! its job events on `pop.job.event`, each typed by a
4//! [`JobEventKind`] (see [`egui_pop_model::jobs`] for their data), with
5//! the [`JobPublisher`](crate::bus::JobPublisher) the application hands
6//! it ([`Host::set_job_publisher`](crate::host::Host::set_job_publisher));
7//! no journal entry is read by its name. The bus delivers each once, in
8//! journal order, to the listeners of `pop.job.event`
9//! (each pass, and before a read that must see them all), and the
10//! [`Jobs`] model behind the [`JOBS`] service is one of them
11//! ([`MODEL`], `pop.jobs.model`): no job state changes but on a bus event or
12//! request. Nothing polls: without events, nothing is read.
13//!
14//! <div class="warning">Experimental: may change in any release
15//! (docs/stability.md).</div>
16//!
17//! - **Every job carries an estimated overall fraction**
18//!   ([`Job::fraction`]): sub-steps and child jobs roll up, weighted by
19//!   their estimates; a job that cannot estimate is indeterminate until
20//!   it can. The `jobs.estimate` step (ADR 0011) lets an application
21//!   refine it: a run-hook or an after-hook sees the job and gives
22//!   `{ "fraction": 0.4 }` (or `null`: the model's own). It runs only
23//!   when a plugin hooks it, once per pass for each job that moved, so
24//!   a job's progress does not double the journal.
25//! - Cancel, pause, resume and retry are requests on the bus
26//!   (`pop.job.cancel`, `pop.job.pause`, `pop.job.resume`, `pop.job.retry`,
27//!   [`AppHandle::request_job`]; [`ask`] asks one): [`MODEL`] marks the
28//!   job as waiting for the answer, then [`HOST`] runs its command (each
29//!   `{ "id" }`), declared for the host to run, or run in-process by a
30//!   runner the application gives ([`JobsPlugin::run_locally`]). The
31//!   answer is the runner's job events.
32//! - A job belongs to a plugin when its `job.started` names it (`owner`,
33//!   or `command`, a command of the plugin), or when the plugin
34//!   published it itself. When that plugin is disconnected (ADR 0028),
35//!   [`CANCEL_ON_DISCONNECT`] (a listener of `pop.plugin.disconnect`, run
36//!   before `plugin.disconnected` is said) asks the host to cancel its
37//!   jobs that can be (`job.cancel` with `{ "id", "reason" }`, from
38//!   `egui_pop`; the job
39//!   keeps the reason, [`Job::reason`]) and publishes `job.orphaned` for
40//!   the others, which go on, marked ([`Job::orphaned`]: the jobs centre
41//!   says "its plugin is off") until they end or the plugin is back
42//!   (`job.adopted`, said by [`ADOPT_ON_CONNECT`], a listener of
43//!   `pop.plugin.connect`). `plugin.disconnected` counts both
44//!   (`jobs_cancelled`, `jobs_orphaned`). An orphaned job is not waited
45//!   on: [`JobsService::idle`] leaves it out (nothing owns it, it may
46//!   never end) and [`JobsService::orphans`] lists it.
47//! - An application adds rows of its own, as **row sources**
48//!   ([`egui_pop_model::job_rows`]): it asks `pop.jobs.rows` with a
49//!   source's every row ([`AppHandle::request_job_rows`], or on the bus
50//!   from any thread) and `pop.jobs.source.drop` to take it away; the
51//!   plugin's listener ([`JOB_SOURCES`]) keeps them
52//!   ([`JobsService::sources`]) and the jobs centre shows them beside the
53//!   jobs, filtered by source and state ([`JobsService::filter`]). A
54//!   plugin disconnected takes the sources it owns with it
55//!   (`job_sources_dropped` in `plugin.disconnected`'s counts).
56//! - Time left comes from the plugin's clock ([`JobsPlugin::clock`]),
57//!   the motion clock by default (`egui_pop_core::motion`, frozen in
58//!   tests); tests may give a
59//!   [`ManualClock`](egui_pop_model::clock::ManualClock) of their own.
60//! - The debug bridge's `jobs` collector shows every job (state,
61//!   fraction, counts, time left, the end of its log) and whether the
62//!   application is idle; its actions ask the host as the buttons do.
63//!
64//! ```
65//! use egui_pop_api::App;
66//! use egui_pop_api::jobs::{JOBS, JobsPlugin};
67//! use egui_pop_model::jobs::JobEventKind;
68//! use serde_json::json;
69//!
70//! let mut app = App::builder()
71//!     .plugin(JobsPlugin::default())
72//!     .build(&egui::Context::default())
73//!     .unwrap();
74//! let h = app.handle().clone();
75//! h.publish_job("host", JobEventKind::Started, json!({ "id": "export", "title": "Export", "total": 8 }));
76//! h.publish_job("host", JobEventKind::Progress, json!({ "id": "export", "done": 2 }));
77//! app.logic(&egui::Context::default());
78//! let jobs = h.service(&JOBS).unwrap();
79//! assert_eq!(jobs.job("export").unwrap().fraction, Some(0.25));
80//! assert!(!jobs.idle());
81//! ```
82
83use std::collections::BTreeSet;
84use std::fmt;
85use std::rc::Rc;
86use std::sync::Mutex;
87
88use egui::Ui;
89use egui_pop_core::debug::FnCollector;
90use egui_pop_core::lock;
91use egui_pop_core::progress::{Tone, paint_ring};
92use egui_pop_core::strings::{self, Arg};
93use egui_pop_core::theme::Tokens;
94use egui_pop_core::ui::UiPop as _;
95use egui_pop_model::clock::SharedClock;
96use egui_pop_model::commands::CommandSpec;
97use egui_pop_model::commands::Origin;
98use egui_pop_model::ids::{BlockId, CommandId, PluginId, StepId};
99use egui_pop_model::job_rows::{RowFilter, RowSource};
100use egui_pop_model::jobs::{Incoming, Job, JobEventKind, Jobs, Left, Request, Summary};
101use egui_pop_model::panels::{Area, PanelSpec};
102use serde_json::{Value as Json, json};
103
104use crate::app::AppHandle;
105use crate::bus::{
106    self, JOB_SOURCES, JobAsk, JobCancel, JobEvent, JobEvents, JobPause, JobResume, JobRetry,
107    JobRowsAsk, JobRowsSet, JobSourceDrop, PluginConnect, PluginDisconnect,
108};
109use crate::hooks::On;
110use crate::services::ServiceToken;
111use crate::steps::StepSpec;
112use crate::strings as txt;
113use crate::zones::{self, Block};
114use crate::{Ctx, Plugin, PluginError};
115use bus_contract::{Bus, ListenOpts, Point};
116
117/// The jobs, as a service.
118pub const JOBS: ServiceToken<JobsService> = ServiceToken::new("egui_pop.jobs");
119
120pub const CMD_CANCEL: CommandId = CommandId::from_static("job.cancel");
121pub const CMD_PAUSE: CommandId = CommandId::from_static("job.pause");
122pub const CMD_RESUME: CommandId = CommandId::from_static("job.resume");
123pub const CMD_RETRY: CommandId = CommandId::from_static("job.retry");
124
125/// A job's estimate, refined by the application: `{ "id", "title",
126/// "kind", "fraction" (the model's own, `null` while it cannot
127/// estimate), "done", "total", "steps", "step", "elapsed" }`; the result
128/// is `{ "fraction": 0 to 1 }`, or the model's own (or `null`) to leave
129/// it to the model.
130pub const STEP_ESTIMATE: StepId = StepId::from_static("jobs.estimate");
131
132/// The jobs model's listener: of `pop.job.event` (it folds each event), and of
133/// the job requests (the job shows as asked).
134pub const MODEL: &str = "pop.jobs.model";
135/// Runs a job request's command, after [`MODEL`]: the host (or the
136/// application's runner) answers with its events.
137pub const HOST: &str = "pop.jobs.host";
138/// Of `pop.plugin.disconnect`: the jobs a plugin leaves are cancelled, or
139/// said orphaned.
140pub const CANCEL_ON_DISCONNECT: &str = "pop.jobs.cancel-on-disconnect";
141/// Of `pop.plugin.connect`: the jobs a plugin had left are its own again
142/// (`job.adopted`).
143pub const ADOPT_ON_CONNECT: &str = "pop.jobs.adopt-on-connect";
144
145/// Whether `command` is a job command (`job.cancel`…): its dispatch and
146/// answer are job events.
147pub(crate) fn is_job_command(command: &CommandId) -> bool {
148    Request::ALL.into_iter().any(|r| command_of(r) == *command)
149}
150
151/// The command asking `request`.
152pub fn command_of(request: Request) -> CommandId {
153    match request {
154        Request::Cancel => CMD_CANCEL,
155        Request::Pause => CMD_PAUSE,
156        Request::Resume => CMD_RESUME,
157        Request::Retry => CMD_RETRY,
158    }
159}
160
161#[derive(Debug, Default)]
162struct State {
163    jobs: Jobs,
164    /// The motion clock's time at the last event or pass.
165    now: f64,
166    /// The jobs whose log console is open.
167    expanded: BTreeSet<String>,
168    /// The application's row sources, in the order they were declared.
169    sources: Vec<RowSource>,
170    /// What the list shows.
171    filter: RowFilter,
172}
173
174/// The jobs, folded from the journal: what views and agents read.
175pub struct JobsService {
176    state: Mutex<State>,
177    clock: Option<SharedClock>,
178}
179
180impl fmt::Debug for JobsService {
181    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182        f.debug_struct("JobsService")
183            .field("state", &self.state)
184            .field("clock", &self.clock.is_some())
185            .finish()
186    }
187}
188
189impl JobsService {
190    fn new(jobs: Jobs, clock: Option<SharedClock>) -> Self {
191        Self {
192            state: Mutex::new(State {
193                jobs,
194                ..State::default()
195            }),
196            clock,
197        }
198    }
199
200    /// Now, by the plugin's clock (the motion clock by default:
201    /// `egui_pop_core::motion`, frozen in tests).
202    pub fn now(&self) -> f64 {
203        match &self.clock {
204            Some(c) => c.now(),
205            None => lock(&self.state).now,
206        }
207    }
208
209    /// Reads the model.
210    pub fn with<R>(&self, f: impl FnOnce(&Jobs) -> R) -> R {
211        f(&lock(&self.state).jobs)
212    }
213
214    pub fn job(&self, id: &str) -> Option<Job> {
215        self.with(|j| j.get(id).cloned())
216    }
217
218    /// Every job, in the order they first started.
219    pub fn all(&self) -> Vec<Job> {
220        self.with(|j| j.all().into_iter().cloned().collect())
221    }
222
223    /// The top-level jobs, in order.
224    pub fn roots(&self) -> Vec<Job> {
225        self.with(|j| j.roots().into_iter().cloned().collect())
226    }
227
228    pub fn children(&self, id: &str) -> Vec<Job> {
229        self.with(|j| j.children(id).into_iter().cloned().collect())
230    }
231
232    pub fn summary(&self) -> Summary {
233        self.with(Jobs::summary)
234    }
235
236    /// Whether no job that something still owns goes on; orphaned jobs
237    /// are not waited on ([`Jobs::idle`]).
238    pub fn idle(&self) -> bool {
239        self.with(Jobs::idle)
240    }
241
242    /// The orphaned jobs still going on ([`Jobs::orphans`]).
243    pub fn orphans(&self) -> Vec<Job> {
244        self.with(|j| j.orphans().into_iter().cloned().collect())
245    }
246
247    /// A job's log from line `from` on, as far as it is kept.
248    pub fn log_from(&self, id: &str, from: u64) -> Vec<String> {
249        self.with(|j| j.log_from(id, from).into_iter().map(String::from).collect())
250    }
251
252    /// Forgets a finished job and its finished children; a child still
253    /// going on becomes a top-level job. A late event for a job forgotten
254    /// is dropped ([`Jobs::dismiss`]).
255    pub fn dismiss(&self, id: &str) -> bool {
256        let now = self.now();
257        let mut s = lock(&self.state);
258        s.expanded.remove(id);
259        s.jobs.advance(now);
260        s.jobs.dismiss(id)
261    }
262
263    /// Forgets every finished job.
264    pub fn clear_finished(&self) {
265        let now = self.now();
266        let mut s = lock(&self.state);
267        s.jobs.advance(now);
268        s.jobs.clear_finished();
269        let State { jobs, expanded, .. } = &mut *s;
270        expanded.retain(|id| jobs.get(id).is_some());
271    }
272
273    /// Overrides a job's estimate (0 to 1), or gives it back to the
274    /// model: the `jobs.estimate` step's answer.
275    pub(crate) fn refine(&self, id: &str, fraction: Option<f64>) {
276        let now = self.now();
277        lock(&self.state).jobs.refine(id, fraction, now);
278    }
279
280    /// Notes that `request` was asked for a job ([`MODEL`] on a job
281    /// request); whether the job is known.
282    pub(crate) fn mark(&self, id: &str, request: Request) -> bool {
283        let mut s = lock(&self.state);
284        if s.jobs.get(id).is_none() {
285            return false;
286        }
287        s.jobs.request(id, request);
288        true
289    }
290
291    /// Whether a job's log console is open (remembered per job, shared
292    /// by every view of it).
293    pub fn expanded(&self, id: &str) -> bool {
294        lock(&self.state).expanded.contains(id)
295    }
296
297    pub fn set_expanded(&self, id: &str, open: bool) {
298        let mut s = lock(&self.state);
299        if open {
300            s.expanded.insert(id.into());
301        } else {
302            s.expanded.remove(id);
303        }
304    }
305
306    /// The application's row sources, in the order they were declared
307    /// (`pop.jobs.rows`).
308    pub fn sources(&self) -> Vec<RowSource> {
309        lock(&self.state).sources.clone()
310    }
311
312    /// A row source, by id.
313    pub fn source(&self, id: &str) -> Option<RowSource> {
314        lock(&self.state)
315            .sources
316            .iter()
317            .find(|s| s.id == id)
318            .cloned()
319    }
320
321    /// Declares a source or replaces its rows (its title and owner too);
322    /// whether anything changed.
323    pub(crate) fn set_rows(&self, ask: &JobRowsAsk) -> bool {
324        let mut s = lock(&self.state);
325        match s.sources.iter_mut().find(|x| x.id == ask.source) {
326            Some(x) => {
327                let changed = x.title != ask.title || x.owner != ask.owner || x.rows != ask.rows;
328                x.title.clone_from(&ask.title);
329                x.owner.clone_from(&ask.owner);
330                x.rows.clone_from(&ask.rows);
331                changed
332            }
333            None => {
334                let mut source = RowSource::new(&ask.source, &ask.title, &ask.owner);
335                source.rows.clone_from(&ask.rows);
336                s.sources.push(source);
337                true
338            }
339        }
340    }
341
342    /// Takes a source away; whether it was there.
343    pub(crate) fn drop_source(&self, id: &str) -> bool {
344        let mut s = lock(&self.state);
345        let before = s.sources.len();
346        s.sources.retain(|x| x.id != id);
347        s.sources.len() != before
348    }
349
350    /// Takes away the sources any of `owners` declared; their ids.
351    fn drop_owned_by(&self, owners: &[&str]) -> Vec<String> {
352        let mut s = lock(&self.state);
353        let gone: Vec<String> = s
354            .sources
355            .iter()
356            .filter(|x| owners.contains(&x.owner.as_str()))
357            .map(|x| x.id.clone())
358            .collect();
359        s.sources.retain(|x| !gone.contains(&x.id));
360        gone
361    }
362
363    /// What the list shows: the sources hidden and the states shown.
364    pub fn filter(&self) -> RowFilter {
365        lock(&self.state).filter.clone()
366    }
367
368    pub fn set_filter(&self, filter: RowFilter) {
369        lock(&self.state).filter = filter;
370    }
371
372    /// What the `jobs` collector shows.
373    pub fn describe(&self) -> Json {
374        let now = self.now();
375        let s = lock(&self.state);
376        let mut d = s.jobs.describe(now);
377        d["expanded"] = json!(s.expanded);
378        d["sources"] = json!(s.sources);
379        d["filter"] = json!(s.filter);
380        d["now"] = json!(now);
381        d
382    }
383
384    /// A pass: the motion clock's time kept; the jobs that moved since
385    /// the last one.
386    fn pass(&self, app: &AppHandle) -> BTreeSet<String> {
387        let time = egui_pop_core::motion::now(&app.egui());
388        let mut s = lock(&self.state);
389        s.now = time;
390        s.jobs.take_changed()
391    }
392
393    /// Folds one event the bus delivered ([`MODEL`] on `pop.job.event`).
394    fn follow(&self, app: &AppHandle, e: &JobEvent) {
395        let time = egui_pop_core::motion::now(&app.egui());
396        lock(&self.state).now = time;
397        let now = self.now();
398        let incoming = Incoming::new(e.seq, e.kind, &e.data)
399            .source(&e.source)
400            .cause(e.cause);
401        lock(&self.state).jobs.apply(&incoming, now);
402    }
403}
404
405/// The journal's source of what the framework itself asks or says.
406const FRAMEWORK: &str = "egui_pop";
407
408/// Does what [`Jobs::left_by`] found, on the bus alone (the model
409/// follows from there, as for any job event): `job.cancel` is asked for
410/// the jobs that can be, with the reason, and the others are published
411/// as orphaned.
412fn owner_gone(app: &AppHandle, plugin: &str, left: &Left) {
413    if left.is_empty() {
414        return;
415    }
416    let reason = format!("its plugin `{plugin}` is disconnected");
417    for id in &left.cancel {
418        log::info!(target: "egui_pop", "job `{id}`: the host is asked to cancel it: {reason}");
419        // The framework's own request, whoever asked for the plugin to go.
420        app.request_job(
421            JobAsk::new(id.clone(), Request::Cancel)
422                .reason(reason.clone())
423                .by_framework(),
424        );
425    }
426    for id in &left.orphan {
427        log::info!(target: "egui_pop", "job `{id}` is orphaned: {reason}");
428        app.publish_job(
429            FRAMEWORK,
430            JobEventKind::Orphaned,
431            json!({ "id": id, "plugin": plugin, "reason": reason }),
432        );
433    }
434}
435
436/// Asks the host to cancel, pause, resume or retry a job, on the bus
437/// ([`AppHandle::request_job`]): the job shows as waiting for the
438/// answer, and its command runs for whoever acts now.
439pub fn ask(app: &AppHandle, id: &str, request: Request) {
440    app.request_job(JobAsk::new(id, request));
441}
442
443/// Registers `request`'s listeners: [`MODEL`] marks the job, then
444/// [`HOST`] runs its command.
445fn listen_request<P: Point<Input = JobAsk, Value = Vec<String>>>(
446    kernel: &dyn Bus,
447    owner: &str,
448) -> Vec<Result<(), bus_contract::Refused>> {
449    let mine = || ListenOpts::new().owner(owner);
450    vec![
451        kernel.listen::<P>(MODEL, mine().before(HOST), |ask, did| {
452            let Some(app) = bus::asking() else {
453                return Ok(());
454            };
455            if app
456                .service(&JOBS)
457                .is_some_and(|j| j.mark(&ask.id, ask.request))
458            {
459                did.push(format!("{MODEL}: `{}` waits for the answer", ask.id));
460            }
461            Ok(())
462        }),
463        kernel.listen::<P>(HOST, mine().after(MODEL), |ask, did| {
464            let Some(app) = bus::asking() else {
465                return Ok(());
466            };
467            let command = command_of(ask.request);
468            if ask.is_framework() {
469                // Queued as the framework's own request.
470                app.push_request(crate::app::Request::Run {
471                    command: command.clone(),
472                    args: ask.args(),
473                    origin: Origin::Script(FRAMEWORK.into()),
474                });
475            } else {
476                app.run(command.clone(), ask.args());
477            }
478            did.push(format!("{HOST}: `{command}` asked"));
479            Ok(())
480        }),
481    ]
482}
483
484/// Registers the jobs plugin's listeners on the bus, replacing those of
485/// an earlier connection.
486fn listen(app: &AppHandle, owner: &str) {
487    let kernel = app.bus();
488    for point in bus::JOB_POINTS
489        .iter()
490        .chain(&bus::PLUGIN_POINTS)
491        .chain(&bus::JOB_ROW_POINTS)
492    {
493        for id in [
494            MODEL,
495            HOST,
496            CANCEL_ON_DISCONNECT,
497            ADOPT_ON_CONNECT,
498            JOB_SOURCES,
499        ] {
500            kernel.unlisten(point, id);
501        }
502    }
503    let mine = || ListenOpts::new().owner(owner);
504    let mut listened = Vec::new();
505    listened.extend(listen_request::<JobCancel>(&*kernel, owner));
506    listened.extend(listen_request::<JobPause>(&*kernel, owner));
507    listened.extend(listen_request::<JobResume>(&*kernel, owner));
508    listened.extend(listen_request::<JobRetry>(&*kernel, owner));
509    listened.push(kernel.listen::<JobEvents>(MODEL, mine(), |e, _| {
510        if let Some(app) = bus::asking()
511            && let Some(jobs) = app.service(&JOBS)
512        {
513            jobs.follow(&app, e);
514        }
515        Ok(())
516    }));
517    // The row sources: asked from any thread, so the listener holds the
518    // service and the context to wake, not the application.
519    if let Some(service) = app.service(&JOBS) {
520        let ctx = app.egui();
521        let (s, c) = (service.clone(), ctx.clone());
522        listened.push(
523            kernel.listen::<JobRowsSet>(JOB_SOURCES, mine(), move |ask, did| {
524                if s.set_rows(ask) {
525                    did.push(format!(
526                        "{JOB_SOURCES}: `{}` has {} row(s)",
527                        ask.source,
528                        ask.rows.len()
529                    ));
530                    c.request_repaint();
531                }
532                Ok(())
533            }),
534        );
535        listened.push(
536            kernel.listen::<JobSourceDrop>(JOB_SOURCES, mine(), move |ask, did| {
537                if service.drop_source(&ask.source) {
538                    did.push(format!("{JOB_SOURCES}: `{}` dropped", ask.source));
539                    ctx.request_repaint();
540                }
541                Ok(())
542            }),
543        );
544    }
545    listened.push(kernel.listen::<PluginDisconnect>(
546        CANCEL_ON_DISCONNECT,
547        mine(),
548        |change, counts| {
549            let Some(app) = bus::asking() else {
550                return Ok(());
551            };
552            let Some(jobs) = app.service(&JOBS) else {
553                return Ok(());
554            };
555            let commands: Vec<&str> = change.commands.iter().map(String::as_str).collect();
556            let left = jobs
557                .with(|j| j.left_by(&[change.plugin.as_str(), change.owner.as_str()], &commands));
558            owner_gone(&app, &change.plugin, &left);
559            // Its row sources go with it.
560            let dropped = jobs.drop_owned_by(&[change.plugin.as_str(), change.owner.as_str()]);
561            if !dropped.is_empty() {
562                counts.insert("job_sources_dropped".into(), json!(dropped.len()));
563            }
564            // The model follows what was said, in this call.
565            app.deliver_events();
566            counts.insert("jobs_cancelled".into(), json!(left.cancel.len()));
567            counts.insert("jobs_orphaned".into(), json!(left.orphan.len()));
568            Ok(())
569        },
570    ));
571    listened.push(
572        kernel.listen::<PluginConnect>(ADOPT_ON_CONNECT, mine(), |change, did| {
573            let Some(app) = bus::asking() else {
574                return Ok(());
575            };
576            let Some(jobs) = app.service(&JOBS) else {
577                return Ok(());
578            };
579            let back = jobs.with(|j| j.orphaned_by(&change.plugin));
580            if !back.is_empty() {
581                app.publish_job(
582                    FRAMEWORK,
583                    JobEventKind::Adopted,
584                    json!({ "plugin": change.plugin, "jobs": back }),
585                );
586                app.deliver_events();
587                did.push(format!(
588                    "{ADOPT_ON_CONNECT}: {} job(s) its own again",
589                    back.len()
590                ));
591            }
592            Ok(())
593        }),
594    );
595    for l in listened {
596        if let Err(e) = l {
597            log::error!(target: "egui_pop", "jobs: {e}");
598        }
599    }
600}
601
602/// Runs a job command in-process: the application's own job runner.
603pub type Runner = Rc<dyn Fn(&AppHandle, Request, &str) -> Result<Json, String>>;
604
605/// The plugin.
606#[derive(Clone)]
607pub struct JobsPlugin {
608    clock: Option<SharedClock>,
609    runner: Option<Runner>,
610    log_lines: Option<usize>,
611    history: Option<usize>,
612    panel: bool,
613}
614
615impl Default for JobsPlugin {
616    fn default() -> Self {
617        Self {
618            clock: None,
619            runner: None,
620            log_lines: None,
621            history: None,
622            panel: true,
623        }
624    }
625}
626
627impl fmt::Debug for JobsPlugin {
628    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
629        f.debug_struct("JobsPlugin")
630            .field("clock", &self.clock.is_some())
631            .field("runner", &self.runner.is_some())
632            .field("log_lines", &self.log_lines)
633            .field("history", &self.history)
634            .field("panel", &self.panel)
635            .finish()
636    }
637}
638
639impl JobsPlugin {
640    /// Where time left and durations take "now" from (the motion clock
641    /// by default).
642    pub fn clock(mut self, clock: SharedClock) -> Self {
643        self.clock = Some(clock);
644        self
645    }
646
647    /// Runs the job commands in-process instead of declaring them for
648    /// the host: `f(app, request, job id)`.
649    pub fn run_locally(
650        mut self,
651        f: impl Fn(&AppHandle, Request, &str) -> Result<Json, String> + 'static,
652    ) -> Self {
653        self.runner = Some(Rc::new(f));
654        self
655    }
656
657    /// Keeps `lines` lines of each job's log
658    /// ([`LOG_LINES`](egui_pop_model::jobs::LOG_LINES) by default).
659    pub fn log_lines(mut self, lines: usize) -> Self {
660        self.log_lines = Some(lines);
661        self
662    }
663
664    /// Without the jobs panel (the status bar's popover stays).
665    pub fn without_panel(mut self) -> Self {
666        self.panel = false;
667        self
668    }
669
670    /// Keeps `jobs` finished jobs
671    /// ([`HISTORY`](egui_pop_model::jobs::HISTORY) by default).
672    pub fn history(mut self, jobs: usize) -> Self {
673        self.history = Some(jobs);
674        self
675    }
676}
677
678fn spec(request: Request) -> CommandSpec {
679    let (title, description) = match request {
680        Request::Cancel => (
681            "Cancel a job",
682            "Asks the host to cancel the job `id`; it shows as cancelling until the host says it is cancelled.",
683        ),
684        Request::Pause => ("Pause a job", "Asks the host to pause the job `id`."),
685        Request::Resume => (
686            "Resume a job",
687            "Asks the host to resume the paused job `id`.",
688        ),
689        Request::Retry => (
690            "Retry a job",
691            "Asks the host to run the failed or cancelled job `id` again.",
692        ),
693    };
694    CommandSpec::new(command_of(request), title, "Jobs")
695        .description(description)
696        .args(json!({ "id": "export-1" }))
697        .hidden()
698}
699
700/// What the status bar's jobs item says: how many go on (with their
701/// overall estimate), and how many failed.
702pub fn status_text(ctx: &egui::Context, summary: &Summary) -> (String, Option<String>) {
703    let count = Arg::from(summary.active);
704    let active = match summary.fraction {
705        Some(f) => strings::tr_with(
706            ctx,
707            &txt::JOBS_ACTIVE_PERCENT,
708            &[
709                ("count", count),
710                (
711                    "percent",
712                    Arg::Str(&strings::number(ctx, (f * 100.0).round(), 0)),
713                ),
714            ],
715        ),
716        None => strings::tr_with(ctx, &txt::JOBS_ACTIVE, &[("count", count)]),
717    };
718    let failed = (summary.failed > 0)
719        .then(|| strings::tr_with(ctx, &txt::JOBS_FAILED, &[("count", summary.failed.into())]));
720    (active, failed)
721}
722
723/// The status bar's jobs item: a ring with the jobs' overall estimate
724/// (turning while one cannot estimate), how many go on and how many
725/// failed; nothing when there is nothing to say.
726fn status_item(ui: &mut Ui, app: &AppHandle) {
727    let Some(jobs) = app.service(&JOBS) else {
728        return;
729    };
730    let summary = jobs.summary();
731    if summary.active == 0 && summary.failed == 0 {
732        return;
733    }
734    let ctx = ui.ctx().clone();
735    let t = Tokens::of(&ctx);
736    let (active, failed) = status_text(&ctx, &summary);
737    ui.horizontal(|ui| {
738        ui.spacing_mut().item_spacing.x = t.space.s;
739        let mut text = active;
740        if summary.active > 0 {
741            // The ring is drawn only: the button's text names the item.
742            let side = t.size.icon_inline;
743            let (rect, _) = ui.allocate_exact_size(egui::vec2(side, side), egui::Sense::hover());
744            // Only orphaned jobs going on: nothing owns them and they may
745            // never end, so the ring does not spin for them (a spinning
746            // ring asks for a repaint each pass, and the application
747            // would never settle).
748            let owned = jobs.with(|j| j.roots().iter().any(|r| r.active() && r.orphaned.is_none()));
749            let fraction = summary.fraction.map(|f| f as f32);
750            paint_ring(
751                ui,
752                rect,
753                if owned {
754                    fraction
755                } else {
756                    Some(fraction.unwrap_or(0.0))
757                },
758                Tone::Accent.color(&ctx),
759            );
760        } else {
761            text.clear();
762        }
763        let mut label = egui::text::LayoutJob::default();
764        let small = egui::TextFormat {
765            font_id: egui::FontId::proportional(t.font.small),
766            color: t.text.default,
767            ..Default::default()
768        };
769        label.append(&text, 0.0, small.clone());
770        if let Some(failed) = &failed {
771            if !text.is_empty() {
772                label.append("  ", 0.0, small.clone());
773            }
774            label.append(
775                failed,
776                0.0,
777                egui::TextFormat {
778                    color: t.status.danger,
779                    ..small
780                },
781            );
782        }
783        let response = egui_pop_core::widgets::bar_text_button(ui, label);
784        crate::jobs_centre::popover(ui, app, &response);
785    });
786}
787
788/// Whether a plugin hooks `jobs.estimate`.
789fn estimate_hooked(app: &AppHandle) -> bool {
790    app.steps()
791        .iter()
792        .any(|s| s.spec.id == STEP_ESTIMATE && !s.hooks.is_empty())
793}
794
795/// Runs `jobs.estimate` for the jobs that moved, and keeps what the
796/// hooks say.
797fn refine(app: &AppHandle, jobs: &JobsService, moved: &BTreeSet<String>) {
798    let now = jobs.now();
799    for id in moved {
800        let Some(job) = jobs.job(id).filter(Job::active) else {
801            continue;
802        };
803        let own = jobs.with(|j| j.own_fraction(id));
804        let args = json!({
805            "id": job.id,
806            "title": job.title,
807            "kind": job.kind,
808            "fraction": own,
809            "done": job.done,
810            "total": job.total,
811            "steps": job.steps,
812            "step": job.step,
813            "elapsed": job.elapsed(now),
814        });
815        let out = app.step(&STEP_ESTIMATE, args, |_, args| {
816            Ok(json!({ "fraction": args["fraction"] }))
817        });
818        if let Some(Ok(v)) = out.result() {
819            // The model's own given back is no refinement.
820            let refined = v["fraction"].as_f64().filter(|f| Some(*f) != own);
821            if refined != job.refined {
822                jobs.refine(id, refined);
823            }
824        }
825    }
826    // What the refinement changed is not news.
827    let _ = lock(&jobs.state).jobs.take_changed();
828}
829
830impl Plugin for JobsPlugin {
831    fn id(&self) -> PluginId {
832        PluginId::from_static("egui_pop.jobs")
833    }
834
835    fn title(&self) -> String {
836        "Jobs".into()
837    }
838
839    fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
840        let mut model = Jobs::new();
841        if let Some(n) = self.log_lines {
842            model = model.with_log_lines(n);
843        }
844        if let Some(n) = self.history {
845            model = model.with_history(n);
846        }
847        let service = JobsService::new(model, self.clock.clone());
848        // Connected late: the job events said before, up to the last the
849        // bus delivered, from the journal's record; the bus delivers the
850        // rest.
851        let app = ctx.app();
852        let upto = app.delivered_event();
853        if upto > 0 {
854            for e in app.events_since(0).iter().filter(|e| e.seq <= upto) {
855                if let Some(job) = app.job_event_of(e) {
856                    service.follow(&app, &job);
857                }
858            }
859        }
860        ctx.service(&JOBS, service)?;
861        listen(&app, ctx.owner().as_str());
862        for request in Request::ALL {
863            match &self.runner {
864                Some(run) => {
865                    let run = run.clone();
866                    ctx.command(spec(request), move |call| {
867                        let id = call.args["id"]
868                            .as_str()
869                            .ok_or_else(|| "`id` is missing".to_string())?;
870                        run(call.app, request, id)
871                    })?;
872                }
873                None => {
874                    ctx.declare(spec(request))?;
875                }
876            }
877        }
878        ctx.step(
879            StepSpec::new(
880                STEP_ESTIMATE,
881                "A job's estimated fraction, refined by the application (run only when hooked).",
882            )
883            .args(json!({ "id": "export-1", "title": "Export", "kind": "export", "fraction": 0.25, "done": 2, "total": 8, "steps": [], "step": null, "elapsed": 4.0 })),
884        )?;
885        ctx.on(On::Pass, |app, _| {
886            let Some(jobs) = app.service(&JOBS) else {
887                return;
888            };
889            let moved = jobs.pass(app);
890            if !moved.is_empty() && estimate_hooked(app) {
891                refine(app, &jobs, &moved);
892            }
893        });
894        let weak = ctx.app().downgrade();
895        let w = weak.clone();
896        let mut collector = FnCollector::new(
897            "jobs",
898            "The host's jobs folded from its `pop.job.event` events: state, estimated fraction, counts, time left, the end of each log; `idle` says whether any goes on. Actions ask the host (`cancel`, `pause`, `resume`, `retry`, with `id`) or forget finished ones (`dismiss`, `clear`).",
899        )
900        .snapshot(move |_| {
901            w.get()
902                .ok()
903                .and_then(|app| app.service(&JOBS))
904                .map_or(Json::Null, |j| j.describe())
905        });
906        for request in Request::ALL {
907            let w = weak.clone();
908            let name = match request {
909                Request::Cancel => "cancel",
910                Request::Pause => "pause",
911                Request::Resume => "resume",
912                Request::Retry => "retry",
913            };
914            collector = collector
915                .action(
916                    name,
917                    "Asks the host about the job `id`, as its button does.",
918                    true,
919                    move |_, args| {
920                        let app = w.get()?;
921                        let id = args["id"].as_str().ok_or("`id` is missing")?;
922                        if app.service(&JOBS).and_then(|j| j.job(id)).is_none() {
923                            return Err(format!("no job `{id}`"));
924                        }
925                        ask(&app, id, request);
926                        Ok(json!({ "asked": command_of(request), "id": id }))
927                    },
928                )
929                .args(json!({ "id": "export-1" }));
930        }
931        let w = weak.clone();
932        collector = collector
933            .action(
934                "dismiss",
935                "Forgets a finished job (`id`).",
936                true,
937                move |_, args| {
938                    let app = w.get()?;
939                    let id = args["id"].as_str().ok_or("`id` is missing")?;
940                    let jobs = app.service(&JOBS).ok_or("no jobs")?;
941                    if jobs.dismiss(id) {
942                        Ok(json!({ "dismissed": id }))
943                    } else {
944                        Err(format!("no finished job `{id}`"))
945                    }
946                },
947            )
948            .args(json!({ "id": "export-1" }));
949        let w = weak;
950        collector = collector.action("clear", "Forgets every finished job.", true, move |_, _| {
951            let app = w.get()?;
952            app.service(&JOBS).ok_or("no jobs")?.clear_finished();
953            Ok(Json::Null)
954        });
955        ctx.collector(collector)?;
956        ctx.block(
957            zones::STATUS_BAR,
958            Block::add(
959                BlockId::from_static("egui_pop.jobs.status"),
960                900,
961                status_item,
962            ),
963        );
964        if self.panel {
965            ctx.panel(
966                PanelSpec::new(crate::jobs_centre::PANEL_JOBS, "Jobs", Area::Bottom)
967                    .min_size(120.0)
968                    .default_size(240.0)
969                    .icon("history")
970                    .closed(),
971                |ui, app| {
972                    ui.scroll_area(
973                        egui::ScrollArea::vertical().auto_shrink([false, false]),
974                        |ui| crate::jobs_centre::show(ui, app),
975                    );
976                },
977            )?;
978        }
979        Ok(())
980    }
981}