| 1 | use std::collections::{HashMap, HashSet}; |
| 2 | use std::sync::Arc; |
| 3 | use std::time::Instant; |
| 4 | |
| 5 | use chatsvc::TypingEvent; |
| 6 | use chrono::{DateTime, Utc}; |
| 7 | use gpui_kit::*; |
| 8 | use store::{ChatRecord, Sidebar, Store}; |
| 9 | use teams_core::{ |
| 10 | ChatApp, ChatSection, ChatSectionSettings, CoreEvent, ImageRef, PinnedMessage, PresenceStatus, |
| 11 | ScheduledDraft, |
| 12 | }; |
| 13 | |
| 14 | use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState}; |
| 15 | use crate::call::{ActiveCall, CallLauncher, CallMedia, MissedCall, Rings}; |
| 16 | use calling::meeting::LiveMeeting; |
| 17 | use crate::card_state::{CardState, TaskDialogState}; |
| 18 | use crate::data::{self, Directory}; |
| 19 | use crate::image_view_gallery::ViewerRequest; |
| 20 | use crate::local_previews::{LocalPreview, load_local_previews}; |
| 21 | use crate::message_actions::{ForwardSource, SavedSet}; |
| 22 | use crate::notice::Notice; |
| 23 | use crate::profile_state::{ProfileCache, ProfileRequest}; |
| 24 | use crate::translation::TranslationState; |
| 25 | use crate::typing::TypingState; |
| 26 | |
| 27 | const COLLAPSED_META_KEY: &str = "ui.collapsed_sections"; |
| 28 | const RECENT_MESSAGES_FOR_TYPING: usize = 5; |
| 29 | |
| 30 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 31 | pub enum Selection { |
| 32 | Chat(String), |
| 33 | Channel(String), |
| 34 | } |
| 35 | |
| 36 | impl Selection { |
| 37 | pub fn conversation_id(&self) -> &str { |
| 38 | match self { |
| 39 | Selection::Chat(id) | Selection::Channel(id) => id, |
| 40 | } |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | pub enum AppEvent { |
| 45 | Sidebar, |
| 46 | Selection, |
| 47 | Messages(String), |
| 48 | Images(Vec<String>), |
| 49 | Jump, |
| 50 | Status, |
| 51 | Directory, |
| 52 | Cards(String), |
| 53 | TaskDialog, |
| 54 | Typing, |
| 55 | LocalPreviews, |
| 56 | Outbox(String), |
| 57 | Scheduled, |
| 58 | Pins(String), |
| 59 | Saved, |
| 60 | CallHistory, |
| 61 | Translation, |
| 62 | Forward, |
| 63 | ImageViewer, |
| 64 | StatusMessage, |
| 65 | NotificationSettings, |
| 66 | Profile, |
| 67 | Call, |
| 68 | Ring, |
| 69 | LiveMeeting, |
| 70 | MissedCall(MissedCall), |
| 71 | } |
| 72 | |
| 73 | #[derive(Debug, Clone, Copy, Default)] |
| 74 | pub struct Mode { |
| 75 | pub demo: bool, |
| 76 | pub read_only: bool, |
| 77 | pub demo_sync: Option<std::time::Duration>, |
| 78 | } |
| 79 | |
| 80 | pub struct AppState { |
| 81 | pub store: Arc<Store>, |
| 82 | pub engine: Option<Arc<Engine>>, |
| 83 | pub sidebar: Sidebar, |
| 84 | pub favorite_ids: Vec<String>, |
| 85 | pub selection: Option<Selection>, |
| 86 | pub new_chat: bool, |
| 87 | pub connection: ConnectionState, |
| 88 | pub live: LiveState, |
| 89 | pub last_sync: Option<DateTime<Utc>>, |
| 90 | pub mode: Mode, |
| 91 | pub directory: Directory, |
| 92 | pub collapsed: HashSet<String>, |
| 93 | pub expanded_lists: HashSet<String>, |
| 94 | pub start_on_channels: bool, |
| 95 | pub pending_jump: Option<(String, String)>, |
| 96 | pub cards: CardState, |
| 97 | pub task_dialog: Option<TaskDialogState>, |
| 98 | pub bot_apps: HashMap<String, Vec<ChatApp>>, |
| 99 | pub bot_apps_pending: HashSet<String>, |
| 100 | pub notice: Option<Notice>, |
| 101 | pub notice_count: u64, |
| 102 | pub keep_unread: Option<String>, |
| 103 | pub typing: TypingState, |
| 104 | typing_timer_running: bool, |
| 105 | pub local_previews: HashMap<String, LocalPreview>, |
| 106 | pub scheduled: Vec<ScheduledDraft>, |
| 107 | pub scheduled_polling: bool, |
| 108 | pub saved: SavedSet, |
| 109 | pub call_history: Vec<teams_core::CallLogEntry>, |
| 110 | pub calendar_events: Vec<chatsvc::CalendarEvent>, |
| 111 | pub calendar_nudge: Option<tokio::sync::mpsc::UnboundedSender<()>>, |
| 112 | pub calls_list: crate::call::CallsList, |
| 113 | pub pins: HashMap<String, Vec<PinnedMessage>>, |
| 114 | pub forward_request: Option<ForwardSource>, |
| 115 | pub image_viewer_request: Option<ViewerRequest>, |
| 116 | pub own_status: PresenceStatus, |
| 117 | pub own_email: String, |
| 118 | pub status_menu_open: bool, |
| 119 | pub status_message_request: bool, |
| 120 | pub profiles: ProfileCache, |
| 121 | pub profile_request: Option<ProfileRequest>, |
| 122 | pub call: Option<ActiveCall>, |
| 123 | pub call_media: Option<Entity<CallMedia>>, |
| 124 | pub call_launcher: Option<Arc<CallLauncher>>, |
| 125 | pub call_count: u64, |
| 126 | pub call_share_sound: bool, |
| 127 | pub call_background: crate::call::BackgroundPick, |
| 128 | pub call_camera: calling::DeviceChoice, |
| 129 | pub meet_now_pending: bool, |
| 130 | pub call_backgrounds: crate::call::BackgroundLibrary, |
| 131 | pub transfer_picker: Option<Entity<crate::views::transfer_picker::TransferPicker>>, |
| 132 | pub rings: Rings, |
| 133 | pub live_meetings: HashMap<String, LiveMeeting>, |
| 134 | pub live_refreshing: HashSet<String>, |
| 135 | pub translation: TranslationState, |
| 136 | } |
| 137 | |
| 138 | pub struct AppHandle(pub Entity<AppState>); |
| 139 | |
| 140 | impl Global for AppHandle {} |
| 141 | |
| 142 | impl EventEmitter<AppEvent> for AppState {} |
| 143 | |
| 144 | pub fn chat_title(chat: &ChatRecord) -> String { |
| 145 | chat.display_title() |
| 146 | } |
| 147 | |
| 148 | pub fn selection_title(sidebar: &Sidebar, selection: &Selection) -> String { |
| 149 | match selection { |
| 150 | Selection::Chat(id) => sidebar |
| 151 | .chats |
| 152 | .iter() |
| 153 | .find(|chat| &chat.id == id) |
| 154 | .map(chat_title) |
| 155 | .unwrap_or_else(|| "Chat".to_owned()), |
| 156 | Selection::Channel(id) => sidebar |
| 157 | .teams |
| 158 | .iter() |
| 159 | .find_map(|team| { |
| 160 | team.channels |
| 161 | .iter() |
| 162 | .find(|channel| &channel.id == id) |
| 163 | .map(|channel| format!("{} / {}", team.team.name, channel.name)) |
| 164 | }) |
| 165 | .unwrap_or_else(|| "Channel".to_owned()), |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | impl AppState { |
| 170 | pub fn new(store: Arc<Store>, mode: Mode) -> Self { |
| 171 | let sidebar = store.sidebar().unwrap_or_default(); |
| 172 | let mut state = AppState { |
| 173 | store, |
| 174 | engine: None, |
| 175 | sidebar, |
| 176 | favorite_ids: Vec::new(), |
| 177 | selection: None, |
| 178 | new_chat: false, |
| 179 | connection: if mode.demo { |
| 180 | ConnectionState::Online |
| 181 | } else { |
| 182 | ConnectionState::Connecting |
| 183 | }, |
| 184 | live: LiveState::Off, |
| 185 | last_sync: None, |
| 186 | mode, |
| 187 | directory: Directory::default(), |
| 188 | collapsed: HashSet::new(), |
| 189 | expanded_lists: HashSet::new(), |
| 190 | start_on_channels: false, |
| 191 | pending_jump: None, |
| 192 | cards: CardState::default(), |
| 193 | task_dialog: None, |
| 194 | bot_apps: HashMap::new(), |
| 195 | bot_apps_pending: HashSet::new(), |
| 196 | notice: None, |
| 197 | notice_count: 0, |
| 198 | keep_unread: None, |
| 199 | typing: TypingState::default(), |
| 200 | typing_timer_running: false, |
| 201 | local_previews: HashMap::new(), |
| 202 | scheduled: Vec::new(), |
| 203 | scheduled_polling: false, |
| 204 | saved: SavedSet::default(), |
| 205 | call_history: Vec::new(), |
| 206 | calendar_events: Vec::new(), |
| 207 | calendar_nudge: None, |
| 208 | calls_list: crate::call::CallsList::default(), |
| 209 | pins: HashMap::new(), |
| 210 | forward_request: None, |
| 211 | image_viewer_request: None, |
| 212 | own_status: PresenceStatus::default(), |
| 213 | own_email: String::new(), |
| 214 | status_menu_open: false, |
| 215 | status_message_request: false, |
| 216 | profiles: ProfileCache::new(), |
| 217 | profile_request: None, |
| 218 | call: None, |
| 219 | call_media: None, |
| 220 | call_launcher: None, |
| 221 | call_count: 0, |
| 222 | call_share_sound: false, |
| 223 | call_background: crate::call::BackgroundPick::None, |
| 224 | call_camera: calling::DeviceChoice::SystemDefault, |
| 225 | meet_now_pending: false, |
| 226 | call_backgrounds: if mode.demo { |
| 227 | crate::call::demo_library() |
| 228 | } else { |
| 229 | crate::call::BackgroundLibrary::new(crate::call::default_cache_directory()) |
| 230 | }, |
| 231 | transfer_picker: None, |
| 232 | rings: Rings::default(), |
| 233 | live_meetings: HashMap::new(), |
| 234 | live_refreshing: HashSet::new(), |
| 235 | translation: TranslationState::default(), |
| 236 | }; |
| 237 | state.local_previews = load_local_previews(&state.store); |
| 238 | state.collapsed = state.load_collapsed(); |
| 239 | state.call_share_sound = crate::call::load_share_sound(&state.store); |
| 240 | state.call_background = crate::call::load_background(&state.store); |
| 241 | state.call_camera = crate::call::load_camera(&state.store); |
| 242 | state.call_backgrounds.customs = crate::call::load_custom_backgrounds(&state.store); |
| 243 | state.load_cached_translation_settings(); |
| 244 | if !mode.demo { |
| 245 | state.directory.load_cached_presence(&state.store); |
| 246 | state.reload_directory(); |
| 247 | } |
| 248 | state |
| 249 | } |
| 250 | |
| 251 | fn load_collapsed(&self) -> HashSet<String> { |
| 252 | self.store |
| 253 | .meta(COLLAPSED_META_KEY) |
| 254 | .ok() |
| 255 | .flatten() |
| 256 | .map(|value| { |
| 257 | value |
| 258 | .lines() |
| 259 | .map(str::to_owned) |
| 260 | .filter(|id| !id.is_empty()) |
| 261 | .collect() |
| 262 | }) |
| 263 | .unwrap_or_default() |
| 264 | } |
| 265 | |
| 266 | pub fn toggle_collapsed(&mut self, section_id: &str, cx: &mut Context<Self>) { |
| 267 | let now_collapsed = self.collapsed.insert(section_id.to_owned()); |
| 268 | if !now_collapsed { |
| 269 | self.collapsed.remove(section_id); |
| 270 | } |
| 271 | self.save_collapsed(); |
| 272 | self.sync_folder_expanded(section_id, !now_collapsed); |
| 273 | cx.emit(AppEvent::Sidebar); |
| 274 | cx.notify(); |
| 275 | } |
| 276 | |
| 277 | pub fn toggle_list_expanded(&mut self, section_id: &str, cx: &mut Context<Self>) { |
| 278 | if !self.expanded_lists.remove(section_id) { |
| 279 | self.expanded_lists.insert(section_id.to_owned()); |
| 280 | } |
| 281 | cx.emit(AppEvent::Sidebar); |
| 282 | cx.notify(); |
| 283 | } |
| 284 | |
| 285 | fn save_collapsed(&self) { |
| 286 | let mut ids: Vec<&str> = self.collapsed.iter().map(String::as_str).collect(); |
| 287 | ids.sort_unstable(); |
| 288 | let _ = self.store.set_meta(COLLAPSED_META_KEY, &ids.join("\n")); |
| 289 | } |
| 290 | |
| 291 | fn sync_folder_expanded(&mut self, folder_id: &str, expanded: bool) { |
| 292 | let Some(folder) = self |
| 293 | .directory |
| 294 | .folders |
| 295 | .iter_mut() |
| 296 | .find(|folder| folder.id == folder_id && folder.expanded.is_some()) |
| 297 | else { |
| 298 | return; |
| 299 | }; |
| 300 | folder.expanded = Some(expanded); |
| 301 | let _ = self.store.set_folder_expanded(folder_id, expanded); |
| 302 | if let Some(engine) = self.engine.clone().filter(|_| !self.mode.read_only) { |
| 303 | let folder_id = folder_id.to_owned(); |
| 304 | drop(crate::runtime::spawn(async move { |
| 305 | engine.set_folder_expanded(&folder_id, expanded).await |
| 306 | })); |
| 307 | } |
| 308 | } |
| 309 | |
| 310 | fn adopt_folder_expanded(&mut self) { |
| 311 | let snapshot = self.collapsed.clone(); |
| 312 | for folder in &self.directory.folders { |
| 313 | match folder.expanded { |
| 314 | Some(true) => { |
| 315 | self.collapsed.remove(&folder.id); |
| 316 | } |
| 317 | Some(false) => { |
| 318 | self.collapsed.insert(folder.id.clone()); |
| 319 | } |
| 320 | None => {} |
| 321 | } |
| 322 | } |
| 323 | if self.collapsed != snapshot { |
| 324 | self.save_collapsed(); |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | pub fn set_chat_section( |
| 329 | &mut self, |
| 330 | section: ChatSection, |
| 331 | enabled: bool, |
| 332 | cx: &mut Context<Self>, |
| 333 | ) { |
| 334 | let Some(engine_or_demo) = self.chat_action_engine(cx) else { |
| 335 | return; |
| 336 | }; |
| 337 | let previous = self.directory.section_settings; |
| 338 | let mut updated = previous; |
| 339 | updated.set(section, enabled); |
| 340 | self.apply_section_settings(updated, cx); |
| 341 | let Some(engine) = engine_or_demo else { |
| 342 | return; |
| 343 | }; |
| 344 | self.run_chat_action( |
| 345 | "Chat list setting", |
| 346 | async move { engine.set_section_enabled(section, enabled).await }, |
| 347 | move |state, cx| state.apply_section_settings(previous, cx), |
| 348 | |_, _| {}, |
| 349 | cx, |
| 350 | ); |
| 351 | } |
| 352 | |
| 353 | fn apply_section_settings(&mut self, settings: ChatSectionSettings, cx: &mut Context<Self>) { |
| 354 | self.directory.section_settings = settings; |
| 355 | let _ = teams_core::store_section_settings(&self.store, &settings); |
| 356 | cx.emit(AppEvent::Sidebar); |
| 357 | cx.notify(); |
| 358 | } |
| 359 | |
| 360 | pub fn reload_directory(&mut self) { |
| 361 | self.directory.me = data::me(&self.store); |
| 362 | self.own_email = self |
| 363 | .store |
| 364 | .meta("me_email") |
| 365 | .ok() |
| 366 | .flatten() |
| 367 | .unwrap_or_default(); |
| 368 | self.directory.folders = data::folders(&self.store, &self.favorite_ids); |
| 369 | self.directory.section_settings = teams_core::stored_section_settings(&self.store); |
| 370 | self.adopt_folder_expanded(); |
| 371 | self.directory.pinned_channels = data::pinned_channels(&self.store); |
| 372 | if self.directory.pinned_channels.is_empty() { |
| 373 | let known: HashSet<&str> = self |
| 374 | .sidebar |
| 375 | .teams |
| 376 | .iter() |
| 377 | .flat_map(|team| team.channels.iter().map(|channel| channel.id.as_str())) |
| 378 | .collect(); |
| 379 | self.directory.pinned_channels = self |
| 380 | .favorite_ids |
| 381 | .iter() |
| 382 | .filter(|id| known.contains(id.as_str())) |
| 383 | .cloned() |
| 384 | .collect(); |
| 385 | } |
| 386 | self.resolve_pending_avatars(); |
| 387 | self.sync_presence(); |
| 388 | self.directory.unread_counts = match &self.engine { |
| 389 | Some(engine) => data::unread_counts(engine, &self.sidebar.chats), |
| 390 | None => Default::default(), |
| 391 | }; |
| 392 | } |
| 393 | |
| 394 | pub fn request_avatars(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) { |
| 395 | let wanted = self.directory.missing_avatars(user_ids); |
| 396 | if wanted.is_empty() { |
| 397 | return; |
| 398 | } |
| 399 | let mut changed = false; |
| 400 | let mut uncached = Vec::new(); |
| 401 | for user_id in wanted { |
| 402 | match data::cached_avatar(&self.store, &user_id) { |
| 403 | Some(cached) => { |
| 404 | self.directory.set_avatar(&user_id, cached); |
| 405 | changed = true; |
| 406 | } |
| 407 | None => uncached.push(user_id), |
| 408 | } |
| 409 | } |
| 410 | if let Some(engine) = self.engine.clone().filter(|_| !uncached.is_empty()) { |
| 411 | self.directory.mark_avatars_pending(&uncached); |
| 412 | let done = data::fetch_avatars(&engine, uncached); |
| 413 | self.on_done(done, cx, |state, cx| { |
| 414 | state.resolve_pending_avatars(); |
| 415 | cx.emit(AppEvent::Directory); |
| 416 | cx.notify(); |
| 417 | }); |
| 418 | changed = true; |
| 419 | } |
| 420 | if changed { |
| 421 | cx.emit(AppEvent::Directory); |
| 422 | cx.notify(); |
| 423 | } |
| 424 | } |
| 425 | |
| 426 | pub fn request_images(&mut self, images: Vec<ImageRef>, cx: &mut Context<Self>) { |
| 427 | let Some(engine) = self.engine.clone() else { |
| 428 | return; |
| 429 | }; |
| 430 | let wanted = self |
| 431 | .directory |
| 432 | .images_to_request(images.iter().map(|image| image.url.clone())); |
| 433 | let mut changed = false; |
| 434 | for image in images |
| 435 | .into_iter() |
| 436 | .filter(|image| wanted.contains(&image.url)) |
| 437 | { |
| 438 | match engine.image_path(&image) { |
| 439 | Some(path) => { |
| 440 | self.directory.set_image(&image.url, &path); |
| 441 | changed = true; |
| 442 | } |
| 443 | None => { |
| 444 | let done = data::fetch_image(&engine, image.clone()); |
| 445 | cx.spawn(async move |this, cx| { |
| 446 | if !matches!(done.await, Ok(Ok(()))) { |
| 447 | this.update(cx, |state, cx| { |
| 448 | state.directory.mark_image_failed(&image.url); |
| 449 | cx.notify(); |
| 450 | }) |
| 451 | .ok(); |
| 452 | } |
| 453 | }) |
| 454 | .detach(); |
| 455 | } |
| 456 | } |
| 457 | } |
| 458 | if changed { |
| 459 | cx.emit(AppEvent::Images(wanted)); |
| 460 | cx.notify(); |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | pub fn jump_to_message( |
| 465 | &mut self, |
| 466 | selection: Selection, |
| 467 | message_id: String, |
| 468 | cx: &mut Context<Self>, |
| 469 | ) { |
| 470 | self.pending_jump = Some((selection.conversation_id().to_owned(), message_id)); |
| 471 | if self.selection.as_ref() == Some(&selection) { |
| 472 | cx.emit(AppEvent::Jump); |
| 473 | } else { |
| 474 | self.select(selection, cx); |
| 475 | } |
| 476 | } |
| 477 | |
| 478 | fn on_done( |
| 479 | &self, |
| 480 | done: data::Done, |
| 481 | cx: &mut Context<Self>, |
| 482 | then: impl FnOnce(&mut Self, &mut Context<Self>) + 'static, |
| 483 | ) { |
| 484 | cx.spawn(async move |this, cx| { |
| 485 | let _ = done.await; |
| 486 | this.update(cx, |state, cx| then(state, cx)).ok(); |
| 487 | }) |
| 488 | .detach(); |
| 489 | } |
| 490 | |
| 491 | fn resolve_pending_avatars(&mut self) { |
| 492 | for user_id in self.directory.pending_avatars() { |
| 493 | if let Some(cached) = data::cached_avatar(&self.store, &user_id) { |
| 494 | self.directory.set_avatar(&user_id, cached); |
| 495 | } |
| 496 | } |
| 497 | } |
| 498 | |
| 499 | fn sync_presence(&mut self) -> Vec<String> { |
| 500 | let Some(engine) = self.engine.clone() else { |
| 501 | return Vec::new(); |
| 502 | }; |
| 503 | self.directory |
| 504 | .requested_presence_ids() |
| 505 | .into_iter() |
| 506 | .filter(|user_id| { |
| 507 | let Some(kind) = data::presence_kind(&engine, user_id) else { |
| 508 | return false; |
| 509 | }; |
| 510 | let activity_changed = self |
| 511 | .directory |
| 512 | .set_activity(user_id, data::presence_activity(&engine, user_id)); |
| 513 | self.directory.set_presence(user_id, kind) || activity_changed |
| 514 | }) |
| 515 | .collect() |
| 516 | } |
| 517 | |
| 518 | pub fn request_presence(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) { |
| 519 | let now = Instant::now(); |
| 520 | let pushed = self.live == LiveState::Live; |
| 521 | let wanted = self.directory.stale_presence(user_ids, now, pushed); |
| 522 | if wanted.is_empty() { |
| 523 | return; |
| 524 | } |
| 525 | self.directory.mark_presence_pending(&wanted); |
| 526 | if let Some(engine) = self.engine.clone() { |
| 527 | self.directory.mark_presence_requested(&wanted, now); |
| 528 | drop(data::watch_presence(&engine, wanted.clone())); |
| 529 | let done = data::refresh_presence(&engine, wanted.clone()); |
| 530 | self.on_done(done, cx, move |state, cx| { |
| 531 | state.sync_presence(); |
| 532 | state.directory.save_presence(&state.store, &wanted); |
| 533 | state.directory.settle_presence(&wanted); |
| 534 | cx.emit(AppEvent::Directory); |
| 535 | cx.notify(); |
| 536 | }); |
| 537 | } |
| 538 | } |
| 539 | |
| 540 | pub fn move_chat( |
| 541 | &mut self, |
| 542 | conversation_id: &str, |
| 543 | folder_id: Option<&str>, |
| 544 | cx: &mut Context<Self>, |
| 545 | ) { |
| 546 | if self.mode.read_only { |
| 547 | return; |
| 548 | } |
| 549 | let previous_folder = self |
| 550 | .directory |
| 551 | .folder_of(conversation_id) |
| 552 | .map(|folder| folder.id.clone()); |
| 553 | self.directory.assign(conversation_id, folder_id); |
| 554 | if let Some(engine) = self.engine.clone() { |
| 555 | let previous = previous_folder.clone(); |
| 556 | let done = match (folder_id, previous.as_deref()) { |
| 557 | (Some(folder_id), _) => { |
| 558 | Some(data::move_to_folder(&engine, conversation_id, folder_id)) |
| 559 | } |
| 560 | (None, Some(previous)) => { |
| 561 | Some(data::remove_from_folder(&engine, conversation_id, previous)) |
| 562 | } |
| 563 | (None, None) => None, |
| 564 | }; |
| 565 | if let Some(done) = done { |
| 566 | self.on_done(done, cx, |state, cx| { |
| 567 | state.reload_directory(); |
| 568 | cx.emit(AppEvent::Sidebar); |
| 569 | cx.notify(); |
| 570 | }); |
| 571 | } |
| 572 | } |
| 573 | cx.emit(AppEvent::Sidebar); |
| 574 | cx.notify(); |
| 575 | } |
| 576 | |
| 577 | pub fn pin_chat(&mut self, conversation_id: &str, cx: &mut Context<Self>) { |
| 578 | let favorites = self.directory.favorites().map(|folder| folder.id.clone()); |
| 579 | self.move_chat(conversation_id, favorites.as_deref(), cx); |
| 580 | } |
| 581 | |
| 582 | pub fn mark_chat_read(&mut self, conversation_id: &str, cx: &mut Context<Self>) { |
| 583 | if self.keeps_unread(conversation_id) { |
| 584 | self.keep_unread = None; |
| 585 | } |
| 586 | if self.mode.demo { |
| 587 | if let Some(chat) = self |
| 588 | .sidebar |
| 589 | .chats |
| 590 | .iter() |
| 591 | .find(|chat| chat.id == conversation_id) |
| 592 | { |
| 593 | let mut read = chat.clone(); |
| 594 | read.unread = false; |
| 595 | let _ = self.store.upsert_chats(&[read]); |
| 596 | self.reload_sidebar(cx); |
| 597 | } |
| 598 | return; |
| 599 | } |
| 600 | if self.mode.read_only { |
| 601 | return; |
| 602 | } |
| 603 | if let Some(engine) = self.engine.clone() { |
| 604 | let _ = self |
| 605 | .store |
| 606 | .mark_chat_read(conversation_id, chrono::Utc::now()); |
| 607 | self.reload_sidebar(cx); |
| 608 | let conversation_id = conversation_id.to_owned(); |
| 609 | drop(crate::runtime::spawn(async move { |
| 610 | engine.mark_read(&conversation_id).await |
| 611 | })); |
| 612 | } |
| 613 | } |
| 614 | |
| 615 | pub fn start_new_chat(&mut self, cx: &mut Context<Self>) { |
| 616 | self.new_chat = true; |
| 617 | self.show_call(false, cx); |
| 618 | cx.emit(AppEvent::Selection); |
| 619 | cx.notify(); |
| 620 | } |
| 621 | |
| 622 | pub fn close_new_chat(&mut self, cx: &mut Context<Self>) { |
| 623 | if !self.new_chat { |
| 624 | return; |
| 625 | } |
| 626 | self.new_chat = false; |
| 627 | cx.emit(AppEvent::Selection); |
| 628 | cx.notify(); |
| 629 | } |
| 630 | |
| 631 | pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) { |
| 632 | self.show_call(false, cx); |
| 633 | let was_drafting = std::mem::take(&mut self.new_chat); |
| 634 | if !was_drafting && self.selection.as_ref() == Some(&selection) { |
| 635 | return; |
| 636 | } |
| 637 | let conversation_id = selection.conversation_id().to_owned(); |
| 638 | self.selection = Some(selection); |
| 639 | self.keep_unread = None; |
| 640 | cx.emit(AppEvent::Selection); |
| 641 | cx.notify(); |
| 642 | self.refresh_live_meeting(&conversation_id, cx); |
| 643 | self.refresh_language_stamps(&conversation_id, cx); |
| 644 | } |
| 645 | |
| 646 | fn apply_typing(&mut self, event: TypingEvent, cx: &mut Context<Self>) { |
| 647 | let is_me = self |
| 648 | .directory |
| 649 | .me |
| 650 | .as_ref() |
| 651 | .is_some_and(|me| me.user_id == event.user_id); |
| 652 | if is_me { |
| 653 | return; |
| 654 | } |
| 655 | if event.active { |
| 656 | let display_name = match event.display_name.trim() { |
| 657 | "" => crate::people::resolve_names(self, std::slice::from_ref(&event.user_id)) |
| 658 | .remove(&event.user_id) |
| 659 | .unwrap_or_default(), |
| 660 | _ => event.display_name.clone(), |
| 661 | }; |
| 662 | self.typing.start( |
| 663 | &event.conversation_id, |
| 664 | &event.user_id, |
| 665 | &display_name, |
| 666 | Instant::now(), |
| 667 | event.received_at, |
| 668 | ); |
| 669 | self.request_avatars(vec![event.user_id.clone()], cx); |
| 670 | self.schedule_typing_expiry(cx); |
| 671 | } else { |
| 672 | self.typing.clear(&event.conversation_id, &event.user_id); |
| 673 | } |
| 674 | cx.emit(AppEvent::Typing); |
| 675 | cx.notify(); |
| 676 | } |
| 677 | |
| 678 | fn clear_typists_who_sent(&mut self, conversation_id: &str, cx: &mut Context<Self>) { |
| 679 | if !self.typing.is_active(conversation_id) { |
| 680 | return; |
| 681 | } |
| 682 | let Ok(recent) = self |
| 683 | .store |
| 684 | .messages(conversation_id, None, RECENT_MESSAGES_FOR_TYPING) |
| 685 | else { |
| 686 | return; |
| 687 | }; |
| 688 | let mut changed = false; |
| 689 | for message in recent { |
| 690 | if let Some(sender_id) = message.sender_id.as_deref() { |
| 691 | changed |= self |
| 692 | .typing |
| 693 | .message_from(conversation_id, sender_id, message.created_at); |
| 694 | } |
| 695 | } |
| 696 | if changed { |
| 697 | cx.emit(AppEvent::Typing); |
| 698 | cx.notify(); |
| 699 | } |
| 700 | } |
| 701 | |
| 702 | fn schedule_typing_expiry(&mut self, cx: &mut Context<Self>) { |
| 703 | if self.typing_timer_running { |
| 704 | return; |
| 705 | } |
| 706 | self.typing_timer_running = true; |
| 707 | cx.spawn(async move |this, cx| { |
| 708 | loop { |
| 709 | let next = this.update(cx, |state, _| { |
| 710 | let next = state.typing.next_expiry(); |
| 711 | state.typing_timer_running = next.is_some(); |
| 712 | next |
| 713 | }); |
| 714 | let Ok(Some(next)) = next else { return }; |
| 715 | cx.background_executor() |
| 716 | .timer(next.saturating_duration_since(Instant::now())) |
| 717 | .await; |
| 718 | let alive = this.update(cx, |state, cx| { |
| 719 | if state.typing.expire(Instant::now()) { |
| 720 | cx.emit(AppEvent::Typing); |
| 721 | cx.notify(); |
| 722 | } |
| 723 | }); |
| 724 | if alive.is_err() { |
| 725 | return; |
| 726 | } |
| 727 | } |
| 728 | }) |
| 729 | .detach(); |
| 730 | } |
| 731 | |
| 732 | pub fn reload_sidebar(&mut self, cx: &mut Context<Self>) { |
| 733 | if let Ok(sidebar) = self.store.sidebar() { |
| 734 | self.sidebar = sidebar; |
| 735 | self.apply_bot_titles(); |
| 736 | } |
| 737 | self.calls_list.invalidate(); |
| 738 | if !self.mode.demo { |
| 739 | self.reload_directory(); |
| 740 | } |
| 741 | cx.emit(AppEvent::Sidebar); |
| 742 | cx.notify(); |
| 743 | } |
| 744 | |
| 745 | pub fn apply(&mut self, event: BackendEvent, cx: &mut Context<Self>) { |
| 746 | match event { |
| 747 | BackendEvent::Connection(connection) => { |
| 748 | self.connection = connection; |
| 749 | cx.emit(AppEvent::Status); |
| 750 | } |
| 751 | BackendEvent::Calls(launcher) => { |
| 752 | launcher.set_default_camera(self.call_camera.clone()); |
| 753 | self.call_launcher = Some(launcher); |
| 754 | } |
| 755 | BackendEvent::Calendar(events) => self.apply_calendar(events, cx), |
| 756 | BackendEvent::CalendarNudge(nudge) => self.calendar_nudge = Some(nudge), |
| 757 | BackendEvent::Ring(event) => self.on_engine_event(event, cx), |
| 758 | BackendEvent::ThreadChanged(conversation_id) => self.on_thread_changed(&conversation_id, cx), |
| 759 | BackendEvent::Engine(engine) => { |
| 760 | crate::agent_api::engine_ready(engine.clone(), cx); |
| 761 | self.engine = Some(engine); |
| 762 | self.resend_outbox(cx); |
| 763 | self.refresh_scheduled(cx); |
| 764 | self.refresh_translation_settings(cx); |
| 765 | let waiting = self.directory.waiting_presence_ids(); |
| 766 | self.request_presence(waiting, cx); |
| 767 | self.refresh_own_status(cx); |
| 768 | cx.emit(AppEvent::Status); |
| 769 | } |
| 770 | BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar(cx), |
| 771 | BackendEvent::Core( |
| 772 | CoreEvent::MessagesChanged { conversation_id } |
| 773 | | CoreEvent::ReceiptsChanged { conversation_id }, |
| 774 | ) => { |
| 775 | self.clear_typists_who_sent(&conversation_id, cx); |
| 776 | self.refresh_language_stamps(&conversation_id, cx); |
| 777 | cx.emit(AppEvent::Messages(conversation_id)); |
| 778 | } |
| 779 | BackendEvent::Core(CoreEvent::PinsChanged { conversation_id }) => { |
| 780 | self.refresh_pins(&conversation_id, cx); |
| 781 | } |
| 782 | BackendEvent::Core(CoreEvent::ImagesChanged { keys }) => { |
| 783 | if let Some(engine) = &self.engine { |
| 784 | for key in &keys { |
| 785 | let image = ImageRef { |
| 786 | id: String::new(), |
| 787 | url: key.clone(), |
| 788 | width: None, |
| 789 | height: None, |
| 790 | }; |
| 791 | if let Some(path) = engine.image_path(&image) { |
| 792 | self.directory.set_image(key, &path); |
| 793 | } |
| 794 | } |
| 795 | } |
| 796 | cx.emit(AppEvent::Images(keys)); |
| 797 | } |
| 798 | BackendEvent::Core(CoreEvent::PresenceChanged) => { |
| 799 | let changed = self.sync_presence(); |
| 800 | self.directory.save_presence(&self.store, &changed); |
| 801 | cx.emit(AppEvent::Directory); |
| 802 | cx.notify(); |
| 803 | } |
| 804 | BackendEvent::Core(CoreEvent::PresenceStatusChanged(status)) => { |
| 805 | self.apply_own_status(status, cx); |
| 806 | self.reload_directory(); |
| 807 | } |
| 808 | BackendEvent::Core(_) => { |
| 809 | if !self.mode.demo { |
| 810 | self.reload_directory(); |
| 811 | } |
| 812 | cx.emit(AppEvent::Directory); |
| 813 | } |
| 814 | BackendEvent::Typing(event) => self.apply_typing(event, cx), |
| 815 | BackendEvent::Live(live) => { |
| 816 | self.live = live; |
| 817 | cx.emit(AppEvent::Status); |
| 818 | } |
| 819 | BackendEvent::Favorites(ids) => { |
| 820 | self.favorite_ids = ids; |
| 821 | if !self.mode.demo { |
| 822 | self.reload_directory(); |
| 823 | } |
| 824 | cx.emit(AppEvent::Sidebar); |
| 825 | } |
| 826 | BackendEvent::Synced(time) => { |
| 827 | if self.last_sync.is_none() { |
| 828 | self.refresh_saved(cx); |
| 829 | } |
| 830 | self.last_sync = Some(time); |
| 831 | cx.emit(AppEvent::Status); |
| 832 | } |
| 833 | } |
| 834 | cx.notify(); |
| 835 | } |
| 836 | } |
| 837 | |
| 838 | #[cfg(test)] |
| 839 | mod tests { |
| 840 | use std::sync::Arc; |
| 841 | |
| 842 | use chatsvc::TypingEvent; |
| 843 | use chrono::{Duration, Utc}; |
| 844 | use gpui_kit::{AppContext as _, TestAppContext}; |
| 845 | use store::{ |
| 846 | ChannelRecord, ChatRecord, MemberRecord, MessageRecord, SidebarTeam, Store, TeamRecord, |
| 847 | }; |
| 848 | use teams_core::CoreEvent; |
| 849 | |
| 850 | use super::{AppState, Mode, Selection, chat_title, selection_title}; |
| 851 | use crate::backend::BackendEvent; |
| 852 | use crate::data::Person; |
| 853 | use store::Sidebar; |
| 854 | |
| 855 | fn chat(id: &str, title: &str, unread: bool) -> ChatRecord { |
| 856 | ChatRecord { |
| 857 | id: id.into(), |
| 858 | kind: "group".into(), |
| 859 | title: title.into(), |
| 860 | member_summary: "Member".into(), |
| 861 | last_message_at: None, |
| 862 | last_read_at: None, |
| 863 | unread, |
| 864 | ..Default::default() |
| 865 | } |
| 866 | } |
| 867 | |
| 868 | fn sidebar() -> Sidebar { |
| 869 | Sidebar { |
| 870 | chats: vec![chat("c1", "First", true), chat("c2", "", false)], |
| 871 | teams: vec![SidebarTeam { |
| 872 | team: TeamRecord { |
| 873 | id: "t".into(), |
| 874 | name: "Team".into(), |
| 875 | }, |
| 876 | channels: vec![ChannelRecord { |
| 877 | id: "ch".into(), |
| 878 | team_id: "t".into(), |
| 879 | name: "General".into(), |
| 880 | membership_type: None, |
| 881 | last_message_at: None, |
| 882 | unread: false, |
| 883 | }], |
| 884 | hidden: false, |
| 885 | hidden_channel_ids: Vec::new(), |
| 886 | notifications: Default::default(), |
| 887 | }], |
| 888 | } |
| 889 | } |
| 890 | |
| 891 | #[test] |
| 892 | fn empty_chat_title_falls_back_to_members() { |
| 893 | assert_eq!(chat_title(&sidebar().chats[1]), "Member"); |
| 894 | } |
| 895 | |
| 896 | #[test] |
| 897 | fn selection_titles() { |
| 898 | assert_eq!( |
| 899 | selection_title(&sidebar(), &Selection::Channel("ch".into())), |
| 900 | "Team / General" |
| 901 | ); |
| 902 | assert_eq!( |
| 903 | selection_title(&sidebar(), &Selection::Chat("c1".into())), |
| 904 | "First" |
| 905 | ); |
| 906 | } |
| 907 | |
| 908 | fn typing_event(user_id: &str, active: bool) -> BackendEvent { |
| 909 | BackendEvent::Typing(TypingEvent { |
| 910 | conversation_id: "c1".into(), |
| 911 | user_id: user_id.into(), |
| 912 | display_name: format!("Name {user_id}"), |
| 913 | active, |
| 914 | received_at: Utc::now(), |
| 915 | }) |
| 916 | } |
| 917 | |
| 918 | #[gpui_kit::test] |
| 919 | fn typing_events_track_other_users_and_ignore_me(cx: &mut TestAppContext) { |
| 920 | cx.update(gpui_kit::init); |
| 921 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 922 | let app = cx.update(|cx| { |
| 923 | cx.new(|_| { |
| 924 | let mut state = AppState::new(store.clone(), Mode::default()); |
| 925 | state.directory.me = Some(Person { |
| 926 | user_id: "me".into(), |
| 927 | display_name: "Me".into(), |
| 928 | }); |
| 929 | state |
| 930 | }) |
| 931 | }); |
| 932 | let names = |cx: &mut TestAppContext| cx.update(|cx| app.read(cx).typing.names("c1")); |
| 933 | cx.update(|cx| { |
| 934 | app.update(cx, |state, cx| { |
| 935 | state.apply(typing_event("me", true), cx); |
| 936 | state.apply(typing_event("ada", true), cx); |
| 937 | }) |
| 938 | }); |
| 939 | assert_eq!(names(cx), vec!["Name ada".to_owned()]); |
| 940 | |
| 941 | let message = MessageRecord { |
| 942 | conversation_id: "c1".into(), |
| 943 | message_id: "m1".into(), |
| 944 | sender_id: Some("ada".into()), |
| 945 | created_at: Utc::now() + Duration::seconds(1), |
| 946 | ..Default::default() |
| 947 | }; |
| 948 | store.upsert_messages(&[message]).unwrap(); |
| 949 | cx.update(|cx| { |
| 950 | app.update(cx, |state, cx| { |
| 951 | state.apply( |
| 952 | BackendEvent::Core(CoreEvent::MessagesChanged { |
| 953 | conversation_id: "c1".into(), |
| 954 | }), |
| 955 | cx, |
| 956 | ) |
| 957 | }) |
| 958 | }); |
| 959 | assert!(names(cx).is_empty()); |
| 960 | |
| 961 | cx.update(|cx| { |
| 962 | app.update(cx, |state, cx| { |
| 963 | state.apply(typing_event("ada", true), cx); |
| 964 | state.apply(typing_event("ada", false), cx); |
| 965 | }) |
| 966 | }); |
| 967 | assert!(names(cx).is_empty()); |
| 968 | } |
| 969 | |
| 970 | #[gpui_kit::test] |
| 971 | fn typing_without_a_display_name_uses_the_chat_member_name(cx: &mut TestAppContext) { |
| 972 | cx.update(gpui_kit::init); |
| 973 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 974 | let app = cx.update(|cx| { |
| 975 | cx.new(|_| { |
| 976 | let mut state = AppState::new(store.clone(), Mode::default()); |
| 977 | let mut member_chat = chat("c1", "First", false); |
| 978 | member_chat.members = vec![MemberRecord { |
| 979 | user_id: Some("ada".into()), |
| 980 | display_name: "Ada Lovelace".into(), |
| 981 | }]; |
| 982 | state.sidebar.chats = vec![member_chat]; |
| 983 | state |
| 984 | }) |
| 985 | }); |
| 986 | cx.update(|cx| { |
| 987 | app.update(cx, |state, cx| { |
| 988 | state.apply( |
| 989 | BackendEvent::Typing(TypingEvent { |
| 990 | conversation_id: "c1".into(), |
| 991 | user_id: "ada".into(), |
| 992 | display_name: String::new(), |
| 993 | active: true, |
| 994 | received_at: Utc::now(), |
| 995 | }), |
| 996 | cx, |
| 997 | ) |
| 998 | }) |
| 999 | }); |
| 1000 | assert_eq!( |
| 1001 | cx.update(|cx| app.read(cx).typing.names("c1")), |
| 1002 | vec!["Ada Lovelace".to_owned()] |
| 1003 | ); |
| 1004 | } |
| 1005 | } |