room.rs

   1use crate::{
   2    call_settings::CallSettings,
   3    participant::{LocalParticipant, ParticipantLocation, RemoteParticipant},
   4};
   5use anyhow::{Context as _, Result, anyhow};
   6use audio::{Audio, Sound};
   7use client::{
   8    ChannelId, Client, ParticipantIndex, TypedEnvelope, User, UserStore,
   9    proto::{self, PeerId},
  10};
  11use collections::{BTreeMap, HashMap, HashSet};
  12use fs::Fs;
  13use futures::StreamExt;
  14use gpui::{
  15    App, AppContext as _, AsyncApp, Context, Entity, EventEmitter, FutureExt as _,
  16    ScreenCaptureSource, ScreenCaptureStream, Task, Timeout, WeakEntity,
  17};
  18use gpui_tokio::Tokio;
  19use language::LanguageRegistry;
  20use livekit::{LocalTrackPublication, ParticipantIdentity, RoomEvent};
  21use livekit_client::{self as livekit, AudioStream, TrackSid};
  22use postage::{sink::Sink, stream::Stream, watch};
  23use project::Project;
  24use settings::Settings as _;
  25use std::{future::Future, mem, rc::Rc, sync::Arc, time::Duration};
  26use util::{ResultExt, TryFutureExt, post_inc};
  27
  28pub const RECONNECT_TIMEOUT: Duration = Duration::from_secs(30);
  29
  30#[derive(Clone, Debug, PartialEq, Eq)]
  31pub enum Event {
  32    RoomJoined {
  33        channel_id: Option<ChannelId>,
  34    },
  35    ParticipantLocationChanged {
  36        participant_id: proto::PeerId,
  37    },
  38    RemoteVideoTracksChanged {
  39        participant_id: proto::PeerId,
  40    },
  41    RemoteVideoTrackUnsubscribed {
  42        sid: TrackSid,
  43    },
  44    RemoteAudioTracksChanged {
  45        participant_id: proto::PeerId,
  46    },
  47    RemoteProjectShared {
  48        owner: Arc<User>,
  49        project_id: u64,
  50        worktree_root_names: Vec<String>,
  51    },
  52    RemoteProjectUnshared {
  53        project_id: u64,
  54    },
  55    RemoteProjectJoined {
  56        project_id: u64,
  57    },
  58    RemoteProjectInvitationDiscarded {
  59        project_id: u64,
  60    },
  61    RoomLeft {
  62        channel_id: Option<ChannelId>,
  63    },
  64}
  65
  66pub struct Room {
  67    id: u64,
  68    channel_id: Option<ChannelId>,
  69    live_kit: Option<LiveKitRoom>,
  70    status: RoomStatus,
  71    shared_projects: HashSet<WeakEntity<Project>>,
  72    joined_projects: HashSet<WeakEntity<Project>>,
  73    local_participant: LocalParticipant,
  74    remote_participants: BTreeMap<u64, RemoteParticipant>,
  75    pending_participants: Vec<Arc<User>>,
  76    participant_user_ids: HashSet<u64>,
  77    pending_call_count: usize,
  78    leave_when_empty: bool,
  79    client: Arc<Client>,
  80    user_store: Entity<UserStore>,
  81    follows_by_leader_id_project_id: HashMap<(PeerId, u64), Vec<PeerId>>,
  82    client_subscriptions: Vec<client::Subscription>,
  83    _subscriptions: Vec<gpui::Subscription>,
  84    room_update_completed_tx: watch::Sender<Option<()>>,
  85    room_update_completed_rx: watch::Receiver<Option<()>>,
  86    pending_room_update: Option<Task<()>>,
  87    maintain_connection: Option<Task<Option<()>>>,
  88}
  89
  90impl EventEmitter<Event> for Room {}
  91
  92impl Room {
  93    pub fn channel_id(&self) -> Option<ChannelId> {
  94        self.channel_id
  95    }
  96
  97    pub fn is_sharing_project(&self) -> bool {
  98        !self.shared_projects.is_empty()
  99    }
 100
 101    pub fn is_connected(&self, _: &App) -> bool {
 102        if let Some(live_kit) = self.live_kit.as_ref() {
 103            live_kit.room.connection_state() == livekit::ConnectionState::Connected
 104        } else {
 105            false
 106        }
 107    }
 108
 109    fn new(
 110        id: u64,
 111        channel_id: Option<ChannelId>,
 112        livekit_connection_info: Option<proto::LiveKitConnectionInfo>,
 113        client: Arc<Client>,
 114        user_store: Entity<UserStore>,
 115        cx: &mut Context<Self>,
 116    ) -> Self {
 117        spawn_room_connection(livekit_connection_info, cx);
 118
 119        let maintain_connection = cx.spawn({
 120            let client = client.clone();
 121            async move |this, cx| {
 122                Self::maintain_connection(this, client.clone(), cx)
 123                    .log_err()
 124                    .await
 125            }
 126        });
 127
 128        Audio::play_sound(Sound::Joined, cx);
 129
 130        let (room_update_completed_tx, room_update_completed_rx) = watch::channel();
 131
 132        Self {
 133            id,
 134            channel_id,
 135            live_kit: None,
 136            status: RoomStatus::Online,
 137            shared_projects: Default::default(),
 138            joined_projects: Default::default(),
 139            participant_user_ids: Default::default(),
 140            local_participant: Default::default(),
 141            remote_participants: Default::default(),
 142            pending_participants: Default::default(),
 143            pending_call_count: 0,
 144            client_subscriptions: vec![
 145                client.add_message_handler(cx.weak_entity(), Self::handle_room_updated),
 146            ],
 147            _subscriptions: vec![
 148                cx.on_release(Self::released),
 149                cx.on_app_quit(Self::app_will_quit),
 150            ],
 151            leave_when_empty: false,
 152            pending_room_update: None,
 153            client,
 154            user_store,
 155            follows_by_leader_id_project_id: Default::default(),
 156            maintain_connection: Some(maintain_connection),
 157            room_update_completed_tx,
 158            room_update_completed_rx,
 159        }
 160    }
 161
 162    pub(crate) fn create(
 163        called_user_id: u64,
 164        initial_project: Option<Entity<Project>>,
 165        client: Arc<Client>,
 166        user_store: Entity<UserStore>,
 167        cx: &mut App,
 168    ) -> Task<Result<Entity<Self>>> {
 169        cx.spawn(async move |cx| {
 170            let response = client.request(proto::CreateRoom {}).await?;
 171            let room_proto = response.room.context("invalid room")?;
 172            let room = cx.new(|cx| {
 173                let mut room = Self::new(
 174                    room_proto.id,
 175                    None,
 176                    response.live_kit_connection_info,
 177                    client,
 178                    user_store,
 179                    cx,
 180                );
 181                if let Some(participant) = room_proto.participants.first() {
 182                    room.local_participant.role = participant.role()
 183                }
 184                room
 185            })?;
 186
 187            let initial_project_id = if let Some(initial_project) = initial_project {
 188                let initial_project_id = room
 189                    .update(cx, |room, cx| {
 190                        room.share_project(initial_project.clone(), cx)
 191                    })?
 192                    .await?;
 193                Some(initial_project_id)
 194            } else {
 195                None
 196            };
 197
 198            let did_join = room
 199                .update(cx, |room, cx| {
 200                    room.leave_when_empty = true;
 201                    room.call(called_user_id, initial_project_id, cx)
 202                })?
 203                .await;
 204            match did_join {
 205                Ok(()) => Ok(room),
 206                Err(error) => Err(error.context("room creation failed")),
 207            }
 208        })
 209    }
 210
 211    pub(crate) async fn join_channel(
 212        channel_id: ChannelId,
 213        client: Arc<Client>,
 214        user_store: Entity<UserStore>,
 215        cx: AsyncApp,
 216    ) -> Result<Entity<Self>> {
 217        Self::from_join_response(
 218            client
 219                .request(proto::JoinChannel {
 220                    channel_id: channel_id.0,
 221                })
 222                .await?,
 223            client,
 224            user_store,
 225            cx,
 226        )
 227    }
 228
 229    pub(crate) async fn join(
 230        room_id: u64,
 231        client: Arc<Client>,
 232        user_store: Entity<UserStore>,
 233        cx: AsyncApp,
 234    ) -> Result<Entity<Self>> {
 235        Self::from_join_response(
 236            client.request(proto::JoinRoom { id: room_id }).await?,
 237            client,
 238            user_store,
 239            cx,
 240        )
 241    }
 242
 243    fn released(&mut self, cx: &mut App) {
 244        if self.status.is_online() {
 245            self.leave_internal(cx).detach_and_log_err(cx);
 246        }
 247    }
 248
 249    fn app_will_quit(&mut self, cx: &mut Context<Self>) -> impl Future<Output = ()> + use<> {
 250        let task = if self.status.is_online() {
 251            let leave = self.leave_internal(cx);
 252            Some(cx.background_spawn(async move {
 253                leave.await.log_err();
 254            }))
 255        } else {
 256            None
 257        };
 258
 259        async move {
 260            if let Some(task) = task {
 261                task.await;
 262            }
 263        }
 264    }
 265
 266    pub fn mute_on_join(cx: &App) -> bool {
 267        CallSettings::get_global(cx).mute_on_join || client::IMPERSONATE_LOGIN.is_some()
 268    }
 269
 270    fn from_join_response(
 271        response: proto::JoinRoomResponse,
 272        client: Arc<Client>,
 273        user_store: Entity<UserStore>,
 274        mut cx: AsyncApp,
 275    ) -> Result<Entity<Self>> {
 276        let room_proto = response.room.context("invalid room")?;
 277        let room = cx.new(|cx| {
 278            Self::new(
 279                room_proto.id,
 280                response.channel_id.map(ChannelId),
 281                response.live_kit_connection_info,
 282                client,
 283                user_store,
 284                cx,
 285            )
 286        })?;
 287        room.update(&mut cx, |room, cx| {
 288            room.leave_when_empty = room.channel_id.is_none();
 289            room.apply_room_update(room_proto, cx)?;
 290            anyhow::Ok(())
 291        })??;
 292        Ok(room)
 293    }
 294
 295    fn should_leave(&self) -> bool {
 296        self.leave_when_empty
 297            && self.pending_room_update.is_none()
 298            && self.pending_participants.is_empty()
 299            && self.remote_participants.is_empty()
 300            && self.pending_call_count == 0
 301    }
 302
 303    pub(crate) fn leave(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
 304        cx.notify();
 305        self.leave_internal(cx)
 306    }
 307
 308    fn leave_internal(&mut self, cx: &mut App) -> Task<Result<()>> {
 309        if self.status.is_offline() {
 310            return Task::ready(Err(anyhow!("room is offline")));
 311        }
 312
 313        log::info!("leaving room");
 314        Audio::play_sound(Sound::Leave, cx);
 315
 316        self.clear_state(cx);
 317
 318        let leave_room = self.client.request(proto::LeaveRoom {});
 319        cx.background_spawn(async move {
 320            leave_room.await?;
 321            anyhow::Ok(())
 322        })
 323    }
 324
 325    pub(crate) fn clear_state(&mut self, cx: &mut App) {
 326        for project in self.shared_projects.drain() {
 327            if let Some(project) = project.upgrade() {
 328                project.update(cx, |project, cx| {
 329                    project.unshare(cx).log_err();
 330                });
 331            }
 332        }
 333        for project in self.joined_projects.drain() {
 334            if let Some(project) = project.upgrade() {
 335                project.update(cx, |project, cx| {
 336                    project.disconnected_from_host(cx);
 337                    project.close(cx);
 338                });
 339            }
 340        }
 341
 342        self.status = RoomStatus::Offline;
 343        self.remote_participants.clear();
 344        self.pending_participants.clear();
 345        self.participant_user_ids.clear();
 346        self.client_subscriptions.clear();
 347        self.live_kit.take();
 348        self.pending_room_update.take();
 349        self.maintain_connection.take();
 350    }
 351
 352    async fn maintain_connection(
 353        this: WeakEntity<Self>,
 354        client: Arc<Client>,
 355        cx: &mut AsyncApp,
 356    ) -> Result<()> {
 357        let mut client_status = client.status();
 358        loop {
 359            let _ = client_status.try_recv();
 360            let is_connected = client_status.borrow().is_connected();
 361            // Even if we're initially connected, any future change of the status means we momentarily disconnected.
 362            if !is_connected || client_status.next().await.is_some() {
 363                log::info!("detected client disconnection");
 364
 365                this.upgrade()
 366                    .context("room was dropped")?
 367                    .update(cx, |this, cx| {
 368                        this.status = RoomStatus::Rejoining;
 369                        cx.notify();
 370                    })?;
 371
 372                // Wait for client to re-establish a connection to the server.
 373                let executor = cx.background_executor().clone();
 374                let client_reconnection = async {
 375                    let mut remaining_attempts = 3;
 376                    while remaining_attempts > 0 {
 377                        if client_status.borrow().is_connected() {
 378                            log::info!("client reconnected, attempting to rejoin room");
 379
 380                            let Some(this) = this.upgrade() else { break };
 381                            match this.update(cx, |this, cx| this.rejoin(cx)) {
 382                                Ok(task) => {
 383                                    if task.await.log_err().is_some() {
 384                                        return true;
 385                                    } else {
 386                                        remaining_attempts -= 1;
 387                                    }
 388                                }
 389                                Err(_app_dropped) => return false,
 390                            }
 391                        } else if client_status.borrow().is_signed_out() {
 392                            return false;
 393                        }
 394
 395                        log::info!(
 396                            "waiting for client status change, remaining attempts {}",
 397                            remaining_attempts
 398                        );
 399                        client_status.next().await;
 400                    }
 401                    false
 402                };
 403
 404                match client_reconnection
 405                    .with_timeout(RECONNECT_TIMEOUT, &executor)
 406                    .await
 407                {
 408                    Ok(true) => {
 409                        log::info!("successfully reconnected to room");
 410                        // If we successfully joined the room, go back around the loop
 411                        // waiting for future connection status changes.
 412                        continue;
 413                    }
 414                    Ok(false) => break,
 415                    Err(Timeout) => {
 416                        log::info!("room reconnection timeout expired");
 417                        break;
 418                    }
 419                }
 420            }
 421        }
 422
 423        // The client failed to re-establish a connection to the server
 424        // or an error occurred while trying to re-join the room. Either way
 425        // we leave the room and return an error.
 426        if let Some(this) = this.upgrade() {
 427            log::info!("reconnection failed, leaving room");
 428            this.update(cx, |this, cx| this.leave(cx))?.await?;
 429        }
 430        anyhow::bail!("can't reconnect to room: client failed to re-establish connection");
 431    }
 432
 433    fn rejoin(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
 434        let mut projects = HashMap::default();
 435        let mut reshared_projects = Vec::new();
 436        let mut rejoined_projects = Vec::new();
 437        self.shared_projects.retain(|project| {
 438            if let Some(handle) = project.upgrade() {
 439                let project = handle.read(cx);
 440                if let Some(project_id) = project.remote_id() {
 441                    projects.insert(project_id, handle.clone());
 442                    reshared_projects.push(proto::UpdateProject {
 443                        project_id,
 444                        worktrees: project.worktree_metadata_protos(cx),
 445                    });
 446                    return true;
 447                }
 448            }
 449            false
 450        });
 451        self.joined_projects.retain(|project| {
 452            if let Some(handle) = project.upgrade() {
 453                let project = handle.read(cx);
 454                if let Some(project_id) = project.remote_id() {
 455                    projects.insert(project_id, handle.clone());
 456                    let mut worktrees = Vec::new();
 457                    let mut repositories = Vec::new();
 458                    for worktree in project.worktrees(cx) {
 459                        let worktree = worktree.read(cx);
 460                        worktrees.push(proto::RejoinWorktree {
 461                            id: worktree.id().to_proto(),
 462                            scan_id: worktree.completed_scan_id() as u64,
 463                        });
 464                    }
 465                    for (entry_id, repository) in project.repositories(cx) {
 466                        let repository = repository.read(cx);
 467                        repositories.push(proto::RejoinRepository {
 468                            id: entry_id.to_proto(),
 469                            scan_id: repository.scan_id,
 470                        });
 471                    }
 472
 473                    rejoined_projects.push(proto::RejoinProject {
 474                        id: project_id,
 475                        worktrees,
 476                        repositories,
 477                    });
 478                }
 479                return true;
 480            }
 481            false
 482        });
 483
 484        let response = self.client.request_envelope(proto::RejoinRoom {
 485            id: self.id,
 486            reshared_projects,
 487            rejoined_projects,
 488        });
 489
 490        cx.spawn(async move |this, cx| {
 491            let response = response.await?;
 492            let message_id = response.message_id;
 493            let response = response.payload;
 494            let room_proto = response.room.context("invalid room")?;
 495            this.update(cx, |this, cx| {
 496                this.status = RoomStatus::Online;
 497                this.apply_room_update(room_proto, cx)?;
 498
 499                for reshared_project in response.reshared_projects {
 500                    if let Some(project) = projects.get(&reshared_project.id) {
 501                        project.update(cx, |project, cx| {
 502                            project.reshared(reshared_project, cx).log_err();
 503                        });
 504                    }
 505                }
 506
 507                for rejoined_project in response.rejoined_projects {
 508                    if let Some(project) = projects.get(&rejoined_project.id) {
 509                        project.update(cx, |project, cx| {
 510                            project.rejoined(rejoined_project, message_id, cx).log_err();
 511                        });
 512                    }
 513                }
 514
 515                anyhow::Ok(())
 516            })?
 517        })
 518    }
 519
 520    pub fn id(&self) -> u64 {
 521        self.id
 522    }
 523
 524    pub fn status(&self) -> RoomStatus {
 525        self.status
 526    }
 527
 528    pub fn local_participant(&self) -> &LocalParticipant {
 529        &self.local_participant
 530    }
 531
 532    pub fn local_participant_user(&self, cx: &App) -> Option<Arc<User>> {
 533        self.user_store.read(cx).current_user()
 534    }
 535
 536    pub fn remote_participants(&self) -> &BTreeMap<u64, RemoteParticipant> {
 537        &self.remote_participants
 538    }
 539
 540    pub fn remote_participant_for_peer_id(&self, peer_id: PeerId) -> Option<&RemoteParticipant> {
 541        self.remote_participants
 542            .values()
 543            .find(|p| p.peer_id == peer_id)
 544    }
 545
 546    pub fn role_for_user(&self, user_id: u64) -> Option<proto::ChannelRole> {
 547        self.remote_participants
 548            .get(&user_id)
 549            .map(|participant| participant.role)
 550    }
 551
 552    pub fn contains_guests(&self) -> bool {
 553        self.local_participant.role == proto::ChannelRole::Guest
 554            || self
 555                .remote_participants
 556                .values()
 557                .any(|p| p.role == proto::ChannelRole::Guest)
 558    }
 559
 560    pub fn local_participant_is_admin(&self) -> bool {
 561        self.local_participant.role == proto::ChannelRole::Admin
 562    }
 563
 564    pub fn local_participant_is_guest(&self) -> bool {
 565        self.local_participant.role == proto::ChannelRole::Guest
 566    }
 567
 568    pub fn set_participant_role(
 569        &mut self,
 570        user_id: u64,
 571        role: proto::ChannelRole,
 572        cx: &Context<Self>,
 573    ) -> Task<Result<()>> {
 574        let client = self.client.clone();
 575        let room_id = self.id;
 576        let role = role.into();
 577        cx.spawn(async move |_, _| {
 578            client
 579                .request(proto::SetRoomParticipantRole {
 580                    room_id,
 581                    user_id,
 582                    role,
 583                })
 584                .await
 585                .map(|_| ())
 586        })
 587    }
 588
 589    pub fn pending_participants(&self) -> &[Arc<User>] {
 590        &self.pending_participants
 591    }
 592
 593    pub fn contains_participant(&self, user_id: u64) -> bool {
 594        self.participant_user_ids.contains(&user_id)
 595    }
 596
 597    pub fn followers_for(&self, leader_id: PeerId, project_id: u64) -> &[PeerId] {
 598        self.follows_by_leader_id_project_id
 599            .get(&(leader_id, project_id))
 600            .map_or(&[], |v| v.as_slice())
 601    }
 602
 603    /// Returns the most 'active' projects, defined as most people in the project
 604    pub fn most_active_project(&self, cx: &App) -> Option<(u64, u64)> {
 605        let mut project_hosts_and_guest_counts = HashMap::<u64, (Option<u64>, u32)>::default();
 606        for participant in self.remote_participants.values() {
 607            match participant.location {
 608                ParticipantLocation::SharedProject { project_id } => {
 609                    project_hosts_and_guest_counts
 610                        .entry(project_id)
 611                        .or_default()
 612                        .1 += 1;
 613                }
 614                ParticipantLocation::External | ParticipantLocation::UnsharedProject => {}
 615            }
 616            for project in &participant.projects {
 617                project_hosts_and_guest_counts
 618                    .entry(project.id)
 619                    .or_default()
 620                    .0 = Some(participant.user.id);
 621            }
 622        }
 623
 624        if let Some(user) = self.user_store.read(cx).current_user() {
 625            for project in &self.local_participant.projects {
 626                project_hosts_and_guest_counts
 627                    .entry(project.id)
 628                    .or_default()
 629                    .0 = Some(user.id);
 630            }
 631        }
 632
 633        project_hosts_and_guest_counts
 634            .into_iter()
 635            .filter_map(|(id, (host, guest_count))| Some((id, host?, guest_count)))
 636            .max_by_key(|(_, _, guest_count)| *guest_count)
 637            .map(|(id, host, _)| (id, host))
 638    }
 639
 640    async fn handle_room_updated(
 641        this: Entity<Self>,
 642        envelope: TypedEnvelope<proto::RoomUpdated>,
 643        mut cx: AsyncApp,
 644    ) -> Result<()> {
 645        let room = envelope.payload.room.context("invalid room")?;
 646        this.update(&mut cx, |this, cx| this.apply_room_update(room, cx))?
 647    }
 648
 649    fn apply_room_update(&mut self, room: proto::Room, cx: &mut Context<Self>) -> Result<()> {
 650        log::trace!(
 651            "client {:?}. room update: {:?}",
 652            self.client.user_id(),
 653            &room
 654        );
 655
 656        self.pending_room_update = Some(self.start_room_connection(room, cx));
 657
 658        cx.notify();
 659        Ok(())
 660    }
 661
 662    pub fn room_update_completed(&mut self) -> impl Future<Output = ()> + use<> {
 663        let mut done_rx = self.room_update_completed_rx.clone();
 664        async move {
 665            while let Some(result) = done_rx.next().await {
 666                if result.is_some() {
 667                    break;
 668                }
 669            }
 670        }
 671    }
 672
 673    fn start_room_connection(&self, mut room: proto::Room, cx: &mut Context<Self>) -> Task<()> {
 674        // Filter ourselves out from the room's participants.
 675        let local_participant_ix = room
 676            .participants
 677            .iter()
 678            .position(|participant| Some(participant.user_id) == self.client.user_id());
 679        let local_participant = local_participant_ix.map(|ix| room.participants.swap_remove(ix));
 680
 681        let pending_participant_user_ids = room
 682            .pending_participants
 683            .iter()
 684            .map(|p| p.user_id)
 685            .collect::<Vec<_>>();
 686
 687        let remote_participant_user_ids = room
 688            .participants
 689            .iter()
 690            .map(|p| p.user_id)
 691            .collect::<Vec<_>>();
 692
 693        let (remote_participants, pending_participants) =
 694            self.user_store.update(cx, move |user_store, cx| {
 695                (
 696                    user_store.get_users(remote_participant_user_ids, cx),
 697                    user_store.get_users(pending_participant_user_ids, cx),
 698                )
 699            });
 700        cx.spawn(async move |this, cx| {
 701            let (remote_participants, pending_participants) =
 702                futures::join!(remote_participants, pending_participants);
 703
 704            this.update(cx, |this, cx| {
 705                this.participant_user_ids.clear();
 706
 707                if let Some(participant) = local_participant {
 708                    let role = participant.role();
 709                    this.local_participant.projects = participant.projects;
 710                    if this.local_participant.role != role {
 711                        this.local_participant.role = role;
 712
 713                        if role == proto::ChannelRole::Guest {
 714                            for project in mem::take(&mut this.shared_projects) {
 715                                if let Some(project) = project.upgrade() {
 716                                    this.unshare_project(project, cx).log_err();
 717                                }
 718                            }
 719                            this.local_participant.projects.clear();
 720                            if let Some(livekit_room) = &mut this.live_kit {
 721                                livekit_room.stop_publishing(cx);
 722                            }
 723                        }
 724
 725                        this.joined_projects.retain(|project| {
 726                            if let Some(project) = project.upgrade() {
 727                                project.update(cx, |project, cx| project.set_role(role, cx));
 728                                true
 729                            } else {
 730                                false
 731                            }
 732                        });
 733                    }
 734                } else {
 735                    this.local_participant.projects.clear();
 736                }
 737
 738                let livekit_participants = this
 739                    .live_kit
 740                    .as_ref()
 741                    .map(|live_kit| live_kit.room.remote_participants());
 742
 743                if let Some(participants) = remote_participants.log_err() {
 744                    for (participant, user) in room.participants.into_iter().zip(participants) {
 745                        let Some(peer_id) = participant.peer_id else {
 746                            continue;
 747                        };
 748                        let participant_index = ParticipantIndex(participant.participant_index);
 749                        this.participant_user_ids.insert(participant.user_id);
 750
 751                        let old_projects = this
 752                            .remote_participants
 753                            .get(&participant.user_id)
 754                            .into_iter()
 755                            .flat_map(|existing| &existing.projects)
 756                            .map(|project| project.id)
 757                            .collect::<HashSet<_>>();
 758                        let new_projects = participant
 759                            .projects
 760                            .iter()
 761                            .map(|project| project.id)
 762                            .collect::<HashSet<_>>();
 763
 764                        for project in &participant.projects {
 765                            if !old_projects.contains(&project.id) {
 766                                cx.emit(Event::RemoteProjectShared {
 767                                    owner: user.clone(),
 768                                    project_id: project.id,
 769                                    worktree_root_names: project.worktree_root_names.clone(),
 770                                });
 771                            }
 772                        }
 773
 774                        for unshared_project_id in old_projects.difference(&new_projects) {
 775                            this.joined_projects.retain(|project| {
 776                                if let Some(project) = project.upgrade() {
 777                                    project.update(cx, |project, cx| {
 778                                        if project.remote_id() == Some(*unshared_project_id) {
 779                                            project.disconnected_from_host(cx);
 780                                            false
 781                                        } else {
 782                                            true
 783                                        }
 784                                    })
 785                                } else {
 786                                    false
 787                                }
 788                            });
 789                            cx.emit(Event::RemoteProjectUnshared {
 790                                project_id: *unshared_project_id,
 791                            });
 792                        }
 793
 794                        let role = participant.role();
 795                        let location = ParticipantLocation::from_proto(participant.location)
 796                            .unwrap_or(ParticipantLocation::External);
 797                        if let Some(remote_participant) =
 798                            this.remote_participants.get_mut(&participant.user_id)
 799                        {
 800                            remote_participant.peer_id = peer_id;
 801                            remote_participant.projects = participant.projects;
 802                            remote_participant.participant_index = participant_index;
 803                            if location != remote_participant.location
 804                                || role != remote_participant.role
 805                            {
 806                                remote_participant.location = location;
 807                                remote_participant.role = role;
 808                                cx.emit(Event::ParticipantLocationChanged {
 809                                    participant_id: peer_id,
 810                                });
 811                            }
 812                        } else {
 813                            this.remote_participants.insert(
 814                                participant.user_id,
 815                                RemoteParticipant {
 816                                    user: user.clone(),
 817                                    participant_index,
 818                                    peer_id,
 819                                    projects: participant.projects,
 820                                    location,
 821                                    role,
 822                                    muted: true,
 823                                    speaking: false,
 824                                    video_tracks: Default::default(),
 825                                    audio_tracks: Default::default(),
 826                                },
 827                            );
 828
 829                            Audio::play_sound(Sound::Joined, cx);
 830                            if let Some(livekit_participants) = &livekit_participants
 831                                && let Some(livekit_participant) = livekit_participants
 832                                    .get(&ParticipantIdentity(user.id.to_string()))
 833                                {
 834                                    for publication in
 835                                        livekit_participant.track_publications().into_values()
 836                                    {
 837                                        if let Some(track) = publication.track() {
 838                                            this.livekit_room_updated(
 839                                                RoomEvent::TrackSubscribed {
 840                                                    track,
 841                                                    publication,
 842                                                    participant: livekit_participant.clone(),
 843                                                },
 844                                                cx,
 845                                            )
 846                                            .warn_on_err();
 847                                        }
 848                                    }
 849                                }
 850                        }
 851                    }
 852
 853                    this.remote_participants.retain(|user_id, participant| {
 854                        if this.participant_user_ids.contains(user_id) {
 855                            true
 856                        } else {
 857                            for project in &participant.projects {
 858                                cx.emit(Event::RemoteProjectUnshared {
 859                                    project_id: project.id,
 860                                });
 861                            }
 862                            false
 863                        }
 864                    });
 865                }
 866
 867                if let Some(pending_participants) = pending_participants.log_err() {
 868                    this.pending_participants = pending_participants;
 869                    for participant in &this.pending_participants {
 870                        this.participant_user_ids.insert(participant.id);
 871                    }
 872                }
 873
 874                this.follows_by_leader_id_project_id.clear();
 875                for follower in room.followers {
 876                    let project_id = follower.project_id;
 877                    let (leader, follower) = match (follower.leader_id, follower.follower_id) {
 878                        (Some(leader), Some(follower)) => (leader, follower),
 879
 880                        _ => {
 881                            log::error!("Follower message {follower:?} missing some state");
 882                            continue;
 883                        }
 884                    };
 885
 886                    let list = this
 887                        .follows_by_leader_id_project_id
 888                        .entry((leader, project_id))
 889                        .or_default();
 890                    if !list.contains(&follower) {
 891                        list.push(follower);
 892                    }
 893                }
 894
 895                this.pending_room_update.take();
 896                if this.should_leave() {
 897                    log::info!("room is empty, leaving");
 898                    this.leave(cx).detach();
 899                }
 900
 901                this.user_store.update(cx, |user_store, cx| {
 902                    let participant_indices_by_user_id = this
 903                        .remote_participants
 904                        .iter()
 905                        .map(|(user_id, participant)| (*user_id, participant.participant_index))
 906                        .collect();
 907                    user_store.set_participant_indices(participant_indices_by_user_id, cx);
 908                });
 909
 910                this.check_invariants();
 911                this.room_update_completed_tx.try_send(Some(())).ok();
 912                cx.notify();
 913            })
 914            .ok();
 915        })
 916    }
 917
 918    fn livekit_room_updated(&mut self, event: RoomEvent, cx: &mut Context<Self>) -> Result<()> {
 919        log::trace!(
 920            "client {:?}. livekit event: {:?}",
 921            self.client.user_id(),
 922            &event
 923        );
 924
 925        match event {
 926            RoomEvent::TrackSubscribed {
 927                track,
 928                participant,
 929                publication,
 930            } => {
 931                let user_id = participant.identity().0.parse()?;
 932                let track_id = track.sid();
 933                let participant =
 934                    self.remote_participants
 935                        .get_mut(&user_id)
 936                        .with_context(|| {
 937                            format!(
 938                                "{:?} subscribed to track by unknown participant {user_id}",
 939                                self.client.user_id()
 940                            )
 941                        })?;
 942                if self.live_kit.as_ref().map_or(true, |kit| kit.deafened)
 943                    && publication.is_audio() {
 944                        publication.set_enabled(false, cx);
 945                    }
 946                match track {
 947                    livekit_client::RemoteTrack::Audio(track) => {
 948                        cx.emit(Event::RemoteAudioTracksChanged {
 949                            participant_id: participant.peer_id,
 950                        });
 951                        if let Some(live_kit) = self.live_kit.as_ref() {
 952                            let stream = live_kit.room.play_remote_audio_track(&track, cx)?;
 953                            participant.audio_tracks.insert(track_id, (track, stream));
 954                            participant.muted = publication.is_muted();
 955                        }
 956                    }
 957                    livekit_client::RemoteTrack::Video(track) => {
 958                        cx.emit(Event::RemoteVideoTracksChanged {
 959                            participant_id: participant.peer_id,
 960                        });
 961                        participant.video_tracks.insert(track_id, track);
 962                    }
 963                }
 964            }
 965
 966            RoomEvent::TrackUnsubscribed {
 967                track, participant, ..
 968            } => {
 969                let user_id = participant.identity().0.parse()?;
 970                let participant =
 971                    self.remote_participants
 972                        .get_mut(&user_id)
 973                        .with_context(|| {
 974                            format!(
 975                                "{:?}, unsubscribed from track by unknown participant {user_id}",
 976                                self.client.user_id()
 977                            )
 978                        })?;
 979                match track {
 980                    livekit_client::RemoteTrack::Audio(track) => {
 981                        participant.audio_tracks.remove(&track.sid());
 982                        participant.muted = true;
 983                        cx.emit(Event::RemoteAudioTracksChanged {
 984                            participant_id: participant.peer_id,
 985                        });
 986                    }
 987                    livekit_client::RemoteTrack::Video(track) => {
 988                        participant.video_tracks.remove(&track.sid());
 989                        cx.emit(Event::RemoteVideoTracksChanged {
 990                            participant_id: participant.peer_id,
 991                        });
 992                        cx.emit(Event::RemoteVideoTrackUnsubscribed { sid: track.sid() });
 993                    }
 994                }
 995            }
 996
 997            RoomEvent::ActiveSpeakersChanged { speakers } => {
 998                let mut speaker_ids = speakers
 999                    .into_iter()
1000                    .filter_map(|speaker| speaker.identity().0.parse().ok())
1001                    .collect::<Vec<u64>>();
1002                speaker_ids.sort_unstable();
1003                for (sid, participant) in &mut self.remote_participants {
1004                    participant.speaking = speaker_ids.binary_search(sid).is_ok();
1005                }
1006                if let Some(id) = self.client.user_id()
1007                    && let Some(room) = &mut self.live_kit {
1008                        room.speaking = speaker_ids.binary_search(&id).is_ok();
1009                    }
1010            }
1011
1012            RoomEvent::TrackMuted {
1013                participant,
1014                publication,
1015            }
1016            | RoomEvent::TrackUnmuted {
1017                participant,
1018                publication,
1019            } => {
1020                let mut found = false;
1021                let user_id = participant.identity().0.parse()?;
1022                let track_id = publication.sid();
1023                if let Some(participant) = self.remote_participants.get_mut(&user_id) {
1024                    for (track, _) in participant.audio_tracks.values() {
1025                        if track.sid() == track_id {
1026                            found = true;
1027                            break;
1028                        }
1029                    }
1030                    if found {
1031                        participant.muted = publication.is_muted();
1032                    }
1033                }
1034            }
1035
1036            RoomEvent::LocalTrackUnpublished { publication, .. } => {
1037                log::info!("unpublished track {}", publication.sid());
1038                if let Some(room) = &mut self.live_kit {
1039                    if let LocalTrack::Published {
1040                        track_publication, ..
1041                    } = &room.microphone_track
1042                        && track_publication.sid() == publication.sid() {
1043                            room.microphone_track = LocalTrack::None;
1044                        }
1045                    if let LocalTrack::Published {
1046                        track_publication, ..
1047                    } = &room.screen_track
1048                        && track_publication.sid() == publication.sid() {
1049                            room.screen_track = LocalTrack::None;
1050                        }
1051                }
1052            }
1053
1054            RoomEvent::LocalTrackPublished { publication, .. } => {
1055                log::info!("published track {:?}", publication.sid());
1056            }
1057
1058            RoomEvent::Disconnected { reason } => {
1059                log::info!("disconnected from room: {reason:?}");
1060                self.leave(cx).detach_and_log_err(cx);
1061            }
1062            _ => {}
1063        }
1064
1065        cx.notify();
1066        Ok(())
1067    }
1068
1069    fn check_invariants(&self) {
1070        #[cfg(any(test, feature = "test-support"))]
1071        {
1072            for participant in self.remote_participants.values() {
1073                assert!(self.participant_user_ids.contains(&participant.user.id));
1074                assert_ne!(participant.user.id, self.client.user_id().unwrap());
1075            }
1076
1077            for participant in &self.pending_participants {
1078                assert!(self.participant_user_ids.contains(&participant.id));
1079                assert_ne!(participant.id, self.client.user_id().unwrap());
1080            }
1081
1082            assert_eq!(
1083                self.participant_user_ids.len(),
1084                self.remote_participants.len() + self.pending_participants.len()
1085            );
1086        }
1087    }
1088
1089    pub(crate) fn call(
1090        &mut self,
1091        called_user_id: u64,
1092        initial_project_id: Option<u64>,
1093        cx: &mut Context<Self>,
1094    ) -> Task<Result<()>> {
1095        if self.status.is_offline() {
1096            return Task::ready(Err(anyhow!("room is offline")));
1097        }
1098
1099        cx.notify();
1100        let client = self.client.clone();
1101        let room_id = self.id;
1102        self.pending_call_count += 1;
1103        cx.spawn(async move |this, cx| {
1104            let result = client
1105                .request(proto::Call {
1106                    room_id,
1107                    called_user_id,
1108                    initial_project_id,
1109                })
1110                .await;
1111            this.update(cx, |this, cx| {
1112                this.pending_call_count -= 1;
1113                if this.should_leave() {
1114                    this.leave(cx).detach_and_log_err(cx);
1115                }
1116            })?;
1117            result?;
1118            Ok(())
1119        })
1120    }
1121
1122    pub fn join_project(
1123        &mut self,
1124        id: u64,
1125        language_registry: Arc<LanguageRegistry>,
1126        fs: Arc<dyn Fs>,
1127        cx: &mut Context<Self>,
1128    ) -> Task<Result<Entity<Project>>> {
1129        let client = self.client.clone();
1130        let user_store = self.user_store.clone();
1131        cx.emit(Event::RemoteProjectJoined { project_id: id });
1132        cx.spawn(async move |this, cx| {
1133            let project =
1134                Project::in_room(id, client, user_store, language_registry, fs, cx.clone()).await?;
1135
1136            this.update(cx, |this, cx| {
1137                this.joined_projects.retain(|project| {
1138                    if let Some(project) = project.upgrade() {
1139                        !project.read(cx).is_disconnected(cx)
1140                    } else {
1141                        false
1142                    }
1143                });
1144                this.joined_projects.insert(project.downgrade());
1145            })?;
1146            Ok(project)
1147        })
1148    }
1149
1150    pub fn share_project(
1151        &mut self,
1152        project: Entity<Project>,
1153        cx: &mut Context<Self>,
1154    ) -> Task<Result<u64>> {
1155        if let Some(project_id) = project.read(cx).remote_id() {
1156            return Task::ready(Ok(project_id));
1157        }
1158
1159        let request = self.client.request(proto::ShareProject {
1160            room_id: self.id(),
1161            worktrees: project.read(cx).worktree_metadata_protos(cx),
1162            is_ssh_project: project.read(cx).is_via_ssh(),
1163        });
1164
1165        cx.spawn(async move |this, cx| {
1166            let response = request.await?;
1167
1168            project.update(cx, |project, cx| project.shared(response.project_id, cx))??;
1169
1170            // If the user's location is in this project, it changes from UnsharedProject to SharedProject.
1171            this.update(cx, |this, cx| {
1172                this.shared_projects.insert(project.downgrade());
1173                let active_project = this.local_participant.active_project.as_ref();
1174                if active_project.map_or(false, |location| *location == project) {
1175                    this.set_location(Some(&project), cx)
1176                } else {
1177                    Task::ready(Ok(()))
1178                }
1179            })?
1180            .await?;
1181
1182            Ok(response.project_id)
1183        })
1184    }
1185
1186    pub(crate) fn unshare_project(
1187        &mut self,
1188        project: Entity<Project>,
1189        cx: &mut Context<Self>,
1190    ) -> Result<()> {
1191        let project_id = match project.read(cx).remote_id() {
1192            Some(project_id) => project_id,
1193            None => return Ok(()),
1194        };
1195
1196        self.client.send(proto::UnshareProject { project_id })?;
1197        project.update(cx, |this, cx| this.unshare(cx))?;
1198
1199        if self.local_participant.active_project == Some(project.downgrade()) {
1200            self.set_location(Some(&project), cx).detach_and_log_err(cx);
1201        }
1202        Ok(())
1203    }
1204
1205    pub(crate) fn set_location(
1206        &mut self,
1207        project: Option<&Entity<Project>>,
1208        cx: &mut Context<Self>,
1209    ) -> Task<Result<()>> {
1210        if self.status.is_offline() {
1211            return Task::ready(Err(anyhow!("room is offline")));
1212        }
1213
1214        let client = self.client.clone();
1215        let room_id = self.id;
1216        let location = if let Some(project) = project {
1217            self.local_participant.active_project = Some(project.downgrade());
1218            if let Some(project_id) = project.read(cx).remote_id() {
1219                proto::participant_location::Variant::SharedProject(
1220                    proto::participant_location::SharedProject { id: project_id },
1221                )
1222            } else {
1223                proto::participant_location::Variant::UnsharedProject(
1224                    proto::participant_location::UnsharedProject {},
1225                )
1226            }
1227        } else {
1228            self.local_participant.active_project = None;
1229            proto::participant_location::Variant::External(proto::participant_location::External {})
1230        };
1231
1232        cx.notify();
1233        cx.background_spawn(async move {
1234            client
1235                .request(proto::UpdateParticipantLocation {
1236                    room_id,
1237                    location: Some(proto::ParticipantLocation {
1238                        variant: Some(location),
1239                    }),
1240                })
1241                .await?;
1242            Ok(())
1243        })
1244    }
1245
1246    pub fn is_sharing_screen(&self) -> bool {
1247        self.live_kit.as_ref().map_or(false, |live_kit| {
1248            !matches!(live_kit.screen_track, LocalTrack::None)
1249        })
1250    }
1251
1252    pub fn shared_screen_id(&self) -> Option<u64> {
1253        self.live_kit.as_ref().and_then(|lk| match lk.screen_track {
1254            LocalTrack::Published { ref _stream, .. } => {
1255                _stream.metadata().ok().map(|meta| meta.id)
1256            }
1257            _ => None,
1258        })
1259    }
1260
1261    pub fn is_sharing_mic(&self) -> bool {
1262        self.live_kit.as_ref().map_or(false, |live_kit| {
1263            !matches!(live_kit.microphone_track, LocalTrack::None)
1264        })
1265    }
1266
1267    pub fn is_muted(&self) -> bool {
1268        self.live_kit.as_ref().map_or(false, |live_kit| {
1269            matches!(live_kit.microphone_track, LocalTrack::None)
1270                || live_kit.muted_by_user
1271                || live_kit.deafened
1272        })
1273    }
1274
1275    pub fn muted_by_user(&self) -> bool {
1276        self.live_kit
1277            .as_ref()
1278            .map_or(false, |live_kit| live_kit.muted_by_user)
1279    }
1280
1281    pub fn is_speaking(&self) -> bool {
1282        self.live_kit
1283            .as_ref()
1284            .map_or(false, |live_kit| live_kit.speaking)
1285    }
1286
1287    pub fn is_deafened(&self) -> Option<bool> {
1288        self.live_kit.as_ref().map(|live_kit| live_kit.deafened)
1289    }
1290
1291    pub fn can_use_microphone(&self) -> bool {
1292        use proto::ChannelRole::*;
1293
1294        match self.local_participant.role {
1295            Admin | Member | Talker => true,
1296            Guest | Banned => false,
1297        }
1298    }
1299
1300    pub fn can_share_projects(&self) -> bool {
1301        use proto::ChannelRole::*;
1302        match self.local_participant.role {
1303            Admin | Member => true,
1304            Guest | Banned | Talker => false,
1305        }
1306    }
1307
1308    #[track_caller]
1309    pub fn share_microphone(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
1310        if self.status.is_offline() {
1311            return Task::ready(Err(anyhow!("room is offline")));
1312        }
1313
1314        let (room, publish_id) = if let Some(live_kit) = self.live_kit.as_mut() {
1315            let publish_id = post_inc(&mut live_kit.next_publish_id);
1316            live_kit.microphone_track = LocalTrack::Pending { publish_id };
1317            cx.notify();
1318            (live_kit.room.clone(), publish_id)
1319        } else {
1320            return Task::ready(Err(anyhow!("live-kit was not initialized")));
1321        };
1322
1323        cx.spawn(async move |this, cx| {
1324            let publication = room.publish_local_microphone_track(cx).await;
1325            this.update(cx, |this, cx| {
1326                let live_kit = this
1327                    .live_kit
1328                    .as_mut()
1329                    .context("live-kit was not initialized")?;
1330
1331                let canceled = if let LocalTrack::Pending {
1332                    publish_id: cur_publish_id,
1333                } = &live_kit.microphone_track
1334                {
1335                    *cur_publish_id != publish_id
1336                } else {
1337                    true
1338                };
1339
1340                match publication {
1341                    Ok((publication, stream)) => {
1342                        if canceled {
1343                            cx.spawn(async move |_, cx| {
1344                                room.unpublish_local_track(publication.sid(), cx).await
1345                            })
1346                            .detach_and_log_err(cx)
1347                        } else {
1348                            if live_kit.muted_by_user || live_kit.deafened {
1349                                publication.mute(cx);
1350                            }
1351                            live_kit.microphone_track = LocalTrack::Published {
1352                                track_publication: publication,
1353                                _stream: Box::new(stream),
1354                            };
1355                            cx.notify();
1356                        }
1357                        Ok(())
1358                    }
1359                    Err(error) => {
1360                        if canceled {
1361                            Ok(())
1362                        } else {
1363                            live_kit.microphone_track = LocalTrack::None;
1364                            cx.notify();
1365                            Err(error)
1366                        }
1367                    }
1368                }
1369            })?
1370        })
1371    }
1372
1373    pub fn share_screen(
1374        &mut self,
1375        source: Rc<dyn ScreenCaptureSource>,
1376        cx: &mut Context<Self>,
1377    ) -> Task<Result<()>> {
1378        if self.status.is_offline() {
1379            return Task::ready(Err(anyhow!("room is offline")));
1380        }
1381        if self.is_sharing_screen() {
1382            return Task::ready(Err(anyhow!("screen was already shared")));
1383        }
1384
1385        let (participant, publish_id) = if let Some(live_kit) = self.live_kit.as_mut() {
1386            let publish_id = post_inc(&mut live_kit.next_publish_id);
1387            live_kit.screen_track = LocalTrack::Pending { publish_id };
1388            cx.notify();
1389            (live_kit.room.local_participant(), publish_id)
1390        } else {
1391            return Task::ready(Err(anyhow!("live-kit was not initialized")));
1392        };
1393
1394        cx.spawn(async move |this, cx| {
1395            let publication = participant.publish_screenshare_track(&*source, cx).await;
1396
1397            this.update(cx, |this, cx| {
1398                let live_kit = this
1399                    .live_kit
1400                    .as_mut()
1401                    .context("live-kit was not initialized")?;
1402
1403                let canceled = if let LocalTrack::Pending {
1404                    publish_id: cur_publish_id,
1405                } = &live_kit.screen_track
1406                {
1407                    *cur_publish_id != publish_id
1408                } else {
1409                    true
1410                };
1411
1412                match publication {
1413                    Ok((publication, stream)) => {
1414                        if canceled {
1415                            cx.spawn(async move |_, cx| {
1416                                participant.unpublish_track(publication.sid(), cx).await
1417                            })
1418                            .detach()
1419                        } else {
1420                            live_kit.screen_track = LocalTrack::Published {
1421                                track_publication: publication,
1422                                _stream: stream,
1423                            };
1424                            cx.notify();
1425                        }
1426
1427                        Audio::play_sound(Sound::StartScreenshare, cx);
1428                        Ok(())
1429                    }
1430                    Err(error) => {
1431                        if canceled {
1432                            Ok(())
1433                        } else {
1434                            live_kit.screen_track = LocalTrack::None;
1435                            cx.notify();
1436                            Err(error)
1437                        }
1438                    }
1439                }
1440            })?
1441        })
1442    }
1443
1444    pub fn toggle_mute(&mut self, cx: &mut Context<Self>) {
1445        if let Some(live_kit) = self.live_kit.as_mut() {
1446            // When unmuting, undeafen if the user was deafened before.
1447            let was_deafened = live_kit.deafened;
1448            if live_kit.muted_by_user
1449                || live_kit.deafened
1450                || matches!(live_kit.microphone_track, LocalTrack::None)
1451            {
1452                live_kit.muted_by_user = false;
1453                live_kit.deafened = false;
1454            } else {
1455                live_kit.muted_by_user = true;
1456            }
1457            let muted = live_kit.muted_by_user;
1458            let should_undeafen = was_deafened && !live_kit.deafened;
1459
1460            if let Some(task) = self.set_mute(muted, cx) {
1461                task.detach_and_log_err(cx);
1462            }
1463
1464            if should_undeafen {
1465                self.set_deafened(false, cx);
1466            }
1467        }
1468    }
1469
1470    pub fn toggle_deafen(&mut self, cx: &mut Context<Self>) {
1471        if let Some(live_kit) = self.live_kit.as_mut() {
1472            // When deafening, mute the microphone if it was not already muted.
1473            // When un-deafening, unmute the microphone, unless it was explicitly muted.
1474            let deafened = !live_kit.deafened;
1475            live_kit.deafened = deafened;
1476            let should_change_mute = !live_kit.muted_by_user;
1477
1478            self.set_deafened(deafened, cx);
1479
1480            if should_change_mute
1481                && let Some(task) = self.set_mute(deafened, cx) {
1482                    task.detach_and_log_err(cx);
1483                }
1484        }
1485    }
1486
1487    pub fn unshare_screen(&mut self, play_sound: bool, cx: &mut Context<Self>) -> Result<()> {
1488        anyhow::ensure!(!self.status.is_offline(), "room is offline");
1489
1490        let live_kit = self
1491            .live_kit
1492            .as_mut()
1493            .context("live-kit was not initialized")?;
1494        match mem::take(&mut live_kit.screen_track) {
1495            LocalTrack::None => anyhow::bail!("screen was not shared"),
1496            LocalTrack::Pending { .. } => {
1497                cx.notify();
1498                Ok(())
1499            }
1500            LocalTrack::Published {
1501                track_publication, ..
1502            } => {
1503                {
1504                    let local_participant = live_kit.room.local_participant();
1505                    let sid = track_publication.sid();
1506                    cx.spawn(async move |_, cx| local_participant.unpublish_track(sid, cx).await)
1507                        .detach_and_log_err(cx);
1508                    cx.notify();
1509                }
1510
1511                if play_sound {
1512                    Audio::play_sound(Sound::StopScreenshare, cx);
1513                }
1514
1515                Ok(())
1516            }
1517        }
1518    }
1519
1520    fn set_deafened(&mut self, deafened: bool, cx: &mut Context<Self>) -> Option<()> {
1521        {
1522            let live_kit = self.live_kit.as_mut()?;
1523            cx.notify();
1524            for (_, participant) in live_kit.room.remote_participants() {
1525                for (_, publication) in participant.track_publications() {
1526                    if publication.is_audio() {
1527                        publication.set_enabled(!deafened, cx);
1528                    }
1529                }
1530            }
1531        }
1532
1533        None
1534    }
1535
1536    fn set_mute(&mut self, should_mute: bool, cx: &mut Context<Room>) -> Option<Task<Result<()>>> {
1537        let live_kit = self.live_kit.as_mut()?;
1538        cx.notify();
1539
1540        if should_mute {
1541            Audio::play_sound(Sound::Mute, cx);
1542        } else {
1543            Audio::play_sound(Sound::Unmute, cx);
1544        }
1545
1546        match &mut live_kit.microphone_track {
1547            LocalTrack::None => {
1548                if should_mute {
1549                    None
1550                } else {
1551                    Some(self.share_microphone(cx))
1552                }
1553            }
1554            LocalTrack::Pending { .. } => None,
1555            LocalTrack::Published {
1556                track_publication, ..
1557            } => {
1558                let guard = Tokio::handle(cx);
1559                if should_mute {
1560                    track_publication.mute(cx)
1561                } else {
1562                    track_publication.unmute(cx)
1563                }
1564                drop(guard);
1565
1566                None
1567            }
1568        }
1569    }
1570}
1571
1572fn spawn_room_connection(
1573    livekit_connection_info: Option<proto::LiveKitConnectionInfo>,
1574    cx: &mut Context<Room>,
1575) {
1576    if let Some(connection_info) = livekit_connection_info {
1577        cx.spawn(async move |this, cx| {
1578            let (room, mut events) =
1579                livekit::Room::connect(connection_info.server_url, connection_info.token, cx)
1580                    .await?;
1581
1582            this.update(cx, |this, cx| {
1583                let _handle_updates = cx.spawn(async move |this, cx| {
1584                    while let Some(event) = events.next().await {
1585                        if this
1586                            .update(cx, |this, cx| {
1587                                this.livekit_room_updated(event, cx).warn_on_err();
1588                            })
1589                            .is_err()
1590                        {
1591                            break;
1592                        }
1593                    }
1594                });
1595
1596                let muted_by_user = Room::mute_on_join(cx);
1597                this.live_kit = Some(LiveKitRoom {
1598                    room: Rc::new(room),
1599                    screen_track: LocalTrack::None,
1600                    microphone_track: LocalTrack::None,
1601                    next_publish_id: 0,
1602                    muted_by_user,
1603                    deafened: false,
1604                    speaking: false,
1605                    _handle_updates,
1606                });
1607
1608                if !muted_by_user && this.can_use_microphone() {
1609                    this.share_microphone(cx)
1610                } else {
1611                    Task::ready(Ok(()))
1612                }
1613            })?
1614            .await
1615        })
1616        .detach_and_log_err(cx);
1617    }
1618}
1619
1620struct LiveKitRoom {
1621    room: Rc<livekit::Room>,
1622    screen_track: LocalTrack<dyn ScreenCaptureStream>,
1623    microphone_track: LocalTrack<AudioStream>,
1624    /// Tracks whether we're currently in a muted state due to auto-mute from deafening or manual mute performed by user.
1625    muted_by_user: bool,
1626    deafened: bool,
1627    speaking: bool,
1628    next_publish_id: usize,
1629    _handle_updates: Task<()>,
1630}
1631
1632impl LiveKitRoom {
1633    fn stop_publishing(&mut self, cx: &mut Context<Room>) {
1634        let mut tracks_to_unpublish = Vec::new();
1635        if let LocalTrack::Published {
1636            track_publication, ..
1637        } = mem::replace(&mut self.microphone_track, LocalTrack::None)
1638        {
1639            tracks_to_unpublish.push(track_publication.sid());
1640            cx.notify();
1641        }
1642
1643        if let LocalTrack::Published {
1644            track_publication, ..
1645        } = mem::replace(&mut self.screen_track, LocalTrack::None)
1646        {
1647            tracks_to_unpublish.push(track_publication.sid());
1648            cx.notify();
1649        }
1650
1651        let participant = self.room.local_participant();
1652        cx.spawn(async move |_, cx| {
1653            for sid in tracks_to_unpublish {
1654                participant.unpublish_track(sid, cx).await.log_err();
1655            }
1656        })
1657        .detach();
1658    }
1659}
1660
1661enum LocalTrack<Stream: ?Sized> {
1662    None,
1663    Pending {
1664        publish_id: usize,
1665    },
1666    Published {
1667        track_publication: LocalTrackPublication,
1668        _stream: Box<Stream>,
1669    },
1670}
1671
1672impl<T: ?Sized> Default for LocalTrack<T> {
1673    fn default() -> Self {
1674        Self::None
1675    }
1676}
1677
1678#[derive(Copy, Clone, PartialEq, Eq)]
1679pub enum RoomStatus {
1680    Online,
1681    Rejoining,
1682    Offline,
1683}
1684
1685impl RoomStatus {
1686    pub fn is_offline(&self) -> bool {
1687        matches!(self, RoomStatus::Offline)
1688    }
1689
1690    pub fn is_online(&self) -> bool {
1691        matches!(self, RoomStatus::Online)
1692    }
1693}