BlueGit

ict rusty-teams

Files

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

center.rs

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