| 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 crate::card_state::{CardState, TaskDialogState}; |
| 17 | use crate::data::{self, Directory}; |
| 18 | use crate::forward_selection::ForwardSelection; |
| 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::notify::LateArrivals; |
| 24 | use crate::profile_state::{ProfileCache, ProfileRequest}; |
| 25 | use crate::translation::TranslationState; |
| 26 | use crate::typing::TypingState; |
| 27 | use calling::meeting::LiveMeeting; |
| 28 | |
| 29 | const COLLAPSED_META_KEY: &str = "ui.collapsed_sections"; |
| 30 | const RECENT_MESSAGES_FOR_TYPING: usize = 5; |
| 31 | |
| 32 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 33 | pub enum QuickView { |
| 34 | Mentions, |
| 35 | Drafts, |
| 36 | Saved, |
| 37 | } |
| 38 | |
| 39 | impl QuickView { |
| 40 | pub fn title(self) -> &'static str { |
| 41 | match self { |
| 42 | QuickView::Mentions => "Mentions", |
| 43 | QuickView::Drafts => "Drafts", |
| 44 | QuickView::Saved => "Saved", |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | pub fn empty_text(self) -> &'static str { |
| 49 | match self { |
| 50 | QuickView::Mentions => "No mentions yet. When someone @mentions you, it shows up here.", |
| 51 | QuickView::Drafts => "No drafts. Messages you start and do not send show up here.", |
| 52 | QuickView::Saved => "No saved messages. Use Save message in the ... menu of a message.", |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 58 | pub enum Selection { |
| 59 | Chat(String), |
| 60 | Channel(String), |
| 61 | } |
| 62 | |
| 63 | impl Selection { |
| 64 | pub fn conversation_id(&self) -> &str { |
| 65 | match self { |
| 66 | Selection::Chat(id) | Selection::Channel(id) => id, |
| 67 | } |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | pub enum AppEvent { |
| 72 | Sidebar, |
| 73 | Activity, |
| 74 | Selection, |
| 75 | Messages(String), |
| 76 | Images(Vec<String>), |
| 77 | Jump, |
| 78 | Status, |
| 79 | Directory, |
| 80 | Cards(String), |
| 81 | TaskDialog, |
| 82 | Typing, |
| 83 | LocalPreviews, |
| 84 | Outbox(String), |
| 85 | Scheduled, |
| 86 | Pins(String), |
| 87 | Saved, |
| 88 | CallHistory, |
| 89 | Translation, |
| 90 | Forward, |
| 91 | ForwardSelection, |
| 92 | ImageViewer, |
| 93 | StatusMessage, |
| 94 | Settings(crate::settings_section::SettingsSection), |
| 95 | Profile, |
| 96 | Call, |
| 97 | Ring, |
| 98 | LiveMeeting, |
| 99 | MissedCall(MissedCall), |
| 100 | MeetingReminder, |
| 101 | MeetingChime, |
| 102 | CallTone(chatsvc::sounds::CallTone), |
| 103 | SoundSettings, |
| 104 | ChatSettings, |
| 105 | FollowedStatus { |
| 106 | user_id: String, |
| 107 | text: &'static str, |
| 108 | }, |
| 109 | } |
| 110 | |
| 111 | #[derive(Debug, Clone, Copy, Default)] |
| 112 | pub struct Mode { |
| 113 | pub demo: bool, |
| 114 | pub read_only: bool, |
| 115 | pub demo_sync: Option<std::time::Duration>, |
| 116 | } |
| 117 | |
| 118 | pub struct AppState { |
| 119 | pub store: Arc<Store>, |
| 120 | pub engine: Option<Arc<Engine>>, |
| 121 | pub sidebar: Sidebar, |
| 122 | pub favorite_ids: Vec<String>, |
| 123 | pub selection: Option<Selection>, |
| 124 | pub late_arrivals: LateArrivals, |
| 125 | pub acked_urgent: std::collections::HashSet<String>, |
| 126 | pub new_chat: bool, |
| 127 | pub new_chat_people: Vec<store::MemberRecord>, |
| 128 | pub connection: ConnectionState, |
| 129 | pub live: LiveState, |
| 130 | pub last_sync: Option<DateTime<Utc>>, |
| 131 | pub mode: Mode, |
| 132 | pub directory: Directory, |
| 133 | pub collapsed: HashSet<String>, |
| 134 | pub expanded_lists: HashSet<String>, |
| 135 | pub start_on_channels: bool, |
| 136 | pub pending_jump: Option<(String, String)>, |
| 137 | pub cards: CardState, |
| 138 | pub task_dialog: Option<TaskDialogState>, |
| 139 | pub bot_apps: HashMap<String, Vec<ChatApp>>, |
| 140 | pub bot_apps_pending: HashSet<String>, |
| 141 | pub notice: Option<Notice>, |
| 142 | pub connection_banner: crate::connection_banner::BannerTiming, |
| 143 | pub live_retry: Option<Arc<tokio::sync::Notify>>, |
| 144 | pub notice_count: u64, |
| 145 | pub followed_presence: Vec<crate::presence_follow::FollowedPerson>, |
| 146 | pub dismissed_absence_notices: std::collections::HashSet<String>, |
| 147 | pub followed_changes: Vec<(String, &'static str)>, |
| 148 | pub keep_unread: Option<String>, |
| 149 | pub restorable_deletes: crate::restorable_deletes::RestorableDeletes, |
| 150 | pub typing: TypingState, |
| 151 | typing_timer_running: bool, |
| 152 | pub(crate) sidebar_load: crate::sidebar_load::SidebarLoad, |
| 153 | pub(crate) warm_chats: crate::warm_chats::WarmChats, |
| 154 | pub local_previews: HashMap<String, LocalPreview>, |
| 155 | pub quick_view: Option<QuickView>, |
| 156 | pub manage_team: Option<crate::manage_team::ManageTeam>, |
| 157 | pub scheduled: Vec<ScheduledDraft>, |
| 158 | pub scheduled_polling: bool, |
| 159 | pub saved: SavedSet, |
| 160 | pub call_history: Vec<teams_core::CallLogEntry>, |
| 161 | pub calendar_events: Vec<chatsvc::CalendarEvent>, |
| 162 | pub calendar_nudge: Option<tokio::sync::mpsc::UnboundedSender<()>>, |
| 163 | pub calls_list: crate::call::CallsList, |
| 164 | pub speed_dial: Vec<crate::call::SpeedDialEntry>, |
| 165 | pub pins: HashMap<String, Vec<PinnedMessage>>, |
| 166 | pub post_follows: crate::post_follow::PostFollows, |
| 167 | pub forward_request: Option<ForwardSource>, |
| 168 | pub forward_selection: Option<ForwardSelection>, |
| 169 | pub image_viewer_request: Option<ViewerRequest>, |
| 170 | pub own_status: PresenceStatus, |
| 171 | pub notifications_paused_until: Option<chrono::DateTime<chrono::Utc>>, |
| 172 | pub own_email: String, |
| 173 | pub own_time_zone: Option<String>, |
| 174 | pub own_time_zone_requested: bool, |
| 175 | pub status_menu_open: bool, |
| 176 | pub status_message_request: bool, |
| 177 | pub profiles: ProfileCache, |
| 178 | pub profile_request: Option<ProfileRequest>, |
| 179 | pub call: Option<ActiveCall>, |
| 180 | pub held_call: Option<ActiveCall>, |
| 181 | pub call_end: Option<crate::call::end_screen::CallEndScreen>, |
| 182 | pub call_media: Option<Entity<CallMedia>>, |
| 183 | pub call_launcher: Option<Arc<CallLauncher>>, |
| 184 | pub call_count: u64, |
| 185 | pub call_share_sound: bool, |
| 186 | pub recording_policy: teams_core::RecordingPolicy, |
| 187 | pub allow_priority_messages: bool, |
| 188 | pub account_sounds: Option<chatsvc::sound_settings::SoundSettings>, |
| 189 | pub chat_settings: teams_core::ChatSettingsDocument, |
| 190 | pub markdown_mode: bool, |
| 191 | pub actions_on_right_click: bool, |
| 192 | pub demo_chat_desktop: HashMap<String, teams_core::DesktopNotifications>, |
| 193 | pub own_tenant: Option<String>, |
| 194 | pub call_share_motion: bool, |
| 195 | pub call_share_standout: bool, |
| 196 | pub call_report_enabled: bool, |
| 197 | pub call_view: crate::call::ViewSettings, |
| 198 | pub call_background: crate::call::BackgroundPick, |
| 199 | pub call_camera: calling::DeviceChoice, |
| 200 | pub call_input: calling::DeviceChoice, |
| 201 | pub call_output: calling::DeviceChoice, |
| 202 | pub call_mic: calling::MicSettings, |
| 203 | pub call_video_quality: calling::VideoQuality, |
| 204 | pub call_effects: calling::CameraEffects, |
| 205 | pub meet_now_pending: bool, |
| 206 | pub prejoin: Option<crate::call::PendingJoin>, |
| 207 | pub prejoin_count: u64, |
| 208 | pub join_options: crate::call::JoinOptions, |
| 209 | pub rsvp_send_response: bool, |
| 210 | pub meeting_toasts: crate::call::MeetingToasts, |
| 211 | pub demo_meetings: Vec<chatsvc::CalendarEvent>, |
| 212 | pub calendar_week: crate::call::week::CalendarWeek, |
| 213 | pub call_backgrounds: crate::call::BackgroundLibrary, |
| 214 | pub transfer_picker: Option<AnyView>, |
| 215 | pub transcript_panel: Option<AnyView>, |
| 216 | pub rings: Rings, |
| 217 | pub live_meetings: HashMap<String, LiveMeeting>, |
| 218 | pub live_refreshing: HashSet<String>, |
| 219 | pub translation: TranslationState, |
| 220 | pub section_changes: crate::section_actions::SectionChanges, |
| 221 | } |
| 222 | |
| 223 | pub struct AppHandle(pub Entity<AppState>); |
| 224 | |
| 225 | impl Global for AppHandle {} |
| 226 | |
| 227 | impl EventEmitter<AppEvent> for AppState {} |
| 228 | |
| 229 | pub fn selection_for(sidebar: &Sidebar, conversation_id: &str) -> Option<Selection> { |
| 230 | if sidebar.chats.iter().any(|chat| chat.id == conversation_id) { |
| 231 | return Some(Selection::Chat(conversation_id.to_owned())); |
| 232 | } |
| 233 | sidebar |
| 234 | .teams |
| 235 | .iter() |
| 236 | .flat_map(|team| team.channels.iter()) |
| 237 | .any(|channel| channel.id == conversation_id) |
| 238 | .then(|| Selection::Channel(conversation_id.to_owned())) |
| 239 | } |
| 240 | |
| 241 | pub fn chat_title(chat: &ChatRecord) -> String { |
| 242 | chat.display_title() |
| 243 | } |
| 244 | |
| 245 | pub fn selection_title(sidebar: &Sidebar, selection: &Selection) -> String { |
| 246 | match selection { |
| 247 | Selection::Chat(id) => sidebar |
| 248 | .chats |
| 249 | .iter() |
| 250 | .find(|chat| &chat.id == id) |
| 251 | .map(chat_title) |
| 252 | .unwrap_or_else(|| "Chat".to_owned()), |
| 253 | Selection::Channel(id) => sidebar |
| 254 | .teams |
| 255 | .iter() |
| 256 | .find_map(|team| { |
| 257 | team.channels |
| 258 | .iter() |
| 259 | .find(|channel| &channel.id == id) |
| 260 | .map(|channel| format!("{} / {}", team.team.name, channel.name)) |
| 261 | }) |
| 262 | .unwrap_or_else(|| "Channel".to_owned()), |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | impl AppState { |
| 267 | pub fn new(store: Arc<Store>, mode: Mode) -> Self { |
| 268 | let sidebar = store.sidebar().unwrap_or_default(); |
| 269 | let speed_dial = crate::call::speed_dial::load(&store); |
| 270 | let notifications_paused_until = crate::notify::pause::load(&store); |
| 271 | let chat_settings = teams_core::stored_chat_settings(&store); |
| 272 | let markdown_mode = crate::chat_settings_actions::stored_markdown_mode(&store); |
| 273 | let actions_on_right_click = |
| 274 | crate::chat_settings_actions::stored_actions_on_right_click(&store); |
| 275 | let mut state = AppState { |
| 276 | store, |
| 277 | engine: None, |
| 278 | sidebar, |
| 279 | favorite_ids: Vec::new(), |
| 280 | selection: None, |
| 281 | late_arrivals: LateArrivals::default(), |
| 282 | acked_urgent: Default::default(), |
| 283 | new_chat: false, |
| 284 | new_chat_people: Vec::new(), |
| 285 | connection: if mode.demo { |
| 286 | ConnectionState::Online |
| 287 | } else { |
| 288 | ConnectionState::Connecting |
| 289 | }, |
| 290 | live: LiveState::Off, |
| 291 | last_sync: None, |
| 292 | mode, |
| 293 | directory: Directory::default(), |
| 294 | collapsed: HashSet::new(), |
| 295 | expanded_lists: HashSet::new(), |
| 296 | start_on_channels: false, |
| 297 | pending_jump: None, |
| 298 | cards: CardState::default(), |
| 299 | task_dialog: None, |
| 300 | bot_apps: HashMap::new(), |
| 301 | bot_apps_pending: HashSet::new(), |
| 302 | notice: None, |
| 303 | connection_banner: Default::default(), |
| 304 | live_retry: None, |
| 305 | notice_count: 0, |
| 306 | followed_presence: Vec::new(), |
| 307 | dismissed_absence_notices: Default::default(), |
| 308 | followed_changes: Vec::new(), |
| 309 | keep_unread: None, |
| 310 | restorable_deletes: Default::default(), |
| 311 | typing: TypingState::default(), |
| 312 | typing_timer_running: false, |
| 313 | sidebar_load: Default::default(), |
| 314 | warm_chats: Default::default(), |
| 315 | local_previews: HashMap::new(), |
| 316 | quick_view: None, |
| 317 | manage_team: None, |
| 318 | scheduled: Vec::new(), |
| 319 | scheduled_polling: false, |
| 320 | saved: SavedSet::default(), |
| 321 | call_history: Vec::new(), |
| 322 | calendar_events: Vec::new(), |
| 323 | calendar_nudge: None, |
| 324 | calls_list: crate::call::CallsList::default(), |
| 325 | speed_dial, |
| 326 | pins: HashMap::new(), |
| 327 | post_follows: Default::default(), |
| 328 | forward_request: None, |
| 329 | forward_selection: None, |
| 330 | image_viewer_request: None, |
| 331 | own_status: PresenceStatus::default(), |
| 332 | notifications_paused_until, |
| 333 | own_email: String::new(), |
| 334 | own_time_zone: None, |
| 335 | own_time_zone_requested: false, |
| 336 | status_menu_open: false, |
| 337 | status_message_request: false, |
| 338 | profiles: ProfileCache::new(), |
| 339 | profile_request: None, |
| 340 | call: None, |
| 341 | call_end: None, |
| 342 | held_call: None, |
| 343 | call_media: None, |
| 344 | call_launcher: None, |
| 345 | call_count: 0, |
| 346 | call_share_sound: false, |
| 347 | recording_policy: teams_core::RecordingPolicy::default(), |
| 348 | allow_priority_messages: true, |
| 349 | account_sounds: None, |
| 350 | chat_settings, |
| 351 | markdown_mode, |
| 352 | actions_on_right_click, |
| 353 | demo_chat_desktop: HashMap::new(), |
| 354 | own_tenant: None, |
| 355 | call_share_motion: false, |
| 356 | call_share_standout: false, |
| 357 | call_report_enabled: true, |
| 358 | call_view: crate::call::ViewSettings::default(), |
| 359 | call_background: crate::call::BackgroundPick::None, |
| 360 | call_camera: calling::DeviceChoice::SystemDefault, |
| 361 | call_input: calling::DeviceChoice::SystemDefault, |
| 362 | call_output: calling::DeviceChoice::SystemDefault, |
| 363 | call_mic: calling::MicSettings::default(), |
| 364 | call_video_quality: calling::VideoQuality::default(), |
| 365 | call_effects: calling::CameraEffects::default(), |
| 366 | meet_now_pending: false, |
| 367 | prejoin: None, |
| 368 | prejoin_count: 0, |
| 369 | join_options: crate::call::JoinOptions::default(), |
| 370 | rsvp_send_response: true, |
| 371 | meeting_toasts: crate::call::MeetingToasts::default(), |
| 372 | demo_meetings: Vec::new(), |
| 373 | calendar_week: crate::call::week::CalendarWeek::default(), |
| 374 | call_backgrounds: if mode.demo { |
| 375 | crate::call::demo_library() |
| 376 | } else { |
| 377 | crate::call::BackgroundLibrary::new(crate::call::default_cache_directory()) |
| 378 | }, |
| 379 | transfer_picker: None, |
| 380 | transcript_panel: None, |
| 381 | rings: Rings::default(), |
| 382 | live_meetings: HashMap::new(), |
| 383 | live_refreshing: HashSet::new(), |
| 384 | translation: TranslationState::default(), |
| 385 | section_changes: crate::section_actions::SectionChanges::default(), |
| 386 | }; |
| 387 | state.local_previews = load_local_previews(&state.store); |
| 388 | state.followed_presence = crate::presence_follow::load_followed(&state.store); |
| 389 | state.collapsed = state.load_collapsed(); |
| 390 | state.call_share_sound = crate::call::load_share_sound(&state.store); |
| 391 | state.call_share_motion = crate::call::load_flag(&state.store, crate::call::SHARE_MOTION_META_KEY); |
| 392 | state.call_share_standout = crate::call::load_flag(&state.store, crate::call::SHARE_STANDOUT_META_KEY); |
| 393 | state.call_report_enabled = crate::call::load_report_enabled(&state.store); |
| 394 | state.call_view = crate::call::ViewSettings::load(&state.store); |
| 395 | state.call_background = crate::call::load_background(&state.store); |
| 396 | state.call_camera = crate::call::load_camera(&state.store); |
| 397 | state.call_input = crate::call::load_input(&state.store); |
| 398 | state.call_output = crate::call::load_output(&state.store); |
| 399 | crate::call::apply_sound_output(&state.call_output); |
| 400 | state.call_mic = crate::call::load_mic(&state.store); |
| 401 | state.call_video_quality = crate::call::load_video_quality(&state.store); |
| 402 | state.call_effects = crate::call::load_camera_effects(&state.store); |
| 403 | state.join_options = crate::call::load_join_options(&state.store); |
| 404 | state.call_backgrounds.customs = crate::call::load_custom_backgrounds(&state.store); |
| 405 | state.load_cached_translation_settings(); |
| 406 | if !mode.demo { |
| 407 | state.directory.load_cached_presence(&state.store); |
| 408 | state.reload_directory(); |
| 409 | } |
| 410 | state |
| 411 | } |
| 412 | |
| 413 | fn load_collapsed(&self) -> HashSet<String> { |
| 414 | self.store |
| 415 | .meta(COLLAPSED_META_KEY) |
| 416 | .ok() |
| 417 | .flatten() |
| 418 | .map(|value| { |
| 419 | value |
| 420 | .lines() |
| 421 | .map(str::to_owned) |
| 422 | .filter(|id| !id.is_empty()) |
| 423 | .collect() |
| 424 | }) |
| 425 | .unwrap_or_default() |
| 426 | } |
| 427 | |
| 428 | pub fn toggle_collapsed(&mut self, section_id: &str, cx: &mut Context<Self>) { |
| 429 | if data::is_pending_folder(section_id) { |
| 430 | return; |
| 431 | } |
| 432 | let now_collapsed = self.collapsed.insert(section_id.to_owned()); |
| 433 | if !now_collapsed { |
| 434 | self.collapsed.remove(section_id); |
| 435 | } |
| 436 | self.save_collapsed(); |
| 437 | self.sync_folder_expanded(section_id, !now_collapsed); |
| 438 | cx.emit(AppEvent::Sidebar); |
| 439 | cx.notify(); |
| 440 | } |
| 441 | |
| 442 | pub fn collapse_sections(&mut self, section_ids: &[String], cx: &mut Context<Self>) { |
| 443 | let newly_collapsed: Vec<String> = section_ids |
| 444 | .iter() |
| 445 | .filter(|id| !data::is_pending_folder(id) && !self.collapsed.contains(*id)) |
| 446 | .cloned() |
| 447 | .collect(); |
| 448 | if newly_collapsed.is_empty() { |
| 449 | return; |
| 450 | } |
| 451 | for id in &newly_collapsed { |
| 452 | self.collapsed.insert(id.clone()); |
| 453 | self.sync_folder_expanded(id, false); |
| 454 | } |
| 455 | self.save_collapsed(); |
| 456 | cx.emit(AppEvent::Sidebar); |
| 457 | cx.notify(); |
| 458 | } |
| 459 | |
| 460 | pub fn mark_all_chats_read(&mut self, cx: &mut Context<Self>) { |
| 461 | let unread: Vec<String> = self |
| 462 | .sidebar |
| 463 | .chats |
| 464 | .iter() |
| 465 | .filter(|chat| chat.unread) |
| 466 | .map(|chat| chat.id.clone()) |
| 467 | .collect(); |
| 468 | for conversation_id in unread { |
| 469 | self.mark_chat_read(&conversation_id, cx); |
| 470 | } |
| 471 | } |
| 472 | |
| 473 | pub fn older_chats(&self) -> (bool, bool) { |
| 474 | self.engine.as_ref().map_or((false, false), |engine| { |
| 475 | (engine.has_older_chats(), engine.is_loading_older_chats()) |
| 476 | }) |
| 477 | } |
| 478 | |
| 479 | pub fn request_older_chats(&self) { |
| 480 | let Some(engine) = self.engine.clone() else { |
| 481 | return; |
| 482 | }; |
| 483 | if !engine.has_older_chats() || engine.is_loading_older_chats() { |
| 484 | return; |
| 485 | } |
| 486 | drop(crate::runtime::spawn(async move { |
| 487 | if let Err(error) = engine.load_older_chats().await { |
| 488 | crate::diagnostics::record(format!("sync: older chats not loaded: {error}")); |
| 489 | } |
| 490 | })); |
| 491 | } |
| 492 | |
| 493 | pub fn toggle_list_expanded(&mut self, section_id: &str, cx: &mut Context<Self>) { |
| 494 | if !self.expanded_lists.remove(section_id) { |
| 495 | self.expanded_lists.insert(section_id.to_owned()); |
| 496 | } |
| 497 | cx.emit(AppEvent::Sidebar); |
| 498 | cx.notify(); |
| 499 | } |
| 500 | |
| 501 | fn save_collapsed(&self) { |
| 502 | let mut ids: Vec<&str> = self.collapsed.iter().map(String::as_str).collect(); |
| 503 | ids.sort_unstable(); |
| 504 | let _ = self.store.set_meta(COLLAPSED_META_KEY, &ids.join("\n")); |
| 505 | } |
| 506 | |
| 507 | fn sync_folder_expanded(&mut self, folder_id: &str, expanded: bool) { |
| 508 | let Some(folder) = self |
| 509 | .directory |
| 510 | .folders |
| 511 | .iter_mut() |
| 512 | .find(|folder| folder.id == folder_id && folder.expanded.is_some()) |
| 513 | else { |
| 514 | return; |
| 515 | }; |
| 516 | folder.expanded = Some(expanded); |
| 517 | let _ = self.store.set_folder_expanded(folder_id, expanded); |
| 518 | if let Some(engine) = self.engine.clone().filter(|_| !self.mode.read_only) { |
| 519 | let folder_id = folder_id.to_owned(); |
| 520 | drop(crate::runtime::spawn(async move { |
| 521 | engine.set_folder_expanded(&folder_id, expanded).await |
| 522 | })); |
| 523 | } |
| 524 | } |
| 525 | |
| 526 | fn adopt_folder_expanded(&mut self) { |
| 527 | let snapshot = self.collapsed.clone(); |
| 528 | for folder in &self.directory.folders { |
| 529 | match folder.expanded { |
| 530 | Some(true) => { |
| 531 | self.collapsed.remove(&folder.id); |
| 532 | } |
| 533 | Some(false) => { |
| 534 | self.collapsed.insert(folder.id.clone()); |
| 535 | } |
| 536 | None => {} |
| 537 | } |
| 538 | } |
| 539 | if self.collapsed != snapshot { |
| 540 | self.save_collapsed(); |
| 541 | } |
| 542 | } |
| 543 | |
| 544 | pub fn set_chat_section( |
| 545 | &mut self, |
| 546 | section: ChatSection, |
| 547 | enabled: bool, |
| 548 | cx: &mut Context<Self>, |
| 549 | ) { |
| 550 | let Some(engine_or_demo) = self.chat_action_engine(cx) else { |
| 551 | return; |
| 552 | }; |
| 553 | let previous = self.directory.section_settings; |
| 554 | let mut updated = previous; |
| 555 | updated.set(section, enabled); |
| 556 | self.apply_section_settings(updated, cx); |
| 557 | let Some(engine) = engine_or_demo else { |
| 558 | return; |
| 559 | }; |
| 560 | self.run_chat_action( |
| 561 | "Chat list setting", |
| 562 | async move { engine.set_section_enabled(section, enabled).await }, |
| 563 | move |state, cx| state.apply_section_settings(previous, cx), |
| 564 | |_, _| {}, |
| 565 | cx, |
| 566 | ); |
| 567 | } |
| 568 | |
| 569 | pub fn set_skin_tone(&mut self, tone: u8, cx: &mut Context<Self>) { |
| 570 | let Some(engine_or_demo) = self.chat_action_engine(cx) else { |
| 571 | return; |
| 572 | }; |
| 573 | let previous = teams_core::skin_tone(&self.store); |
| 574 | let _ = teams_core::store_account_skin_tone(&self.store, tone); |
| 575 | let Some(engine) = engine_or_demo else { |
| 576 | return; |
| 577 | }; |
| 578 | self.run_chat_action( |
| 579 | "Skin tone", |
| 580 | async move { engine.set_skin_tone(tone).await }, |
| 581 | move |state, _| { |
| 582 | let _ = teams_core::store_account_skin_tone(&state.store, previous); |
| 583 | }, |
| 584 | |_, _| {}, |
| 585 | cx, |
| 586 | ); |
| 587 | } |
| 588 | |
| 589 | fn apply_section_settings(&mut self, settings: ChatSectionSettings, cx: &mut Context<Self>) { |
| 590 | self.directory.section_settings = settings; |
| 591 | let _ = teams_core::store_section_settings(&self.store, &settings); |
| 592 | cx.emit(AppEvent::Sidebar); |
| 593 | cx.notify(); |
| 594 | } |
| 595 | |
| 596 | fn reload_directory_without_unread(&mut self) { |
| 597 | self.directory.me = data::me(&self.store); |
| 598 | self.own_email = self |
| 599 | .store |
| 600 | .meta("me_email") |
| 601 | .ok() |
| 602 | .flatten() |
| 603 | .unwrap_or_default(); |
| 604 | self.directory.folders = data::folders(&self.store, &self.favorite_ids); |
| 605 | self.reapply_section_changes(); |
| 606 | self.directory.section_settings = teams_core::stored_section_settings(&self.store); |
| 607 | self.adopt_folder_expanded(); |
| 608 | self.directory.pinned_channels = data::pinned_channels(&self.store); |
| 609 | if self.directory.pinned_channels.is_empty() { |
| 610 | let known: HashSet<&str> = self |
| 611 | .sidebar |
| 612 | .teams |
| 613 | .iter() |
| 614 | .flat_map(|team| team.channels.iter().map(|channel| channel.id.as_str())) |
| 615 | .collect(); |
| 616 | self.directory.pinned_channels = self |
| 617 | .favorite_ids |
| 618 | .iter() |
| 619 | .filter(|id| known.contains(id.as_str())) |
| 620 | .cloned() |
| 621 | .collect(); |
| 622 | } |
| 623 | self.resolve_pending_avatars(); |
| 624 | self.sync_presence(); |
| 625 | } |
| 626 | |
| 627 | pub fn reload_directory(&mut self) { |
| 628 | self.reload_directory_without_unread(); |
| 629 | let unread = crate::sidebar_load::unread_of(self.engine.as_deref(), &self.sidebar.chats); |
| 630 | self.directory.unread_counts = unread.counts; |
| 631 | self.directory.unread_importance = unread.importance; |
| 632 | } |
| 633 | |
| 634 | pub fn request_avatars(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) { |
| 635 | let wanted = self.directory.missing_avatars(user_ids); |
| 636 | if wanted.is_empty() { |
| 637 | return; |
| 638 | } |
| 639 | let mut changed = false; |
| 640 | let mut uncached = Vec::new(); |
| 641 | for user_id in wanted { |
| 642 | match data::cached_avatar(&self.store, &user_id) { |
| 643 | Some(cached) => { |
| 644 | self.directory.set_avatar(&user_id, cached); |
| 645 | changed = true; |
| 646 | } |
| 647 | None => uncached.push(user_id), |
| 648 | } |
| 649 | } |
| 650 | if let Some(engine) = self.engine.clone().filter(|_| !uncached.is_empty()) { |
| 651 | self.directory.mark_avatars_pending(&uncached); |
| 652 | let done = data::fetch_avatars(&engine, uncached); |
| 653 | self.on_done(done, cx, |state, cx| { |
| 654 | state.resolve_pending_avatars(); |
| 655 | cx.emit(AppEvent::Directory); |
| 656 | cx.notify(); |
| 657 | }); |
| 658 | changed = true; |
| 659 | } |
| 660 | if changed { |
| 661 | cx.emit(AppEvent::Directory); |
| 662 | cx.notify(); |
| 663 | } |
| 664 | } |
| 665 | |
| 666 | pub fn request_images(&mut self, images: Vec<ImageRef>, cx: &mut Context<Self>) { |
| 667 | let Some(engine) = self.engine.clone() else { |
| 668 | return; |
| 669 | }; |
| 670 | let wanted = self |
| 671 | .directory |
| 672 | .images_to_request(images.iter().map(|image| image.url.clone())); |
| 673 | let mut changed = false; |
| 674 | for image in images |
| 675 | .into_iter() |
| 676 | .filter(|image| wanted.contains(&image.url)) |
| 677 | { |
| 678 | match engine.image_path(&image) { |
| 679 | Some(path) => { |
| 680 | self.directory.set_image(&image.url, &path); |
| 681 | changed = true; |
| 682 | } |
| 683 | None => { |
| 684 | let done = data::fetch_image(&engine, image.clone()); |
| 685 | cx.spawn(async move |this, cx| { |
| 686 | let failure = match done.await { |
| 687 | Ok(Ok(())) => None, |
| 688 | Ok(Err(error)) => Some(error), |
| 689 | Err(_) => Some("cancelled".to_owned()), |
| 690 | }; |
| 691 | if let Some(failure) = failure { |
| 692 | let host = image.url.split("://").nth(1).and_then(|rest| rest.split('/').next()).unwrap_or_default(); |
| 693 | log::warn!("image from {host} not loaded: {failure}"); |
| 694 | this.update(cx, |state, cx| { |
| 695 | state.directory.mark_image_failed(&image.url); |
| 696 | cx.notify(); |
| 697 | }) |
| 698 | .ok(); |
| 699 | } |
| 700 | }) |
| 701 | .detach(); |
| 702 | } |
| 703 | } |
| 704 | } |
| 705 | if changed { |
| 706 | cx.emit(AppEvent::Images(wanted)); |
| 707 | cx.notify(); |
| 708 | } |
| 709 | } |
| 710 | |
| 711 | pub fn jump_to_message( |
| 712 | &mut self, |
| 713 | selection: Selection, |
| 714 | message_id: String, |
| 715 | cx: &mut Context<Self>, |
| 716 | ) { |
| 717 | self.pending_jump = Some((selection.conversation_id().to_owned(), message_id)); |
| 718 | if self.selection.as_ref() == Some(&selection) { |
| 719 | cx.emit(AppEvent::Jump); |
| 720 | } else { |
| 721 | self.select(selection, cx); |
| 722 | } |
| 723 | } |
| 724 | |
| 725 | fn on_done( |
| 726 | &self, |
| 727 | done: data::Done, |
| 728 | cx: &mut Context<Self>, |
| 729 | then: impl FnOnce(&mut Self, &mut Context<Self>) + 'static, |
| 730 | ) { |
| 731 | cx.spawn(async move |this, cx| { |
| 732 | let _ = done.await; |
| 733 | this.update(cx, |state, cx| then(state, cx)).ok(); |
| 734 | }) |
| 735 | .detach(); |
| 736 | } |
| 737 | |
| 738 | fn resolve_pending_avatars(&mut self) { |
| 739 | for user_id in self.directory.pending_avatars() { |
| 740 | if let Some(cached) = data::cached_avatar(&self.store, &user_id) { |
| 741 | self.directory.set_avatar(&user_id, cached); |
| 742 | } |
| 743 | } |
| 744 | } |
| 745 | |
| 746 | fn sync_presence(&mut self) -> Vec<String> { |
| 747 | let Some(engine) = self.engine.clone() else { |
| 748 | return Vec::new(); |
| 749 | }; |
| 750 | self.directory |
| 751 | .requested_presence_ids() |
| 752 | .into_iter() |
| 753 | .filter(|user_id| { |
| 754 | let Some(kind) = data::presence_kind(&engine, user_id) else { |
| 755 | return false; |
| 756 | }; |
| 757 | let activity_changed = self |
| 758 | .directory |
| 759 | .set_activity(user_id, data::presence_activity(&engine, user_id)); |
| 760 | let previous = self.directory.presence_of(user_id); |
| 761 | let changed = self.directory.set_presence(user_id, kind); |
| 762 | if changed { |
| 763 | self.note_followed_change(user_id, previous, kind); |
| 764 | } |
| 765 | changed || activity_changed |
| 766 | }) |
| 767 | .collect() |
| 768 | } |
| 769 | |
| 770 | pub fn request_presence(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) { |
| 771 | let now = Instant::now(); |
| 772 | let pushed = self.live == LiveState::Live; |
| 773 | let wanted = self.directory.stale_presence(user_ids, now, pushed); |
| 774 | if wanted.is_empty() { |
| 775 | return; |
| 776 | } |
| 777 | self.directory.mark_presence_pending(&wanted); |
| 778 | if let Some(engine) = self.engine.clone() { |
| 779 | self.directory.mark_presence_requested(&wanted, now); |
| 780 | drop(data::watch_presence(&engine, wanted.clone())); |
| 781 | let done = data::refresh_presence(&engine, wanted.clone()); |
| 782 | self.on_done(done, cx, move |state, cx| { |
| 783 | state.sync_presence(); |
| 784 | state.announce_followed_changes(cx); |
| 785 | state.directory.save_presence(&state.store, &wanted); |
| 786 | state.directory.settle_presence(&wanted); |
| 787 | cx.emit(AppEvent::Directory); |
| 788 | cx.notify(); |
| 789 | }); |
| 790 | } |
| 791 | } |
| 792 | |
| 793 | pub fn move_chat( |
| 794 | &mut self, |
| 795 | conversation_id: &str, |
| 796 | folder_id: Option<&str>, |
| 797 | cx: &mut Context<Self>, |
| 798 | ) { |
| 799 | self.place_chat(conversation_id, folder_id, None, cx); |
| 800 | } |
| 801 | |
| 802 | pub fn drop_chat_on( |
| 803 | &mut self, |
| 804 | conversation_id: &str, |
| 805 | target_conversation_id: &str, |
| 806 | folder_id: &str, |
| 807 | cx: &mut Context<Self>, |
| 808 | ) { |
| 809 | if conversation_id == target_conversation_id { |
| 810 | return; |
| 811 | } |
| 812 | let Some(slot) = self.directory.slot_of(folder_id, target_conversation_id) else { |
| 813 | return; |
| 814 | }; |
| 815 | self.place_chat(conversation_id, Some(folder_id), Some(slot), cx); |
| 816 | } |
| 817 | |
| 818 | pub fn place_chat( |
| 819 | &mut self, |
| 820 | conversation_id: &str, |
| 821 | folder_id: Option<&str>, |
| 822 | index: Option<usize>, |
| 823 | cx: &mut Context<Self>, |
| 824 | ) { |
| 825 | if self.mode.read_only { |
| 826 | return; |
| 827 | } |
| 828 | let previous_folder = self |
| 829 | .directory |
| 830 | .folder_of(conversation_id) |
| 831 | .map(|folder| folder.id.clone()); |
| 832 | self.directory.place(conversation_id, folder_id, index); |
| 833 | if let Some(engine) = self.engine.clone() { |
| 834 | let previous = previous_folder.clone(); |
| 835 | let done = match (folder_id, previous.as_deref()) { |
| 836 | (Some(folder_id), _) => Some(data::move_to_folder( |
| 837 | &engine, |
| 838 | conversation_id, |
| 839 | folder_id, |
| 840 | index, |
| 841 | )), |
| 842 | (None, Some(previous)) => { |
| 843 | Some(data::remove_from_folder(&engine, conversation_id, previous)) |
| 844 | } |
| 845 | (None, None) => None, |
| 846 | }; |
| 847 | if let Some(done) = done { |
| 848 | self.on_done(done, cx, |state, cx| { |
| 849 | state.reload_directory(); |
| 850 | cx.emit(AppEvent::Sidebar); |
| 851 | cx.notify(); |
| 852 | }); |
| 853 | } |
| 854 | } |
| 855 | cx.emit(AppEvent::Sidebar); |
| 856 | cx.notify(); |
| 857 | } |
| 858 | |
| 859 | pub fn mark_chat_read(&mut self, conversation_id: &str, cx: &mut Context<Self>) { |
| 860 | if self.keeps_unread(conversation_id) { |
| 861 | self.keep_unread = None; |
| 862 | } |
| 863 | if self.mode.demo { |
| 864 | if let Some(chat) = self |
| 865 | .sidebar |
| 866 | .chats |
| 867 | .iter() |
| 868 | .find(|chat| chat.id == conversation_id) |
| 869 | { |
| 870 | let mut read = chat.clone(); |
| 871 | read.unread = false; |
| 872 | let _ = self.store.upsert_chats(&[read]); |
| 873 | self.reload_sidebar(cx); |
| 874 | } |
| 875 | return; |
| 876 | } |
| 877 | if self.mode.read_only { |
| 878 | return; |
| 879 | } |
| 880 | if let Some(engine) = self.engine.clone() { |
| 881 | let _ = self |
| 882 | .store |
| 883 | .mark_chat_read(conversation_id, chrono::Utc::now()); |
| 884 | self.reload_sidebar(cx); |
| 885 | let conversation_id = conversation_id.to_owned(); |
| 886 | drop(crate::runtime::spawn(async move { |
| 887 | engine.mark_read(&conversation_id).await |
| 888 | })); |
| 889 | } |
| 890 | } |
| 891 | |
| 892 | pub fn mark_channel_read(&mut self, channel_id: &str, cx: &mut Context<Self>) { |
| 893 | if self.mode.read_only { |
| 894 | return; |
| 895 | } |
| 896 | let _ = self.store.mark_channel_read(channel_id); |
| 897 | self.reload_sidebar(cx); |
| 898 | if self.mode.demo { |
| 899 | return; |
| 900 | } |
| 901 | if let Some(engine) = self.engine.clone() { |
| 902 | let channel_id = channel_id.to_owned(); |
| 903 | drop(crate::runtime::spawn(async move { |
| 904 | engine.mark_read(&channel_id).await |
| 905 | })); |
| 906 | } |
| 907 | } |
| 908 | |
| 909 | pub fn mark_all_channels_read(&mut self, cx: &mut Context<Self>) { |
| 910 | let Some(engine_or_demo) = self.chat_action_engine(cx) else { |
| 911 | return; |
| 912 | }; |
| 913 | let previous_unread: Vec<store::ChannelReadState> = self |
| 914 | .sidebar |
| 915 | .teams |
| 916 | .iter() |
| 917 | .flat_map(|team| team.channels.iter()) |
| 918 | .map(|channel| store::ChannelReadState { |
| 919 | channel_id: channel.id.clone(), |
| 920 | unread: channel.unread, |
| 921 | last_message_at: None, |
| 922 | read_until: None, |
| 923 | }) |
| 924 | .collect(); |
| 925 | let previous_mentions: Vec<(String, store::ChannelMentions)> = self |
| 926 | .sidebar |
| 927 | .teams |
| 928 | .iter() |
| 929 | .flat_map(|team| team.mentions.iter()) |
| 930 | .map(|(channel_id, mentions)| (channel_id.clone(), *mentions)) |
| 931 | .collect(); |
| 932 | let _ = self.store.mark_all_channels_read(); |
| 933 | self.reload_sidebar(cx); |
| 934 | let Some(engine) = engine_or_demo else { |
| 935 | return; |
| 936 | }; |
| 937 | self.run_chat_action( |
| 938 | "Mark all as read", |
| 939 | async move { engine.mark_all_channels_read().await }, |
| 940 | move |state, cx| { |
| 941 | let _ = state.store.apply_channel_read_states(&previous_unread); |
| 942 | let _ = state.store.replace_channel_mentions(&previous_mentions); |
| 943 | state.reload_sidebar(cx); |
| 944 | }, |
| 945 | |_, _| {}, |
| 946 | cx, |
| 947 | ); |
| 948 | } |
| 949 | |
| 950 | pub fn open_quick_view(&mut self, view: QuickView, cx: &mut Context<Self>) { |
| 951 | self.cancel_prejoin(cx); |
| 952 | self.new_chat = false; |
| 953 | self.quick_view = Some(view); |
| 954 | if view == QuickView::Saved { |
| 955 | self.refresh_saved(cx); |
| 956 | } |
| 957 | cx.emit(AppEvent::Sidebar); |
| 958 | cx.notify(); |
| 959 | } |
| 960 | |
| 961 | pub fn close_quick_view(&mut self, cx: &mut Context<Self>) { |
| 962 | if self.quick_view.take().is_some() { |
| 963 | cx.emit(AppEvent::Sidebar); |
| 964 | cx.notify(); |
| 965 | } |
| 966 | } |
| 967 | |
| 968 | pub fn start_new_chat(&mut self, cx: &mut Context<Self>) { |
| 969 | self.quick_view = None; |
| 970 | self.new_chat = true; |
| 971 | cx.emit(AppEvent::Selection); |
| 972 | cx.notify(); |
| 973 | } |
| 974 | |
| 975 | pub fn close_new_chat(&mut self, cx: &mut Context<Self>) { |
| 976 | if !self.new_chat { |
| 977 | return; |
| 978 | } |
| 979 | self.new_chat = false; |
| 980 | cx.emit(AppEvent::Selection); |
| 981 | cx.notify(); |
| 982 | } |
| 983 | |
| 984 | pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) { |
| 985 | self.cancel_prejoin(cx); |
| 986 | self.call_end = None; |
| 987 | let was_drafting = std::mem::take(&mut self.new_chat); |
| 988 | let left_quick_view = self.quick_view.take().is_some(); |
| 989 | let left_manage_team = self.manage_team.take().is_some(); |
| 990 | if !was_drafting && self.selection.as_ref() == Some(&selection) { |
| 991 | if left_quick_view || left_manage_team { |
| 992 | cx.emit(AppEvent::Sidebar); |
| 993 | cx.notify(); |
| 994 | } |
| 995 | return; |
| 996 | } |
| 997 | let conversation_id = selection.conversation_id().to_owned(); |
| 998 | self.selection = Some(selection); |
| 999 | self.keep_unread = None; |
| 1000 | self.forward_selection = None; |
| 1001 | cx.emit(AppEvent::Selection); |
| 1002 | cx.notify(); |
| 1003 | self.refresh_live_meeting(&conversation_id, cx); |
| 1004 | self.refresh_language_stamps(&conversation_id, cx); |
| 1005 | self.refresh_partner_absence(&conversation_id, cx); |
| 1006 | } |
| 1007 | |
| 1008 | fn apply_typing(&mut self, event: TypingEvent, cx: &mut Context<Self>) { |
| 1009 | let is_me = self |
| 1010 | .directory |
| 1011 | .me |
| 1012 | .as_ref() |
| 1013 | .is_some_and(|me| me.user_id == event.user_id); |
| 1014 | if is_me { |
| 1015 | return; |
| 1016 | } |
| 1017 | if event.active { |
| 1018 | let display_name = match event.display_name.trim() { |
| 1019 | "" => crate::people::resolve_names(self, std::slice::from_ref(&event.user_id)) |
| 1020 | .remove(&event.user_id) |
| 1021 | .unwrap_or_default(), |
| 1022 | _ => event.display_name.clone(), |
| 1023 | }; |
| 1024 | self.typing.start( |
| 1025 | &event.conversation_id, |
| 1026 | &event.user_id, |
| 1027 | &display_name, |
| 1028 | Instant::now(), |
| 1029 | event.received_at, |
| 1030 | ); |
| 1031 | self.request_avatars(vec![event.user_id.clone()], cx); |
| 1032 | self.schedule_typing_expiry(cx); |
| 1033 | } else { |
| 1034 | self.typing.clear(&event.conversation_id, &event.user_id); |
| 1035 | } |
| 1036 | cx.emit(AppEvent::Typing); |
| 1037 | cx.notify(); |
| 1038 | } |
| 1039 | |
| 1040 | fn clear_typists_who_sent(&mut self, conversation_id: &str, cx: &mut Context<Self>) { |
| 1041 | if !self.typing.is_active(conversation_id) { |
| 1042 | return; |
| 1043 | } |
| 1044 | let Ok(recent) = self |
| 1045 | .store |
| 1046 | .messages(conversation_id, None, RECENT_MESSAGES_FOR_TYPING) |
| 1047 | else { |
| 1048 | return; |
| 1049 | }; |
| 1050 | let mut changed = false; |
| 1051 | for message in recent { |
| 1052 | if let Some(sender_id) = message.sender_id.as_deref() { |
| 1053 | changed |= self |
| 1054 | .typing |
| 1055 | .message_from(conversation_id, sender_id, message.created_at); |
| 1056 | } |
| 1057 | } |
| 1058 | if changed { |
| 1059 | cx.emit(AppEvent::Typing); |
| 1060 | cx.notify(); |
| 1061 | } |
| 1062 | } |
| 1063 | |
| 1064 | fn schedule_typing_expiry(&mut self, cx: &mut Context<Self>) { |
| 1065 | if self.typing_timer_running { |
| 1066 | return; |
| 1067 | } |
| 1068 | self.typing_timer_running = true; |
| 1069 | cx.spawn(async move |this, cx| { |
| 1070 | loop { |
| 1071 | let next = this.update(cx, |state, _| { |
| 1072 | let next = state.typing.next_expiry(); |
| 1073 | state.typing_timer_running = next.is_some(); |
| 1074 | next |
| 1075 | }); |
| 1076 | let Ok(Some(next)) = next else { return }; |
| 1077 | cx.background_executor() |
| 1078 | .timer(next.saturating_duration_since(Instant::now())) |
| 1079 | .await; |
| 1080 | let alive = this.update(cx, |state, cx| { |
| 1081 | if state.typing.expire(Instant::now()) { |
| 1082 | cx.emit(AppEvent::Typing); |
| 1083 | cx.notify(); |
| 1084 | } |
| 1085 | }); |
| 1086 | if alive.is_err() { |
| 1087 | return; |
| 1088 | } |
| 1089 | } |
| 1090 | }) |
| 1091 | .detach(); |
| 1092 | } |
| 1093 | |
| 1094 | pub fn reload_sidebar(&mut self, cx: &mut Context<Self>) { |
| 1095 | self.sidebar_load.local_change(); |
| 1096 | if let Ok(sidebar) = self.store.sidebar() { |
| 1097 | self.sidebar = sidebar; |
| 1098 | self.apply_bot_titles(); |
| 1099 | } |
| 1100 | self.calls_list.invalidate(); |
| 1101 | if !self.mode.demo { |
| 1102 | self.reload_directory(); |
| 1103 | self.load_own_time_zone(cx); |
| 1104 | } |
| 1105 | cx.emit(AppEvent::Sidebar); |
| 1106 | cx.notify(); |
| 1107 | } |
| 1108 | |
| 1109 | pub(crate) fn adopt_loaded_sidebar( |
| 1110 | &mut self, |
| 1111 | loaded: crate::sidebar_load::LoadedSidebar, |
| 1112 | cx: &mut Context<Self>, |
| 1113 | ) { |
| 1114 | self.sidebar = loaded.sidebar; |
| 1115 | self.apply_bot_titles(); |
| 1116 | self.calls_list.invalidate(); |
| 1117 | if !self.mode.demo { |
| 1118 | self.reload_directory_without_unread(); |
| 1119 | self.directory.unread_counts = loaded.unread.counts; |
| 1120 | self.directory.unread_importance = loaded.unread.importance; |
| 1121 | self.load_own_time_zone(cx); |
| 1122 | } |
| 1123 | cx.emit(AppEvent::Sidebar); |
| 1124 | cx.notify(); |
| 1125 | } |
| 1126 | |
| 1127 | pub fn apply(&mut self, event: BackendEvent, cx: &mut Context<Self>) { |
| 1128 | match event { |
| 1129 | BackendEvent::Connection(connection) => { |
| 1130 | if connection != self.connection { |
| 1131 | app_base::diagnostics::record(format!("connection: {connection:?}")); |
| 1132 | } |
| 1133 | self.connection = connection; |
| 1134 | self.refresh_connection_banner(cx); |
| 1135 | cx.emit(AppEvent::Status); |
| 1136 | } |
| 1137 | BackendEvent::LiveRetry(retry) => self.live_retry = Some(retry), |
| 1138 | BackendEvent::Calls(launcher) => { |
| 1139 | launcher.set_default_camera(self.call_camera.clone()); |
| 1140 | self.call_launcher = Some(launcher); |
| 1141 | self.load_own_time_zone(cx); |
| 1142 | } |
| 1143 | BackendEvent::Calendar(events) => self.apply_calendar(events, cx), |
| 1144 | BackendEvent::CalendarNudge(nudge) => self.calendar_nudge = Some(nudge), |
| 1145 | BackendEvent::Ring(event) => self.on_engine_event(event, cx), |
| 1146 | BackendEvent::ThreadChanged(conversation_id) => { |
| 1147 | self.on_thread_changed(&conversation_id, cx) |
| 1148 | } |
| 1149 | BackendEvent::Engine(engine) => { |
| 1150 | crate::agent_api::engine_ready(engine.clone(), cx); |
| 1151 | self.engine = Some(engine); |
| 1152 | self.resend_outbox(cx); |
| 1153 | self.refresh_scheduled(cx); |
| 1154 | self.refresh_translation_settings(cx); |
| 1155 | self.refresh_recording_policy(cx); |
| 1156 | self.refresh_messaging_policy(cx); |
| 1157 | self.refresh_sound_settings(cx); |
| 1158 | self.refresh_chat_settings(cx); |
| 1159 | let waiting = self.directory.waiting_presence_ids(); |
| 1160 | self.request_presence(waiting, cx); |
| 1161 | self.watch_followed_presence(cx); |
| 1162 | self.refresh_own_status(cx); |
| 1163 | cx.emit(AppEvent::Status); |
| 1164 | } |
| 1165 | BackendEvent::Core(CoreEvent::SidebarChanged) => self.reload_sidebar_after_sync(cx), |
| 1166 | BackendEvent::Core(CoreEvent::ActivityChanged) => cx.emit(AppEvent::Activity), |
| 1167 | BackendEvent::Core( |
| 1168 | CoreEvent::MessagesChanged { conversation_id } |
| 1169 | | CoreEvent::ReceiptsChanged { conversation_id }, |
| 1170 | ) => { |
| 1171 | self.clear_typists_who_sent(&conversation_id, cx); |
| 1172 | self.refresh_language_stamps(&conversation_id, cx); |
| 1173 | cx.emit(AppEvent::Messages(conversation_id)); |
| 1174 | } |
| 1175 | BackendEvent::Core(CoreEvent::MessagesStoredLate { |
| 1176 | conversation_id, |
| 1177 | message_ids, |
| 1178 | }) => self.late_arrivals.insert(&conversation_id, message_ids), |
| 1179 | BackendEvent::Core(CoreEvent::PinsChanged { conversation_id }) => { |
| 1180 | self.refresh_pins(&conversation_id, cx); |
| 1181 | } |
| 1182 | BackendEvent::Core(CoreEvent::ImagesChanged { keys }) => { |
| 1183 | if let Some(engine) = &self.engine { |
| 1184 | for key in &keys { |
| 1185 | let image = ImageRef { |
| 1186 | id: String::new(), |
| 1187 | url: key.clone(), |
| 1188 | width: None, |
| 1189 | height: None, |
| 1190 | alt: None, |
| 1191 | }; |
| 1192 | if let Some(path) = engine.image_path(&image) { |
| 1193 | self.directory.set_image(key, &path); |
| 1194 | } |
| 1195 | } |
| 1196 | } |
| 1197 | cx.emit(AppEvent::Images(keys)); |
| 1198 | } |
| 1199 | BackendEvent::Core(CoreEvent::PresenceChanged) => { |
| 1200 | let changed = self.sync_presence(); |
| 1201 | self.announce_followed_changes(cx); |
| 1202 | self.directory.save_presence(&self.store, &changed); |
| 1203 | cx.emit(AppEvent::Directory); |
| 1204 | cx.notify(); |
| 1205 | } |
| 1206 | BackendEvent::Core(CoreEvent::PresenceStatusChanged(status)) => { |
| 1207 | self.apply_own_status(status, cx); |
| 1208 | self.reload_directory(); |
| 1209 | } |
| 1210 | BackendEvent::Core(_) => { |
| 1211 | if !self.mode.demo { |
| 1212 | self.reload_directory(); |
| 1213 | } |
| 1214 | cx.emit(AppEvent::Directory); |
| 1215 | } |
| 1216 | BackendEvent::Typing(event) => self.apply_typing(event, cx), |
| 1217 | BackendEvent::Live(live) => { |
| 1218 | self.live = live; |
| 1219 | self.refresh_connection_banner(cx); |
| 1220 | cx.emit(AppEvent::Status); |
| 1221 | } |
| 1222 | BackendEvent::Favorites(ids) => { |
| 1223 | self.favorite_ids = ids; |
| 1224 | if !self.mode.demo { |
| 1225 | self.reload_directory(); |
| 1226 | } |
| 1227 | cx.emit(AppEvent::Sidebar); |
| 1228 | } |
| 1229 | BackendEvent::Synced(time) => { |
| 1230 | if self.last_sync.is_none() { |
| 1231 | self.refresh_saved(cx); |
| 1232 | } |
| 1233 | self.last_sync = Some(time); |
| 1234 | cx.emit(AppEvent::Status); |
| 1235 | } |
| 1236 | } |
| 1237 | cx.notify(); |
| 1238 | } |
| 1239 | } |
| 1240 | |
| 1241 | #[cfg(test)] |
| 1242 | mod tests { |
| 1243 | use std::sync::Arc; |
| 1244 | |
| 1245 | use chatsvc::TypingEvent; |
| 1246 | use chrono::{Duration, Utc}; |
| 1247 | use gpui_kit::{AppContext as _, TestAppContext}; |
| 1248 | use store::{ |
| 1249 | ChannelRecord, ChatRecord, MemberRecord, MessageRecord, SidebarTeam, Store, TeamRecord, |
| 1250 | }; |
| 1251 | use teams_core::CoreEvent; |
| 1252 | |
| 1253 | use super::{AppState, Mode, Selection, chat_title, selection_for, selection_title}; |
| 1254 | use crate::backend::BackendEvent; |
| 1255 | use crate::data::Person; |
| 1256 | use store::Sidebar; |
| 1257 | |
| 1258 | fn chat(id: &str, title: &str, unread: bool) -> ChatRecord { |
| 1259 | ChatRecord { |
| 1260 | id: id.into(), |
| 1261 | kind: "group".into(), |
| 1262 | title: title.into(), |
| 1263 | member_summary: "Member".into(), |
| 1264 | last_message_at: None, |
| 1265 | last_read_at: None, |
| 1266 | unread, |
| 1267 | ..Default::default() |
| 1268 | } |
| 1269 | } |
| 1270 | |
| 1271 | #[test] |
| 1272 | fn selection_kind_follows_sidebar() { |
| 1273 | assert_eq!( |
| 1274 | selection_for(&sidebar(), "c1"), |
| 1275 | Some(Selection::Chat("c1".into())) |
| 1276 | ); |
| 1277 | assert_eq!( |
| 1278 | selection_for(&sidebar(), "ch"), |
| 1279 | Some(Selection::Channel("ch".into())) |
| 1280 | ); |
| 1281 | assert_eq!(selection_for(&sidebar(), "x"), None); |
| 1282 | } |
| 1283 | |
| 1284 | fn sidebar() -> Sidebar { |
| 1285 | Sidebar { |
| 1286 | chats: vec![chat("c1", "First", true), chat("c2", "", false)], |
| 1287 | teams: vec![SidebarTeam { |
| 1288 | rights: Default::default(), |
| 1289 | team: TeamRecord { |
| 1290 | id: "t".into(), |
| 1291 | name: "Team".into(), |
| 1292 | }, |
| 1293 | channels: vec![ChannelRecord { |
| 1294 | id: "ch".into(), |
| 1295 | team_id: "t".into(), |
| 1296 | name: "General".into(), |
| 1297 | membership_type: None, |
| 1298 | last_message_at: None, |
| 1299 | unread: false, |
| 1300 | }], |
| 1301 | hidden: false, |
| 1302 | hidden_channel_ids: Vec::new(), |
| 1303 | notifications: Default::default(), |
| 1304 | mentions: Default::default(), |
| 1305 | }], |
| 1306 | } |
| 1307 | } |
| 1308 | |
| 1309 | #[test] |
| 1310 | fn empty_chat_title_falls_back_to_members() { |
| 1311 | assert_eq!(chat_title(&sidebar().chats[1]), "Member"); |
| 1312 | } |
| 1313 | |
| 1314 | #[test] |
| 1315 | fn selection_titles() { |
| 1316 | assert_eq!( |
| 1317 | selection_title(&sidebar(), &Selection::Channel("ch".into())), |
| 1318 | "Team / General" |
| 1319 | ); |
| 1320 | assert_eq!( |
| 1321 | selection_title(&sidebar(), &Selection::Chat("c1".into())), |
| 1322 | "First" |
| 1323 | ); |
| 1324 | } |
| 1325 | |
| 1326 | fn typing_event(user_id: &str, active: bool) -> BackendEvent { |
| 1327 | BackendEvent::Typing(TypingEvent { |
| 1328 | conversation_id: "c1".into(), |
| 1329 | user_id: user_id.into(), |
| 1330 | display_name: format!("Name {user_id}"), |
| 1331 | active, |
| 1332 | received_at: Utc::now(), |
| 1333 | }) |
| 1334 | } |
| 1335 | |
| 1336 | #[gpui_kit::test] |
| 1337 | fn toggle_collapsed_ignores_pending_sections(cx: &mut TestAppContext) { |
| 1338 | cx.update(gpui_kit::init); |
| 1339 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 1340 | let app = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default()))); |
| 1341 | cx.update(|cx| { |
| 1342 | app.update(cx, |state, cx| { |
| 1343 | state.toggle_collapsed("pending-section:1", cx); |
| 1344 | assert!(state.collapsed.is_empty()); |
| 1345 | }) |
| 1346 | }); |
| 1347 | } |
| 1348 | |
| 1349 | #[gpui_kit::test] |
| 1350 | fn typing_events_track_other_users_and_ignore_me(cx: &mut TestAppContext) { |
| 1351 | cx.update(gpui_kit::init); |
| 1352 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 1353 | let app = cx.update(|cx| { |
| 1354 | cx.new(|_| { |
| 1355 | let mut state = AppState::new(store.clone(), Mode::default()); |
| 1356 | state.directory.me = Some(Person { |
| 1357 | user_id: "me".into(), |
| 1358 | display_name: "Me".into(), |
| 1359 | }); |
| 1360 | state |
| 1361 | }) |
| 1362 | }); |
| 1363 | let names = |cx: &mut TestAppContext| cx.update(|cx| app.read(cx).typing.names("c1")); |
| 1364 | cx.update(|cx| { |
| 1365 | app.update(cx, |state, cx| { |
| 1366 | state.apply(typing_event("me", true), cx); |
| 1367 | state.apply(typing_event("ada", true), cx); |
| 1368 | }) |
| 1369 | }); |
| 1370 | assert_eq!(names(cx), vec!["Name ada".to_owned()]); |
| 1371 | |
| 1372 | let message = MessageRecord { |
| 1373 | conversation_id: "c1".into(), |
| 1374 | message_id: "m1".into(), |
| 1375 | sender_id: Some("ada".into()), |
| 1376 | created_at: Utc::now() + Duration::seconds(1), |
| 1377 | ..Default::default() |
| 1378 | }; |
| 1379 | store.upsert_messages(&[message]).unwrap(); |
| 1380 | cx.update(|cx| { |
| 1381 | app.update(cx, |state, cx| { |
| 1382 | state.apply( |
| 1383 | BackendEvent::Core(CoreEvent::MessagesChanged { |
| 1384 | conversation_id: "c1".into(), |
| 1385 | }), |
| 1386 | cx, |
| 1387 | ) |
| 1388 | }) |
| 1389 | }); |
| 1390 | assert!(names(cx).is_empty()); |
| 1391 | |
| 1392 | cx.update(|cx| { |
| 1393 | app.update(cx, |state, cx| { |
| 1394 | state.apply(typing_event("ada", true), cx); |
| 1395 | state.apply(typing_event("ada", false), cx); |
| 1396 | }) |
| 1397 | }); |
| 1398 | assert!(names(cx).is_empty()); |
| 1399 | } |
| 1400 | |
| 1401 | #[gpui_kit::test] |
| 1402 | fn typing_without_a_display_name_uses_the_chat_member_name(cx: &mut TestAppContext) { |
| 1403 | cx.update(gpui_kit::init); |
| 1404 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 1405 | let app = cx.update(|cx| { |
| 1406 | cx.new(|_| { |
| 1407 | let mut state = AppState::new(store.clone(), Mode::default()); |
| 1408 | let mut member_chat = chat("c1", "First", false); |
| 1409 | member_chat.members = vec![MemberRecord { |
| 1410 | user_id: Some("ada".into()), |
| 1411 | display_name: "Ada Lovelace".into(), |
| 1412 | }]; |
| 1413 | state.sidebar.chats = vec![member_chat]; |
| 1414 | state |
| 1415 | }) |
| 1416 | }); |
| 1417 | cx.update(|cx| { |
| 1418 | app.update(cx, |state, cx| { |
| 1419 | state.apply( |
| 1420 | BackendEvent::Typing(TypingEvent { |
| 1421 | conversation_id: "c1".into(), |
| 1422 | user_id: "ada".into(), |
| 1423 | display_name: String::new(), |
| 1424 | active: true, |
| 1425 | received_at: Utc::now(), |
| 1426 | }), |
| 1427 | cx, |
| 1428 | ) |
| 1429 | }) |
| 1430 | }); |
| 1431 | assert_eq!( |
| 1432 | cx.update(|cx| app.read(cx).typing.names("c1")), |
| 1433 | vec!["Ada Lovelace".to_owned()] |
| 1434 | ); |
| 1435 | } |
| 1436 | } |