BlueGit

ict rusty-teams

Files

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

center.rs

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