BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / notify / center.rs

center.rs

center.rs 30.7 KiB Download Raw
1use std::collections::{HashMap, HashSet};
2use std::time::{Duration, Instant};
3
4use chrono::Utc;
5use gpui_kit::*;
6use store::Sidebar;
7
8use super::badge::{Badge, badge_for};
9use super::incoming::IncomingTracker;
10use super::layout::{self, Slot};
11use super::platform::{self, NativeHandle, Tray, TrayCommand, WorkArea};
12use super::rules::{
13 ChatKind, Decision, Environment, Incoming, Preview, Settings, SoundThrottle, decide,
14 should_flash,
15};
16use super::settings;
17use super::settings_view::SettingsView;
18use super::stack::{
19 FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE, ToastModel, ToastStack,
20};
21use super::toast::{PillView, ToastView};
22use crate::app_state::{AppEvent, AppState, Selection};
23use crate::data::{self, Directory, PresenceKind};
24use crate::runtime;
25
26const TICK: Duration = Duration::from_millis(33);
27const SLIDE_DURATION: Duration = Duration::from_millis(180);
28const SLIDE_DISTANCE: f32 = 48.;
29const DEMO_SPEC_DELAY: Duration = Duration::from_secs(3);
30
31struct OpenWindow {
32 handle: AnyWindowHandle,
33 native: Option<NativeHandle>,
34 opened: Instant,
35}
36
37impl OpenWindow {
38 fn place(&self, native: NativeHandle, slot: Slot, x: i32, cx: &mut App) {
39 platform::place(native, x, slot.y, slot.width, slot.height);
40 // WM_SIZE arrives while the app is borrowed, so GPUI drops its own resize report.
41 self.handle
42 .update(cx, |_, window, cx| window.bounds_changed(cx))
43 .ok();
44 }
45}
46
47pub struct NotificationCenter {
48 app: Entity<AppState>,
49 main_window: AnyWindowHandle,
50 main_native: Option<NativeHandle>,
51 settings: Settings,
52 stack: ToastStack,
53 tracker: IncomingTracker,
54 throttle: SoundThrottle,
55 windows: HashMap<u64, OpenWindow>,
56 opening: HashSet<u64>,
57 pill: Option<OpenWindow>,
58 pill_opening: bool,
59 hover_hold: bool,
60 settings_window: Option<AnyWindowHandle>,
61 settings_opening: bool,
62 unread_mentions: HashSet<String>,
63 tray: Option<Tray>,
64 shown_badge: Option<Badge>,
65 animations: bool,
66 _subscription: Subscription,
67}
68
69impl NotificationCenter {
70 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
71 let settings = settings::load(&app.read(cx).store);
72 let tray = if app.read(cx).mode.demo {
73 None
74 } else {
75 Tray::new(settings.sound, settings.do_not_disturb)
76 };
77 let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {
78 this.on_app_event(event, cx);
79 });
80 let center = NotificationCenter {
81 main_window: window.window_handle(),
82 main_native: platform::native_handle(window),
83 settings,
84 stack: ToastStack::default(),
85 tracker: IncomingTracker::new(Utc::now()),
86 throttle: SoundThrottle::default(),
87 windows: HashMap::new(),
88 opening: HashSet::new(),
89 pill: None,
90 pill_opening: false,
91 hover_hold: false,
92 settings_window: None,
93 settings_opening: false,
94 unread_mentions: HashSet::new(),
95 tray,
96 shown_badge: None,
97 animations: platform::animations_enabled(),
98 app,
99 _subscription: subscription,
100 };
101 cx.spawn(async move |this, cx| {
102 loop {
103 cx.background_executor().timer(TICK).await;
104 if this.update(cx, |center, cx| center.tick(cx)).is_err() {
105 break;
106 }
107 }
108 })
109 .detach();
110 if center.app.read(cx).mode.demo {
111 cx.spawn(async move |this, cx| {
112 cx.background_executor().timer(DEMO_SPEC_DELAY).await;
113 this.update(cx, |center, cx| center.show_demo_toasts(cx))
114 .ok();
115 })
116 .detach();
117 }
118 center
119 }
120
121 pub fn settings(&self) -> &Settings {
122 &self.settings
123 }
124
125 pub fn model(&self, id: u64) -> Option<&ToastModel> {
126 self.stack.get(id)
127 }
128
129 pub fn queued_count(&self) -> usize {
130 self.stack.queued_count()
131 }
132
133 pub fn stack_opacity(&self) -> f32 {
134 let now = Instant::now();
135 self.stack
136 .visible()
137 .iter()
138 .map(|toast| toast.opacity(now))
139 .fold(0., f32::max)
140 }
141
142 fn animated(&self, duration: Duration) -> Duration {
143 if self.animations { duration } else { Duration::ZERO }
144 }
145
146 pub fn directory<'a>(&self, cx: &'a App) -> &'a Directory {
147 &self.app.read(cx).directory
148 }
149
150 pub fn reply_text(&self, id: u64) -> Option<String> {
151 self.stack.get(id).map(|toast| toast.reply_text.clone())
152 }
153
154 pub fn intercept_close(&self, _cx: &App) -> bool {
155 match (self.settings.close_to_tray, &self.tray, self.main_native) {
156 (true, Some(_), Some(native)) => {
157 platform::hide_window(native);
158 true
159 }
160 _ => false,
161 }
162 }
163
164 pub fn update_settings(&mut self, cx: &mut Context<Self>, change: impl FnOnce(&mut Settings)) {
165 change(&mut self.settings);
166 settings::save(&self.app.read(cx).store, &self.settings);
167 self.sync_tray();
168 cx.notify();
169 }
170
171 fn on_app_event(&mut self, event: &AppEvent, cx: &mut Context<Self>) {
172 match event {
173 AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),
174 AppEvent::Selection => self.on_selection(cx),
175 AppEvent::Sidebar => self.refresh_badge(cx),
176 _ => {}
177 }
178 }
179
180 fn on_selection(&mut self, cx: &mut Context<Self>) {
181 let selected = self
182 .app
183 .read(cx)
184 .selection
185 .as_ref()
186 .map(|selection| selection.conversation_id().to_owned());
187 if let Some(conversation_id) = selected {
188 self.unread_mentions.remove(&conversation_id);
189 self.stack.remove_conversation(&conversation_id);
190 }
191 self.refresh_badge(cx);
192 }
193
194 fn on_messages(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
195 let state = self.app.read(cx);
196 let my_user_id = state.directory.me.as_ref().map(|me| me.user_id.clone());
197 let found = self.tracker.collect(
198 &state.store,
199 &state.sidebar,
200 my_user_id.as_deref(),
201 conversation_id,
202 );
203 for incoming in found {
204 self.handle_incoming(incoming, cx);
205 }
206 self.refresh_badge(cx);
207 }
208
209 fn environment(&self, conversation_id: &str, cx: &mut Context<Self>) -> Environment {
210 let state = self.app.read(cx);
211 let selected = state
212 .selection
213 .as_ref()
214 .is_some_and(|selection| selection.conversation_id() == conversation_id);
215 let own_do_not_disturb = state.directory.me.as_ref().is_some_and(|me| {
216 state.directory.presence_of(&me.user_id).kind() == PresenceKind::DoNotDisturb
217 });
218 let in_call = match (state.engine.as_ref(), state.directory.me.as_ref()) {
219 (Some(engine), Some(me)) => data::in_call(engine, &me.user_id),
220 _ => false,
221 };
222 Environment {
223 chat_in_foreground: selected && self.main_window_active(cx),
224 system_quiet: platform::system_quiet(),
225 own_do_not_disturb,
226 in_call,
227 }
228 }
229
230 fn main_window_active(&self, cx: &mut Context<Self>) -> bool {
231 self.main_window
232 .update(cx, |_, window, _| window.is_window_active())
233 .unwrap_or(false)
234 }
235
236 pub fn handle_incoming(&mut self, incoming: Incoming, cx: &mut Context<Self>) {
237 let environment = self.environment(&incoming.conversation_id, cx);
238 if !environment.chat_in_foreground && incoming.mentions_me {
239 self.unread_mentions
240 .insert(incoming.conversation_id.clone());
241 }
242 let decision = decide(&self.settings, &incoming, environment);
243 self.present(&incoming, decision, cx);
244 if should_flash(
245 &self.settings,
246 incoming.mentions_me && decision.toast,
247 self.main_window_active(cx),
248 ) && let Some(native) = self.main_native
249 {
250 platform::flash(native);
251 }
252 }
253
254 fn present(&mut self, incoming: &Incoming, decision: Decision, cx: &mut Context<Self>) {
255 if !decision.toast {
256 return;
257 }
258 let now = Instant::now();
259 let outcome = self.stack.push(incoming, now);
260 if let Some(model) = self.stack.get_mut(outcome.id) {
261 model.time = chrono::Local::now().format("%H:%M").to_string();
262 }
263 let throttle_allows = self.throttle.allow(&incoming.conversation_id, now);
264 if decision.sound && outcome.plays_sound(throttle_allows) && !self.app.read(cx).mode.demo {
265 platform::play_sound();
266 }
267 if let Some(user_id) = incoming.sender_id.clone() {
268 self.app
269 .update(cx, |state, cx| state.request_avatars(vec![user_id], cx));
270 }
271 self.sync_windows(cx);
272 }
273
274 fn visible_ids(&self) -> Vec<u64> {
275 self.stack.visible().iter().map(|toast| toast.id).collect()
276 }
277
278 fn work_area(&self, cx: &App) -> WorkArea {
279 if let Some(area) = self.main_native.and_then(platform::work_area) {
280 return area;
281 }
282 let bounds = cx
283 .primary_display()
284 .map(|display| display.bounds())
285 .unwrap_or_else(|| Bounds::new(point(px(0.), px(0.)), size(px(1280.), px(720.))));
286 WorkArea {
287 left: f32::from(bounds.origin.x) as i32,
288 top: f32::from(bounds.origin.y) as i32,
289 right: f32::from(bounds.origin.x + bounds.size.width) as i32,
290 bottom: f32::from(bounds.origin.y + bounds.size.height) as i32,
291 scale: 1.,
292 }
293 }
294
295 fn sync_windows(&mut self, cx: &mut Context<Self>) {
296 let visible = self.visible_ids();
297 let stale: Vec<u64> = self
298 .windows
299 .keys()
300 .filter(|id| !visible.contains(id))
301 .copied()
302 .collect();
303 for id in stale {
304 self.close_window(id, cx);
305 }
306 let area = self.work_area(cx);
307 let heights: Vec<f32> = self
308 .stack
309 .visible()
310 .iter()
311 .map(|toast| layout::toast_height(toast, self.settings.preview))
312 .collect();
313 let with_hide_all = visible.len() > 1 || self.stack.queued_count() > 0;
314 let slots = layout::stack_slots(area, self.settings.corner, &heights, with_hide_all);
315 for (id, slot) in visible.iter().zip(slots.toasts.iter()) {
316 self.place_toast(*id, *slot, area, cx);
317 }
318 self.sync_pill(slots.pill, area, cx);
319 }
320
321 fn slide_offset(&self, opened: Instant, area: WorkArea) -> i32 {
322 if !self.animations {
323 return 0;
324 }
325 let progress = (opened.elapsed().as_secs_f32() / SLIDE_DURATION.as_secs_f32()).min(1.);
326 let eased = 1. - (1. - progress).powi(3);
327 let distance = ((1. - eased) * SLIDE_DISTANCE * area.scale) as i32;
328 if self.settings.corner.is_right() {
329 distance
330 } else {
331 -distance
332 }
333 }
334
335 fn place_toast(&mut self, id: u64, slot: Slot, area: WorkArea, cx: &mut Context<Self>) {
336 if !self.windows.contains_key(&id) {
337 self.open_toast_window(id, slot, area, cx);
338 return;
339 }
340 let offset = self
341 .windows
342 .get(&id)
343 .map(|window| self.slide_offset(window.opened, area))
344 .unwrap_or(0);
345 if let Some(window) = self.windows.get(&id)
346 && let Some(native) = window.native
347 {
348 window.place(native, slot, slot.x + offset, cx);
349 }
350 }
351
352 fn open_toast_window(&mut self, id: u64, slot: Slot, area: WorkArea, cx: &mut Context<Self>) {
353 if !self.opening.insert(id) {
354 return;
355 }
356 open_popup(
357 popup_options(slot, area),
358 cx,
359 move |center, window, cx| cx.new(|cx| ToastView::new(center, id, window, cx)),
360 move |this, window| {
361 this.opening.remove(&id);
362 if let Some(window) = window {
363 this.windows.insert(id, window);
364 }
365 },
366 );
367 }
368
369 fn sync_pill(
370 &mut self,
371 slot: Option<Slot>,
372 area: WorkArea,
373 cx: &mut Context<Self>,
374 ) {
375 let Some(slot) = slot else {
376 if let Some(pill) = self.pill.take() {
377 pill.handle
378 .update(cx, |_, window, _| window.remove_window())
379 .ok();
380 }
381 return;
382 };
383 if self.pill.is_none() && !self.pill_opening {
384 self.pill_opening = true;
385 open_popup(
386 popup_options(slot, area),
387 cx,
388 |center, _, cx| cx.new(|cx| PillView::new(center, cx)),
389 |this, window| {
390 this.pill_opening = false;
391 this.pill = window;
392 },
393 );
394 }
395 if let Some(pill) = self.pill.as_ref()
396 && let Some(native) = pill.native
397 {
398 pill.place(native, slot, slot.x, cx);
399 }
400 }
401
402 fn close_window(&mut self, id: u64, cx: &mut Context<Self>) {
403 let closed = self.windows.get(&id).is_some_and(|window| {
404 window
405 .handle
406 .update(cx, |_, window, _| window.remove_window())
407 .is_ok()
408 });
409 if closed {
410 self.windows.remove(&id);
411 }
412 }
413
414 fn drop_toast(&mut self, id: u64, cx: &mut Context<Self>) {
415 let fast = self.animated(FAST_FADE);
416 self.stack.dismiss(id, Instant::now(), fast);
417 cx.notify();
418 }
419
420 pub fn hide_all(&mut self, cx: &mut Context<Self>) {
421 for id in self.stack.ids() {
422 self.drop_toast(id, cx);
423 }
424 }
425
426 fn sync_hover_hold(&mut self, now: Instant) {
427 let any_hovered = self.stack.any_hovered();
428 if !any_hovered && !self.hover_hold {
429 return;
430 }
431 if any_hovered {
432 let fast = self.animated(FAST_FADE);
433 self.stack.restore(now, fast);
434 }
435 for id in self.stack.ids() {
436 if let Some(toast) = self.stack.get_mut(id)
437 && !toast.queued
438 {
439 if any_hovered {
440 toast.timer.pause(now);
441 } else if !toast.holds_open() {
442 toast.timer.resume(now);
443 }
444 }
445 }
446 self.hover_hold = any_hovered;
447 }
448
449 fn is_dismissed(&self, id: u64) -> bool {
450 self.stack.get(id).is_none_or(|toast| toast.dismissed)
451 }
452
453 fn tick(&mut self, cx: &mut Context<Self>) {
454 let now = Instant::now();
455 let (fade_in, slow) = (self.animated(FADE_IN), self.animated(SLOW_FADE));
456 for id in self.stack.expired(now) {
457 self.stack.fade_out(id, now, slow);
458 }
459 for id in self.stack.gone(now) {
460 self.stack.remove(id);
461 }
462 self.stack.promote(now, fade_in);
463 self.sync_hover_hold(now);
464 if !self.stack.is_empty() || !self.windows.is_empty() || self.pill.is_some() {
465 self.sync_windows(cx);
466 cx.notify();
467 }
468 self.poll_tray(cx);
469 }
470
471 fn poll_tray(&mut self, cx: &mut Context<Self>) {
472 let commands = self.tray.as_ref().map(Tray::poll).unwrap_or_default();
473 for command in commands {
474 match command {
475 TrayCommand::Toggle => self.toggle_main_window(cx),
476 TrayCommand::Open => self.raise_main_window(cx),
477 TrayCommand::ToggleSound => {
478 self.update_settings(cx, |settings| settings.sound = !settings.sound)
479 }
480 TrayCommand::ToggleDoNotDisturb => self.update_settings(cx, |settings| {
481 settings.do_not_disturb = !settings.do_not_disturb
482 }),
483 TrayCommand::Settings => self.open_settings(cx),
484 TrayCommand::Quit => cx.quit(),
485 }
486 }
487 }
488
489 fn toggle_main_window(&mut self, cx: &mut Context<Self>) {
490 if self.main_window_active(cx) {
491 if let Some(native) = self.main_native {
492 platform::hide_window(native);
493 }
494 } else {
495 self.raise_main_window(cx);
496 }
497 }
498
499 fn raise_main_window(&mut self, cx: &mut Context<Self>) {
500 if let Some(native) = self.main_native {
501 platform::restore_and_raise(native);
502 }
503 self.main_window
504 .update(cx, |_, window, _| window.activate_window())
505 .ok();
506 }
507
508 fn sync_tray(&self) {
509 if let Some(tray) = &self.tray {
510 tray.sync(
511 self.settings.sound,
512 self.settings.do_not_disturb,
513 !self.unread_mentions.is_empty(),
514 );
515 }
516 }
517
518 fn refresh_badge(&mut self, cx: &mut Context<Self>) {
519 let (count, still_unread) = unread_summary(&self.app.read(cx).sidebar);
520 self.unread_mentions
521 .retain(|conversation_id| still_unread.contains(conversation_id));
522 let badge = badge_for(count, !self.unread_mentions.is_empty());
523 if badge == self.shown_badge {
524 return;
525 }
526 if let Some(native) = self.main_native {
527 platform::set_badge(native, badge.as_ref());
528 }
529 self.shown_badge = badge;
530 self.sync_tray();
531 }
532
533 pub fn set_hover(&mut self, id: u64, hovered: bool, cx: &mut Context<Self>) {
534 let now = Instant::now();
535 let Some(toast) = self.stack.get_mut(id) else {
536 return;
537 };
538 if toast.hovered == hovered {
539 return;
540 }
541 toast.hovered = hovered;
542 self.sync_hover_hold(now);
543 cx.notify();
544 }
545
546 pub fn dismiss(&mut self, id: u64, cx: &mut Context<Self>) {
547 self.drop_toast(id, cx);
548 }
549
550 pub fn open_reply(&mut self, id: u64, cx: &mut Context<Self>) -> Option<String> {
551 let now = Instant::now();
552 let toast = self.stack.get_mut(id)?;
553 toast.reply = ReplyState::Open;
554 toast.timer.pause(now);
555 let draft = toast.reply_text.clone();
556 cx.notify();
557 Some(draft)
558 }
559
560 pub fn close_reply(&mut self, id: u64, cx: &mut Context<Self>) {
561 if let Some(toast) = self.stack.get_mut(id) {
562 toast.reply = ReplyState::Closed;
563 toast.reply_text.clear();
564 toast.hovered = false;
565 }
566 cx.notify();
567 }
568
569 pub fn submit_reply(&mut self, id: u64, text: String, cx: &mut Context<Self>) {
570 let Some(toast) = self.stack.get_mut(id) else {
571 return;
572 };
573 toast.reply_text = text.clone();
574 let conversation_id = toast.conversation_id.clone();
575 let message_id = toast.message_id.clone();
576 let is_channel = matches!(toast.kind, ChatKind::Channel { .. });
577 let state = self.app.read(cx);
578 let (mode, engine) = (state.mode, state.engine.clone());
579 let outcome: Result<(), ()> = if mode.demo {
580 Ok(())
581 } else if mode.read_only {
582 Err(())
583 } else if let Some(engine) = engine {
584 let receiver = runtime::spawn(async move {
585 if is_channel {
586 engine.reply_to(&conversation_id, &message_id, &text).await
587 } else {
588 engine.send_message(&conversation_id, &text, None).await
589 }
590 .map(|_| ())
591 });
592 cx.spawn(async move |this, cx| {
593 let sent = matches!(receiver.await, Ok(Ok(())));
594 this.update(cx, |center, cx| center.finish_reply(id, sent, cx))
595 .ok();
596 })
597 .detach();
598 return;
599 } else {
600 Err(())
601 };
602 self.finish_reply(id, outcome.is_ok(), cx);
603 }
604
605 fn finish_reply(&mut self, id: u64, sent: bool, cx: &mut Context<Self>) {
606 let Some(toast) = self.stack.get_mut(id) else {
607 return;
608 };
609 toast.reply = if sent {
610 ReplyState::Sent
611 } else {
612 ReplyState::Failed
613 };
614 let conversation_id = toast.conversation_id.clone();
615 cx.notify();
616 if sent {
617 cx.spawn(async move |this, cx| {
618 cx.background_executor().timer(SENT_DURATION).await;
619 this.update(cx, |center, cx| {
620 center.mark_conversation_read(&conversation_id, cx);
621 center.drop_toast(id, cx);
622 })
623 .ok();
624 })
625 .detach();
626 }
627 }
628
629 fn mark_conversation_read(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
630 self.unread_mentions.remove(conversation_id);
631 let conversation_id = conversation_id.to_owned();
632 self.app
633 .update(cx, |state, cx| state.mark_chat_read(&conversation_id, cx));
634 self.refresh_badge(cx);
635 }
636
637 pub fn mark_read(&mut self, id: u64, cx: &mut Context<Self>) {
638 if self.is_dismissed(id) {
639 return;
640 }
641 let Some(conversation_id) = self
642 .stack
643 .get(id)
644 .map(|toast| toast.conversation_id.clone())
645 else {
646 return;
647 };
648 self.mark_conversation_read(&conversation_id, cx);
649 self.drop_toast(id, cx);
650 }
651
652 pub fn activate(&mut self, id: u64, cx: &mut Context<Self>) {
653 if self.is_dismissed(id) {
654 return;
655 }
656 let Some((conversation_id, message_id)) = self
657 .stack
658 .get(id)
659 .map(|toast| (toast.conversation_id.clone(), toast.message_id.clone()))
660 else {
661 return;
662 };
663 self.drop_toast(id, cx);
664 self.raise_main_window(cx);
665 let selection = selection_for(&self.app.read(cx).sidebar, &conversation_id);
666 if let Some(selection) = selection {
667 self.app.update(cx, |state, cx| {
668 state.jump_to_message(selection, message_id, cx)
669 });
670 }
671 }
672
673 pub fn open_settings(&mut self, cx: &mut Context<Self>) {
674 if let Some(handle) = self.settings_window {
675 if handle
676 .update(cx, |_, window, _| window.activate_window())
677 .is_ok()
678 {
679 return;
680 }
681 self.settings_window = None;
682 }
683 if self.settings_opening {
684 return;
685 }
686 self.settings_opening = true;
687 let center = cx.entity();
688 let options = WindowOptions {
689 window_bounds: Some(WindowBounds::Windowed(Bounds::centered(
690 None,
691 size(px(SettingsView::WIDTH), px(SettingsView::HEIGHT)),
692 cx,
693 ))),
694 titlebar: Some(TitlebarOptions {
695 title: Some("Notifications".into()),
696 ..Default::default()
697 }),
698 is_resizable: false,
699 is_minimizable: false,
700 ..Default::default()
701 };
702 // open_window draws once right away, and SettingsView reads this entity while rendering.
703 cx.defer(move |cx| {
704 let view_center = center.clone();
705 let opened = gpui_kit::open_window(options, cx, move |_, cx| {
706 cx.new(|cx| SettingsView::new(view_center, cx))
707 });
708 center.update(cx, |this, _| {
709 this.settings_opening = false;
710 this.settings_window = opened.ok().map(|(handle, _)| handle);
711 });
712 });
713 }
714
715 pub fn send_test_notification(&mut self, cx: &mut Context<Self>) {
716 let incoming = Incoming {
717 conversation_id: "test-notification".to_owned(),
718 message_id: "test".to_owned(),
719 kind: ChatKind::Direct,
720 chat_title: "Mara Lindqvist".to_owned(),
721 sender_id: None,
722 sender_name: "Mara Lindqvist".to_owned(),
723 preview: Preview::Text("This is a test notification.".to_owned()),
724 mentions_me: false,
725 muted: false,
726 };
727 let decision = Decision {
728 toast: true,
729 sound: self.settings.sound,
730 };
731 self.throttle = SoundThrottle::default();
732 self.present(&incoming, decision, cx);
733 }
734
735 fn show_demo_toasts(&mut self, cx: &mut Context<Self>) {
736 for incoming in demo_incoming() {
737 let decision = Decision {
738 toast: true,
739 sound: false,
740 };
741 self.present(&incoming, decision, cx);
742 }
743 }
744}
745
746/// Opens a window outside the current update: `open_window` draws right away, and every
747/// notification view reads the center while rendering.
748fn open_popup<V: Render>(
749 options: WindowOptions,
750 cx: &mut Context<NotificationCenter>,
751 build: impl FnOnce(Entity<NotificationCenter>, &mut Window, &mut App) -> Entity<V> + 'static,
752 opened: impl FnOnce(&mut NotificationCenter, Option<OpenWindow>) + 'static,
753) {
754 let center = cx.entity();
755 cx.defer(move |cx| {
756 let view_center = center.clone();
757 let Ok((handle, _)) = gpui_kit::open_window(options, cx, move |window, cx| {
758 build(view_center, window, cx)
759 }) else {
760 center.update(cx, |this, _| opened(this, None));
761 return;
762 };
763 let native = handle
764 .update(cx, |_, window, _| platform::native_handle(window))
765 .ok()
766 .flatten();
767 if let Some(native) = native {
768 platform::prepare_toast_window(native);
769 }
770 let window = OpenWindow {
771 handle,
772 native,
773 opened: Instant::now(),
774 };
775 center.update(cx, |this, _| opened(this, Some(window)));
776 });
777}
778
779fn popup_options(slot: Slot, area: WorkArea) -> WindowOptions {
780 let scale = area.scale;
781 let bounds = Bounds::new(
782 point(px(slot.x as f32 / scale), px(slot.y as f32 / scale)),
783 size(
784 px(slot.width as f32 / scale),
785 px(slot.height as f32 / scale),
786 ),
787 );
788 WindowOptions {
789 window_bounds: Some(WindowBounds::Windowed(bounds)),
790 titlebar: None,
791 focus: false,
792 show: true,
793 kind: WindowKind::PopUp,
794 is_movable: false,
795 is_resizable: false,
796 is_minimizable: false,
797 window_background: WindowBackgroundAppearance::Transparent,
798 ..Default::default()
799 }
800}
801
802pub fn selection_for(sidebar: &Sidebar, conversation_id: &str) -> Option<Selection> {
803 if sidebar.chats.iter().any(|chat| chat.id == conversation_id) {
804 return Some(Selection::Chat(conversation_id.to_owned()));
805 }
806 sidebar
807 .teams
808 .iter()
809 .flat_map(|team| team.channels.iter())
810 .any(|channel| channel.id == conversation_id)
811 .then(|| Selection::Channel(conversation_id.to_owned()))
812}
813
814pub fn unread_summary(sidebar: &Sidebar) -> (usize, HashSet<String>) {
815 let chats = sidebar.chats.iter().filter(|chat| chat.unread);
816 let channels = sidebar
817 .teams
818 .iter()
819 .flat_map(|team| team.channels.iter())
820 .filter(|channel| channel.unread);
821 let ids: HashSet<String> = chats
822 .map(|chat| chat.id.clone())
823 .chain(channels.map(|channel| channel.id.clone()))
824 .collect();
825 (ids.len(), ids)
826}
827
828fn demo_incoming() -> Vec<Incoming> {
829 let item = |conversation: &str,
830 kind: ChatKind,
831 title: &str,
832 sender: &str,
833 text: &str,
834 mention: bool| Incoming {
835 conversation_id: conversation.to_owned(),
836 message_id: format!("{conversation}-message"),
837 kind,
838 chat_title: title.to_owned(),
839 sender_id: None,
840 sender_name: sender.to_owned(),
841 preview: Preview::Text(text.to_owned()),
842 mentions_me: mention,
843 muted: false,
844 };
845 vec![
846 item(
847 "demo-toast-direct",
848 ChatKind::Direct,
849 "Tobias Klein",
850 "Tobias Klein",
851 "Sounds good, I will look at it tomorrow.",
852 false,
853 ),
854 item(
855 "demo-toast-group",
856 ChatKind::Group { member_count: 5 },
857 "Retro-Team",
858 "Priya Nair",
859 "Please add topics by 5 pm.",
860 false,
861 ),
862 item(
863 "demo-toast-mention",
864 ChatKind::Channel {
865 team: "Platform".to_owned(),
866 channel: "Releases".to_owned(),
867 },
868 "Releases",
869 "Mara Lindqvist",
870 "@Jonas can you approve the merge? The pipeline is waiting.",
871 true,
872 ),
873 item(
874 "demo-toast-lea",
875 ChatKind::Direct,
876 "Lea Schneider",
877 "Lea Schneider",
878 "Lunch at 12?",
879 false,
880 ),
881 item(
882 "demo-toast-jonas",
883 ChatKind::Direct,
884 "Jonas Ortega",
885 "Jonas Ortega",
886 "Deploy window moved to Thursday 6 pm.",
887 false,
888 ),
889 ]
890}
891
892#[cfg(test)]
893mod tests {
894 use store::{ChannelRecord, ChatRecord, SidebarTeam, TeamRecord};
895
896 use super::{selection_for, unread_summary};
897 use crate::app_state::Selection;
898 use store::Sidebar;
899
900 fn sidebar() -> Sidebar {
901 Sidebar {
902 chats: vec![
903 ChatRecord {
904 id: "a".into(),
905 unread: true,
906 ..Default::default()
907 },
908 ChatRecord {
909 id: "b".into(),
910 unread: false,
911 ..Default::default()
912 },
913 ],
914 teams: vec![SidebarTeam {
915 team: TeamRecord {
916 id: "t".into(),
917 name: "Team".into(),
918 },
919 channels: vec![ChannelRecord {
920 id: "ch".into(),
921 team_id: "t".into(),
922 name: "General".into(),
923 membership_type: None,
924 last_message_at: None,
925 unread: true,
926 }],
927 hidden: false,
928 hidden_channel_ids: Vec::new(),
929 }],
930 }
931 }
932
933 #[test]
934 fn unread_summary_counts_chats_and_channels() {
935 let (count, ids) = unread_summary(&sidebar());
936 assert_eq!(count, 2);
937 assert!(ids.contains("a") && ids.contains("ch"));
938 }
939
940 #[test]
941 fn selection_kind_follows_sidebar() {
942 assert_eq!(
943 selection_for(&sidebar(), "a"),
944 Some(Selection::Chat("a".into()))
945 );
946 assert_eq!(
947 selection_for(&sidebar(), "ch"),
948 Some(Selection::Channel("ch".into()))
949 );
950 assert_eq!(selection_for(&sidebar(), "x"), None);
951 }
952}