collab_panel.rs

   1mod channel_modal;
   2mod contact_finder;
   3
   4use self::channel_modal::ChannelModal;
   5use crate::{CollaborationPanelSettings, channel_view::ChannelView};
   6use anyhow::Context as _;
   7use call::ActiveCall;
   8use channel::{Channel, ChannelEvent, ChannelStore};
   9use client::{ChannelId, Client, Contact, User, UserStore};
  10use collections::{HashMap, HashSet};
  11use contact_finder::ContactFinder;
  12use db::kvp::KEY_VALUE_STORE;
  13use editor::{Editor, EditorElement, EditorStyle};
  14use fuzzy::{StringMatch, StringMatchCandidate, match_strings};
  15use gpui::{
  16    AnyElement, App, AsyncWindowContext, Bounds, ClickEvent, ClipboardItem, Context, DismissEvent,
  17    Div, Entity, EventEmitter, FocusHandle, Focusable, FontStyle, InteractiveElement, IntoElement,
  18    KeyContext, ListOffset, ListState, MouseDownEvent, ParentElement, Pixels, Point, PromptLevel,
  19    Render, SharedString, Styled, Subscription, Task, TextStyle, WeakEntity, Window, actions,
  20    anchored, canvas, deferred, div, fill, list, point, prelude::*, px,
  21};
  22use menu::{Cancel, Confirm, SecondaryConfirm, SelectNext, SelectPrevious};
  23use project::{Fs, Project};
  24use rpc::{
  25    ErrorCode, ErrorExt,
  26    proto::{self, ChannelVisibility, PeerId},
  27};
  28use serde::{Deserialize, Serialize};
  29use settings::Settings;
  30use smallvec::SmallVec;
  31use std::{mem, sync::Arc};
  32use theme::{ActiveTheme, ThemeSettings};
  33use ui::{
  34    Avatar, AvatarAvailabilityIndicator, ContextMenu, CopyButton, Facepile, HighlightedLabel,
  35    IconButtonShape, Indicator, ListHeader, ListItem, Tab, Tooltip, prelude::*, tooltip_container,
  36};
  37use util::{ResultExt, TryFutureExt, maybe};
  38use workspace::{
  39    CopyRoomId, Deafen, LeaveCall, MultiWorkspace, Mute, OpenChannelNotes, ScreenShare,
  40    ShareProject, Workspace,
  41    dock::{DockPosition, Panel, PanelEvent},
  42    notifications::{DetachAndPromptErr, NotifyResultExt},
  43};
  44
  45actions!(
  46    collab_panel,
  47    [
  48        /// Toggles focus on the collaboration panel.
  49        ToggleFocus,
  50        /// Removes the selected channel or contact.
  51        Remove,
  52        /// Opens the context menu for the selected item.
  53        Secondary,
  54        /// Collapses the selected channel in the tree view.
  55        CollapseSelectedChannel,
  56        /// Expands the selected channel in the tree view.
  57        ExpandSelectedChannel,
  58        /// Opens the meeting notes for the selected channel in the panel.
  59        ///
  60        /// Use `collab::OpenChannelNotes` to open the channel notes for the current call.
  61        OpenSelectedChannelNotes,
  62        /// Starts moving a channel to a new location.
  63        StartMoveChannel,
  64        /// Moves the selected item to the current location.
  65        MoveSelected,
  66        /// Inserts a space character in the filter input.
  67        InsertSpace,
  68        /// Moves the selected channel up in the list.
  69        MoveChannelUp,
  70        /// Moves the selected channel down in the list.
  71        MoveChannelDown,
  72    ]
  73);
  74
  75#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  76struct ChannelMoveClipboard {
  77    channel_id: ChannelId,
  78}
  79
  80const COLLABORATION_PANEL_KEY: &str = "CollaborationPanel";
  81
  82pub fn init(cx: &mut App) {
  83    cx.observe_new(|workspace: &mut Workspace, _, _| {
  84        workspace.register_action(|workspace, _: &ToggleFocus, window, cx| {
  85            workspace.toggle_panel_focus::<CollabPanel>(window, cx);
  86            if let Some(collab_panel) = workspace.panel::<CollabPanel>(cx) {
  87                collab_panel.update(cx, |panel, cx| {
  88                    panel.filter_editor.update(cx, |editor, cx| {
  89                        if editor.snapshot(window, cx).is_focused() {
  90                            editor.select_all(&Default::default(), window, cx);
  91                        }
  92                    });
  93                })
  94            }
  95        });
  96        workspace.register_action(|_, _: &OpenChannelNotes, window, cx| {
  97            let channel_id = ActiveCall::global(cx)
  98                .read(cx)
  99                .room()
 100                .and_then(|room| room.read(cx).channel_id());
 101
 102            if let Some(channel_id) = channel_id {
 103                let workspace = cx.entity();
 104                window.defer(cx, move |window, cx| {
 105                    ChannelView::open(channel_id, None, workspace, window, cx)
 106                        .detach_and_log_err(cx)
 107                });
 108            }
 109        });
 110        // TODO: make it possible to bind this one to a held key for push to talk?
 111        // how to make "toggle_on_modifiers_press" contextual?
 112        workspace.register_action(|_, _: &Mute, _, cx| title_bar::collab::toggle_mute(cx));
 113        workspace.register_action(|_, _: &Deafen, _, cx| title_bar::collab::toggle_deafen(cx));
 114        workspace.register_action(|_, _: &LeaveCall, window, cx| {
 115            CollabPanel::leave_call(window, cx);
 116        });
 117        workspace.register_action(|workspace, _: &CopyRoomId, window, cx| {
 118            use workspace::notifications::{NotificationId, NotifyTaskExt as _};
 119
 120            struct RoomIdCopiedToast;
 121
 122            if let Some(room) = ActiveCall::global(cx).read(cx).room() {
 123                let romo_id_fut = room.read(cx).room_id();
 124                let workspace_handle = cx.weak_entity();
 125                cx.spawn(async move |workspace, cx| {
 126                    let room_id = romo_id_fut.await.context("Failed to get livekit room")?;
 127                    workspace.update(cx, |workspace, cx| {
 128                        cx.write_to_clipboard(ClipboardItem::new_string(room_id));
 129                        workspace.show_toast(
 130                            workspace::Toast::new(
 131                                NotificationId::unique::<RoomIdCopiedToast>(),
 132                                "Room ID copied to clipboard",
 133                            )
 134                            .autohide(),
 135                            cx,
 136                        );
 137                    })
 138                })
 139                .detach_and_notify_err(workspace_handle, window, cx);
 140            } else {
 141                workspace.show_error(&"There’s no active call; join one first.", cx);
 142            }
 143        });
 144        workspace.register_action(|workspace, _: &ShareProject, window, cx| {
 145            let project = workspace.project().clone();
 146            println!("{project:?}");
 147            window.defer(cx, move |_window, cx| {
 148                ActiveCall::global(cx).update(cx, move |call, cx| {
 149                    if let Some(room) = call.room() {
 150                        println!("{room:?}");
 151                        if room.read(cx).is_sharing_project() {
 152                            call.unshare_project(project, cx).ok();
 153                        } else {
 154                            call.share_project(project, cx).detach_and_log_err(cx);
 155                        }
 156                    }
 157                });
 158            });
 159        });
 160        workspace.register_action(|_, _: &ScreenShare, window, cx| {
 161            let room = ActiveCall::global(cx).read(cx).room().cloned();
 162            if let Some(room) = room {
 163                window.defer(cx, move |_window, cx| {
 164                    room.update(cx, |room, cx| {
 165                        if room.is_sharing_screen() {
 166                            room.unshare_screen(true, cx).ok();
 167                        } else {
 168                            let sources = cx.screen_capture_sources();
 169
 170                            cx.spawn(async move |room, cx| {
 171                                let sources = sources.await??;
 172                                let first = sources.into_iter().next();
 173                                if let Some(first) = first {
 174                                    room.update(cx, |room, cx| room.share_screen(first, cx))?
 175                                        .await
 176                                } else {
 177                                    Ok(())
 178                                }
 179                            })
 180                            .detach_and_log_err(cx);
 181                        };
 182                    });
 183                });
 184            }
 185        });
 186    })
 187    .detach();
 188}
 189
 190#[derive(Debug)]
 191pub enum ChannelEditingState {
 192    Create {
 193        location: Option<ChannelId>,
 194        pending_name: Option<String>,
 195    },
 196    Rename {
 197        location: ChannelId,
 198        pending_name: Option<String>,
 199    },
 200}
 201
 202impl ChannelEditingState {
 203    fn pending_name(&self) -> Option<String> {
 204        match self {
 205            ChannelEditingState::Create { pending_name, .. } => pending_name.clone(),
 206            ChannelEditingState::Rename { pending_name, .. } => pending_name.clone(),
 207        }
 208    }
 209}
 210
 211pub struct CollabPanel {
 212    width: Option<Pixels>,
 213    fs: Arc<dyn Fs>,
 214    focus_handle: FocusHandle,
 215    channel_clipboard: Option<ChannelMoveClipboard>,
 216    pending_serialization: Task<Option<()>>,
 217    context_menu: Option<(Entity<ContextMenu>, Point<Pixels>, Subscription)>,
 218    list_state: ListState,
 219    filter_editor: Entity<Editor>,
 220    channel_name_editor: Entity<Editor>,
 221    channel_editing_state: Option<ChannelEditingState>,
 222    entries: Vec<ListEntry>,
 223    selection: Option<usize>,
 224    channel_store: Entity<ChannelStore>,
 225    user_store: Entity<UserStore>,
 226    client: Arc<Client>,
 227    project: Entity<Project>,
 228    match_candidates: Vec<StringMatchCandidate>,
 229    subscriptions: Vec<Subscription>,
 230    collapsed_sections: Vec<Section>,
 231    collapsed_channels: Vec<ChannelId>,
 232    filter_active_channels: bool,
 233    workspace: WeakEntity<Workspace>,
 234}
 235
 236#[derive(Serialize, Deserialize)]
 237struct SerializedCollabPanel {
 238    width: Option<Pixels>,
 239    collapsed_channels: Option<Vec<u64>>,
 240}
 241
 242#[derive(Clone, Copy, PartialEq, Eq, Debug, PartialOrd, Ord)]
 243enum Section {
 244    ActiveCall,
 245    Channels,
 246    ChannelInvites,
 247    ContactRequests,
 248    Contacts,
 249    Online,
 250    Offline,
 251}
 252
 253#[derive(Clone, Debug)]
 254enum ListEntry {
 255    Header(Section),
 256    CallParticipant {
 257        user: Arc<User>,
 258        peer_id: Option<PeerId>,
 259        is_pending: bool,
 260        role: proto::ChannelRole,
 261    },
 262    ParticipantProject {
 263        project_id: u64,
 264        worktree_root_names: Vec<String>,
 265        host_user_id: u64,
 266        is_last: bool,
 267    },
 268    ParticipantScreen {
 269        peer_id: Option<PeerId>,
 270        is_last: bool,
 271    },
 272    IncomingRequest(Arc<User>),
 273    OutgoingRequest(Arc<User>),
 274    ChannelInvite(Arc<Channel>),
 275    Channel {
 276        channel: Arc<Channel>,
 277        depth: usize,
 278        has_children: bool,
 279        // `None` when the channel is a parent of a matched channel.
 280        string_match: Option<StringMatch>,
 281    },
 282    ChannelNotes {
 283        channel_id: ChannelId,
 284    },
 285    ChannelEditor {
 286        depth: usize,
 287    },
 288    Contact {
 289        contact: Arc<Contact>,
 290        calling: bool,
 291    },
 292    ContactPlaceholder,
 293}
 294
 295impl CollabPanel {
 296    pub fn new(
 297        workspace: &mut Workspace,
 298        window: &mut Window,
 299        cx: &mut Context<Workspace>,
 300    ) -> Entity<Self> {
 301        cx.new(|cx| {
 302            let filter_editor = cx.new(|cx| {
 303                let mut editor = Editor::single_line(window, cx);
 304                editor.set_placeholder_text("Search channels…", window, cx);
 305                editor
 306            });
 307
 308            cx.subscribe(&filter_editor, |this: &mut Self, _, event, cx| {
 309                if let editor::EditorEvent::BufferEdited = event {
 310                    let query = this.filter_editor.read(cx).text(cx);
 311                    if !query.is_empty() {
 312                        this.selection.take();
 313                    }
 314                    this.update_entries(true, cx);
 315                    if !query.is_empty() {
 316                        this.selection = this
 317                            .entries
 318                            .iter()
 319                            .position(|entry| !matches!(entry, ListEntry::Header(_)));
 320                    }
 321                }
 322            })
 323            .detach();
 324
 325            let channel_name_editor = cx.new(|cx| Editor::single_line(window, cx));
 326
 327            cx.subscribe_in(
 328                &channel_name_editor,
 329                window,
 330                |this: &mut Self, _, event, window, cx| {
 331                    if let editor::EditorEvent::Blurred = event {
 332                        if let Some(state) = &this.channel_editing_state
 333                            && state.pending_name().is_some()
 334                        {
 335                            return;
 336                        }
 337                        this.take_editing_state(window, cx);
 338                        this.update_entries(false, cx);
 339                        cx.notify();
 340                    }
 341                },
 342            )
 343            .detach();
 344
 345            let mut this = Self {
 346                width: None,
 347                focus_handle: cx.focus_handle(),
 348                channel_clipboard: None,
 349                fs: workspace.app_state().fs.clone(),
 350                pending_serialization: Task::ready(None),
 351                context_menu: None,
 352                list_state: ListState::new(0, gpui::ListAlignment::Top, px(1000.)),
 353                channel_name_editor,
 354                filter_editor,
 355                entries: Vec::default(),
 356                channel_editing_state: None,
 357                selection: None,
 358                channel_store: ChannelStore::global(cx),
 359                user_store: workspace.user_store().clone(),
 360                project: workspace.project().clone(),
 361                subscriptions: Vec::default(),
 362                match_candidates: Vec::default(),
 363                collapsed_sections: vec![Section::Offline],
 364                collapsed_channels: Vec::default(),
 365                filter_active_channels: false,
 366                workspace: workspace.weak_handle(),
 367                client: workspace.app_state().client.clone(),
 368            };
 369
 370            this.update_entries(false, cx);
 371
 372            let active_call = ActiveCall::global(cx);
 373            this.subscriptions
 374                .push(cx.observe(&this.user_store, |this, _, cx| {
 375                    this.update_entries(true, cx)
 376                }));
 377            this.subscriptions
 378                .push(cx.observe(&this.channel_store, move |this, _, cx| {
 379                    this.update_entries(true, cx)
 380                }));
 381            this.subscriptions
 382                .push(cx.observe(&active_call, |this, _, cx| this.update_entries(true, cx)));
 383            this.subscriptions.push(cx.subscribe_in(
 384                &this.channel_store,
 385                window,
 386                |this, _channel_store, e, window, cx| match e {
 387                    ChannelEvent::ChannelCreated(channel_id)
 388                    | ChannelEvent::ChannelRenamed(channel_id) => {
 389                        if this.take_editing_state(window, cx) {
 390                            this.update_entries(false, cx);
 391                            this.selection = this.entries.iter().position(|entry| {
 392                                if let ListEntry::Channel { channel, .. } = entry {
 393                                    channel.id == *channel_id
 394                                } else {
 395                                    false
 396                                }
 397                            });
 398                        }
 399                    }
 400                },
 401            ));
 402
 403            this
 404        })
 405    }
 406
 407    pub async fn load(
 408        workspace: WeakEntity<Workspace>,
 409        mut cx: AsyncWindowContext,
 410    ) -> anyhow::Result<Entity<Self>> {
 411        let serialized_panel = match workspace
 412            .read_with(&cx, |workspace, _| {
 413                CollabPanel::serialization_key(workspace)
 414            })
 415            .ok()
 416            .flatten()
 417        {
 418            Some(serialization_key) => cx
 419                .background_spawn(async move { KEY_VALUE_STORE.read_kvp(&serialization_key) })
 420                .await
 421                .context("reading collaboration panel from key value store")
 422                .log_err()
 423                .flatten()
 424                .map(|panel| serde_json::from_str::<SerializedCollabPanel>(&panel))
 425                .transpose()
 426                .log_err()
 427                .flatten(),
 428            None => None,
 429        };
 430
 431        workspace.update_in(&mut cx, |workspace, window, cx| {
 432            let panel = CollabPanel::new(workspace, window, cx);
 433            if let Some(serialized_panel) = serialized_panel {
 434                panel.update(cx, |panel, cx| {
 435                    panel.width = serialized_panel.width.map(|w| w.round());
 436                    panel.collapsed_channels = serialized_panel
 437                        .collapsed_channels
 438                        .unwrap_or_else(Vec::new)
 439                        .iter()
 440                        .map(|cid| ChannelId(*cid))
 441                        .collect();
 442                    cx.notify();
 443                });
 444            }
 445            panel
 446        })
 447    }
 448
 449    fn serialization_key(workspace: &Workspace) -> Option<String> {
 450        workspace
 451            .database_id()
 452            .map(|id| i64::from(id).to_string())
 453            .or(workspace.session_id())
 454            .map(|id| format!("{}-{:?}", COLLABORATION_PANEL_KEY, id))
 455    }
 456
 457    fn serialize(&mut self, cx: &mut Context<Self>) {
 458        let Some(serialization_key) = self
 459            .workspace
 460            .read_with(cx, |workspace, _| CollabPanel::serialization_key(workspace))
 461            .ok()
 462            .flatten()
 463        else {
 464            return;
 465        };
 466        let width = self.width;
 467        let collapsed_channels = self.collapsed_channels.clone();
 468        self.pending_serialization = cx.background_spawn(
 469            async move {
 470                KEY_VALUE_STORE
 471                    .write_kvp(
 472                        serialization_key,
 473                        serde_json::to_string(&SerializedCollabPanel {
 474                            width,
 475                            collapsed_channels: Some(
 476                                collapsed_channels.iter().map(|cid| cid.0).collect(),
 477                            ),
 478                        })?,
 479                    )
 480                    .await?;
 481                anyhow::Ok(())
 482            }
 483            .log_err(),
 484        );
 485    }
 486
 487    fn scroll_to_item(&mut self, ix: usize) {
 488        self.list_state.scroll_to_reveal_item(ix)
 489    }
 490
 491    fn update_entries(&mut self, select_same_item: bool, cx: &mut Context<Self>) {
 492        let channel_store = self.channel_store.read(cx);
 493        let user_store = self.user_store.read(cx);
 494        let query = self.filter_editor.read(cx).text(cx);
 495        let fg_executor = cx.foreground_executor();
 496        let executor = cx.background_executor().clone();
 497
 498        let prev_selected_entry = self.selection.and_then(|ix| self.entries.get(ix).cloned());
 499        let old_entries = mem::take(&mut self.entries);
 500        let mut scroll_to_top = false;
 501
 502        if let Some(room) = ActiveCall::global(cx).read(cx).room() {
 503            self.entries.push(ListEntry::Header(Section::ActiveCall));
 504            if !old_entries
 505                .iter()
 506                .any(|entry| matches!(entry, ListEntry::Header(Section::ActiveCall)))
 507            {
 508                scroll_to_top = true;
 509            }
 510
 511            if !self.collapsed_sections.contains(&Section::ActiveCall) {
 512                let room = room.read(cx);
 513
 514                if query.is_empty()
 515                    && let Some(channel_id) = room.channel_id()
 516                {
 517                    self.entries.push(ListEntry::ChannelNotes { channel_id });
 518                }
 519
 520                // Populate the active user.
 521                if let Some(user) = user_store.current_user() {
 522                    self.match_candidates.clear();
 523                    self.match_candidates
 524                        .push(StringMatchCandidate::new(0, &user.github_login));
 525                    let matches = fg_executor.block_on(match_strings(
 526                        &self.match_candidates,
 527                        &query,
 528                        true,
 529                        true,
 530                        usize::MAX,
 531                        &Default::default(),
 532                        executor.clone(),
 533                    ));
 534                    if !matches.is_empty() {
 535                        let user_id = user.id;
 536                        self.entries.push(ListEntry::CallParticipant {
 537                            user,
 538                            peer_id: None,
 539                            is_pending: false,
 540                            role: room.local_participant().role,
 541                        });
 542                        let mut projects = room.local_participant().projects.iter().peekable();
 543                        while let Some(project) = projects.next() {
 544                            self.entries.push(ListEntry::ParticipantProject {
 545                                project_id: project.id,
 546                                worktree_root_names: project.worktree_root_names.clone(),
 547                                host_user_id: user_id,
 548                                is_last: projects.peek().is_none() && !room.is_sharing_screen(),
 549                            });
 550                        }
 551                        if room.is_sharing_screen() {
 552                            self.entries.push(ListEntry::ParticipantScreen {
 553                                peer_id: None,
 554                                is_last: true,
 555                            });
 556                        }
 557                    }
 558                }
 559
 560                // Populate remote participants.
 561                self.match_candidates.clear();
 562                self.match_candidates
 563                    .extend(room.remote_participants().values().map(|participant| {
 564                        StringMatchCandidate::new(
 565                            participant.user.id as usize,
 566                            &participant.user.github_login,
 567                        )
 568                    }));
 569                let mut matches = fg_executor.block_on(match_strings(
 570                    &self.match_candidates,
 571                    &query,
 572                    true,
 573                    true,
 574                    usize::MAX,
 575                    &Default::default(),
 576                    executor.clone(),
 577                ));
 578                matches.sort_by(|a, b| {
 579                    let a_is_guest = room.role_for_user(a.candidate_id as u64)
 580                        == Some(proto::ChannelRole::Guest);
 581                    let b_is_guest = room.role_for_user(b.candidate_id as u64)
 582                        == Some(proto::ChannelRole::Guest);
 583                    a_is_guest
 584                        .cmp(&b_is_guest)
 585                        .then_with(|| a.string.cmp(&b.string))
 586                });
 587                for mat in matches {
 588                    let user_id = mat.candidate_id as u64;
 589                    let participant = &room.remote_participants()[&user_id];
 590                    self.entries.push(ListEntry::CallParticipant {
 591                        user: participant.user.clone(),
 592                        peer_id: Some(participant.peer_id),
 593                        is_pending: false,
 594                        role: participant.role,
 595                    });
 596                    let mut projects = participant.projects.iter().peekable();
 597                    while let Some(project) = projects.next() {
 598                        self.entries.push(ListEntry::ParticipantProject {
 599                            project_id: project.id,
 600                            worktree_root_names: project.worktree_root_names.clone(),
 601                            host_user_id: participant.user.id,
 602                            is_last: projects.peek().is_none() && !participant.has_video_tracks(),
 603                        });
 604                    }
 605                    if participant.has_video_tracks() {
 606                        self.entries.push(ListEntry::ParticipantScreen {
 607                            peer_id: Some(participant.peer_id),
 608                            is_last: true,
 609                        });
 610                    }
 611                }
 612
 613                // Populate pending participants.
 614                self.match_candidates.clear();
 615                self.match_candidates
 616                    .extend(room.pending_participants().iter().enumerate().map(
 617                        |(id, participant)| {
 618                            StringMatchCandidate::new(id, &participant.github_login)
 619                        },
 620                    ));
 621                let matches = fg_executor.block_on(match_strings(
 622                    &self.match_candidates,
 623                    &query,
 624                    true,
 625                    true,
 626                    usize::MAX,
 627                    &Default::default(),
 628                    executor.clone(),
 629                ));
 630                self.entries
 631                    .extend(matches.iter().map(|mat| ListEntry::CallParticipant {
 632                        user: room.pending_participants()[mat.candidate_id].clone(),
 633                        peer_id: None,
 634                        is_pending: true,
 635                        role: proto::ChannelRole::Member,
 636                    }));
 637            }
 638        }
 639
 640        let mut request_entries = Vec::new();
 641
 642        self.entries.push(ListEntry::Header(Section::Channels));
 643
 644        if channel_store.channel_count() > 0 || self.channel_editing_state.is_some() {
 645            self.match_candidates.clear();
 646            self.match_candidates.extend(
 647                channel_store
 648                    .ordered_channels()
 649                    .enumerate()
 650                    .map(|(ix, (_, channel))| StringMatchCandidate::new(ix, &channel.name)),
 651            );
 652            let mut channels = channel_store
 653                .ordered_channels()
 654                .map(|(_, chan)| chan)
 655                .collect::<Vec<_>>();
 656            let matches = fg_executor.block_on(match_strings(
 657                &self.match_candidates,
 658                &query,
 659                true,
 660                true,
 661                usize::MAX,
 662                &Default::default(),
 663                executor.clone(),
 664            ));
 665
 666            let matches_by_id: HashMap<_, _> = matches
 667                .iter()
 668                .map(|mat| (channels[mat.candidate_id].id, mat.clone()))
 669                .collect();
 670
 671            let channel_ids_of_matches_or_parents: HashSet<_> = matches
 672                .iter()
 673                .flat_map(|mat| {
 674                    let match_channel = channels[mat.candidate_id];
 675
 676                    match_channel
 677                        .parent_path
 678                        .iter()
 679                        .copied()
 680                        .chain(Some(match_channel.id))
 681                })
 682                .collect();
 683
 684            channels.retain(|chan| channel_ids_of_matches_or_parents.contains(&chan.id));
 685
 686            if self.filter_active_channels {
 687                let active_channel_ids_or_ancestors: HashSet<_> = channel_store
 688                    .ordered_channels()
 689                    .map(|(_, channel)| channel)
 690                    .filter(|channel| !channel_store.channel_participants(channel.id).is_empty())
 691                    .flat_map(|channel| channel.parent_path.iter().copied().chain(Some(channel.id)))
 692                    .collect();
 693                channels.retain(|channel| active_channel_ids_or_ancestors.contains(&channel.id));
 694            }
 695
 696            if let Some(state) = &self.channel_editing_state
 697                && matches!(state, ChannelEditingState::Create { location: None, .. })
 698            {
 699                self.entries.push(ListEntry::ChannelEditor { depth: 0 });
 700            }
 701
 702            let should_respect_collapse = query.is_empty() && !self.filter_active_channels;
 703            let mut collapse_depth = None;
 704
 705            for (idx, channel) in channels.into_iter().enumerate() {
 706                let depth = channel.parent_path.len();
 707
 708                if should_respect_collapse {
 709                    if collapse_depth.is_none() && self.is_channel_collapsed(channel.id) {
 710                        collapse_depth = Some(depth);
 711                    } else if let Some(collapsed_depth) = collapse_depth {
 712                        if depth > collapsed_depth {
 713                            continue;
 714                        }
 715                        if self.is_channel_collapsed(channel.id) {
 716                            collapse_depth = Some(depth);
 717                        } else {
 718                            collapse_depth = None;
 719                        }
 720                    }
 721                }
 722
 723                let has_children = channel_store
 724                    .channel_at_index(idx + 1)
 725                    .is_some_and(|next_channel| next_channel.parent_path.ends_with(&[channel.id]));
 726
 727                match &self.channel_editing_state {
 728                    Some(ChannelEditingState::Create {
 729                        location: parent_id,
 730                        ..
 731                    }) if *parent_id == Some(channel.id) => {
 732                        self.entries.push(ListEntry::Channel {
 733                            channel: channel.clone(),
 734                            depth,
 735                            has_children: false,
 736                            string_match: matches_by_id.get(&channel.id).map(|mat| (*mat).clone()),
 737                        });
 738                        self.entries
 739                            .push(ListEntry::ChannelEditor { depth: depth + 1 });
 740                    }
 741                    Some(ChannelEditingState::Rename {
 742                        location: parent_id,
 743                        ..
 744                    }) if parent_id == &channel.id => {
 745                        self.entries.push(ListEntry::ChannelEditor { depth });
 746                    }
 747                    _ => {
 748                        self.entries.push(ListEntry::Channel {
 749                            channel: channel.clone(),
 750                            depth,
 751                            has_children,
 752                            string_match: matches_by_id.get(&channel.id).map(|mat| (*mat).clone()),
 753                        });
 754                    }
 755                }
 756            }
 757        }
 758
 759        let channel_invites = channel_store.channel_invitations();
 760        if !channel_invites.is_empty() {
 761            self.match_candidates.clear();
 762            self.match_candidates.extend(
 763                channel_invites
 764                    .iter()
 765                    .enumerate()
 766                    .map(|(ix, channel)| StringMatchCandidate::new(ix, &channel.name)),
 767            );
 768            let matches = fg_executor.block_on(match_strings(
 769                &self.match_candidates,
 770                &query,
 771                true,
 772                true,
 773                usize::MAX,
 774                &Default::default(),
 775                executor.clone(),
 776            ));
 777            request_entries.extend(
 778                matches
 779                    .iter()
 780                    .map(|mat| ListEntry::ChannelInvite(channel_invites[mat.candidate_id].clone())),
 781            );
 782
 783            if !request_entries.is_empty() {
 784                self.entries
 785                    .push(ListEntry::Header(Section::ChannelInvites));
 786                if !self.collapsed_sections.contains(&Section::ChannelInvites) {
 787                    self.entries.append(&mut request_entries);
 788                }
 789            }
 790        }
 791
 792        self.entries.push(ListEntry::Header(Section::Contacts));
 793
 794        request_entries.clear();
 795        let incoming = user_store.incoming_contact_requests();
 796        if !incoming.is_empty() {
 797            self.match_candidates.clear();
 798            self.match_candidates.extend(
 799                incoming
 800                    .iter()
 801                    .enumerate()
 802                    .map(|(ix, user)| StringMatchCandidate::new(ix, &user.github_login)),
 803            );
 804            let matches = fg_executor.block_on(match_strings(
 805                &self.match_candidates,
 806                &query,
 807                true,
 808                true,
 809                usize::MAX,
 810                &Default::default(),
 811                executor.clone(),
 812            ));
 813            request_entries.extend(
 814                matches
 815                    .iter()
 816                    .map(|mat| ListEntry::IncomingRequest(incoming[mat.candidate_id].clone())),
 817            );
 818        }
 819
 820        let outgoing = user_store.outgoing_contact_requests();
 821        if !outgoing.is_empty() {
 822            self.match_candidates.clear();
 823            self.match_candidates.extend(
 824                outgoing
 825                    .iter()
 826                    .enumerate()
 827                    .map(|(ix, user)| StringMatchCandidate::new(ix, &user.github_login)),
 828            );
 829            let matches = fg_executor.block_on(match_strings(
 830                &self.match_candidates,
 831                &query,
 832                true,
 833                true,
 834                usize::MAX,
 835                &Default::default(),
 836                executor.clone(),
 837            ));
 838            request_entries.extend(
 839                matches
 840                    .iter()
 841                    .map(|mat| ListEntry::OutgoingRequest(outgoing[mat.candidate_id].clone())),
 842            );
 843        }
 844
 845        if !request_entries.is_empty() {
 846            self.entries
 847                .push(ListEntry::Header(Section::ContactRequests));
 848            if !self.collapsed_sections.contains(&Section::ContactRequests) {
 849                self.entries.append(&mut request_entries);
 850            }
 851        }
 852
 853        let contacts = user_store.contacts();
 854        if !contacts.is_empty() {
 855            self.match_candidates.clear();
 856            self.match_candidates.extend(
 857                contacts
 858                    .iter()
 859                    .enumerate()
 860                    .map(|(ix, contact)| StringMatchCandidate::new(ix, &contact.user.github_login)),
 861            );
 862
 863            let matches = fg_executor.block_on(match_strings(
 864                &self.match_candidates,
 865                &query,
 866                true,
 867                true,
 868                usize::MAX,
 869                &Default::default(),
 870                executor,
 871            ));
 872
 873            let (online_contacts, offline_contacts) = matches
 874                .iter()
 875                .partition::<Vec<_>, _>(|mat| contacts[mat.candidate_id].online);
 876
 877            for (matches, section) in [
 878                (online_contacts, Section::Online),
 879                (offline_contacts, Section::Offline),
 880            ] {
 881                if !matches.is_empty() {
 882                    self.entries.push(ListEntry::Header(section));
 883                    if !self.collapsed_sections.contains(&section) {
 884                        let active_call = &ActiveCall::global(cx).read(cx);
 885                        for mat in matches {
 886                            let contact = &contacts[mat.candidate_id];
 887                            self.entries.push(ListEntry::Contact {
 888                                contact: contact.clone(),
 889                                calling: active_call.pending_invites().contains(&contact.user.id),
 890                            });
 891                        }
 892                    }
 893                }
 894            }
 895        }
 896
 897        if incoming.is_empty() && outgoing.is_empty() && contacts.is_empty() {
 898            self.entries.push(ListEntry::ContactPlaceholder);
 899        }
 900
 901        if select_same_item {
 902            if let Some(prev_selected_entry) = prev_selected_entry {
 903                self.selection.take();
 904                for (ix, entry) in self.entries.iter().enumerate() {
 905                    if *entry == prev_selected_entry {
 906                        self.selection = Some(ix);
 907                        break;
 908                    }
 909                }
 910            }
 911        } else {
 912            self.selection = self.selection.and_then(|prev_selection| {
 913                if self.entries.is_empty() {
 914                    None
 915                } else {
 916                    Some(prev_selection.min(self.entries.len() - 1))
 917                }
 918            });
 919        }
 920
 921        let old_scroll_top = self.list_state.logical_scroll_top();
 922        self.list_state.reset(self.entries.len());
 923
 924        if scroll_to_top {
 925            self.list_state.scroll_to(ListOffset::default());
 926        } else {
 927            // Attempt to maintain the same scroll position.
 928            if let Some(old_top_entry) = old_entries.get(old_scroll_top.item_ix) {
 929                let new_scroll_top = self
 930                    .entries
 931                    .iter()
 932                    .position(|entry| entry == old_top_entry)
 933                    .map(|item_ix| ListOffset {
 934                        item_ix,
 935                        offset_in_item: old_scroll_top.offset_in_item,
 936                    })
 937                    .or_else(|| {
 938                        let entry_after_old_top = old_entries.get(old_scroll_top.item_ix + 1)?;
 939                        let item_ix = self
 940                            .entries
 941                            .iter()
 942                            .position(|entry| entry == entry_after_old_top)?;
 943                        Some(ListOffset {
 944                            item_ix,
 945                            offset_in_item: Pixels::ZERO,
 946                        })
 947                    })
 948                    .or_else(|| {
 949                        let entry_before_old_top =
 950                            old_entries.get(old_scroll_top.item_ix.saturating_sub(1))?;
 951                        let item_ix = self
 952                            .entries
 953                            .iter()
 954                            .position(|entry| entry == entry_before_old_top)?;
 955                        Some(ListOffset {
 956                            item_ix,
 957                            offset_in_item: Pixels::ZERO,
 958                        })
 959                    });
 960
 961                self.list_state
 962                    .scroll_to(new_scroll_top.unwrap_or(old_scroll_top));
 963            }
 964        }
 965
 966        cx.notify();
 967    }
 968
 969    fn render_call_participant(
 970        &self,
 971        user: &Arc<User>,
 972        peer_id: Option<PeerId>,
 973        is_pending: bool,
 974        role: proto::ChannelRole,
 975        is_selected: bool,
 976        cx: &mut Context<Self>,
 977    ) -> ListItem {
 978        let user_id = user.id;
 979        let is_current_user =
 980            self.user_store.read(cx).current_user().map(|user| user.id) == Some(user_id);
 981        let tooltip = format!("Follow {}", user.github_login);
 982
 983        let is_call_admin = ActiveCall::global(cx).read(cx).room().is_some_and(|room| {
 984            room.read(cx).local_participant().role == proto::ChannelRole::Admin
 985        });
 986
 987        ListItem::new(user.github_login.clone())
 988            .start_slot(Avatar::new(user.avatar_uri.clone()))
 989            .child(render_participant_name_and_handle(user))
 990            .toggle_state(is_selected)
 991            .end_slot(if is_pending {
 992                Label::new("Calling").color(Color::Muted).into_any_element()
 993            } else if is_current_user {
 994                IconButton::new("leave-call", IconName::Exit)
 995                    .style(ButtonStyle::Subtle)
 996                    .on_click(move |_, window, cx| Self::leave_call(window, cx))
 997                    .tooltip(Tooltip::text("Leave Call"))
 998                    .into_any_element()
 999            } else if role == proto::ChannelRole::Guest {
1000                Label::new("Guest").color(Color::Muted).into_any_element()
1001            } else if role == proto::ChannelRole::Talker {
1002                Label::new("Mic only")
1003                    .color(Color::Muted)
1004                    .into_any_element()
1005            } else {
1006                div().into_any_element()
1007            })
1008            .when_some(peer_id, |el, peer_id| {
1009                if role == proto::ChannelRole::Guest {
1010                    return el;
1011                }
1012                el.tooltip(Tooltip::text(tooltip.clone()))
1013                    .on_click(cx.listener(move |this, _, window, cx| {
1014                        this.workspace
1015                            .update(cx, |workspace, cx| workspace.follow(peer_id, window, cx))
1016                            .ok();
1017                    }))
1018            })
1019            .when(is_call_admin, |el| {
1020                el.on_secondary_mouse_down(cx.listener(
1021                    move |this, event: &MouseDownEvent, window, cx| {
1022                        this.deploy_participant_context_menu(
1023                            event.position,
1024                            user_id,
1025                            role,
1026                            window,
1027                            cx,
1028                        )
1029                    },
1030                ))
1031            })
1032    }
1033
1034    fn render_participant_project(
1035        &self,
1036        project_id: u64,
1037        worktree_root_names: &[String],
1038        host_user_id: u64,
1039        is_last: bool,
1040        is_selected: bool,
1041        window: &mut Window,
1042        cx: &mut Context<Self>,
1043    ) -> impl IntoElement {
1044        let project_name: SharedString = if worktree_root_names.is_empty() {
1045            "untitled".to_string()
1046        } else {
1047            worktree_root_names.join(", ")
1048        }
1049        .into();
1050
1051        ListItem::new(project_id as usize)
1052            .toggle_state(is_selected)
1053            .on_click(cx.listener(move |this, _, window, cx| {
1054                this.workspace
1055                    .update(cx, |workspace, cx| {
1056                        let app_state = workspace.app_state().clone();
1057                        workspace::join_in_room_project(project_id, host_user_id, app_state, cx)
1058                            .detach_and_prompt_err(
1059                                "Failed to join project",
1060                                window,
1061                                cx,
1062                                |_, _, _| None,
1063                            );
1064                    })
1065                    .ok();
1066            }))
1067            .start_slot(
1068                h_flex()
1069                    .gap_1()
1070                    .child(render_tree_branch(is_last, false, window, cx))
1071                    .child(IconButton::new(0, IconName::Folder)),
1072            )
1073            .child(Label::new(project_name.clone()))
1074            .tooltip(Tooltip::text(format!("Open {}", project_name)))
1075    }
1076
1077    fn render_participant_screen(
1078        &self,
1079        peer_id: Option<PeerId>,
1080        is_last: bool,
1081        is_selected: bool,
1082        window: &mut Window,
1083        cx: &mut Context<Self>,
1084    ) -> impl IntoElement {
1085        let id = peer_id.map_or(usize::MAX, |id| id.as_u64() as usize);
1086
1087        ListItem::new(("screen", id))
1088            .toggle_state(is_selected)
1089            .start_slot(
1090                h_flex()
1091                    .gap_1()
1092                    .child(render_tree_branch(is_last, false, window, cx))
1093                    .child(IconButton::new(0, IconName::Screen)),
1094            )
1095            .child(Label::new("Screen"))
1096            .when_some(peer_id, |this, _| {
1097                this.on_click(cx.listener(move |this, _, window, cx| {
1098                    this.workspace
1099                        .update(cx, |workspace, cx| {
1100                            workspace.open_shared_screen(peer_id.unwrap(), window, cx)
1101                        })
1102                        .ok();
1103                }))
1104                .tooltip(Tooltip::text("Open shared screen"))
1105            })
1106    }
1107
1108    fn take_editing_state(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
1109        if self.channel_editing_state.take().is_some() {
1110            self.channel_name_editor.update(cx, |editor, cx| {
1111                editor.set_text("", window, cx);
1112            });
1113            true
1114        } else {
1115            false
1116        }
1117    }
1118
1119    fn render_channel_notes(
1120        &self,
1121        channel_id: ChannelId,
1122        is_selected: bool,
1123        window: &mut Window,
1124        cx: &mut Context<Self>,
1125    ) -> impl IntoElement {
1126        let channel_store = self.channel_store.read(cx);
1127        let has_channel_buffer_changed = channel_store.has_channel_buffer_changed(channel_id);
1128        ListItem::new("channel-notes")
1129            .toggle_state(is_selected)
1130            .on_click(cx.listener(move |this, _, window, cx| {
1131                this.open_channel_notes(channel_id, window, cx);
1132            }))
1133            .start_slot(
1134                h_flex()
1135                    .relative()
1136                    .gap_1()
1137                    .child(render_tree_branch(false, true, window, cx))
1138                    .child(IconButton::new(0, IconName::File))
1139                    .children(has_channel_buffer_changed.then(|| {
1140                        div()
1141                            .w_1p5()
1142                            .absolute()
1143                            .right(px(2.))
1144                            .top(px(2.))
1145                            .child(Indicator::dot().color(Color::Info))
1146                    })),
1147            )
1148            .child(Label::new("notes"))
1149            .tooltip(Tooltip::text("Open Channel Notes"))
1150    }
1151
1152    fn has_subchannels(&self, ix: usize) -> bool {
1153        self.entries.get(ix).is_some_and(|entry| {
1154            if let ListEntry::Channel { has_children, .. } = entry {
1155                *has_children
1156            } else {
1157                false
1158            }
1159        })
1160    }
1161
1162    fn deploy_participant_context_menu(
1163        &mut self,
1164        position: Point<Pixels>,
1165        user_id: u64,
1166        role: proto::ChannelRole,
1167        window: &mut Window,
1168        cx: &mut Context<Self>,
1169    ) {
1170        let this = cx.entity();
1171        if !(role == proto::ChannelRole::Guest
1172            || role == proto::ChannelRole::Talker
1173            || role == proto::ChannelRole::Member)
1174        {
1175            return;
1176        }
1177
1178        let context_menu = ContextMenu::build(window, cx, |mut context_menu, window, _| {
1179            if role == proto::ChannelRole::Guest {
1180                context_menu = context_menu.entry(
1181                    "Grant Mic Access",
1182                    None,
1183                    window.handler_for(&this, move |_, window, cx| {
1184                        ActiveCall::global(cx)
1185                            .update(cx, |call, cx| {
1186                                let Some(room) = call.room() else {
1187                                    return Task::ready(Ok(()));
1188                                };
1189                                room.update(cx, |room, cx| {
1190                                    room.set_participant_role(
1191                                        user_id,
1192                                        proto::ChannelRole::Talker,
1193                                        cx,
1194                                    )
1195                                })
1196                            })
1197                            .detach_and_prompt_err(
1198                                "Failed to grant mic access",
1199                                window,
1200                                cx,
1201                                |_, _, _| None,
1202                            )
1203                    }),
1204                );
1205            }
1206            if role == proto::ChannelRole::Guest || role == proto::ChannelRole::Talker {
1207                context_menu = context_menu.entry(
1208                    "Grant Write Access",
1209                    None,
1210                    window.handler_for(&this, move |_, window, cx| {
1211                        ActiveCall::global(cx)
1212                            .update(cx, |call, cx| {
1213                                let Some(room) = call.room() else {
1214                                    return Task::ready(Ok(()));
1215                                };
1216                                room.update(cx, |room, cx| {
1217                                    room.set_participant_role(
1218                                        user_id,
1219                                        proto::ChannelRole::Member,
1220                                        cx,
1221                                    )
1222                                })
1223                            })
1224                            .detach_and_prompt_err("Failed to grant write access", window, cx, |e, _, _| {
1225                                match e.error_code() {
1226                                    ErrorCode::NeedsCla => Some("This user has not yet signed the CLA at https://zed.dev/cla.".into()),
1227                                    _ => None,
1228                                }
1229                            })
1230                    }),
1231                );
1232            }
1233            if role == proto::ChannelRole::Member || role == proto::ChannelRole::Talker {
1234                let label = if role == proto::ChannelRole::Talker {
1235                    "Mute"
1236                } else {
1237                    "Revoke Access"
1238                };
1239                context_menu = context_menu.entry(
1240                    label,
1241                    None,
1242                    window.handler_for(&this, move |_, window, cx| {
1243                        ActiveCall::global(cx)
1244                            .update(cx, |call, cx| {
1245                                let Some(room) = call.room() else {
1246                                    return Task::ready(Ok(()));
1247                                };
1248                                room.update(cx, |room, cx| {
1249                                    room.set_participant_role(
1250                                        user_id,
1251                                        proto::ChannelRole::Guest,
1252                                        cx,
1253                                    )
1254                                })
1255                            })
1256                            .detach_and_prompt_err(
1257                                "Failed to revoke access",
1258                                window,
1259                                cx,
1260                                |_, _, _| None,
1261                            )
1262                    }),
1263                );
1264            }
1265
1266            context_menu
1267        });
1268
1269        window.focus(&context_menu.focus_handle(cx), cx);
1270        let subscription = cx.subscribe_in(
1271            &context_menu,
1272            window,
1273            |this, _, _: &DismissEvent, window, cx| {
1274                if this.context_menu.as_ref().is_some_and(|context_menu| {
1275                    context_menu.0.focus_handle(cx).contains_focused(window, cx)
1276                }) {
1277                    cx.focus_self(window);
1278                }
1279                this.context_menu.take();
1280                cx.notify();
1281            },
1282        );
1283        self.context_menu = Some((context_menu, position, subscription));
1284    }
1285
1286    fn deploy_channel_context_menu(
1287        &mut self,
1288        position: Point<Pixels>,
1289        channel_id: ChannelId,
1290        ix: usize,
1291        window: &mut Window,
1292        cx: &mut Context<Self>,
1293    ) {
1294        let clipboard_channel_name = self.channel_clipboard.as_ref().and_then(|clipboard| {
1295            self.channel_store
1296                .read(cx)
1297                .channel_for_id(clipboard.channel_id)
1298                .map(|channel| channel.name.clone())
1299        });
1300        let this = cx.entity();
1301
1302        let context_menu = ContextMenu::build(window, cx, |mut context_menu, window, cx| {
1303            if self.has_subchannels(ix) {
1304                let expand_action_name = if self.is_channel_collapsed(channel_id) {
1305                    "Expand Subchannels"
1306                } else {
1307                    "Collapse Subchannels"
1308                };
1309                context_menu = context_menu.entry(
1310                    expand_action_name,
1311                    None,
1312                    window.handler_for(&this, move |this, window, cx| {
1313                        this.toggle_channel_collapsed(channel_id, window, cx)
1314                    }),
1315                );
1316            }
1317
1318            context_menu = context_menu
1319                .entry(
1320                    "Open Notes",
1321                    None,
1322                    window.handler_for(&this, move |this, window, cx| {
1323                        this.open_channel_notes(channel_id, window, cx)
1324                    }),
1325                )
1326                .entry(
1327                    "Copy Channel Link",
1328                    None,
1329                    window.handler_for(&this, move |this, _, cx| {
1330                        this.copy_channel_link(channel_id, cx)
1331                    }),
1332                )
1333                .entry(
1334                    "Copy Channel Notes Link",
1335                    None,
1336                    window.handler_for(&this, move |this, _, cx| {
1337                        this.copy_channel_notes_link(channel_id, cx)
1338                    }),
1339                );
1340
1341            let mut has_destructive_actions = false;
1342            if self.channel_store.read(cx).is_channel_admin(channel_id) {
1343                has_destructive_actions = true;
1344                context_menu = context_menu
1345                    .separator()
1346                    .entry(
1347                        "New Subchannel",
1348                        None,
1349                        window.handler_for(&this, move |this, window, cx| {
1350                            this.new_subchannel(channel_id, window, cx)
1351                        }),
1352                    )
1353                    .entry(
1354                        "Rename",
1355                        Some(Box::new(SecondaryConfirm)),
1356                        window.handler_for(&this, move |this, window, cx| {
1357                            this.rename_channel(channel_id, window, cx)
1358                        }),
1359                    );
1360
1361                if let Some(channel_name) = clipboard_channel_name {
1362                    context_menu = context_menu.separator().entry(
1363                        format!("Move '#{}' here", channel_name),
1364                        None,
1365                        window.handler_for(&this, move |this, window, cx| {
1366                            this.move_channel_on_clipboard(channel_id, window, cx)
1367                        }),
1368                    );
1369                }
1370
1371                if self.channel_store.read(cx).is_root_channel(channel_id) {
1372                    context_menu = context_menu.separator().entry(
1373                        "Manage Members",
1374                        None,
1375                        window.handler_for(&this, move |this, window, cx| {
1376                            this.manage_members(channel_id, window, cx)
1377                        }),
1378                    )
1379                } else {
1380                    context_menu = context_menu.entry(
1381                        "Move this channel",
1382                        None,
1383                        window.handler_for(&this, move |this, window, cx| {
1384                            this.start_move_channel(channel_id, window, cx)
1385                        }),
1386                    );
1387                    if self.channel_store.read(cx).is_public_channel(channel_id) {
1388                        context_menu = context_menu.separator().entry(
1389                            "Make Channel Private",
1390                            None,
1391                            window.handler_for(&this, move |this, window, cx| {
1392                                this.set_channel_visibility(
1393                                    channel_id,
1394                                    ChannelVisibility::Members,
1395                                    window,
1396                                    cx,
1397                                )
1398                            }),
1399                        )
1400                    } else {
1401                        context_menu = context_menu.separator().entry(
1402                            "Make Channel Public",
1403                            None,
1404                            window.handler_for(&this, move |this, window, cx| {
1405                                this.set_channel_visibility(
1406                                    channel_id,
1407                                    ChannelVisibility::Public,
1408                                    window,
1409                                    cx,
1410                                )
1411                            }),
1412                        )
1413                    }
1414                }
1415
1416                context_menu = context_menu.entry(
1417                    "Delete",
1418                    None,
1419                    window.handler_for(&this, move |this, window, cx| {
1420                        this.remove_channel(channel_id, window, cx)
1421                    }),
1422                );
1423            }
1424
1425            if self.channel_store.read(cx).is_root_channel(channel_id) {
1426                if !has_destructive_actions {
1427                    context_menu = context_menu.separator()
1428                }
1429                context_menu = context_menu.entry(
1430                    "Leave Channel",
1431                    None,
1432                    window.handler_for(&this, move |this, window, cx| {
1433                        this.leave_channel(channel_id, window, cx)
1434                    }),
1435                );
1436            }
1437
1438            context_menu
1439        });
1440
1441        window.focus(&context_menu.focus_handle(cx), cx);
1442        let subscription = cx.subscribe_in(
1443            &context_menu,
1444            window,
1445            |this, _, _: &DismissEvent, window, cx| {
1446                if this.context_menu.as_ref().is_some_and(|context_menu| {
1447                    context_menu.0.focus_handle(cx).contains_focused(window, cx)
1448                }) {
1449                    cx.focus_self(window);
1450                }
1451                this.context_menu.take();
1452                cx.notify();
1453            },
1454        );
1455        self.context_menu = Some((context_menu, position, subscription));
1456
1457        cx.notify();
1458    }
1459
1460    fn deploy_contact_context_menu(
1461        &mut self,
1462        position: Point<Pixels>,
1463        contact: Arc<Contact>,
1464        window: &mut Window,
1465        cx: &mut Context<Self>,
1466    ) {
1467        let this = cx.entity();
1468        let in_room = ActiveCall::global(cx).read(cx).room().is_some();
1469
1470        let context_menu = ContextMenu::build(window, cx, |mut context_menu, _, _| {
1471            let user_id = contact.user.id;
1472
1473            if contact.online && !contact.busy {
1474                let label = if in_room {
1475                    format!("Invite {} to join", contact.user.github_login)
1476                } else {
1477                    format!("Call {}", contact.user.github_login)
1478                };
1479                context_menu = context_menu.entry(label, None, {
1480                    let this = this.clone();
1481                    move |window, cx| {
1482                        this.update(cx, |this, cx| {
1483                            this.call(user_id, window, cx);
1484                        });
1485                    }
1486                });
1487            }
1488
1489            context_menu.entry("Remove Contact", None, {
1490                let this = this.clone();
1491                move |window, cx| {
1492                    this.update(cx, |this, cx| {
1493                        this.remove_contact(
1494                            contact.user.id,
1495                            &contact.user.github_login,
1496                            window,
1497                            cx,
1498                        );
1499                    });
1500                }
1501            })
1502        });
1503
1504        window.focus(&context_menu.focus_handle(cx), cx);
1505        let subscription = cx.subscribe_in(
1506            &context_menu,
1507            window,
1508            |this, _, _: &DismissEvent, window, cx| {
1509                if this.context_menu.as_ref().is_some_and(|context_menu| {
1510                    context_menu.0.focus_handle(cx).contains_focused(window, cx)
1511                }) {
1512                    cx.focus_self(window);
1513                }
1514                this.context_menu.take();
1515                cx.notify();
1516            },
1517        );
1518        self.context_menu = Some((context_menu, position, subscription));
1519
1520        cx.notify();
1521    }
1522
1523    fn reset_filter_editor_text(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
1524        self.filter_editor.update(cx, |editor, cx| {
1525            if editor.buffer().read(cx).len(cx).0 > 0 {
1526                editor.set_text("", window, cx);
1527                true
1528            } else {
1529                false
1530            }
1531        })
1532    }
1533
1534    fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
1535        if cx.stop_active_drag(window) {
1536            return;
1537        } else if self.take_editing_state(window, cx) {
1538            window.focus(&self.filter_editor.focus_handle(cx), cx);
1539        } else if !self.reset_filter_editor_text(window, cx) {
1540            self.focus_handle.focus(window, cx);
1541        }
1542
1543        if self.context_menu.is_some() {
1544            self.context_menu.take();
1545            cx.notify();
1546        }
1547
1548        self.update_entries(false, cx);
1549    }
1550
1551    fn select_next(&mut self, _: &SelectNext, _: &mut Window, cx: &mut Context<Self>) {
1552        let ix = self.selection.map_or(0, |ix| ix + 1);
1553        if ix < self.entries.len() {
1554            self.selection = Some(ix);
1555        }
1556
1557        if let Some(ix) = self.selection {
1558            self.scroll_to_item(ix)
1559        }
1560        cx.notify();
1561    }
1562
1563    fn select_previous(&mut self, _: &SelectPrevious, _: &mut Window, cx: &mut Context<Self>) {
1564        let ix = self.selection.take().unwrap_or(0);
1565        if ix > 0 {
1566            self.selection = Some(ix - 1);
1567        }
1568
1569        if let Some(ix) = self.selection {
1570            self.scroll_to_item(ix)
1571        }
1572        cx.notify();
1573    }
1574
1575    fn confirm(&mut self, _: &Confirm, window: &mut Window, cx: &mut Context<Self>) {
1576        if self.confirm_channel_edit(window, cx) {
1577            return;
1578        }
1579
1580        if let Some(selection) = self.selection
1581            && let Some(entry) = self.entries.get(selection)
1582        {
1583            match entry {
1584                ListEntry::Header(section) => match section {
1585                    Section::ActiveCall => Self::leave_call(window, cx),
1586                    Section::Channels => self.new_root_channel(window, cx),
1587                    Section::Contacts => self.toggle_contact_finder(window, cx),
1588                    Section::ContactRequests
1589                    | Section::Online
1590                    | Section::Offline
1591                    | Section::ChannelInvites => {
1592                        self.toggle_section_expanded(*section, cx);
1593                    }
1594                },
1595                ListEntry::Contact { contact, calling } => {
1596                    if contact.online && !contact.busy && !calling {
1597                        self.call(contact.user.id, window, cx);
1598                    }
1599                }
1600                ListEntry::ParticipantProject {
1601                    project_id,
1602                    host_user_id,
1603                    ..
1604                } => {
1605                    if let Some(workspace) = self.workspace.upgrade() {
1606                        let app_state = workspace.read(cx).app_state().clone();
1607                        workspace::join_in_room_project(*project_id, *host_user_id, app_state, cx)
1608                            .detach_and_prompt_err(
1609                                "Failed to join project",
1610                                window,
1611                                cx,
1612                                |_, _, _| None,
1613                            );
1614                    }
1615                }
1616                ListEntry::ParticipantScreen { peer_id, .. } => {
1617                    let Some(peer_id) = peer_id else {
1618                        return;
1619                    };
1620                    if let Some(workspace) = self.workspace.upgrade() {
1621                        workspace.update(cx, |workspace, cx| {
1622                            workspace.open_shared_screen(*peer_id, window, cx)
1623                        });
1624                    }
1625                }
1626                ListEntry::Channel { channel, .. } => {
1627                    let is_active = maybe!({
1628                        let call_channel = ActiveCall::global(cx)
1629                            .read(cx)
1630                            .room()?
1631                            .read(cx)
1632                            .channel_id()?;
1633
1634                        Some(call_channel == channel.id)
1635                    })
1636                    .unwrap_or(false);
1637                    if is_active {
1638                        self.open_channel_notes(channel.id, window, cx)
1639                    } else {
1640                        self.join_channel(channel.id, window, cx)
1641                    }
1642                }
1643                ListEntry::ContactPlaceholder => self.toggle_contact_finder(window, cx),
1644                ListEntry::CallParticipant { user, peer_id, .. } => {
1645                    if Some(user) == self.user_store.read(cx).current_user().as_ref() {
1646                        Self::leave_call(window, cx);
1647                    } else if let Some(peer_id) = peer_id {
1648                        self.workspace
1649                            .update(cx, |workspace, cx| workspace.follow(*peer_id, window, cx))
1650                            .ok();
1651                    }
1652                }
1653                ListEntry::IncomingRequest(user) => {
1654                    self.respond_to_contact_request(user.id, true, window, cx)
1655                }
1656                ListEntry::ChannelInvite(channel) => {
1657                    self.respond_to_channel_invite(channel.id, true, cx)
1658                }
1659                ListEntry::ChannelNotes { channel_id } => {
1660                    self.open_channel_notes(*channel_id, window, cx)
1661                }
1662                ListEntry::OutgoingRequest(_) => {}
1663                ListEntry::ChannelEditor { .. } => {}
1664            }
1665        }
1666    }
1667
1668    fn insert_space(&mut self, _: &InsertSpace, window: &mut Window, cx: &mut Context<Self>) {
1669        if self.channel_editing_state.is_some() {
1670            self.channel_name_editor.update(cx, |editor, cx| {
1671                editor.insert(" ", window, cx);
1672            });
1673        } else if self.filter_editor.focus_handle(cx).is_focused(window) {
1674            self.filter_editor.update(cx, |editor, cx| {
1675                editor.insert(" ", window, cx);
1676            });
1677        }
1678    }
1679
1680    fn confirm_channel_edit(&mut self, window: &mut Window, cx: &mut Context<CollabPanel>) -> bool {
1681        if let Some(editing_state) = &mut self.channel_editing_state {
1682            match editing_state {
1683                ChannelEditingState::Create {
1684                    location,
1685                    pending_name,
1686                    ..
1687                } => {
1688                    if pending_name.is_some() {
1689                        return false;
1690                    }
1691                    let channel_name = self.channel_name_editor.read(cx).text(cx);
1692
1693                    *pending_name = Some(channel_name.clone());
1694
1695                    let create = self.channel_store.update(cx, |channel_store, cx| {
1696                        channel_store.create_channel(&channel_name, *location, cx)
1697                    });
1698                    if location.is_none() {
1699                        cx.spawn_in(window, async move |this, cx| {
1700                            let channel_id = create.await?;
1701                            this.update_in(cx, |this, window, cx| {
1702                                this.show_channel_modal(
1703                                    channel_id,
1704                                    channel_modal::Mode::InviteMembers,
1705                                    window,
1706                                    cx,
1707                                )
1708                            })
1709                        })
1710                        .detach_and_prompt_err(
1711                            "Failed to create channel",
1712                            window,
1713                            cx,
1714                            |_, _, _| None,
1715                        );
1716                    } else {
1717                        create.detach_and_prompt_err(
1718                            "Failed to create channel",
1719                            window,
1720                            cx,
1721                            |_, _, _| None,
1722                        );
1723                    }
1724                    cx.notify();
1725                }
1726                ChannelEditingState::Rename {
1727                    location,
1728                    pending_name,
1729                } => {
1730                    if pending_name.is_some() {
1731                        return false;
1732                    }
1733                    let channel_name = self.channel_name_editor.read(cx).text(cx);
1734                    *pending_name = Some(channel_name.clone());
1735
1736                    self.channel_store
1737                        .update(cx, |channel_store, cx| {
1738                            channel_store.rename(*location, &channel_name, cx)
1739                        })
1740                        .detach();
1741                    cx.notify();
1742                }
1743            }
1744            cx.focus_self(window);
1745            true
1746        } else {
1747            false
1748        }
1749    }
1750
1751    fn toggle_section_expanded(&mut self, section: Section, cx: &mut Context<Self>) {
1752        if let Some(ix) = self.collapsed_sections.iter().position(|s| *s == section) {
1753            self.collapsed_sections.remove(ix);
1754        } else {
1755            self.collapsed_sections.push(section);
1756        }
1757        self.update_entries(false, cx);
1758    }
1759
1760    fn collapse_selected_channel(
1761        &mut self,
1762        _: &CollapseSelectedChannel,
1763        window: &mut Window,
1764        cx: &mut Context<Self>,
1765    ) {
1766        let Some(channel_id) = self.selected_channel().map(|channel| channel.id) else {
1767            return;
1768        };
1769
1770        if self.is_channel_collapsed(channel_id) {
1771            return;
1772        }
1773
1774        self.toggle_channel_collapsed(channel_id, window, cx);
1775    }
1776
1777    fn expand_selected_channel(
1778        &mut self,
1779        _: &ExpandSelectedChannel,
1780        window: &mut Window,
1781        cx: &mut Context<Self>,
1782    ) {
1783        let Some(id) = self.selected_channel().map(|channel| channel.id) else {
1784            return;
1785        };
1786
1787        if !self.is_channel_collapsed(id) {
1788            return;
1789        }
1790
1791        self.toggle_channel_collapsed(id, window, cx)
1792    }
1793
1794    fn toggle_channel_collapsed(
1795        &mut self,
1796        channel_id: ChannelId,
1797        window: &mut Window,
1798        cx: &mut Context<Self>,
1799    ) {
1800        match self.collapsed_channels.binary_search(&channel_id) {
1801            Ok(ix) => {
1802                self.collapsed_channels.remove(ix);
1803            }
1804            Err(ix) => {
1805                self.collapsed_channels.insert(ix, channel_id);
1806            }
1807        };
1808        self.serialize(cx);
1809        self.update_entries(true, cx);
1810        cx.notify();
1811        cx.focus_self(window);
1812    }
1813
1814    fn is_channel_collapsed(&self, channel_id: ChannelId) -> bool {
1815        self.collapsed_channels.binary_search(&channel_id).is_ok()
1816    }
1817
1818    fn leave_call(window: &mut Window, cx: &mut App) {
1819        ActiveCall::global(cx)
1820            .update(cx, |call, cx| call.hang_up(cx))
1821            .detach_and_prompt_err("Failed to hang up", window, cx, |_, _, _| None);
1822    }
1823
1824    fn toggle_contact_finder(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1825        if let Some(workspace) = self.workspace.upgrade() {
1826            workspace.update(cx, |workspace, cx| {
1827                workspace.toggle_modal(window, cx, |window, cx| {
1828                    let mut finder = ContactFinder::new(self.user_store.clone(), window, cx);
1829                    finder.set_query(self.filter_editor.read(cx).text(cx), window, cx);
1830                    finder
1831                });
1832            });
1833        }
1834    }
1835
1836    fn new_root_channel(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1837        self.channel_editing_state = Some(ChannelEditingState::Create {
1838            location: None,
1839            pending_name: None,
1840        });
1841        self.update_entries(false, cx);
1842        self.select_channel_editor();
1843        window.focus(&self.channel_name_editor.focus_handle(cx), cx);
1844        cx.notify();
1845    }
1846
1847    fn select_channel_editor(&mut self) {
1848        self.selection = self
1849            .entries
1850            .iter()
1851            .position(|entry| matches!(entry, ListEntry::ChannelEditor { .. }));
1852    }
1853
1854    fn new_subchannel(
1855        &mut self,
1856        channel_id: ChannelId,
1857        window: &mut Window,
1858        cx: &mut Context<Self>,
1859    ) {
1860        self.collapsed_channels
1861            .retain(|channel| *channel != channel_id);
1862        self.channel_editing_state = Some(ChannelEditingState::Create {
1863            location: Some(channel_id),
1864            pending_name: None,
1865        });
1866        self.update_entries(false, cx);
1867        self.select_channel_editor();
1868        window.focus(&self.channel_name_editor.focus_handle(cx), cx);
1869        cx.notify();
1870    }
1871
1872    fn manage_members(
1873        &mut self,
1874        channel_id: ChannelId,
1875        window: &mut Window,
1876        cx: &mut Context<Self>,
1877    ) {
1878        self.show_channel_modal(channel_id, channel_modal::Mode::ManageMembers, window, cx);
1879    }
1880
1881    fn remove_selected_channel(&mut self, _: &Remove, window: &mut Window, cx: &mut Context<Self>) {
1882        if let Some(channel) = self.selected_channel() {
1883            self.remove_channel(channel.id, window, cx)
1884        }
1885    }
1886
1887    fn rename_selected_channel(
1888        &mut self,
1889        _: &SecondaryConfirm,
1890        window: &mut Window,
1891        cx: &mut Context<Self>,
1892    ) {
1893        if let Some(channel) = self.selected_channel() {
1894            self.rename_channel(channel.id, window, cx);
1895        }
1896    }
1897
1898    fn rename_channel(
1899        &mut self,
1900        channel_id: ChannelId,
1901        window: &mut Window,
1902        cx: &mut Context<Self>,
1903    ) {
1904        let channel_store = self.channel_store.read(cx);
1905        if !channel_store.is_channel_admin(channel_id) {
1906            return;
1907        }
1908        if let Some(channel) = channel_store.channel_for_id(channel_id).cloned() {
1909            self.channel_editing_state = Some(ChannelEditingState::Rename {
1910                location: channel_id,
1911                pending_name: None,
1912            });
1913            self.channel_name_editor.update(cx, |editor, cx| {
1914                editor.set_text(channel.name.clone(), window, cx);
1915                editor.select_all(&Default::default(), window, cx);
1916            });
1917            window.focus(&self.channel_name_editor.focus_handle(cx), cx);
1918            self.update_entries(false, cx);
1919            self.select_channel_editor();
1920        }
1921    }
1922
1923    fn open_selected_channel_notes(
1924        &mut self,
1925        _: &OpenSelectedChannelNotes,
1926        window: &mut Window,
1927        cx: &mut Context<Self>,
1928    ) {
1929        if let Some(channel) = self.selected_channel() {
1930            self.open_channel_notes(channel.id, window, cx);
1931        }
1932    }
1933
1934    fn set_channel_visibility(
1935        &mut self,
1936        channel_id: ChannelId,
1937        visibility: ChannelVisibility,
1938        window: &mut Window,
1939        cx: &mut Context<Self>,
1940    ) {
1941        self.channel_store
1942            .update(cx, |channel_store, cx| {
1943                channel_store.set_channel_visibility(channel_id, visibility, cx)
1944            })
1945            .detach_and_prompt_err("Failed to set channel visibility", window, cx, |e, _, _| match e.error_code() {
1946                ErrorCode::BadPublicNesting =>
1947                    if e.error_tag("direction") == Some("parent") {
1948                        Some("To make a channel public, its parent channel must be public.".to_string())
1949                    } else {
1950                        Some("To make a channel private, all of its subchannels must be private.".to_string())
1951                    },
1952                _ => None
1953            });
1954    }
1955
1956    fn start_move_channel(
1957        &mut self,
1958        channel_id: ChannelId,
1959        _window: &mut Window,
1960        _cx: &mut Context<Self>,
1961    ) {
1962        self.channel_clipboard = Some(ChannelMoveClipboard { channel_id });
1963    }
1964
1965    fn start_move_selected_channel(
1966        &mut self,
1967        _: &StartMoveChannel,
1968        window: &mut Window,
1969        cx: &mut Context<Self>,
1970    ) {
1971        if let Some(channel) = self.selected_channel() {
1972            self.start_move_channel(channel.id, window, cx);
1973        }
1974    }
1975
1976    fn move_channel_on_clipboard(
1977        &mut self,
1978        to_channel_id: ChannelId,
1979        window: &mut Window,
1980        cx: &mut Context<CollabPanel>,
1981    ) {
1982        if let Some(clipboard) = self.channel_clipboard.take() {
1983            self.move_channel(clipboard.channel_id, to_channel_id, window, cx)
1984        }
1985    }
1986
1987    fn move_channel(
1988        &self,
1989        channel_id: ChannelId,
1990        to: ChannelId,
1991        window: &mut Window,
1992        cx: &mut Context<Self>,
1993    ) {
1994        self.channel_store
1995            .update(cx, |channel_store, cx| {
1996                channel_store.move_channel(channel_id, to, cx)
1997            })
1998            .detach_and_prompt_err("Failed to move channel", window, cx, |e, _, _| {
1999                match e.error_code() {
2000                    ErrorCode::BadPublicNesting => {
2001                        Some("Public channels must have public parents".into())
2002                    }
2003                    ErrorCode::CircularNesting => {
2004                        Some("You cannot move a channel into itself".into())
2005                    }
2006                    ErrorCode::WrongMoveTarget => {
2007                        Some("You cannot move a channel into a different root channel".into())
2008                    }
2009                    _ => None,
2010                }
2011            })
2012    }
2013
2014    fn move_channel_up(&mut self, _: &MoveChannelUp, window: &mut Window, cx: &mut Context<Self>) {
2015        if let Some(channel) = self.selected_channel() {
2016            self.channel_store.update(cx, |store, cx| {
2017                store
2018                    .reorder_channel(channel.id, proto::reorder_channel::Direction::Up, cx)
2019                    .detach_and_prompt_err("Failed to move channel up", window, cx, |_, _, _| None)
2020            });
2021        }
2022    }
2023
2024    fn move_channel_down(
2025        &mut self,
2026        _: &MoveChannelDown,
2027        window: &mut Window,
2028        cx: &mut Context<Self>,
2029    ) {
2030        if let Some(channel) = self.selected_channel() {
2031            self.channel_store.update(cx, |store, cx| {
2032                store
2033                    .reorder_channel(channel.id, proto::reorder_channel::Direction::Down, cx)
2034                    .detach_and_prompt_err("Failed to move channel down", window, cx, |_, _, _| {
2035                        None
2036                    })
2037            });
2038        }
2039    }
2040
2041    fn open_channel_notes(
2042        &mut self,
2043        channel_id: ChannelId,
2044        window: &mut Window,
2045        cx: &mut Context<Self>,
2046    ) {
2047        if let Some(workspace) = self.workspace.upgrade() {
2048            ChannelView::open(channel_id, None, workspace, window, cx).detach();
2049        }
2050    }
2051
2052    fn show_inline_context_menu(
2053        &mut self,
2054        _: &Secondary,
2055        window: &mut Window,
2056        cx: &mut Context<Self>,
2057    ) {
2058        let Some(bounds) = self
2059            .selection
2060            .and_then(|ix| self.list_state.bounds_for_item(ix))
2061        else {
2062            return;
2063        };
2064
2065        if let Some(channel) = self.selected_channel() {
2066            self.deploy_channel_context_menu(
2067                bounds.center(),
2068                channel.id,
2069                self.selection.unwrap(),
2070                window,
2071                cx,
2072            );
2073            cx.stop_propagation();
2074            return;
2075        };
2076
2077        if let Some(contact) = self.selected_contact() {
2078            self.deploy_contact_context_menu(bounds.center(), contact, window, cx);
2079            cx.stop_propagation();
2080        }
2081    }
2082
2083    fn dispatch_context(&self, window: &Window, cx: &Context<Self>) -> KeyContext {
2084        let mut dispatch_context = KeyContext::new_with_defaults();
2085        dispatch_context.add("CollabPanel");
2086        dispatch_context.add("menu");
2087
2088        let identifier = if self.channel_name_editor.focus_handle(cx).is_focused(window)
2089            || self.filter_editor.focus_handle(cx).is_focused(window)
2090        {
2091            "editing"
2092        } else {
2093            "not_editing"
2094        };
2095
2096        dispatch_context.add(identifier);
2097        dispatch_context
2098    }
2099
2100    fn selected_channel(&self) -> Option<&Arc<Channel>> {
2101        self.selection
2102            .and_then(|ix| self.entries.get(ix))
2103            .and_then(|entry| match entry {
2104                ListEntry::Channel { channel, .. } => Some(channel),
2105                _ => None,
2106            })
2107    }
2108
2109    fn selected_contact(&self) -> Option<Arc<Contact>> {
2110        self.selection
2111            .and_then(|ix| self.entries.get(ix))
2112            .and_then(|entry| match entry {
2113                ListEntry::Contact { contact, .. } => Some(contact.clone()),
2114                _ => None,
2115            })
2116    }
2117
2118    fn show_channel_modal(
2119        &mut self,
2120        channel_id: ChannelId,
2121        mode: channel_modal::Mode,
2122        window: &mut Window,
2123        cx: &mut Context<Self>,
2124    ) {
2125        let workspace = self.workspace.clone();
2126        let user_store = self.user_store.clone();
2127        let channel_store = self.channel_store.clone();
2128
2129        cx.spawn_in(window, async move |_, cx| {
2130            workspace.update_in(cx, |workspace, window, cx| {
2131                workspace.toggle_modal(window, cx, |window, cx| {
2132                    ChannelModal::new(
2133                        user_store.clone(),
2134                        channel_store.clone(),
2135                        channel_id,
2136                        mode,
2137                        window,
2138                        cx,
2139                    )
2140                });
2141            })
2142        })
2143        .detach();
2144    }
2145
2146    fn leave_channel(&self, channel_id: ChannelId, window: &mut Window, cx: &mut Context<Self>) {
2147        let Some(user_id) = self.user_store.read(cx).current_user().map(|u| u.id) else {
2148            return;
2149        };
2150        let Some(channel) = self.channel_store.read(cx).channel_for_id(channel_id) else {
2151            return;
2152        };
2153        let prompt_message = format!("Are you sure you want to leave \"#{}\"?", channel.name);
2154        let answer = window.prompt(
2155            PromptLevel::Warning,
2156            &prompt_message,
2157            None,
2158            &["Leave", "Cancel"],
2159            cx,
2160        );
2161        cx.spawn_in(window, async move |this, cx| {
2162            if answer.await? != 0 {
2163                return Ok(());
2164            }
2165            this.update(cx, |this, cx| {
2166                this.channel_store.update(cx, |channel_store, cx| {
2167                    channel_store.remove_member(channel_id, user_id, cx)
2168                })
2169            })?
2170            .await
2171        })
2172        .detach_and_prompt_err("Failed to leave channel", window, cx, |_, _, _| None)
2173    }
2174
2175    fn remove_channel(
2176        &mut self,
2177        channel_id: ChannelId,
2178        window: &mut Window,
2179        cx: &mut Context<Self>,
2180    ) {
2181        let channel_store = self.channel_store.clone();
2182        if let Some(channel) = channel_store.read(cx).channel_for_id(channel_id) {
2183            let prompt_message = format!(
2184                "Are you sure you want to remove the channel \"{}\"?",
2185                channel.name
2186            );
2187            let answer = window.prompt(
2188                PromptLevel::Warning,
2189                &prompt_message,
2190                None,
2191                &["Remove", "Cancel"],
2192                cx,
2193            );
2194            let workspace = self.workspace.clone();
2195            cx.spawn_in(window, async move |this, mut cx| {
2196                if answer.await? == 0 {
2197                    channel_store
2198                        .update(cx, |channels, _| channels.remove_channel(channel_id))
2199                        .await
2200                        .notify_workspace_async_err(workspace, &mut cx);
2201                    this.update_in(cx, |_, window, cx| cx.focus_self(window))
2202                        .ok();
2203                }
2204                anyhow::Ok(())
2205            })
2206            .detach();
2207        }
2208    }
2209
2210    fn remove_contact(
2211        &mut self,
2212        user_id: u64,
2213        github_login: &str,
2214        window: &mut Window,
2215        cx: &mut Context<Self>,
2216    ) {
2217        let user_store = self.user_store.clone();
2218        let prompt_message = format!(
2219            "Are you sure you want to remove \"{}\" from your contacts?",
2220            github_login
2221        );
2222        let answer = window.prompt(
2223            PromptLevel::Warning,
2224            &prompt_message,
2225            None,
2226            &["Remove", "Cancel"],
2227            cx,
2228        );
2229        let workspace = self.workspace.clone();
2230        cx.spawn_in(window, async move |_, mut cx| {
2231            if answer.await? == 0 {
2232                user_store
2233                    .update(cx, |store, cx| store.remove_contact(user_id, cx))
2234                    .await
2235                    .notify_workspace_async_err(workspace, &mut cx);
2236            }
2237            anyhow::Ok(())
2238        })
2239        .detach_and_prompt_err("Failed to remove contact", window, cx, |_, _, _| None);
2240    }
2241
2242    fn respond_to_contact_request(
2243        &mut self,
2244        user_id: u64,
2245        accept: bool,
2246        window: &mut Window,
2247        cx: &mut Context<Self>,
2248    ) {
2249        self.user_store
2250            .update(cx, |store, cx| {
2251                store.respond_to_contact_request(user_id, accept, cx)
2252            })
2253            .detach_and_prompt_err(
2254                "Failed to respond to contact request",
2255                window,
2256                cx,
2257                |_, _, _| None,
2258            );
2259    }
2260
2261    fn respond_to_channel_invite(
2262        &mut self,
2263        channel_id: ChannelId,
2264        accept: bool,
2265        cx: &mut Context<Self>,
2266    ) {
2267        self.channel_store
2268            .update(cx, |store, cx| {
2269                store.respond_to_channel_invite(channel_id, accept, cx)
2270            })
2271            .detach();
2272    }
2273
2274    fn call(&mut self, recipient_user_id: u64, window: &mut Window, cx: &mut Context<Self>) {
2275        ActiveCall::global(cx)
2276            .update(cx, |call, cx| {
2277                call.invite(recipient_user_id, Some(self.project.clone()), cx)
2278            })
2279            .detach_and_prompt_err("Call failed", window, cx, |_, _, _| None);
2280    }
2281
2282    fn join_channel(&self, channel_id: ChannelId, window: &mut Window, cx: &mut Context<Self>) {
2283        let Some(workspace) = self.workspace.upgrade() else {
2284            return;
2285        };
2286
2287        let Some(handle) = window.window_handle().downcast::<MultiWorkspace>() else {
2288            return;
2289        };
2290        workspace::join_channel(
2291            channel_id,
2292            workspace.read(cx).app_state().clone(),
2293            Some(handle),
2294            Some(self.workspace.clone()),
2295            cx,
2296        )
2297        .detach_and_prompt_err("Failed to join channel", window, cx, |_, _, _| None)
2298    }
2299
2300    fn copy_channel_link(&mut self, channel_id: ChannelId, cx: &mut Context<Self>) {
2301        let channel_store = self.channel_store.read(cx);
2302        let Some(channel) = channel_store.channel_for_id(channel_id) else {
2303            return;
2304        };
2305        let item = ClipboardItem::new_string(channel.link(cx));
2306        cx.write_to_clipboard(item)
2307    }
2308
2309    fn copy_channel_notes_link(&mut self, channel_id: ChannelId, cx: &mut Context<Self>) {
2310        let channel_store = self.channel_store.read(cx);
2311        let Some(channel) = channel_store.channel_for_id(channel_id) else {
2312            return;
2313        };
2314        let item = ClipboardItem::new_string(channel.notes_link(None, cx));
2315        cx.write_to_clipboard(item)
2316    }
2317
2318    fn render_signed_out(&mut self, cx: &mut Context<Self>) -> Div {
2319        let collab_blurb = "Work with your team in realtime with collaborative editing, voice, shared notes and more.";
2320
2321        v_flex()
2322            .gap_6()
2323            .p_4()
2324            .child(Label::new(collab_blurb))
2325            .child(
2326                v_flex()
2327                    .gap_2()
2328                    .child(
2329                        Button::new("sign_in", "Sign in")
2330                            .icon_color(Color::Muted)
2331                            .icon(IconName::Github)
2332                            .icon_position(IconPosition::Start)
2333                            .style(ButtonStyle::Filled)
2334                            .full_width()
2335                            .on_click(cx.listener(|this, _, window, cx| {
2336                                let client = this.client.clone();
2337                                let workspace = this.workspace.clone();
2338                                cx.spawn_in(window, async move |_, mut cx| {
2339                                    client
2340                                        .connect(true, &mut cx)
2341                                        .await
2342                                        .into_response()
2343                                        .notify_workspace_async_err(workspace, &mut cx);
2344                                })
2345                                .detach()
2346                            })),
2347                    )
2348                    .child(
2349                        v_flex().w_full().items_center().child(
2350                            Label::new("Sign in to enable collaboration.")
2351                                .color(Color::Muted)
2352                                .size(LabelSize::Small),
2353                        ),
2354                    ),
2355            )
2356    }
2357
2358    fn render_list_entry(
2359        &mut self,
2360        ix: usize,
2361        window: &mut Window,
2362        cx: &mut Context<Self>,
2363    ) -> AnyElement {
2364        let entry = &self.entries[ix];
2365
2366        let is_selected = self.selection == Some(ix);
2367        match entry {
2368            ListEntry::Header(section) => {
2369                let is_collapsed = self.collapsed_sections.contains(section);
2370                self.render_header(*section, is_selected, is_collapsed, cx)
2371                    .into_any_element()
2372            }
2373            ListEntry::Contact { contact, calling } => self
2374                .render_contact(contact, *calling, is_selected, cx)
2375                .into_any_element(),
2376            ListEntry::ContactPlaceholder => self
2377                .render_contact_placeholder(is_selected, cx)
2378                .into_any_element(),
2379            ListEntry::IncomingRequest(user) => self
2380                .render_contact_request(user, true, is_selected, cx)
2381                .into_any_element(),
2382            ListEntry::OutgoingRequest(user) => self
2383                .render_contact_request(user, false, is_selected, cx)
2384                .into_any_element(),
2385            ListEntry::Channel {
2386                channel,
2387                depth,
2388                has_children,
2389                string_match,
2390            } => self
2391                .render_channel(
2392                    channel,
2393                    *depth,
2394                    *has_children,
2395                    is_selected,
2396                    ix,
2397                    string_match.as_ref(),
2398                    cx,
2399                )
2400                .into_any_element(),
2401            ListEntry::ChannelEditor { depth } => self
2402                .render_channel_editor(*depth, window, cx)
2403                .into_any_element(),
2404            ListEntry::ChannelInvite(channel) => self
2405                .render_channel_invite(channel, is_selected, cx)
2406                .into_any_element(),
2407            ListEntry::CallParticipant {
2408                user,
2409                peer_id,
2410                is_pending,
2411                role,
2412            } => self
2413                .render_call_participant(user, *peer_id, *is_pending, *role, is_selected, cx)
2414                .into_any_element(),
2415            ListEntry::ParticipantProject {
2416                project_id,
2417                worktree_root_names,
2418                host_user_id,
2419                is_last,
2420            } => self
2421                .render_participant_project(
2422                    *project_id,
2423                    worktree_root_names,
2424                    *host_user_id,
2425                    *is_last,
2426                    is_selected,
2427                    window,
2428                    cx,
2429                )
2430                .into_any_element(),
2431            ListEntry::ParticipantScreen { peer_id, is_last } => self
2432                .render_participant_screen(*peer_id, *is_last, is_selected, window, cx)
2433                .into_any_element(),
2434            ListEntry::ChannelNotes { channel_id } => self
2435                .render_channel_notes(*channel_id, is_selected, window, cx)
2436                .into_any_element(),
2437        }
2438    }
2439
2440    fn render_signed_in(&mut self, _: &mut Window, cx: &mut Context<Self>) -> Div {
2441        self.channel_store.update(cx, |channel_store, _| {
2442            channel_store.initialize();
2443        });
2444
2445        let has_query = !self.filter_editor.read(cx).text(cx).is_empty();
2446
2447        v_flex()
2448            .size_full()
2449            .gap_1()
2450            .child(
2451                h_flex()
2452                    .p_2()
2453                    .h(Tab::container_height(cx))
2454                    .gap_1p5()
2455                    .border_b_1()
2456                    .border_color(cx.theme().colors().border)
2457                    .child(
2458                        Icon::new(IconName::MagnifyingGlass)
2459                            .size(IconSize::Small)
2460                            .color(Color::Muted),
2461                    )
2462                    .child(self.render_filter_input(&self.filter_editor, cx))
2463                    .when(has_query, |this| {
2464                        this.pr_2p5().child(
2465                            IconButton::new("clear_filter", IconName::Close)
2466                                .shape(IconButtonShape::Square)
2467                                .tooltip(Tooltip::text("Clear Filter"))
2468                                .on_click(cx.listener(|this, _, window, cx| {
2469                                    this.reset_filter_editor_text(window, cx);
2470                                    cx.notify();
2471                                })),
2472                        )
2473                    }),
2474            )
2475            .child(
2476                list(
2477                    self.list_state.clone(),
2478                    cx.processor(Self::render_list_entry),
2479                )
2480                .size_full(),
2481            )
2482    }
2483
2484    fn render_filter_input(
2485        &self,
2486        editor: &Entity<Editor>,
2487        cx: &mut Context<Self>,
2488    ) -> impl IntoElement {
2489        let settings = ThemeSettings::get_global(cx);
2490        let text_style = TextStyle {
2491            color: if editor.read(cx).read_only(cx) {
2492                cx.theme().colors().text_disabled
2493            } else {
2494                cx.theme().colors().text
2495            },
2496            font_family: settings.ui_font.family.clone(),
2497            font_features: settings.ui_font.features.clone(),
2498            font_fallbacks: settings.ui_font.fallbacks.clone(),
2499            font_size: rems(0.875).into(),
2500            font_weight: settings.ui_font.weight,
2501            font_style: FontStyle::Normal,
2502            line_height: relative(1.3),
2503            ..Default::default()
2504        };
2505
2506        EditorElement::new(
2507            editor,
2508            EditorStyle {
2509                local_player: cx.theme().players().local(),
2510                text: text_style,
2511                ..Default::default()
2512            },
2513        )
2514    }
2515
2516    fn render_header(
2517        &self,
2518        section: Section,
2519        is_selected: bool,
2520        is_collapsed: bool,
2521        cx: &mut Context<Self>,
2522    ) -> impl IntoElement {
2523        let mut channel_link = None;
2524        let mut channel_tooltip_text = None;
2525        let mut channel_icon = None;
2526
2527        let text = match section {
2528            Section::ActiveCall => {
2529                let channel_name = maybe!({
2530                    let channel_id = ActiveCall::global(cx).read(cx).channel_id(cx)?;
2531
2532                    let channel = self.channel_store.read(cx).channel_for_id(channel_id)?;
2533
2534                    channel_link = Some(channel.link(cx));
2535                    (channel_icon, channel_tooltip_text) = match channel.visibility {
2536                        proto::ChannelVisibility::Public => {
2537                            (Some("icons/public.svg"), Some("Copy public channel link."))
2538                        }
2539                        proto::ChannelVisibility::Members => {
2540                            (Some("icons/hash.svg"), Some("Copy private channel link."))
2541                        }
2542                    };
2543
2544                    Some(channel.name.as_ref())
2545                });
2546
2547                if let Some(name) = channel_name {
2548                    SharedString::from(name.to_string())
2549                } else {
2550                    SharedString::from("Current Call")
2551                }
2552            }
2553            Section::ContactRequests => SharedString::from("Requests"),
2554            Section::Contacts => SharedString::from("Contacts"),
2555            Section::Channels => SharedString::from("Channels"),
2556            Section::ChannelInvites => SharedString::from("Invites"),
2557            Section::Online => SharedString::from("Online"),
2558            Section::Offline => SharedString::from("Offline"),
2559        };
2560
2561        let button = match section {
2562            Section::ActiveCall => channel_link.map(|channel_link| {
2563                CopyButton::new("copy-channel-link", channel_link)
2564                    .visible_on_hover("section-header")
2565                    .tooltip_label("Copy Channel Link")
2566                    .into_any_element()
2567            }),
2568            Section::Contacts => Some(
2569                IconButton::new("add-contact", IconName::Plus)
2570                    .on_click(
2571                        cx.listener(|this, _, window, cx| this.toggle_contact_finder(window, cx)),
2572                    )
2573                    .tooltip(Tooltip::text("Search for new contact"))
2574                    .into_any_element(),
2575            ),
2576            Section::Channels => {
2577                Some(
2578                    h_flex()
2579                        .gap_1()
2580                        .child(
2581                            IconButton::new("filter-active-channels", IconName::ListFilter)
2582                                .toggle_state(self.filter_active_channels)
2583                                .when(!self.filter_active_channels, |button| {
2584                                    button.visible_on_hover("section-header")
2585                                })
2586                                .on_click(cx.listener(|this, _, _window, cx| {
2587                                    this.filter_active_channels = !this.filter_active_channels;
2588                                    this.update_entries(true, cx);
2589                                }))
2590                                .tooltip(Tooltip::text(if self.filter_active_channels {
2591                                    "Show All Channels"
2592                                } else {
2593                                    "Show Active Channels"
2594                                })),
2595                        )
2596                        .child(
2597                            IconButton::new("add-channel", IconName::Plus)
2598                                .on_click(cx.listener(|this, _, window, cx| {
2599                                    this.new_root_channel(window, cx)
2600                                }))
2601                                .tooltip(Tooltip::text("Create a channel")),
2602                        )
2603                        .into_any_element(),
2604                )
2605            }
2606            _ => None,
2607        };
2608
2609        let can_collapse = match section {
2610            Section::ActiveCall | Section::Channels | Section::Contacts => false,
2611            Section::ChannelInvites
2612            | Section::ContactRequests
2613            | Section::Online
2614            | Section::Offline => true,
2615        };
2616
2617        h_flex().w_full().group("section-header").child(
2618            ListHeader::new(text)
2619                .when(can_collapse, |header| {
2620                    header.toggle(Some(!is_collapsed)).on_toggle(cx.listener(
2621                        move |this, _, _, cx| {
2622                            this.toggle_section_expanded(section, cx);
2623                        },
2624                    ))
2625                })
2626                .inset(true)
2627                .end_slot::<AnyElement>(button)
2628                .toggle_state(is_selected),
2629        )
2630    }
2631
2632    fn render_contact(
2633        &self,
2634        contact: &Arc<Contact>,
2635        calling: bool,
2636        is_selected: bool,
2637        cx: &mut Context<Self>,
2638    ) -> impl IntoElement {
2639        let online = contact.online;
2640        let busy = contact.busy || calling;
2641        let github_login = contact.user.github_login.clone();
2642        let item = ListItem::new(github_login.clone())
2643            .indent_level(1)
2644            .indent_step_size(px(20.))
2645            .toggle_state(is_selected)
2646            .child(
2647                h_flex()
2648                    .w_full()
2649                    .justify_between()
2650                    .child(render_participant_name_and_handle(&contact.user))
2651                    .when(calling, |el| {
2652                        el.child(Label::new("Calling").color(Color::Muted))
2653                    })
2654                    .when(!calling, |el| {
2655                        el.child(
2656                            IconButton::new("contact context menu", IconName::Ellipsis)
2657                                .icon_color(Color::Muted)
2658                                .visible_on_hover("")
2659                                .on_click(cx.listener({
2660                                    let contact = contact.clone();
2661                                    move |this, event: &ClickEvent, window, cx| {
2662                                        this.deploy_contact_context_menu(
2663                                            event.position(),
2664                                            contact.clone(),
2665                                            window,
2666                                            cx,
2667                                        );
2668                                    }
2669                                })),
2670                        )
2671                    }),
2672            )
2673            .on_secondary_mouse_down(cx.listener({
2674                let contact = contact.clone();
2675                move |this, event: &MouseDownEvent, window, cx| {
2676                    this.deploy_contact_context_menu(event.position, contact.clone(), window, cx);
2677                }
2678            }))
2679            .start_slot(
2680                // todo handle contacts with no avatar
2681                Avatar::new(contact.user.avatar_uri.clone())
2682                    .indicator::<AvatarAvailabilityIndicator>(if online {
2683                        Some(AvatarAvailabilityIndicator::new(match busy {
2684                            true => ui::CollaboratorAvailability::Busy,
2685                            false => ui::CollaboratorAvailability::Free,
2686                        }))
2687                    } else {
2688                        None
2689                    }),
2690            );
2691
2692        div()
2693            .id(github_login.clone())
2694            .group("")
2695            .child(item)
2696            .tooltip(move |_, cx| {
2697                let text = if !online {
2698                    format!(" {} is offline", &github_login)
2699                } else if busy {
2700                    format!(" {} is on a call", &github_login)
2701                } else {
2702                    let room = ActiveCall::global(cx).read(cx).room();
2703                    if room.is_some() {
2704                        format!("Invite {} to join call", &github_login)
2705                    } else {
2706                        format!("Call {}", &github_login)
2707                    }
2708                };
2709                Tooltip::simple(text, cx)
2710            })
2711    }
2712
2713    fn render_contact_request(
2714        &self,
2715        user: &Arc<User>,
2716        is_incoming: bool,
2717        is_selected: bool,
2718        cx: &mut Context<Self>,
2719    ) -> impl IntoElement {
2720        let github_login = user.github_login.clone();
2721        let user_id = user.id;
2722        let is_response_pending = self.user_store.read(cx).is_contact_request_pending(user);
2723        let color = if is_response_pending {
2724            Color::Muted
2725        } else {
2726            Color::Default
2727        };
2728
2729        let controls = if is_incoming {
2730            vec![
2731                IconButton::new("decline-contact", IconName::Close)
2732                    .on_click(cx.listener(move |this, _, window, cx| {
2733                        this.respond_to_contact_request(user_id, false, window, cx);
2734                    }))
2735                    .icon_color(color)
2736                    .tooltip(Tooltip::text("Decline invite")),
2737                IconButton::new("accept-contact", IconName::Check)
2738                    .on_click(cx.listener(move |this, _, window, cx| {
2739                        this.respond_to_contact_request(user_id, true, window, cx);
2740                    }))
2741                    .icon_color(color)
2742                    .tooltip(Tooltip::text("Accept invite")),
2743            ]
2744        } else {
2745            let github_login = github_login.clone();
2746            vec![
2747                IconButton::new("remove_contact", IconName::Close)
2748                    .on_click(cx.listener(move |this, _, window, cx| {
2749                        this.remove_contact(user_id, &github_login, window, cx);
2750                    }))
2751                    .icon_color(color)
2752                    .tooltip(Tooltip::text("Cancel invite")),
2753            ]
2754        };
2755
2756        ListItem::new(github_login.clone())
2757            .indent_level(1)
2758            .indent_step_size(px(20.))
2759            .toggle_state(is_selected)
2760            .child(
2761                h_flex()
2762                    .w_full()
2763                    .justify_between()
2764                    .child(Label::new(github_login))
2765                    .child(h_flex().children(controls)),
2766            )
2767            .start_slot(Avatar::new(user.avatar_uri.clone()))
2768    }
2769
2770    fn render_channel_invite(
2771        &self,
2772        channel: &Arc<Channel>,
2773        is_selected: bool,
2774        cx: &mut Context<Self>,
2775    ) -> ListItem {
2776        let channel_id = channel.id;
2777        let response_is_pending = self
2778            .channel_store
2779            .read(cx)
2780            .has_pending_channel_invite_response(channel);
2781        let color = if response_is_pending {
2782            Color::Muted
2783        } else {
2784            Color::Default
2785        };
2786
2787        let controls = [
2788            IconButton::new("reject-invite", IconName::Close)
2789                .on_click(cx.listener(move |this, _, _, cx| {
2790                    this.respond_to_channel_invite(channel_id, false, cx);
2791                }))
2792                .icon_color(color)
2793                .tooltip(Tooltip::text("Decline invite")),
2794            IconButton::new("accept-invite", IconName::Check)
2795                .on_click(cx.listener(move |this, _, _, cx| {
2796                    this.respond_to_channel_invite(channel_id, true, cx);
2797                }))
2798                .icon_color(color)
2799                .tooltip(Tooltip::text("Accept invite")),
2800        ];
2801
2802        ListItem::new(("channel-invite", channel.id.0 as usize))
2803            .toggle_state(is_selected)
2804            .child(
2805                h_flex()
2806                    .w_full()
2807                    .justify_between()
2808                    .child(Label::new(channel.name.clone()))
2809                    .child(h_flex().children(controls)),
2810            )
2811            .start_slot(
2812                Icon::new(IconName::Hash)
2813                    .size(IconSize::Small)
2814                    .color(Color::Muted),
2815            )
2816    }
2817
2818    fn render_contact_placeholder(&self, is_selected: bool, cx: &mut Context<Self>) -> ListItem {
2819        ListItem::new("contact-placeholder")
2820            .child(Icon::new(IconName::Plus))
2821            .child(Label::new("Add a Contact"))
2822            .toggle_state(is_selected)
2823            .on_click(cx.listener(|this, _, window, cx| this.toggle_contact_finder(window, cx)))
2824    }
2825
2826    fn render_channel(
2827        &self,
2828        channel: &Channel,
2829        depth: usize,
2830        has_children: bool,
2831        is_selected: bool,
2832        ix: usize,
2833        string_match: Option<&StringMatch>,
2834        cx: &mut Context<Self>,
2835    ) -> impl IntoElement {
2836        let channel_id = channel.id;
2837
2838        let is_active = maybe!({
2839            let call_channel = ActiveCall::global(cx)
2840                .read(cx)
2841                .room()?
2842                .read(cx)
2843                .channel_id()?;
2844            Some(call_channel == channel_id)
2845        })
2846        .unwrap_or(false);
2847        let channel_store = self.channel_store.read(cx);
2848        let is_public = channel_store
2849            .channel_for_id(channel_id)
2850            .map(|channel| channel.visibility)
2851            == Some(proto::ChannelVisibility::Public);
2852        let disclosed =
2853            has_children.then(|| self.collapsed_channels.binary_search(&channel.id).is_err());
2854
2855        let has_notes_notification = channel_store.has_channel_buffer_changed(channel_id);
2856
2857        const FACEPILE_LIMIT: usize = 3;
2858        let participants = self.channel_store.read(cx).channel_participants(channel_id);
2859
2860        let face_pile = if participants.is_empty() {
2861            None
2862        } else {
2863            let extra_count = participants.len().saturating_sub(FACEPILE_LIMIT);
2864            let result = Facepile::new(
2865                participants
2866                    .iter()
2867                    .map(|user| Avatar::new(user.avatar_uri.clone()).into_any_element())
2868                    .take(FACEPILE_LIMIT)
2869                    .chain(if extra_count > 0 {
2870                        Some(
2871                            Label::new(format!("+{extra_count}"))
2872                                .ml_2()
2873                                .into_any_element(),
2874                        )
2875                    } else {
2876                        None
2877                    })
2878                    .collect::<SmallVec<_>>(),
2879            );
2880
2881            Some(result)
2882        };
2883
2884        let width = self.width.unwrap_or(px(240.));
2885        let root_id = channel.root_id();
2886
2887        div()
2888            .h_6()
2889            .id(channel_id.0 as usize)
2890            .group("")
2891            .flex()
2892            .w_full()
2893            .when(!channel.is_root_channel(), |el| {
2894                el.on_drag(channel.clone(), move |channel, _, _, cx| {
2895                    cx.new(|_| DraggedChannelView {
2896                        channel: channel.clone(),
2897                        width,
2898                    })
2899                })
2900            })
2901            .drag_over::<Channel>({
2902                move |style, dragged_channel: &Channel, _window, cx| {
2903                    if dragged_channel.root_id() == root_id {
2904                        style.bg(cx.theme().colors().ghost_element_hover)
2905                    } else {
2906                        style
2907                    }
2908                }
2909            })
2910            .on_drop(
2911                cx.listener(move |this, dragged_channel: &Channel, window, cx| {
2912                    if dragged_channel.root_id() != root_id {
2913                        return;
2914                    }
2915                    this.move_channel(dragged_channel.id, channel_id, window, cx);
2916                }),
2917            )
2918            .child(
2919                ListItem::new(channel_id.0 as usize)
2920                    // Add one level of depth for the disclosure arrow.
2921                    .indent_level(depth + 1)
2922                    .indent_step_size(px(20.))
2923                    .toggle_state(is_selected || is_active)
2924                    .toggle(disclosed)
2925                    .on_toggle(cx.listener(move |this, _, window, cx| {
2926                        this.toggle_channel_collapsed(channel_id, window, cx)
2927                    }))
2928                    .on_click(cx.listener(move |this, _, window, cx| {
2929                        if is_active {
2930                            this.open_channel_notes(channel_id, window, cx)
2931                        } else {
2932                            this.join_channel(channel_id, window, cx)
2933                        }
2934                    }))
2935                    .on_secondary_mouse_down(cx.listener(
2936                        move |this, event: &MouseDownEvent, window, cx| {
2937                            this.deploy_channel_context_menu(
2938                                event.position,
2939                                channel_id,
2940                                ix,
2941                                window,
2942                                cx,
2943                            )
2944                        },
2945                    ))
2946                    .start_slot(
2947                        div()
2948                            .relative()
2949                            .child(
2950                                Icon::new(if is_public {
2951                                    IconName::Public
2952                                } else {
2953                                    IconName::Hash
2954                                })
2955                                .size(IconSize::Small)
2956                                .color(Color::Muted),
2957                            )
2958                            .children(has_notes_notification.then(|| {
2959                                div()
2960                                    .w_1p5()
2961                                    .absolute()
2962                                    .right(px(-1.))
2963                                    .top(px(-1.))
2964                                    .child(Indicator::dot().color(Color::Info))
2965                            })),
2966                    )
2967                    .child(
2968                        h_flex()
2969                            .id(channel_id.0 as usize)
2970                            .child(match string_match {
2971                                None => Label::new(channel.name.clone()).into_any_element(),
2972                                Some(string_match) => HighlightedLabel::new(
2973                                    channel.name.clone(),
2974                                    string_match.positions.clone(),
2975                                )
2976                                .into_any_element(),
2977                            })
2978                            .children(face_pile.map(|face_pile| face_pile.p_1())),
2979                    ),
2980            )
2981            .child(
2982                h_flex().absolute().right(rems(0.)).h_full().child(
2983                    h_flex()
2984                        .h_full()
2985                        .bg(cx.theme().colors().background)
2986                        .rounded_l_sm()
2987                        .gap_1()
2988                        .px_1()
2989                        .child(
2990                            IconButton::new("channel_notes", IconName::Reader)
2991                                .style(ButtonStyle::Filled)
2992                                .shape(ui::IconButtonShape::Square)
2993                                .icon_size(IconSize::Small)
2994                                .icon_color(if has_notes_notification {
2995                                    Color::Default
2996                                } else {
2997                                    Color::Muted
2998                                })
2999                                .on_click(cx.listener(move |this, _, window, cx| {
3000                                    this.open_channel_notes(channel_id, window, cx)
3001                                }))
3002                                .tooltip(Tooltip::text("Open channel notes")),
3003                        )
3004                        .visible_on_hover(""),
3005                ),
3006            )
3007            .tooltip({
3008                let channel_store = self.channel_store.clone();
3009                move |_window, cx| {
3010                    cx.new(|_| JoinChannelTooltip {
3011                        channel_store: channel_store.clone(),
3012                        channel_id,
3013                        has_notes_notification,
3014                    })
3015                    .into()
3016                }
3017            })
3018    }
3019
3020    fn render_channel_editor(
3021        &self,
3022        depth: usize,
3023        _window: &mut Window,
3024        _cx: &mut Context<Self>,
3025    ) -> impl IntoElement {
3026        let item = ListItem::new("channel-editor")
3027            .inset(false)
3028            // Add one level of depth for the disclosure arrow.
3029            .indent_level(depth + 1)
3030            .indent_step_size(px(20.))
3031            .start_slot(
3032                Icon::new(IconName::Hash)
3033                    .size(IconSize::Small)
3034                    .color(Color::Muted),
3035            );
3036
3037        if let Some(pending_name) = self
3038            .channel_editing_state
3039            .as_ref()
3040            .and_then(|state| state.pending_name())
3041        {
3042            item.child(Label::new(pending_name))
3043        } else {
3044            item.child(self.channel_name_editor.clone())
3045        }
3046    }
3047}
3048
3049fn render_tree_branch(
3050    is_last: bool,
3051    overdraw: bool,
3052    window: &mut Window,
3053    cx: &mut App,
3054) -> impl IntoElement {
3055    let rem_size = window.rem_size();
3056    let line_height = window.text_style().line_height_in_pixels(rem_size);
3057    let width = rem_size * 1.5;
3058    let thickness = px(1.);
3059    let color = cx.theme().colors().text;
3060
3061    canvas(
3062        |_, _, _| {},
3063        move |bounds, _, window, _| {
3064            let start_x = (bounds.left() + bounds.right() - thickness) / 2.;
3065            let start_y = (bounds.top() + bounds.bottom() - thickness) / 2.;
3066            let right = bounds.right();
3067            let top = bounds.top();
3068
3069            window.paint_quad(fill(
3070                Bounds::from_corners(
3071                    point(start_x, top),
3072                    point(
3073                        start_x + thickness,
3074                        if is_last {
3075                            start_y
3076                        } else {
3077                            bounds.bottom() + if overdraw { px(1.) } else { px(0.) }
3078                        },
3079                    ),
3080                ),
3081                color,
3082            ));
3083            window.paint_quad(fill(
3084                Bounds::from_corners(point(start_x, start_y), point(right, start_y + thickness)),
3085                color,
3086            ));
3087        },
3088    )
3089    .w(width)
3090    .h(line_height)
3091}
3092
3093fn render_participant_name_and_handle(user: &User) -> impl IntoElement {
3094    Label::new(if let Some(ref display_name) = user.name {
3095        format!("{display_name} ({})", user.github_login)
3096    } else {
3097        user.github_login.to_string()
3098    })
3099}
3100
3101impl Render for CollabPanel {
3102    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3103        v_flex()
3104            .key_context(self.dispatch_context(window, cx))
3105            .on_action(cx.listener(CollabPanel::cancel))
3106            .on_action(cx.listener(CollabPanel::select_next))
3107            .on_action(cx.listener(CollabPanel::select_previous))
3108            .on_action(cx.listener(CollabPanel::confirm))
3109            .on_action(cx.listener(CollabPanel::insert_space))
3110            .on_action(cx.listener(CollabPanel::remove_selected_channel))
3111            .on_action(cx.listener(CollabPanel::show_inline_context_menu))
3112            .on_action(cx.listener(CollabPanel::rename_selected_channel))
3113            .on_action(cx.listener(CollabPanel::open_selected_channel_notes))
3114            .on_action(cx.listener(CollabPanel::collapse_selected_channel))
3115            .on_action(cx.listener(CollabPanel::expand_selected_channel))
3116            .on_action(cx.listener(CollabPanel::start_move_selected_channel))
3117            .on_action(cx.listener(CollabPanel::move_channel_up))
3118            .on_action(cx.listener(CollabPanel::move_channel_down))
3119            .track_focus(&self.focus_handle)
3120            .size_full()
3121            .child(if !self.client.status().borrow().is_or_was_connected() {
3122                self.render_signed_out(cx)
3123            } else {
3124                self.render_signed_in(window, cx)
3125            })
3126            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
3127                deferred(
3128                    anchored()
3129                        .position(*position)
3130                        .anchor(gpui::Corner::TopLeft)
3131                        .child(menu.clone()),
3132                )
3133                .with_priority(1)
3134            }))
3135    }
3136}
3137
3138impl EventEmitter<PanelEvent> for CollabPanel {}
3139
3140impl Panel for CollabPanel {
3141    fn position(&self, _window: &Window, cx: &App) -> DockPosition {
3142        CollaborationPanelSettings::get_global(cx).dock
3143    }
3144
3145    fn position_is_valid(&self, position: DockPosition) -> bool {
3146        matches!(position, DockPosition::Left | DockPosition::Right)
3147    }
3148
3149    fn set_position(
3150        &mut self,
3151        position: DockPosition,
3152        _window: &mut Window,
3153        cx: &mut Context<Self>,
3154    ) {
3155        settings::update_settings_file(self.fs.clone(), cx, move |settings, _| {
3156            settings.collaboration_panel.get_or_insert_default().dock = Some(position.into())
3157        });
3158    }
3159
3160    fn size(&self, _window: &Window, cx: &App) -> Pixels {
3161        self.width
3162            .unwrap_or_else(|| CollaborationPanelSettings::get_global(cx).default_width)
3163    }
3164
3165    fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
3166        self.width = size;
3167        cx.notify();
3168        cx.defer_in(window, |this, _, cx| {
3169            this.serialize(cx);
3170        });
3171    }
3172
3173    fn icon(&self, _window: &Window, cx: &App) -> Option<ui::IconName> {
3174        CollaborationPanelSettings::get_global(cx)
3175            .button
3176            .then_some(ui::IconName::UserGroup)
3177    }
3178
3179    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
3180        Some("Collab Panel")
3181    }
3182
3183    fn toggle_action(&self) -> Box<dyn gpui::Action> {
3184        Box::new(ToggleFocus)
3185    }
3186
3187    fn persistent_name() -> &'static str {
3188        "CollabPanel"
3189    }
3190
3191    fn panel_key() -> &'static str {
3192        COLLABORATION_PANEL_KEY
3193    }
3194
3195    fn activation_priority(&self) -> u32 {
3196        6
3197    }
3198}
3199
3200impl Focusable for CollabPanel {
3201    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
3202        self.filter_editor.focus_handle(cx)
3203    }
3204}
3205
3206impl PartialEq for ListEntry {
3207    fn eq(&self, other: &Self) -> bool {
3208        match self {
3209            ListEntry::Header(section_1) => {
3210                if let ListEntry::Header(section_2) = other {
3211                    return section_1 == section_2;
3212                }
3213            }
3214            ListEntry::CallParticipant { user: user_1, .. } => {
3215                if let ListEntry::CallParticipant { user: user_2, .. } = other {
3216                    return user_1.id == user_2.id;
3217                }
3218            }
3219            ListEntry::ParticipantProject {
3220                project_id: project_id_1,
3221                ..
3222            } => {
3223                if let ListEntry::ParticipantProject {
3224                    project_id: project_id_2,
3225                    ..
3226                } = other
3227                {
3228                    return project_id_1 == project_id_2;
3229                }
3230            }
3231            ListEntry::ParticipantScreen {
3232                peer_id: peer_id_1, ..
3233            } => {
3234                if let ListEntry::ParticipantScreen {
3235                    peer_id: peer_id_2, ..
3236                } = other
3237                {
3238                    return peer_id_1 == peer_id_2;
3239                }
3240            }
3241            ListEntry::Channel {
3242                channel: channel_1, ..
3243            } => {
3244                if let ListEntry::Channel {
3245                    channel: channel_2, ..
3246                } = other
3247                {
3248                    return channel_1.id == channel_2.id;
3249                }
3250            }
3251            ListEntry::ChannelNotes { channel_id } => {
3252                if let ListEntry::ChannelNotes {
3253                    channel_id: other_id,
3254                } = other
3255                {
3256                    return channel_id == other_id;
3257                }
3258            }
3259            ListEntry::ChannelInvite(channel_1) => {
3260                if let ListEntry::ChannelInvite(channel_2) = other {
3261                    return channel_1.id == channel_2.id;
3262                }
3263            }
3264            ListEntry::IncomingRequest(user_1) => {
3265                if let ListEntry::IncomingRequest(user_2) = other {
3266                    return user_1.id == user_2.id;
3267                }
3268            }
3269            ListEntry::OutgoingRequest(user_1) => {
3270                if let ListEntry::OutgoingRequest(user_2) = other {
3271                    return user_1.id == user_2.id;
3272                }
3273            }
3274            ListEntry::Contact {
3275                contact: contact_1, ..
3276            } => {
3277                if let ListEntry::Contact {
3278                    contact: contact_2, ..
3279                } = other
3280                {
3281                    return contact_1.user.id == contact_2.user.id;
3282                }
3283            }
3284            ListEntry::ChannelEditor { depth } => {
3285                if let ListEntry::ChannelEditor { depth: other_depth } = other {
3286                    return depth == other_depth;
3287                }
3288            }
3289            ListEntry::ContactPlaceholder => {
3290                if let ListEntry::ContactPlaceholder = other {
3291                    return true;
3292                }
3293            }
3294        }
3295        false
3296    }
3297}
3298
3299struct DraggedChannelView {
3300    channel: Channel,
3301    width: Pixels,
3302}
3303
3304impl Render for DraggedChannelView {
3305    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3306        let ui_font = ThemeSettings::get_global(cx).ui_font.family.clone();
3307        h_flex()
3308            .font_family(ui_font)
3309            .bg(cx.theme().colors().background)
3310            .w(self.width)
3311            .p_1()
3312            .gap_1()
3313            .child(
3314                Icon::new(
3315                    if self.channel.visibility == proto::ChannelVisibility::Public {
3316                        IconName::Public
3317                    } else {
3318                        IconName::Hash
3319                    },
3320                )
3321                .size(IconSize::Small)
3322                .color(Color::Muted),
3323            )
3324            .child(Label::new(self.channel.name.clone()))
3325    }
3326}
3327
3328struct JoinChannelTooltip {
3329    channel_store: Entity<ChannelStore>,
3330    channel_id: ChannelId,
3331    #[allow(unused)]
3332    has_notes_notification: bool,
3333}
3334
3335impl Render for JoinChannelTooltip {
3336    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3337        tooltip_container(cx, |container, cx| {
3338            let participants = self
3339                .channel_store
3340                .read(cx)
3341                .channel_participants(self.channel_id);
3342
3343            container
3344                .child(Label::new("Join channel"))
3345                .children(participants.iter().map(|participant| {
3346                    h_flex()
3347                        .gap_2()
3348                        .child(Avatar::new(participant.avatar_uri.clone()))
3349                        .child(render_participant_name_and_handle(participant))
3350                }))
3351        })
3352    }
3353}