BlueGit

ict rusty-teams

Files

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

center.rs

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