BlueGit

ict rusty-teams

Files

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

center.rs

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