BlueGit

ict rusty-teams

Files

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

center.rs

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