Skip to main content

sui_widgets/
overlay.rs

1use crate::draw::inset_rect_evenly;
2use std::{
3    collections::HashMap,
4    sync::{
5        Arc, Mutex,
6        atomic::{AtomicU64, Ordering},
7    },
8};
9
10use sui_core::{
11    Color, Event, InvalidationKind, Rect, SemanticsLiveRegion, SemanticsNode, SemanticsRole, Size,
12    TimerToken, WakeEvent, WidgetId,
13};
14use sui_layout::Constraints;
15use sui_reactive::Signal;
16use sui_runtime::{
17    ArrangeCtx, Command, EventCtx, FrameClock, LayerOptions, MeasureCtx, Motion,
18    OverlayDismissPolicy, OverlayFocusBehavior, OverlayKind, OverlayOptions, PaintBoundaryMode,
19    PaintCtx, REACTIVE_CHANGED, SemanticsCtx, SingleChild, StackHostOptions, StackSurfaceOptions,
20    Widget, WidgetPod, WidgetPodMutVisitor, WidgetPodVisitor, motion_policy,
21};
22use sui_scene::{Border, LayerCompositionMode};
23
24use crate::DefaultTheme;
25
26use sui_core::Point;
27
28/// Defines an independent overlay stacking root.
29///
30/// Windows are stacking hosts automatically. Use this widget for embedded
31/// viewports or independently ordered workspace regions; focus and dismissal
32/// remain coordinated by the containing window's overlay manager.
33pub struct OverlayHost {
34    child: SingleChild,
35}
36
37impl OverlayHost {
38    pub fn new<W>(child: W) -> Self
39    where
40        W: Widget + 'static,
41    {
42        Self {
43            child: SingleChild::new(child),
44        }
45    }
46
47    pub fn child_pod(&self) -> &WidgetPod {
48        self.child.child()
49    }
50
51    pub fn child_mut(&mut self) -> &mut WidgetPod {
52        self.child.child_mut()
53    }
54}
55
56impl Widget for OverlayHost {
57    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
58        self.child.measure(ctx, constraints)
59    }
60
61    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
62        self.child.arrange(ctx, bounds);
63    }
64
65    fn paint(&self, ctx: &mut PaintCtx) {
66        self.child.paint(ctx);
67    }
68
69    fn semantics(&self, ctx: &mut SemanticsCtx) {
70        self.child.semantics(ctx);
71    }
72
73    fn stack_host_options(&self) -> Option<StackHostOptions> {
74        Some(StackHostOptions::default())
75    }
76
77    fn visit_children(&self, visitor: &mut dyn WidgetPodVisitor) {
78        self.child.visit_children(visitor);
79    }
80
81    fn visit_children_mut(&mut self, visitor: &mut dyn WidgetPodMutVisitor) {
82        self.child.visit_children_mut(visitor);
83    }
84}
85
86#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
87pub enum OverlaySide {
88    Top,
89    Bottom,
90    Left,
91    Right,
92}
93
94impl OverlaySide {
95    pub const fn opposite(self) -> Self {
96        match self {
97            Self::Top => Self::Bottom,
98            Self::Bottom => Self::Top,
99            Self::Left => Self::Right,
100            Self::Right => Self::Left,
101        }
102    }
103}
104
105#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
106pub enum OverlayAlignment {
107    Start,
108    Center,
109    End,
110}
111
112#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
113pub struct OverlayPlacement {
114    pub side: OverlaySide,
115    pub alignment: OverlayAlignment,
116}
117
118impl OverlayPlacement {
119    pub const TOP_START: Self = Self::new(OverlaySide::Top, OverlayAlignment::Start);
120    pub const TOP_CENTER: Self = Self::new(OverlaySide::Top, OverlayAlignment::Center);
121    pub const TOP_END: Self = Self::new(OverlaySide::Top, OverlayAlignment::End);
122    pub const BOTTOM_START: Self = Self::new(OverlaySide::Bottom, OverlayAlignment::Start);
123    pub const BOTTOM_CENTER: Self = Self::new(OverlaySide::Bottom, OverlayAlignment::Center);
124    pub const BOTTOM_END: Self = Self::new(OverlaySide::Bottom, OverlayAlignment::End);
125    pub const LEFT_START: Self = Self::new(OverlaySide::Left, OverlayAlignment::Start);
126    pub const LEFT_CENTER: Self = Self::new(OverlaySide::Left, OverlayAlignment::Center);
127    pub const LEFT_END: Self = Self::new(OverlaySide::Left, OverlayAlignment::End);
128    pub const RIGHT_START: Self = Self::new(OverlaySide::Right, OverlayAlignment::Start);
129    pub const RIGHT_CENTER: Self = Self::new(OverlaySide::Right, OverlayAlignment::Center);
130    pub const RIGHT_END: Self = Self::new(OverlaySide::Right, OverlayAlignment::End);
131
132    pub const fn new(side: OverlaySide, alignment: OverlayAlignment) -> Self {
133        Self { side, alignment }
134    }
135
136    pub const fn flipped(self) -> Self {
137        Self::new(self.side.opposite(), self.alignment)
138    }
139}
140
141#[derive(Debug, Clone, Copy, PartialEq)]
142pub struct OverlayCollisionPolicy {
143    pub flip: bool,
144    pub shift: bool,
145    pub resize: bool,
146}
147
148impl OverlayCollisionPolicy {
149    pub const NONE: Self = Self {
150        flip: false,
151        shift: false,
152        resize: false,
153    };
154
155    pub const ADAPTIVE: Self = Self {
156        flip: true,
157        shift: true,
158        resize: true,
159    };
160}
161
162impl Default for OverlayCollisionPolicy {
163    fn default() -> Self {
164        Self::ADAPTIVE
165    }
166}
167
168#[derive(Debug, Clone, PartialEq)]
169pub struct OverlayPlacementRequest {
170    pub anchor: Rect,
171    pub overlay_size: Size,
172    pub viewport: Rect,
173    pub preferred: OverlayPlacement,
174    pub fallbacks: Vec<OverlayPlacement>,
175    pub gap: f32,
176    pub margin: f32,
177    pub collision: OverlayCollisionPolicy,
178}
179
180impl OverlayPlacementRequest {
181    pub fn new(
182        anchor: Rect,
183        overlay_size: Size,
184        viewport: Rect,
185        preferred: OverlayPlacement,
186    ) -> Self {
187        Self {
188            anchor,
189            overlay_size,
190            viewport,
191            preferred,
192            fallbacks: Vec::new(),
193            gap: 0.0,
194            margin: 4.0,
195            collision: OverlayCollisionPolicy::ADAPTIVE,
196        }
197    }
198
199    pub fn fallbacks(mut self, fallbacks: impl IntoIterator<Item = OverlayPlacement>) -> Self {
200        self.fallbacks = fallbacks.into_iter().collect();
201        self
202    }
203
204    pub fn gap(mut self, gap: f32) -> Self {
205        self.gap = gap.max(0.0);
206        self
207    }
208
209    pub fn margin(mut self, margin: f32) -> Self {
210        self.margin = margin.max(0.0);
211        self
212    }
213
214    pub fn collision(mut self, collision: OverlayCollisionPolicy) -> Self {
215        self.collision = collision;
216        self
217    }
218}
219
220#[derive(Debug, Clone, Copy, PartialEq)]
221pub struct OverlayPlacementResult {
222    pub bounds: Rect,
223    pub placement: OverlayPlacement,
224    pub shifted: bool,
225    pub resized: bool,
226    pub overflow: f32,
227}
228
229/// Place an overlay relative to an anchor while keeping it inside a viewport.
230///
231/// Candidates are evaluated before shifting so an actually fitting fallback
232/// wins over a preferred side that would need a large corrective movement.
233pub fn place_overlay(request: &OverlayPlacementRequest) -> OverlayPlacementResult {
234    if !request.viewport.width().is_finite()
235        || !request.viewport.height().is_finite()
236        || request.viewport.width() <= 0.0
237        || request.viewport.height() <= 0.0
238    {
239        return OverlayPlacementResult {
240            bounds: placement_rect(
241                request.anchor,
242                request.overlay_size,
243                request.preferred,
244                request.gap,
245            ),
246            placement: request.preferred,
247            shifted: false,
248            resized: false,
249            overflow: 0.0,
250        };
251    }
252    let safe_viewport = inset_rect_evenly(request.viewport, request.margin);
253    let mut size = request.overlay_size;
254    let mut resized = false;
255    if request.collision.resize {
256        let next = Size::new(
257            size.width.min(safe_viewport.width()).max(0.0),
258            size.height.min(safe_viewport.height()).max(0.0),
259        );
260        resized = next != size;
261        size = next;
262    }
263
264    let mut candidates = vec![request.preferred];
265    candidates.extend(request.fallbacks.iter().copied());
266    if request.collision.flip {
267        let flipped = request.preferred.flipped();
268        if !candidates.contains(&flipped) {
269            candidates.push(flipped);
270        }
271    }
272
273    let mut best = None::<(usize, f32, Rect, OverlayPlacement)>;
274    for (index, placement) in candidates.into_iter().enumerate() {
275        let raw = placement_rect(request.anchor, size, placement, request.gap);
276        let overflow = overflow_amount(raw, safe_viewport);
277        let score = overflow + index as f32 * 0.001;
278        if best
279            .as_ref()
280            .is_none_or(|(_, best_score, _, _)| score < *best_score)
281        {
282            best = Some((index, score, raw, placement));
283        }
284    }
285
286    let (_, _, raw, placement) = best.unwrap_or((0, 0.0, Rect::ZERO, request.preferred));
287    let overflow = overflow_amount(raw, safe_viewport);
288    let bounds = if request.collision.shift {
289        shift_inside(raw, safe_viewport)
290    } else {
291        raw
292    };
293    OverlayPlacementResult {
294        bounds,
295        placement,
296        shifted: bounds.origin != raw.origin,
297        resized,
298        overflow,
299    }
300}
301
302fn placement_rect(anchor: Rect, size: Size, placement: OverlayPlacement, gap: f32) -> Rect {
303    let (x, y) = match placement.side {
304        OverlaySide::Top | OverlaySide::Bottom => {
305            let x = match placement.alignment {
306                OverlayAlignment::Start => anchor.x(),
307                OverlayAlignment::Center => anchor.x() + (anchor.width() - size.width) * 0.5,
308                OverlayAlignment::End => anchor.max_x() - size.width,
309            };
310            let y = if placement.side == OverlaySide::Top {
311                anchor.y() - gap - size.height
312            } else {
313                anchor.max_y() + gap
314            };
315            (x, y)
316        }
317        OverlaySide::Left | OverlaySide::Right => {
318            let y = match placement.alignment {
319                OverlayAlignment::Start => anchor.y(),
320                OverlayAlignment::Center => anchor.y() + (anchor.height() - size.height) * 0.5,
321                OverlayAlignment::End => anchor.max_y() - size.height,
322            };
323            let x = if placement.side == OverlaySide::Left {
324                anchor.x() - gap - size.width
325            } else {
326                anchor.max_x() + gap
327            };
328            (x, y)
329        }
330    };
331    Rect::new(x, y, size.width, size.height)
332}
333
334fn overflow_amount(rect: Rect, viewport: Rect) -> f32 {
335    (viewport.x() - rect.x()).max(0.0)
336        + (rect.max_x() - viewport.max_x()).max(0.0)
337        + (viewport.y() - rect.y()).max(0.0)
338        + (rect.max_y() - viewport.max_y()).max(0.0)
339}
340
341fn shift_inside(rect: Rect, viewport: Rect) -> Rect {
342    let max_x = (viewport.max_x() - rect.width()).max(viewport.x());
343    let max_y = (viewport.max_y() - rect.height()).max(viewport.y());
344    Rect::from_origin_size(
345        Point::new(
346            rect.x().clamp(viewport.x(), max_x),
347            rect.y().clamp(viewport.y(), max_y),
348        ),
349        rect.size,
350    )
351}
352
353static NEXT_NOTIFICATION_ID: AtomicU64 = AtomicU64::new(1);
354
355#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
356pub struct NotificationId(u64);
357
358impl NotificationId {
359    pub const fn new(value: u64) -> Self {
360        Self(value)
361    }
362
363    pub const fn get(self) -> u64 {
364        self.0
365    }
366}
367
368#[derive(Debug, Clone, Copy, PartialEq, Eq)]
369pub enum NotificationUrgency {
370    Polite,
371    Assertive,
372}
373
374#[derive(Debug, Clone, PartialEq)]
375pub struct TransientNotification {
376    pub id: NotificationId,
377    pub title: String,
378    pub message: String,
379    pub duration: Option<f64>,
380    pub urgency: NotificationUrgency,
381}
382
383impl Default for TransientNotification {
384    /// An empty notification with a fresh identifier.
385    fn default() -> Self {
386        Self::new("", "")
387    }
388}
389
390impl TransientNotification {
391    pub fn new(title: impl Into<String>, message: impl Into<String>) -> Self {
392        Self {
393            id: NotificationId(NEXT_NOTIFICATION_ID.fetch_add(1, Ordering::Relaxed)),
394            title: title.into(),
395            message: message.into(),
396            duration: Some(5.0),
397            urgency: NotificationUrgency::Polite,
398        }
399    }
400
401    /// Expire the notification after `seconds`; the host treats a negative
402    /// or non-finite time as zero.
403    pub fn duration(mut self, seconds: f64) -> Self {
404        self.duration = Some(seconds);
405        self
406    }
407
408    pub fn persistent(mut self) -> Self {
409        self.duration = None;
410        self
411    }
412
413    pub fn urgency(mut self, urgency: NotificationUrgency) -> Self {
414        self.urgency = urgency;
415        self
416    }
417}
418
419#[derive(Default)]
420struct NotificationCenterInner {
421    revision: u64,
422    notifications: Vec<TransientNotification>,
423}
424
425/// Thread-safe producer for transient, window-hosted notifications.
426#[derive(Clone)]
427pub struct NotificationCenter {
428    inner: Arc<Mutex<NotificationCenterInner>>,
429    revision: Signal<u64>,
430}
431
432impl NotificationCenter {
433    pub fn new() -> Self {
434        Self {
435            inner: Arc::new(Mutex::new(NotificationCenterInner::default())),
436            revision: Signal::named("NotificationCenter", 0),
437        }
438    }
439
440    pub fn push(&self, notification: TransientNotification) -> NotificationId {
441        let id = notification.id;
442        let revision = {
443            let mut inner = self
444                .inner
445                .lock()
446                .unwrap_or_else(std::sync::PoisonError::into_inner);
447            inner.notifications.push(notification);
448            inner.revision = inner.revision.wrapping_add(1);
449            inner.revision
450        };
451        self.revision.set(revision);
452        id
453    }
454
455    pub fn notify(&self, title: impl Into<String>, message: impl Into<String>) -> NotificationId {
456        self.push(TransientNotification::new(title, message))
457    }
458
459    pub fn dismiss(&self, id: NotificationId) -> bool {
460        let (changed, revision) = {
461            let mut inner = self
462                .inner
463                .lock()
464                .unwrap_or_else(std::sync::PoisonError::into_inner);
465            let before = inner.notifications.len();
466            inner
467                .notifications
468                .retain(|notification| notification.id != id);
469            let changed = before != inner.notifications.len();
470            if changed {
471                inner.revision = inner.revision.wrapping_add(1);
472            }
473            (changed, inner.revision)
474        };
475        if changed {
476            self.revision.set(revision);
477        }
478        changed
479    }
480
481    pub fn clear(&self) -> bool {
482        let (changed, revision) = {
483            let mut inner = self
484                .inner
485                .lock()
486                .unwrap_or_else(std::sync::PoisonError::into_inner);
487            let changed = !inner.notifications.is_empty();
488            inner.notifications.clear();
489            if changed {
490                inner.revision = inner.revision.wrapping_add(1);
491            }
492            (changed, inner.revision)
493        };
494        if changed {
495            self.revision.set(revision);
496        }
497        changed
498    }
499
500    pub fn snapshot(&self) -> Vec<TransientNotification> {
501        self.inner
502            .lock()
503            .unwrap_or_else(std::sync::PoisonError::into_inner)
504            .notifications
505            .clone()
506    }
507}
508
509impl Default for NotificationCenter {
510    fn default() -> Self {
511        Self::new()
512    }
513}
514
515/// How far a notification slides in from, toward the window edge.
516const TOAST_SLIDE: f32 = 24.0;
517
518/// A notification on screen: arriving, shown, or leaving.
519struct Toast {
520    notification: TransientNotification,
521    /// 0 gone, 1 shown.
522    presence: Motion<f32>,
523    /// Where the toast is stacked; it glides when others arrive or leave.
524    y: Motion<f32>,
525    frame: Rect,
526    positioned: bool,
527    leaving: bool,
528}
529
530impl Toast {
531    fn new(notification: TransientNotification) -> Self {
532        Self {
533            notification,
534            presence: Motion::new(0.0),
535            y: Motion::new(0.0).movement(),
536            frame: Rect::ZERO,
537            positioned: false,
538            leaving: false,
539        }
540    }
541
542    fn is_gone(&self, clock: &impl FrameClock) -> bool {
543        self.leaving && !self.presence.is_animating(clock) && self.presence.get(clock) <= 1.0e-4
544    }
545}
546
547/// Window-level visual and semantic host for a [`NotificationCenter`].
548///
549/// Notifications slide in at the window's edge, stack in arrival order, and
550/// fade out when dismissed or expired while the rest glide into place.
551pub struct NotificationHost {
552    center: NotificationCenter,
553    notifications: Vec<TransientNotification>,
554    toasts: Vec<Toast>,
555    timers: HashMap<TimerToken, NotificationId>,
556    scheduled: HashMap<NotificationId, TimerToken>,
557    frames: Vec<(NotificationId, Rect)>,
558    theme: DefaultTheme,
559    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
560    width: f32,
561    margin: f32,
562    gap: f32,
563}
564
565impl NotificationHost {
566    pub fn new(center: NotificationCenter) -> Self {
567        Self {
568            center,
569            notifications: Vec::new(),
570            toasts: Vec::new(),
571            timers: HashMap::new(),
572            scheduled: HashMap::new(),
573            frames: Vec::new(),
574            theme: DefaultTheme::default(),
575            theme_reader: None,
576            width: 340.0,
577            margin: 16.0,
578            gap: 8.0,
579        }
580    }
581
582    pub fn theme(mut self, theme: DefaultTheme) -> Self {
583        self.theme = theme;
584        self.theme_reader = None;
585        self
586    }
587
588    /// Resolve the theme each time the host lays out.
589    pub fn theme_when<F>(mut self, theme: F) -> Self
590    where
591        F: Fn() -> DefaultTheme + 'static,
592    {
593        self.theme = theme();
594        self.theme_reader = Some(Box::new(theme));
595        self
596    }
597
598    pub fn width(mut self, width: f32) -> Self {
599        self.width = width.max(120.0);
600        self
601    }
602
603    fn sync(&mut self, ctx: &mut EventCtx) {
604        self.notifications = self.center.snapshot();
605        let active = self
606            .notifications
607            .iter()
608            .map(|notification| notification.id)
609            .collect::<Vec<_>>();
610        let obsolete = self
611            .scheduled
612            .keys()
613            .copied()
614            .filter(|id| !active.contains(id))
615            .collect::<Vec<_>>();
616        for id in obsolete {
617            if let Some(token) = self.scheduled.remove(&id) {
618                self.timers.remove(&token);
619                ctx.cancel_timer(token);
620            }
621        }
622        for notification in &self.notifications {
623            let Some(duration) = notification.duration else {
624                continue;
625            };
626            if self.scheduled.contains_key(&notification.id) {
627                continue;
628            }
629            let duration = if duration.is_finite() {
630                duration.max(0.0)
631            } else {
632                0.0
633            };
634            let token = ctx.schedule_timer_after(duration);
635            self.scheduled.insert(notification.id, token);
636            self.timers.insert(token, notification.id);
637        }
638        ctx.request_measure();
639        ctx.request_paint();
640        ctx.request_semantics();
641    }
642
643    fn notification_height(&self, notification: &TransientNotification) -> f32 {
644        if notification.message.is_empty() {
645            48.0
646        } else {
647            68.0
648        }
649    }
650
651    /// Bring toasts in step with the notifications: new ones arrive, removed
652    /// ones start leaving, and finished ones go.
653    fn reconcile_toasts(&mut self, ctx: &mut MeasureCtx) {
654        let motion = self.theme.motion;
655        for toast in &mut self.toasts {
656            let current = self
657                .notifications
658                .iter()
659                .find(|notification| notification.id == toast.notification.id);
660            match current {
661                Some(notification) => {
662                    toast.notification = notification.clone();
663                    if toast.leaving {
664                        toast.leaving = false;
665                        ctx.animate(&mut toast.presence, 1.0, motion.entrance_spec());
666                    }
667                }
668                None if !toast.leaving => {
669                    toast.leaving = true;
670                    if ctx.animate(&mut toast.presence, 0.0, motion.exit_spec())
671                        && let Some(until) = toast.presence.end_time()
672                    {
673                        ctx.track_motion_end(until, InvalidationKind::Measure);
674                    }
675                }
676                None => {}
677            }
678        }
679        for notification in &self.notifications {
680            if self
681                .toasts
682                .iter()
683                .all(|toast| toast.notification.id != notification.id)
684            {
685                let mut toast = Toast::new(notification.clone());
686                ctx.animate(&mut toast.presence, 1.0, motion.entrance_spec());
687                self.toasts.push(toast);
688            }
689        }
690        self.toasts.retain(|toast| !toast.is_gone(ctx));
691    }
692}
693
694impl Widget for NotificationHost {
695    fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
696        if command.is(REACTIVE_CHANGED) {
697            self.sync(ctx);
698            ctx.set_handled();
699        }
700    }
701
702    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
703        match event {
704            Event::Wake(WakeEvent::AnimationFrame { .. }) => {
705                self.sync(ctx);
706                ctx.set_handled();
707            }
708            Event::Wake(WakeEvent::Timer { token, .. }) => {
709                if let Some(id) = self.timers.remove(token) {
710                    self.scheduled.remove(&id);
711                    self.center.dismiss(id);
712                    self.sync(ctx);
713                    ctx.set_handled();
714                }
715            }
716            _ => {}
717        }
718    }
719
720    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
721        if let Some(theme) = &self.theme_reader {
722            self.theme = theme();
723        }
724        let _ = ctx.observe(&self.center.revision);
725        self.notifications = self.center.snapshot();
726        self.reconcile_toasts(ctx);
727        if self.notifications.iter().any(|notification| {
728            notification.duration.is_some() && !self.scheduled.contains_key(&notification.id)
729        }) {
730            ctx.request_animation_frame();
731        }
732        constraints.clamp(Size::new(
733            if constraints.max.width.is_finite() {
734                constraints.max.width
735            } else {
736                self.width + self.margin * 2.0
737            },
738            if constraints.max.height.is_finite() {
739                constraints.max.height
740            } else {
741                480.0
742            },
743        ))
744    }
745
746    fn arrange(&mut self, ctx: &mut ArrangeCtx, bounds: Rect) {
747        self.frames.clear();
748        let width = self
749            .width
750            .min((bounds.width() - self.margin * 2.0).max(0.0));
751        let x = bounds.max_x() - self.margin - width;
752        let glide = self.theme.motion.layout_spec();
753        let mut y = bounds.y() + self.margin;
754        for index in 0..self.toasts.len() {
755            if self.toasts[index].leaving {
756                // Leaving toasts fade where they are; the rest close up.
757                continue;
758            }
759            let height = self.notification_height(&self.toasts[index].notification);
760            let toast = &mut self.toasts[index];
761            if toast.positioned {
762                ctx.animate(&mut toast.y, y, glide);
763            } else {
764                toast.y.jump_to(y);
765                toast.positioned = true;
766            }
767            toast.frame = Rect::new(x, y, width, height);
768            self.frames.push((toast.notification.id, toast.frame));
769            y += height + self.gap;
770        }
771    }
772
773    fn paint(&self, ctx: &mut PaintCtx) {
774        let metrics = self.theme.metrics;
775        let policy = motion_policy();
776        for toast in &self.toasts {
777            let presence = toast.presence.get(ctx).clamp(0.0, 1.0);
778            if presence <= 1.0e-4 {
779                continue;
780            }
781            let notification = &toast.notification;
782            let fade = |color: Color| color.with_alpha(color.alpha * presence);
783            let slide = TOAST_SLIDE * policy.entrance_offset(presence);
784            let frame = &Rect::new(
785                toast.frame.x() + slide,
786                toast.y.get(ctx),
787                toast.frame.width(),
788                toast.frame.height(),
789            );
790            let mut title_style = self.theme.body_text_style();
791            title_style.color = fade(title_style.color);
792            let mut message_style = self.theme.placeholder_text_style();
793            message_style.color = fade(message_style.color);
794            ctx.fill_rrect_bordered(
795                *frame,
796                [metrics.corner_radius; 4],
797                fade(self.theme.palette.surface_raised),
798                Border {
799                    width: metrics.border_width,
800                    color: fade(self.theme.palette.border),
801                },
802            );
803            let padding = 12.0;
804            let title_rect = Rect::new(
805                frame.x() + padding,
806                frame.y() + 8.0,
807                (frame.width() - padding * 2.0).max(0.0),
808                title_style.line_height,
809            );
810            ctx.draw_text(title_rect, notification.title.clone(), title_style.clone());
811            if !notification.message.is_empty() {
812                let message_rect = Rect::new(
813                    title_rect.x(),
814                    title_rect.max_y() + 4.0,
815                    title_rect.width(),
816                    message_style.line_height,
817                );
818                ctx.draw_text(
819                    message_rect,
820                    notification.message.clone(),
821                    message_style.clone(),
822                );
823            }
824        }
825    }
826
827    fn layer_options(&self) -> LayerOptions {
828        LayerOptions {
829            paint_boundary: PaintBoundaryMode::Explicit,
830            composition_mode: if self.toasts.is_empty() {
831                LayerCompositionMode::Normal
832            } else {
833                LayerCompositionMode::Overlay
834            },
835        }
836    }
837
838    fn stack_surface_options(&self) -> Option<StackSurfaceOptions> {
839        (!self.toasts.is_empty()).then_some(StackSurfaceOptions {
840            transient: true,
841            hit_test: false,
842            ..StackSurfaceOptions::default()
843        })
844    }
845
846    fn overlay_options(&self) -> Option<OverlayOptions> {
847        (!self.toasts.is_empty()).then_some(
848            OverlayOptions::new(OverlayKind::Notification)
849                .dismiss(OverlayDismissPolicy::NONE)
850                .focus(OverlayFocusBehavior::NONE),
851        )
852    }
853
854    fn semantics(&self, ctx: &mut SemanticsCtx) {
855        for notification in &self.notifications {
856            let Some((_, frame)) = self.frames.iter().find(|(id, _)| *id == notification.id) else {
857                continue;
858            };
859            let mut node = SemanticsNode::new(
860                WidgetId::new((1_u64 << 62) | notification.id.get()),
861                SemanticsRole::Status,
862                *frame,
863            );
864            node.parent = Some(ctx.widget_id());
865            node.name = Some(notification.title.clone());
866            node.description =
867                (!notification.message.is_empty()).then(|| notification.message.clone());
868            node.live_region = Some(match notification.urgency {
869                NotificationUrgency::Polite => SemanticsLiveRegion::Polite,
870                NotificationUrgency::Assertive => SemanticsLiveRegion::Assertive,
871            });
872            ctx.push(node);
873        }
874    }
875}
876
877#[cfg(test)]
878mod tests {
879    use super::*;
880    use sui_runtime::{Application, Runtime, WindowBuilder};
881
882    #[test]
883    fn placement_flips_before_shifting_when_the_other_side_fits() {
884        let result = place_overlay(
885            &OverlayPlacementRequest::new(
886                Rect::new(80.0, 170.0, 40.0, 20.0),
887                Size::new(100.0, 70.0),
888                Rect::new(0.0, 0.0, 240.0, 200.0),
889                OverlayPlacement::BOTTOM_START,
890            )
891            .gap(4.0),
892        );
893        assert_eq!(result.placement, OverlayPlacement::TOP_START);
894        assert_eq!(result.bounds, Rect::new(80.0, 96.0, 100.0, 70.0));
895        assert!(!result.shifted);
896    }
897
898    #[test]
899    fn placement_shifts_and_resizes_inside_safe_viewport() {
900        let result = place_overlay(
901            &OverlayPlacementRequest::new(
902                Rect::new(190.0, 90.0, 10.0, 10.0),
903                Size::new(260.0, 140.0),
904                Rect::new(0.0, 0.0, 200.0, 120.0),
905                OverlayPlacement::RIGHT_START,
906            )
907            .margin(8.0),
908        );
909        assert_eq!(result.bounds, Rect::new(8.0, 8.0, 184.0, 104.0));
910        assert!(result.resized);
911        assert!(result.shifted);
912    }
913
914    #[test]
915    fn notification_host_exposes_live_status_and_expires_it() {
916        let center = NotificationCenter::new();
917        let mut runtime = Application::new()
918            .window(
919                WindowBuilder::new()
920                    .title("Notifications")
921                    .root(NotificationHost::new(center.clone())),
922            )
923            .build()
924            .unwrap();
925        let window_id = runtime.window_ids()[0];
926        let initial = runtime.render(window_id).unwrap();
927        assert!(
928            initial
929                .semantics
930                .iter()
931                .all(|node| node.role != SemanticsRole::Status)
932        );
933
934        center.push(
935            TransientNotification::new("Upload complete", "artifact.zip is ready")
936                .duration(0.05)
937                .urgency(NotificationUrgency::Assertive),
938        );
939        let _ = runtime.render(window_id).unwrap();
940        for (ready_window, event) in runtime.drain_ready_events() {
941            runtime.handle_event(ready_window, event).unwrap();
942        }
943        let shown = runtime.render(window_id).unwrap();
944        let status = shown
945            .semantics
946            .iter()
947            .find(|node| node.role == SemanticsRole::Status)
948            .expect("notification status semantics");
949        assert_eq!(status.name.as_deref(), Some("Upload complete"));
950        assert_eq!(status.live_region, Some(SemanticsLiveRegion::Assertive));
951        assert_eq!(
952            runtime.overlay_snapshot(window_id).unwrap().overlays.len(),
953            1
954        );
955
956        runtime.tick(0.06);
957        for (ready_window, event) in runtime.drain_ready_events() {
958            runtime.handle_event(ready_window, event).unwrap();
959        }
960        let expired = runtime.render(window_id).unwrap();
961        assert!(
962            expired
963                .semantics
964                .iter()
965                .all(|node| node.role != SemanticsRole::Status)
966        );
967        // The toast fades out before the host leaves the overlay stack.
968        assert_eq!(
969            runtime.overlay_snapshot(window_id).unwrap().overlays.len(),
970            1
971        );
972        runtime.tick(0.06 + DefaultTheme::default().motion.exit_spec().duration() + 0.01);
973        for (ready_window, event) in runtime.drain_ready_events() {
974            runtime.handle_event(ready_window, event).unwrap();
975        }
976        runtime.render(window_id).unwrap();
977        assert!(
978            runtime
979                .overlay_snapshot(window_id)
980                .unwrap()
981                .overlays
982                .is_empty()
983        );
984        assert_eq!(runtime.next_wakeup_time(window_id).unwrap(), None);
985    }
986
987    #[test]
988    fn remaining_notifications_glide_up_when_one_leaves() {
989        let center = NotificationCenter::new();
990        let mut runtime = Application::new()
991            .window(WindowBuilder::new().root(NotificationHost::new(center.clone())))
992            .build()
993            .unwrap();
994        let window_id = runtime.window_ids()[0];
995        runtime
996            .handle_event(
997                window_id,
998                Event::Window(sui_core::WindowEvent::Resized(Size::new(400.0, 400.0))),
999            )
1000            .unwrap();
1001        let first = center.push(TransientNotification::new("First", "").persistent());
1002        center.push(TransientNotification::new("Second", "").persistent());
1003        runtime.render(window_id).unwrap();
1004        let status_top = |runtime: &Runtime, name: &str| {
1005            runtime
1006                .semantics(window_id)
1007                .unwrap()
1008                .iter()
1009                .find(|node| node.name.as_deref() == Some(name))
1010                .map(|node| node.bounds.y())
1011        };
1012        assert_eq!(status_top(&runtime, "Second"), Some(16.0 + 48.0 + 8.0));
1013
1014        center.dismiss(first);
1015        runtime.tick(1.0);
1016        for (ready_window, event) in runtime.drain_ready_events() {
1017            runtime.handle_event(ready_window, event).unwrap();
1018        }
1019        runtime.render(window_id).unwrap();
1020        // Semantics move at once; the painted toast glides.
1021        assert_eq!(status_top(&runtime, "Second"), Some(16.0));
1022        assert!(
1023            runtime.next_wakeup_time(window_id).unwrap().is_some(),
1024            "the toasts are still moving"
1025        );
1026    }
1027
1028    #[test]
1029    fn notification_center_accepts_threaded_producers() {
1030        let center = NotificationCenter::new();
1031        let producer = center.clone();
1032        std::thread::spawn(move || {
1033            producer.notify("Background task", "Indexed 42 files");
1034        })
1035        .join()
1036        .unwrap();
1037
1038        let notifications = center.snapshot();
1039        assert_eq!(notifications.len(), 1);
1040        assert_eq!(notifications[0].title, "Background task");
1041    }
1042}