BlueGit

ict rusty-teams

Files

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

center.rs

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