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