BlueGit

ict rusty-teams

Files

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

center.rs

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