Skip to main content

sui_widgets/
overlay.rs

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