| 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, Slot}; |
| 11 | use super::platform::{self, NativeHandle, Tray, TrayCommand, WorkArea}; |
| 12 | use super::rules::{ |
| 13 | ChatKind, Decision, Environment, Incoming, Preview, Settings, SoundThrottle, decide, |
| 14 | should_flash, |
| 15 | }; |
| 16 | use super::settings; |
| 17 | use super::settings_view::SettingsView; |
| 18 | use super::stack::{ |
| 19 | FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE, ToastModel, ToastStack, |
| 20 | }; |
| 21 | use super::text::describe; |
| 22 | use super::toast::{PillView, ToastView}; |
| 23 | use crate::app_state::{AppEvent, AppState, Selection}; |
| 24 | use crate::data::{self, Directory, PresenceKind}; |
| 25 | use crate::runtime; |
| 26 | |
| 27 | const TICK: Duration = Duration::from_millis(33); |
| 28 | const SLIDE_DURATION: Duration = Duration::from_millis(180); |
| 29 | const SLIDE_DISTANCE: f32 = 48.; |
| 30 | const DEMO_SPEC_DELAY: Duration = Duration::from_secs(3); |
| 31 | |
| 32 | struct OpenWindow { |
| 33 | handle: AnyWindowHandle, |
| 34 | native: Option<NativeHandle>, |
| 35 | opened: Instant, |
| 36 | } |
| 37 | |
| 38 | impl OpenWindow { |
| 39 | fn place(&self, native: NativeHandle, slot: Slot, x: i32, cx: &mut App) { |
| 40 | platform::place(native, x, slot.y, slot.width, slot.height); |
| 41 | // WM_SIZE arrives while the app is borrowed, so GPUI drops its own resize report. |
| 42 | self.handle |
| 43 | .update(cx, |_, window, cx| window.bounds_changed(cx)) |
| 44 | .ok(); |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | pub struct NotificationCenter { |
| 49 | app: Entity<AppState>, |
| 50 | main_window: AnyWindowHandle, |
| 51 | main_native: Option<NativeHandle>, |
| 52 | settings: Settings, |
| 53 | stack: ToastStack, |
| 54 | tracker: IncomingTracker, |
| 55 | throttle: SoundThrottle, |
| 56 | windows: HashMap<u64, OpenWindow>, |
| 57 | opening: HashSet<u64>, |
| 58 | pill: Option<OpenWindow>, |
| 59 | pill_opening: bool, |
| 60 | hover_hold: bool, |
| 61 | settings_window: Option<AnyWindowHandle>, |
| 62 | settings_opening: bool, |
| 63 | unread_mentions: HashSet<String>, |
| 64 | tray: Option<Tray>, |
| 65 | shown_badge: Option<Badge>, |
| 66 | animations: bool, |
| 67 | _subscription: Subscription, |
| 68 | } |
| 69 | |
| 70 | impl NotificationCenter { |
| 71 | pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self { |
| 72 | let settings = settings::load(&app.read(cx).store); |
| 73 | let tray = if app.read(cx).mode.demo { |
| 74 | None |
| 75 | } else { |
| 76 | Tray::new(settings.sound, settings.do_not_disturb) |
| 77 | }; |
| 78 | let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| { |
| 79 | this.on_app_event(event, cx); |
| 80 | }); |
| 81 | let center = NotificationCenter { |
| 82 | main_window: window.window_handle(), |
| 83 | main_native: platform::native_handle(window), |
| 84 | settings, |
| 85 | stack: ToastStack::default(), |
| 86 | tracker: IncomingTracker::new(Utc::now()), |
| 87 | throttle: SoundThrottle::default(), |
| 88 | windows: HashMap::new(), |
| 89 | opening: HashSet::new(), |
| 90 | pill: None, |
| 91 | pill_opening: false, |
| 92 | hover_hold: false, |
| 93 | settings_window: None, |
| 94 | settings_opening: false, |
| 95 | unread_mentions: HashSet::new(), |
| 96 | tray, |
| 97 | shown_badge: None, |
| 98 | animations: platform::animations_enabled(), |
| 99 | app, |
| 100 | _subscription: subscription, |
| 101 | }; |
| 102 | cx.spawn(async move |this, cx| { |
| 103 | loop { |
| 104 | cx.background_executor().timer(TICK).await; |
| 105 | if this.update(cx, |center, cx| center.tick(cx)).is_err() { |
| 106 | break; |
| 107 | } |
| 108 | } |
| 109 | }) |
| 110 | .detach(); |
| 111 | if center.app.read(cx).mode.demo { |
| 112 | cx.spawn(async move |this, cx| { |
| 113 | cx.background_executor().timer(DEMO_SPEC_DELAY).await; |
| 114 | this.update(cx, |center, cx| center.show_demo_toasts(cx)) |
| 115 | .ok(); |
| 116 | }) |
| 117 | .detach(); |
| 118 | } |
| 119 | center |
| 120 | } |
| 121 | |
| 122 | pub fn settings(&self) -> &Settings { |
| 123 | &self.settings |
| 124 | } |
| 125 | |
| 126 | pub fn model(&self, id: u64) -> Option<&ToastModel> { |
| 127 | self.stack.get(id) |
| 128 | } |
| 129 | |
| 130 | pub fn queued_count(&self) -> usize { |
| 131 | self.stack.queued_count() |
| 132 | } |
| 133 | |
| 134 | pub fn stack_opacity(&self) -> f32 { |
| 135 | let now = Instant::now(); |
| 136 | self.stack |
| 137 | .visible() |
| 138 | .iter() |
| 139 | .map(|toast| toast.opacity(now)) |
| 140 | .fold(0., f32::max) |
| 141 | } |
| 142 | |
| 143 | fn animated(&self, duration: Duration) -> Duration { |
| 144 | if self.animations { duration } else { Duration::ZERO } |
| 145 | } |
| 146 | |
| 147 | pub fn directory<'a>(&self, cx: &'a App) -> &'a Directory { |
| 148 | &self.app.read(cx).directory |
| 149 | } |
| 150 | |
| 151 | pub fn reply_text(&self, id: u64) -> Option<String> { |
| 152 | self.stack.get(id).map(|toast| toast.reply_text.clone()) |
| 153 | } |
| 154 | |
| 155 | pub fn intercept_close(&self, _cx: &App) -> bool { |
| 156 | match (self.settings.close_to_tray, &self.tray, self.main_native) { |
| 157 | (true, Some(_), Some(native)) => { |
| 158 | platform::hide_window(native); |
| 159 | true |
| 160 | } |
| 161 | _ => false, |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | pub fn update_settings(&mut self, cx: &mut Context<Self>, change: impl FnOnce(&mut Settings)) { |
| 166 | change(&mut self.settings); |
| 167 | settings::save(&self.app.read(cx).store, &self.settings); |
| 168 | self.sync_tray(); |
| 169 | cx.notify(); |
| 170 | } |
| 171 | |
| 172 | fn on_app_event(&mut self, event: &AppEvent, cx: &mut Context<Self>) { |
| 173 | match event { |
| 174 | AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx), |
| 175 | AppEvent::Selection => self.on_selection(cx), |
| 176 | AppEvent::Sidebar => self.refresh_badge(cx), |
| 177 | _ => {} |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | fn on_selection(&mut self, cx: &mut Context<Self>) { |
| 182 | let selected = self |
| 183 | .app |
| 184 | .read(cx) |
| 185 | .selection |
| 186 | .as_ref() |
| 187 | .map(|selection| selection.conversation_id().to_owned()); |
| 188 | if let Some(conversation_id) = selected { |
| 189 | self.unread_mentions.remove(&conversation_id); |
| 190 | self.stack.remove_conversation(&conversation_id); |
| 191 | } |
| 192 | self.refresh_badge(cx); |
| 193 | } |
| 194 | |
| 195 | fn on_messages(&mut self, conversation_id: &str, cx: &mut Context<Self>) { |
| 196 | let state = self.app.read(cx); |
| 197 | let my_user_id = state.directory.me.as_ref().map(|me| me.user_id.clone()); |
| 198 | let found = self.tracker.collect( |
| 199 | &state.store, |
| 200 | &state.sidebar, |
| 201 | &state.followed_channels, |
| 202 | my_user_id.as_deref(), |
| 203 | conversation_id, |
| 204 | ); |
| 205 | for incoming in found { |
| 206 | self.handle_incoming(incoming, cx); |
| 207 | } |
| 208 | self.refresh_badge(cx); |
| 209 | } |
| 210 | |
| 211 | fn environment(&self, conversation_id: &str, cx: &mut Context<Self>) -> Environment { |
| 212 | let state = self.app.read(cx); |
| 213 | let selected = state |
| 214 | .selection |
| 215 | .as_ref() |
| 216 | .is_some_and(|selection| selection.conversation_id() == conversation_id); |
| 217 | let own_do_not_disturb = state.directory.me.as_ref().is_some_and(|me| { |
| 218 | state.directory.presence_of(&me.user_id).kind() == PresenceKind::DoNotDisturb |
| 219 | }); |
| 220 | let in_call = match (state.engine.as_ref(), state.directory.me.as_ref()) { |
| 221 | (Some(engine), Some(me)) => data::in_call(engine, &me.user_id), |
| 222 | _ => false, |
| 223 | }; |
| 224 | Environment { |
| 225 | chat_in_foreground: selected && self.main_window_active(cx), |
| 226 | system_quiet: platform::system_quiet(), |
| 227 | own_do_not_disturb, |
| 228 | in_call, |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | fn main_window_active(&self, cx: &mut Context<Self>) -> bool { |
| 233 | self.main_window |
| 234 | .update(cx, |_, window, _| window.is_window_active()) |
| 235 | .unwrap_or(false) |
| 236 | } |
| 237 | |
| 238 | pub fn handle_incoming(&mut self, incoming: Incoming, cx: &mut Context<Self>) { |
| 239 | let environment = self.environment(&incoming.conversation_id, cx); |
| 240 | if !environment.chat_in_foreground && incoming.mentions_me { |
| 241 | self.unread_mentions |
| 242 | .insert(incoming.conversation_id.clone()); |
| 243 | } |
| 244 | let decision = decide(&self.settings, &incoming, environment); |
| 245 | self.present(&incoming, decision, cx); |
| 246 | if should_flash( |
| 247 | &self.settings, |
| 248 | decision.toast, |
| 249 | self.main_window_active(cx), |
| 250 | ) && let Some(native) = self.main_native |
| 251 | { |
| 252 | platform::flash(native); |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | fn present(&mut self, incoming: &Incoming, decision: Decision, cx: &mut Context<Self>) { |
| 257 | if !decision.toast { |
| 258 | return; |
| 259 | } |
| 260 | let now = Instant::now(); |
| 261 | let outcome = self.stack.push(incoming, now); |
| 262 | if let Some(model) = self.stack.get_mut(outcome.id) { |
| 263 | model.time = chrono::Local::now().format("%H:%M").to_string(); |
| 264 | } |
| 265 | let throttle_allows = self.throttle.allow(&incoming.conversation_id, now); |
| 266 | if decision.sound && outcome.plays_sound(throttle_allows) && !self.app.read(cx).mode.demo { |
| 267 | platform::play_sound(); |
| 268 | } |
| 269 | if let Some(user_id) = incoming.sender_id.clone() { |
| 270 | self.app |
| 271 | .update(cx, |state, cx| state.request_avatars(vec![user_id], cx)); |
| 272 | } |
| 273 | self.sync_windows(cx); |
| 274 | } |
| 275 | |
| 276 | fn visible_ids(&self) -> Vec<u64> { |
| 277 | self.stack.visible().iter().map(|toast| toast.id).collect() |
| 278 | } |
| 279 | |
| 280 | fn work_area(&self, cx: &App) -> WorkArea { |
| 281 | if let Some(area) = self.main_native.and_then(platform::work_area) { |
| 282 | return area; |
| 283 | } |
| 284 | let bounds = cx |
| 285 | .primary_display() |
| 286 | .map(|display| display.bounds()) |
| 287 | .unwrap_or_else(|| Bounds::new(point(px(0.), px(0.)), size(px(1280.), px(720.)))); |
| 288 | WorkArea { |
| 289 | left: f32::from(bounds.origin.x) as i32, |
| 290 | top: f32::from(bounds.origin.y) as i32, |
| 291 | right: f32::from(bounds.origin.x + bounds.size.width) as i32, |
| 292 | bottom: f32::from(bounds.origin.y + bounds.size.height) as i32, |
| 293 | scale: 1., |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | fn sync_windows(&mut self, cx: &mut Context<Self>) { |
| 298 | let visible = self.visible_ids(); |
| 299 | let stale: Vec<u64> = self |
| 300 | .windows |
| 301 | .keys() |
| 302 | .filter(|id| !visible.contains(id)) |
| 303 | .copied() |
| 304 | .collect(); |
| 305 | for id in stale { |
| 306 | self.close_window(id, cx); |
| 307 | } |
| 308 | let area = self.work_area(cx); |
| 309 | let heights: Vec<f32> = self |
| 310 | .stack |
| 311 | .visible() |
| 312 | .iter() |
| 313 | .map(|toast| { |
| 314 | let lines = preview_lines(&describe(toast, self.settings.preview).preview, cx); |
| 315 | layout::toast_height(toast, lines) |
| 316 | }) |
| 317 | .collect(); |
| 318 | let with_hide_all = visible.len() > 1 || self.stack.queued_count() > 0; |
| 319 | let slots = layout::stack_slots(area, self.settings.corner, &heights, with_hide_all); |
| 320 | for (id, slot) in visible.iter().zip(slots.toasts.iter()) { |
| 321 | self.place_toast(*id, *slot, area, cx); |
| 322 | } |
| 323 | self.sync_pill(slots.pill, area, cx); |
| 324 | } |
| 325 | |
| 326 | fn slide_offset(&self, opened: Instant, area: WorkArea) -> i32 { |
| 327 | if !self.animations { |
| 328 | return 0; |
| 329 | } |
| 330 | let progress = (opened.elapsed().as_secs_f32() / SLIDE_DURATION.as_secs_f32()).min(1.); |
| 331 | let eased = 1. - (1. - progress).powi(3); |
| 332 | let distance = ((1. - eased) * SLIDE_DISTANCE * area.scale) as i32; |
| 333 | if self.settings.corner.is_right() { |
| 334 | distance |
| 335 | } else { |
| 336 | -distance |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | fn place_toast(&mut self, id: u64, slot: Slot, area: WorkArea, cx: &mut Context<Self>) { |
| 341 | if !self.windows.contains_key(&id) { |
| 342 | self.open_toast_window(id, slot, area, cx); |
| 343 | return; |
| 344 | } |
| 345 | let offset = self |
| 346 | .windows |
| 347 | .get(&id) |
| 348 | .map(|window| self.slide_offset(window.opened, area)) |
| 349 | .unwrap_or(0); |
| 350 | if let Some(window) = self.windows.get(&id) |
| 351 | && let Some(native) = window.native |
| 352 | { |
| 353 | window.place(native, slot, slot.x + offset, cx); |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | fn open_toast_window(&mut self, id: u64, slot: Slot, area: WorkArea, cx: &mut Context<Self>) { |
| 358 | if !self.opening.insert(id) { |
| 359 | return; |
| 360 | } |
| 361 | open_popup( |
| 362 | popup_options(slot, area), |
| 363 | cx, |
| 364 | move |center, window, cx| cx.new(|cx| ToastView::new(center, id, window, cx)), |
| 365 | move |this, window| { |
| 366 | this.opening.remove(&id); |
| 367 | if let Some(window) = window { |
| 368 | this.windows.insert(id, window); |
| 369 | } |
| 370 | }, |
| 371 | ); |
| 372 | } |
| 373 | |
| 374 | fn sync_pill( |
| 375 | &mut self, |
| 376 | slot: Option<Slot>, |
| 377 | area: WorkArea, |
| 378 | cx: &mut Context<Self>, |
| 379 | ) { |
| 380 | let Some(slot) = slot else { |
| 381 | if let Some(pill) = self.pill.take() { |
| 382 | pill.handle |
| 383 | .update(cx, |_, window, _| window.remove_window()) |
| 384 | .ok(); |
| 385 | } |
| 386 | return; |
| 387 | }; |
| 388 | if self.pill.is_none() && !self.pill_opening { |
| 389 | self.pill_opening = true; |
| 390 | open_popup( |
| 391 | popup_options(slot, area), |
| 392 | cx, |
| 393 | |center, _, cx| cx.new(|cx| PillView::new(center, cx)), |
| 394 | |this, window| { |
| 395 | this.pill_opening = false; |
| 396 | this.pill = window; |
| 397 | }, |
| 398 | ); |
| 399 | } |
| 400 | if let Some(pill) = self.pill.as_ref() |
| 401 | && let Some(native) = pill.native |
| 402 | { |
| 403 | pill.place(native, slot, slot.x, cx); |
| 404 | } |
| 405 | } |
| 406 | |
| 407 | fn close_window(&mut self, id: u64, cx: &mut Context<Self>) { |
| 408 | let closed = self.windows.get(&id).is_some_and(|window| { |
| 409 | window |
| 410 | .handle |
| 411 | .update(cx, |_, window, _| window.remove_window()) |
| 412 | .is_ok() |
| 413 | }); |
| 414 | if closed { |
| 415 | self.windows.remove(&id); |
| 416 | } |
| 417 | } |
| 418 | |
| 419 | fn drop_toast(&mut self, id: u64, cx: &mut Context<Self>) { |
| 420 | let fast = self.animated(FAST_FADE); |
| 421 | self.stack.dismiss(id, Instant::now(), fast); |
| 422 | cx.notify(); |
| 423 | } |
| 424 | |
| 425 | pub fn hide_all(&mut self, cx: &mut Context<Self>) { |
| 426 | for id in self.stack.ids() { |
| 427 | self.drop_toast(id, cx); |
| 428 | } |
| 429 | } |
| 430 | |
| 431 | fn sync_hover_hold(&mut self, now: Instant) { |
| 432 | let any_hovered = self.stack.any_hovered(); |
| 433 | if !any_hovered && !self.hover_hold { |
| 434 | return; |
| 435 | } |
| 436 | if any_hovered { |
| 437 | let fast = self.animated(FAST_FADE); |
| 438 | self.stack.restore(now, fast); |
| 439 | } |
| 440 | for id in self.stack.ids() { |
| 441 | if let Some(toast) = self.stack.get_mut(id) |
| 442 | && !toast.queued |
| 443 | { |
| 444 | if any_hovered { |
| 445 | toast.timer.pause(now); |
| 446 | } else if !toast.holds_open() { |
| 447 | toast.timer.resume(now); |
| 448 | } |
| 449 | } |
| 450 | } |
| 451 | self.hover_hold = any_hovered; |
| 452 | } |
| 453 | |
| 454 | fn is_dismissed(&self, id: u64) -> bool { |
| 455 | self.stack.get(id).is_none_or(|toast| toast.dismissed) |
| 456 | } |
| 457 | |
| 458 | fn tick(&mut self, cx: &mut Context<Self>) { |
| 459 | let now = Instant::now(); |
| 460 | let (fade_in, slow) = (self.animated(FADE_IN), self.animated(SLOW_FADE)); |
| 461 | for id in self.stack.expired(now) { |
| 462 | self.stack.fade_out(id, now, slow); |
| 463 | } |
| 464 | for id in self.stack.gone(now) { |
| 465 | self.stack.remove(id); |
| 466 | } |
| 467 | self.stack.promote(now, fade_in); |
| 468 | self.sync_hover_hold(now); |
| 469 | if !self.stack.is_empty() || !self.windows.is_empty() || self.pill.is_some() { |
| 470 | self.sync_windows(cx); |
| 471 | cx.notify(); |
| 472 | } |
| 473 | self.poll_tray(cx); |
| 474 | } |
| 475 | |
| 476 | fn poll_tray(&mut self, cx: &mut Context<Self>) { |
| 477 | let commands = self.tray.as_ref().map(Tray::poll).unwrap_or_default(); |
| 478 | for command in commands { |
| 479 | match command { |
| 480 | TrayCommand::Toggle => self.toggle_main_window(cx), |
| 481 | TrayCommand::Open => self.raise_main_window(cx), |
| 482 | TrayCommand::ToggleSound => { |
| 483 | self.update_settings(cx, |settings| settings.sound = !settings.sound) |
| 484 | } |
| 485 | TrayCommand::ToggleDoNotDisturb => self.update_settings(cx, |settings| { |
| 486 | settings.do_not_disturb = !settings.do_not_disturb |
| 487 | }), |
| 488 | TrayCommand::Settings => self.open_settings(cx), |
| 489 | TrayCommand::Quit => cx.quit(), |
| 490 | } |
| 491 | } |
| 492 | } |
| 493 | |
| 494 | fn toggle_main_window(&mut self, cx: &mut Context<Self>) { |
| 495 | if self.main_window_active(cx) { |
| 496 | if let Some(native) = self.main_native { |
| 497 | platform::hide_window(native); |
| 498 | } |
| 499 | } else { |
| 500 | self.raise_main_window(cx); |
| 501 | } |
| 502 | } |
| 503 | |
| 504 | fn raise_main_window(&mut self, cx: &mut Context<Self>) { |
| 505 | if let Some(native) = self.main_native { |
| 506 | platform::restore_and_raise(native); |
| 507 | } |
| 508 | self.main_window |
| 509 | .update(cx, |_, window, _| window.activate_window()) |
| 510 | .ok(); |
| 511 | } |
| 512 | |
| 513 | fn sync_tray(&self) { |
| 514 | if let Some(tray) = &self.tray { |
| 515 | tray.sync( |
| 516 | self.settings.sound, |
| 517 | self.settings.do_not_disturb, |
| 518 | !self.unread_mentions.is_empty(), |
| 519 | ); |
| 520 | } |
| 521 | } |
| 522 | |
| 523 | fn refresh_badge(&mut self, cx: &mut Context<Self>) { |
| 524 | let (count, still_unread) = |
| 525 | unread_summary(&self.app.read(cx).sidebar, &self.unread_mentions); |
| 526 | self.unread_mentions |
| 527 | .retain(|conversation_id| still_unread.contains(conversation_id)); |
| 528 | let badge = badge_for(count); |
| 529 | if badge == self.shown_badge { |
| 530 | return; |
| 531 | } |
| 532 | if let Some(native) = self.main_native { |
| 533 | platform::set_badge(native, badge.as_ref()); |
| 534 | if badge.is_none() && self.shown_badge.is_some() { |
| 535 | platform::stop_flash(native); |
| 536 | } |
| 537 | } |
| 538 | self.shown_badge = badge; |
| 539 | self.sync_tray(); |
| 540 | } |
| 541 | |
| 542 | pub fn set_hover(&mut self, id: u64, hovered: bool, cx: &mut Context<Self>) { |
| 543 | let now = Instant::now(); |
| 544 | let Some(toast) = self.stack.get_mut(id) else { |
| 545 | return; |
| 546 | }; |
| 547 | if toast.hovered == hovered { |
| 548 | return; |
| 549 | } |
| 550 | toast.hovered = hovered; |
| 551 | self.sync_hover_hold(now); |
| 552 | cx.notify(); |
| 553 | } |
| 554 | |
| 555 | pub fn dismiss(&mut self, id: u64, cx: &mut Context<Self>) { |
| 556 | self.drop_toast(id, cx); |
| 557 | } |
| 558 | |
| 559 | pub fn open_reply(&mut self, id: u64, cx: &mut Context<Self>) -> Option<String> { |
| 560 | let now = Instant::now(); |
| 561 | let toast = self.stack.get_mut(id)?; |
| 562 | toast.reply = ReplyState::Open; |
| 563 | toast.timer.pause(now); |
| 564 | let draft = toast.reply_text.clone(); |
| 565 | cx.notify(); |
| 566 | Some(draft) |
| 567 | } |
| 568 | |
| 569 | pub fn close_reply(&mut self, id: u64, cx: &mut Context<Self>) { |
| 570 | if let Some(toast) = self.stack.get_mut(id) { |
| 571 | toast.reply = ReplyState::Closed; |
| 572 | toast.reply_text.clear(); |
| 573 | toast.hovered = false; |
| 574 | } |
| 575 | cx.notify(); |
| 576 | } |
| 577 | |
| 578 | pub fn submit_reply(&mut self, id: u64, text: String, cx: &mut Context<Self>) { |
| 579 | let Some(toast) = self.stack.get_mut(id) else { |
| 580 | return; |
| 581 | }; |
| 582 | toast.reply_text = text.clone(); |
| 583 | let conversation_id = toast.conversation_id.clone(); |
| 584 | let message_id = toast.message_id.clone(); |
| 585 | let is_channel = matches!(toast.kind, ChatKind::Channel { .. }); |
| 586 | let state = self.app.read(cx); |
| 587 | let (mode, engine) = (state.mode, state.engine.clone()); |
| 588 | let outcome: Result<(), ()> = if mode.demo { |
| 589 | Ok(()) |
| 590 | } else if mode.read_only { |
| 591 | Err(()) |
| 592 | } else if let Some(engine) = engine { |
| 593 | let receiver = runtime::spawn(async move { |
| 594 | if is_channel { |
| 595 | engine.reply_to(&conversation_id, &message_id, &text).await |
| 596 | } else { |
| 597 | engine.send_message(&conversation_id, &text, None).await |
| 598 | } |
| 599 | .map(|_| ()) |
| 600 | }); |
| 601 | cx.spawn(async move |this, cx| { |
| 602 | let sent = matches!(receiver.await, Ok(Ok(()))); |
| 603 | this.update(cx, |center, cx| center.finish_reply(id, sent, cx)) |
| 604 | .ok(); |
| 605 | }) |
| 606 | .detach(); |
| 607 | return; |
| 608 | } else { |
| 609 | Err(()) |
| 610 | }; |
| 611 | self.finish_reply(id, outcome.is_ok(), cx); |
| 612 | } |
| 613 | |
| 614 | fn finish_reply(&mut self, id: u64, sent: bool, cx: &mut Context<Self>) { |
| 615 | let Some(toast) = self.stack.get_mut(id) else { |
| 616 | return; |
| 617 | }; |
| 618 | toast.reply = if sent { |
| 619 | ReplyState::Sent |
| 620 | } else { |
| 621 | ReplyState::Failed |
| 622 | }; |
| 623 | let conversation_id = toast.conversation_id.clone(); |
| 624 | cx.notify(); |
| 625 | if sent { |
| 626 | cx.spawn(async move |this, cx| { |
| 627 | cx.background_executor().timer(SENT_DURATION).await; |
| 628 | this.update(cx, |center, cx| { |
| 629 | center.mark_conversation_read(&conversation_id, cx); |
| 630 | center.drop_toast(id, cx); |
| 631 | }) |
| 632 | .ok(); |
| 633 | }) |
| 634 | .detach(); |
| 635 | } |
| 636 | } |
| 637 | |
| 638 | fn mark_conversation_read(&mut self, conversation_id: &str, cx: &mut Context<Self>) { |
| 639 | self.unread_mentions.remove(conversation_id); |
| 640 | let conversation_id = conversation_id.to_owned(); |
| 641 | self.app |
| 642 | .update(cx, |state, cx| state.mark_chat_read(&conversation_id, cx)); |
| 643 | self.refresh_badge(cx); |
| 644 | } |
| 645 | |
| 646 | pub fn mark_read(&mut self, id: u64, cx: &mut Context<Self>) { |
| 647 | if self.is_dismissed(id) { |
| 648 | return; |
| 649 | } |
| 650 | let Some(conversation_id) = self |
| 651 | .stack |
| 652 | .get(id) |
| 653 | .map(|toast| toast.conversation_id.clone()) |
| 654 | else { |
| 655 | return; |
| 656 | }; |
| 657 | self.mark_conversation_read(&conversation_id, cx); |
| 658 | self.drop_toast(id, cx); |
| 659 | } |
| 660 | |
| 661 | pub fn activate(&mut self, id: u64, cx: &mut Context<Self>) { |
| 662 | if self.is_dismissed(id) { |
| 663 | return; |
| 664 | } |
| 665 | let Some((conversation_id, message_id)) = self |
| 666 | .stack |
| 667 | .get(id) |
| 668 | .map(|toast| (toast.conversation_id.clone(), toast.message_id.clone())) |
| 669 | else { |
| 670 | return; |
| 671 | }; |
| 672 | self.drop_toast(id, cx); |
| 673 | self.raise_main_window(cx); |
| 674 | let selection = selection_for(&self.app.read(cx).sidebar, &conversation_id); |
| 675 | if let Some(selection) = selection { |
| 676 | self.app.update(cx, |state, cx| { |
| 677 | state.jump_to_message(selection, message_id, cx) |
| 678 | }); |
| 679 | } |
| 680 | } |
| 681 | |
| 682 | pub fn open_settings(&mut self, cx: &mut Context<Self>) { |
| 683 | if let Some(handle) = self.settings_window { |
| 684 | if handle |
| 685 | .update(cx, |_, window, _| window.activate_window()) |
| 686 | .is_ok() |
| 687 | { |
| 688 | return; |
| 689 | } |
| 690 | self.settings_window = None; |
| 691 | } |
| 692 | if self.settings_opening { |
| 693 | return; |
| 694 | } |
| 695 | self.settings_opening = true; |
| 696 | let center = cx.entity(); |
| 697 | let options = WindowOptions { |
| 698 | window_bounds: Some(WindowBounds::Windowed(Bounds::centered( |
| 699 | None, |
| 700 | size(px(SettingsView::WIDTH), px(SettingsView::HEIGHT)), |
| 701 | cx, |
| 702 | ))), |
| 703 | titlebar: Some(TitlebarOptions { |
| 704 | title: Some("Notifications".into()), |
| 705 | ..Default::default() |
| 706 | }), |
| 707 | is_resizable: false, |
| 708 | is_minimizable: false, |
| 709 | ..Default::default() |
| 710 | }; |
| 711 | // open_window draws once right away, and SettingsView reads this entity while rendering. |
| 712 | cx.defer(move |cx| { |
| 713 | let view_center = center.clone(); |
| 714 | let opened = gpui_kit::open_window(options, cx, move |_, cx| { |
| 715 | cx.new(|cx| SettingsView::new(view_center, cx)) |
| 716 | }); |
| 717 | center.update(cx, |this, _| { |
| 718 | this.settings_opening = false; |
| 719 | this.settings_window = opened.ok().map(|(handle, _)| handle); |
| 720 | }); |
| 721 | }); |
| 722 | } |
| 723 | |
| 724 | pub fn send_test_notification(&mut self, cx: &mut Context<Self>) { |
| 725 | let incoming = Incoming { |
| 726 | conversation_id: "test-notification".to_owned(), |
| 727 | message_id: "test".to_owned(), |
| 728 | kind: ChatKind::Direct, |
| 729 | chat_title: "Mara Lindqvist".to_owned(), |
| 730 | sender_id: None, |
| 731 | sender_name: "Mara Lindqvist".to_owned(), |
| 732 | preview: Preview::Text("This is a test notification.".to_owned()), |
| 733 | mentions_me: false, |
| 734 | muted: false, |
| 735 | signals: Default::default(), |
| 736 | created_at: Utc::now(), |
| 737 | }; |
| 738 | let decision = Decision { |
| 739 | toast: true, |
| 740 | sound: self.settings.sound, |
| 741 | }; |
| 742 | self.throttle = SoundThrottle::default(); |
| 743 | self.present(&incoming, decision, cx); |
| 744 | } |
| 745 | |
| 746 | fn show_demo_toasts(&mut self, cx: &mut Context<Self>) { |
| 747 | for incoming in demo_incoming() { |
| 748 | let decision = Decision { |
| 749 | toast: true, |
| 750 | sound: false, |
| 751 | }; |
| 752 | self.present(&incoming, decision, cx); |
| 753 | } |
| 754 | } |
| 755 | } |
| 756 | |
| 757 | /// Opens a window outside the current update: `open_window` draws right away, and every |
| 758 | /// notification view reads the center while rendering. |
| 759 | fn open_popup<V: Render>( |
| 760 | options: WindowOptions, |
| 761 | cx: &mut Context<NotificationCenter>, |
| 762 | build: impl FnOnce(Entity<NotificationCenter>, &mut Window, &mut App) -> Entity<V> + 'static, |
| 763 | opened: impl FnOnce(&mut NotificationCenter, Option<OpenWindow>) + 'static, |
| 764 | ) { |
| 765 | let center = cx.entity(); |
| 766 | cx.defer(move |cx| { |
| 767 | let view_center = center.clone(); |
| 768 | let Ok(handle) = cx.open_window(options, move |window, cx| { |
| 769 | let view = build(view_center, window, cx); |
| 770 | cx.new(|cx| base::Root::new(view, window, cx).bg(transparent_black())) |
| 771 | }) else { |
| 772 | center.update(cx, |this, _| opened(this, None)); |
| 773 | return; |
| 774 | }; |
| 775 | let handle = AnyWindowHandle::from(handle); |
| 776 | let native = handle |
| 777 | .update(cx, |_, window, _| platform::native_handle(window)) |
| 778 | .ok() |
| 779 | .flatten(); |
| 780 | if let Some(native) = native { |
| 781 | platform::prepare_toast_window(native); |
| 782 | } |
| 783 | let window = OpenWindow { |
| 784 | handle, |
| 785 | native, |
| 786 | opened: Instant::now(), |
| 787 | }; |
| 788 | center.update(cx, |this, _| opened(this, Some(window))); |
| 789 | }); |
| 790 | } |
| 791 | |
| 792 | fn preview_lines(text: &str, cx: &App) -> usize { |
| 793 | let mut wrapper = cx |
| 794 | .text_system() |
| 795 | .line_wrapper(font(crate::theme::font_family()), px(layout::PREVIEW_SIZE)); |
| 796 | text.split('\n') |
| 797 | .map(|line| { |
| 798 | let fragments = [LineFragment::text(line)]; |
| 799 | wrapper |
| 800 | .wrap_line(&fragments, px(layout::PREVIEW_WIDTH), IndentAdjustment::NoIndent) |
| 801 | .count() |
| 802 | + 1 |
| 803 | }) |
| 804 | .sum() |
| 805 | } |
| 806 | |
| 807 | fn popup_options(slot: Slot, area: WorkArea) -> WindowOptions { |
| 808 | let scale = area.scale; |
| 809 | let bounds = Bounds::new( |
| 810 | point(px(slot.x as f32 / scale), px(slot.y as f32 / scale)), |
| 811 | size( |
| 812 | px(slot.width as f32 / scale), |
| 813 | px(slot.height as f32 / scale), |
| 814 | ), |
| 815 | ); |
| 816 | WindowOptions { |
| 817 | window_bounds: Some(WindowBounds::Windowed(bounds)), |
| 818 | titlebar: None, |
| 819 | focus: false, |
| 820 | show: true, |
| 821 | kind: WindowKind::PopUp, |
| 822 | is_movable: false, |
| 823 | is_resizable: false, |
| 824 | is_minimizable: false, |
| 825 | window_background: WindowBackgroundAppearance::Transparent, |
| 826 | ..Default::default() |
| 827 | } |
| 828 | } |
| 829 | |
| 830 | pub fn selection_for(sidebar: &Sidebar, conversation_id: &str) -> Option<Selection> { |
| 831 | if sidebar.chats.iter().any(|chat| chat.id == conversation_id) { |
| 832 | return Some(Selection::Chat(conversation_id.to_owned())); |
| 833 | } |
| 834 | sidebar |
| 835 | .teams |
| 836 | .iter() |
| 837 | .flat_map(|team| team.channels.iter()) |
| 838 | .any(|channel| channel.id == conversation_id) |
| 839 | .then(|| Selection::Channel(conversation_id.to_owned())) |
| 840 | } |
| 841 | |
| 842 | pub fn unread_summary( |
| 843 | sidebar: &Sidebar, |
| 844 | unread_mentions: &HashSet<String>, |
| 845 | ) -> (usize, HashSet<String>) { |
| 846 | let chats = sidebar.chats.iter().filter(|chat| chat.unread); |
| 847 | let channels = sidebar |
| 848 | .teams |
| 849 | .iter() |
| 850 | .flat_map(|team| team.channels.iter()) |
| 851 | .filter(|channel| channel.unread); |
| 852 | let silenced_chat_ids: HashSet<&str> = sidebar |
| 853 | .chats |
| 854 | .iter() |
| 855 | .filter(|chat| chat.muted && !unread_mentions.contains(&chat.id)) |
| 856 | .map(|chat| chat.id.as_str()) |
| 857 | .collect(); |
| 858 | let ids: HashSet<String> = chats |
| 859 | .map(|chat| chat.id.clone()) |
| 860 | .chain(channels.map(|channel| channel.id.clone())) |
| 861 | .collect(); |
| 862 | let counted = ids |
| 863 | .iter() |
| 864 | .filter(|id| !silenced_chat_ids.contains(id.as_str())) |
| 865 | .count(); |
| 866 | (counted, ids) |
| 867 | } |
| 868 | |
| 869 | fn demo_incoming() -> Vec<Incoming> { |
| 870 | let item = |conversation: &str, |
| 871 | kind: ChatKind, |
| 872 | title: &str, |
| 873 | sender: &str, |
| 874 | text: &str, |
| 875 | mention: bool| Incoming { |
| 876 | conversation_id: conversation.to_owned(), |
| 877 | message_id: format!("{conversation}-message"), |
| 878 | kind, |
| 879 | chat_title: title.to_owned(), |
| 880 | sender_id: None, |
| 881 | sender_name: sender.to_owned(), |
| 882 | preview: Preview::Text(text.to_owned()), |
| 883 | mentions_me: mention, |
| 884 | muted: false, |
| 885 | signals: Default::default(), |
| 886 | created_at: Utc::now(), |
| 887 | }; |
| 888 | vec![ |
| 889 | item( |
| 890 | "demo-toast-direct", |
| 891 | ChatKind::Direct, |
| 892 | "Tobias Klein", |
| 893 | "Tobias Klein", |
| 894 | "Sounds good, I will look at it tomorrow.", |
| 895 | false, |
| 896 | ), |
| 897 | item( |
| 898 | "demo-toast-group", |
| 899 | ChatKind::Group { member_count: 5 }, |
| 900 | "Retro-Team", |
| 901 | "Priya Nair", |
| 902 | "Please add topics by 5 pm.", |
| 903 | false, |
| 904 | ), |
| 905 | item( |
| 906 | "demo-toast-mention", |
| 907 | ChatKind::Channel { |
| 908 | team: "Platform".to_owned(), |
| 909 | channel: "Releases".to_owned(), |
| 910 | }, |
| 911 | "Releases", |
| 912 | "Mara Lindqvist", |
| 913 | "@Jonas can you approve the merge? The pipeline is waiting.", |
| 914 | true, |
| 915 | ), |
| 916 | item( |
| 917 | "demo-toast-lea", |
| 918 | ChatKind::Direct, |
| 919 | "Lea Schneider", |
| 920 | "Lea Schneider", |
| 921 | "Lunch at 12?", |
| 922 | false, |
| 923 | ), |
| 924 | item( |
| 925 | "demo-toast-jonas", |
| 926 | ChatKind::Direct, |
| 927 | "Jonas Ortega", |
| 928 | "Jonas Ortega", |
| 929 | "Deploy window moved to Thursday 6 pm.", |
| 930 | false, |
| 931 | ), |
| 932 | ] |
| 933 | } |
| 934 | |
| 935 | #[cfg(test)] |
| 936 | mod tests { |
| 937 | use store::{ChannelRecord, ChatRecord, SidebarTeam, TeamRecord}; |
| 938 | |
| 939 | use std::collections::HashSet; |
| 940 | |
| 941 | use super::{preview_lines, selection_for, unread_summary}; |
| 942 | use crate::app_state::Selection; |
| 943 | use store::Sidebar; |
| 944 | |
| 945 | fn sidebar() -> Sidebar { |
| 946 | Sidebar { |
| 947 | chats: vec![ |
| 948 | ChatRecord { |
| 949 | id: "a".into(), |
| 950 | unread: true, |
| 951 | ..Default::default() |
| 952 | }, |
| 953 | ChatRecord { |
| 954 | id: "b".into(), |
| 955 | unread: false, |
| 956 | ..Default::default() |
| 957 | }, |
| 958 | ], |
| 959 | teams: vec![SidebarTeam { |
| 960 | team: TeamRecord { |
| 961 | id: "t".into(), |
| 962 | name: "Team".into(), |
| 963 | }, |
| 964 | channels: vec![ChannelRecord { |
| 965 | id: "ch".into(), |
| 966 | team_id: "t".into(), |
| 967 | name: "General".into(), |
| 968 | membership_type: None, |
| 969 | last_message_at: None, |
| 970 | unread: true, |
| 971 | }], |
| 972 | hidden: false, |
| 973 | hidden_channel_ids: Vec::new(), |
| 974 | }], |
| 975 | } |
| 976 | } |
| 977 | |
| 978 | #[test] |
| 979 | fn unread_summary_counts_chats_and_channels() { |
| 980 | let (count, ids) = unread_summary(&sidebar(), &HashSet::new()); |
| 981 | assert_eq!(count, 2); |
| 982 | assert!(ids.contains("a") && ids.contains("ch")); |
| 983 | } |
| 984 | |
| 985 | #[test] |
| 986 | fn muted_chats_only_count_with_an_unread_mention() { |
| 987 | let mut quiet = sidebar(); |
| 988 | quiet.chats[0].muted = true; |
| 989 | let (count, ids) = unread_summary(&quiet, &HashSet::new()); |
| 990 | assert_eq!(count, 1); |
| 991 | assert!(ids.contains("a")); |
| 992 | let (count, _) = unread_summary(&quiet, &HashSet::from(["a".to_owned()])); |
| 993 | assert_eq!(count, 2); |
| 994 | } |
| 995 | |
| 996 | #[test] |
| 997 | fn selection_kind_follows_sidebar() { |
| 998 | assert_eq!( |
| 999 | selection_for(&sidebar(), "a"), |
| 1000 | Some(Selection::Chat("a".into())) |
| 1001 | ); |
| 1002 | assert_eq!( |
| 1003 | selection_for(&sidebar(), "ch"), |
| 1004 | Some(Selection::Channel("ch".into())) |
| 1005 | ); |
| 1006 | assert_eq!(selection_for(&sidebar(), "x"), None); |
| 1007 | } |
| 1008 | |
| 1009 | #[gpui_kit::test] |
| 1010 | fn preview_lines_follow_the_wrapped_text(cx: &mut gpui_kit::TestAppContext) { |
| 1011 | cx.update(|cx| { |
| 1012 | assert_eq!(preview_lines("ok", cx), 1); |
| 1013 | assert_eq!(preview_lines("a\nb", cx), 2); |
| 1014 | let long = "Cristina: ok, thanks for the info! I think not now ".repeat(3); |
| 1015 | assert!(preview_lines(&long, cx) >= 2); |
| 1016 | }); |
| 1017 | } |
| 1018 | } |