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