BlueGit

ict rusty-teams

Files

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

center.rs

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