BlueGit

ict rusty-teams

Files

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

center.rs

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