BlueGit

ict rusty-teams

Files

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

center.rs

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