BlueGit

ict rusty-teams

Files

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

center.rs

center.rs 42.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::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 bubble_text = match &incoming.preview {
306 Preview::Text(text) => text.replace('\n', " "),
307 Preview::Image => "Sent a picture".to_owned(),
308 };
309 self.app.update(cx, |state, cx| {
310 state.note_call_chat_message(
311 &incoming.conversation_id,
312 &incoming.message_id,
313 incoming.sender_id.clone(),
314 &incoming.sender_name,
315 &bubble_text,
316 cx,
317 )
318 });
319 let environment = self.environment(&incoming.conversation_id, cx);
320 if !environment.chat_in_foreground && incoming.mentions_me {
321 self.unread_mentions
322 .insert(incoming.conversation_id.clone());
323 }
324 let decision = decide(&self.settings, &incoming, environment);
325 self.present(&incoming, decision, cx);
326 if should_flash(&self.settings, decision.toast, self.main_window_active(cx))
327 && let Some(native) = self.main_native
328 {
329 platform::flash(native);
330 }
331 }
332
333 fn present(&mut self, incoming: &Incoming, decision: Decision, cx: &mut Context<Self>) {
334 if !decision.toast {
335 return;
336 }
337 let now = Instant::now();
338 let outcome = self.stack.push(incoming, now);
339 if let Some(model) = self.stack.get_mut(outcome.id) {
340 model.time = chrono::Local::now().format("%H:%M").to_string();
341 }
342 let throttle_allows = self.throttle.allow(&incoming.conversation_id, now);
343 if decision.sound && outcome.plays_sound(throttle_allows) && !self.app.read(cx).mode.demo {
344 platform::play_sound();
345 }
346 if let Some(user_id) = incoming.sender_id.clone() {
347 self.app
348 .update(cx, |state, cx| state.request_avatars(vec![user_id], cx));
349 }
350 self.sync_windows(cx);
351 }
352
353 pub fn present_agent_run(&mut self, run: &AgentRun, cx: &mut Context<Self>) {
354 let failed = matches!(run.state, RunState::Failed { .. });
355 let verb = if failed { "failed" } else { "finished" };
356 let body = if failed {
357 run.current_step.clone()
358 } else {
359 first_lines(&run.final_text, AGENT_BODY_LINES)
360 };
361 let toast = AgentToast {
362 run_id: run.id,
363 session_id: run.session_id.clone(),
364 header: format!(
365 "{} - {} - {}",
366 run.action_label,
367 run.agent_name,
368 run.elapsed_text()
369 ),
370 title: format!(
371 "{} {verb}: {} for {}",
372 run.agent_name, run.action_label, run.sender_name
373 ),
374 body: if body.is_empty() {
375 "Done".to_owned()
376 } else {
377 body
378 },
379 failed,
380 };
381 let now = Instant::now();
382 let id = self
383 .stack
384 .push_agent(toast, &run.conversation_id, &run.message_id, now);
385 if let Some(model) = self.stack.get_mut(id) {
386 model.time = chrono::Local::now().format("%H:%M").to_string();
387 }
388 let quiet = self.settings.do_not_disturb || self.app.read(cx).mode.demo;
389 if self.settings.sound && !quiet {
390 platform::play_sound();
391 }
392 self.sync_windows(cx);
393 }
394
395 pub fn agent_toast_follow_up(&mut self, id: u64, cx: &mut Context<Self>) {
396 let Some(agent) = self.stack.get(id).and_then(|toast| toast.agent.clone()) else {
397 return;
398 };
399 self.drop_toast(id, cx);
400 if agent.failed {
401 crate::agents::retry_run(agent.run_id, cx);
402 } else {
403 crate::agents::open_session(&agent.session_id, cx);
404 }
405 }
406
407 fn visible_ids(&self) -> Vec<u64> {
408 self.stack.visible().iter().map(|toast| toast.id).collect()
409 }
410
411 fn work_area(&self, cx: &App) -> WorkArea {
412 if let Some(area) = self.main_native.and_then(platform::work_area) {
413 return area;
414 }
415 let bounds = cx
416 .primary_display()
417 .map(|display| display.bounds())
418 .unwrap_or_else(|| Bounds::new(point(px(0.), px(0.)), size(px(1280.), px(720.))));
419 WorkArea {
420 left: f32::from(bounds.origin.x) as i32,
421 top: f32::from(bounds.origin.y) as i32,
422 right: f32::from(bounds.origin.x + bounds.size.width) as i32,
423 bottom: f32::from(bounds.origin.y + bounds.size.height) as i32,
424 scale: 1.,
425 }
426 }
427
428 fn ringing_ids(&self, cx: &App) -> Vec<(u64, bool)> {
429 let state = self.app.read(cx);
430 let in_call = state.call.is_some();
431 state
432 .rings
433 .ringing()
434 .map(|entry| (entry.ring.ring_id, in_call))
435 .collect()
436 }
437
438 fn sync_windows(&mut self, cx: &mut Context<Self>) {
439 let visible = self.visible_ids();
440 let stale: Vec<u64> = self
441 .windows
442 .keys()
443 .filter(|id| !visible.contains(id))
444 .copied()
445 .collect();
446 for id in stale {
447 self.close_window(id, cx);
448 }
449 let rings = self.ringing_ids(cx);
450 let stale_rings: Vec<u64> = self
451 .ring_windows
452 .keys()
453 .filter(|id| !rings.iter().any(|(ring_id, _)| ring_id == *id))
454 .copied()
455 .collect();
456 for id in stale_rings {
457 self.close_ring_window(id, cx);
458 }
459 let area = self.work_area(cx);
460 let mut heights: Vec<f32> = self
461 .stack
462 .visible()
463 .iter()
464 .map(|toast| {
465 let lines = match &toast.agent {
466 Some(agent) => wrapped_lines(&agent.body, layout::AGENT_BODY_WIDTH, cx),
467 None => preview_lines(&describe(toast, self.settings.preview).preview, cx),
468 };
469 layout::toast_height(toast, lines)
470 })
471 .collect();
472 heights.extend(rings.iter().map(|(_, in_call)| ring_height(*in_call)));
473 let with_hide_all = visible.len() > 1 || self.stack.queued_count() > 0;
474 let slots = layout::stack_slots(area, self.settings.corner, &heights, with_hide_all);
475 for (id, slot) in visible.iter().zip(slots.toasts.iter()) {
476 self.place_toast(*id, *slot, area, cx);
477 }
478 for ((ring_id, _), slot) in rings.iter().zip(slots.toasts.iter().skip(visible.len())) {
479 self.place_ring(*ring_id, *slot, area, cx);
480 }
481 self.sync_pill(slots.pill, area, cx);
482 }
483
484 fn place_ring(&mut self, ring_id: u64, slot: Slot, area: WorkArea, cx: &mut Context<Self>) {
485 let Some(window) = self.ring_windows.get(&ring_id) else {
486 self.open_ring_window(ring_id, slot, area, cx);
487 return;
488 };
489 if let Some(native) = window.native {
490 let offset = self.slide_offset(window.opened, area);
491 window.place(native, slot, slot.x + offset, cx);
492 }
493 }
494
495 fn open_ring_window(
496 &mut self,
497 ring_id: u64,
498 slot: Slot,
499 area: WorkArea,
500 cx: &mut Context<Self>,
501 ) {
502 if !self.ring_opening.insert(ring_id) {
503 return;
504 }
505 open_popup(
506 popup_options(slot, area),
507 cx,
508 move |center, _, cx| cx.new(|cx| RingView::new(center, ring_id, cx)),
509 move |this, window| {
510 this.ring_opening.remove(&ring_id);
511 if let Some(window) = window {
512 this.ring_windows.insert(ring_id, window);
513 }
514 },
515 );
516 }
517
518 fn close_ring_window(&mut self, ring_id: u64, cx: &mut Context<Self>) {
519 let closed = self.ring_windows.get(&ring_id).is_some_and(|window| {
520 window
521 .handle
522 .update(cx, |_, window, _| window.remove_window())
523 .is_ok()
524 });
525 if closed {
526 self.ring_windows.remove(&ring_id);
527 }
528 }
529
530 fn on_rings_changed(&mut self, cx: &mut Context<Self>) {
531 let ringing = self.app.read(cx).rings.is_ringing();
532 if ringing
533 && !self.main_window_active(cx)
534 && let Some(native) = self.main_native
535 {
536 platform::flash(native);
537 }
538 self.sync_windows(cx);
539 self.sync_ring_tone(ringing);
540 cx.notify();
541 }
542
543 fn sync_ring_tone(&mut self, ringing: bool) {
544 let audible = ringing && self.settings.sound && !self.demo_mode;
545 match (audible, self.ring_tone.is_some()) {
546 (true, false) => self.ring_tone = platform::start_ring(self.settings.ringtone),
547 (false, true) => self.ring_tone = None,
548 _ => {}
549 }
550 }
551
552 fn sync_ringback(&mut self, cx: &Context<Self>) {
553 let audible = should_ringback(self.app.read(cx).call.as_ref().map(|call| &call.model))
554 && !self.demo_mode;
555 match (audible, self.ringback.is_some()) {
556 (true, false) => self.ringback = platform::start_ringback(),
557 (false, true) => self.ringback = None,
558 _ => {}
559 }
560 }
561
562 fn slide_offset(&self, opened: Instant, area: WorkArea) -> i32 {
563 if !self.animations {
564 return 0;
565 }
566 let progress = (opened.elapsed().as_secs_f32() / SLIDE_DURATION.as_secs_f32()).min(1.);
567 let eased = 1. - (1. - progress).powi(3);
568 let distance = ((1. - eased) * SLIDE_DISTANCE * area.scale) as i32;
569 if self.settings.corner.is_right() {
570 distance
571 } else {
572 -distance
573 }
574 }
575
576 fn place_toast(&mut self, id: u64, slot: Slot, area: WorkArea, cx: &mut Context<Self>) {
577 if !self.windows.contains_key(&id) {
578 self.open_toast_window(id, slot, area, cx);
579 return;
580 }
581 let offset = self
582 .windows
583 .get(&id)
584 .map(|window| self.slide_offset(window.opened, area))
585 .unwrap_or(0);
586 if let Some(window) = self.windows.get(&id)
587 && let Some(native) = window.native
588 {
589 window.place(native, slot, slot.x + offset, cx);
590 }
591 }
592
593 fn open_toast_window(&mut self, id: u64, slot: Slot, area: WorkArea, cx: &mut Context<Self>) {
594 if !self.opening.insert(id) {
595 return;
596 }
597 open_popup(
598 popup_options(slot, area),
599 cx,
600 move |center, window, cx| cx.new(|cx| ToastView::new(center, id, window, cx)),
601 move |this, window| {
602 this.opening.remove(&id);
603 if let Some(window) = window {
604 this.windows.insert(id, window);
605 }
606 },
607 );
608 }
609
610 fn sync_pill(&mut self, slot: Option<Slot>, area: WorkArea, cx: &mut Context<Self>) {
611 let Some(slot) = slot else {
612 if let Some(pill) = self.pill.take() {
613 pill.handle
614 .update(cx, |_, window, _| window.remove_window())
615 .ok();
616 }
617 return;
618 };
619 if self.pill.is_none() && !self.pill_opening {
620 self.pill_opening = true;
621 open_popup(
622 popup_options(slot, area),
623 cx,
624 |center, _, cx| cx.new(|cx| PillView::new(center, cx)),
625 |this, window| {
626 this.pill_opening = false;
627 this.pill = window;
628 },
629 );
630 }
631 if let Some(pill) = self.pill.as_ref()
632 && let Some(native) = pill.native
633 {
634 pill.place(native, slot, slot.x, cx);
635 }
636 }
637
638 fn close_window(&mut self, id: u64, cx: &mut Context<Self>) {
639 let closed = self.windows.get(&id).is_some_and(|window| {
640 window
641 .handle
642 .update(cx, |_, window, _| window.remove_window())
643 .is_ok()
644 });
645 if closed {
646 self.windows.remove(&id);
647 }
648 }
649
650 fn drop_toast(&mut self, id: u64, cx: &mut Context<Self>) {
651 let fast = self.animated(FAST_FADE);
652 self.stack.dismiss(id, Instant::now(), fast);
653 cx.notify();
654 }
655
656 pub fn hide_all(&mut self, cx: &mut Context<Self>) {
657 for id in self.stack.ids() {
658 self.drop_toast(id, cx);
659 }
660 }
661
662 fn sync_hover_hold(&mut self, now: Instant) {
663 let any_hovered = self.stack.any_hovered();
664 if !any_hovered && !self.hover_hold {
665 return;
666 }
667 if any_hovered {
668 let fast = self.animated(FAST_FADE);
669 self.stack.restore(now, fast);
670 }
671 for id in self.stack.ids() {
672 if let Some(toast) = self.stack.get_mut(id)
673 && !toast.queued
674 {
675 if any_hovered {
676 toast.timer.pause(now);
677 } else if !toast.holds_open() {
678 toast.timer.resume(now);
679 }
680 }
681 }
682 self.hover_hold = any_hovered;
683 }
684
685 fn is_dismissed(&self, id: u64) -> bool {
686 self.stack.get(id).is_none_or(|toast| toast.dismissed)
687 }
688
689 fn tick(&mut self, cx: &mut Context<Self>) {
690 let now = Instant::now();
691 let (fade_in, slow) = (self.animated(FADE_IN), self.animated(SLOW_FADE));
692 for id in self.stack.expired(now) {
693 self.stack.fade_out(id, now, slow);
694 }
695 for id in self.stack.gone(now) {
696 self.stack.remove(id);
697 }
698 self.stack.promote(now, fade_in);
699 self.sync_hover_hold(now);
700 if !self.app.read(cx).rings.is_empty() {
701 self.app.update(cx, |state, cx| state.tick_rings(cx));
702 }
703 if !self.stack.is_empty()
704 || !self.windows.is_empty()
705 || self.pill.is_some()
706 || !self.ring_windows.is_empty()
707 {
708 self.sync_windows(cx);
709 cx.notify();
710 }
711 self.poll_tray(cx);
712 if single_instance::take_activation() {
713 self.raise_main_window(cx);
714 }
715 }
716
717 fn poll_tray(&mut self, cx: &mut Context<Self>) {
718 let commands = self.tray.as_ref().map(Tray::poll).unwrap_or_default();
719 for command in commands {
720 match command {
721 TrayCommand::Toggle => self.toggle_main_window(cx),
722 TrayCommand::Open => self.raise_main_window(cx),
723 TrayCommand::ToggleSound => {
724 self.update_settings(cx, |settings| settings.sound = !settings.sound)
725 }
726 TrayCommand::ToggleDoNotDisturb => self.update_settings(cx, |settings| {
727 settings.do_not_disturb = !settings.do_not_disturb
728 }),
729 TrayCommand::Settings => self.open_settings(cx),
730 TrayCommand::Quit => cx.quit(),
731 }
732 }
733 }
734
735 fn toggle_main_window(&mut self, cx: &mut Context<Self>) {
736 if self.main_window_active(cx) {
737 if let Some(native) = self.main_native {
738 platform::hide_window(native);
739 }
740 } else {
741 self.raise_main_window(cx);
742 }
743 }
744
745 fn raise_main_window(&mut self, cx: &mut Context<Self>) {
746 if let Some(native) = self.main_native {
747 platform::restore_and_raise(native);
748 }
749 self.main_window
750 .update(cx, |_, window, _| window.activate_window())
751 .ok();
752 }
753
754 fn sync_tray(&self) {
755 if let Some(tray) = &self.tray {
756 tray.sync(
757 self.settings.sound,
758 self.settings.do_not_disturb,
759 !self.unread_mentions.is_empty(),
760 );
761 }
762 }
763
764 fn refresh_badge(&mut self, cx: &mut Context<Self>) {
765 let (count, still_unread) =
766 unread_summary(&self.app.read(cx).sidebar, &self.unread_mentions);
767 self.unread_mentions
768 .retain(|conversation_id| still_unread.contains(conversation_id));
769 let badge = badge_for(count);
770 if badge == self.shown_badge {
771 return;
772 }
773 if let Some(native) = self.main_native {
774 platform::set_badge(native, badge.as_ref());
775 if badge.is_none() && self.shown_badge.is_some() {
776 platform::stop_flash(native);
777 }
778 }
779 self.shown_badge = badge;
780 self.sync_tray();
781 }
782
783 pub fn set_hover(&mut self, id: u64, hovered: bool, cx: &mut Context<Self>) {
784 let now = Instant::now();
785 let Some(toast) = self.stack.get_mut(id) else {
786 return;
787 };
788 if toast.hovered == hovered {
789 return;
790 }
791 toast.hovered = hovered;
792 self.sync_hover_hold(now);
793 cx.notify();
794 }
795
796 pub fn dismiss(&mut self, id: u64, cx: &mut Context<Self>) {
797 self.drop_toast(id, cx);
798 }
799
800 pub fn open_reply(&mut self, id: u64, cx: &mut Context<Self>) -> Option<String> {
801 let now = Instant::now();
802 let toast = self.stack.get_mut(id)?;
803 toast.reply = ReplyState::Open;
804 toast.timer.pause(now);
805 let draft = toast.reply_text.clone();
806 cx.notify();
807 Some(draft)
808 }
809
810 pub fn close_reply(&mut self, id: u64, cx: &mut Context<Self>) {
811 if let Some(toast) = self.stack.get_mut(id) {
812 toast.reply = ReplyState::Closed;
813 toast.reply_text.clear();
814 toast.hovered = false;
815 }
816 cx.notify();
817 }
818
819 pub fn submit_reply(&mut self, id: u64, text: String, cx: &mut Context<Self>) {
820 let Some(toast) = self.stack.get_mut(id) else {
821 return;
822 };
823 toast.reply_text = text.clone();
824 let conversation_id = toast.conversation_id.clone();
825 let message_id = toast.message_id.clone();
826 let is_channel = matches!(toast.kind, ChatKind::Channel { .. });
827 let state = self.app.read(cx);
828 let (mode, engine) = (state.mode, state.engine.clone());
829 let outcome: Result<(), ()> = if mode.demo {
830 Ok(())
831 } else if mode.read_only {
832 Err(())
833 } else if let Some(engine) = engine {
834 let receiver = runtime::spawn(async move {
835 if is_channel {
836 engine.reply_to(&conversation_id, &message_id, &text).await
837 } else {
838 engine.send_message(&conversation_id, &text, None).await
839 }
840 .map(|_| ())
841 });
842 cx.spawn(async move |this, cx| {
843 let sent = matches!(receiver.await, Ok(Ok(())));
844 this.update(cx, |center, cx| center.finish_reply(id, sent, cx))
845 .ok();
846 })
847 .detach();
848 return;
849 } else {
850 Err(())
851 };
852 self.finish_reply(id, outcome.is_ok(), cx);
853 }
854
855 fn finish_reply(&mut self, id: u64, sent: bool, cx: &mut Context<Self>) {
856 let Some(toast) = self.stack.get_mut(id) else {
857 return;
858 };
859 toast.reply = if sent {
860 ReplyState::Sent
861 } else {
862 ReplyState::Failed
863 };
864 let conversation_id = toast.conversation_id.clone();
865 cx.notify();
866 if sent {
867 cx.spawn(async move |this, cx| {
868 cx.background_executor().timer(SENT_DURATION).await;
869 this.update(cx, |center, cx| {
870 center.mark_conversation_read(&conversation_id, cx);
871 center.drop_toast(id, cx);
872 })
873 .ok();
874 })
875 .detach();
876 }
877 }
878
879 fn mark_conversation_read(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
880 self.unread_mentions.remove(conversation_id);
881 let conversation_id = conversation_id.to_owned();
882 self.app
883 .update(cx, |state, cx| state.mark_chat_read(&conversation_id, cx));
884 self.refresh_badge(cx);
885 }
886
887 pub fn mark_read(&mut self, id: u64, cx: &mut Context<Self>) {
888 if self.is_dismissed(id) {
889 return;
890 }
891 let Some(conversation_id) = self
892 .stack
893 .get(id)
894 .map(|toast| toast.conversation_id.clone())
895 else {
896 return;
897 };
898 self.mark_conversation_read(&conversation_id, cx);
899 self.drop_toast(id, cx);
900 }
901
902 pub fn activate(&mut self, id: u64, cx: &mut Context<Self>) {
903 if self.is_dismissed(id) {
904 return;
905 }
906 let Some((conversation_id, message_id)) = self
907 .stack
908 .get(id)
909 .map(|toast| (toast.conversation_id.clone(), toast.message_id.clone()))
910 else {
911 return;
912 };
913 self.drop_toast(id, cx);
914 self.raise_main_window(cx);
915 let selection = selection_for(&self.app.read(cx).sidebar, &conversation_id);
916 if let Some(selection) = selection {
917 self.app.update(cx, |state, cx| {
918 state.jump_to_message(selection, message_id, cx)
919 });
920 }
921 }
922
923 pub fn open_settings(&mut self, cx: &mut Context<Self>) {
924 self.show_settings(Section::Notifications, false, cx);
925 }
926
927 pub fn open_agent_settings(&mut self, cx: &mut Context<Self>) {
928 self.show_settings(Section::Agents, true, cx);
929 }
930
931 fn show_settings(
932 &mut self,
933 section: Section,
934 switch_open_window: bool,
935 cx: &mut Context<Self>,
936 ) {
937 if let Some(handle) = self.settings_window {
938 let shown = handle.update(cx, |view, window, cx| {
939 window.activate_window();
940 if switch_open_window && let Ok(view) = view.downcast::<SettingsView>() {
941 view.update(cx, |view, cx| view.select_section(section, cx));
942 }
943 });
944 if shown.is_ok() {
945 return;
946 }
947 self.settings_window = None;
948 }
949 if self.settings_opening {
950 return;
951 }
952 self.settings_opening = true;
953 let center = cx.entity();
954 let options = WindowOptions {
955 window_bounds: Some(WindowBounds::Windowed(Bounds::centered(
956 None,
957 size(px(SettingsView::WIDTH), px(SettingsView::HEIGHT)),
958 cx,
959 ))),
960 titlebar: Some(TitlebarOptions {
961 title: Some("Settings".into()),
962 ..Default::default()
963 }),
964 is_resizable: false,
965 is_minimizable: false,
966 ..Default::default()
967 };
968 // open_window draws once right away, and SettingsView reads this entity while rendering.
969 cx.defer(move |cx| {
970 let view_center = center.clone();
971 let opened = gpui_kit::open_window(options, cx, move |window, cx| {
972 cx.new(|cx| SettingsView::new(view_center, section, window, cx))
973 });
974 center.update(cx, |this, _| {
975 this.settings_opening = false;
976 this.settings_window = opened.ok().map(|(handle, _)| handle);
977 });
978 });
979 }
980
981 pub fn send_test_notification(&mut self, cx: &mut Context<Self>) {
982 let incoming = Incoming {
983 conversation_id: "test-notification".to_owned(),
984 message_id: "test".to_owned(),
985 kind: ChatKind::Direct,
986 chat_title: "Mara Lindqvist".to_owned(),
987 sender_id: None,
988 sender_name: "Mara Lindqvist".to_owned(),
989 preview: Preview::Text("This is a test notification.".to_owned()),
990 mentions_me: false,
991 muted: false,
992 signals: Default::default(),
993 created_at: Utc::now(),
994 };
995 let decision = Decision {
996 toast: true,
997 sound: self.settings.sound,
998 };
999 self.throttle = SoundThrottle::default();
1000 self.present(&incoming, decision, cx);
1001 }
1002
1003 fn show_demo_toasts(&mut self, cx: &mut Context<Self>) {
1004 for incoming in demo_incoming() {
1005 let decision = Decision {
1006 toast: true,
1007 sound: false,
1008 };
1009 self.present(&incoming, decision, cx);
1010 }
1011 }
1012}
1013
1014/// Opens a window outside the current update: `open_window` draws right away, and every
1015/// notification view reads the center while rendering.
1016fn open_popup<V: Render>(
1017 options: WindowOptions,
1018 cx: &mut Context<NotificationCenter>,
1019 build: impl FnOnce(Entity<NotificationCenter>, &mut Window, &mut App) -> Entity<V> + 'static,
1020 opened: impl FnOnce(&mut NotificationCenter, Option<OpenWindow>) + 'static,
1021) {
1022 let center = cx.entity();
1023 cx.defer(move |cx| {
1024 let view_center = center.clone();
1025 let Ok(handle) = cx.open_window(options, move |window, cx| {
1026 let view = build(view_center, window, cx);
1027 cx.new(|cx| base::Root::new(view, window, cx).bg(transparent_black()))
1028 }) else {
1029 center.update(cx, |this, _| opened(this, None));
1030 return;
1031 };
1032 let handle = AnyWindowHandle::from(handle);
1033 let native = handle
1034 .update(cx, |_, window, _| platform::native_handle(window))
1035 .ok()
1036 .flatten();
1037 if let Some(native) = native {
1038 platform::prepare_toast_window(native);
1039 }
1040 let window = OpenWindow {
1041 handle,
1042 native,
1043 opened: Instant::now(),
1044 };
1045 center.update(cx, |this, _| opened(this, Some(window)));
1046 });
1047}
1048
1049fn demo_scene() -> Option<DemoScene> {
1050 DemoScene::from_name(&std::env::var(DEMO_CALL_ENV).ok()?)
1051}
1052
1053/// `TEAMS_DEMO_RING=<seconds>` rings a fake incoming call that long after the demo starts.
1054fn demo_ring_delay() -> Option<Duration> {
1055 let seconds: f32 = std::env::var(DEMO_RING_ENV).ok()?.trim().parse().ok()?;
1056 (seconds >= 0.).then(|| Duration::from_secs_f32(seconds))
1057}
1058
1059fn first_lines(text: &str, count: usize) -> String {
1060 text.lines()
1061 .map(str::trim)
1062 .filter(|line| !line.is_empty())
1063 .take(count)
1064 .collect::<Vec<_>>()
1065 .join("\n")
1066}
1067
1068fn preview_lines(text: &str, cx: &App) -> usize {
1069 wrapped_lines(text, layout::PREVIEW_WIDTH, cx)
1070}
1071
1072fn wrapped_lines(text: &str, width: f32, cx: &App) -> usize {
1073 let mut wrapper = cx
1074 .text_system()
1075 .line_wrapper(font(crate::theme::font_family()), px(layout::PREVIEW_SIZE));
1076 text.split('\n')
1077 .map(|line| {
1078 let fragments = [LineFragment::text(line)];
1079 wrapper
1080 .wrap_line(&fragments, px(width), IndentAdjustment::NoIndent)
1081 .count()
1082 + 1
1083 })
1084 .sum()
1085}
1086
1087fn popup_options(slot: Slot, area: WorkArea) -> WindowOptions {
1088 let scale = area.scale;
1089 let bounds = Bounds::new(
1090 point(px(slot.x as f32 / scale), px(slot.y as f32 / scale)),
1091 size(
1092 px(slot.width as f32 / scale),
1093 px(slot.height as f32 / scale),
1094 ),
1095 );
1096 WindowOptions {
1097 window_bounds: Some(WindowBounds::Windowed(bounds)),
1098 titlebar: None,
1099 focus: false,
1100 show: true,
1101 kind: WindowKind::PopUp,
1102 is_movable: false,
1103 is_resizable: false,
1104 is_minimizable: false,
1105 window_background: WindowBackgroundAppearance::Transparent,
1106 ..Default::default()
1107 }
1108}
1109
1110pub fn selection_for(sidebar: &Sidebar, conversation_id: &str) -> Option<Selection> {
1111 if sidebar.chats.iter().any(|chat| chat.id == conversation_id) {
1112 return Some(Selection::Chat(conversation_id.to_owned()));
1113 }
1114 sidebar
1115 .teams
1116 .iter()
1117 .flat_map(|team| team.channels.iter())
1118 .any(|channel| channel.id == conversation_id)
1119 .then(|| Selection::Channel(conversation_id.to_owned()))
1120}
1121
1122pub fn unread_summary(
1123 sidebar: &Sidebar,
1124 unread_mentions: &HashSet<String>,
1125) -> (usize, HashSet<String>) {
1126 let chats = sidebar.chats.iter().filter(|chat| chat.unread);
1127 let channels = sidebar
1128 .teams
1129 .iter()
1130 .flat_map(|team| team.channels.iter())
1131 .filter(|channel| channel.unread);
1132 let silenced_chat_ids: HashSet<&str> = sidebar
1133 .chats
1134 .iter()
1135 .filter(|chat| chat.muted && !unread_mentions.contains(&chat.id))
1136 .map(|chat| chat.id.as_str())
1137 .collect();
1138 let ids: HashSet<String> = chats
1139 .map(|chat| chat.id.clone())
1140 .chain(channels.map(|channel| channel.id.clone()))
1141 .collect();
1142 let counted = ids
1143 .iter()
1144 .filter(|id| !silenced_chat_ids.contains(id.as_str()))
1145 .count();
1146 (counted, ids)
1147}
1148
1149fn demo_incoming() -> Vec<Incoming> {
1150 let item = |conversation: &str,
1151 kind: ChatKind,
1152 title: &str,
1153 sender: &str,
1154 text: &str,
1155 mention: bool| Incoming {
1156 conversation_id: conversation.to_owned(),
1157 message_id: format!("{conversation}-message"),
1158 kind,
1159 chat_title: title.to_owned(),
1160 sender_id: None,
1161 sender_name: sender.to_owned(),
1162 preview: Preview::Text(text.to_owned()),
1163 mentions_me: mention,
1164 muted: false,
1165 signals: Default::default(),
1166 created_at: Utc::now(),
1167 };
1168 vec![
1169 item(
1170 "demo-toast-direct",
1171 ChatKind::Direct,
1172 "Tobias Klein",
1173 "Tobias Klein",
1174 "Sounds good, I will look at it tomorrow.",
1175 false,
1176 ),
1177 item(
1178 "demo-toast-group",
1179 ChatKind::Group { member_count: 5 },
1180 "Retro-Team",
1181 "Priya Nair",
1182 "Please add topics by 5 pm.",
1183 false,
1184 ),
1185 item(
1186 "demo-toast-mention",
1187 ChatKind::Channel {
1188 team: "Platform".to_owned(),
1189 channel: "Releases".to_owned(),
1190 },
1191 "Releases",
1192 "Mara Lindqvist",
1193 "@Jonas can you approve the merge? The pipeline is waiting.",
1194 true,
1195 ),
1196 item(
1197 "demo-toast-lea",
1198 ChatKind::Direct,
1199 "Lea Schneider",
1200 "Lea Schneider",
1201 "Lunch at 12?",
1202 false,
1203 ),
1204 item(
1205 "demo-toast-jonas",
1206 ChatKind::Direct,
1207 "Jonas Ortega",
1208 "Jonas Ortega",
1209 "Deploy window moved to Thursday 6 pm.",
1210 false,
1211 ),
1212 ]
1213}
1214
1215#[cfg(test)]
1216mod tests {
1217 use store::{ChannelRecord, ChatRecord, SidebarTeam, TeamRecord};
1218
1219 use std::collections::HashSet;
1220
1221 use super::{preview_lines, selection_for, unread_summary};
1222 use crate::app_state::Selection;
1223 use store::Sidebar;
1224
1225 fn sidebar() -> Sidebar {
1226 Sidebar {
1227 chats: vec![
1228 ChatRecord {
1229 id: "a".into(),
1230 unread: true,
1231 ..Default::default()
1232 },
1233 ChatRecord {
1234 id: "b".into(),
1235 unread: false,
1236 ..Default::default()
1237 },
1238 ],
1239 teams: vec![SidebarTeam {
1240 team: TeamRecord {
1241 id: "t".into(),
1242 name: "Team".into(),
1243 },
1244 channels: vec![ChannelRecord {
1245 id: "ch".into(),
1246 team_id: "t".into(),
1247 name: "General".into(),
1248 membership_type: None,
1249 last_message_at: None,
1250 unread: true,
1251 }],
1252 hidden: false,
1253 hidden_channel_ids: Vec::new(),
1254 notifications: Default::default(),
1255 }],
1256 }
1257 }
1258
1259 #[test]
1260 fn unread_summary_counts_chats_and_channels() {
1261 let (count, ids) = unread_summary(&sidebar(), &HashSet::new());
1262 assert_eq!(count, 2);
1263 assert!(ids.contains("a") && ids.contains("ch"));
1264 }
1265
1266 #[test]
1267 fn muted_chats_only_count_with_an_unread_mention() {
1268 let mut quiet = sidebar();
1269 quiet.chats[0].muted = true;
1270 let (count, ids) = unread_summary(&quiet, &HashSet::new());
1271 assert_eq!(count, 1);
1272 assert!(ids.contains("a"));
1273 let (count, _) = unread_summary(&quiet, &HashSet::from(["a".to_owned()]));
1274 assert_eq!(count, 2);
1275 }
1276
1277 #[test]
1278 fn selection_kind_follows_sidebar() {
1279 assert_eq!(
1280 selection_for(&sidebar(), "a"),
1281 Some(Selection::Chat("a".into()))
1282 );
1283 assert_eq!(
1284 selection_for(&sidebar(), "ch"),
1285 Some(Selection::Channel("ch".into()))
1286 );
1287 assert_eq!(selection_for(&sidebar(), "x"), None);
1288 }
1289
1290 #[gpui_kit::test]
1291 fn preview_lines_follow_the_wrapped_text(cx: &mut gpui_kit::TestAppContext) {
1292 cx.update(|cx| {
1293 assert_eq!(preview_lines("ok", cx), 1);
1294 assert_eq!(preview_lines("a\nb", cx), 2);
1295 let long = "Cristina: ok, thanks for the info! I think not now ".repeat(3);
1296 assert!(preview_lines(&long, cx) >= 2);
1297 });
1298 }
1299}