BlueGit

ict rusty-teams

Files

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

center.rs

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