BlueGit

ict rusty-teams

Files

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

center.rs

center.rs 78.7 KiB Download Raw
1use std::cell::Cell;
2use std::collections::{HashMap, HashSet};
3use std::time::{Duration, Instant};
4
5use chrono::{DateTime, Local, Offset, Utc};
6use gpui_kit::*;
7use store::Sidebar;
8use teams_core::{ForcedAvailability, ForcedKind};
9
10use super::badge::{Badge, badge_for};
11#[cfg(target_os = "linux")]
12use super::desktop_payload::{
13 self, DesktopKey, DesktopPayload, MeetingLabels, MessageLabels, RingLabels, action,
14};
15use super::incoming::IncomingTracker;
16use super::layout::{self, MEETING_HEIGHT, Slot, ring_height};
17use super::meeting_view::MeetingToastView;
18use super::platform::{self, NativeHandle, Tray, TrayCommand, TrayPresence, WorkArea};
19#[cfg(target_os = "linux")]
20use super::platform::{
21 BusNotification, DesktopNotifications, NotificationEvent, NotificationImage,
22};
23use super::ring_view::RingView;
24use super::rules::{
25 ChatKind, Decision, Environment, Incoming, Preview, Settings, SoundThrottle, decide,
26 decide_proposal, in_call, meeting_start_sound, ringtone_for, should_flash, should_ringback,
27 shows_preview,
28};
29use super::settings;
30use super::sound_cache::{self, SoundHandle};
31use super::sounds::{CallTone, Ringtone};
32use super::stack::{
33 AgentToast, AgentToastKind, FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE,
34 ToastModel, ToastStack,
35};
36use super::taskbar::taskbar_badge_count;
37use super::text::describe;
38use super::toast::{PillView, ToastView};
39use super::urgent_repeat::UrgentRepeats;
40use crate::active_appearance::{self, ActiveAppearance};
41use crate::active_locale::ActiveLocale;
42use crate::activity::ActivityCenter;
43use crate::agent_api::{self, pending::PendingProposal};
44use crate::agents::{AgentRun, AgentRunsEvent, RunState};
45use crate::app_state::{AppEvent, AppState, selection_for};
46use crate::appearance::AppIcon;
47use crate::autostart::{self, StartupSettings};
48use crate::call::DemoScene;
49use crate::data::{self, Directory, PresenceKind};
50use crate::org_watch::OrgMessage;
51use crate::own_status;
52use crate::runtime;
53use crate::settings_section::SettingsSection;
54use crate::single_instance;
55
56const TICK: Duration = Duration::from_millis(33);
57const SLIDE_DURATION: Duration = Duration::from_millis(180);
58const SLIDE_DISTANCE: f32 = 48.;
59const DEMO_SPEC_DELAY: Duration = Duration::from_secs(3);
60const DEMO_RING_ENV: &str = "TEAMS_DEMO_RING";
61const DEMO_RING_KIND_ENV: &str = "TEAMS_DEMO_RING_KIND";
62const DEMO_CALL_ENV: &str = "TEAMS_DEMO_CALL";
63const DEMO_SCENE_DELAY: Duration = Duration::from_millis(1500);
64const AGENT_BODY_LINES: usize = 2;
65
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
67enum CallToast {
68 Ring(u64),
69 Meeting(u64),
70}
71
72struct OpenWindow {
73 handle: AnyWindowHandle,
74 native: Option<NativeHandle>,
75 opened: Instant,
76 placed: Cell<Option<(i32, i32, i32, i32)>>,
77}
78
79impl OpenWindow {
80 fn place(&self, native: NativeHandle, slot: Slot, x: i32, cx: &mut App) {
81 let rect = (x, slot.y, slot.width, slot.height);
82 match self.placed.replace(Some(rect)) {
83 Some(previous) if previous == rect => return,
84 Some(_) => platform::place_rect(native, x, slot.y, slot.width, slot.height),
85 None => platform::place(native, x, slot.y, slot.width, slot.height),
86 }
87 // WM_SIZE arrives while the app is borrowed, so GPUI drops its own resize report.
88 self.handle
89 .update(cx, |_, window, cx| window.bounds_changed(cx))
90 .ok();
91 }
92}
93
94pub struct NotificationCenter {
95 app: Entity<AppState>,
96 activity: Entity<ActivityCenter>,
97 main_window: AnyWindowHandle,
98 main_native: Option<NativeHandle>,
99 settings: Settings,
100 startup: StartupSettings,
101 stack: ToastStack,
102 tracker: IncomingTracker,
103 throttle: SoundThrottle,
104 urgent_repeats: UrgentRepeats,
105 windows: HashMap<u64, OpenWindow>,
106 opening: HashSet<u64>,
107 call_windows: HashMap<CallToast, OpenWindow>,
108 call_opening: HashSet<CallToast>,
109 ring_tone: Option<SoundHandle>,
110 ringback: Option<SoundHandle>,
111 reconnecting: Option<SoundHandle>,
112 preview: Option<SoundHandle>,
113 demo_mode: bool,
114 pill: Option<OpenWindow>,
115 pill_opening: bool,
116 hover_hold: bool,
117 unread_mentions: HashSet<String>,
118 tray: Option<Tray>,
119 #[cfg(target_os = "linux")]
120 desktop: Option<DesktopNotifications>,
121 #[cfg(target_os = "linux")]
122 desktop_close: Vec<String>,
123 #[cfg(target_os = "linux")]
124 desktop_published: HashSet<String>,
125 #[cfg(target_os = "linux")]
126 desktop_avatar_cache: HashMap<String, (u64, NotificationImage)>,
127 last_tray_presence: Option<TrayPresence>,
128 app_icon: AppIcon,
129 shown_badge: Option<Badge>,
130 shown_mention_dot: bool,
131 animations: bool,
132 _subscription: Subscription,
133 _activity_observation: Subscription,
134 _appearance_observation: Subscription,
135 _locale_observation: Subscription,
136 _agent_subscription: Option<Subscription>,
137 started_at: DateTime<Utc>,
138 known_proposals: HashSet<String>,
139 _proposal_observation: Option<Subscription>,
140}
141
142impl NotificationCenter {
143 pub fn new(
144 app: Entity<AppState>,
145 activity: Entity<ActivityCenter>,
146 window: &mut Window,
147 cx: &mut Context<Self>,
148 ) -> Self {
149 let mut settings = settings::load(&app.read(cx).store);
150 settings.account = app.read(cx).account_chat_settings().notifications;
151 let app_icon = active_appearance::current(cx).app_icon;
152 let initial_presence = tray_presence_from(&app.read(cx), false);
153 let tray = if app.read(cx).mode.demo || !settings.show_in_tray {
154 None
155 } else {
156 Tray::new(initial_presence.clone(), app_icon.png())
157 };
158 let last_tray_presence = tray.as_ref().map(|_| initial_presence);
159 platform::set_window_icon(window, app_icon.png());
160 let appearance_observation = cx.observe_global::<ActiveAppearance>(|this, cx| {
161 this.apply_app_icon(active_appearance::current(cx).app_icon, cx)
162 });
163 let locale_observation = cx.observe_global::<ActiveLocale>(|this, cx| {
164 // Locale changes the presence title; force a tray sync.
165 this.last_tray_presence = None;
166 this.relocalize_tray();
167 this.sync_tray(cx);
168 });
169 let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {
170 this.on_app_event(event, cx);
171 });
172 let activity_observation = cx.observe(&activity, |this, _, cx| this.refresh_badge(cx));
173 let agent_subscription = crate::agents::runs_handle(cx).map(|runs| {
174 cx.subscribe(&runs, |this, runs, event: &AgentRunsEvent, cx| {
175 if let AgentRunsEvent::Finished(run_id) = event
176 && let Some(run) = runs.read(cx).get(*run_id).cloned()
177 {
178 this.present_agent_run(&run, cx);
179 }
180 })
181 });
182 let proposal_observation =
183 agent_api::handle(cx).map(|api| cx.observe(&api, |this, _, cx| this.on_proposals(cx)));
184 let center = NotificationCenter {
185 started_at: Utc::now(),
186 known_proposals: HashSet::new(),
187 _proposal_observation: proposal_observation,
188 main_window: window.window_handle(),
189 main_native: platform::native_handle(window),
190 settings,
191 startup: StartupSettings::load(&app.read(cx).store, !app.read(cx).mode.demo),
192 stack: ToastStack::default(),
193 tracker: IncomingTracker::new(Utc::now()),
194 throttle: SoundThrottle::default(),
195 urgent_repeats: UrgentRepeats::default(),
196 windows: HashMap::new(),
197 opening: HashSet::new(),
198 call_windows: HashMap::new(),
199 call_opening: HashSet::new(),
200 ring_tone: None,
201 ringback: None,
202 reconnecting: None,
203 preview: None,
204 demo_mode: app.read(cx).mode.demo,
205 pill: None,
206 pill_opening: false,
207 hover_hold: false,
208 unread_mentions: HashSet::new(),
209 tray,
210 #[cfg(target_os = "linux")]
211 desktop: if app.read(cx).mode.demo {
212 None
213 } else {
214 DesktopNotifications::start()
215 },
216 #[cfg(target_os = "linux")]
217 desktop_close: Vec::new(),
218 #[cfg(target_os = "linux")]
219 desktop_published: HashSet::new(),
220 #[cfg(target_os = "linux")]
221 desktop_avatar_cache: HashMap::new(),
222 last_tray_presence,
223 app_icon,
224 shown_badge: None,
225 shown_mention_dot: false,
226 animations: platform::animations_enabled(),
227 app,
228 activity,
229 _subscription: subscription,
230 _activity_observation: activity_observation,
231 _appearance_observation: appearance_observation,
232 _locale_observation: locale_observation,
233 _agent_subscription: agent_subscription,
234 };
235 cx.spawn(async move |this, cx| {
236 loop {
237 cx.background_executor().timer(TICK).await;
238 if this.update(cx, |center, cx| center.tick(cx)).is_err() {
239 break;
240 }
241 }
242 })
243 .detach();
244 if !center.demo_mode {
245 center.prefetch_sounds(cx);
246 }
247 if center.app.read(cx).mode.demo {
248 if demo_scene().is_none() {
249 cx.spawn(async move |this, cx| {
250 cx.background_executor().timer(DEMO_SPEC_DELAY).await;
251 this.update(cx, |center, cx| center.show_demo_toasts(cx))
252 .ok();
253 })
254 .detach();
255 }
256 if let Some(delay) = demo_ring_delay() {
257 let app = center.app.clone();
258 let video =
259 std::env::var(DEMO_RING_KIND_ENV).is_ok_and(|kind| kind.trim() == "video");
260 cx.spawn(async move |_, cx| {
261 cx.background_executor().timer(delay).await;
262 app.update(cx, |state, cx| {
263 if video {
264 state.demo_incoming_video_ring(cx)
265 } else {
266 state.demo_incoming_ring(cx)
267 }
268 });
269 })
270 .detach();
271 }
272 if let Some(scene) = demo_scene() {
273 let app = center.app.clone();
274 cx.spawn(async move |_, cx| {
275 cx.background_executor().timer(DEMO_SCENE_DELAY).await;
276 app.update(cx, |state, cx| state.start_demo_scene(scene, cx));
277 })
278 .detach();
279 }
280 }
281 center
282 }
283
284 pub fn app(&self) -> &Entity<AppState> {
285 &self.app
286 }
287
288 pub fn settings(&self) -> &Settings {
289 &self.settings
290 }
291
292 pub fn model(&self, id: u64) -> Option<&ToastModel> {
293 self.stack.get(id)
294 }
295
296 pub fn queued_count(&self) -> usize {
297 self.stack.queued_count()
298 }
299
300 pub fn stack_opacity(&self) -> f32 {
301 let now = Instant::now();
302 self.stack
303 .visible()
304 .iter()
305 .map(|toast| toast.opacity(now))
306 .fold(0., f32::max)
307 }
308
309 fn animated(&self, duration: Duration) -> Duration {
310 if self.animations {
311 duration
312 } else {
313 Duration::ZERO
314 }
315 }
316
317 pub fn directory<'a>(&self, cx: &'a App) -> &'a Directory {
318 &self.app.read(cx).directory
319 }
320
321 pub fn reply_text(&self, id: u64) -> Option<String> {
322 self.stack.get(id).map(|toast| toast.reply_text.clone())
323 }
324
325 pub fn startup(&self) -> StartupSettings {
326 self.startup
327 }
328
329 pub fn set_auto_start(&mut self, enabled: bool, cx: &mut Context<Self>) {
330 if !self.demo_mode
331 && let Err(error) = autostart::set_enabled(crate::APP_NAME, enabled)
332 {
333 self.app.update(cx, |state, cx| {
334 state.raise_notice(
335 format!("Auto-start could not be changed: {error}"),
336 None,
337 cx,
338 )
339 });
340 return;
341 }
342 self.startup.auto_start = enabled;
343 cx.notify();
344 }
345
346 pub fn set_open_in_background(&mut self, enabled: bool, cx: &mut Context<Self>) {
347 self.startup.open_in_background = enabled;
348 self.startup.save_background(&self.app.read(cx).store);
349 cx.notify();
350 }
351
352 /// Points at a main window reopened from the tray.
353 pub fn attach_main_window(&mut self, window: &mut Window) {
354 self.main_window = window.window_handle();
355 self.main_native = platform::native_handle(window);
356 platform::set_window_icon(window, self.app_icon.png());
357 }
358
359 pub fn start_in_background(&self, window: &mut Window, cx: &mut App) {
360 match (&self.tray, self.main_native) {
361 (Some(_), Some(native)) => platform::hide_window(native),
362 #[cfg(any(target_os = "linux", target_os = "macos"))]
363 (Some(_), None) => crate::main_window::hide(cx),
364 _ => window.minimize_window(),
365 }
366 let _ = cx;
367 }
368
369 /// True when the close is handled here (window hidden natively). On Linux the
370 /// window closes for real and the app stays in the tray.
371 pub fn intercept_close(&self, cx: &mut App) -> bool {
372 match (self.settings.close_to_tray, &self.tray, self.main_native) {
373 (true, Some(_), Some(native)) => {
374 platform::hide_window(native);
375 true
376 }
377 #[cfg(any(target_os = "linux", target_os = "macos"))]
378 (true, Some(_), None) => {
379 crate::main_window::mark_hiding(cx);
380 false
381 }
382 _ => {
383 let _ = cx;
384 false
385 }
386 }
387 }
388
389 pub fn update_settings(&mut self, cx: &mut Context<Self>, change: impl FnOnce(&mut Settings)) {
390 let previous = self.settings.sounds.clone();
391 change(&mut self.settings);
392 settings::save(&self.app.read(cx).store, &self.settings);
393 self.show_in_tray(self.settings.show_in_tray, cx);
394 self.sync_tray(cx);
395 if self.settings.sounds != previous {
396 let updated = self.settings.sounds.clone();
397 self.app.update(cx, |state, cx| {
398 state.save_sound_settings(previous, updated, cx)
399 });
400 self.prefetch_sounds(cx);
401 }
402 cx.notify();
403 }
404
405 fn on_account_notifications(&mut self, cx: &mut Context<Self>) {
406 self.settings.account = self.app.read(cx).account_chat_settings().notifications;
407 cx.notify();
408 }
409
410 fn on_account_sounds(&mut self, cx: &mut Context<Self>) {
411 let Some(account) = self.app.read(cx).account_sounds.clone() else {
412 return;
413 };
414 if account == self.settings.sounds {
415 return;
416 }
417 self.settings.sounds = account;
418 settings::save(&self.app.read(cx).store, &self.settings);
419 self.sync_tray(cx);
420 if !self.demo_mode {
421 self.prefetch_sounds(cx);
422 }
423 cx.notify();
424 }
425
426 fn prefetch_sounds(&self, cx: &App) {
427 let sounds = &self.settings.sounds;
428 let chosen = [
429 sounds.notification_sound_type.file_name(),
430 sounds.urgent_sound_type.file_name(),
431 sounds.ringtones.regular.file_name(),
432 Ringtone::Beep.file_name(),
433 ];
434 let call_tones = CallTone::ALL.map(CallTone::file_name);
435 sound_cache::prefetch(&chosen, cx);
436 sound_cache::prefetch(&call_tones, cx);
437 }
438
439 pub fn preview_sound(&mut self, file_name: &'static str, cx: &mut Context<Self>) {
440 self.preview = Some(sound_cache::start(file_name, false, cx));
441 }
442
443 fn play_notification_sound(&self, cx: &App) {
444 let file_name = self.settings.sounds.notification_sound_type.file_name();
445 sound_cache::play_or(file_name, platform::play_sound, cx);
446 }
447
448 fn play_urgent_sound(&self, cx: &App) {
449 let file_name = self.settings.sounds.urgent_sound_type.file_name();
450 sound_cache::play_or(file_name, platform::play_sound, cx);
451 }
452
453 fn on_app_event(&mut self, event: &AppEvent, cx: &mut Context<Self>) {
454 match event {
455 AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),
456 AppEvent::Selection => self.on_selection(cx),
457 AppEvent::Sidebar => self.refresh_badge(cx),
458 AppEvent::Directory | AppEvent::Status => self.sync_tray(cx),
459 AppEvent::Ring => self.on_rings_changed(cx),
460 AppEvent::MeetingReminder => self.on_meeting_reminder(cx),
461 AppEvent::MeetingChime => self.on_meeting_chime(cx),
462 AppEvent::CallTone(tone) => self.on_call_tone(*tone, cx),
463 AppEvent::Call => self.sync_call_sounds(cx),
464 AppEvent::SoundSettings => self.on_account_sounds(cx),
465 AppEvent::ChatSettings => self.on_account_notifications(cx),
466 AppEvent::OrgMessage(message) => self.present_org_message(message, cx),
467 AppEvent::FollowedStatus { user_id, text } => {
468 self.present_status_change(user_id, text, cx)
469 }
470 _ => {}
471 }
472 }
473
474 fn on_selection(&mut self, cx: &mut Context<Self>) {
475 let selected = self
476 .app
477 .read(cx)
478 .selection
479 .as_ref()
480 .map(|selection| selection.conversation_id().to_owned());
481 if let Some(conversation_id) = selected {
482 self.unread_mentions.remove(&conversation_id);
483 self.stack.remove_conversation(&conversation_id);
484 self.urgent_repeats.stop_conversation(&conversation_id);
485 }
486 self.refresh_badge(cx);
487 }
488
489 fn on_messages(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
490 let state = self.app.read(cx);
491 let my_user_id = state.directory.me.as_ref().map(|me| me.user_id.clone());
492 let found = self.tracker.collect(
493 &state.store,
494 &state.sidebar,
495 my_user_id.as_deref(),
496 &state.late_arrivals,
497 conversation_id,
498 );
499 for incoming in found {
500 self.handle_incoming(incoming, cx);
501 }
502 self.refresh_badge(cx);
503 }
504
505 fn environment(&self, conversation_id: &str, cx: &mut Context<Self>) -> Environment {
506 let state = self.app.read(cx);
507 let selected = state
508 .selection
509 .as_ref()
510 .is_some_and(|selection| selection.conversation_id() == conversation_id);
511 let own_do_not_disturb = own_do_not_disturb(state);
512 let own_busy = own_presence(state) == PresenceKind::Busy;
513 let server_in_call = match (state.engine.as_ref(), state.directory.me.as_ref()) {
514 (Some(engine), Some(me)) => data::in_call(engine, &me.user_id),
515 _ => false,
516 };
517 let in_call = in_call(server_in_call, state.call.as_ref().map(|call| &call.model));
518 let paused = state.notifications_paused(chrono::Utc::now());
519 Environment {
520 chat_in_foreground: selected && self.main_window_active(cx),
521 system_quiet: platform::system_quiet(),
522 own_do_not_disturb,
523 paused,
524 own_busy,
525 in_call,
526 }
527 }
528
529 fn main_window_active(&self, cx: &mut Context<Self>) -> bool {
530 self.main_window
531 .update(cx, |_, window, _| window.is_window_active())
532 .unwrap_or(false)
533 }
534
535 pub fn handle_incoming(&mut self, mut incoming: Incoming, cx: &mut Context<Self>) {
536 incoming.chat.desktop = self
537 .app
538 .read(cx)
539 .chat_desktop_notifications(&incoming.conversation_id);
540 let bubble_text = match &incoming.preview {
541 Preview::Text(text) => text.replace('\n', " "),
542 Preview::Image => "Sent a picture".to_owned(),
543 };
544 self.app.update(cx, |state, cx| {
545 state.note_call_chat_message(
546 &incoming.conversation_id,
547 &incoming.message_id,
548 incoming.sender_id.clone(),
549 &incoming.sender_name,
550 &bubble_text,
551 cx,
552 )
553 });
554 let environment = self.environment(&incoming.conversation_id, cx);
555 if !environment.chat_in_foreground && incoming.mentions_me {
556 self.unread_mentions
557 .insert(incoming.conversation_id.clone());
558 }
559 let decision = decide(&self.settings, &incoming, environment);
560 self.present(&incoming, decision, cx);
561 if !environment.chat_in_foreground {
562 self.urgent_repeats.track(&incoming, Utc::now());
563 }
564 if should_flash(&self.settings, decision.toast, self.main_window_active(cx))
565 && let Some(native) = self.main_native
566 {
567 platform::flash(native);
568 }
569 }
570
571 fn present(&mut self, incoming: &Incoming, decision: Decision, cx: &mut Context<Self>) {
572 if !decision.toast {
573 return;
574 }
575 let now = Instant::now();
576 let outcome = self.stack.push(incoming, now);
577 if let Some(model) = self.stack.get_mut(outcome.id) {
578 model.time = chrono::Local::now()
579 .format(crate::format::clock_format())
580 .to_string();
581 }
582 let throttle_allows = self.throttle.allow(&incoming.conversation_id, now);
583 let audible =
584 outcome.plays_sound(throttle_allows) || (decision.urgent_sound && throttle_allows);
585 if decision.sound && audible && !self.app.read(cx).mode.demo {
586 if decision.urgent_sound {
587 self.play_urgent_sound(cx);
588 } else {
589 self.play_notification_sound(cx);
590 }
591 }
592 if let Some(user_id) = incoming.sender_id.clone() {
593 self.app
594 .update(cx, |state, cx| state.request_avatars(vec![user_id], cx));
595 }
596 self.sync_windows(cx);
597 }
598
599 fn own_feature_decision(&self, cx: &mut Context<Self>) -> Decision {
600 let environment = self.environment("", cx);
601 decide_proposal(
602 &self.settings,
603 teams_core::DesktopNotifications::MatchAllChats,
604 environment,
605 )
606 }
607
608 fn present_org_message(&mut self, message: &OrgMessage, cx: &mut Context<Self>) {
609 let decision = self.own_feature_decision(cx);
610 if !decision.toast {
611 return;
612 }
613 let now = Instant::now();
614 let id = self.stack.push_org_message(message, now);
615 if let Some(model) = self.stack.get_mut(id) {
616 model.time = chrono::Local::now()
617 .format(crate::format::clock_format())
618 .to_string();
619 }
620 if decision.sound && self.throttle.allow(&message.conversation_id, now) {
621 self.play_notification_sound(cx);
622 }
623 self.sync_windows(cx);
624 }
625
626 fn present_status_change(&mut self, user_id: &str, text: &str, cx: &mut Context<Self>) {
627 if !self.own_feature_decision(cx).toast {
628 return;
629 }
630 let (name, conversation_id) = {
631 let state = self.app.read(cx);
632 let name = state
633 .followed_presence
634 .iter()
635 .find(|person| person.user_id == user_id)
636 .map(|person| person.name.clone())
637 .unwrap_or_default();
638 (
639 name,
640 state.one_on_one_chat_with(user_id).unwrap_or_default(),
641 )
642 };
643 let id =
644 self.stack
645 .push_status_change(user_id, &name, text, &conversation_id, Instant::now());
646 if let Some(model) = self.stack.get_mut(id) {
647 model.time = chrono::Local::now()
648 .format(crate::format::clock_format())
649 .to_string();
650 }
651 let user_id = user_id.to_owned();
652 self.app
653 .update(cx, |state, cx| state.request_avatars(vec![user_id], cx));
654 self.sync_windows(cx);
655 }
656
657 pub fn present_agent_run(&mut self, run: &AgentRun, cx: &mut Context<Self>) {
658 let decision = self.own_feature_decision(cx);
659 if !decision.toast {
660 return;
661 }
662 let failed = matches!(run.state, RunState::Failed { .. });
663 let verb = if failed { "failed" } else { "finished" };
664 let body = if failed {
665 run.current_step.clone()
666 } else {
667 first_lines(&run.final_text, AGENT_BODY_LINES)
668 };
669 let toast = AgentToast {
670 kind: AgentToastKind::Run {
671 run_id: run.id,
672 session_id: run.session_id.clone(),
673 failed,
674 },
675 header: format!(
676 "{} - {} - {}",
677 run.action_label,
678 run.agent_name,
679 run.elapsed_text()
680 ),
681 title: format!(
682 "{} {verb}: {} for {}",
683 run.agent_name, run.action_label, run.sender_name
684 ),
685 body: if body.is_empty() {
686 "Done".to_owned()
687 } else {
688 body
689 },
690 };
691 let now = Instant::now();
692 let id = self
693 .stack
694 .push_agent(toast, &run.conversation_id, &run.message_id, now);
695 if let Some(model) = self.stack.get_mut(id) {
696 model.time = chrono::Local::now()
697 .format(crate::format::clock_format())
698 .to_string();
699 }
700 if decision.sound && !self.app.read(cx).mode.demo {
701 self.play_notification_sound(cx);
702 }
703 self.sync_windows(cx);
704 }
705
706 pub fn agent_toast_follow_up(&mut self, id: u64, cx: &mut Context<Self>) {
707 let Some(agent) = self.stack.get(id).and_then(|toast| toast.agent.clone()) else {
708 return;
709 };
710 self.drop_toast(id, cx);
711 match agent.kind {
712 AgentToastKind::Run {
713 run_id,
714 failed: true,
715 ..
716 } => crate::agents::retry_run(run_id, cx),
717 AgentToastKind::Run { session_id, .. } => crate::agents::open_session(&session_id, cx),
718 AgentToastKind::Proposal { .. } => {}
719 }
720 }
721
722 fn on_proposals(&mut self, cx: &mut Context<Self>) {
723 let pending = agent_api::pending_proposals(cx);
724 let unseen: HashSet<&str> = pending
725 .iter()
726 .filter(|proposal| !proposal.seen)
727 .map(|proposal| proposal.id.as_str())
728 .collect();
729 let resolved: Vec<u64> = self
730 .stack
731 .ids()
732 .into_iter()
733 .filter(|id| {
734 self.stack
735 .get(*id)
736 .and_then(|toast| toast.agent.as_ref()?.proposal_id())
737 .is_some_and(|proposal_id| !unseen.contains(proposal_id))
738 })
739 .collect();
740 for id in resolved {
741 self.drop_toast(id, cx);
742 }
743 let arrived: Vec<PendingProposal> = pending
744 .iter()
745 .filter(|proposal| {
746 !self.known_proposals.contains(&proposal.id)
747 && !proposal.seen
748 && proposal.created_at >= self.started_at
749 })
750 .cloned()
751 .collect();
752 self.known_proposals = pending.into_iter().map(|proposal| proposal.id).collect();
753 for proposal in arrived {
754 self.present_proposal(&proposal, cx);
755 }
756 self.refresh_badge(cx);
757 }
758
759 fn present_proposal(&mut self, proposal: &PendingProposal, cx: &mut Context<Self>) {
760 let state = self.app.read(cx);
761 let desktop = state.chat_desktop_notifications(&proposal.conversation_id);
762 let conversation =
763 agent_api::pending::conversation_label(&state.sidebar, &proposal.conversation_id);
764 let environment = self.environment(&proposal.conversation_id, cx);
765 let decision = decide_proposal(&self.settings, desktop, environment);
766 if !decision.toast {
767 return;
768 }
769 let toast = AgentToast {
770 kind: AgentToastKind::Proposal {
771 proposal_id: proposal.id.clone(),
772 },
773 header: conversation.unwrap_or_else(|| proposal.agent.to_owned()),
774 title: proposal.title(),
775 body: proposal.detail(),
776 };
777 let id = self.stack.push_agent(
778 toast,
779 &proposal.conversation_id,
780 proposal.jump_message_id(),
781 Instant::now(),
782 );
783 if let Some(model) = self.stack.get_mut(id) {
784 model.time = chrono::Local::now()
785 .format(crate::format::clock_format())
786 .to_string();
787 }
788 if decision.sound && !self.demo_mode {
789 self.play_notification_sound(cx);
790 }
791 if should_flash(&self.settings, decision.toast, self.main_window_active(cx))
792 && let Some(native) = self.main_native
793 {
794 platform::flash(native);
795 }
796 self.sync_windows(cx);
797 }
798
799 fn visible_ids(&self) -> Vec<u64> {
800 self.stack.visible().iter().map(|toast| toast.id).collect()
801 }
802
803 fn work_area(&self, cx: &App) -> WorkArea {
804 if let Some(area) = self.main_native.and_then(platform::work_area) {
805 return area;
806 }
807 let bounds = cx
808 .primary_display()
809 .map(|display| display.bounds())
810 .unwrap_or_else(|| Bounds::new(point(px(0.), px(0.)), size(px(1280.), px(720.))));
811 WorkArea {
812 left: f32::from(bounds.origin.x) as i32,
813 top: f32::from(bounds.origin.y) as i32,
814 right: f32::from(bounds.origin.x + bounds.size.width) as i32,
815 bottom: f32::from(bounds.origin.y + bounds.size.height) as i32,
816 scale: 1.,
817 }
818 }
819
820 fn call_toasts(&self, cx: &App) -> Vec<(CallToast, f32)> {
821 let state = self.app.read(cx);
822 let in_call = state.call.is_some();
823 let rings = state
824 .rings
825 .ringing()
826 .map(|entry| (CallToast::Ring(entry.ring.ring_id), ring_height(in_call)));
827 let meetings = state
828 .meeting_toasts
829 .entries()
830 .iter()
831 .map(|toast| (CallToast::Meeting(toast.id), MEETING_HEIGHT));
832 rings.chain(meetings).collect()
833 }
834}
835
836fn call_cards_while_desktop_connected(toasts: &[(CallToast, f32)]) -> Vec<(CallToast, f32)> {
837 toasts
838 .iter()
839 .copied()
840 .filter(|(key, _)| matches!(key, CallToast::Ring(_) | CallToast::Meeting(_)))
841 .collect()
842}
843
844impl NotificationCenter {
845 /// Ring and meeting cards stay on screen when a notification service is connected.
846 /// Chat toasts stay desktop notifications.
847 fn sync_ring_cards(&mut self, cx: &mut Context<Self>) {
848 let rings = call_cards_while_desktop_connected(&self.call_toasts(cx));
849 let stale: Vec<CallToast> = self
850 .call_windows
851 .keys()
852 .copied()
853 .filter(|key| !rings.iter().any(|(toast, _)| toast == key))
854 .collect();
855 for key in stale {
856 self.close_call_window(key, cx);
857 }
858 let area = self.work_area(cx);
859 let heights: Vec<f32> = rings.iter().map(|(_, height)| *height).collect();
860 let slots = layout::stack_slots(area, self.settings.corner, &heights, false);
861 for ((key, _), slot) in rings.iter().zip(slots.toasts.iter()) {
862 self.place_call_toast(*key, *slot, area, cx);
863 }
864 }
865
866 fn finish_ring_card(&mut self, ring_id: u64, cx: &mut Context<Self>) {
867 #[cfg(target_os = "linux")]
868 {
869 let still_ringing = self
870 .app
871 .read(cx)
872 .rings
873 .ringing()
874 .any(|entry| entry.ring.ring_id == ring_id);
875 if !still_ringing {
876 self.queue_desktop_close(DesktopKey::Ring(ring_id));
877 }
878 }
879 self.sync_windows(cx);
880 }
881
882 fn sync_windows(&mut self, cx: &mut Context<Self>) {
883 #[cfg(target_os = "linux")]
884 if self.desktop.is_some() {
885 self.sync_desktop(cx);
886 self.sync_ring_cards(cx);
887 return;
888 }
889 let visible = self.visible_ids();
890 let stale: Vec<u64> = self
891 .windows
892 .keys()
893 .filter(|id| !visible.contains(id))
894 .copied()
895 .collect();
896 for id in stale {
897 self.close_window(id, cx);
898 }
899 let call_toasts = self.call_toasts(cx);
900 let stale_call_toasts: Vec<CallToast> = self
901 .call_windows
902 .keys()
903 .filter(|key| !call_toasts.iter().any(|(toast, _)| toast == *key))
904 .copied()
905 .collect();
906 for key in stale_call_toasts {
907 self.close_call_window(key, cx);
908 }
909 let area = self.work_area(cx);
910 let mut heights: Vec<f32> = self
911 .stack
912 .visible()
913 .iter()
914 .map(|toast| {
915 let lines = match &toast.agent {
916 Some(agent) => wrapped_lines(&agent.body, layout::AGENT_BODY_WIDTH, cx),
917 None => {
918 preview_lines(&describe(toast, shows_preview(&self.settings)).preview, cx)
919 }
920 };
921 layout::toast_height(toast, lines)
922 })
923 .collect();
924 heights.extend(call_toasts.iter().map(|(_, height)| *height));
925 let with_hide_all = visible.len() > 1 || self.stack.queued_count() > 0;
926 let slots = layout::stack_slots(area, self.settings.corner, &heights, with_hide_all);
927 for (id, slot) in visible.iter().zip(slots.toasts.iter()) {
928 self.place_toast(*id, *slot, area, cx);
929 }
930 for ((key, _), slot) in call_toasts
931 .iter()
932 .zip(slots.toasts.iter().skip(visible.len()))
933 {
934 self.place_call_toast(*key, *slot, area, cx);
935 }
936 self.sync_pill(slots.pill, area, cx);
937 }
938
939 fn place_call_toast(
940 &mut self,
941 key: CallToast,
942 slot: Slot,
943 area: WorkArea,
944 cx: &mut Context<Self>,
945 ) {
946 let Some(window) = self.call_windows.get(&key) else {
947 self.open_call_window(key, slot, area, cx);
948 return;
949 };
950 if let Some(native) = window.native {
951 let offset = self.slide_offset(window.opened, area);
952 window.place(native, slot, slot.x + offset, cx);
953 }
954 }
955
956 fn open_call_window(
957 &mut self,
958 key: CallToast,
959 slot: Slot,
960 area: WorkArea,
961 cx: &mut Context<Self>,
962 ) {
963 if !self.call_opening.insert(key) {
964 return;
965 }
966 let options = ring_card_options(slot, area);
967 open_popup(
968 options,
969 cx,
970 move |center, _, cx| match key {
971 CallToast::Ring(ring_id) => {
972 AnyView::from(cx.new(|cx| RingView::new(center, ring_id, cx)))
973 }
974 CallToast::Meeting(toast_id) => {
975 AnyView::from(cx.new(|cx| MeetingToastView::new(center, toast_id, cx)))
976 }
977 },
978 move |this, window| {
979 this.call_opening.remove(&key);
980 if let Some(window) = window {
981 this.call_windows.insert(key, window);
982 }
983 },
984 );
985 }
986
987 fn close_call_window(&mut self, key: CallToast, cx: &mut Context<Self>) {
988 let closed = self.call_windows.get(&key).is_some_and(|window| {
989 window
990 .handle
991 .update(cx, |_, window, _| window.remove_window())
992 .is_ok()
993 || !window_is_open(window.handle.window_id(), cx)
994 });
995 if closed {
996 self.call_windows.remove(&key);
997 }
998 }
999
1000 fn on_meeting_reminder(&mut self, cx: &mut Context<Self>) {
1001 if !self.app.read(cx).meeting_toasts.is_empty()
1002 && !self.main_window_active(cx)
1003 && let Some(native) = self.main_native
1004 {
1005 platform::flash(native);
1006 }
1007 self.sync_windows(cx);
1008 cx.notify();
1009 }
1010
1011 fn on_meeting_chime(&mut self, cx: &mut Context<Self>) {
1012 let busy = self.environment("", cx).busy();
1013 if meeting_start_sound(&self.settings, busy) && !self.reminders_quiet(cx) && !self.demo_mode
1014 {
1015 sound_cache::play(CallTone::MeetingReminder.file_name(), cx);
1016 }
1017 }
1018
1019 fn on_call_tone(&mut self, tone: CallTone, cx: &mut Context<Self>) {
1020 if !self.demo_mode {
1021 sound_cache::play(tone.file_name(), cx);
1022 }
1023 }
1024
1025 pub fn join_meeting_toast(&mut self, id: u64, cx: &mut Context<Self>) {
1026 self.raise_main_window(cx);
1027 self.app
1028 .update(cx, |state, cx| state.join_meeting_toast(id, cx));
1029 }
1030
1031 fn reminders_quiet(&self, cx: &App) -> bool {
1032 platform::system_quiet() || own_do_not_disturb(self.app.read(cx))
1033 }
1034
1035 fn on_rings_changed(&mut self, cx: &mut Context<Self>) {
1036 let ringing = self.app.read(cx).rings.is_ringing();
1037 if ringing
1038 && !self.main_window_active(cx)
1039 && let Some(native) = self.main_native
1040 {
1041 platform::flash(native);
1042 }
1043 self.sync_windows(cx);
1044 self.sync_ring_tone(ringing, cx);
1045 cx.notify();
1046 }
1047
1048 fn sync_ring_tone(&mut self, ringing: bool, cx: &mut Context<Self>) {
1049 if !ringing || self.demo_mode {
1050 self.ring_tone = None;
1051 return;
1052 }
1053 if self.ring_tone.is_some() {
1054 return;
1055 }
1056 let environment = self.environment("", cx);
1057 let native_call = self.app.read(cx).call.is_some();
1058 if let Some(ringtone) = ringtone_for(&self.settings, native_call, environment.busy()) {
1059 self.ring_tone = Some(sound_cache::start(ringtone.file_name(), true, cx));
1060 }
1061 }
1062
1063 fn sync_call_sounds(&mut self, cx: &Context<Self>) {
1064 let model = self.app.read(cx).call.as_ref().map(|call| &call.model);
1065 let ringback = should_ringback(model) && !self.demo_mode;
1066 let reconnecting =
1067 model.is_some_and(|model| model.is_reconnecting() && !model.lobby) && !self.demo_mode;
1068 sync_loop(&mut self.ringback, ringback, CallTone::OutgoingRinging, cx);
1069 sync_loop(
1070 &mut self.reconnecting,
1071 reconnecting,
1072 CallTone::Reconnecting,
1073 cx,
1074 );
1075 }
1076
1077 fn slide_offset(&self, opened: Instant, area: WorkArea) -> i32 {
1078 if !self.animations {
1079 return 0;
1080 }
1081 let progress = (opened.elapsed().as_secs_f32() / SLIDE_DURATION.as_secs_f32()).min(1.);
1082 let eased = 1. - (1. - progress).powi(3);
1083 let distance = ((1. - eased) * SLIDE_DISTANCE * area.scale) as i32;
1084 if self.settings.corner.is_right() {
1085 distance
1086 } else {
1087 -distance
1088 }
1089 }
1090
1091 fn place_toast(&mut self, id: u64, slot: Slot, area: WorkArea, cx: &mut Context<Self>) {
1092 if !self.windows.contains_key(&id) {
1093 self.open_toast_window(id, slot, area, cx);
1094 return;
1095 }
1096 let offset = self
1097 .windows
1098 .get(&id)
1099 .map(|window| self.slide_offset(window.opened, area))
1100 .unwrap_or(0);
1101 if let Some(window) = self.windows.get(&id)
1102 && let Some(native) = window.native
1103 {
1104 window.place(native, slot, slot.x + offset, cx);
1105 }
1106 }
1107
1108 fn open_toast_window(&mut self, id: u64, slot: Slot, area: WorkArea, cx: &mut Context<Self>) {
1109 if !self.opening.insert(id) {
1110 return;
1111 }
1112 open_popup(
1113 popup_options(slot, area),
1114 cx,
1115 move |center, window, cx| cx.new(|cx| ToastView::new(center, id, window, cx)),
1116 move |this, window| {
1117 this.opening.remove(&id);
1118 if let Some(window) = window {
1119 this.windows.insert(id, window);
1120 }
1121 },
1122 );
1123 }
1124
1125 fn sync_pill(&mut self, slot: Option<Slot>, area: WorkArea, cx: &mut Context<Self>) {
1126 let Some(slot) = slot else {
1127 if let Some(pill) = self.pill.take() {
1128 pill.handle
1129 .update(cx, |_, window, _| window.remove_window())
1130 .ok();
1131 }
1132 return;
1133 };
1134 if self.pill.is_none() && !self.pill_opening {
1135 self.pill_opening = true;
1136 open_popup(
1137 popup_options(slot, area),
1138 cx,
1139 |center, _, cx| cx.new(|cx| PillView::new(center, cx)),
1140 |this, window| {
1141 this.pill_opening = false;
1142 this.pill = window;
1143 },
1144 );
1145 }
1146 if let Some(pill) = self.pill.as_ref()
1147 && let Some(native) = pill.native
1148 {
1149 pill.place(native, slot, slot.x, cx);
1150 }
1151 }
1152
1153 fn close_window(&mut self, id: u64, cx: &mut Context<Self>) {
1154 let closed = self.windows.get(&id).is_some_and(|window| {
1155 window
1156 .handle
1157 .update(cx, |_, window, _| window.remove_window())
1158 .is_ok()
1159 || !window_is_open(window.handle.window_id(), cx)
1160 });
1161 if closed {
1162 self.windows.remove(&id);
1163 }
1164 }
1165
1166 fn drop_toast(&mut self, id: u64, cx: &mut Context<Self>) {
1167 #[cfg(target_os = "linux")]
1168 self.queue_desktop_close(DesktopKey::Message(id));
1169 let fast = self.animated(FAST_FADE);
1170 self.stack.dismiss(id, Instant::now(), fast);
1171 cx.notify();
1172 }
1173
1174 pub fn hide_all(&mut self, cx: &mut Context<Self>) {
1175 for id in self.stack.ids() {
1176 self.drop_toast(id, cx);
1177 }
1178 }
1179
1180 fn sync_hover_hold(&mut self, now: Instant) {
1181 let any_hovered = self.stack.any_hovered();
1182 if !any_hovered && !self.hover_hold {
1183 return;
1184 }
1185 if any_hovered {
1186 let fast = self.animated(FAST_FADE);
1187 self.stack.restore(now, fast);
1188 }
1189 for id in self.stack.ids() {
1190 if let Some(toast) = self.stack.get_mut(id)
1191 && !toast.queued
1192 {
1193 if any_hovered {
1194 toast.timer.pause(now);
1195 } else if !toast.holds_open() {
1196 toast.timer.resume(now);
1197 }
1198 }
1199 }
1200 self.hover_hold = any_hovered;
1201 }
1202
1203 fn is_dismissed(&self, id: u64) -> bool {
1204 self.stack.get(id).is_none_or(|toast| toast.dismissed)
1205 }
1206
1207 fn tick(&mut self, cx: &mut Context<Self>) {
1208 let now = Instant::now();
1209 let (fade_in, slow) = (self.animated(FADE_IN), self.animated(SLOW_FADE));
1210 for id in self.stack.expired(now) {
1211 self.stack.fade_out(id, now, slow);
1212 }
1213 for id in self.stack.gone(now) {
1214 self.stack.remove(id);
1215 }
1216 self.stack.promote(now, fade_in);
1217 self.sync_hover_hold(now);
1218 if !self.urgent_repeats.is_empty() {
1219 self.repeat_urgent(cx);
1220 }
1221 if !self.app.read(cx).rings.is_empty() {
1222 self.app.update(cx, |state, cx| state.tick_rings(cx));
1223 }
1224 if self
1225 .app
1226 .read(cx)
1227 .meeting_toasts
1228 .is_due_for_check(Utc::now())
1229 {
1230 let show = !self.reminders_quiet(cx);
1231 self.app
1232 .update(cx, |state, cx| state.tick_meeting_reminders(show, cx));
1233 }
1234 let needs_sync = !self.stack.is_empty()
1235 || !self.windows.is_empty()
1236 || self.pill.is_some()
1237 || !self.call_windows.is_empty()
1238 || self.app.read(cx).rings.is_ringing()
1239 || !self.app.read(cx).meeting_toasts.is_empty();
1240 #[cfg(target_os = "linux")]
1241 let needs_sync =
1242 needs_sync || !self.desktop_close.is_empty() || !self.desktop_published.is_empty();
1243 #[cfg(target_os = "linux")]
1244 if self
1245 .desktop
1246 .as_ref()
1247 .is_some_and(DesktopNotifications::failed)
1248 {
1249 self.desktop = None;
1250 self.desktop_published.clear();
1251 }
1252 // Poll desktop actions before sync so dismiss/reply land in the same tick.
1253 #[cfg(target_os = "linux")]
1254 if self.desktop.is_some() {
1255 self.poll_desktop(cx);
1256 }
1257 if needs_sync {
1258 self.sync_windows(cx);
1259 cx.notify();
1260 }
1261 self.poll_tray(cx);
1262 if single_instance::take_activation() {
1263 self.raise_main_window(cx);
1264 }
1265 for command in single_instance::take_commands() {
1266 self.app
1267 .update(cx, |state, cx| state.run_remote_command(&command, cx));
1268 }
1269 }
1270
1271 fn repeat_urgent(&mut self, cx: &mut Context<Self>) {
1272 let sidebar = &self.app.read(cx).sidebar;
1273 self.urgent_repeats.stop_read(|conversation_id| {
1274 sidebar
1275 .chats
1276 .iter()
1277 .find(|chat| chat.id == conversation_id)
1278 .and_then(|chat| chat.last_read_at.filter(|_| !chat.unread))
1279 });
1280 for incoming in self.urgent_repeats.due(Utc::now()) {
1281 let environment = self.environment(&incoming.conversation_id, cx);
1282 if environment.chat_in_foreground {
1283 self.urgent_repeats
1284 .stop_conversation(&incoming.conversation_id);
1285 continue;
1286 }
1287 self.stack.remove_conversation(&incoming.conversation_id);
1288 let decision = decide(&self.settings, &incoming, environment);
1289 self.present(&incoming, decision, cx);
1290 if should_flash(&self.settings, decision.toast, self.main_window_active(cx))
1291 && let Some(native) = self.main_native
1292 {
1293 platform::flash(native);
1294 }
1295 }
1296 }
1297
1298 #[cfg(target_os = "linux")]
1299 fn queue_desktop_close(&mut self, key: DesktopKey) {
1300 self.desktop_close.push(key.replace_token());
1301 }
1302
1303 #[cfg(target_os = "linux")]
1304 fn message_labels() -> MessageLabels {
1305 MessageLabels {
1306 mark_read: crate::i18n::tr("notify.mark_read"),
1307 reply: crate::i18n::tr("notify.reply"),
1308 }
1309 }
1310
1311 #[cfg(target_os = "linux")]
1312 fn ring_labels() -> RingLabels {
1313 RingLabels {
1314 decline: crate::i18n::tr("notify.decline"),
1315 accept: crate::i18n::tr("notify.accept"),
1316 audio: crate::i18n::tr("notify.audio"),
1317 video: crate::i18n::tr("notify.video"),
1318 }
1319 }
1320
1321 #[cfg(target_os = "linux")]
1322 fn meeting_labels() -> MeetingLabels {
1323 MeetingLabels {
1324 join: crate::i18n::tr("notify.join"),
1325 snooze: crate::i18n::tr("notify.snooze"),
1326 }
1327 }
1328
1329 #[cfg(target_os = "linux")]
1330 fn to_bus(payload: DesktopPayload, image: Option<NotificationImage>) -> BusNotification {
1331 BusNotification {
1332 logical_key: payload.key.replace_token(),
1333 replace_key: payload.replace_key,
1334 summary: payload.summary,
1335 body: payload.body,
1336 actions: payload
1337 .actions
1338 .into_iter()
1339 .map(|action| (action.id.to_owned(), action.label))
1340 .collect(),
1341 timeout_ms: payload.timeout_ms,
1342 urgency: payload.urgency as u8,
1343 category: payload.category.to_owned(),
1344 image,
1345 }
1346 }
1347
1348 #[cfg(target_os = "linux")]
1349 fn avatar_notification_image(
1350 &mut self,
1351 state: &AppState,
1352 user_id: Option<&str>,
1353 ) -> Option<NotificationImage> {
1354 use crate::data::AvatarState;
1355 use image::imageops::FilterType;
1356 use std::collections::hash_map::DefaultHasher;
1357 use std::hash::{Hash, Hasher};
1358
1359 let user_id = user_id?;
1360 let AvatarState::Ready(photo) = state.directory.avatar(user_id)? else {
1361 return None;
1362 };
1363 let bytes = photo.source_bytes();
1364 let mut hasher = DefaultHasher::new();
1365 bytes.hash(&mut hasher);
1366 let fingerprint = hasher.finish();
1367 if let Some((cached_fp, image)) = self.desktop_avatar_cache.get(user_id)
1368 && *cached_fp == fingerprint
1369 {
1370 return Some(image.clone());
1371 }
1372 let decoded = image::load_from_memory(bytes).ok()?;
1373 let rgba = decoded
1374 .resize_exact(64, 64, FilterType::Lanczos3)
1375 .into_rgba8();
1376 let image = NotificationImage {
1377 width: rgba.width(),
1378 height: rgba.height(),
1379 rgba: rgba.into_raw(),
1380 };
1381 self.desktop_avatar_cache
1382 .insert(user_id.to_owned(), (fingerprint, image.clone()));
1383 Some(image)
1384 }
1385
1386 #[cfg(target_os = "linux")]
1387 fn sync_desktop(&mut self, cx: &mut Context<Self>) {
1388 if self.desktop.is_none() {
1389 return;
1390 }
1391 let preview_on = shows_preview(&self.settings);
1392 let message_labels = Self::message_labels();
1393 let ring_labels = Self::ring_labels();
1394 let meeting_labels = Self::meeting_labels();
1395 let mut visible = Vec::new();
1396 let mut visible_logical = HashSet::new();
1397 let mut used_avatars = HashSet::new();
1398 let message_toasts: Vec<_> = self.stack.visible().to_vec();
1399 let (ring_payloads, meeting_payloads) = {
1400 let state = self.app.read(cx);
1401 let rings: Vec<_> = state
1402 .rings
1403 .ringing()
1404 .map(|entry| {
1405 (
1406 desktop_payload::ring_payload(
1407 entry.ring.ring_id,
1408 entry.caller_name(),
1409 entry.subtitle(),
1410 entry.ring.video,
1411 &ring_labels,
1412 ),
1413 entry.caller_user_id(),
1414 )
1415 })
1416 .collect();
1417 let now = Utc::now();
1418 let offset = Local::now().offset().fix();
1419 let meetings: Vec<_> = state
1420 .meeting_toasts
1421 .entries()
1422 .iter()
1423 .map(|toast| {
1424 let body = crate::call::meeting_subtitle(toast, now, offset);
1425 desktop_payload::meeting_payload(toast, &body, &meeting_labels)
1426 })
1427 .collect();
1428 (rings, meetings)
1429 };
1430 for toast in &message_toasts {
1431 if let Some(user_id) = toast.sender_id.as_deref() {
1432 used_avatars.insert(user_id.to_owned());
1433 }
1434 let image =
1435 self.avatar_notification_image(self.app.read(cx), toast.sender_id.as_deref());
1436 let payload = desktop_payload::message_payload(toast, preview_on, &message_labels);
1437 visible_logical.insert(payload.key.replace_token());
1438 visible.push(Self::to_bus(payload, image));
1439 }
1440 for (payload, caller_id) in ring_payloads {
1441 if let Some(user_id) = caller_id.as_deref() {
1442 used_avatars.insert(user_id.to_owned());
1443 }
1444 let image = self.avatar_notification_image(self.app.read(cx), caller_id.as_deref());
1445 visible_logical.insert(payload.key.replace_token());
1446 visible.push(Self::to_bus(payload, image));
1447 }
1448 for payload in meeting_payloads {
1449 visible_logical.insert(payload.key.replace_token());
1450 visible.push(Self::to_bus(payload, None));
1451 }
1452 self.desktop_avatar_cache
1453 .retain(|user_id, _| used_avatars.contains(user_id));
1454 let mut close = std::mem::take(&mut self.desktop_close);
1455 for previous in &self.desktop_published {
1456 if visible_logical.contains(previous) {
1457 continue;
1458 }
1459 if previous.starts_with("ring:") || previous.starts_with("meeting:") {
1460 close.push(previous.clone());
1461 }
1462 }
1463 close.sort();
1464 close.dedup();
1465 if let Some(desktop) = &self.desktop {
1466 desktop.sync(visible, close);
1467 }
1468 self.desktop_published = visible_logical;
1469 }
1470
1471 #[cfg(target_os = "linux")]
1472 fn poll_desktop(&mut self, cx: &mut Context<Self>) {
1473 let Some(desktop) = &self.desktop else {
1474 return;
1475 };
1476 let events = desktop.poll();
1477 for event in events {
1478 match event {
1479 NotificationEvent::Action {
1480 logical_key,
1481 action_id,
1482 } => self.handle_desktop_action(&logical_key, &action_id, cx),
1483 NotificationEvent::Reply { logical_key, text } => {
1484 if let Some(DesktopKey::Message(id)) = parse_logical_key(&logical_key) {
1485 self.submit_reply(id, text, cx);
1486 }
1487 }
1488 NotificationEvent::Closed {
1489 logical_key,
1490 reason,
1491 } => {
1492 if reason == CLOSED_BY_USER
1493 && let Some(DesktopKey::Meeting(toast_id)) = parse_logical_key(&logical_key)
1494 {
1495 self.app
1496 .update(cx, |state, cx| state.dismiss_meeting_toast(toast_id, cx));
1497 }
1498 }
1499 }
1500 }
1501 }
1502
1503 #[cfg(target_os = "linux")]
1504 fn handle_desktop_action(
1505 &mut self,
1506 logical_key: &str,
1507 action_id: &str,
1508 cx: &mut Context<Self>,
1509 ) {
1510 let Some(key) = parse_logical_key(logical_key) else {
1511 return;
1512 };
1513 match key {
1514 DesktopKey::Message(id)
1515 if action_id == action::DEFAULT
1516 || action_id == action::REPLY
1517 || action_id == "reply-open" =>
1518 {
1519 self.activate(id, cx);
1520 }
1521 DesktopKey::Message(id) if action_id == action::MARK_READ => self.mark_read(id, cx),
1522 DesktopKey::Ring(ring_id) if action_id == action::DECLINE => {
1523 self.queue_desktop_close(DesktopKey::Ring(ring_id));
1524 self.app
1525 .update(cx, |state, cx| state.decline_ring(ring_id, cx));
1526 }
1527 DesktopKey::Ring(ring_id) if action_id == action::ACCEPT_AUDIO => {
1528 self.queue_desktop_close(DesktopKey::Ring(ring_id));
1529 self.accept_ring(ring_id, calling::AcceptMode::Audio, cx);
1530 }
1531 DesktopKey::Ring(ring_id) if action_id == action::ACCEPT_VIDEO => {
1532 self.queue_desktop_close(DesktopKey::Ring(ring_id));
1533 self.accept_ring(ring_id, calling::AcceptMode::Video, cx);
1534 }
1535 DesktopKey::Meeting(toast_id)
1536 if action_id == action::JOIN || action_id == action::DEFAULT =>
1537 {
1538 self.queue_desktop_close(DesktopKey::Meeting(toast_id));
1539 self.join_meeting_toast(toast_id, cx);
1540 }
1541 DesktopKey::Meeting(toast_id) if action_id == action::SNOOZE => {
1542 self.queue_desktop_close(DesktopKey::Meeting(toast_id));
1543 self.app
1544 .update(cx, |state, cx| state.snooze_meeting_toast(toast_id, cx));
1545 }
1546 _ => {}
1547 }
1548 }
1549
1550 fn poll_tray(&mut self, cx: &mut Context<Self>) {
1551 let commands = self.tray.as_ref().map(Tray::poll).unwrap_or_default();
1552 for command in commands {
1553 match command {
1554 TrayCommand::Toggle => self.toggle_main_window(cx),
1555 TrayCommand::Open => self.raise_main_window(cx),
1556 TrayCommand::SetStatus(kind) => {
1557 let forced = ForcedAvailability {
1558 kind,
1559 expires_at: None,
1560 };
1561 self.app
1562 .update(cx, |state, cx| state.set_own_availability(Some(forced), cx));
1563 self.sync_tray(cx);
1564 }
1565 TrayCommand::SetStatusDuration(duration) => {
1566 let Some(kind) = self
1567 .app
1568 .read(cx)
1569 .own_status
1570 .forced
1571 .map(|forced| forced.kind)
1572 .filter(|kind| *kind != ForcedKind::Available)
1573 else {
1574 continue;
1575 };
1576 let forced = ForcedAvailability {
1577 kind,
1578 expires_at: Some(duration.expires_at(Local::now())),
1579 };
1580 self.app
1581 .update(cx, |state, cx| state.set_own_availability(Some(forced), cx));
1582 self.sync_tray(cx);
1583 }
1584 TrayCommand::ResetStatus => {
1585 self.app
1586 .update(cx, |state, cx| state.set_own_availability(None, cx));
1587 self.sync_tray(cx);
1588 }
1589 TrayCommand::Notifications => {
1590 self.raise_main_window(cx);
1591 self.app.update(cx, |state, cx| {
1592 state.open_settings(SettingsSection::Notifications, cx)
1593 });
1594 }
1595 TrayCommand::Quit => cx.quit(),
1596 }
1597 }
1598 }
1599
1600 fn toggle_main_window(&mut self, cx: &mut Context<Self>) {
1601 if self.main_window_active(cx) {
1602 if let Some(native) = self.main_native {
1603 platform::hide_window(native);
1604 } else {
1605 #[cfg(any(target_os = "linux", target_os = "macos"))]
1606 crate::main_window::hide(cx);
1607 }
1608 } else {
1609 self.raise_main_window(cx);
1610 }
1611 }
1612
1613 pub fn accept_ring(&mut self, ring_id: u64, mode: calling::AcceptMode, cx: &mut Context<Self>) {
1614 self.raise_main_window(cx);
1615 self.app
1616 .update(cx, |state, cx| state.accept_ring(ring_id, mode, cx));
1617 self.finish_ring_card(ring_id, cx);
1618 }
1619
1620 pub fn decline_ring(&mut self, ring_id: u64, cx: &mut Context<Self>) {
1621 self.app
1622 .update(cx, |state, cx| state.decline_ring(ring_id, cx));
1623 self.finish_ring_card(ring_id, cx);
1624 }
1625
1626 fn raise_main_window(&mut self, cx: &mut Context<Self>) {
1627 #[cfg(any(target_os = "linux", target_os = "macos"))]
1628 if crate::main_window::is_hidden(cx) {
1629 crate::main_window::show(cx);
1630 return;
1631 }
1632 if let Some(native) = self.main_native {
1633 platform::restore_and_raise(native);
1634 }
1635 self.main_window
1636 .update(cx, |_, window, _| window.activate_window())
1637 .ok();
1638 }
1639
1640 fn apply_app_icon(&mut self, icon: AppIcon, cx: &mut Context<Self>) {
1641 if icon == self.app_icon {
1642 return;
1643 }
1644 self.app_icon = icon;
1645 let mention = !self.unread_mentions.is_empty();
1646 if let Some(tray) = &mut self.tray {
1647 tray.set_app_icon(icon.png(), mention);
1648 }
1649 let _ = self.main_window.update(cx, |_, window, _| {
1650 platform::set_window_icon(window, icon.png())
1651 });
1652 }
1653
1654 fn show_in_tray(&mut self, shown: bool, cx: &mut Context<Self>) {
1655 if !shown {
1656 self.tray = None;
1657 self.last_tray_presence = None;
1658 } else if self.tray.is_none() && !self.demo_mode {
1659 let presence = tray_presence_from(self.app.read(cx), !self.unread_mentions.is_empty());
1660 self.tray = Tray::new(presence, self.app_icon.png());
1661 self.last_tray_presence = None;
1662 }
1663 }
1664
1665 fn relocalize_tray(&self) {
1666 if let Some(tray) = &self.tray {
1667 tray.relocalize();
1668 }
1669 }
1670
1671 fn sync_tray(&mut self, cx: &App) {
1672 let Some(tray) = &self.tray else {
1673 return;
1674 };
1675 let presence = tray_presence_from(self.app.read(cx), !self.unread_mentions.is_empty());
1676 if self.last_tray_presence.as_ref() == Some(&presence) {
1677 return;
1678 }
1679 tray.sync(presence.clone());
1680 self.last_tray_presence = Some(presence);
1681 }
1682
1683 fn refresh_badge(&mut self, cx: &mut Context<Self>) {
1684 let state = self.app.read(cx);
1685 let count = taskbar_badge_count(
1686 &state.sidebar,
1687 self.activity.read(cx).feed(),
1688 state.directory.section_settings.adaptive_rail(),
1689 ) + crate::agent_api::unseen_proposal_count(cx);
1690 let still_unread = unread_conversation_ids(&state.sidebar);
1691 self.unread_mentions
1692 .retain(|conversation_id| still_unread.contains(conversation_id.as_str()));
1693 let badge = badge_for(count);
1694 let mention_dot = !self.unread_mentions.is_empty();
1695 if badge == self.shown_badge && mention_dot == self.shown_mention_dot {
1696 return;
1697 }
1698 self.shown_mention_dot = mention_dot;
1699 if badge != self.shown_badge
1700 && let Some(native) = self.main_native
1701 {
1702 platform::set_badge(native, badge.as_ref());
1703 if badge.is_none() && self.shown_badge.is_some() {
1704 platform::stop_flash(native);
1705 }
1706 }
1707 self.shown_badge = badge;
1708 self.sync_tray(cx);
1709 }
1710
1711 pub fn set_hover(&mut self, id: u64, hovered: bool, cx: &mut Context<Self>) {
1712 let now = Instant::now();
1713 let Some(toast) = self.stack.get_mut(id) else {
1714 return;
1715 };
1716 if toast.hovered == hovered {
1717 return;
1718 }
1719 toast.hovered = hovered;
1720 self.sync_hover_hold(now);
1721 cx.notify();
1722 }
1723
1724 pub fn dismiss(&mut self, id: u64, cx: &mut Context<Self>) {
1725 self.drop_toast(id, cx);
1726 }
1727
1728 pub fn open_reply(&mut self, id: u64, cx: &mut Context<Self>) -> Option<String> {
1729 let now = Instant::now();
1730 let toast = self.stack.get_mut(id)?;
1731 toast.reply = ReplyState::Open;
1732 toast.timer.pause(now);
1733 let draft = toast.reply_text.clone();
1734 cx.notify();
1735 Some(draft)
1736 }
1737
1738 pub fn close_reply(&mut self, id: u64, cx: &mut Context<Self>) {
1739 if let Some(toast) = self.stack.get_mut(id) {
1740 toast.reply = ReplyState::Closed;
1741 toast.reply_text.clear();
1742 toast.hovered = false;
1743 }
1744 cx.notify();
1745 }
1746
1747 pub fn submit_reply(&mut self, id: u64, text: String, cx: &mut Context<Self>) {
1748 let Some(toast) = self.stack.get_mut(id) else {
1749 return;
1750 };
1751 toast.reply_text = text.clone();
1752 let conversation_id = toast.conversation_id.clone();
1753 let message_id = toast.message_id.clone();
1754 let is_channel = matches!(toast.kind, ChatKind::Channel { .. });
1755 let state = self.app.read(cx);
1756 let (mode, engine) = (state.mode, state.engine.clone());
1757 let outcome: Result<(), ()> = if mode.demo {
1758 Ok(())
1759 } else if mode.read_only {
1760 Err(())
1761 } else if let Some(engine) = engine {
1762 let receiver = runtime::spawn(async move {
1763 if is_channel {
1764 engine.reply_to(&conversation_id, &message_id, &text).await
1765 } else {
1766 engine.send_message(&conversation_id, &text, None).await
1767 }
1768 .map(|_| ())
1769 });
1770 cx.spawn(async move |this, cx| {
1771 let sent = matches!(receiver.await, Ok(Ok(())));
1772 this.update(cx, |center, cx| center.finish_reply(id, sent, cx))
1773 .ok();
1774 })
1775 .detach();
1776 return;
1777 } else {
1778 Err(())
1779 };
1780 self.finish_reply(id, outcome.is_ok(), cx);
1781 }
1782
1783 fn finish_reply(&mut self, id: u64, sent: bool, cx: &mut Context<Self>) {
1784 let Some(toast) = self.stack.get_mut(id) else {
1785 return;
1786 };
1787 toast.reply = if sent {
1788 ReplyState::Sent
1789 } else {
1790 ReplyState::Failed
1791 };
1792 let conversation_id = toast.conversation_id.clone();
1793 cx.notify();
1794 if sent {
1795 cx.spawn(async move |this, cx| {
1796 cx.background_executor().timer(SENT_DURATION).await;
1797 this.update(cx, |center, cx| {
1798 center.mark_conversation_read(&conversation_id, cx);
1799 center.drop_toast(id, cx);
1800 })
1801 .ok();
1802 })
1803 .detach();
1804 }
1805 }
1806
1807 fn mark_conversation_read(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
1808 self.unread_mentions.remove(conversation_id);
1809 let conversation_id = conversation_id.to_owned();
1810 self.app
1811 .update(cx, |state, cx| state.mark_chat_read(&conversation_id, cx));
1812 self.refresh_badge(cx);
1813 }
1814
1815 pub fn mark_read(&mut self, id: u64, cx: &mut Context<Self>) {
1816 if self.is_dismissed(id) {
1817 return;
1818 }
1819 let Some(conversation_id) = self
1820 .stack
1821 .get(id)
1822 .map(|toast| toast.conversation_id.clone())
1823 else {
1824 return;
1825 };
1826 self.mark_conversation_read(&conversation_id, cx);
1827 self.drop_toast(id, cx);
1828 }
1829
1830 pub fn activate(&mut self, id: u64, cx: &mut Context<Self>) {
1831 if self.is_dismissed(id) {
1832 return;
1833 }
1834 if let Some((org, conversation_id)) = self
1835 .stack
1836 .get(id)
1837 .and_then(|toast| Some((toast.org.clone()?, toast.conversation_id.clone())))
1838 {
1839 self.drop_toast(id, cx);
1840 self.app.update(cx, |state, cx| {
1841 state.switch_org(&org, Some(&conversation_id), cx)
1842 });
1843 return;
1844 }
1845 let Some((conversation_id, message_id, proposal_id)) = self.stack.get(id).map(|toast| {
1846 (
1847 toast.conversation_id.clone(),
1848 toast.message_id.clone(),
1849 toast
1850 .agent
1851 .as_ref()
1852 .and_then(|agent| agent.proposal_id().map(str::to_owned)),
1853 )
1854 }) else {
1855 return;
1856 };
1857 self.drop_toast(id, cx);
1858 if let Some(proposal_id) = proposal_id {
1859 agent_api::mark_proposal_seen(&proposal_id, cx);
1860 }
1861 self.raise_main_window(cx);
1862 let selection = selection_for(&self.app.read(cx).sidebar, &conversation_id);
1863 if let Some(selection) = selection {
1864 self.app.update(cx, |state, cx| {
1865 if message_id.is_empty() {
1866 state.select(selection, cx)
1867 } else {
1868 state.jump_to_message(selection, message_id, cx)
1869 }
1870 });
1871 }
1872 }
1873
1874 pub fn send_test_notification(&mut self, cx: &mut Context<Self>) {
1875 let incoming = Incoming {
1876 conversation_id: "test-notification".to_owned(),
1877 message_id: "test".to_owned(),
1878 kind: ChatKind::Direct,
1879 chat_title: "Mara Lindqvist".to_owned(),
1880 sender_id: None,
1881 sender_name: "Mara Lindqvist".to_owned(),
1882 preview: Preview::Text("This is a test notification.".to_owned()),
1883 mentions_me: false,
1884 muted: false,
1885 signals: Default::default(),
1886 chat: Default::default(),
1887 created_at: Utc::now(),
1888 importance: Default::default(),
1889 };
1890 let decision = Decision {
1891 toast: true,
1892 sound: self.settings.sounds.notification_sound,
1893 urgent_sound: false,
1894 };
1895 self.throttle = SoundThrottle::default();
1896 self.present(&incoming, decision, cx);
1897 }
1898
1899 fn show_demo_toasts(&mut self, cx: &mut Context<Self>) {
1900 for incoming in demo_incoming() {
1901 let decision = Decision {
1902 toast: true,
1903 sound: false,
1904 urgent_sound: false,
1905 };
1906 self.present(&incoming, decision, cx);
1907 }
1908 }
1909}
1910
1911/// Opens a window outside the current update: `open_window` draws right away, and every
1912/// notification view reads the center while rendering.
1913fn open_popup<V: Into<AnyView>>(
1914 options: WindowOptions,
1915 cx: &mut Context<NotificationCenter>,
1916 build: impl FnOnce(Entity<NotificationCenter>, &mut Window, &mut App) -> V + 'static,
1917 opened: impl FnOnce(&mut NotificationCenter, Option<OpenWindow>) + 'static,
1918) {
1919 let center = cx.entity();
1920 cx.defer(move |cx| {
1921 let view_center = center.clone();
1922 let Ok(handle) = cx.open_window(options, move |window, cx| {
1923 let view = build(view_center, window, cx);
1924 cx.new(|cx| base::Root::new(view, window, cx).bg(transparent_black()))
1925 }) else {
1926 center.update(cx, |this, _| opened(this, None));
1927 return;
1928 };
1929 let handle = AnyWindowHandle::from(handle);
1930 let native = handle
1931 .update(cx, |_, window, _| platform::native_handle(window))
1932 .ok()
1933 .flatten();
1934 if let Some(native) = native {
1935 platform::prepare_toast_window(native);
1936 }
1937 let window = OpenWindow {
1938 handle,
1939 native,
1940 opened: Instant::now(),
1941 placed: Cell::new(None),
1942 };
1943 center.update(cx, |this, _| opened(this, Some(window)));
1944 });
1945}
1946
1947fn window_is_open(window_id: WindowId, cx: &App) -> bool {
1948 cx.windows()
1949 .iter()
1950 .any(|window| window.window_id() == window_id)
1951}
1952
1953fn own_presence(state: &AppState) -> PresenceKind {
1954 state
1955 .directory
1956 .me
1957 .as_ref()
1958 .map_or(PresenceKind::Unknown, |me| {
1959 state.directory.presence_of(&me.user_id).kind()
1960 })
1961}
1962
1963fn own_do_not_disturb(state: &AppState) -> bool {
1964 own_presence(state) == PresenceKind::DoNotDisturb
1965}
1966
1967fn tray_presence_from(state: &AppState, mention: bool) -> TrayPresence {
1968 let summary = own_status::state_summary(&state.own_status, own_presence(state), &Local::now());
1969 let title = match &summary.until {
1970 Some(until) => format!("{} {until}", summary.label),
1971 None => summary.label.to_owned(),
1972 };
1973 TrayPresence::new(
1974 title,
1975 state.own_status.forced.map(|forced| forced.kind),
1976 mention,
1977 )
1978}
1979
1980fn sync_loop(handle: &mut Option<SoundHandle>, audible: bool, tone: CallTone, cx: &App) {
1981 match (audible, handle.is_some()) {
1982 (true, false) => *handle = Some(sound_cache::start(tone.file_name(), true, cx)),
1983 (false, true) => *handle = None,
1984 _ => {}
1985 }
1986}
1987
1988fn demo_scene() -> Option<DemoScene> {
1989 DemoScene::from_name(&std::env::var(DEMO_CALL_ENV).ok()?)
1990}
1991
1992/// `TEAMS_DEMO_RING=<seconds>` rings a fake incoming call that long after the demo starts.
1993fn demo_ring_delay() -> Option<Duration> {
1994 let seconds: f32 = std::env::var(DEMO_RING_ENV).ok()?.trim().parse().ok()?;
1995 (seconds >= 0.).then(|| Duration::from_secs_f32(seconds))
1996}
1997
1998fn first_lines(text: &str, count: usize) -> String {
1999 text.lines()
2000 .map(str::trim)
2001 .filter(|line| !line.is_empty())
2002 .take(count)
2003 .collect::<Vec<_>>()
2004 .join("\n")
2005}
2006
2007fn preview_lines(text: &str, cx: &App) -> usize {
2008 wrapped_lines(text, layout::PREVIEW_WIDTH, cx)
2009}
2010
2011fn wrapped_lines(text: &str, width: f32, cx: &App) -> usize {
2012 let mut wrapper = cx
2013 .text_system()
2014 .line_wrapper(font(crate::theme::font_family()), px(layout::PREVIEW_SIZE));
2015 text.split('\n')
2016 .map(|line| {
2017 let fragments = [LineFragment::text(line)];
2018 wrapper
2019 .wrap_line(&fragments, px(width), IndentAdjustment::NoIndent)
2020 .count()
2021 + 1
2022 })
2023 .sum()
2024}
2025
2026#[cfg(target_os = "linux")]
2027const CLOSED_BY_USER: u32 = 2;
2028
2029#[cfg(target_os = "linux")]
2030fn parse_logical_key(key: &str) -> Option<DesktopKey> {
2031 let (kind, id) = key.split_once(':')?;
2032 let id = id.parse().ok()?;
2033 match kind {
2034 "message" => Some(DesktopKey::Message(id)),
2035 "ring" => Some(DesktopKey::Ring(id)),
2036 "meeting" => Some(DesktopKey::Meeting(id)),
2037 _ => None,
2038 }
2039}
2040
2041fn ring_card_options(slot: Slot, area: WorkArea) -> WindowOptions {
2042 // Wayland treats PopUp as a normal toplevel, so Hyprland tiles ring and meeting cards.
2043 #[cfg(target_os = "linux")]
2044 {
2045 let mut options = popup_options(slot, area);
2046 options.kind = WindowKind::Floating;
2047 return options;
2048 }
2049 #[cfg(not(target_os = "linux"))]
2050 popup_options(slot, area)
2051}
2052
2053fn popup_options(slot: Slot, area: WorkArea) -> WindowOptions {
2054 let scale = area.scale;
2055 let bounds = Bounds::new(
2056 point(px(slot.x as f32 / scale), px(slot.y as f32 / scale)),
2057 size(
2058 px(slot.width as f32 / scale),
2059 px(slot.height as f32 / scale),
2060 ),
2061 );
2062 WindowOptions {
2063 window_bounds: Some(WindowBounds::Windowed(bounds)),
2064 titlebar: None,
2065 focus: false,
2066 show: true,
2067 kind: WindowKind::PopUp,
2068 is_movable: false,
2069 is_resizable: false,
2070 is_minimizable: false,
2071 window_background: WindowBackgroundAppearance::Transparent,
2072 ..Default::default()
2073 }
2074}
2075
2076pub fn unread_conversation_ids(sidebar: &Sidebar) -> HashSet<&str> {
2077 let chats = sidebar.chats.iter().filter(|chat| chat.unread);
2078 let channels = sidebar
2079 .teams
2080 .iter()
2081 .flat_map(|team| team.channels.iter())
2082 .filter(|channel| channel.unread);
2083 chats
2084 .map(|chat| chat.id.as_str())
2085 .chain(channels.map(|channel| channel.id.as_str()))
2086 .collect()
2087}
2088
2089fn demo_incoming() -> Vec<Incoming> {
2090 let item = |conversation: &str,
2091 kind: ChatKind,
2092 title: &str,
2093 sender: &str,
2094 text: &str,
2095 mention: bool| Incoming {
2096 conversation_id: conversation.to_owned(),
2097 message_id: format!("{conversation}-message"),
2098 kind,
2099 chat_title: title.to_owned(),
2100 sender_id: None,
2101 sender_name: sender.to_owned(),
2102 preview: Preview::Text(text.to_owned()),
2103 mentions_me: mention,
2104 muted: false,
2105 signals: Default::default(),
2106 chat: Default::default(),
2107 created_at: Utc::now(),
2108 importance: Default::default(),
2109 };
2110 vec![
2111 item(
2112 "demo-toast-direct",
2113 ChatKind::Direct,
2114 "Tobias Klein",
2115 "Tobias Klein",
2116 "Sounds good, I will look at it tomorrow.",
2117 false,
2118 ),
2119 item(
2120 "demo-toast-group",
2121 ChatKind::Group { member_count: 5 },
2122 "Retro-Team",
2123 "Priya Nair",
2124 "Please add topics by 5 pm.",
2125 false,
2126 ),
2127 item(
2128 "demo-toast-mention",
2129 ChatKind::Channel {
2130 team: "Platform".to_owned(),
2131 channel: "Releases".to_owned(),
2132 },
2133 "Releases",
2134 "Mara Lindqvist",
2135 "@Jonas can you approve the merge? The pipeline is waiting.",
2136 true,
2137 ),
2138 item(
2139 "demo-toast-lea",
2140 ChatKind::Direct,
2141 "Lea Schneider",
2142 "Lea Schneider",
2143 "Lunch at 12?",
2144 false,
2145 ),
2146 item(
2147 "demo-toast-jonas",
2148 ChatKind::Direct,
2149 "Jonas Ortega",
2150 "Jonas Ortega",
2151 "Deploy window moved to Thursday 6 pm.",
2152 false,
2153 ),
2154 ]
2155}
2156
2157#[cfg(test)]
2158mod tests {
2159 use store::{ChannelRecord, ChatRecord, SidebarTeam, TeamRecord};
2160
2161 use std::collections::HashSet;
2162
2163 use gpui_kit::{WindowBackgroundAppearance, WindowKind};
2164
2165 use super::{Slot, WorkArea, popup_options, preview_lines, unread_conversation_ids};
2166 use store::Sidebar;
2167
2168 #[test]
2169 fn toast_windows_ask_for_a_transparent_background() {
2170 let slot = Slot {
2171 x: 0,
2172 y: 0,
2173 width: 360,
2174 height: 120,
2175 };
2176 let area = WorkArea {
2177 left: 0,
2178 top: 0,
2179 right: 1920,
2180 bottom: 1080,
2181 scale: 1.,
2182 };
2183 let options = popup_options(slot, area);
2184 assert_eq!(
2185 options.window_background,
2186 WindowBackgroundAppearance::Transparent
2187 );
2188 assert_eq!(options.kind, WindowKind::PopUp);
2189 }
2190
2191 #[cfg(target_os = "linux")]
2192 #[test]
2193 fn linux_ring_card_is_a_floating_window() {
2194 use super::ring_card_options;
2195
2196 let slot = Slot {
2197 x: 10,
2198 y: 20,
2199 width: 360,
2200 height: 140,
2201 };
2202 let area = WorkArea {
2203 left: 0,
2204 top: 0,
2205 right: 1920,
2206 bottom: 1080,
2207 scale: 1.,
2208 };
2209 let options = ring_card_options(slot, area);
2210 assert_eq!(options.kind, WindowKind::Floating);
2211 assert!(!options.focus);
2212 }
2213
2214 #[test]
2215 fn call_cards_while_desktop_connected_keep_rings_and_meetings() {
2216 use super::{CallToast, call_cards_while_desktop_connected};
2217
2218 let toasts = vec![
2219 (CallToast::Ring(7), 140.),
2220 (CallToast::Meeting(3), 96.),
2221 (CallToast::Ring(9), 140.),
2222 ];
2223 let cards = call_cards_while_desktop_connected(&toasts);
2224 assert_eq!(
2225 cards,
2226 vec![
2227 (CallToast::Ring(7), 140.),
2228 (CallToast::Meeting(3), 96.),
2229 (CallToast::Ring(9), 140.)
2230 ]
2231 );
2232 }
2233
2234 #[cfg(target_os = "linux")]
2235 #[test]
2236 fn ring_card_close_token_matches_the_published_ring() {
2237 use super::DesktopKey;
2238
2239 assert_eq!(DesktopKey::Ring(7).replace_token(), "ring:7");
2240 }
2241
2242 fn sidebar() -> Sidebar {
2243 Sidebar {
2244 chats: vec![
2245 ChatRecord {
2246 id: "a".into(),
2247 unread: true,
2248 ..Default::default()
2249 },
2250 ChatRecord {
2251 id: "b".into(),
2252 unread: false,
2253 ..Default::default()
2254 },
2255 ],
2256 teams: vec![SidebarTeam {
2257 rights: Default::default(),
2258 team: TeamRecord {
2259 id: "t".into(),
2260 name: "Team".into(),
2261 },
2262 channels: vec![ChannelRecord {
2263 id: "ch".into(),
2264 team_id: "t".into(),
2265 name: "General".into(),
2266 membership_type: None,
2267 last_message_at: None,
2268 unread: true,
2269 }],
2270 hidden: false,
2271 hidden_channel_ids: Vec::new(),
2272 notifications: Default::default(),
2273 mentions: Default::default(),
2274 }],
2275 }
2276 }
2277
2278 #[test]
2279 fn unread_conversation_ids_hold_chats_and_channels() {
2280 let sidebar = sidebar();
2281 assert_eq!(
2282 unread_conversation_ids(&sidebar),
2283 HashSet::from(["a", "ch"])
2284 );
2285 }
2286
2287 #[gpui_kit::test]
2288 fn preview_lines_follow_the_wrapped_text(cx: &mut gpui_kit::TestAppContext) {
2289 cx.update(|cx| {
2290 assert_eq!(preview_lines("ok", cx), 1);
2291 assert_eq!(preview_lines("a\nb", cx), 2);
2292 let long = "Cristina: ok, thanks for the info! I think not now ".repeat(3);
2293 assert!(preview_lines(&long, cx) >= 2);
2294 });
2295 }
2296}