BlueGit

ict rusty-teams

Files

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

center.rs

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