BlueGit

ict rusty-teams

Files

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

center.rs

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