BlueGit

ict rusty-teams

Files

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

center.rs

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