BlueGit

ict rusty-teams

Files

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

center.rs

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