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