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