1use 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
88pub const TOASTS: ServiceToken<Toasts> = ServiceToken::new("app.toasts");
90
91pub const SHOWN: usize = 4;
93pub const HISTORY: usize = 32;
95
96pub const SETTING_CORNER: SettingId = SettingId::from_static("appearance.toast_corner");
98
99#[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 #[default]
114 BottomRight,
115}
116
117impl Corner {
118 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 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 pub fn top(self) -> bool {
155 matches!(self, Corner::TopLeft | Corner::TopCenter | Corner::TopRight)
156 }
157
158 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 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
188pub 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
196pub(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#[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 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#[derive(Clone, Debug, PartialEq, Serialize)]
239pub struct ToastAction {
240 pub label: String,
241 pub command: CommandId,
242 pub args: Json,
243}
244
245#[derive(Clone, Debug, PartialEq, Serialize)]
247pub struct Toast {
248 pub level: Level,
249 pub text: String,
250 pub action: Option<ToastAction>,
251 pub lifetime: Option<f64>,
254 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 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 pub fn job(mut self, id: &str) -> Self {
299 self.job = Some(id.into());
300 self
301 }
302
303 pub fn sticky(mut self) -> Self {
305 self.lifetime = None;
306 self
307 }
308
309 pub fn lifetime(mut self, seconds: f64) -> Self {
311 self.lifetime = Some(seconds);
312 self
313 }
314}
315
316#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
319#[serde(rename_all = "lowercase")]
320pub enum Phase {
321 #[default]
323 Appear,
324 Idle,
326 Disappear,
328}
329
330#[derive(Clone, Debug, PartialEq, Serialize)]
332pub struct Shown {
333 pub id: u64,
334 #[serde(flatten)]
335 pub toast: Toast,
336 pub until: Option<f64>,
339 pub ended: Option<&'static str>,
341 pub since: Option<f64>,
343 pub phase: Phase,
345 pub left: Option<f32>,
348 pub held: Option<f64>,
350 pub window: Option<String>,
353 #[serde(skip)]
355 group: Option<egui::ViewportId>,
356}
357
358#[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 fresh: Vec<Shown>,
372 leaving: Vec<Leaving>,
374 notices: std::collections::HashMap<u64, (NoticeId, String)>,
376}
377
378#[derive(Clone, Debug, Default)]
382pub struct Toasts(Arc<Mutex<State>>);
383
384impl Toasts {
385 pub fn notify(&self, toast: Toast) -> u64 {
388 self.notify_to(crate::windows::current_group(), toast)
389 }
390
391 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 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 fn notice_of(&self, id: u64) -> Option<(NoticeId, String)> {
450 lock(&self.0).notices.get(&id).cloned()
451 }
452
453 pub fn shown(&self) -> Vec<Shown> {
455 lock(&self.0).queue.iter().cloned().collect()
456 }
457
458 pub fn history(&self) -> Vec<Shown> {
460 lock(&self.0).history.iter().cloned().collect()
461 }
462
463 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 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#[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 *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 ctx.block(
539 zones::WINDOW_OVERLAYS,
540 Block::add(BlockId::from_static("egui_pop.toasts"), 20, show),
541 );
542 Ok(())
543 }
544}
545
546type Clear = Vec<(egui::ViewportId, u64, Rect)>;
549
550fn clear_id() -> Id {
551 area_id().with("keep_clear")
552}
553
554pub 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
569fn 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
600pub(crate) fn area_id() -> Id {
602 Id::unique("egui_pop.toasts")
603}
604
605fn size_id(id: u64) -> Id {
607 area_id().with(("size", id))
608}
609
610fn eased(p: f64) -> f32 {
616 egui::emath::easing::cubic_out(p.clamp(0.0, 1.0) as f32)
617}
618
619enum 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
633fn 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 {
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 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 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 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 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 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 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 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 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 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 if running {
884 if motion::reduced(&ctx) {
885 motion::wake_at(&ctx, now + 1.0);
886 } else {
887 motion::animate(&ctx);
888 }
889 }
890 {
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 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
924fn 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 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)) = ¬ice {
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 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 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
1053fn 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}