1use 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
117pub 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
125pub const STEP_ESTIMATE: StepId = StepId::from_static("jobs.estimate");
131
132pub const MODEL: &str = "pop.jobs.model";
135pub const HOST: &str = "pop.jobs.host";
138pub const CANCEL_ON_DISCONNECT: &str = "pop.jobs.cancel-on-disconnect";
141pub const ADOPT_ON_CONNECT: &str = "pop.jobs.adopt-on-connect";
144
145pub(crate) fn is_job_command(command: &CommandId) -> bool {
148 Request::ALL.into_iter().any(|r| command_of(r) == *command)
149}
150
151pub 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 now: f64,
166 expanded: BTreeSet<String>,
168 sources: Vec<RowSource>,
170 filter: RowFilter,
172}
173
174pub 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 pub fn now(&self) -> f64 {
203 match &self.clock {
204 Some(c) => c.now(),
205 None => lock(&self.state).now,
206 }
207 }
208
209 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 pub fn all(&self) -> Vec<Job> {
220 self.with(|j| j.all().into_iter().cloned().collect())
221 }
222
223 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 pub fn idle(&self) -> bool {
239 self.with(Jobs::idle)
240 }
241
242 pub fn orphans(&self) -> Vec<Job> {
244 self.with(|j| j.orphans().into_iter().cloned().collect())
245 }
246
247 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 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 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 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 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 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 pub fn sources(&self) -> Vec<RowSource> {
309 lock(&self.state).sources.clone()
310 }
311
312 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 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 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 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 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 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 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 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
405const FRAMEWORK: &str = "egui_pop";
407
408fn 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 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
436pub fn ask(app: &AppHandle, id: &str, request: Request) {
440 app.request_job(JobAsk::new(id, request));
441}
442
443fn 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 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
484fn 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 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 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 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
602pub type Runner = Rc<dyn Fn(&AppHandle, Request, &str) -> Result<Json, String>>;
604
605#[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 pub fn clock(mut self, clock: SharedClock) -> Self {
643 self.clock = Some(clock);
644 self
645 }
646
647 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 pub fn log_lines(mut self, lines: usize) -> Self {
660 self.log_lines = Some(lines);
661 self
662 }
663
664 pub fn without_panel(mut self) -> Self {
666 self.panel = false;
667 self
668 }
669
670 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
700pub 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
723fn 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 let side = t.size.icon_inline;
743 let (rect, _) = ui.allocate_exact_size(egui::vec2(side, side), egui::Sense::hover());
744 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
788fn estimate_hooked(app: &AppHandle) -> bool {
790 app.steps()
791 .iter()
792 .any(|s| s.spec.id == STEP_ESTIMATE && !s.hooks.is_empty())
793}
794
795fn 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 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 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 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}