use std::cell::Cell; use std::collections::{HashMap, HashSet}; use std::time::{Duration, Instant}; use chrono::{DateTime, Local, Offset, Utc}; use gpui_kit::*; use store::Sidebar; use teams_core::{ForcedAvailability, ForcedKind}; use super::badge::{Badge, badge_for}; #[cfg(target_os = "linux")] use super::desktop_payload::{ self, DesktopKey, DesktopPayload, MeetingLabels, MessageLabels, RingLabels, action, }; use super::incoming::IncomingTracker; use super::layout::{self, MEETING_HEIGHT, Slot, ring_height}; use super::meeting_view::MeetingToastView; use super::platform::{self, NativeHandle, Tray, TrayCommand, TrayPresence, WorkArea}; #[cfg(target_os = "linux")] use super::platform::{ BusNotification, DesktopNotifications, NotificationEvent, NotificationImage, }; use super::ring_view::RingView; use super::rules::{ ChatKind, Decision, Environment, Incoming, Preview, Settings, SoundThrottle, decide, decide_proposal, in_call, meeting_start_sound, ringtone_for, should_flash, should_ringback, shows_preview, }; use super::settings; use super::sound_cache::{self, SoundHandle}; use super::sounds::{CallTone, Ringtone}; use super::stack::{ AgentToast, AgentToastKind, FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE, ToastModel, ToastStack, }; use super::taskbar::taskbar_badge_count; use super::text::describe; use super::toast::{PillView, ToastView}; use super::urgent_repeat::UrgentRepeats; use crate::active_appearance::{self, ActiveAppearance}; use crate::active_locale::ActiveLocale; use crate::activity::ActivityCenter; use crate::agent_api::{self, pending::PendingProposal}; use crate::agents::{AgentRun, AgentRunsEvent, RunState}; use crate::app_state::{AppEvent, AppState, selection_for}; use crate::appearance::AppIcon; use crate::autostart::{self, StartupSettings}; use crate::call::DemoScene; use crate::data::{self, Directory, PresenceKind}; use crate::org_watch::OrgMessage; use crate::own_status; use crate::runtime; use crate::settings_section::SettingsSection; use crate::single_instance; const TICK: Duration = Duration::from_millis(33); const SLIDE_DURATION: Duration = Duration::from_millis(180); const SLIDE_DISTANCE: f32 = 48.; const DEMO_SPEC_DELAY: Duration = Duration::from_secs(3); const DEMO_RING_ENV: &str = "TEAMS_DEMO_RING"; const DEMO_RING_KIND_ENV: &str = "TEAMS_DEMO_RING_KIND"; const DEMO_CALL_ENV: &str = "TEAMS_DEMO_CALL"; const DEMO_SCENE_DELAY: Duration = Duration::from_millis(1500); const AGENT_BODY_LINES: usize = 2; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] enum CallToast { Ring(u64), Meeting(u64), } struct OpenWindow { handle: AnyWindowHandle, native: Option, opened: Instant, placed: Cell>, } impl OpenWindow { fn place(&self, native: NativeHandle, slot: Slot, x: i32, cx: &mut App) { let rect = (x, slot.y, slot.width, slot.height); match self.placed.replace(Some(rect)) { Some(previous) if previous == rect => return, Some(_) => platform::place_rect(native, x, slot.y, slot.width, slot.height), None => platform::place(native, x, slot.y, slot.width, slot.height), } // WM_SIZE arrives while the app is borrowed, so GPUI drops its own resize report. self.handle .update(cx, |_, window, cx| window.bounds_changed(cx)) .ok(); } } pub struct NotificationCenter { app: Entity, activity: Entity, main_window: AnyWindowHandle, main_native: Option, settings: Settings, startup: StartupSettings, stack: ToastStack, tracker: IncomingTracker, throttle: SoundThrottle, urgent_repeats: UrgentRepeats, windows: HashMap, opening: HashSet, call_windows: HashMap, call_opening: HashSet, ring_tone: Option, ringback: Option, reconnecting: Option, preview: Option, demo_mode: bool, pill: Option, pill_opening: bool, hover_hold: bool, unread_mentions: HashSet, tray: Option, #[cfg(target_os = "linux")] desktop: Option, #[cfg(target_os = "linux")] desktop_close: Vec, #[cfg(target_os = "linux")] desktop_published: HashSet, #[cfg(target_os = "linux")] desktop_avatar_cache: HashMap, last_tray_presence: Option, app_icon: AppIcon, shown_badge: Option, shown_mention_dot: bool, animations: bool, _subscription: Subscription, _activity_observation: Subscription, _appearance_observation: Subscription, _locale_observation: Subscription, _agent_subscription: Option, started_at: DateTime, known_proposals: HashSet, _proposal_observation: Option, } impl NotificationCenter { pub fn new( app: Entity, activity: Entity, window: &mut Window, cx: &mut Context, ) -> Self { let mut settings = settings::load(&app.read(cx).store); settings.account = app.read(cx).account_chat_settings().notifications; let app_icon = active_appearance::current(cx).app_icon; let initial_presence = tray_presence_from(&app.read(cx), false); let tray = if app.read(cx).mode.demo || !settings.show_in_tray { None } else { Tray::new(initial_presence.clone(), app_icon.png()) }; let last_tray_presence = tray.as_ref().map(|_| initial_presence); platform::set_window_icon(window, app_icon.png()); let appearance_observation = cx.observe_global::(|this, cx| { this.apply_app_icon(active_appearance::current(cx).app_icon, cx) }); let locale_observation = cx.observe_global::(|this, cx| { // Locale changes the presence title; force a tray sync. this.last_tray_presence = None; this.relocalize_tray(); this.sync_tray(cx); }); let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| { this.on_app_event(event, cx); }); let activity_observation = cx.observe(&activity, |this, _, cx| this.refresh_badge(cx)); let agent_subscription = crate::agents::runs_handle(cx).map(|runs| { cx.subscribe(&runs, |this, runs, event: &AgentRunsEvent, cx| { if let AgentRunsEvent::Finished(run_id) = event && let Some(run) = runs.read(cx).get(*run_id).cloned() { this.present_agent_run(&run, cx); } }) }); let proposal_observation = agent_api::handle(cx).map(|api| cx.observe(&api, |this, _, cx| this.on_proposals(cx))); let center = NotificationCenter { started_at: Utc::now(), known_proposals: HashSet::new(), _proposal_observation: proposal_observation, main_window: window.window_handle(), main_native: platform::native_handle(window), settings, startup: StartupSettings::load(&app.read(cx).store, !app.read(cx).mode.demo), stack: ToastStack::default(), tracker: IncomingTracker::new(Utc::now()), throttle: SoundThrottle::default(), urgent_repeats: UrgentRepeats::default(), windows: HashMap::new(), opening: HashSet::new(), call_windows: HashMap::new(), call_opening: HashSet::new(), ring_tone: None, ringback: None, reconnecting: None, preview: None, demo_mode: app.read(cx).mode.demo, pill: None, pill_opening: false, hover_hold: false, unread_mentions: HashSet::new(), tray, #[cfg(target_os = "linux")] desktop: if app.read(cx).mode.demo { None } else { DesktopNotifications::start() }, #[cfg(target_os = "linux")] desktop_close: Vec::new(), #[cfg(target_os = "linux")] desktop_published: HashSet::new(), #[cfg(target_os = "linux")] desktop_avatar_cache: HashMap::new(), last_tray_presence, app_icon, shown_badge: None, shown_mention_dot: false, animations: platform::animations_enabled(), app, activity, _subscription: subscription, _activity_observation: activity_observation, _appearance_observation: appearance_observation, _locale_observation: locale_observation, _agent_subscription: agent_subscription, }; cx.spawn(async move |this, cx| { loop { cx.background_executor().timer(TICK).await; if this.update(cx, |center, cx| center.tick(cx)).is_err() { break; } } }) .detach(); if !center.demo_mode { center.prefetch_sounds(cx); } if center.app.read(cx).mode.demo { if demo_scene().is_none() { cx.spawn(async move |this, cx| { cx.background_executor().timer(DEMO_SPEC_DELAY).await; this.update(cx, |center, cx| center.show_demo_toasts(cx)) .ok(); }) .detach(); } if let Some(delay) = demo_ring_delay() { let app = center.app.clone(); let video = std::env::var(DEMO_RING_KIND_ENV).is_ok_and(|kind| kind.trim() == "video"); cx.spawn(async move |_, cx| { cx.background_executor().timer(delay).await; app.update(cx, |state, cx| { if video { state.demo_incoming_video_ring(cx) } else { state.demo_incoming_ring(cx) } }); }) .detach(); } if let Some(scene) = demo_scene() { let app = center.app.clone(); cx.spawn(async move |_, cx| { cx.background_executor().timer(DEMO_SCENE_DELAY).await; app.update(cx, |state, cx| state.start_demo_scene(scene, cx)); }) .detach(); } } center } pub fn app(&self) -> &Entity { &self.app } pub fn settings(&self) -> &Settings { &self.settings } pub fn model(&self, id: u64) -> Option<&ToastModel> { self.stack.get(id) } pub fn queued_count(&self) -> usize { self.stack.queued_count() } pub fn stack_opacity(&self) -> f32 { let now = Instant::now(); self.stack .visible() .iter() .map(|toast| toast.opacity(now)) .fold(0., f32::max) } fn animated(&self, duration: Duration) -> Duration { if self.animations { duration } else { Duration::ZERO } } pub fn directory<'a>(&self, cx: &'a App) -> &'a Directory { &self.app.read(cx).directory } pub fn reply_text(&self, id: u64) -> Option { self.stack.get(id).map(|toast| toast.reply_text.clone()) } pub fn startup(&self) -> StartupSettings { self.startup } pub fn set_auto_start(&mut self, enabled: bool, cx: &mut Context) { if !self.demo_mode && let Err(error) = autostart::set_enabled(crate::APP_NAME, enabled) { self.app.update(cx, |state, cx| { state.raise_notice( format!("Auto-start could not be changed: {error}"), None, cx, ) }); return; } self.startup.auto_start = enabled; cx.notify(); } pub fn set_open_in_background(&mut self, enabled: bool, cx: &mut Context) { self.startup.open_in_background = enabled; self.startup.save_background(&self.app.read(cx).store); cx.notify(); } /// Points at a main window reopened from the tray. pub fn attach_main_window(&mut self, window: &mut Window) { self.main_window = window.window_handle(); self.main_native = platform::native_handle(window); platform::set_window_icon(window, self.app_icon.png()); } pub fn start_in_background(&self, window: &mut Window, cx: &mut App) { match (&self.tray, self.main_native) { (Some(_), Some(native)) => platform::hide_window(native), #[cfg(any(target_os = "linux", target_os = "macos"))] (Some(_), None) => crate::main_window::hide(cx), _ => window.minimize_window(), } let _ = cx; } /// True when the close is handled here (window hidden natively). On Linux the /// window closes for real and the app stays in the tray. pub fn intercept_close(&self, cx: &mut App) -> bool { match (self.settings.close_to_tray, &self.tray, self.main_native) { (true, Some(_), Some(native)) => { platform::hide_window(native); true } #[cfg(any(target_os = "linux", target_os = "macos"))] (true, Some(_), None) => { crate::main_window::mark_hiding(cx); false } _ => { let _ = cx; false } } } pub fn update_settings(&mut self, cx: &mut Context, change: impl FnOnce(&mut Settings)) { let previous = self.settings.sounds.clone(); change(&mut self.settings); settings::save(&self.app.read(cx).store, &self.settings); self.show_in_tray(self.settings.show_in_tray, cx); self.sync_tray(cx); if self.settings.sounds != previous { let updated = self.settings.sounds.clone(); self.app.update(cx, |state, cx| { state.save_sound_settings(previous, updated, cx) }); self.prefetch_sounds(cx); } cx.notify(); } fn on_account_notifications(&mut self, cx: &mut Context) { self.settings.account = self.app.read(cx).account_chat_settings().notifications; cx.notify(); } fn on_account_sounds(&mut self, cx: &mut Context) { let Some(account) = self.app.read(cx).account_sounds.clone() else { return; }; if account == self.settings.sounds { return; } self.settings.sounds = account; settings::save(&self.app.read(cx).store, &self.settings); self.sync_tray(cx); if !self.demo_mode { self.prefetch_sounds(cx); } cx.notify(); } fn prefetch_sounds(&self, cx: &App) { let sounds = &self.settings.sounds; let chosen = [ sounds.notification_sound_type.file_name(), sounds.urgent_sound_type.file_name(), sounds.ringtones.regular.file_name(), Ringtone::Beep.file_name(), ]; let call_tones = CallTone::ALL.map(CallTone::file_name); sound_cache::prefetch(&chosen, cx); sound_cache::prefetch(&call_tones, cx); } pub fn preview_sound(&mut self, file_name: &'static str, cx: &mut Context) { self.preview = Some(sound_cache::start(file_name, false, cx)); } fn play_notification_sound(&self, cx: &App) { let file_name = self.settings.sounds.notification_sound_type.file_name(); sound_cache::play_or(file_name, platform::play_sound, cx); } fn play_urgent_sound(&self, cx: &App) { let file_name = self.settings.sounds.urgent_sound_type.file_name(); sound_cache::play_or(file_name, platform::play_sound, cx); } fn on_app_event(&mut self, event: &AppEvent, cx: &mut Context) { match event { AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx), AppEvent::Selection => self.on_selection(cx), AppEvent::Sidebar => self.refresh_badge(cx), AppEvent::Directory | AppEvent::Status => self.sync_tray(cx), AppEvent::Ring => self.on_rings_changed(cx), AppEvent::MeetingReminder => self.on_meeting_reminder(cx), AppEvent::MeetingChime => self.on_meeting_chime(cx), AppEvent::CallTone(tone) => self.on_call_tone(*tone, cx), AppEvent::Call => self.sync_call_sounds(cx), AppEvent::SoundSettings => self.on_account_sounds(cx), AppEvent::ChatSettings => self.on_account_notifications(cx), AppEvent::OrgMessage(message) => self.present_org_message(message, cx), AppEvent::FollowedStatus { user_id, text } => { self.present_status_change(user_id, text, cx) } _ => {} } } fn on_selection(&mut self, cx: &mut Context) { let selected = self .app .read(cx) .selection .as_ref() .map(|selection| selection.conversation_id().to_owned()); if let Some(conversation_id) = selected { self.unread_mentions.remove(&conversation_id); self.stack.remove_conversation(&conversation_id); self.urgent_repeats.stop_conversation(&conversation_id); } self.refresh_badge(cx); } fn on_messages(&mut self, conversation_id: &str, cx: &mut Context) { let state = self.app.read(cx); let my_user_id = state.directory.me.as_ref().map(|me| me.user_id.clone()); let found = self.tracker.collect( &state.store, &state.sidebar, my_user_id.as_deref(), &state.late_arrivals, conversation_id, ); for incoming in found { self.handle_incoming(incoming, cx); } self.refresh_badge(cx); } fn environment(&self, conversation_id: &str, cx: &mut Context) -> Environment { let state = self.app.read(cx); let selected = state .selection .as_ref() .is_some_and(|selection| selection.conversation_id() == conversation_id); let own_do_not_disturb = own_do_not_disturb(state); let own_busy = own_presence(state) == PresenceKind::Busy; let server_in_call = match (state.engine.as_ref(), state.directory.me.as_ref()) { (Some(engine), Some(me)) => data::in_call(engine, &me.user_id), _ => false, }; let in_call = in_call(server_in_call, state.call.as_ref().map(|call| &call.model)); let paused = state.notifications_paused(chrono::Utc::now()); Environment { chat_in_foreground: selected && self.main_window_active(cx), system_quiet: platform::system_quiet(), own_do_not_disturb, paused, own_busy, in_call, } } fn main_window_active(&self, cx: &mut Context) -> bool { self.main_window .update(cx, |_, window, _| window.is_window_active()) .unwrap_or(false) } pub fn handle_incoming(&mut self, mut incoming: Incoming, cx: &mut Context) { incoming.chat.desktop = self .app .read(cx) .chat_desktop_notifications(&incoming.conversation_id); let bubble_text = match &incoming.preview { Preview::Text(text) => text.replace('\n', " "), Preview::Image => "Sent a picture".to_owned(), }; self.app.update(cx, |state, cx| { state.note_call_chat_message( &incoming.conversation_id, &incoming.message_id, incoming.sender_id.clone(), &incoming.sender_name, &bubble_text, cx, ) }); let environment = self.environment(&incoming.conversation_id, cx); if !environment.chat_in_foreground && incoming.mentions_me { self.unread_mentions .insert(incoming.conversation_id.clone()); } let decision = decide(&self.settings, &incoming, environment); self.present(&incoming, decision, cx); if !environment.chat_in_foreground { self.urgent_repeats.track(&incoming, Utc::now()); } if should_flash(&self.settings, decision.toast, self.main_window_active(cx)) && let Some(native) = self.main_native { platform::flash(native); } } fn present(&mut self, incoming: &Incoming, decision: Decision, cx: &mut Context) { if !decision.toast { return; } let now = Instant::now(); let outcome = self.stack.push(incoming, now); if let Some(model) = self.stack.get_mut(outcome.id) { model.time = chrono::Local::now() .format(crate::format::clock_format()) .to_string(); } let throttle_allows = self.throttle.allow(&incoming.conversation_id, now); let audible = outcome.plays_sound(throttle_allows) || (decision.urgent_sound && throttle_allows); if decision.sound && audible && !self.app.read(cx).mode.demo { if decision.urgent_sound { self.play_urgent_sound(cx); } else { self.play_notification_sound(cx); } } if let Some(user_id) = incoming.sender_id.clone() { self.app .update(cx, |state, cx| state.request_avatars(vec![user_id], cx)); } self.sync_windows(cx); } fn own_feature_decision(&self, cx: &mut Context) -> Decision { let environment = self.environment("", cx); decide_proposal( &self.settings, teams_core::DesktopNotifications::MatchAllChats, environment, ) } fn present_org_message(&mut self, message: &OrgMessage, cx: &mut Context) { let decision = self.own_feature_decision(cx); if !decision.toast { return; } let now = Instant::now(); let id = self.stack.push_org_message(message, now); if let Some(model) = self.stack.get_mut(id) { model.time = chrono::Local::now() .format(crate::format::clock_format()) .to_string(); } if decision.sound && self.throttle.allow(&message.conversation_id, now) { self.play_notification_sound(cx); } self.sync_windows(cx); } fn present_status_change(&mut self, user_id: &str, text: &str, cx: &mut Context) { if !self.own_feature_decision(cx).toast { return; } let (name, conversation_id) = { let state = self.app.read(cx); let name = state .followed_presence .iter() .find(|person| person.user_id == user_id) .map(|person| person.name.clone()) .unwrap_or_default(); ( name, state.one_on_one_chat_with(user_id).unwrap_or_default(), ) }; let id = self.stack .push_status_change(user_id, &name, text, &conversation_id, Instant::now()); if let Some(model) = self.stack.get_mut(id) { model.time = chrono::Local::now() .format(crate::format::clock_format()) .to_string(); } let user_id = user_id.to_owned(); self.app .update(cx, |state, cx| state.request_avatars(vec![user_id], cx)); self.sync_windows(cx); } pub fn present_agent_run(&mut self, run: &AgentRun, cx: &mut Context) { let decision = self.own_feature_decision(cx); if !decision.toast { return; } let failed = matches!(run.state, RunState::Failed { .. }); let verb = if failed { "failed" } else { "finished" }; let body = if failed { run.current_step.clone() } else { first_lines(&run.final_text, AGENT_BODY_LINES) }; let toast = AgentToast { kind: AgentToastKind::Run { run_id: run.id, session_id: run.session_id.clone(), failed, }, header: format!( "{} - {} - {}", run.action_label, run.agent_name, run.elapsed_text() ), title: format!( "{} {verb}: {} for {}", run.agent_name, run.action_label, run.sender_name ), body: if body.is_empty() { "Done".to_owned() } else { body }, }; let now = Instant::now(); let id = self .stack .push_agent(toast, &run.conversation_id, &run.message_id, now); if let Some(model) = self.stack.get_mut(id) { model.time = chrono::Local::now() .format(crate::format::clock_format()) .to_string(); } if decision.sound && !self.app.read(cx).mode.demo { self.play_notification_sound(cx); } self.sync_windows(cx); } pub fn agent_toast_follow_up(&mut self, id: u64, cx: &mut Context) { let Some(agent) = self.stack.get(id).and_then(|toast| toast.agent.clone()) else { return; }; self.drop_toast(id, cx); match agent.kind { AgentToastKind::Run { run_id, failed: true, .. } => crate::agents::retry_run(run_id, cx), AgentToastKind::Run { session_id, .. } => crate::agents::open_session(&session_id, cx), AgentToastKind::Proposal { .. } => {} } } fn on_proposals(&mut self, cx: &mut Context) { let pending = agent_api::pending_proposals(cx); let unseen: HashSet<&str> = pending .iter() .filter(|proposal| !proposal.seen) .map(|proposal| proposal.id.as_str()) .collect(); let resolved: Vec = self .stack .ids() .into_iter() .filter(|id| { self.stack .get(*id) .and_then(|toast| toast.agent.as_ref()?.proposal_id()) .is_some_and(|proposal_id| !unseen.contains(proposal_id)) }) .collect(); for id in resolved { self.drop_toast(id, cx); } let arrived: Vec = pending .iter() .filter(|proposal| { !self.known_proposals.contains(&proposal.id) && !proposal.seen && proposal.created_at >= self.started_at }) .cloned() .collect(); self.known_proposals = pending.into_iter().map(|proposal| proposal.id).collect(); for proposal in arrived { self.present_proposal(&proposal, cx); } self.refresh_badge(cx); } fn present_proposal(&mut self, proposal: &PendingProposal, cx: &mut Context) { let state = self.app.read(cx); let desktop = state.chat_desktop_notifications(&proposal.conversation_id); let conversation = agent_api::pending::conversation_label(&state.sidebar, &proposal.conversation_id); let environment = self.environment(&proposal.conversation_id, cx); let decision = decide_proposal(&self.settings, desktop, environment); if !decision.toast { return; } let toast = AgentToast { kind: AgentToastKind::Proposal { proposal_id: proposal.id.clone(), }, header: conversation.unwrap_or_else(|| proposal.agent.to_owned()), title: proposal.title(), body: proposal.detail(), }; let id = self.stack.push_agent( toast, &proposal.conversation_id, proposal.jump_message_id(), Instant::now(), ); if let Some(model) = self.stack.get_mut(id) { model.time = chrono::Local::now() .format(crate::format::clock_format()) .to_string(); } if decision.sound && !self.demo_mode { self.play_notification_sound(cx); } if should_flash(&self.settings, decision.toast, self.main_window_active(cx)) && let Some(native) = self.main_native { platform::flash(native); } self.sync_windows(cx); } fn visible_ids(&self) -> Vec { self.stack.visible().iter().map(|toast| toast.id).collect() } fn work_area(&self, cx: &App) -> WorkArea { if let Some(area) = self.main_native.and_then(platform::work_area) { return area; } let bounds = cx .primary_display() .map(|display| display.bounds()) .unwrap_or_else(|| Bounds::new(point(px(0.), px(0.)), size(px(1280.), px(720.)))); WorkArea { left: f32::from(bounds.origin.x) as i32, top: f32::from(bounds.origin.y) as i32, right: f32::from(bounds.origin.x + bounds.size.width) as i32, bottom: f32::from(bounds.origin.y + bounds.size.height) as i32, scale: 1., } } fn call_toasts(&self, cx: &App) -> Vec<(CallToast, f32)> { let state = self.app.read(cx); let in_call = state.call.is_some(); let rings = state .rings .ringing() .map(|entry| (CallToast::Ring(entry.ring.ring_id), ring_height(in_call))); let meetings = state .meeting_toasts .entries() .iter() .map(|toast| (CallToast::Meeting(toast.id), MEETING_HEIGHT)); rings.chain(meetings).collect() } } fn call_cards_while_desktop_connected(toasts: &[(CallToast, f32)]) -> Vec<(CallToast, f32)> { toasts .iter() .copied() .filter(|(key, _)| matches!(key, CallToast::Ring(_) | CallToast::Meeting(_))) .collect() } impl NotificationCenter { /// Ring and meeting cards stay on screen when a notification service is connected. /// Chat toasts stay desktop notifications. fn sync_ring_cards(&mut self, cx: &mut Context) { let rings = call_cards_while_desktop_connected(&self.call_toasts(cx)); let stale: Vec = self .call_windows .keys() .copied() .filter(|key| !rings.iter().any(|(toast, _)| toast == key)) .collect(); for key in stale { self.close_call_window(key, cx); } let area = self.work_area(cx); let heights: Vec = rings.iter().map(|(_, height)| *height).collect(); let slots = layout::stack_slots(area, self.settings.corner, &heights, false); for ((key, _), slot) in rings.iter().zip(slots.toasts.iter()) { self.place_call_toast(*key, *slot, area, cx); } } fn finish_ring_card(&mut self, ring_id: u64, cx: &mut Context) { #[cfg(target_os = "linux")] { let still_ringing = self .app .read(cx) .rings .ringing() .any(|entry| entry.ring.ring_id == ring_id); if !still_ringing { self.queue_desktop_close(DesktopKey::Ring(ring_id)); } } self.sync_windows(cx); } fn sync_windows(&mut self, cx: &mut Context) { #[cfg(target_os = "linux")] if self.desktop.is_some() { self.sync_desktop(cx); self.sync_ring_cards(cx); return; } let visible = self.visible_ids(); let stale: Vec = self .windows .keys() .filter(|id| !visible.contains(id)) .copied() .collect(); for id in stale { self.close_window(id, cx); } let call_toasts = self.call_toasts(cx); let stale_call_toasts: Vec = self .call_windows .keys() .filter(|key| !call_toasts.iter().any(|(toast, _)| toast == *key)) .copied() .collect(); for key in stale_call_toasts { self.close_call_window(key, cx); } let area = self.work_area(cx); let mut heights: Vec = self .stack .visible() .iter() .map(|toast| { let lines = match &toast.agent { Some(agent) => wrapped_lines(&agent.body, layout::AGENT_BODY_WIDTH, cx), None => { preview_lines(&describe(toast, shows_preview(&self.settings)).preview, cx) } }; layout::toast_height(toast, lines) }) .collect(); heights.extend(call_toasts.iter().map(|(_, height)| *height)); let with_hide_all = visible.len() > 1 || self.stack.queued_count() > 0; let slots = layout::stack_slots(area, self.settings.corner, &heights, with_hide_all); for (id, slot) in visible.iter().zip(slots.toasts.iter()) { self.place_toast(*id, *slot, area, cx); } for ((key, _), slot) in call_toasts .iter() .zip(slots.toasts.iter().skip(visible.len())) { self.place_call_toast(*key, *slot, area, cx); } self.sync_pill(slots.pill, area, cx); } fn place_call_toast( &mut self, key: CallToast, slot: Slot, area: WorkArea, cx: &mut Context, ) { let Some(window) = self.call_windows.get(&key) else { self.open_call_window(key, slot, area, cx); return; }; if let Some(native) = window.native { let offset = self.slide_offset(window.opened, area); window.place(native, slot, slot.x + offset, cx); } } fn open_call_window( &mut self, key: CallToast, slot: Slot, area: WorkArea, cx: &mut Context, ) { if !self.call_opening.insert(key) { return; } let options = ring_card_options(slot, area); open_popup( options, cx, move |center, _, cx| match key { CallToast::Ring(ring_id) => { AnyView::from(cx.new(|cx| RingView::new(center, ring_id, cx))) } CallToast::Meeting(toast_id) => { AnyView::from(cx.new(|cx| MeetingToastView::new(center, toast_id, cx))) } }, move |this, window| { this.call_opening.remove(&key); if let Some(window) = window { this.call_windows.insert(key, window); } }, ); } fn close_call_window(&mut self, key: CallToast, cx: &mut Context) { let closed = self.call_windows.get(&key).is_some_and(|window| { window .handle .update(cx, |_, window, _| window.remove_window()) .is_ok() || !window_is_open(window.handle.window_id(), cx) }); if closed { self.call_windows.remove(&key); } } fn on_meeting_reminder(&mut self, cx: &mut Context) { if !self.app.read(cx).meeting_toasts.is_empty() && !self.main_window_active(cx) && let Some(native) = self.main_native { platform::flash(native); } self.sync_windows(cx); cx.notify(); } fn on_meeting_chime(&mut self, cx: &mut Context) { let busy = self.environment("", cx).busy(); if meeting_start_sound(&self.settings, busy) && !self.reminders_quiet(cx) && !self.demo_mode { sound_cache::play(CallTone::MeetingReminder.file_name(), cx); } } fn on_call_tone(&mut self, tone: CallTone, cx: &mut Context) { if !self.demo_mode { sound_cache::play(tone.file_name(), cx); } } pub fn join_meeting_toast(&mut self, id: u64, cx: &mut Context) { self.raise_main_window(cx); self.app .update(cx, |state, cx| state.join_meeting_toast(id, cx)); } fn reminders_quiet(&self, cx: &App) -> bool { platform::system_quiet() || own_do_not_disturb(self.app.read(cx)) } fn on_rings_changed(&mut self, cx: &mut Context) { let ringing = self.app.read(cx).rings.is_ringing(); if ringing && !self.main_window_active(cx) && let Some(native) = self.main_native { platform::flash(native); } self.sync_windows(cx); self.sync_ring_tone(ringing, cx); cx.notify(); } fn sync_ring_tone(&mut self, ringing: bool, cx: &mut Context) { if !ringing || self.demo_mode { self.ring_tone = None; return; } if self.ring_tone.is_some() { return; } let environment = self.environment("", cx); let native_call = self.app.read(cx).call.is_some(); if let Some(ringtone) = ringtone_for(&self.settings, native_call, environment.busy()) { self.ring_tone = Some(sound_cache::start(ringtone.file_name(), true, cx)); } } fn sync_call_sounds(&mut self, cx: &Context) { let model = self.app.read(cx).call.as_ref().map(|call| &call.model); let ringback = should_ringback(model) && !self.demo_mode; let reconnecting = model.is_some_and(|model| model.is_reconnecting() && !model.lobby) && !self.demo_mode; sync_loop(&mut self.ringback, ringback, CallTone::OutgoingRinging, cx); sync_loop( &mut self.reconnecting, reconnecting, CallTone::Reconnecting, cx, ); } fn slide_offset(&self, opened: Instant, area: WorkArea) -> i32 { if !self.animations { return 0; } let progress = (opened.elapsed().as_secs_f32() / SLIDE_DURATION.as_secs_f32()).min(1.); let eased = 1. - (1. - progress).powi(3); let distance = ((1. - eased) * SLIDE_DISTANCE * area.scale) as i32; if self.settings.corner.is_right() { distance } else { -distance } } fn place_toast(&mut self, id: u64, slot: Slot, area: WorkArea, cx: &mut Context) { if !self.windows.contains_key(&id) { self.open_toast_window(id, slot, area, cx); return; } let offset = self .windows .get(&id) .map(|window| self.slide_offset(window.opened, area)) .unwrap_or(0); if let Some(window) = self.windows.get(&id) && let Some(native) = window.native { window.place(native, slot, slot.x + offset, cx); } } fn open_toast_window(&mut self, id: u64, slot: Slot, area: WorkArea, cx: &mut Context) { if !self.opening.insert(id) { return; } open_popup( popup_options(slot, area), cx, move |center, window, cx| cx.new(|cx| ToastView::new(center, id, window, cx)), move |this, window| { this.opening.remove(&id); if let Some(window) = window { this.windows.insert(id, window); } }, ); } fn sync_pill(&mut self, slot: Option, area: WorkArea, cx: &mut Context) { let Some(slot) = slot else { if let Some(pill) = self.pill.take() { pill.handle .update(cx, |_, window, _| window.remove_window()) .ok(); } return; }; if self.pill.is_none() && !self.pill_opening { self.pill_opening = true; open_popup( popup_options(slot, area), cx, |center, _, cx| cx.new(|cx| PillView::new(center, cx)), |this, window| { this.pill_opening = false; this.pill = window; }, ); } if let Some(pill) = self.pill.as_ref() && let Some(native) = pill.native { pill.place(native, slot, slot.x, cx); } } fn close_window(&mut self, id: u64, cx: &mut Context) { let closed = self.windows.get(&id).is_some_and(|window| { window .handle .update(cx, |_, window, _| window.remove_window()) .is_ok() || !window_is_open(window.handle.window_id(), cx) }); if closed { self.windows.remove(&id); } } fn drop_toast(&mut self, id: u64, cx: &mut Context) { #[cfg(target_os = "linux")] self.queue_desktop_close(DesktopKey::Message(id)); let fast = self.animated(FAST_FADE); self.stack.dismiss(id, Instant::now(), fast); cx.notify(); } pub fn hide_all(&mut self, cx: &mut Context) { for id in self.stack.ids() { self.drop_toast(id, cx); } } fn sync_hover_hold(&mut self, now: Instant) { let any_hovered = self.stack.any_hovered(); if !any_hovered && !self.hover_hold { return; } if any_hovered { let fast = self.animated(FAST_FADE); self.stack.restore(now, fast); } for id in self.stack.ids() { if let Some(toast) = self.stack.get_mut(id) && !toast.queued { if any_hovered { toast.timer.pause(now); } else if !toast.holds_open() { toast.timer.resume(now); } } } self.hover_hold = any_hovered; } fn is_dismissed(&self, id: u64) -> bool { self.stack.get(id).is_none_or(|toast| toast.dismissed) } fn tick(&mut self, cx: &mut Context) { let now = Instant::now(); let (fade_in, slow) = (self.animated(FADE_IN), self.animated(SLOW_FADE)); for id in self.stack.expired(now) { self.stack.fade_out(id, now, slow); } for id in self.stack.gone(now) { self.stack.remove(id); } self.stack.promote(now, fade_in); self.sync_hover_hold(now); if !self.urgent_repeats.is_empty() { self.repeat_urgent(cx); } if !self.app.read(cx).rings.is_empty() { self.app.update(cx, |state, cx| state.tick_rings(cx)); } if self .app .read(cx) .meeting_toasts .is_due_for_check(Utc::now()) { let show = !self.reminders_quiet(cx); self.app .update(cx, |state, cx| state.tick_meeting_reminders(show, cx)); } let needs_sync = !self.stack.is_empty() || !self.windows.is_empty() || self.pill.is_some() || !self.call_windows.is_empty() || self.app.read(cx).rings.is_ringing() || !self.app.read(cx).meeting_toasts.is_empty(); #[cfg(target_os = "linux")] let needs_sync = needs_sync || !self.desktop_close.is_empty() || !self.desktop_published.is_empty(); #[cfg(target_os = "linux")] if self .desktop .as_ref() .is_some_and(DesktopNotifications::failed) { self.desktop = None; self.desktop_published.clear(); } // Poll desktop actions before sync so dismiss/reply land in the same tick. #[cfg(target_os = "linux")] if self.desktop.is_some() { self.poll_desktop(cx); } if needs_sync { self.sync_windows(cx); cx.notify(); } self.poll_tray(cx); if single_instance::take_activation() { self.raise_main_window(cx); } for command in single_instance::take_commands() { self.app .update(cx, |state, cx| state.run_remote_command(&command, cx)); } } fn repeat_urgent(&mut self, cx: &mut Context) { let sidebar = &self.app.read(cx).sidebar; self.urgent_repeats.stop_read(|conversation_id| { sidebar .chats .iter() .find(|chat| chat.id == conversation_id) .and_then(|chat| chat.last_read_at.filter(|_| !chat.unread)) }); for incoming in self.urgent_repeats.due(Utc::now()) { let environment = self.environment(&incoming.conversation_id, cx); if environment.chat_in_foreground { self.urgent_repeats .stop_conversation(&incoming.conversation_id); continue; } self.stack.remove_conversation(&incoming.conversation_id); let decision = decide(&self.settings, &incoming, environment); self.present(&incoming, decision, cx); if should_flash(&self.settings, decision.toast, self.main_window_active(cx)) && let Some(native) = self.main_native { platform::flash(native); } } } #[cfg(target_os = "linux")] fn queue_desktop_close(&mut self, key: DesktopKey) { self.desktop_close.push(key.replace_token()); } #[cfg(target_os = "linux")] fn message_labels() -> MessageLabels { MessageLabels { mark_read: crate::i18n::tr("notify.mark_read"), reply: crate::i18n::tr("notify.reply"), } } #[cfg(target_os = "linux")] fn ring_labels() -> RingLabels { RingLabels { decline: crate::i18n::tr("notify.decline"), accept: crate::i18n::tr("notify.accept"), audio: crate::i18n::tr("notify.audio"), video: crate::i18n::tr("notify.video"), } } #[cfg(target_os = "linux")] fn meeting_labels() -> MeetingLabels { MeetingLabels { join: crate::i18n::tr("notify.join"), snooze: crate::i18n::tr("notify.snooze"), } } #[cfg(target_os = "linux")] fn to_bus(payload: DesktopPayload, image: Option) -> BusNotification { BusNotification { logical_key: payload.key.replace_token(), replace_key: payload.replace_key, summary: payload.summary, body: payload.body, actions: payload .actions .into_iter() .map(|action| (action.id.to_owned(), action.label)) .collect(), timeout_ms: payload.timeout_ms, urgency: payload.urgency as u8, category: payload.category.to_owned(), image, } } #[cfg(target_os = "linux")] fn avatar_notification_image( &mut self, state: &AppState, user_id: Option<&str>, ) -> Option { use crate::data::AvatarState; use image::imageops::FilterType; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; let user_id = user_id?; let AvatarState::Ready(photo) = state.directory.avatar(user_id)? else { return None; }; let bytes = photo.source_bytes(); let mut hasher = DefaultHasher::new(); bytes.hash(&mut hasher); let fingerprint = hasher.finish(); if let Some((cached_fp, image)) = self.desktop_avatar_cache.get(user_id) && *cached_fp == fingerprint { return Some(image.clone()); } let decoded = image::load_from_memory(bytes).ok()?; let rgba = decoded .resize_exact(64, 64, FilterType::Lanczos3) .into_rgba8(); let image = NotificationImage { width: rgba.width(), height: rgba.height(), rgba: rgba.into_raw(), }; self.desktop_avatar_cache .insert(user_id.to_owned(), (fingerprint, image.clone())); Some(image) } #[cfg(target_os = "linux")] fn sync_desktop(&mut self, cx: &mut Context) { if self.desktop.is_none() { return; } let preview_on = shows_preview(&self.settings); let message_labels = Self::message_labels(); let ring_labels = Self::ring_labels(); let meeting_labels = Self::meeting_labels(); let mut visible = Vec::new(); let mut visible_logical = HashSet::new(); let mut used_avatars = HashSet::new(); let message_toasts: Vec<_> = self.stack.visible().to_vec(); let (ring_payloads, meeting_payloads) = { let state = self.app.read(cx); let rings: Vec<_> = state .rings .ringing() .map(|entry| { ( desktop_payload::ring_payload( entry.ring.ring_id, entry.caller_name(), entry.subtitle(), entry.ring.video, &ring_labels, ), entry.caller_user_id(), ) }) .collect(); let now = Utc::now(); let offset = Local::now().offset().fix(); let meetings: Vec<_> = state .meeting_toasts .entries() .iter() .map(|toast| { let body = crate::call::meeting_subtitle(toast, now, offset); desktop_payload::meeting_payload(toast, &body, &meeting_labels) }) .collect(); (rings, meetings) }; for toast in &message_toasts { if let Some(user_id) = toast.sender_id.as_deref() { used_avatars.insert(user_id.to_owned()); } let image = self.avatar_notification_image(self.app.read(cx), toast.sender_id.as_deref()); let payload = desktop_payload::message_payload(toast, preview_on, &message_labels); visible_logical.insert(payload.key.replace_token()); visible.push(Self::to_bus(payload, image)); } for (payload, caller_id) in ring_payloads { if let Some(user_id) = caller_id.as_deref() { used_avatars.insert(user_id.to_owned()); } let image = self.avatar_notification_image(self.app.read(cx), caller_id.as_deref()); visible_logical.insert(payload.key.replace_token()); visible.push(Self::to_bus(payload, image)); } for payload in meeting_payloads { visible_logical.insert(payload.key.replace_token()); visible.push(Self::to_bus(payload, None)); } self.desktop_avatar_cache .retain(|user_id, _| used_avatars.contains(user_id)); let mut close = std::mem::take(&mut self.desktop_close); for previous in &self.desktop_published { if visible_logical.contains(previous) { continue; } if previous.starts_with("ring:") || previous.starts_with("meeting:") { close.push(previous.clone()); } } close.sort(); close.dedup(); if let Some(desktop) = &self.desktop { desktop.sync(visible, close); } self.desktop_published = visible_logical; } #[cfg(target_os = "linux")] fn poll_desktop(&mut self, cx: &mut Context) { let Some(desktop) = &self.desktop else { return; }; let events = desktop.poll(); for event in events { match event { NotificationEvent::Action { logical_key, action_id, } => self.handle_desktop_action(&logical_key, &action_id, cx), NotificationEvent::Reply { logical_key, text } => { if let Some(DesktopKey::Message(id)) = parse_logical_key(&logical_key) { self.submit_reply(id, text, cx); } } NotificationEvent::Closed { logical_key, reason, } => { if reason == CLOSED_BY_USER && let Some(DesktopKey::Meeting(toast_id)) = parse_logical_key(&logical_key) { self.app .update(cx, |state, cx| state.dismiss_meeting_toast(toast_id, cx)); } } } } } #[cfg(target_os = "linux")] fn handle_desktop_action( &mut self, logical_key: &str, action_id: &str, cx: &mut Context, ) { let Some(key) = parse_logical_key(logical_key) else { return; }; match key { DesktopKey::Message(id) if action_id == action::DEFAULT || action_id == action::REPLY || action_id == "reply-open" => { self.activate(id, cx); } DesktopKey::Message(id) if action_id == action::MARK_READ => self.mark_read(id, cx), DesktopKey::Ring(ring_id) if action_id == action::DECLINE => { self.queue_desktop_close(DesktopKey::Ring(ring_id)); self.app .update(cx, |state, cx| state.decline_ring(ring_id, cx)); } DesktopKey::Ring(ring_id) if action_id == action::ACCEPT_AUDIO => { self.queue_desktop_close(DesktopKey::Ring(ring_id)); self.accept_ring(ring_id, calling::AcceptMode::Audio, cx); } DesktopKey::Ring(ring_id) if action_id == action::ACCEPT_VIDEO => { self.queue_desktop_close(DesktopKey::Ring(ring_id)); self.accept_ring(ring_id, calling::AcceptMode::Video, cx); } DesktopKey::Meeting(toast_id) if action_id == action::JOIN || action_id == action::DEFAULT => { self.queue_desktop_close(DesktopKey::Meeting(toast_id)); self.join_meeting_toast(toast_id, cx); } DesktopKey::Meeting(toast_id) if action_id == action::SNOOZE => { self.queue_desktop_close(DesktopKey::Meeting(toast_id)); self.app .update(cx, |state, cx| state.snooze_meeting_toast(toast_id, cx)); } _ => {} } } fn poll_tray(&mut self, cx: &mut Context) { let commands = self.tray.as_ref().map(Tray::poll).unwrap_or_default(); for command in commands { match command { TrayCommand::Toggle => self.toggle_main_window(cx), TrayCommand::Open => self.raise_main_window(cx), TrayCommand::SetStatus(kind) => { let forced = ForcedAvailability { kind, expires_at: None, }; self.app .update(cx, |state, cx| state.set_own_availability(Some(forced), cx)); self.sync_tray(cx); } TrayCommand::SetStatusDuration(duration) => { let Some(kind) = self .app .read(cx) .own_status .forced .map(|forced| forced.kind) .filter(|kind| *kind != ForcedKind::Available) else { continue; }; let forced = ForcedAvailability { kind, expires_at: Some(duration.expires_at(Local::now())), }; self.app .update(cx, |state, cx| state.set_own_availability(Some(forced), cx)); self.sync_tray(cx); } TrayCommand::ResetStatus => { self.app .update(cx, |state, cx| state.set_own_availability(None, cx)); self.sync_tray(cx); } TrayCommand::Notifications => { self.raise_main_window(cx); self.app.update(cx, |state, cx| { state.open_settings(SettingsSection::Notifications, cx) }); } TrayCommand::Quit => cx.quit(), } } } fn toggle_main_window(&mut self, cx: &mut Context) { if self.main_window_active(cx) { if let Some(native) = self.main_native { platform::hide_window(native); } else { #[cfg(any(target_os = "linux", target_os = "macos"))] crate::main_window::hide(cx); } } else { self.raise_main_window(cx); } } pub fn accept_ring(&mut self, ring_id: u64, mode: calling::AcceptMode, cx: &mut Context) { self.raise_main_window(cx); self.app .update(cx, |state, cx| state.accept_ring(ring_id, mode, cx)); self.finish_ring_card(ring_id, cx); } pub fn decline_ring(&mut self, ring_id: u64, cx: &mut Context) { self.app .update(cx, |state, cx| state.decline_ring(ring_id, cx)); self.finish_ring_card(ring_id, cx); } fn raise_main_window(&mut self, cx: &mut Context) { #[cfg(any(target_os = "linux", target_os = "macos"))] if crate::main_window::is_hidden(cx) { crate::main_window::show(cx); return; } if let Some(native) = self.main_native { platform::restore_and_raise(native); } self.main_window .update(cx, |_, window, _| window.activate_window()) .ok(); } fn apply_app_icon(&mut self, icon: AppIcon, cx: &mut Context) { if icon == self.app_icon { return; } self.app_icon = icon; let mention = !self.unread_mentions.is_empty(); if let Some(tray) = &mut self.tray { tray.set_app_icon(icon.png(), mention); } let _ = self.main_window.update(cx, |_, window, _| { platform::set_window_icon(window, icon.png()) }); } fn show_in_tray(&mut self, shown: bool, cx: &mut Context) { if !shown { self.tray = None; self.last_tray_presence = None; } else if self.tray.is_none() && !self.demo_mode { let presence = tray_presence_from(self.app.read(cx), !self.unread_mentions.is_empty()); self.tray = Tray::new(presence, self.app_icon.png()); self.last_tray_presence = None; } } fn relocalize_tray(&self) { if let Some(tray) = &self.tray { tray.relocalize(); } } fn sync_tray(&mut self, cx: &App) { let Some(tray) = &self.tray else { return; }; let presence = tray_presence_from(self.app.read(cx), !self.unread_mentions.is_empty()); if self.last_tray_presence.as_ref() == Some(&presence) { return; } tray.sync(presence.clone()); self.last_tray_presence = Some(presence); } fn refresh_badge(&mut self, cx: &mut Context) { let state = self.app.read(cx); let count = taskbar_badge_count( &state.sidebar, self.activity.read(cx).feed(), state.directory.section_settings.adaptive_rail(), ) + crate::agent_api::unseen_proposal_count(cx); let still_unread = unread_conversation_ids(&state.sidebar); self.unread_mentions .retain(|conversation_id| still_unread.contains(conversation_id.as_str())); let badge = badge_for(count); let mention_dot = !self.unread_mentions.is_empty(); if badge == self.shown_badge && mention_dot == self.shown_mention_dot { return; } self.shown_mention_dot = mention_dot; if badge != self.shown_badge && let Some(native) = self.main_native { platform::set_badge(native, badge.as_ref()); if badge.is_none() && self.shown_badge.is_some() { platform::stop_flash(native); } } self.shown_badge = badge; self.sync_tray(cx); } pub fn set_hover(&mut self, id: u64, hovered: bool, cx: &mut Context) { let now = Instant::now(); let Some(toast) = self.stack.get_mut(id) else { return; }; if toast.hovered == hovered { return; } toast.hovered = hovered; self.sync_hover_hold(now); cx.notify(); } pub fn dismiss(&mut self, id: u64, cx: &mut Context) { self.drop_toast(id, cx); } pub fn open_reply(&mut self, id: u64, cx: &mut Context) -> Option { let now = Instant::now(); let toast = self.stack.get_mut(id)?; toast.reply = ReplyState::Open; toast.timer.pause(now); let draft = toast.reply_text.clone(); cx.notify(); Some(draft) } pub fn close_reply(&mut self, id: u64, cx: &mut Context) { if let Some(toast) = self.stack.get_mut(id) { toast.reply = ReplyState::Closed; toast.reply_text.clear(); toast.hovered = false; } cx.notify(); } pub fn submit_reply(&mut self, id: u64, text: String, cx: &mut Context) { let Some(toast) = self.stack.get_mut(id) else { return; }; toast.reply_text = text.clone(); let conversation_id = toast.conversation_id.clone(); let message_id = toast.message_id.clone(); let is_channel = matches!(toast.kind, ChatKind::Channel { .. }); let state = self.app.read(cx); let (mode, engine) = (state.mode, state.engine.clone()); let outcome: Result<(), ()> = if mode.demo { Ok(()) } else if mode.read_only { Err(()) } else if let Some(engine) = engine { let receiver = runtime::spawn(async move { if is_channel { engine.reply_to(&conversation_id, &message_id, &text).await } else { engine.send_message(&conversation_id, &text, None).await } .map(|_| ()) }); cx.spawn(async move |this, cx| { let sent = matches!(receiver.await, Ok(Ok(()))); this.update(cx, |center, cx| center.finish_reply(id, sent, cx)) .ok(); }) .detach(); return; } else { Err(()) }; self.finish_reply(id, outcome.is_ok(), cx); } fn finish_reply(&mut self, id: u64, sent: bool, cx: &mut Context) { let Some(toast) = self.stack.get_mut(id) else { return; }; toast.reply = if sent { ReplyState::Sent } else { ReplyState::Failed }; let conversation_id = toast.conversation_id.clone(); cx.notify(); if sent { cx.spawn(async move |this, cx| { cx.background_executor().timer(SENT_DURATION).await; this.update(cx, |center, cx| { center.mark_conversation_read(&conversation_id, cx); center.drop_toast(id, cx); }) .ok(); }) .detach(); } } fn mark_conversation_read(&mut self, conversation_id: &str, cx: &mut Context) { self.unread_mentions.remove(conversation_id); let conversation_id = conversation_id.to_owned(); self.app .update(cx, |state, cx| state.mark_chat_read(&conversation_id, cx)); self.refresh_badge(cx); } pub fn mark_read(&mut self, id: u64, cx: &mut Context) { if self.is_dismissed(id) { return; } let Some(conversation_id) = self .stack .get(id) .map(|toast| toast.conversation_id.clone()) else { return; }; self.mark_conversation_read(&conversation_id, cx); self.drop_toast(id, cx); } pub fn activate(&mut self, id: u64, cx: &mut Context) { if self.is_dismissed(id) { return; } if let Some((org, conversation_id)) = self .stack .get(id) .and_then(|toast| Some((toast.org.clone()?, toast.conversation_id.clone()))) { self.drop_toast(id, cx); self.app.update(cx, |state, cx| { state.switch_org(&org, Some(&conversation_id), cx) }); return; } let Some((conversation_id, message_id, proposal_id)) = self.stack.get(id).map(|toast| { ( toast.conversation_id.clone(), toast.message_id.clone(), toast .agent .as_ref() .and_then(|agent| agent.proposal_id().map(str::to_owned)), ) }) else { return; }; self.drop_toast(id, cx); if let Some(proposal_id) = proposal_id { agent_api::mark_proposal_seen(&proposal_id, cx); } self.raise_main_window(cx); let selection = selection_for(&self.app.read(cx).sidebar, &conversation_id); if let Some(selection) = selection { self.app.update(cx, |state, cx| { if message_id.is_empty() { state.select(selection, cx) } else { state.jump_to_message(selection, message_id, cx) } }); } } pub fn send_test_notification(&mut self, cx: &mut Context) { let incoming = Incoming { conversation_id: "test-notification".to_owned(), message_id: "test".to_owned(), kind: ChatKind::Direct, chat_title: "Mara Lindqvist".to_owned(), sender_id: None, sender_name: "Mara Lindqvist".to_owned(), preview: Preview::Text("This is a test notification.".to_owned()), mentions_me: false, muted: false, signals: Default::default(), chat: Default::default(), created_at: Utc::now(), importance: Default::default(), }; let decision = Decision { toast: true, sound: self.settings.sounds.notification_sound, urgent_sound: false, }; self.throttle = SoundThrottle::default(); self.present(&incoming, decision, cx); } fn show_demo_toasts(&mut self, cx: &mut Context) { for incoming in demo_incoming() { let decision = Decision { toast: true, sound: false, urgent_sound: false, }; self.present(&incoming, decision, cx); } } } /// Opens a window outside the current update: `open_window` draws right away, and every /// notification view reads the center while rendering. fn open_popup>( options: WindowOptions, cx: &mut Context, build: impl FnOnce(Entity, &mut Window, &mut App) -> V + 'static, opened: impl FnOnce(&mut NotificationCenter, Option) + 'static, ) { let center = cx.entity(); cx.defer(move |cx| { let view_center = center.clone(); let Ok(handle) = cx.open_window(options, move |window, cx| { let view = build(view_center, window, cx); cx.new(|cx| base::Root::new(view, window, cx).bg(transparent_black())) }) else { center.update(cx, |this, _| opened(this, None)); return; }; let handle = AnyWindowHandle::from(handle); let native = handle .update(cx, |_, window, _| platform::native_handle(window)) .ok() .flatten(); if let Some(native) = native { platform::prepare_toast_window(native); } let window = OpenWindow { handle, native, opened: Instant::now(), placed: Cell::new(None), }; center.update(cx, |this, _| opened(this, Some(window))); }); } fn window_is_open(window_id: WindowId, cx: &App) -> bool { cx.windows() .iter() .any(|window| window.window_id() == window_id) } fn own_presence(state: &AppState) -> PresenceKind { state .directory .me .as_ref() .map_or(PresenceKind::Unknown, |me| { state.directory.presence_of(&me.user_id).kind() }) } fn own_do_not_disturb(state: &AppState) -> bool { own_presence(state) == PresenceKind::DoNotDisturb } fn tray_presence_from(state: &AppState, mention: bool) -> TrayPresence { let summary = own_status::state_summary(&state.own_status, own_presence(state), &Local::now()); let title = match &summary.until { Some(until) => format!("{} {until}", summary.label), None => summary.label.to_owned(), }; TrayPresence::new( title, state.own_status.forced.map(|forced| forced.kind), mention, ) } fn sync_loop(handle: &mut Option, audible: bool, tone: CallTone, cx: &App) { match (audible, handle.is_some()) { (true, false) => *handle = Some(sound_cache::start(tone.file_name(), true, cx)), (false, true) => *handle = None, _ => {} } } fn demo_scene() -> Option { DemoScene::from_name(&std::env::var(DEMO_CALL_ENV).ok()?) } /// `TEAMS_DEMO_RING=` rings a fake incoming call that long after the demo starts. fn demo_ring_delay() -> Option { let seconds: f32 = std::env::var(DEMO_RING_ENV).ok()?.trim().parse().ok()?; (seconds >= 0.).then(|| Duration::from_secs_f32(seconds)) } fn first_lines(text: &str, count: usize) -> String { text.lines() .map(str::trim) .filter(|line| !line.is_empty()) .take(count) .collect::>() .join("\n") } fn preview_lines(text: &str, cx: &App) -> usize { wrapped_lines(text, layout::PREVIEW_WIDTH, cx) } fn wrapped_lines(text: &str, width: f32, cx: &App) -> usize { let mut wrapper = cx .text_system() .line_wrapper(font(crate::theme::font_family()), px(layout::PREVIEW_SIZE)); text.split('\n') .map(|line| { let fragments = [LineFragment::text(line)]; wrapper .wrap_line(&fragments, px(width), IndentAdjustment::NoIndent) .count() + 1 }) .sum() } #[cfg(target_os = "linux")] const CLOSED_BY_USER: u32 = 2; #[cfg(target_os = "linux")] fn parse_logical_key(key: &str) -> Option { let (kind, id) = key.split_once(':')?; let id = id.parse().ok()?; match kind { "message" => Some(DesktopKey::Message(id)), "ring" => Some(DesktopKey::Ring(id)), "meeting" => Some(DesktopKey::Meeting(id)), _ => None, } } fn ring_card_options(slot: Slot, area: WorkArea) -> WindowOptions { // Wayland treats PopUp as a normal toplevel, so Hyprland tiles ring and meeting cards. #[cfg(target_os = "linux")] { let mut options = popup_options(slot, area); options.kind = WindowKind::Floating; return options; } #[cfg(not(target_os = "linux"))] popup_options(slot, area) } fn popup_options(slot: Slot, area: WorkArea) -> WindowOptions { let scale = area.scale; let bounds = Bounds::new( point(px(slot.x as f32 / scale), px(slot.y as f32 / scale)), size( px(slot.width as f32 / scale), px(slot.height as f32 / scale), ), ); WindowOptions { window_bounds: Some(WindowBounds::Windowed(bounds)), titlebar: None, focus: false, show: true, kind: WindowKind::PopUp, is_movable: false, is_resizable: false, is_minimizable: false, window_background: WindowBackgroundAppearance::Transparent, ..Default::default() } } pub fn unread_conversation_ids(sidebar: &Sidebar) -> HashSet<&str> { let chats = sidebar.chats.iter().filter(|chat| chat.unread); let channels = sidebar .teams .iter() .flat_map(|team| team.channels.iter()) .filter(|channel| channel.unread); chats .map(|chat| chat.id.as_str()) .chain(channels.map(|channel| channel.id.as_str())) .collect() } fn demo_incoming() -> Vec { let item = |conversation: &str, kind: ChatKind, title: &str, sender: &str, text: &str, mention: bool| Incoming { conversation_id: conversation.to_owned(), message_id: format!("{conversation}-message"), kind, chat_title: title.to_owned(), sender_id: None, sender_name: sender.to_owned(), preview: Preview::Text(text.to_owned()), mentions_me: mention, muted: false, signals: Default::default(), chat: Default::default(), created_at: Utc::now(), importance: Default::default(), }; vec![ item( "demo-toast-direct", ChatKind::Direct, "Tobias Klein", "Tobias Klein", "Sounds good, I will look at it tomorrow.", false, ), item( "demo-toast-group", ChatKind::Group { member_count: 5 }, "Retro-Team", "Priya Nair", "Please add topics by 5 pm.", false, ), item( "demo-toast-mention", ChatKind::Channel { team: "Platform".to_owned(), channel: "Releases".to_owned(), }, "Releases", "Mara Lindqvist", "@Jonas can you approve the merge? The pipeline is waiting.", true, ), item( "demo-toast-lea", ChatKind::Direct, "Lea Schneider", "Lea Schneider", "Lunch at 12?", false, ), item( "demo-toast-jonas", ChatKind::Direct, "Jonas Ortega", "Jonas Ortega", "Deploy window moved to Thursday 6 pm.", false, ), ] } #[cfg(test)] mod tests { use store::{ChannelRecord, ChatRecord, SidebarTeam, TeamRecord}; use std::collections::HashSet; use gpui_kit::{WindowBackgroundAppearance, WindowKind}; use super::{Slot, WorkArea, popup_options, preview_lines, unread_conversation_ids}; use store::Sidebar; #[test] fn toast_windows_ask_for_a_transparent_background() { let slot = Slot { x: 0, y: 0, width: 360, height: 120, }; let area = WorkArea { left: 0, top: 0, right: 1920, bottom: 1080, scale: 1., }; let options = popup_options(slot, area); assert_eq!( options.window_background, WindowBackgroundAppearance::Transparent ); assert_eq!(options.kind, WindowKind::PopUp); } #[cfg(target_os = "linux")] #[test] fn linux_ring_card_is_a_floating_window() { use super::ring_card_options; let slot = Slot { x: 10, y: 20, width: 360, height: 140, }; let area = WorkArea { left: 0, top: 0, right: 1920, bottom: 1080, scale: 1., }; let options = ring_card_options(slot, area); assert_eq!(options.kind, WindowKind::Floating); assert!(!options.focus); } #[test] fn call_cards_while_desktop_connected_keep_rings_and_meetings() { use super::{CallToast, call_cards_while_desktop_connected}; let toasts = vec![ (CallToast::Ring(7), 140.), (CallToast::Meeting(3), 96.), (CallToast::Ring(9), 140.), ]; let cards = call_cards_while_desktop_connected(&toasts); assert_eq!( cards, vec![ (CallToast::Ring(7), 140.), (CallToast::Meeting(3), 96.), (CallToast::Ring(9), 140.) ] ); } #[cfg(target_os = "linux")] #[test] fn ring_card_close_token_matches_the_published_ring() { use super::DesktopKey; assert_eq!(DesktopKey::Ring(7).replace_token(), "ring:7"); } fn sidebar() -> Sidebar { Sidebar { chats: vec![ ChatRecord { id: "a".into(), unread: true, ..Default::default() }, ChatRecord { id: "b".into(), unread: false, ..Default::default() }, ], teams: vec![SidebarTeam { rights: Default::default(), team: TeamRecord { id: "t".into(), name: "Team".into(), }, channels: vec![ChannelRecord { id: "ch".into(), team_id: "t".into(), name: "General".into(), membership_type: None, last_message_at: None, unread: true, }], hidden: false, hidden_channel_ids: Vec::new(), notifications: Default::default(), mentions: Default::default(), }], } } #[test] fn unread_conversation_ids_hold_chats_and_channels() { let sidebar = sidebar(); assert_eq!( unread_conversation_ids(&sidebar), HashSet::from(["a", "ch"]) ); } #[gpui_kit::test] fn preview_lines_follow_the_wrapped_text(cx: &mut gpui_kit::TestAppContext) { cx.update(|cx| { assert_eq!(preview_lines("ok", cx), 1); assert_eq!(preview_lines("a\nb", cx), 2); let long = "Cristina: ok, thanks for the info! I think not now ".repeat(3); assert!(preview_lines(&long, cx) >= 2); }); } }