Skip to main content

egui_pop_api/
toasts.rs

1//! Toasts, as a plugin ([`ToastsPlugin`], in `DefaultPlugins`): short
2//! notices in a corner that never take the focus, each with a level, an
3//! optional action (a command, run through the host) and a close button.
4//! Information and success go after a few seconds, warnings after
5//! longer, errors stay until closed; a thin bar empties as the time
6//! runs, and stops while the pointer is over the toast. Screen readers
7//! hear them through the live region (errors at once).
8//!
9//! They show in a corner of the window, or the middle of its top or
10//! bottom edge (the `appearance.toast_corner` setting, [`Corner`];
11//! `AppBuilder::toast_corner` gives its default), the newest the nearest
12//! to the edge. They slide in from the corner's side and out again in
13//! `motion.toast.slide` (fade in the middle of an edge); under reduced
14//! motion they appear and go at once, and the bar steps once a second.
15//! They cast the shadow of what lies over the interface
16//! (`toast.shadow-*`, aliases of `shadow.popup.*`).
17//!
18//! They keep off what an interface asks them to ([`keep_clear`]): the
19//! Settings app's wizard footer, whose Finish sits in the default corner,
20//! is never under a toast that would take its click.
21//!
22//! Each application window has its own toasts (ADR 0025): a toast
23//! belongs to the window it was raised from (the application window being
24//! drawn, or the one whose command raised it, else the active one;
25//! [`Toasts::notify_in`] names one), and each window stacks its own, up
26//! to [`SHOWN`] at a time. In the main window's group they show in the
27//! window of it the user works in ([`AppHandle::active_window`]): a
28//! detached panel's window while it has the focus, the main window again
29//! when that one closes. A closed application window's toasts go to the
30//! main window.
31//!
32//! The queue is data: [`Toasts::shown`] and [`Toasts::history`], the
33//! debug bridge's `toasts` collector (with `dismiss`), and a
34//! `toast.shown` event in the journal.
35//!
36//! Owned: egui-notify and egui-toast (both MIT) keep a queue of strings,
37//! with no command actions and no state another plugin or an agent can
38//! read; their stacking ideas are reused. From egui-notify (MIT,
39//! <https://github.com/ItsEthra/egui-notify>) come the slide with its
40//! appear, idle and disappear states and its eased value (`toast.rs`,
41//! `lib.rs`), the time-left bar that stops under the pointer (`lib.rs`),
42//! the choice of corner (`anchor.rs`), the newest nearest the edge (its
43//! `reverse`, `lib.rs`) and a shadow under each toast (`lib.rs`); the
44//! code is egui-pop's own.
45//!
46//! ```
47//! use egui_pop_api::toasts::{self, Toast};
48//! use egui_pop_api::App;
49//! use egui_pop_model::ids::CommandId;
50//!
51//! let app = App::builder()
52//!     .plugin(toasts::ToastsPlugin)
53//!     .build(&egui::Context::default())
54//!     .unwrap();
55//! let t = app.handle().service(&toasts::TOASTS).unwrap();
56//! t.notify(Toast::success("Exported 3 images")
57//!     .action("Show", CommandId::from_static("files.reveal"), serde_json::json!({ "path": "out" })));
58//! assert_eq!(t.shown().len(), 1);
59//! ```
60
61use std::collections::VecDeque;
62use std::sync::{Arc, Mutex};
63
64use egui::{Align2, Id, Order, Rect, Ui, UiBuilder, Vec2, vec2};
65use egui_pop_core::a11y::{self, Politeness};
66use egui_pop_core::debug::FnCollector;
67use egui_pop_core::icon::{Icon, Size, Tone};
68use egui_pop_core::kit::{self, Kit};
69use egui_pop_core::lock;
70use egui_pop_core::motion;
71use egui_pop_core::progress::ProgressTokens;
72use egui_pop_core::strings;
73use egui_pop_core::theme::Tokens;
74use egui_pop_model::commands::Origin;
75use egui_pop_model::ids::{BlockId, CommandId, PluginId, SettingId};
76use egui_pop_model::notice::{Notice, NoticeId, Severity};
77use egui_pop_model::values::Descriptor;
78use serde::Serialize;
79use serde_json::{Value as Json, json};
80
81use crate::app::AppHandle;
82use crate::ctx::CtxError;
83use crate::services::ServiceToken;
84use crate::strings as txt;
85use crate::zones::{self, Block};
86use crate::{Ctx, Plugin, PluginError};
87
88/// The toasts, as a service.
89pub const TOASTS: ServiceToken<Toasts> = ServiceToken::new("app.toasts");
90
91/// How many toasts show at once (the others wait).
92pub const SHOWN: usize = 4;
93/// How many past toasts are kept.
94pub const HISTORY: usize = 32;
95
96/// The setting: where the toasts show ([`Corner`]'s choices).
97pub const SETTING_CORNER: SettingId = SettingId::from_static("appearance.toast_corner");
98
99/// Where the toasts show: a corner of the window, or the middle of its
100/// top or bottom edge. The newest is always the nearest to the edge:
101/// at the top under a top corner, at the bottom under a bottom one.
102// The corners as a choice, after egui-notify's `Anchor` (MIT, anchor.rs),
103// with the middle of the top and bottom edges added.
104#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
105#[serde(rename_all = "kebab-case")]
106pub enum Corner {
107    TopLeft,
108    TopCenter,
109    TopRight,
110    BottomLeft,
111    BottomCenter,
112    /// The default.
113    #[default]
114    BottomRight,
115}
116
117impl Corner {
118    /// Every corner, in the setting's order.
119    pub const ALL: [Corner; 6] = [
120        Corner::TopLeft,
121        Corner::TopCenter,
122        Corner::TopRight,
123        Corner::BottomLeft,
124        Corner::BottomCenter,
125        Corner::BottomRight,
126    ];
127
128    /// The setting's choices, in order.
129    pub const CHOICES: [&'static str; 6] = [
130        "top-left",
131        "top-center",
132        "top-right",
133        "bottom-left",
134        "bottom-center",
135        "bottom-right",
136    ];
137
138    pub fn as_str(self) -> &'static str {
139        match self {
140            Corner::TopLeft => "top-left",
141            Corner::TopCenter => "top-center",
142            Corner::TopRight => "top-right",
143            Corner::BottomLeft => "bottom-left",
144            Corner::BottomCenter => "bottom-center",
145            Corner::BottomRight => "bottom-right",
146        }
147    }
148
149    pub fn parse(s: &str) -> Option<Corner> {
150        Corner::ALL.into_iter().find(|c| c.as_str() == s)
151    }
152
153    /// Whether it is on the top edge (the newest toast on top).
154    pub fn top(self) -> bool {
155        matches!(self, Corner::TopLeft | Corner::TopCenter | Corner::TopRight)
156    }
157
158    /// The side a toast slides in from: -1 the left, 1 the right, 0 the
159    /// edge itself (the middle of an edge: it fades as it slides).
160    // egui-notify's `Anchor::anim_side` (MIT, anchor.rs).
161    fn side(self) -> f32 {
162        match self {
163            Corner::TopLeft | Corner::BottomLeft => -1.0,
164            Corner::TopRight | Corner::BottomRight => 1.0,
165            Corner::TopCenter | Corner::BottomCenter => 0.0,
166        }
167    }
168
169    fn align(self) -> Align2 {
170        match self {
171            Corner::TopLeft => Align2::LEFT_TOP,
172            Corner::TopCenter => Align2::CENTER_TOP,
173            Corner::TopRight => Align2::RIGHT_TOP,
174            Corner::BottomLeft => Align2::LEFT_BOTTOM,
175            Corner::BottomCenter => Align2::CENTER_BOTTOM,
176            Corner::BottomRight => Align2::RIGHT_BOTTOM,
177        }
178    }
179
180    /// The area's offset from the window's edges, `margin` away.
181    fn offset(self, margin: f32) -> Vec2 {
182        let x = self.side() * -margin;
183        let y = if self.top() { margin } else { -margin };
184        vec2(x, y)
185    }
186}
187
188/// Where the toasts show, as the setting says now.
189pub fn corner(app: &AppHandle) -> Corner {
190    lock(&app.store())
191        .get(&format!("settings/{SETTING_CORNER}"))
192        .and_then(|e| e.value.as_choice().and_then(Corner::parse))
193        .unwrap_or_default()
194}
195
196/// Declares the setting, under Appearance, `default` its default.
197pub(crate) fn register(ctx: &mut Ctx<'_>, default: Corner) -> Result<(), CtxError> {
198    ctx.setting(
199        SETTING_CORNER,
200        Descriptor::choice("Toast corner", &Corner::CHOICES, default.as_str()).description(
201            "Where toasts show: a corner of the window, or the middle of its top or bottom edge. The newest is the nearest to the edge.",
202        ),
203    )?;
204    Ok(())
205}
206
207/// How much a toast matters.
208#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
209#[serde(rename_all = "lowercase")]
210pub enum Level {
211    Info,
212    Success,
213    Warning,
214    Error,
215}
216
217impl Level {
218    /// Seconds before it goes; none: until closed.
219    pub fn lifetime(self) -> Option<f64> {
220        match self {
221            Level::Info | Level::Success => Some(4.0),
222            Level::Warning => Some(8.0),
223            Level::Error => None,
224        }
225    }
226
227    fn icon(self) -> (Icon, Tone) {
228        match self {
229            Level::Info => (Icon::Info, Tone::Info),
230            Level::Success => (Icon::Success, Tone::Success),
231            Level::Warning => (Icon::Warning, Tone::Warning),
232            Level::Error => (Icon::Error, Tone::Danger),
233        }
234    }
235}
236
237/// A command offered with a toast.
238#[derive(Clone, Debug, PartialEq, Serialize)]
239pub struct ToastAction {
240    pub label: String,
241    pub command: CommandId,
242    pub args: Json,
243}
244
245/// A notice.
246#[derive(Clone, Debug, PartialEq, Serialize)]
247pub struct Toast {
248    pub level: Level,
249    pub text: String,
250    pub action: Option<ToastAction>,
251    /// Seconds before it goes (the level's by default); none: until
252    /// closed.
253    pub lifetime: Option<f64>,
254    /// A job whose progress it carries (`jobs`): its bar, Cancel while
255    /// it goes on, its first action once ended. It stays while the job
256    /// goes on; closing it does not cancel the job.
257    pub job: Option<String>,
258}
259
260impl Toast {
261    pub fn new(level: Level, text: &str) -> Self {
262        Self {
263            level,
264            text: text.into(),
265            action: None,
266            lifetime: level.lifetime(),
267            job: None,
268        }
269    }
270
271    pub fn info(text: &str) -> Self {
272        Self::new(Level::Info, text)
273    }
274
275    pub fn success(text: &str) -> Self {
276        Self::new(Level::Success, text)
277    }
278
279    pub fn warning(text: &str) -> Self {
280        Self::new(Level::Warning, text)
281    }
282
283    pub fn error(text: &str) -> Self {
284        Self::new(Level::Error, text)
285    }
286
287    /// Offers a command; running it closes the toast.
288    pub fn action(mut self, label: &str, command: CommandId, args: Json) -> Self {
289        self.action = Some(ToastAction {
290            label: label.into(),
291            command,
292            args,
293        });
294        self
295    }
296
297    /// Carries a job's progress (see [`Toast::job`]'s field).
298    pub fn job(mut self, id: &str) -> Self {
299        self.job = Some(id.into());
300        self
301    }
302
303    /// Stays until closed.
304    pub fn sticky(mut self) -> Self {
305        self.lifetime = None;
306        self
307    }
308
309    /// Goes after `seconds`.
310    pub fn lifetime(mut self, seconds: f64) -> Self {
311        self.lifetime = Some(seconds);
312        self
313    }
314}
315
316/// Where a toast is in its slide.
317// egui-notify's `ToastState` (MIT, toast.rs): appear, idle, disappear.
318#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
319#[serde(rename_all = "lowercase")]
320pub enum Phase {
321    /// Sliding in (or waiting for its turn, not drawn yet).
322    #[default]
323    Appear,
324    /// In place.
325    Idle,
326    /// Sliding out: it went already ([`Toasts::leaving`]).
327    Disappear,
328}
329
330/// A toast in the queue.
331#[derive(Clone, Debug, PartialEq, Serialize)]
332pub struct Shown {
333    pub id: u64,
334    #[serde(flatten)]
335    pub toast: Toast,
336    /// When it goes, by the motion clock's seconds (set when first
337    /// drawn; moved on while the pointer holds it).
338    pub until: Option<f64>,
339    /// Why it went: `expired`, `closed`, `action`, `dismissed`.
340    pub ended: Option<&'static str>,
341    /// When it was first drawn, by the motion clock.
342    pub since: Option<f64>,
343    /// Where it is in its slide.
344    pub phase: Phase,
345    /// Its time left, 0 to 1, as its bar shows it; none without a bar
346    /// (no lifetime, or a job going on).
347    pub left: Option<f32>,
348    /// Since when the pointer holds it: its time stops meanwhile.
349    pub held: Option<f64>,
350    /// The application window it shows in (`main` or a window's id),
351    /// once it was first drawn.
352    pub window: Option<String>,
353    /// Its window group (`AppHandle::window_group`).
354    #[serde(skip)]
355    group: Option<egui::ViewportId>,
356}
357
358/// A toast sliding out, and since when (stamped when next drawn).
359#[derive(Debug)]
360struct Leaving {
361    shown: Shown,
362    at: Option<f64>,
363}
364
365#[derive(Debug, Default)]
366struct State {
367    next: u64,
368    queue: VecDeque<Shown>,
369    history: VecDeque<Shown>,
370    /// Toasts to announce and publish on the next frame.
371    fresh: Vec<Shown>,
372    /// Toasts gone, still sliding out.
373    leaving: Vec<Leaving>,
374    /// The toasts showing a notice: its id and what Copy copies.
375    notices: std::collections::HashMap<u64, (NoticeId, String)>,
376}
377
378/// The queue of toasts.
379///
380/// Need (help): a toast, a short notice that fades.
381#[derive(Clone, Debug, Default)]
382pub struct Toasts(Arc<Mutex<State>>);
383
384impl Toasts {
385    /// Shows a toast (it waits while [`SHOWN`] are on screen); returns
386    /// its id.
387    pub fn notify(&self, toast: Toast) -> u64 {
388        self.notify_to(crate::windows::current_group(), toast)
389    }
390
391    /// Shows a toast in a window group (`AppHandle::window_group`: an
392    /// application window's viewport, or `ViewportId::ROOT` for the main
393    /// window); returns its id.
394    pub fn notify_in(&self, group: egui::ViewportId, toast: Toast) -> u64 {
395        self.notify_to(Some(group), toast)
396    }
397
398    fn notify_to(&self, group: Option<egui::ViewportId>, toast: Toast) -> u64 {
399        let mut s = lock(&self.0);
400        s.next += 1;
401        let shown = Shown {
402            id: s.next,
403            toast,
404            until: None,
405            ended: None,
406            since: None,
407            phase: Phase::Appear,
408            left: None,
409            held: None,
410            window: None,
411            group,
412        };
413        s.fresh.push(shown.clone());
414        s.queue.push_back(shown);
415        s.next
416    }
417
418    /// Shows a notice as a toast (the routing policy's
419    /// [`Surface::Toast`](egui_pop_model::notice::route::Surface::Toast)):
420    /// its headline, reason and hint, its severity's level and lifetime,
421    /// its first action when that is a command, and a Copy button
422    /// (headline, reason, hint, details, time). Closing it marks the
423    /// notice seen. Its id.
424    pub(crate) fn notify_notice(&self, n: &Notice) -> u64 {
425        let level = match n.severity {
426            Severity::Info => Level::Info,
427            Severity::Success => Level::Success,
428            Severity::Warning => Level::Warning,
429            Severity::Error => Level::Error,
430        };
431        let text = std::iter::once(n.headline.as_str())
432            .chain(n.reason.as_deref())
433            .chain(n.hint.as_deref())
434            .collect::<Vec<_>>()
435            .join("\n");
436        let mut toast = Toast::new(level, &text);
437        if let Some(a) = n.actions.first()
438            && let Ok(command) = CommandId::new(&a.id)
439        {
440            toast = toast.action(&a.label, command, a.args.clone());
441        }
442        let copy = egui_pop_core::note::Note::from_notice(n).copy_text();
443        let id = self.notify_to(None, toast);
444        lock(&self.0).notices.insert(id, (n.id.clone(), copy));
445        id
446    }
447
448    /// The notice a toast shows, and what its Copy copies.
449    fn notice_of(&self, id: u64) -> Option<(NoticeId, String)> {
450        lock(&self.0).notices.get(&id).cloned()
451    }
452
453    /// The toasts on screen and waiting, oldest first.
454    pub fn shown(&self) -> Vec<Shown> {
455        lock(&self.0).queue.iter().cloned().collect()
456    }
457
458    /// The toasts gone, oldest first, with why.
459    pub fn history(&self) -> Vec<Shown> {
460        lock(&self.0).history.iter().cloned().collect()
461    }
462
463    /// The toasts gone that still slide out, oldest first (drawn
464    /// without their buttons, out of the accessibility tree).
465    pub fn leaving(&self) -> Vec<Shown> {
466        lock(&self.0)
467            .leaving
468            .iter()
469            .map(|l| l.shown.clone())
470            .collect()
471    }
472
473    /// Closes a toast; whether it was there.
474    pub fn dismiss(&self, id: u64) -> bool {
475        self.end(id, "dismissed").is_some()
476    }
477
478    fn end(&self, id: u64, why: &'static str) -> Option<Shown> {
479        let mut s = lock(&self.0);
480        let i = s.queue.iter().position(|t| t.id == id)?;
481        let mut t = s.queue.remove(i)?;
482        s.notices.remove(&id);
483        t.ended = Some(why);
484        t.held = None;
485        if t.since.is_some() {
486            t.phase = Phase::Disappear;
487            s.leaving.push(Leaving {
488                shown: t.clone(),
489                at: None,
490            });
491        }
492        if s.history.len() == HISTORY {
493            s.history.pop_front();
494        }
495        s.history.push_back(t.clone());
496        Some(t)
497    }
498}
499
500/// The plugin.
501#[derive(Debug, Default)]
502pub struct ToastsPlugin;
503
504impl Plugin for ToastsPlugin {
505    fn id(&self) -> PluginId {
506        PluginId::from_static("egui_pop.toasts")
507    }
508
509    fn title(&self) -> String {
510        "Toasts".into()
511    }
512
513    fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
514        let toasts = Toasts::default();
515        ctx.service(&TOASTS, toasts.clone())?;
516        // Notices routed to a toast show here.
517        *lock(&ctx.app.0.bus.notices.toasts) = Some(toasts.clone());
518        let (a, b) = (toasts.clone(), toasts);
519        ctx.collector(
520            FnCollector::new(
521                "toasts",
522                "The toasts on screen and waiting, those sliding out, and the last ones gone with why; `dismiss` closes one.",
523            )
524            .snapshot(move |_| {
525                json!({ "shown": a.shown(), "leaving": a.leaving(), "history": a.history() })
526            })
527            .action("dismiss", "Closes a toast (`id`).", true, move |_, args| {
528                let id = args.get("id").and_then(Json::as_u64).ok_or("`id` is missing")?;
529                if b.dismiss(id) {
530                    Ok(json!({ "dismissed": id }))
531                } else {
532                    Err(format!("no toast {id}"))
533                }
534            })
535            .args(json!({ "id": 1 })),
536        )?;
537        // Drawn in every window, shown in the active one.
538        ctx.block(
539            zones::WINDOW_OVERLAYS,
540            Block::add(BlockId::from_static("egui_pop.toasts"), 20, show),
541        );
542        Ok(())
543    }
544}
545
546/// Rects the toasts keep off: the window's, the pass each was asked in,
547/// the rect.
548type Clear = Vec<(egui::ViewportId, u64, Rect)>;
549
550fn clear_id() -> Id {
551    area_id().with("keep_clear")
552}
553
554/// Keeps the toasts off `rect` (in the window's points) for this frame:
555/// a row of buttons a toast would cover and take the clicks of, as a
556/// wizard's footer. Toasts whose column meets it move past it: above it
557/// under a bottom corner, below it under a top one. Called each frame
558/// the rect is shown; it lapses the frame after it is not.
559pub fn keep_clear(ctx: &egui::Context, rect: Rect) {
560    let viewport = ctx.viewport_id();
561    let pass = ctx.cumulative_pass_nr();
562    ctx.data_mut(|d| {
563        let kept = d.get_temp_mut_or_default::<Clear>(clear_id());
564        kept.retain(|(v, p, _)| *v != viewport || *p + 1 >= pass);
565        kept.push((viewport, pass, rect));
566    });
567}
568
569/// How far the toasts move from the corner's edge to stay off the rects
570/// asked this frame or the last one ([`keep_clear`]): those their column
571/// (`width` wide, `margin` from the edge) meets.
572fn clearance(ctx: &egui::Context, corner: Corner, width: f32, margin: f32) -> f32 {
573    let viewport = ctx.viewport_id();
574    let pass = ctx.cumulative_pass_nr();
575    let screen = ctx.content_rect();
576    let (left, right) = match corner.side() {
577        s if s < 0.0 => (screen.left() + margin, screen.left() + margin + width),
578        s if s > 0.0 => (screen.right() - margin - width, screen.right() - margin),
579        _ => (
580            screen.center().x - width / 2.0,
581            screen.center().x + width / 2.0,
582        ),
583    };
584    ctx.data_mut(|d| {
585        let kept = d.get_temp_mut_or_default::<Clear>(clear_id());
586        kept.retain(|(v, p, _)| *v != viewport || *p + 1 >= pass);
587        kept.iter()
588            .filter(|(v, _, r)| *v == viewport && r.left() < right && r.right() > left)
589            .map(|(_, _, r)| {
590                if corner.top() {
591                    r.bottom() - screen.top()
592                } else {
593                    screen.bottom() - r.top()
594                }
595            })
596            .fold(0.0_f32, f32::max)
597    })
598}
599
600/// The area the toasts are drawn in.
601pub(crate) fn area_id() -> Id {
602    Id::unique("egui_pop.toasts")
603}
604
605/// Where a toast's size is kept, for its slide and its picture going.
606fn size_id(id: u64) -> Id {
607    area_id().with(("size", id))
608}
609
610/// How far in its slide a toast is, eased: 0 out of sight, 1 in place.
611/// `p` is the time gone in the slide, 0 to 1, coming in; going out, the
612/// same curve is run backwards.
613// egui-notify's eased value (MIT, lib.rs: `ease_in_cubic`, the cubic
614// ease-out), here egui's own `emath::easing::cubic_out`.
615fn eased(p: f64) -> f32 {
616    egui::emath::easing::cubic_out(p.clamp(0.0, 1.0) as f32)
617}
618
619/// A toast to draw: on screen, or sliding out.
620enum Item {
621    Live(Shown),
622    Leaving(Shown, f64),
623}
624
625impl Item {
626    fn shown(&self) -> &Shown {
627        match self {
628            Item::Live(s) | Item::Leaving(s, _) => s,
629        }
630    }
631}
632
633/// Draws the toasts in the chosen corner of the active window, the
634/// newest the nearest to the edge.
635fn show(ui: &mut Ui, app: &AppHandle) {
636    let Some(toasts) = app.service(&TOASTS) else {
637        return;
638    };
639    let ctx = ui.ctx().clone();
640    let here = ctx.viewport_id();
641    let group = app.window_group(here);
642    // Each toast's group: the one it was raised in while that window is
643    // open (the main window's otherwise); the active one's when unknown.
644    {
645        let active = app.window_group(app.active_window());
646        let mut s = lock(&toasts.0);
647        let State {
648            queue,
649            fresh,
650            leaving,
651            ..
652        } = &mut *s;
653        for t in queue
654            .iter_mut()
655            .chain(fresh.iter_mut())
656            .chain(leaving.iter_mut().map(|l| &mut l.shown))
657        {
658            let g = app.window_group(t.group.unwrap_or(active));
659            if t.group != Some(g) || t.window.is_none() {
660                t.group = Some(g);
661                t.window = Some(app.window_of_group(g).to_string());
662            }
663        }
664    }
665    if app.shown_in(group) != here {
666        return;
667    }
668    let mine = |t: &Shown| t.group == Some(group);
669    let now = motion::now(&ctx);
670    let fresh: Vec<Shown> = {
671        let mut s = lock(&toasts.0);
672        let (here_now, later) = std::mem::take(&mut s.fresh).into_iter().partition(mine);
673        s.fresh = later;
674        here_now
675    };
676    for t in fresh {
677        let politeness = if t.toast.level == Level::Error {
678            Politeness::Assertive
679        } else {
680            Politeness::Polite
681        };
682        a11y::announce(&ctx, t.toast.text.clone(), politeness);
683        app.publish(
684            "app",
685            None,
686            "toast.shown",
687            json!({ "id": t.id, "level": t.toast.level, "text": t.toast.text }),
688        );
689    }
690    let t = Tokens::of(&ctx);
691    // No slide under reduced motion: they appear and go at once.
692    let slide = if motion::reduced(&ctx) {
693        0.0
694    } else {
695        f64::from(t.motion.toast_slide)
696    };
697    let corner = corner(app);
698    // Start the clocks of the toasts on screen (a job's once the job
699    // ended); end the expired ones. A toast the pointer holds does not
700    // expire.
701    let jobs = app.service(&crate::jobs::JOBS);
702    let job_goes_on = |toast: &Toast| {
703        toast
704            .job
705            .as_ref()
706            .and_then(|id| jobs.as_ref()?.job(id))
707            .is_some_and(|j| j.active())
708    };
709    let on_screen: Vec<Shown> = {
710        let mut s = lock(&toasts.0);
711        for t in s.queue.iter_mut().filter(|t| mine(t)).take(SHOWN) {
712            if job_goes_on(&t.toast) {
713                t.until = None;
714            } else if t.until.is_none() {
715                t.until = t.toast.lifetime.map(|l| now + l);
716            }
717            t.since.get_or_insert(now);
718        }
719        s.queue
720            .iter()
721            .filter(|t| mine(t))
722            .take(SHOWN)
723            .cloned()
724            .collect()
725    };
726    let mut expired = Vec::new();
727    let mut next_deadline: Option<f64> = None;
728    for t in on_screen.iter().filter(|t| t.held.is_none()) {
729        if let Some(u) = t.until {
730            if u <= now {
731                expired.push(t.id);
732            } else {
733                next_deadline = Some(next_deadline.map_or(u, |d: f64| d.min(u)));
734            }
735        }
736    }
737    for id in expired {
738        toasts.end(id, "expired");
739    }
740    if let Some(d) = next_deadline {
741        motion::wake_at(&ctx, d);
742    }
743    // Those sliding out, stamped when first drawn so; the size kept for
744    // them goes with them.
745    let mut gone = Vec::new();
746    let leaving: Vec<(Shown, f64)> = {
747        let mut s = lock(&toasts.0);
748        for l in s.leaving.iter_mut().filter(|l| mine(&l.shown)) {
749            l.at.get_or_insert(now);
750        }
751        s.leaving.retain(|l| {
752            if !mine(&l.shown) {
753                return true;
754            }
755            let stays = slide > 0.0 && l.at.is_some_and(|at| now - at < slide);
756            if !stays {
757                gone.push(l.shown.id);
758            }
759            stays
760        });
761        s.leaving
762            .iter()
763            .filter(|l| mine(&l.shown))
764            .filter_map(|l| Some((l.shown.clone(), l.at?)))
765            .collect()
766    };
767    if !gone.is_empty() {
768        ctx.data_mut(|d| {
769            for id in gone {
770                d.remove::<Vec2>(size_id(id));
771            }
772        });
773    }
774    let mut items: Vec<Item> = toasts
775        .shown()
776        .into_iter()
777        .filter(|t| mine(t))
778        .take(SHOWN)
779        .map(Item::Live)
780        .chain(leaving.into_iter().map(|(s, at)| Item::Leaving(s, at)))
781        .collect();
782    if items.is_empty() {
783        return;
784    }
785    // Oldest first from the top: the newest at the bottom under a bottom
786    // corner, on top under a top one, the nearest to the edge either way.
787    // (egui-notify's `reverse`, MIT, lib.rs, follows the corner here.)
788    items.sort_by_key(|i| i.shown().id);
789    if corner.top() {
790        items.reverse();
791    }
792    let margin = t.space.l;
793    let mut ended: Vec<(u64, &'static str)> = Vec::new();
794    let mut hold: Vec<u64> = Vec::new();
795    let mut drawn: Vec<(u64, Phase, Option<f32>)> = Vec::new();
796    let mut moving = false;
797    let mut running = false;
798    // Off the rects asked clear: past the farthest one, then the margin.
799    let clear = clearance(&ctx, corner, Kit::of(&ctx).toast.data.width, margin);
800    let offset = corner.offset(margin) + vec2(0.0, if corner.top() { clear } else { -clear });
801    // Over the lying-over panels, under menus and dialogs (ADR 0026).
802    egui_pop_core::layers::rank(
803        &ctx,
804        egui::LayerId::new(Order::Foreground, area_id()),
805        egui_pop_core::layers::Rank::Overlay,
806    );
807    egui::Area::new(area_id())
808        .order(Order::Foreground)
809        .anchor(corner.align(), offset)
810        .interactable(true)
811        .show(&ctx, |ui| {
812            let width = Kit::of(ui.ctx()).toast.data.width;
813            ui.set_max_width(width);
814            for item in &items {
815                let shown = item.shown();
816                // How far in its slide (eased), and its phase.
817                let (e, phase) = match item {
818                    Item::Live(s) => {
819                        let p = match s.since {
820                            Some(since) if slide > 0.0 => (now - since) / slide,
821                            _ => 1.0,
822                        };
823                        let phase = if p < 1.0 { Phase::Appear } else { Phase::Idle };
824                        (eased(p), phase)
825                    }
826                    Item::Leaving(_, at) => (eased(1.0 - (now - at) / slide), Phase::Disappear),
827                };
828                moving |= phase != Phase::Idle;
829                // Out of sight by its whole width and the margin, from the
830                // corner's side (egui-notify's offset, MIT, lib.rs); in the
831                // middle of an edge, by its height from the edge, fading.
832                let size_id = size_id(shown.id);
833                let away = 1.0 - e;
834                let shift = if corner.side() == 0.0 {
835                    let height = ctx
836                        .data(|d| d.get_temp::<Vec2>(size_id))
837                        .map_or(0.0, |s| s.y);
838                    let y = away * (height + margin);
839                    vec2(0.0, if corner.top() { -y } else { y })
840                } else {
841                    vec2(corner.side() * away * (width + margin), 0.0)
842                };
843                let at = ui.cursor().min;
844                let room =
845                    Rect::from_min_size(at + shift, vec2(width, ui.available_height().max(0.0)));
846                // A child the stack does not grow by: the slot it keeps
847                // is the one in place.
848                let mut child = ui.new_child(
849                    UiBuilder::new()
850                        .id_salt(("toast", shown.id))
851                        .max_rect(room)
852                        .layout(egui::Layout::top_down(egui::Align::Min)),
853                );
854                if corner.side() == 0.0 {
855                    child.multiply_opacity(e);
856                }
857                match item {
858                    Item::Live(s) => {
859                        let left = match (s.until, s.toast.lifetime) {
860                            (Some(until), Some(life)) if life > 0.0 => Some(
861                                (((until - s.held.unwrap_or(now)) / life) as f32).clamp(0.0, 1.0),
862                            ),
863                            _ => None,
864                        };
865                        let hovered = live(&mut child, app, s, left, size_id, &mut ended);
866                        if hovered {
867                            hold.push(s.id);
868                        }
869                        running |= left.is_some() && s.held.is_none();
870                        drawn.push((s.id, phase, left));
871                    }
872                    Item::Leaving(s, _) => going(&mut child, s, size_id),
873                }
874                let height = child.min_rect().height();
875                ui.allocate_space(vec2(width, height));
876                ui.add_space(t.space.s);
877            }
878        });
879    if moving {
880        motion::animate(&ctx);
881    }
882    // A bar empties smoothly; under reduced motion it steps once a second.
883    if running {
884        if motion::reduced(&ctx) {
885            motion::wake_at(&ctx, now + 1.0);
886        } else {
887            motion::animate(&ctx);
888        }
889    }
890    // The pointer over a toast holds it: its time stops, and goes on
891    // where it stopped once the pointer leaves (egui-notify's, MIT,
892    // lib.rs).
893    {
894        let mut s = lock(&toasts.0);
895        for t in s.queue.iter_mut().filter(|t| mine(t)) {
896            if let Some((_, phase, left)) = drawn.iter().find(|d| d.0 == t.id) {
897                t.phase = *phase;
898                t.left = *left;
899            }
900            match (hold.contains(&t.id), t.held) {
901                (true, None) => t.held = Some(now),
902                (false, Some(since)) => {
903                    if let Some(until) = t.until.as_mut() {
904                        *until += now - since;
905                    }
906                    t.held = None;
907                }
908                _ => {}
909            }
910        }
911    }
912    for (id, why) in ended {
913        // A notice's toast the user closed: the notice is seen.
914        let notice = toasts.notice_of(id);
915        if toasts.end(id, why).is_some()
916            && let Some((n, _)) = notice
917            && why == "closed"
918        {
919            app.see_notice(n);
920        }
921    }
922}
923
924/// Draws a toast on screen; whether the pointer is over it.
925fn live(
926    ui: &mut Ui,
927    app: &AppHandle,
928    shown: &Shown,
929    left: Option<f32>,
930    size_id: Id,
931    ended: &mut Vec<(u64, &'static str)>,
932) -> bool {
933    let t = Tokens::of(ui.ctx());
934    let style = Kit::of(ui.ctx());
935    let toast = &style.toast;
936    let text = toast.style(kit::State::REST).text;
937    let (icon, tone) = shown.toast.level.icon();
938    let frame = toast.show(ui, kit::State::REST, toast.data.shadow, |ui| {
939        ui.set_width(toast.data.width - 2.0 * toast.data.padding_x);
940        ui.horizontal(|ui| {
941            let level = strings::tr(
942                ui.ctx(),
943                match shown.toast.level {
944                    Level::Info => &txt::TOAST_INFO,
945                    Level::Success => &txt::TOAST_SUCCESS,
946                    Level::Warning => &txt::TOAST_WARNING,
947                    Level::Error => &txt::TOAST_ERROR,
948                },
949            );
950            ui.add(icon.tone(tone).label(&level));
951            // The text wraps in what the close button and the action
952            // leave.
953            let spacing = ui.spacing().item_spacing.x;
954            let mut reserved = t.size.icon_inline + spacing;
955            if let Some(a) = &shown.toast.action {
956                let galley = egui::WidgetText::from(a.label.as_str()).into_galley(
957                    ui,
958                    Some(egui::TextWrapMode::Extend),
959                    f32::INFINITY,
960                    egui::TextStyle::Button,
961                );
962                reserved += galley.size().x + 2.0 * ui.spacing().button_padding.x + spacing;
963            }
964            let notice = app.service(&TOASTS).and_then(|ts| ts.notice_of(shown.id));
965            if notice.is_some() {
966                reserved += t.size.icon_inline + spacing;
967            }
968            let width = (ui.available_width() - reserved).max(t.size.icon_inline);
969            ui.allocate_ui_with_layout(
970                egui::vec2(width, 0.0),
971                egui::Layout::top_down(egui::Align::Min),
972                |ui| {
973                    ui.set_max_width(width);
974                    crate::links::Inline::new(&shown.toast.text)
975                        .color(text)
976                        .show(ui, app);
977                },
978            );
979            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
980                let close = ui.add(
981                    Icon::Close
982                        .size(Size::Inline)
983                        .label(&strings::tr_args(
984                            ui.ctx(),
985                            &txt::TOAST_CLOSE,
986                            &[("text", &shown.toast.text)],
987                        ))
988                        .sense_click(),
989                );
990                if close.clicked() {
991                    ended.push((shown.id, "closed"));
992                }
993                if let Some((_, copy)) = &notice {
994                    let r = ui.add(
995                        Icon::Copy
996                            .size(Size::Inline)
997                            .label(&strings::tr_args(
998                                ui.ctx(),
999                                &txt::TOAST_COPY,
1000                                &[("text", &shown.toast.text)],
1001                            ))
1002                            .sense_click(),
1003                    );
1004                    if r.clicked() {
1005                        ui.ctx().copy_text(copy.clone());
1006                    }
1007                }
1008                if let Some(a) = &shown.toast.action {
1009                    // An action whose command went with its plugin is
1010                    // greyed, saying why (ADR 0028).
1011                    let gone = app.command(&a.command).is_none().then(|| {
1012                        match app.command_gone_with(&a.command) {
1013                            Some(p) => strings::tr_args(
1014                                ui.ctx(),
1015                                &txt::TOAST_ACTION_GONE,
1016                                &[("plugin", p.as_str())],
1017                            ),
1018                            None => strings::tr(ui.ctx(), &txt::MENU_NOT_AVAILABLE),
1019                        }
1020                    });
1021                    let button =
1022                        ui.add_enabled(gone.is_none(), egui::Button::new(&a.label).small());
1023                    let button = match &gone {
1024                        Some(why) => button.on_disabled_hover_text(why),
1025                        None => button,
1026                    };
1027                    if button.clicked() {
1028                        app.run_as(a.command.clone(), a.args.clone(), Origin::User);
1029                        ended.push((shown.id, "action"));
1030                    }
1031                }
1032            });
1033        });
1034        if let Some(id) = &shown.toast.job {
1035            crate::jobs_centre::toast_part(ui, app, id);
1036        }
1037        // The time left, emptying towards the start (egui-notify's
1038        // progress bar, MIT, lib.rs), in the level's colour, a thin
1039        // line's thickness.
1040        if let Some(left) = left {
1041            ui.add_space(t.space.xs);
1042            let line = ProgressTokens::of(ui.ctx()).line;
1043            let (_, rect) = ui.allocate_space(vec2(ui.available_width(), line));
1044            let fill = Rect::from_min_size(rect.min, vec2(rect.width() * left, line));
1045            ui.painter().rect_filled(fill, line / 2.0, tone.color(&t));
1046        }
1047        let size = ui.min_rect().size();
1048        ui.ctx().data_mut(|d| d.insert_temp(size_id, size));
1049    });
1050    frame.response.contains_pointer()
1051}
1052
1053/// Draws a toast sliding out: its frame, icon and text, painted only
1054/// (it went: nothing to press, nothing for a screen reader).
1055fn going(ui: &mut Ui, shown: &Shown, size_id: Id) {
1056    let t = Tokens::of(ui.ctx());
1057    let style = Kit::of(ui.ctx());
1058    let toast = &style.toast;
1059    let text = toast.style(kit::State::REST).text;
1060    let (icon, tone) = shown.toast.level.icon();
1061    let inner = ui
1062        .ctx()
1063        .data(|d| d.get_temp::<Vec2>(size_id))
1064        .unwrap_or(vec2(
1065            toast.data.width - 2.0 * toast.data.padding_x,
1066            t.size.icon_inline,
1067        ));
1068    toast.show(ui, kit::State::REST, toast.data.shadow, |ui| {
1069        let (_, rect) = ui.allocate_space(inner);
1070        let side = t.size.icon_inline;
1071        icon.paint(
1072            ui.painter(),
1073            Rect::from_min_size(rect.min, Vec2::splat(side)),
1074            tone.color(&t),
1075        );
1076        let gap = ui.spacing().item_spacing.x;
1077        let wrap = (rect.width() - 2.0 * (side + gap)).max(side);
1078        let galley = egui::WidgetText::from(shown.toast.text.as_str()).into_galley(
1079            ui,
1080            Some(egui::TextWrapMode::Wrap),
1081            wrap,
1082            egui::TextStyle::Body,
1083        );
1084        ui.painter()
1085            .galley(rect.min + vec2(side + gap, 0.0), galley, text);
1086    });
1087}