BlueGit

ict rusty-teams

Files

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

center.rs

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