BlueGit

ict rusty-teams

Files

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

center.rs

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