BlueGit

ict rusty-teams

Files

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

center.rs

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