BlueGit

ict rusty-teams

Files

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

center.rs

center.rs 33.0 KiB Download Raw
1use std::collections::{HashMap, HashSet};
2use std::time::{Duration, Instant};
3
4use chrono::Utc;
5use gpui_kit::*;
6use store::Sidebar;
7
8use super::badge::{Badge, badge_for};
9use super::incoming::IncomingTracker;
10use super::layout::{self, Slot};
11use super::platform::{self, NativeHandle, Tray, TrayCommand, WorkArea};
12use super::rules::{
13 ChatKind, Decision, Environment, Incoming, Preview, Settings, SoundThrottle, decide,
14 should_flash,
15};
16use super::settings;
17use super::settings_view::SettingsView;
18use super::stack::{
19 FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE, ToastModel, ToastStack,
20};
21use super::text::describe;
22use super::toast::{PillView, ToastView};
23use crate::app_state::{AppEvent, AppState, Selection};
24use crate::data::{self, Directory, PresenceKind};
25use crate::runtime;
26use crate::single_instance;
27
28const TICK: Duration = Duration::from_millis(33);
29const SLIDE_DURATION: Duration = Duration::from_millis(180);
30const SLIDE_DISTANCE: f32 = 48.;
31const DEMO_SPEC_DELAY: Duration = Duration::from_secs(3);
32
33struct OpenWindow {
34 handle: AnyWindowHandle,
35 native: Option<NativeHandle>,
36 opened: Instant,
37}
38
39impl OpenWindow {
40 fn place(&self, native: NativeHandle, slot: Slot, x: i32, cx: &mut App) {
41 platform::place(native, x, slot.y, slot.width, slot.height);
42 // WM_SIZE arrives while the app is borrowed, so GPUI drops its own resize report.
43 self.handle
44 .update(cx, |_, window, cx| window.bounds_changed(cx))
45 .ok();
46 }
47}
48
49pub struct NotificationCenter {
50 app: Entity<AppState>,
51 main_window: AnyWindowHandle,
52 main_native: Option<NativeHandle>,
53 settings: Settings,
54 stack: ToastStack,
55 tracker: IncomingTracker,
56 throttle: SoundThrottle,
57 windows: HashMap<u64, OpenWindow>,
58 opening: HashSet<u64>,
59 pill: Option<OpenWindow>,
60 pill_opening: bool,
61 hover_hold: bool,
62 settings_window: Option<AnyWindowHandle>,
63 settings_opening: bool,
64 unread_mentions: HashSet<String>,
65 tray: Option<Tray>,
66 shown_badge: Option<Badge>,
67 animations: bool,
68 _subscription: Subscription,
69}
70
71impl NotificationCenter {
72 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
73 let settings = settings::load(&app.read(cx).store);
74 let tray = if app.read(cx).mode.demo {
75 None
76 } else {
77 Tray::new(settings.sound, settings.do_not_disturb)
78 };
79 let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {
80 this.on_app_event(event, cx);
81 });
82 let center = NotificationCenter {
83 main_window: window.window_handle(),
84 main_native: platform::native_handle(window),
85 settings,
86 stack: ToastStack::default(),
87 tracker: IncomingTracker::new(Utc::now()),
88 throttle: SoundThrottle::default(),
89 windows: HashMap::new(),
90 opening: HashSet::new(),
91 pill: None,
92 pill_opening: false,
93 hover_hold: false,
94 settings_window: None,
95 settings_opening: false,
96 unread_mentions: HashSet::new(),
97 tray,
98 shown_badge: None,
99 animations: platform::animations_enabled(),
100 app,
101 _subscription: subscription,
102 };
103 cx.spawn(async move |this, cx| {
104 loop {
105 cx.background_executor().timer(TICK).await;
106 if this.update(cx, |center, cx| center.tick(cx)).is_err() {
107 break;
108 }
109 }
110 })
111 .detach();
112 if center.app.read(cx).mode.demo {
113 cx.spawn(async move |this, cx| {
114 cx.background_executor().timer(DEMO_SPEC_DELAY).await;
115 this.update(cx, |center, cx| center.show_demo_toasts(cx))
116 .ok();
117 })
118 .detach();
119 }
120 center
121 }
122
123 pub fn settings(&self) -> &Settings {
124 &self.settings
125 }
126
127 pub fn model(&self, id: u64) -> Option<&ToastModel> {
128 self.stack.get(id)
129 }
130
131 pub fn queued_count(&self) -> usize {
132 self.stack.queued_count()
133 }
134
135 pub fn stack_opacity(&self) -> f32 {
136 let now = Instant::now();
137 self.stack
138 .visible()
139 .iter()
140 .map(|toast| toast.opacity(now))
141 .fold(0., f32::max)
142 }
143
144 fn animated(&self, duration: Duration) -> Duration {
145 if self.animations { duration } else { Duration::ZERO }
146 }
147
148 pub fn directory<'a>(&self, cx: &'a App) -> &'a Directory {
149 &self.app.read(cx).directory
150 }
151
152 pub fn reply_text(&self, id: u64) -> Option<String> {
153 self.stack.get(id).map(|toast| toast.reply_text.clone())
154 }
155
156 pub fn intercept_close(&self, _cx: &App) -> bool {
157 match (self.settings.close_to_tray, &self.tray, self.main_native) {
158 (true, Some(_), Some(native)) => {
159 platform::hide_window(native);
160 true
161 }
162 _ => false,
163 }
164 }
165
166 pub fn update_settings(&mut self, cx: &mut Context<Self>, change: impl FnOnce(&mut Settings)) {
167 change(&mut self.settings);
168 settings::save(&self.app.read(cx).store, &self.settings);
169 self.sync_tray();
170 cx.notify();
171 }
172
173 fn on_app_event(&mut self, event: &AppEvent, cx: &mut Context<Self>) {
174 match event {
175 AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),
176 AppEvent::Selection => self.on_selection(cx),
177 AppEvent::Sidebar => self.refresh_badge(cx),
178 _ => {}
179 }
180 }
181
182 fn on_selection(&mut self, cx: &mut Context<Self>) {
183 let selected = self
184 .app
185 .read(cx)
186 .selection
187 .as_ref()
188 .map(|selection| selection.conversation_id().to_owned());
189 if let Some(conversation_id) = selected {
190 self.unread_mentions.remove(&conversation_id);
191 self.stack.remove_conversation(&conversation_id);
192 }
193 self.refresh_badge(cx);
194 }
195
196 fn on_messages(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
197 let state = self.app.read(cx);
198 let my_user_id = state.directory.me.as_ref().map(|me| me.user_id.clone());
199 let found = self.tracker.collect(
200 &state.store,
201 &state.sidebar,
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 if single_instance::take_activation() {
475 self.raise_main_window(cx);
476 }
477 }
478
479 fn poll_tray(&mut self, cx: &mut Context<Self>) {
480 let commands = self.tray.as_ref().map(Tray::poll).unwrap_or_default();
481 for command in commands {
482 match command {
483 TrayCommand::Toggle => self.toggle_main_window(cx),
484 TrayCommand::Open => self.raise_main_window(cx),
485 TrayCommand::ToggleSound => {
486 self.update_settings(cx, |settings| settings.sound = !settings.sound)
487 }
488 TrayCommand::ToggleDoNotDisturb => self.update_settings(cx, |settings| {
489 settings.do_not_disturb = !settings.do_not_disturb
490 }),
491 TrayCommand::Settings => self.open_settings(cx),
492 TrayCommand::Quit => cx.quit(),
493 }
494 }
495 }
496
497 fn toggle_main_window(&mut self, cx: &mut Context<Self>) {
498 if self.main_window_active(cx) {
499 if let Some(native) = self.main_native {
500 platform::hide_window(native);
501 }
502 } else {
503 self.raise_main_window(cx);
504 }
505 }
506
507 fn raise_main_window(&mut self, cx: &mut Context<Self>) {
508 if let Some(native) = self.main_native {
509 platform::restore_and_raise(native);
510 }
511 self.main_window
512 .update(cx, |_, window, _| window.activate_window())
513 .ok();
514 }
515
516 fn sync_tray(&self) {
517 if let Some(tray) = &self.tray {
518 tray.sync(
519 self.settings.sound,
520 self.settings.do_not_disturb,
521 !self.unread_mentions.is_empty(),
522 );
523 }
524 }
525
526 fn refresh_badge(&mut self, cx: &mut Context<Self>) {
527 let (count, still_unread) =
528 unread_summary(&self.app.read(cx).sidebar, &self.unread_mentions);
529 self.unread_mentions
530 .retain(|conversation_id| still_unread.contains(conversation_id));
531 let badge = badge_for(count);
532 if badge == self.shown_badge {
533 return;
534 }
535 if let Some(native) = self.main_native {
536 platform::set_badge(native, badge.as_ref());
537 if badge.is_none() && self.shown_badge.is_some() {
538 platform::stop_flash(native);
539 }
540 }
541 self.shown_badge = badge;
542 self.sync_tray();
543 }
544
545 pub fn set_hover(&mut self, id: u64, hovered: bool, cx: &mut Context<Self>) {
546 let now = Instant::now();
547 let Some(toast) = self.stack.get_mut(id) else {
548 return;
549 };
550 if toast.hovered == hovered {
551 return;
552 }
553 toast.hovered = hovered;
554 self.sync_hover_hold(now);
555 cx.notify();
556 }
557
558 pub fn dismiss(&mut self, id: u64, cx: &mut Context<Self>) {
559 self.drop_toast(id, cx);
560 }
561
562 pub fn open_reply(&mut self, id: u64, cx: &mut Context<Self>) -> Option<String> {
563 let now = Instant::now();
564 let toast = self.stack.get_mut(id)?;
565 toast.reply = ReplyState::Open;
566 toast.timer.pause(now);
567 let draft = toast.reply_text.clone();
568 cx.notify();
569 Some(draft)
570 }
571
572 pub fn close_reply(&mut self, id: u64, cx: &mut Context<Self>) {
573 if let Some(toast) = self.stack.get_mut(id) {
574 toast.reply = ReplyState::Closed;
575 toast.reply_text.clear();
576 toast.hovered = false;
577 }
578 cx.notify();
579 }
580
581 pub fn submit_reply(&mut self, id: u64, text: String, cx: &mut Context<Self>) {
582 let Some(toast) = self.stack.get_mut(id) else {
583 return;
584 };
585 toast.reply_text = text.clone();
586 let conversation_id = toast.conversation_id.clone();
587 let message_id = toast.message_id.clone();
588 let is_channel = matches!(toast.kind, ChatKind::Channel { .. });
589 let state = self.app.read(cx);
590 let (mode, engine) = (state.mode, state.engine.clone());
591 let outcome: Result<(), ()> = if mode.demo {
592 Ok(())
593 } else if mode.read_only {
594 Err(())
595 } else if let Some(engine) = engine {
596 let receiver = runtime::spawn(async move {
597 if is_channel {
598 engine.reply_to(&conversation_id, &message_id, &text).await
599 } else {
600 engine.send_message(&conversation_id, &text, None).await
601 }
602 .map(|_| ())
603 });
604 cx.spawn(async move |this, cx| {
605 let sent = matches!(receiver.await, Ok(Ok(())));
606 this.update(cx, |center, cx| center.finish_reply(id, sent, cx))
607 .ok();
608 })
609 .detach();
610 return;
611 } else {
612 Err(())
613 };
614 self.finish_reply(id, outcome.is_ok(), cx);
615 }
616
617 fn finish_reply(&mut self, id: u64, sent: bool, cx: &mut Context<Self>) {
618 let Some(toast) = self.stack.get_mut(id) else {
619 return;
620 };
621 toast.reply = if sent {
622 ReplyState::Sent
623 } else {
624 ReplyState::Failed
625 };
626 let conversation_id = toast.conversation_id.clone();
627 cx.notify();
628 if sent {
629 cx.spawn(async move |this, cx| {
630 cx.background_executor().timer(SENT_DURATION).await;
631 this.update(cx, |center, cx| {
632 center.mark_conversation_read(&conversation_id, cx);
633 center.drop_toast(id, cx);
634 })
635 .ok();
636 })
637 .detach();
638 }
639 }
640
641 fn mark_conversation_read(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
642 self.unread_mentions.remove(conversation_id);
643 let conversation_id = conversation_id.to_owned();
644 self.app
645 .update(cx, |state, cx| state.mark_chat_read(&conversation_id, cx));
646 self.refresh_badge(cx);
647 }
648
649 pub fn mark_read(&mut self, id: u64, cx: &mut Context<Self>) {
650 if self.is_dismissed(id) {
651 return;
652 }
653 let Some(conversation_id) = self
654 .stack
655 .get(id)
656 .map(|toast| toast.conversation_id.clone())
657 else {
658 return;
659 };
660 self.mark_conversation_read(&conversation_id, cx);
661 self.drop_toast(id, cx);
662 }
663
664 pub fn activate(&mut self, id: u64, cx: &mut Context<Self>) {
665 if self.is_dismissed(id) {
666 return;
667 }
668 let Some((conversation_id, message_id)) = self
669 .stack
670 .get(id)
671 .map(|toast| (toast.conversation_id.clone(), toast.message_id.clone()))
672 else {
673 return;
674 };
675 self.drop_toast(id, cx);
676 self.raise_main_window(cx);
677 let selection = selection_for(&self.app.read(cx).sidebar, &conversation_id);
678 if let Some(selection) = selection {
679 self.app.update(cx, |state, cx| {
680 state.jump_to_message(selection, message_id, cx)
681 });
682 }
683 }
684
685 pub fn open_settings(&mut self, cx: &mut Context<Self>) {
686 if let Some(handle) = self.settings_window {
687 if handle
688 .update(cx, |_, window, _| window.activate_window())
689 .is_ok()
690 {
691 return;
692 }
693 self.settings_window = None;
694 }
695 if self.settings_opening {
696 return;
697 }
698 self.settings_opening = true;
699 let center = cx.entity();
700 let options = WindowOptions {
701 window_bounds: Some(WindowBounds::Windowed(Bounds::centered(
702 None,
703 size(px(SettingsView::WIDTH), px(SettingsView::HEIGHT)),
704 cx,
705 ))),
706 titlebar: Some(TitlebarOptions {
707 title: Some("Notifications".into()),
708 ..Default::default()
709 }),
710 is_resizable: false,
711 is_minimizable: false,
712 ..Default::default()
713 };
714 // open_window draws once right away, and SettingsView reads this entity while rendering.
715 cx.defer(move |cx| {
716 let view_center = center.clone();
717 let opened = gpui_kit::open_window(options, cx, move |_, cx| {
718 cx.new(|cx| SettingsView::new(view_center, cx))
719 });
720 center.update(cx, |this, _| {
721 this.settings_opening = false;
722 this.settings_window = opened.ok().map(|(handle, _)| handle);
723 });
724 });
725 }
726
727 pub fn send_test_notification(&mut self, cx: &mut Context<Self>) {
728 let incoming = Incoming {
729 conversation_id: "test-notification".to_owned(),
730 message_id: "test".to_owned(),
731 kind: ChatKind::Direct,
732 chat_title: "Mara Lindqvist".to_owned(),
733 sender_id: None,
734 sender_name: "Mara Lindqvist".to_owned(),
735 preview: Preview::Text("This is a test notification.".to_owned()),
736 mentions_me: false,
737 muted: false,
738 signals: Default::default(),
739 created_at: Utc::now(),
740 };
741 let decision = Decision {
742 toast: true,
743 sound: self.settings.sound,
744 };
745 self.throttle = SoundThrottle::default();
746 self.present(&incoming, decision, cx);
747 }
748
749 fn show_demo_toasts(&mut self, cx: &mut Context<Self>) {
750 for incoming in demo_incoming() {
751 let decision = Decision {
752 toast: true,
753 sound: false,
754 };
755 self.present(&incoming, decision, cx);
756 }
757 }
758}
759
760/// Opens a window outside the current update: `open_window` draws right away, and every
761/// notification view reads the center while rendering.
762fn open_popup<V: Render>(
763 options: WindowOptions,
764 cx: &mut Context<NotificationCenter>,
765 build: impl FnOnce(Entity<NotificationCenter>, &mut Window, &mut App) -> Entity<V> + 'static,
766 opened: impl FnOnce(&mut NotificationCenter, Option<OpenWindow>) + 'static,
767) {
768 let center = cx.entity();
769 cx.defer(move |cx| {
770 let view_center = center.clone();
771 let Ok(handle) = cx.open_window(options, move |window, cx| {
772 let view = build(view_center, window, cx);
773 cx.new(|cx| base::Root::new(view, window, cx).bg(transparent_black()))
774 }) else {
775 center.update(cx, |this, _| opened(this, None));
776 return;
777 };
778 let handle = AnyWindowHandle::from(handle);
779 let native = handle
780 .update(cx, |_, window, _| platform::native_handle(window))
781 .ok()
782 .flatten();
783 if let Some(native) = native {
784 platform::prepare_toast_window(native);
785 }
786 let window = OpenWindow {
787 handle,
788 native,
789 opened: Instant::now(),
790 };
791 center.update(cx, |this, _| opened(this, Some(window)));
792 });
793}
794
795fn preview_lines(text: &str, cx: &App) -> usize {
796 let mut wrapper = cx
797 .text_system()
798 .line_wrapper(font(crate::theme::font_family()), px(layout::PREVIEW_SIZE));
799 text.split('\n')
800 .map(|line| {
801 let fragments = [LineFragment::text(line)];
802 wrapper
803 .wrap_line(&fragments, px(layout::PREVIEW_WIDTH), IndentAdjustment::NoIndent)
804 .count()
805 + 1
806 })
807 .sum()
808}
809
810fn popup_options(slot: Slot, area: WorkArea) -> WindowOptions {
811 let scale = area.scale;
812 let bounds = Bounds::new(
813 point(px(slot.x as f32 / scale), px(slot.y as f32 / scale)),
814 size(
815 px(slot.width as f32 / scale),
816 px(slot.height as f32 / scale),
817 ),
818 );
819 WindowOptions {
820 window_bounds: Some(WindowBounds::Windowed(bounds)),
821 titlebar: None,
822 focus: false,
823 show: true,
824 kind: WindowKind::PopUp,
825 is_movable: false,
826 is_resizable: false,
827 is_minimizable: false,
828 window_background: WindowBackgroundAppearance::Transparent,
829 ..Default::default()
830 }
831}
832
833pub fn selection_for(sidebar: &Sidebar, conversation_id: &str) -> Option<Selection> {
834 if sidebar.chats.iter().any(|chat| chat.id == conversation_id) {
835 return Some(Selection::Chat(conversation_id.to_owned()));
836 }
837 sidebar
838 .teams
839 .iter()
840 .flat_map(|team| team.channels.iter())
841 .any(|channel| channel.id == conversation_id)
842 .then(|| Selection::Channel(conversation_id.to_owned()))
843}
844
845pub fn unread_summary(
846 sidebar: &Sidebar,
847 unread_mentions: &HashSet<String>,
848) -> (usize, HashSet<String>) {
849 let chats = sidebar.chats.iter().filter(|chat| chat.unread);
850 let channels = sidebar
851 .teams
852 .iter()
853 .flat_map(|team| team.channels.iter())
854 .filter(|channel| channel.unread);
855 let silenced_chat_ids: HashSet<&str> = sidebar
856 .chats
857 .iter()
858 .filter(|chat| chat.muted && !unread_mentions.contains(&chat.id))
859 .map(|chat| chat.id.as_str())
860 .collect();
861 let ids: HashSet<String> = chats
862 .map(|chat| chat.id.clone())
863 .chain(channels.map(|channel| channel.id.clone()))
864 .collect();
865 let counted = ids
866 .iter()
867 .filter(|id| !silenced_chat_ids.contains(id.as_str()))
868 .count();
869 (counted, ids)
870}
871
872fn demo_incoming() -> Vec<Incoming> {
873 let item = |conversation: &str,
874 kind: ChatKind,
875 title: &str,
876 sender: &str,
877 text: &str,
878 mention: bool| Incoming {
879 conversation_id: conversation.to_owned(),
880 message_id: format!("{conversation}-message"),
881 kind,
882 chat_title: title.to_owned(),
883 sender_id: None,
884 sender_name: sender.to_owned(),
885 preview: Preview::Text(text.to_owned()),
886 mentions_me: mention,
887 muted: false,
888 signals: Default::default(),
889 created_at: Utc::now(),
890 };
891 vec![
892 item(
893 "demo-toast-direct",
894 ChatKind::Direct,
895 "Tobias Klein",
896 "Tobias Klein",
897 "Sounds good, I will look at it tomorrow.",
898 false,
899 ),
900 item(
901 "demo-toast-group",
902 ChatKind::Group { member_count: 5 },
903 "Retro-Team",
904 "Priya Nair",
905 "Please add topics by 5 pm.",
906 false,
907 ),
908 item(
909 "demo-toast-mention",
910 ChatKind::Channel {
911 team: "Platform".to_owned(),
912 channel: "Releases".to_owned(),
913 },
914 "Releases",
915 "Mara Lindqvist",
916 "@Jonas can you approve the merge? The pipeline is waiting.",
917 true,
918 ),
919 item(
920 "demo-toast-lea",
921 ChatKind::Direct,
922 "Lea Schneider",
923 "Lea Schneider",
924 "Lunch at 12?",
925 false,
926 ),
927 item(
928 "demo-toast-jonas",
929 ChatKind::Direct,
930 "Jonas Ortega",
931 "Jonas Ortega",
932 "Deploy window moved to Thursday 6 pm.",
933 false,
934 ),
935 ]
936}
937
938#[cfg(test)]
939mod tests {
940 use store::{ChannelRecord, ChatRecord, SidebarTeam, TeamRecord};
941
942 use std::collections::HashSet;
943
944 use super::{preview_lines, selection_for, unread_summary};
945 use crate::app_state::Selection;
946 use store::Sidebar;
947
948 fn sidebar() -> Sidebar {
949 Sidebar {
950 chats: vec![
951 ChatRecord {
952 id: "a".into(),
953 unread: true,
954 ..Default::default()
955 },
956 ChatRecord {
957 id: "b".into(),
958 unread: false,
959 ..Default::default()
960 },
961 ],
962 teams: vec![SidebarTeam {
963 team: TeamRecord {
964 id: "t".into(),
965 name: "Team".into(),
966 },
967 channels: vec![ChannelRecord {
968 id: "ch".into(),
969 team_id: "t".into(),
970 name: "General".into(),
971 membership_type: None,
972 last_message_at: None,
973 unread: true,
974 }],
975 hidden: false,
976 hidden_channel_ids: Vec::new(),
977 notifications: Default::default(),
978 }],
979 }
980 }
981
982 #[test]
983 fn unread_summary_counts_chats_and_channels() {
984 let (count, ids) = unread_summary(&sidebar(), &HashSet::new());
985 assert_eq!(count, 2);
986 assert!(ids.contains("a") && ids.contains("ch"));
987 }
988
989 #[test]
990 fn muted_chats_only_count_with_an_unread_mention() {
991 let mut quiet = sidebar();
992 quiet.chats[0].muted = true;
993 let (count, ids) = unread_summary(&quiet, &HashSet::new());
994 assert_eq!(count, 1);
995 assert!(ids.contains("a"));
996 let (count, _) = unread_summary(&quiet, &HashSet::from(["a".to_owned()]));
997 assert_eq!(count, 2);
998 }
999
1000 #[test]
1001 fn selection_kind_follows_sidebar() {
1002 assert_eq!(
1003 selection_for(&sidebar(), "a"),
1004 Some(Selection::Chat("a".into()))
1005 );
1006 assert_eq!(
1007 selection_for(&sidebar(), "ch"),
1008 Some(Selection::Channel("ch".into()))
1009 );
1010 assert_eq!(selection_for(&sidebar(), "x"), None);
1011 }
1012
1013 #[gpui_kit::test]
1014 fn preview_lines_follow_the_wrapped_text(cx: &mut gpui_kit::TestAppContext) {
1015 cx.update(|cx| {
1016 assert_eq!(preview_lines("ok", cx), 1);
1017 assert_eq!(preview_lines("a\nb", cx), 2);
1018 let long = "Cristina: ok, thanks for the info! I think not now ".repeat(3);
1019 assert!(preview_lines(&long, cx) >= 2);
1020 });
1021 }
1022}