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