BlueGit

ict rusty-teams

Files

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

center.rs

center.rs 47.1 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, MEETING_HEIGHT, Slot, ring_height};
11use super::meeting_view::MeetingToastView;
12use super::platform::{self, NativeHandle, Tray, TrayCommand, WorkArea};
13use super::ring_view::RingView;
14use super::rules::{
15 ChatKind, Decision, Environment, Incoming, Preview, Settings, SoundThrottle, decide, in_call,
16 meeting_start_sound, ringtone_for, should_flash, should_ringback,
17};
18use super::settings;
19use super::sound_cache::{self, SoundHandle};
20use super::sounds::{CallTone, Ringtone};
21use super::stack::{
22 AgentToast, FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE, ToastModel, ToastStack,
23};
24use super::taskbar::taskbar_badge_count;
25use super::text::describe;
26use super::toast::{PillView, ToastView};
27use crate::active_appearance::{self, ActiveAppearance};
28use crate::activity::ActivityCenter;
29use crate::agents::{AgentRun, AgentRunsEvent, RunState};
30use crate::app_state::{AppEvent, AppState, selection_for};
31use crate::appearance::AppIcon;
32use crate::call::DemoScene;
33use crate::data::{self, Directory, PresenceKind};
34use crate::runtime;
35use crate::settings_section::SettingsSection;
36use crate::single_instance;
37
38const TICK: Duration = Duration::from_millis(33);
39const SLIDE_DURATION: Duration = Duration::from_millis(180);
40const SLIDE_DISTANCE: f32 = 48.;
41const DEMO_SPEC_DELAY: Duration = Duration::from_secs(3);
42const DEMO_RING_ENV: &str = "TEAMS_DEMO_RING";
43const DEMO_RING_KIND_ENV: &str = "TEAMS_DEMO_RING_KIND";
44const DEMO_CALL_ENV: &str = "TEAMS_DEMO_CALL";
45const DEMO_SCENE_DELAY: Duration = Duration::from_millis(1500);
46const AGENT_BODY_LINES: usize = 2;
47
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
49enum CallToast {
50 Ring(u64),
51 Meeting(u64),
52}
53
54struct OpenWindow {
55 handle: AnyWindowHandle,
56 native: Option<NativeHandle>,
57 opened: Instant,
58}
59
60impl OpenWindow {
61 fn place(&self, native: NativeHandle, slot: Slot, x: i32, cx: &mut App) {
62 platform::place(native, x, slot.y, slot.width, slot.height);
63 // WM_SIZE arrives while the app is borrowed, so GPUI drops its own resize report.
64 self.handle
65 .update(cx, |_, window, cx| window.bounds_changed(cx))
66 .ok();
67 }
68}
69
70pub struct NotificationCenter {
71 app: Entity<AppState>,
72 activity: Entity<ActivityCenter>,
73 main_window: AnyWindowHandle,
74 main_native: Option<NativeHandle>,
75 settings: Settings,
76 stack: ToastStack,
77 tracker: IncomingTracker,
78 throttle: SoundThrottle,
79 windows: HashMap<u64, OpenWindow>,
80 opening: HashSet<u64>,
81 call_windows: HashMap<CallToast, OpenWindow>,
82 call_opening: HashSet<CallToast>,
83 ring_tone: Option<SoundHandle>,
84 ringback: Option<SoundHandle>,
85 reconnecting: Option<SoundHandle>,
86 preview: Option<SoundHandle>,
87 demo_mode: bool,
88 pill: Option<OpenWindow>,
89 pill_opening: bool,
90 hover_hold: bool,
91 unread_mentions: HashSet<String>,
92 tray: Option<Tray>,
93 app_icon: AppIcon,
94 shown_badge: Option<Badge>,
95 animations: bool,
96 _subscription: Subscription,
97 _activity_observation: Subscription,
98 _appearance_observation: Subscription,
99 _agent_subscription: Option<Subscription>,
100}
101
102impl NotificationCenter {
103 pub fn new(
104 app: Entity<AppState>,
105 activity: Entity<ActivityCenter>,
106 window: &mut Window,
107 cx: &mut Context<Self>,
108 ) -> Self {
109 let settings = settings::load(&app.read(cx).store);
110 let app_icon = active_appearance::current(cx).app_icon;
111 let tray = if app.read(cx).mode.demo {
112 None
113 } else {
114 Tray::new(
115 settings.sounds.notification_sound,
116 settings.do_not_disturb,
117 app_icon.png(),
118 )
119 };
120 platform::set_window_icon(window, app_icon.png());
121 let appearance_observation = cx.observe_global::<ActiveAppearance>(|this, cx| {
122 this.apply_app_icon(active_appearance::current(cx).app_icon, cx)
123 });
124 let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {
125 this.on_app_event(event, cx);
126 });
127 let activity_observation = cx.observe(&activity, |this, _, cx| this.refresh_badge(cx));
128 let agent_subscription = crate::agents::runs_handle(cx).map(|runs| {
129 cx.subscribe(&runs, |this, runs, event: &AgentRunsEvent, cx| {
130 if let AgentRunsEvent::Finished(run_id) = event
131 && let Some(run) = runs.read(cx).get(*run_id).cloned()
132 {
133 this.present_agent_run(&run, cx);
134 }
135 })
136 });
137 let center = NotificationCenter {
138 main_window: window.window_handle(),
139 main_native: platform::native_handle(window),
140 settings,
141 stack: ToastStack::default(),
142 tracker: IncomingTracker::new(Utc::now()),
143 throttle: SoundThrottle::default(),
144 windows: HashMap::new(),
145 opening: HashSet::new(),
146 call_windows: HashMap::new(),
147 call_opening: HashSet::new(),
148 ring_tone: None,
149 ringback: None,
150 reconnecting: None,
151 preview: None,
152 demo_mode: app.read(cx).mode.demo,
153 pill: None,
154 pill_opening: false,
155 hover_hold: false,
156 unread_mentions: HashSet::new(),
157 tray,
158 app_icon,
159 shown_badge: None,
160 animations: platform::animations_enabled(),
161 app,
162 activity,
163 _subscription: subscription,
164 _activity_observation: activity_observation,
165 _appearance_observation: appearance_observation,
166 _agent_subscription: agent_subscription,
167 };
168 cx.spawn(async move |this, cx| {
169 loop {
170 cx.background_executor().timer(TICK).await;
171 if this.update(cx, |center, cx| center.tick(cx)).is_err() {
172 break;
173 }
174 }
175 })
176 .detach();
177 if !center.demo_mode {
178 center.prefetch_sounds(cx);
179 }
180 if center.app.read(cx).mode.demo {
181 if demo_scene().is_none() {
182 cx.spawn(async move |this, cx| {
183 cx.background_executor().timer(DEMO_SPEC_DELAY).await;
184 this.update(cx, |center, cx| center.show_demo_toasts(cx))
185 .ok();
186 })
187 .detach();
188 }
189 if let Some(delay) = demo_ring_delay() {
190 let app = center.app.clone();
191 let video =
192 std::env::var(DEMO_RING_KIND_ENV).is_ok_and(|kind| kind.trim() == "video");
193 cx.spawn(async move |_, cx| {
194 cx.background_executor().timer(delay).await;
195 app.update(cx, |state, cx| {
196 if video {
197 state.demo_incoming_video_ring(cx)
198 } else {
199 state.demo_incoming_ring(cx)
200 }
201 });
202 })
203 .detach();
204 }
205 if let Some(scene) = demo_scene() {
206 let app = center.app.clone();
207 cx.spawn(async move |_, cx| {
208 cx.background_executor().timer(DEMO_SCENE_DELAY).await;
209 app.update(cx, |state, cx| state.start_demo_scene(scene, cx));
210 })
211 .detach();
212 }
213 }
214 center
215 }
216
217 pub fn app(&self) -> &Entity<AppState> {
218 &self.app
219 }
220
221 pub fn settings(&self) -> &Settings {
222 &self.settings
223 }
224
225 pub fn model(&self, id: u64) -> Option<&ToastModel> {
226 self.stack.get(id)
227 }
228
229 pub fn queued_count(&self) -> usize {
230 self.stack.queued_count()
231 }
232
233 pub fn stack_opacity(&self) -> f32 {
234 let now = Instant::now();
235 self.stack
236 .visible()
237 .iter()
238 .map(|toast| toast.opacity(now))
239 .fold(0., f32::max)
240 }
241
242 fn animated(&self, duration: Duration) -> Duration {
243 if self.animations {
244 duration
245 } else {
246 Duration::ZERO
247 }
248 }
249
250 pub fn directory<'a>(&self, cx: &'a App) -> &'a Directory {
251 &self.app.read(cx).directory
252 }
253
254 pub fn reply_text(&self, id: u64) -> Option<String> {
255 self.stack.get(id).map(|toast| toast.reply_text.clone())
256 }
257
258 pub fn intercept_close(&self, _cx: &App) -> bool {
259 match (self.settings.close_to_tray, &self.tray, self.main_native) {
260 (true, Some(_), Some(native)) => {
261 platform::hide_window(native);
262 true
263 }
264 _ => false,
265 }
266 }
267
268 pub fn update_settings(&mut self, cx: &mut Context<Self>, change: impl FnOnce(&mut Settings)) {
269 let previous = self.settings.sounds.clone();
270 change(&mut self.settings);
271 settings::save(&self.app.read(cx).store, &self.settings);
272 self.sync_tray();
273 if self.settings.sounds != previous {
274 let updated = self.settings.sounds.clone();
275 self.app
276 .update(cx, |state, cx| state.save_sound_settings(previous, updated, cx));
277 self.prefetch_sounds(cx);
278 }
279 cx.notify();
280 }
281
282 fn on_account_sounds(&mut self, cx: &mut Context<Self>) {
283 let Some(account) = self.app.read(cx).account_sounds.clone() else {
284 return;
285 };
286 if account == self.settings.sounds {
287 return;
288 }
289 self.settings.sounds = account;
290 settings::save(&self.app.read(cx).store, &self.settings);
291 self.sync_tray();
292 if !self.demo_mode {
293 self.prefetch_sounds(cx);
294 }
295 cx.notify();
296 }
297
298 fn prefetch_sounds(&self, cx: &App) {
299 let sounds = &self.settings.sounds;
300 let chosen = [
301 sounds.notification_sound_type.file_name(),
302 sounds.urgent_sound_type.file_name(),
303 sounds.ringtones.regular.file_name(),
304 Ringtone::Beep.file_name(),
305 ];
306 let call_tones = CallTone::ALL.map(CallTone::file_name);
307 sound_cache::prefetch(&chosen, cx);
308 sound_cache::prefetch(&call_tones, cx);
309 }
310
311 pub fn preview_sound(&mut self, file_name: &'static str, cx: &mut Context<Self>) {
312 self.preview = Some(sound_cache::start(file_name, false, cx));
313 }
314
315 fn play_notification_sound(&self, cx: &App) {
316 let file_name = self.settings.sounds.notification_sound_type.file_name();
317 sound_cache::play_or(file_name, platform::play_sound, cx);
318 }
319
320 fn on_app_event(&mut self, event: &AppEvent, cx: &mut Context<Self>) {
321 match event {
322 AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),
323 AppEvent::Selection => self.on_selection(cx),
324 AppEvent::Sidebar => self.refresh_badge(cx),
325 AppEvent::Ring => self.on_rings_changed(cx),
326 AppEvent::MeetingReminder => self.on_meeting_reminder(cx),
327 AppEvent::MeetingChime => self.on_meeting_chime(cx),
328 AppEvent::CallTone(tone) => self.on_call_tone(*tone, cx),
329 AppEvent::Call => self.sync_call_sounds(cx),
330 AppEvent::SoundSettings => self.on_account_sounds(cx),
331 _ => {}
332 }
333 }
334
335 fn on_selection(&mut self, cx: &mut Context<Self>) {
336 let selected = self
337 .app
338 .read(cx)
339 .selection
340 .as_ref()
341 .map(|selection| selection.conversation_id().to_owned());
342 if let Some(conversation_id) = selected {
343 self.unread_mentions.remove(&conversation_id);
344 self.stack.remove_conversation(&conversation_id);
345 }
346 self.refresh_badge(cx);
347 }
348
349 fn on_messages(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
350 let state = self.app.read(cx);
351 let my_user_id = state.directory.me.as_ref().map(|me| me.user_id.clone());
352 let found = self.tracker.collect(
353 &state.store,
354 &state.sidebar,
355 my_user_id.as_deref(),
356 &state.late_arrivals,
357 conversation_id,
358 );
359 for incoming in found {
360 self.handle_incoming(incoming, cx);
361 }
362 self.refresh_badge(cx);
363 }
364
365 fn environment(&self, conversation_id: &str, cx: &mut Context<Self>) -> Environment {
366 let state = self.app.read(cx);
367 let selected = state
368 .selection
369 .as_ref()
370 .is_some_and(|selection| selection.conversation_id() == conversation_id);
371 let own_do_not_disturb = own_do_not_disturb(state);
372 let own_busy = own_presence(state) == PresenceKind::Busy;
373 let server_in_call = match (state.engine.as_ref(), state.directory.me.as_ref()) {
374 (Some(engine), Some(me)) => data::in_call(engine, &me.user_id),
375 _ => false,
376 };
377 let in_call = in_call(server_in_call, state.call.as_ref().map(|call| &call.model));
378 Environment {
379 chat_in_foreground: selected && self.main_window_active(cx),
380 system_quiet: platform::system_quiet(),
381 own_do_not_disturb,
382 own_busy,
383 in_call,
384 }
385 }
386
387 fn main_window_active(&self, cx: &mut Context<Self>) -> bool {
388 self.main_window
389 .update(cx, |_, window, _| window.is_window_active())
390 .unwrap_or(false)
391 }
392
393 pub fn handle_incoming(&mut self, incoming: Incoming, cx: &mut Context<Self>) {
394 let bubble_text = match &incoming.preview {
395 Preview::Text(text) => text.replace('\n', " "),
396 Preview::Image => "Sent a picture".to_owned(),
397 };
398 self.app.update(cx, |state, cx| {
399 state.note_call_chat_message(
400 &incoming.conversation_id,
401 &incoming.message_id,
402 incoming.sender_id.clone(),
403 &incoming.sender_name,
404 &bubble_text,
405 cx,
406 )
407 });
408 let environment = self.environment(&incoming.conversation_id, cx);
409 if !environment.chat_in_foreground && incoming.mentions_me {
410 self.unread_mentions
411 .insert(incoming.conversation_id.clone());
412 }
413 let decision = decide(&self.settings, &incoming, environment);
414 self.present(&incoming, decision, cx);
415 if should_flash(&self.settings, decision.toast, self.main_window_active(cx))
416 && let Some(native) = self.main_native
417 {
418 platform::flash(native);
419 }
420 }
421
422 fn present(&mut self, incoming: &Incoming, decision: Decision, cx: &mut Context<Self>) {
423 if !decision.toast {
424 return;
425 }
426 let now = Instant::now();
427 let outcome = self.stack.push(incoming, now);
428 if let Some(model) = self.stack.get_mut(outcome.id) {
429 model.time = chrono::Local::now().format("%H:%M").to_string();
430 }
431 let throttle_allows = self.throttle.allow(&incoming.conversation_id, now);
432 if decision.sound && outcome.plays_sound(throttle_allows) && !self.app.read(cx).mode.demo {
433 self.play_notification_sound(cx);
434 }
435 if let Some(user_id) = incoming.sender_id.clone() {
436 self.app
437 .update(cx, |state, cx| state.request_avatars(vec![user_id], cx));
438 }
439 self.sync_windows(cx);
440 }
441
442 pub fn present_agent_run(&mut self, run: &AgentRun, cx: &mut Context<Self>) {
443 let failed = matches!(run.state, RunState::Failed { .. });
444 let verb = if failed { "failed" } else { "finished" };
445 let body = if failed {
446 run.current_step.clone()
447 } else {
448 first_lines(&run.final_text, AGENT_BODY_LINES)
449 };
450 let toast = AgentToast {
451 run_id: run.id,
452 session_id: run.session_id.clone(),
453 header: format!(
454 "{} - {} - {}",
455 run.action_label,
456 run.agent_name,
457 run.elapsed_text()
458 ),
459 title: format!(
460 "{} {verb}: {} for {}",
461 run.agent_name, run.action_label, run.sender_name
462 ),
463 body: if body.is_empty() {
464 "Done".to_owned()
465 } else {
466 body
467 },
468 failed,
469 };
470 let now = Instant::now();
471 let id = self
472 .stack
473 .push_agent(toast, &run.conversation_id, &run.message_id, now);
474 if let Some(model) = self.stack.get_mut(id) {
475 model.time = chrono::Local::now().format("%H:%M").to_string();
476 }
477 let quiet = self.settings.do_not_disturb || self.app.read(cx).mode.demo;
478 if self.settings.sounds.notification_sound && !quiet {
479 self.play_notification_sound(cx);
480 }
481 self.sync_windows(cx);
482 }
483
484 pub fn agent_toast_follow_up(&mut self, id: u64, cx: &mut Context<Self>) {
485 let Some(agent) = self.stack.get(id).and_then(|toast| toast.agent.clone()) else {
486 return;
487 };
488 self.drop_toast(id, cx);
489 if agent.failed {
490 crate::agents::retry_run(agent.run_id, cx);
491 } else {
492 crate::agents::open_session(&agent.session_id, cx);
493 }
494 }
495
496 fn visible_ids(&self) -> Vec<u64> {
497 self.stack.visible().iter().map(|toast| toast.id).collect()
498 }
499
500 fn work_area(&self, cx: &App) -> WorkArea {
501 if let Some(area) = self.main_native.and_then(platform::work_area) {
502 return area;
503 }
504 let bounds = cx
505 .primary_display()
506 .map(|display| display.bounds())
507 .unwrap_or_else(|| Bounds::new(point(px(0.), px(0.)), size(px(1280.), px(720.))));
508 WorkArea {
509 left: f32::from(bounds.origin.x) as i32,
510 top: f32::from(bounds.origin.y) as i32,
511 right: f32::from(bounds.origin.x + bounds.size.width) as i32,
512 bottom: f32::from(bounds.origin.y + bounds.size.height) as i32,
513 scale: 1.,
514 }
515 }
516
517 fn call_toasts(&self, cx: &App) -> Vec<(CallToast, f32)> {
518 let state = self.app.read(cx);
519 let in_call = state.call.is_some();
520 let rings = state
521 .rings
522 .ringing()
523 .map(|entry| (CallToast::Ring(entry.ring.ring_id), ring_height(in_call)));
524 let meetings = state
525 .meeting_toasts
526 .entries()
527 .iter()
528 .map(|toast| (CallToast::Meeting(toast.id), MEETING_HEIGHT));
529 rings.chain(meetings).collect()
530 }
531
532 fn sync_windows(&mut self, cx: &mut Context<Self>) {
533 let visible = self.visible_ids();
534 let stale: Vec<u64> = self
535 .windows
536 .keys()
537 .filter(|id| !visible.contains(id))
538 .copied()
539 .collect();
540 for id in stale {
541 self.close_window(id, cx);
542 }
543 let call_toasts = self.call_toasts(cx);
544 let stale_call_toasts: Vec<CallToast> = self
545 .call_windows
546 .keys()
547 .filter(|key| !call_toasts.iter().any(|(toast, _)| toast == *key))
548 .copied()
549 .collect();
550 for key in stale_call_toasts {
551 self.close_call_window(key, cx);
552 }
553 let area = self.work_area(cx);
554 let mut heights: Vec<f32> = self
555 .stack
556 .visible()
557 .iter()
558 .map(|toast| {
559 let lines = match &toast.agent {
560 Some(agent) => wrapped_lines(&agent.body, layout::AGENT_BODY_WIDTH, cx),
561 None => preview_lines(&describe(toast, self.settings.preview).preview, cx),
562 };
563 layout::toast_height(toast, lines)
564 })
565 .collect();
566 heights.extend(call_toasts.iter().map(|(_, height)| *height));
567 let with_hide_all = visible.len() > 1 || self.stack.queued_count() > 0;
568 let slots = layout::stack_slots(area, self.settings.corner, &heights, with_hide_all);
569 for (id, slot) in visible.iter().zip(slots.toasts.iter()) {
570 self.place_toast(*id, *slot, area, cx);
571 }
572 for ((key, _), slot) in call_toasts
573 .iter()
574 .zip(slots.toasts.iter().skip(visible.len()))
575 {
576 self.place_call_toast(*key, *slot, area, cx);
577 }
578 self.sync_pill(slots.pill, area, cx);
579 }
580
581 fn place_call_toast(
582 &mut self,
583 key: CallToast,
584 slot: Slot,
585 area: WorkArea,
586 cx: &mut Context<Self>,
587 ) {
588 let Some(window) = self.call_windows.get(&key) else {
589 self.open_call_window(key, slot, area, cx);
590 return;
591 };
592 if let Some(native) = window.native {
593 let offset = self.slide_offset(window.opened, area);
594 window.place(native, slot, slot.x + offset, cx);
595 }
596 }
597
598 fn open_call_window(
599 &mut self,
600 key: CallToast,
601 slot: Slot,
602 area: WorkArea,
603 cx: &mut Context<Self>,
604 ) {
605 if !self.call_opening.insert(key) {
606 return;
607 }
608 open_popup(
609 popup_options(slot, area),
610 cx,
611 move |center, _, cx| match key {
612 CallToast::Ring(ring_id) => {
613 AnyView::from(cx.new(|cx| RingView::new(center, ring_id, cx)))
614 }
615 CallToast::Meeting(toast_id) => {
616 AnyView::from(cx.new(|cx| MeetingToastView::new(center, toast_id, cx)))
617 }
618 },
619 move |this, window| {
620 this.call_opening.remove(&key);
621 if let Some(window) = window {
622 this.call_windows.insert(key, window);
623 }
624 },
625 );
626 }
627
628 fn close_call_window(&mut self, key: CallToast, cx: &mut Context<Self>) {
629 let closed = self.call_windows.get(&key).is_some_and(|window| {
630 window
631 .handle
632 .update(cx, |_, window, _| window.remove_window())
633 .is_ok()
634 });
635 if closed {
636 self.call_windows.remove(&key);
637 }
638 }
639
640 fn on_meeting_reminder(&mut self, cx: &mut Context<Self>) {
641 if !self.app.read(cx).meeting_toasts.is_empty()
642 && !self.main_window_active(cx)
643 && let Some(native) = self.main_native
644 {
645 platform::flash(native);
646 }
647 self.sync_windows(cx);
648 cx.notify();
649 }
650
651 fn on_meeting_chime(&mut self, cx: &mut Context<Self>) {
652 let busy = self.environment("", cx).busy();
653 if meeting_start_sound(&self.settings, busy) && !self.reminders_quiet(cx) && !self.demo_mode
654 {
655 sound_cache::play(CallTone::MeetingReminder.file_name(), cx);
656 }
657 }
658
659 fn on_call_tone(&mut self, tone: CallTone, cx: &mut Context<Self>) {
660 if !self.demo_mode {
661 sound_cache::play(tone.file_name(), cx);
662 }
663 }
664
665 pub fn join_meeting_toast(&mut self, id: u64, cx: &mut Context<Self>) {
666 self.raise_main_window(cx);
667 self.app
668 .update(cx, |state, cx| state.join_meeting_toast(id, cx));
669 }
670
671 fn reminders_quiet(&self, cx: &App) -> bool {
672 self.settings.do_not_disturb
673 || platform::system_quiet()
674 || own_do_not_disturb(self.app.read(cx))
675 }
676
677 fn on_rings_changed(&mut self, cx: &mut Context<Self>) {
678 let ringing = self.app.read(cx).rings.is_ringing();
679 if ringing
680 && !self.main_window_active(cx)
681 && let Some(native) = self.main_native
682 {
683 platform::flash(native);
684 }
685 self.sync_windows(cx);
686 self.sync_ring_tone(ringing, cx);
687 cx.notify();
688 }
689
690 fn sync_ring_tone(&mut self, ringing: bool, cx: &mut Context<Self>) {
691 if !ringing || self.demo_mode {
692 self.ring_tone = None;
693 return;
694 }
695 if self.ring_tone.is_some() {
696 return;
697 }
698 let environment = self.environment("", cx);
699 let native_call = self.app.read(cx).call.is_some();
700 if let Some(ringtone) = ringtone_for(&self.settings, native_call, environment.busy()) {
701 self.ring_tone = Some(sound_cache::start(ringtone.file_name(), true, cx));
702 }
703 }
704
705 fn sync_call_sounds(&mut self, cx: &Context<Self>) {
706 let model = self.app.read(cx).call.as_ref().map(|call| &call.model);
707 let ringback = should_ringback(model) && !self.demo_mode;
708 let reconnecting =
709 model.is_some_and(|model| model.is_reconnecting() && !model.lobby) && !self.demo_mode;
710 sync_loop(&mut self.ringback, ringback, CallTone::OutgoingRinging, cx);
711 sync_loop(&mut self.reconnecting, reconnecting, CallTone::Reconnecting, cx);
712 }
713
714 fn slide_offset(&self, opened: Instant, area: WorkArea) -> i32 {
715 if !self.animations {
716 return 0;
717 }
718 let progress = (opened.elapsed().as_secs_f32() / SLIDE_DURATION.as_secs_f32()).min(1.);
719 let eased = 1. - (1. - progress).powi(3);
720 let distance = ((1. - eased) * SLIDE_DISTANCE * area.scale) as i32;
721 if self.settings.corner.is_right() {
722 distance
723 } else {
724 -distance
725 }
726 }
727
728 fn place_toast(&mut self, id: u64, slot: Slot, area: WorkArea, cx: &mut Context<Self>) {
729 if !self.windows.contains_key(&id) {
730 self.open_toast_window(id, slot, area, cx);
731 return;
732 }
733 let offset = self
734 .windows
735 .get(&id)
736 .map(|window| self.slide_offset(window.opened, area))
737 .unwrap_or(0);
738 if let Some(window) = self.windows.get(&id)
739 && let Some(native) = window.native
740 {
741 window.place(native, slot, slot.x + offset, cx);
742 }
743 }
744
745 fn open_toast_window(&mut self, id: u64, slot: Slot, area: WorkArea, cx: &mut Context<Self>) {
746 if !self.opening.insert(id) {
747 return;
748 }
749 open_popup(
750 popup_options(slot, area),
751 cx,
752 move |center, window, cx| cx.new(|cx| ToastView::new(center, id, window, cx)),
753 move |this, window| {
754 this.opening.remove(&id);
755 if let Some(window) = window {
756 this.windows.insert(id, window);
757 }
758 },
759 );
760 }
761
762 fn sync_pill(&mut self, slot: Option<Slot>, area: WorkArea, cx: &mut Context<Self>) {
763 let Some(slot) = slot else {
764 if let Some(pill) = self.pill.take() {
765 pill.handle
766 .update(cx, |_, window, _| window.remove_window())
767 .ok();
768 }
769 return;
770 };
771 if self.pill.is_none() && !self.pill_opening {
772 self.pill_opening = true;
773 open_popup(
774 popup_options(slot, area),
775 cx,
776 |center, _, cx| cx.new(|cx| PillView::new(center, cx)),
777 |this, window| {
778 this.pill_opening = false;
779 this.pill = window;
780 },
781 );
782 }
783 if let Some(pill) = self.pill.as_ref()
784 && let Some(native) = pill.native
785 {
786 pill.place(native, slot, slot.x, cx);
787 }
788 }
789
790 fn close_window(&mut self, id: u64, cx: &mut Context<Self>) {
791 let closed = self.windows.get(&id).is_some_and(|window| {
792 window
793 .handle
794 .update(cx, |_, window, _| window.remove_window())
795 .is_ok()
796 });
797 if closed {
798 self.windows.remove(&id);
799 }
800 }
801
802 fn drop_toast(&mut self, id: u64, cx: &mut Context<Self>) {
803 let fast = self.animated(FAST_FADE);
804 self.stack.dismiss(id, Instant::now(), fast);
805 cx.notify();
806 }
807
808 pub fn hide_all(&mut self, cx: &mut Context<Self>) {
809 for id in self.stack.ids() {
810 self.drop_toast(id, cx);
811 }
812 }
813
814 fn sync_hover_hold(&mut self, now: Instant) {
815 let any_hovered = self.stack.any_hovered();
816 if !any_hovered && !self.hover_hold {
817 return;
818 }
819 if any_hovered {
820 let fast = self.animated(FAST_FADE);
821 self.stack.restore(now, fast);
822 }
823 for id in self.stack.ids() {
824 if let Some(toast) = self.stack.get_mut(id)
825 && !toast.queued
826 {
827 if any_hovered {
828 toast.timer.pause(now);
829 } else if !toast.holds_open() {
830 toast.timer.resume(now);
831 }
832 }
833 }
834 self.hover_hold = any_hovered;
835 }
836
837 fn is_dismissed(&self, id: u64) -> bool {
838 self.stack.get(id).is_none_or(|toast| toast.dismissed)
839 }
840
841 fn tick(&mut self, cx: &mut Context<Self>) {
842 let now = Instant::now();
843 let (fade_in, slow) = (self.animated(FADE_IN), self.animated(SLOW_FADE));
844 for id in self.stack.expired(now) {
845 self.stack.fade_out(id, now, slow);
846 }
847 for id in self.stack.gone(now) {
848 self.stack.remove(id);
849 }
850 self.stack.promote(now, fade_in);
851 self.sync_hover_hold(now);
852 if !self.app.read(cx).rings.is_empty() {
853 self.app.update(cx, |state, cx| state.tick_rings(cx));
854 }
855 if self
856 .app
857 .read(cx)
858 .meeting_toasts
859 .is_due_for_check(Utc::now())
860 {
861 let show = !self.reminders_quiet(cx);
862 self.app
863 .update(cx, |state, cx| state.tick_meeting_reminders(show, cx));
864 }
865 if !self.stack.is_empty()
866 || !self.windows.is_empty()
867 || self.pill.is_some()
868 || !self.call_windows.is_empty()
869 {
870 self.sync_windows(cx);
871 cx.notify();
872 }
873 self.poll_tray(cx);
874 if single_instance::take_activation() {
875 self.raise_main_window(cx);
876 }
877 }
878
879 fn poll_tray(&mut self, cx: &mut Context<Self>) {
880 let commands = self.tray.as_ref().map(Tray::poll).unwrap_or_default();
881 for command in commands {
882 match command {
883 TrayCommand::Toggle => self.toggle_main_window(cx),
884 TrayCommand::Open => self.raise_main_window(cx),
885 TrayCommand::ToggleSound => self.update_settings(cx, |settings| {
886 settings.sounds.notification_sound = !settings.sounds.notification_sound
887 }),
888 TrayCommand::ToggleDoNotDisturb => self.update_settings(cx, |settings| {
889 settings.do_not_disturb = !settings.do_not_disturb
890 }),
891 TrayCommand::Settings => {
892 self.raise_main_window(cx);
893 self.app.update(cx, |state, cx| {
894 state.open_settings(SettingsSection::General, cx)
895 });
896 }
897 TrayCommand::Quit => cx.quit(),
898 }
899 }
900 }
901
902 fn toggle_main_window(&mut self, cx: &mut Context<Self>) {
903 if self.main_window_active(cx) {
904 if let Some(native) = self.main_native {
905 platform::hide_window(native);
906 }
907 } else {
908 self.raise_main_window(cx);
909 }
910 }
911
912 fn raise_main_window(&mut self, cx: &mut Context<Self>) {
913 if let Some(native) = self.main_native {
914 platform::restore_and_raise(native);
915 }
916 self.main_window
917 .update(cx, |_, window, _| window.activate_window())
918 .ok();
919 }
920
921 fn apply_app_icon(&mut self, icon: AppIcon, cx: &mut Context<Self>) {
922 if icon == self.app_icon {
923 return;
924 }
925 self.app_icon = icon;
926 let mention = !self.unread_mentions.is_empty();
927 if let Some(tray) = &mut self.tray {
928 tray.set_app_icon(icon.png(), mention);
929 }
930 let _ = self.main_window.update(cx, |_, window, _| {
931 platform::set_window_icon(window, icon.png())
932 });
933 }
934
935 fn sync_tray(&self) {
936 if let Some(tray) = &self.tray {
937 tray.sync(
938 self.settings.sounds.notification_sound,
939 self.settings.do_not_disturb,
940 !self.unread_mentions.is_empty(),
941 );
942 }
943 }
944
945 fn refresh_badge(&mut self, cx: &mut Context<Self>) {
946 let state = self.app.read(cx);
947 let count = taskbar_badge_count(
948 &state.sidebar,
949 self.activity.read(cx).feed(),
950 state.directory.section_settings.adaptive_rail(),
951 );
952 let still_unread = unread_conversation_ids(&state.sidebar);
953 self.unread_mentions
954 .retain(|conversation_id| still_unread.contains(conversation_id.as_str()));
955 let badge = badge_for(count);
956 if badge == self.shown_badge {
957 return;
958 }
959 if let Some(native) = self.main_native {
960 platform::set_badge(native, badge.as_ref());
961 if badge.is_none() && self.shown_badge.is_some() {
962 platform::stop_flash(native);
963 }
964 }
965 self.shown_badge = badge;
966 self.sync_tray();
967 }
968
969 pub fn set_hover(&mut self, id: u64, hovered: bool, cx: &mut Context<Self>) {
970 let now = Instant::now();
971 let Some(toast) = self.stack.get_mut(id) else {
972 return;
973 };
974 if toast.hovered == hovered {
975 return;
976 }
977 toast.hovered = hovered;
978 self.sync_hover_hold(now);
979 cx.notify();
980 }
981
982 pub fn dismiss(&mut self, id: u64, cx: &mut Context<Self>) {
983 self.drop_toast(id, cx);
984 }
985
986 pub fn open_reply(&mut self, id: u64, cx: &mut Context<Self>) -> Option<String> {
987 let now = Instant::now();
988 let toast = self.stack.get_mut(id)?;
989 toast.reply = ReplyState::Open;
990 toast.timer.pause(now);
991 let draft = toast.reply_text.clone();
992 cx.notify();
993 Some(draft)
994 }
995
996 pub fn close_reply(&mut self, id: u64, cx: &mut Context<Self>) {
997 if let Some(toast) = self.stack.get_mut(id) {
998 toast.reply = ReplyState::Closed;
999 toast.reply_text.clear();
1000 toast.hovered = false;
1001 }
1002 cx.notify();
1003 }
1004
1005 pub fn submit_reply(&mut self, id: u64, text: String, cx: &mut Context<Self>) {
1006 let Some(toast) = self.stack.get_mut(id) else {
1007 return;
1008 };
1009 toast.reply_text = text.clone();
1010 let conversation_id = toast.conversation_id.clone();
1011 let message_id = toast.message_id.clone();
1012 let is_channel = matches!(toast.kind, ChatKind::Channel { .. });
1013 let state = self.app.read(cx);
1014 let (mode, engine) = (state.mode, state.engine.clone());
1015 let outcome: Result<(), ()> = if mode.demo {
1016 Ok(())
1017 } else if mode.read_only {
1018 Err(())
1019 } else if let Some(engine) = engine {
1020 let receiver = runtime::spawn(async move {
1021 if is_channel {
1022 engine.reply_to(&conversation_id, &message_id, &text).await
1023 } else {
1024 engine.send_message(&conversation_id, &text, None).await
1025 }
1026 .map(|_| ())
1027 });
1028 cx.spawn(async move |this, cx| {
1029 let sent = matches!(receiver.await, Ok(Ok(())));
1030 this.update(cx, |center, cx| center.finish_reply(id, sent, cx))
1031 .ok();
1032 })
1033 .detach();
1034 return;
1035 } else {
1036 Err(())
1037 };
1038 self.finish_reply(id, outcome.is_ok(), cx);
1039 }
1040
1041 fn finish_reply(&mut self, id: u64, sent: bool, cx: &mut Context<Self>) {
1042 let Some(toast) = self.stack.get_mut(id) else {
1043 return;
1044 };
1045 toast.reply = if sent {
1046 ReplyState::Sent
1047 } else {
1048 ReplyState::Failed
1049 };
1050 let conversation_id = toast.conversation_id.clone();
1051 cx.notify();
1052 if sent {
1053 cx.spawn(async move |this, cx| {
1054 cx.background_executor().timer(SENT_DURATION).await;
1055 this.update(cx, |center, cx| {
1056 center.mark_conversation_read(&conversation_id, cx);
1057 center.drop_toast(id, cx);
1058 })
1059 .ok();
1060 })
1061 .detach();
1062 }
1063 }
1064
1065 fn mark_conversation_read(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
1066 self.unread_mentions.remove(conversation_id);
1067 let conversation_id = conversation_id.to_owned();
1068 self.app
1069 .update(cx, |state, cx| state.mark_chat_read(&conversation_id, cx));
1070 self.refresh_badge(cx);
1071 }
1072
1073 pub fn mark_read(&mut self, id: u64, cx: &mut Context<Self>) {
1074 if self.is_dismissed(id) {
1075 return;
1076 }
1077 let Some(conversation_id) = self
1078 .stack
1079 .get(id)
1080 .map(|toast| toast.conversation_id.clone())
1081 else {
1082 return;
1083 };
1084 self.mark_conversation_read(&conversation_id, cx);
1085 self.drop_toast(id, cx);
1086 }
1087
1088 pub fn activate(&mut self, id: u64, cx: &mut Context<Self>) {
1089 if self.is_dismissed(id) {
1090 return;
1091 }
1092 let Some((conversation_id, message_id)) = self
1093 .stack
1094 .get(id)
1095 .map(|toast| (toast.conversation_id.clone(), toast.message_id.clone()))
1096 else {
1097 return;
1098 };
1099 self.drop_toast(id, cx);
1100 self.raise_main_window(cx);
1101 let selection = selection_for(&self.app.read(cx).sidebar, &conversation_id);
1102 if let Some(selection) = selection {
1103 self.app.update(cx, |state, cx| {
1104 state.jump_to_message(selection, message_id, cx)
1105 });
1106 }
1107 }
1108
1109 pub fn send_test_notification(&mut self, cx: &mut Context<Self>) {
1110 let incoming = Incoming {
1111 conversation_id: "test-notification".to_owned(),
1112 message_id: "test".to_owned(),
1113 kind: ChatKind::Direct,
1114 chat_title: "Mara Lindqvist".to_owned(),
1115 sender_id: None,
1116 sender_name: "Mara Lindqvist".to_owned(),
1117 preview: Preview::Text("This is a test notification.".to_owned()),
1118 mentions_me: false,
1119 muted: false,
1120 signals: Default::default(),
1121 created_at: Utc::now(),
1122 };
1123 let decision = Decision {
1124 toast: true,
1125 sound: self.settings.sounds.notification_sound,
1126 };
1127 self.throttle = SoundThrottle::default();
1128 self.present(&incoming, decision, cx);
1129 }
1130
1131 fn show_demo_toasts(&mut self, cx: &mut Context<Self>) {
1132 for incoming in demo_incoming() {
1133 let decision = Decision {
1134 toast: true,
1135 sound: false,
1136 };
1137 self.present(&incoming, decision, cx);
1138 }
1139 }
1140}
1141
1142/// Opens a window outside the current update: `open_window` draws right away, and every
1143/// notification view reads the center while rendering.
1144fn open_popup<V: Into<AnyView>>(
1145 options: WindowOptions,
1146 cx: &mut Context<NotificationCenter>,
1147 build: impl FnOnce(Entity<NotificationCenter>, &mut Window, &mut App) -> V + 'static,
1148 opened: impl FnOnce(&mut NotificationCenter, Option<OpenWindow>) + 'static,
1149) {
1150 let center = cx.entity();
1151 cx.defer(move |cx| {
1152 let view_center = center.clone();
1153 let Ok(handle) = cx.open_window(options, move |window, cx| {
1154 let view = build(view_center, window, cx);
1155 cx.new(|cx| base::Root::new(view, window, cx).bg(transparent_black()))
1156 }) else {
1157 center.update(cx, |this, _| opened(this, None));
1158 return;
1159 };
1160 let handle = AnyWindowHandle::from(handle);
1161 let native = handle
1162 .update(cx, |_, window, _| platform::native_handle(window))
1163 .ok()
1164 .flatten();
1165 if let Some(native) = native {
1166 platform::prepare_toast_window(native);
1167 }
1168 let window = OpenWindow {
1169 handle,
1170 native,
1171 opened: Instant::now(),
1172 };
1173 center.update(cx, |this, _| opened(this, Some(window)));
1174 });
1175}
1176
1177fn own_presence(state: &AppState) -> PresenceKind {
1178 state
1179 .directory
1180 .me
1181 .as_ref()
1182 .map_or(PresenceKind::Unknown, |me| {
1183 state.directory.presence_of(&me.user_id).kind()
1184 })
1185}
1186
1187fn own_do_not_disturb(state: &AppState) -> bool {
1188 own_presence(state) == PresenceKind::DoNotDisturb
1189}
1190
1191fn sync_loop(handle: &mut Option<SoundHandle>, audible: bool, tone: CallTone, cx: &App) {
1192 match (audible, handle.is_some()) {
1193 (true, false) => *handle = Some(sound_cache::start(tone.file_name(), true, cx)),
1194 (false, true) => *handle = None,
1195 _ => {}
1196 }
1197}
1198
1199fn demo_scene() -> Option<DemoScene> {
1200 DemoScene::from_name(&std::env::var(DEMO_CALL_ENV).ok()?)
1201}
1202
1203/// `TEAMS_DEMO_RING=<seconds>` rings a fake incoming call that long after the demo starts.
1204fn demo_ring_delay() -> Option<Duration> {
1205 let seconds: f32 = std::env::var(DEMO_RING_ENV).ok()?.trim().parse().ok()?;
1206 (seconds >= 0.).then(|| Duration::from_secs_f32(seconds))
1207}
1208
1209fn first_lines(text: &str, count: usize) -> String {
1210 text.lines()
1211 .map(str::trim)
1212 .filter(|line| !line.is_empty())
1213 .take(count)
1214 .collect::<Vec<_>>()
1215 .join("\n")
1216}
1217
1218fn preview_lines(text: &str, cx: &App) -> usize {
1219 wrapped_lines(text, layout::PREVIEW_WIDTH, cx)
1220}
1221
1222fn wrapped_lines(text: &str, width: f32, cx: &App) -> usize {
1223 let mut wrapper = cx
1224 .text_system()
1225 .line_wrapper(font(crate::theme::font_family()), px(layout::PREVIEW_SIZE));
1226 text.split('\n')
1227 .map(|line| {
1228 let fragments = [LineFragment::text(line)];
1229 wrapper
1230 .wrap_line(&fragments, px(width), IndentAdjustment::NoIndent)
1231 .count()
1232 + 1
1233 })
1234 .sum()
1235}
1236
1237fn popup_options(slot: Slot, area: WorkArea) -> WindowOptions {
1238 let scale = area.scale;
1239 let bounds = Bounds::new(
1240 point(px(slot.x as f32 / scale), px(slot.y as f32 / scale)),
1241 size(
1242 px(slot.width as f32 / scale),
1243 px(slot.height as f32 / scale),
1244 ),
1245 );
1246 WindowOptions {
1247 window_bounds: Some(WindowBounds::Windowed(bounds)),
1248 titlebar: None,
1249 focus: false,
1250 show: true,
1251 kind: WindowKind::PopUp,
1252 is_movable: false,
1253 is_resizable: false,
1254 is_minimizable: false,
1255 window_background: WindowBackgroundAppearance::Transparent,
1256 ..Default::default()
1257 }
1258}
1259
1260pub fn unread_conversation_ids(sidebar: &Sidebar) -> HashSet<&str> {
1261 let chats = sidebar.chats.iter().filter(|chat| chat.unread);
1262 let channels = sidebar
1263 .teams
1264 .iter()
1265 .flat_map(|team| team.channels.iter())
1266 .filter(|channel| channel.unread);
1267 chats
1268 .map(|chat| chat.id.as_str())
1269 .chain(channels.map(|channel| channel.id.as_str()))
1270 .collect()
1271}
1272
1273fn demo_incoming() -> Vec<Incoming> {
1274 let item = |conversation: &str,
1275 kind: ChatKind,
1276 title: &str,
1277 sender: &str,
1278 text: &str,
1279 mention: bool| Incoming {
1280 conversation_id: conversation.to_owned(),
1281 message_id: format!("{conversation}-message"),
1282 kind,
1283 chat_title: title.to_owned(),
1284 sender_id: None,
1285 sender_name: sender.to_owned(),
1286 preview: Preview::Text(text.to_owned()),
1287 mentions_me: mention,
1288 muted: false,
1289 signals: Default::default(),
1290 created_at: Utc::now(),
1291 };
1292 vec![
1293 item(
1294 "demo-toast-direct",
1295 ChatKind::Direct,
1296 "Tobias Klein",
1297 "Tobias Klein",
1298 "Sounds good, I will look at it tomorrow.",
1299 false,
1300 ),
1301 item(
1302 "demo-toast-group",
1303 ChatKind::Group { member_count: 5 },
1304 "Retro-Team",
1305 "Priya Nair",
1306 "Please add topics by 5 pm.",
1307 false,
1308 ),
1309 item(
1310 "demo-toast-mention",
1311 ChatKind::Channel {
1312 team: "Platform".to_owned(),
1313 channel: "Releases".to_owned(),
1314 },
1315 "Releases",
1316 "Mara Lindqvist",
1317 "@Jonas can you approve the merge? The pipeline is waiting.",
1318 true,
1319 ),
1320 item(
1321 "demo-toast-lea",
1322 ChatKind::Direct,
1323 "Lea Schneider",
1324 "Lea Schneider",
1325 "Lunch at 12?",
1326 false,
1327 ),
1328 item(
1329 "demo-toast-jonas",
1330 ChatKind::Direct,
1331 "Jonas Ortega",
1332 "Jonas Ortega",
1333 "Deploy window moved to Thursday 6 pm.",
1334 false,
1335 ),
1336 ]
1337}
1338
1339#[cfg(test)]
1340mod tests {
1341 use store::{ChannelRecord, ChatRecord, SidebarTeam, TeamRecord};
1342
1343 use std::collections::HashSet;
1344
1345 use gpui_kit::{WindowBackgroundAppearance, WindowKind};
1346
1347 use super::{Slot, WorkArea, popup_options, preview_lines, unread_conversation_ids};
1348 use store::Sidebar;
1349
1350 #[test]
1351 fn toast_windows_ask_for_a_transparent_background() {
1352 let slot = Slot {
1353 x: 0,
1354 y: 0,
1355 width: 360,
1356 height: 120,
1357 };
1358 let area = WorkArea {
1359 left: 0,
1360 top: 0,
1361 right: 1920,
1362 bottom: 1080,
1363 scale: 1.,
1364 };
1365 let options = popup_options(slot, area);
1366 assert_eq!(options.window_background, WindowBackgroundAppearance::Transparent);
1367 assert_eq!(options.kind, WindowKind::PopUp);
1368 }
1369
1370 fn sidebar() -> Sidebar {
1371 Sidebar {
1372 chats: vec![
1373 ChatRecord {
1374 id: "a".into(),
1375 unread: true,
1376 ..Default::default()
1377 },
1378 ChatRecord {
1379 id: "b".into(),
1380 unread: false,
1381 ..Default::default()
1382 },
1383 ],
1384 teams: vec![SidebarTeam {
1385 team: TeamRecord {
1386 id: "t".into(),
1387 name: "Team".into(),
1388 },
1389 channels: vec![ChannelRecord {
1390 id: "ch".into(),
1391 team_id: "t".into(),
1392 name: "General".into(),
1393 membership_type: None,
1394 last_message_at: None,
1395 unread: true,
1396 }],
1397 hidden: false,
1398 hidden_channel_ids: Vec::new(),
1399 notifications: Default::default(),
1400 }],
1401 }
1402 }
1403
1404 #[test]
1405 fn unread_conversation_ids_hold_chats_and_channels() {
1406 let sidebar = sidebar();
1407 assert_eq!(
1408 unread_conversation_ids(&sidebar),
1409 HashSet::from(["a", "ch"])
1410 );
1411 }
1412
1413 #[gpui_kit::test]
1414 fn preview_lines_follow_the_wrapped_text(cx: &mut gpui_kit::TestAppContext) {
1415 cx.update(|cx| {
1416 assert_eq!(preview_lines("ok", cx), 1);
1417 assert_eq!(preview_lines("a\nb", cx), 2);
1418 let long = "Cristina: ok, thanks for the info! I think not now ".repeat(3);
1419 assert!(preview_lines(&long, cx) >= 2);
1420 });
1421 }
1422}