collab_panel.rs

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