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                            && state.pending_name().is_some()
 316                        {
 317                            return;
 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                    && let Some(channel_id) = room.channel_id()
 496                {
 497                    self.entries.push(ListEntry::ChannelNotes { channel_id });
 498                    self.entries.push(ListEntry::ChannelChat { channel_id });
 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                && matches!(state, ChannelEditingState::Create { location: None, .. })
 644            {
 645                self.entries.push(ListEntry::ChannelEditor { depth: 0 });
 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            && let Some(entry) = self.entries.get(selection)
1557        {
1558            match entry {
1559                ListEntry::Header(section) => match section {
1560                    Section::ActiveCall => Self::leave_call(window, cx),
1561                    Section::Channels => self.new_root_channel(window, cx),
1562                    Section::Contacts => self.toggle_contact_finder(window, cx),
1563                    Section::ContactRequests
1564                    | Section::Online
1565                    | Section::Offline
1566                    | Section::ChannelInvites => {
1567                        self.toggle_section_expanded(*section, cx);
1568                    }
1569                },
1570                ListEntry::Contact { contact, calling } => {
1571                    if contact.online && !contact.busy && !calling {
1572                        self.call(contact.user.id, window, cx);
1573                    }
1574                }
1575                ListEntry::ParticipantProject {
1576                    project_id,
1577                    host_user_id,
1578                    ..
1579                } => {
1580                    if let Some(workspace) = self.workspace.upgrade() {
1581                        let app_state = workspace.read(cx).app_state().clone();
1582                        workspace::join_in_room_project(*project_id, *host_user_id, app_state, cx)
1583                            .detach_and_prompt_err(
1584                                "Failed to join project",
1585                                window,
1586                                cx,
1587                                |_, _, _| None,
1588                            );
1589                    }
1590                }
1591                ListEntry::ParticipantScreen { peer_id, .. } => {
1592                    let Some(peer_id) = peer_id else {
1593                        return;
1594                    };
1595                    if let Some(workspace) = self.workspace.upgrade() {
1596                        workspace.update(cx, |workspace, cx| {
1597                            workspace.open_shared_screen(*peer_id, window, cx)
1598                        });
1599                    }
1600                }
1601                ListEntry::Channel { channel, .. } => {
1602                    let is_active = maybe!({
1603                        let call_channel = ActiveCall::global(cx)
1604                            .read(cx)
1605                            .room()?
1606                            .read(cx)
1607                            .channel_id()?;
1608
1609                        Some(call_channel == channel.id)
1610                    })
1611                    .unwrap_or(false);
1612                    if is_active {
1613                        self.open_channel_notes(channel.id, window, cx)
1614                    } else {
1615                        self.join_channel(channel.id, window, cx)
1616                    }
1617                }
1618                ListEntry::ContactPlaceholder => self.toggle_contact_finder(window, cx),
1619                ListEntry::CallParticipant { user, peer_id, .. } => {
1620                    if Some(user) == self.user_store.read(cx).current_user().as_ref() {
1621                        Self::leave_call(window, cx);
1622                    } else if let Some(peer_id) = peer_id {
1623                        self.workspace
1624                            .update(cx, |workspace, cx| workspace.follow(*peer_id, window, cx))
1625                            .ok();
1626                    }
1627                }
1628                ListEntry::IncomingRequest(user) => {
1629                    self.respond_to_contact_request(user.id, true, window, cx)
1630                }
1631                ListEntry::ChannelInvite(channel) => {
1632                    self.respond_to_channel_invite(channel.id, true, cx)
1633                }
1634                ListEntry::ChannelNotes { channel_id } => {
1635                    self.open_channel_notes(*channel_id, window, cx)
1636                }
1637                ListEntry::ChannelChat { channel_id } => {
1638                    self.join_channel_chat(*channel_id, window, cx)
1639                }
1640                ListEntry::OutgoingRequest(_) => {}
1641                ListEntry::ChannelEditor { .. } => {}
1642            }
1643        }
1644    }
1645
1646    fn insert_space(&mut self, _: &InsertSpace, window: &mut Window, cx: &mut Context<Self>) {
1647        if self.channel_editing_state.is_some() {
1648            self.channel_name_editor.update(cx, |editor, cx| {
1649                editor.insert(" ", window, cx);
1650            });
1651        } else if self.filter_editor.focus_handle(cx).is_focused(window) {
1652            self.filter_editor.update(cx, |editor, cx| {
1653                editor.insert(" ", window, cx);
1654            });
1655        }
1656    }
1657
1658    fn confirm_channel_edit(&mut self, window: &mut Window, cx: &mut Context<CollabPanel>) -> bool {
1659        if let Some(editing_state) = &mut self.channel_editing_state {
1660            match editing_state {
1661                ChannelEditingState::Create {
1662                    location,
1663                    pending_name,
1664                    ..
1665                } => {
1666                    if pending_name.is_some() {
1667                        return false;
1668                    }
1669                    let channel_name = self.channel_name_editor.read(cx).text(cx);
1670
1671                    *pending_name = Some(channel_name.clone());
1672
1673                    let create = self.channel_store.update(cx, |channel_store, cx| {
1674                        channel_store.create_channel(&channel_name, *location, cx)
1675                    });
1676                    if location.is_none() {
1677                        cx.spawn_in(window, async move |this, cx| {
1678                            let channel_id = create.await?;
1679                            this.update_in(cx, |this, window, cx| {
1680                                this.show_channel_modal(
1681                                    channel_id,
1682                                    channel_modal::Mode::InviteMembers,
1683                                    window,
1684                                    cx,
1685                                )
1686                            })
1687                        })
1688                        .detach_and_prompt_err(
1689                            "Failed to create channel",
1690                            window,
1691                            cx,
1692                            |_, _, _| None,
1693                        );
1694                    } else {
1695                        create.detach_and_prompt_err(
1696                            "Failed to create channel",
1697                            window,
1698                            cx,
1699                            |_, _, _| None,
1700                        );
1701                    }
1702                    cx.notify();
1703                }
1704                ChannelEditingState::Rename {
1705                    location,
1706                    pending_name,
1707                } => {
1708                    if pending_name.is_some() {
1709                        return false;
1710                    }
1711                    let channel_name = self.channel_name_editor.read(cx).text(cx);
1712                    *pending_name = Some(channel_name.clone());
1713
1714                    self.channel_store
1715                        .update(cx, |channel_store, cx| {
1716                            channel_store.rename(*location, &channel_name, cx)
1717                        })
1718                        .detach();
1719                    cx.notify();
1720                }
1721            }
1722            cx.focus_self(window);
1723            true
1724        } else {
1725            false
1726        }
1727    }
1728
1729    fn toggle_section_expanded(&mut self, section: Section, cx: &mut Context<Self>) {
1730        if let Some(ix) = self.collapsed_sections.iter().position(|s| *s == section) {
1731            self.collapsed_sections.remove(ix);
1732        } else {
1733            self.collapsed_sections.push(section);
1734        }
1735        self.update_entries(false, cx);
1736    }
1737
1738    fn collapse_selected_channel(
1739        &mut self,
1740        _: &CollapseSelectedChannel,
1741        window: &mut Window,
1742        cx: &mut Context<Self>,
1743    ) {
1744        let Some(channel_id) = self.selected_channel().map(|channel| channel.id) else {
1745            return;
1746        };
1747
1748        if self.is_channel_collapsed(channel_id) {
1749            return;
1750        }
1751
1752        self.toggle_channel_collapsed(channel_id, window, cx);
1753    }
1754
1755    fn expand_selected_channel(
1756        &mut self,
1757        _: &ExpandSelectedChannel,
1758        window: &mut Window,
1759        cx: &mut Context<Self>,
1760    ) {
1761        let Some(id) = self.selected_channel().map(|channel| channel.id) else {
1762            return;
1763        };
1764
1765        if !self.is_channel_collapsed(id) {
1766            return;
1767        }
1768
1769        self.toggle_channel_collapsed(id, window, cx)
1770    }
1771
1772    fn toggle_channel_collapsed(
1773        &mut self,
1774        channel_id: ChannelId,
1775        window: &mut Window,
1776        cx: &mut Context<Self>,
1777    ) {
1778        match self.collapsed_channels.binary_search(&channel_id) {
1779            Ok(ix) => {
1780                self.collapsed_channels.remove(ix);
1781            }
1782            Err(ix) => {
1783                self.collapsed_channels.insert(ix, channel_id);
1784            }
1785        };
1786        self.serialize(cx);
1787        self.update_entries(true, cx);
1788        cx.notify();
1789        cx.focus_self(window);
1790    }
1791
1792    fn is_channel_collapsed(&self, channel_id: ChannelId) -> bool {
1793        self.collapsed_channels.binary_search(&channel_id).is_ok()
1794    }
1795
1796    fn leave_call(window: &mut Window, cx: &mut App) {
1797        ActiveCall::global(cx)
1798            .update(cx, |call, cx| call.hang_up(cx))
1799            .detach_and_prompt_err("Failed to hang up", window, cx, |_, _, _| None);
1800    }
1801
1802    fn toggle_contact_finder(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1803        if let Some(workspace) = self.workspace.upgrade() {
1804            workspace.update(cx, |workspace, cx| {
1805                workspace.toggle_modal(window, cx, |window, cx| {
1806                    let mut finder = ContactFinder::new(self.user_store.clone(), window, cx);
1807                    finder.set_query(self.filter_editor.read(cx).text(cx), window, cx);
1808                    finder
1809                });
1810            });
1811        }
1812    }
1813
1814    fn new_root_channel(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1815        self.channel_editing_state = Some(ChannelEditingState::Create {
1816            location: None,
1817            pending_name: None,
1818        });
1819        self.update_entries(false, cx);
1820        self.select_channel_editor();
1821        window.focus(&self.channel_name_editor.focus_handle(cx));
1822        cx.notify();
1823    }
1824
1825    fn select_channel_editor(&mut self) {
1826        self.selection = self.entries.iter().position(|entry| match entry {
1827            ListEntry::ChannelEditor { .. } => true,
1828            _ => false,
1829        });
1830    }
1831
1832    fn new_subchannel(
1833        &mut self,
1834        channel_id: ChannelId,
1835        window: &mut Window,
1836        cx: &mut Context<Self>,
1837    ) {
1838        self.collapsed_channels
1839            .retain(|channel| *channel != channel_id);
1840        self.channel_editing_state = Some(ChannelEditingState::Create {
1841            location: Some(channel_id),
1842            pending_name: None,
1843        });
1844        self.update_entries(false, cx);
1845        self.select_channel_editor();
1846        window.focus(&self.channel_name_editor.focus_handle(cx));
1847        cx.notify();
1848    }
1849
1850    fn manage_members(
1851        &mut self,
1852        channel_id: ChannelId,
1853        window: &mut Window,
1854        cx: &mut Context<Self>,
1855    ) {
1856        self.show_channel_modal(channel_id, channel_modal::Mode::ManageMembers, window, cx);
1857    }
1858
1859    fn remove_selected_channel(&mut self, _: &Remove, window: &mut Window, cx: &mut Context<Self>) {
1860        if let Some(channel) = self.selected_channel() {
1861            self.remove_channel(channel.id, window, cx)
1862        }
1863    }
1864
1865    fn rename_selected_channel(
1866        &mut self,
1867        _: &SecondaryConfirm,
1868        window: &mut Window,
1869        cx: &mut Context<Self>,
1870    ) {
1871        if let Some(channel) = self.selected_channel() {
1872            self.rename_channel(channel.id, window, cx);
1873        }
1874    }
1875
1876    fn rename_channel(
1877        &mut self,
1878        channel_id: ChannelId,
1879        window: &mut Window,
1880        cx: &mut Context<Self>,
1881    ) {
1882        let channel_store = self.channel_store.read(cx);
1883        if !channel_store.is_channel_admin(channel_id) {
1884            return;
1885        }
1886        if let Some(channel) = channel_store.channel_for_id(channel_id).cloned() {
1887            self.channel_editing_state = Some(ChannelEditingState::Rename {
1888                location: channel_id,
1889                pending_name: None,
1890            });
1891            self.channel_name_editor.update(cx, |editor, cx| {
1892                editor.set_text(channel.name.clone(), window, cx);
1893                editor.select_all(&Default::default(), window, cx);
1894            });
1895            window.focus(&self.channel_name_editor.focus_handle(cx));
1896            self.update_entries(false, cx);
1897            self.select_channel_editor();
1898        }
1899    }
1900
1901    fn set_channel_visibility(
1902        &mut self,
1903        channel_id: ChannelId,
1904        visibility: ChannelVisibility,
1905        window: &mut Window,
1906        cx: &mut Context<Self>,
1907    ) {
1908        self.channel_store
1909            .update(cx, |channel_store, cx| {
1910                channel_store.set_channel_visibility(channel_id, visibility, cx)
1911            })
1912            .detach_and_prompt_err("Failed to set channel visibility", window, cx, |e, _, _| match e.error_code() {
1913                ErrorCode::BadPublicNesting =>
1914                    if e.error_tag("direction") == Some("parent") {
1915                        Some("To make a channel public, its parent channel must be public.".to_string())
1916                    } else {
1917                        Some("To make a channel private, all of its subchannels must be private.".to_string())
1918                    },
1919                _ => None
1920            });
1921    }
1922
1923    fn start_move_channel(
1924        &mut self,
1925        channel_id: ChannelId,
1926        _window: &mut Window,
1927        _cx: &mut Context<Self>,
1928    ) {
1929        self.channel_clipboard = Some(ChannelMoveClipboard { channel_id });
1930    }
1931
1932    fn start_move_selected_channel(
1933        &mut self,
1934        _: &StartMoveChannel,
1935        window: &mut Window,
1936        cx: &mut Context<Self>,
1937    ) {
1938        if let Some(channel) = self.selected_channel() {
1939            self.start_move_channel(channel.id, window, cx);
1940        }
1941    }
1942
1943    fn move_channel_on_clipboard(
1944        &mut self,
1945        to_channel_id: ChannelId,
1946        window: &mut Window,
1947        cx: &mut Context<CollabPanel>,
1948    ) {
1949        if let Some(clipboard) = self.channel_clipboard.take() {
1950            self.move_channel(clipboard.channel_id, to_channel_id, window, cx)
1951        }
1952    }
1953
1954    fn move_channel(
1955        &self,
1956        channel_id: ChannelId,
1957        to: ChannelId,
1958        window: &mut Window,
1959        cx: &mut Context<Self>,
1960    ) {
1961        self.channel_store
1962            .update(cx, |channel_store, cx| {
1963                channel_store.move_channel(channel_id, to, cx)
1964            })
1965            .detach_and_prompt_err("Failed to move channel", window, cx, |e, _, _| {
1966                match e.error_code() {
1967                    ErrorCode::BadPublicNesting => {
1968                        Some("Public channels must have public parents".into())
1969                    }
1970                    ErrorCode::CircularNesting => {
1971                        Some("You cannot move a channel into itself".into())
1972                    }
1973                    ErrorCode::WrongMoveTarget => {
1974                        Some("You cannot move a channel into a different root channel".into())
1975                    }
1976                    _ => None,
1977                }
1978            })
1979    }
1980
1981    fn move_channel_up(&mut self, _: &MoveChannelUp, window: &mut Window, cx: &mut Context<Self>) {
1982        if let Some(channel) = self.selected_channel() {
1983            self.channel_store.update(cx, |store, cx| {
1984                store
1985                    .reorder_channel(channel.id, proto::reorder_channel::Direction::Up, cx)
1986                    .detach_and_prompt_err("Failed to move channel up", window, cx, |_, _, _| None)
1987            });
1988        }
1989    }
1990
1991    fn move_channel_down(
1992        &mut self,
1993        _: &MoveChannelDown,
1994        window: &mut Window,
1995        cx: &mut Context<Self>,
1996    ) {
1997        if let Some(channel) = self.selected_channel() {
1998            self.channel_store.update(cx, |store, cx| {
1999                store
2000                    .reorder_channel(channel.id, proto::reorder_channel::Direction::Down, cx)
2001                    .detach_and_prompt_err("Failed to move channel down", window, cx, |_, _, _| {
2002                        None
2003                    })
2004            });
2005        }
2006    }
2007
2008    fn open_channel_notes(
2009        &mut self,
2010        channel_id: ChannelId,
2011        window: &mut Window,
2012        cx: &mut Context<Self>,
2013    ) {
2014        if let Some(workspace) = self.workspace.upgrade() {
2015            ChannelView::open(channel_id, None, workspace, window, cx).detach();
2016        }
2017    }
2018
2019    fn show_inline_context_menu(
2020        &mut self,
2021        _: &Secondary,
2022        window: &mut Window,
2023        cx: &mut Context<Self>,
2024    ) {
2025        let Some(bounds) = self
2026            .selection
2027            .and_then(|ix| self.list_state.bounds_for_item(ix))
2028        else {
2029            return;
2030        };
2031
2032        if let Some(channel) = self.selected_channel() {
2033            self.deploy_channel_context_menu(
2034                bounds.center(),
2035                channel.id,
2036                self.selection.unwrap(),
2037                window,
2038                cx,
2039            );
2040            cx.stop_propagation();
2041            return;
2042        };
2043
2044        if let Some(contact) = self.selected_contact() {
2045            self.deploy_contact_context_menu(bounds.center(), contact, window, cx);
2046            cx.stop_propagation();
2047        }
2048    }
2049
2050    fn dispatch_context(&self, window: &Window, cx: &Context<Self>) -> KeyContext {
2051        let mut dispatch_context = KeyContext::new_with_defaults();
2052        dispatch_context.add("CollabPanel");
2053        dispatch_context.add("menu");
2054
2055        let identifier = if self.channel_name_editor.focus_handle(cx).is_focused(window)
2056            || self.filter_editor.focus_handle(cx).is_focused(window)
2057        {
2058            "editing"
2059        } else {
2060            "not_editing"
2061        };
2062
2063        dispatch_context.add(identifier);
2064        dispatch_context
2065    }
2066
2067    fn selected_channel(&self) -> Option<&Arc<Channel>> {
2068        self.selection
2069            .and_then(|ix| self.entries.get(ix))
2070            .and_then(|entry| match entry {
2071                ListEntry::Channel { channel, .. } => Some(channel),
2072                _ => None,
2073            })
2074    }
2075
2076    fn selected_contact(&self) -> Option<Arc<Contact>> {
2077        self.selection
2078            .and_then(|ix| self.entries.get(ix))
2079            .and_then(|entry| match entry {
2080                ListEntry::Contact { contact, .. } => Some(contact.clone()),
2081                _ => None,
2082            })
2083    }
2084
2085    fn show_channel_modal(
2086        &mut self,
2087        channel_id: ChannelId,
2088        mode: channel_modal::Mode,
2089        window: &mut Window,
2090        cx: &mut Context<Self>,
2091    ) {
2092        let workspace = self.workspace.clone();
2093        let user_store = self.user_store.clone();
2094        let channel_store = self.channel_store.clone();
2095
2096        cx.spawn_in(window, async move |_, cx| {
2097            workspace.update_in(cx, |workspace, window, cx| {
2098                workspace.toggle_modal(window, cx, |window, cx| {
2099                    ChannelModal::new(
2100                        user_store.clone(),
2101                        channel_store.clone(),
2102                        channel_id,
2103                        mode,
2104                        window,
2105                        cx,
2106                    )
2107                });
2108            })
2109        })
2110        .detach();
2111    }
2112
2113    fn leave_channel(&self, channel_id: ChannelId, window: &mut Window, cx: &mut Context<Self>) {
2114        let Some(user_id) = self.user_store.read(cx).current_user().map(|u| u.id) else {
2115            return;
2116        };
2117        let Some(channel) = self.channel_store.read(cx).channel_for_id(channel_id) else {
2118            return;
2119        };
2120        let prompt_message = format!("Are you sure you want to leave \"#{}\"?", channel.name);
2121        let answer = window.prompt(
2122            PromptLevel::Warning,
2123            &prompt_message,
2124            None,
2125            &["Leave", "Cancel"],
2126            cx,
2127        );
2128        cx.spawn_in(window, async move |this, cx| {
2129            if answer.await? != 0 {
2130                return Ok(());
2131            }
2132            this.update(cx, |this, cx| {
2133                this.channel_store.update(cx, |channel_store, cx| {
2134                    channel_store.remove_member(channel_id, user_id, cx)
2135                })
2136            })?
2137            .await
2138        })
2139        .detach_and_prompt_err("Failed to leave channel", window, cx, |_, _, _| None)
2140    }
2141
2142    fn remove_channel(
2143        &mut self,
2144        channel_id: ChannelId,
2145        window: &mut Window,
2146        cx: &mut Context<Self>,
2147    ) {
2148        let channel_store = self.channel_store.clone();
2149        if let Some(channel) = channel_store.read(cx).channel_for_id(channel_id) {
2150            let prompt_message = format!(
2151                "Are you sure you want to remove the channel \"{}\"?",
2152                channel.name
2153            );
2154            let answer = window.prompt(
2155                PromptLevel::Warning,
2156                &prompt_message,
2157                None,
2158                &["Remove", "Cancel"],
2159                cx,
2160            );
2161            cx.spawn_in(window, async move |this, cx| {
2162                if answer.await? == 0 {
2163                    channel_store
2164                        .update(cx, |channels, _| channels.remove_channel(channel_id))?
2165                        .await
2166                        .notify_async_err(cx);
2167                    this.update_in(cx, |_, window, cx| cx.focus_self(window))
2168                        .ok();
2169                }
2170                anyhow::Ok(())
2171            })
2172            .detach();
2173        }
2174    }
2175
2176    fn remove_contact(
2177        &mut self,
2178        user_id: u64,
2179        github_login: &str,
2180        window: &mut Window,
2181        cx: &mut Context<Self>,
2182    ) {
2183        let user_store = self.user_store.clone();
2184        let prompt_message = format!(
2185            "Are you sure you want to remove \"{}\" from your contacts?",
2186            github_login
2187        );
2188        let answer = window.prompt(
2189            PromptLevel::Warning,
2190            &prompt_message,
2191            None,
2192            &["Remove", "Cancel"],
2193            cx,
2194        );
2195        cx.spawn_in(window, async move |_, cx| {
2196            if answer.await? == 0 {
2197                user_store
2198                    .update(cx, |store, cx| store.remove_contact(user_id, cx))?
2199                    .await
2200                    .notify_async_err(cx);
2201            }
2202            anyhow::Ok(())
2203        })
2204        .detach_and_prompt_err("Failed to remove contact", window, cx, |_, _, _| None);
2205    }
2206
2207    fn respond_to_contact_request(
2208        &mut self,
2209        user_id: u64,
2210        accept: bool,
2211        window: &mut Window,
2212        cx: &mut Context<Self>,
2213    ) {
2214        self.user_store
2215            .update(cx, |store, cx| {
2216                store.respond_to_contact_request(user_id, accept, cx)
2217            })
2218            .detach_and_prompt_err(
2219                "Failed to respond to contact request",
2220                window,
2221                cx,
2222                |_, _, _| None,
2223            );
2224    }
2225
2226    fn respond_to_channel_invite(
2227        &mut self,
2228        channel_id: ChannelId,
2229        accept: bool,
2230        cx: &mut Context<Self>,
2231    ) {
2232        self.channel_store
2233            .update(cx, |store, cx| {
2234                store.respond_to_channel_invite(channel_id, accept, cx)
2235            })
2236            .detach();
2237    }
2238
2239    fn call(&mut self, recipient_user_id: u64, window: &mut Window, cx: &mut Context<Self>) {
2240        ActiveCall::global(cx)
2241            .update(cx, |call, cx| {
2242                call.invite(recipient_user_id, Some(self.project.clone()), cx)
2243            })
2244            .detach_and_prompt_err("Call failed", window, cx, |_, _, _| None);
2245    }
2246
2247    fn join_channel(&self, channel_id: ChannelId, window: &mut Window, cx: &mut Context<Self>) {
2248        let Some(workspace) = self.workspace.upgrade() else {
2249            return;
2250        };
2251        let Some(handle) = window.window_handle().downcast::<Workspace>() else {
2252            return;
2253        };
2254        workspace::join_channel(
2255            channel_id,
2256            workspace.read(cx).app_state().clone(),
2257            Some(handle),
2258            cx,
2259        )
2260        .detach_and_prompt_err("Failed to join channel", window, cx, |_, _, _| None)
2261    }
2262
2263    fn join_channel_chat(
2264        &mut self,
2265        channel_id: ChannelId,
2266        window: &mut Window,
2267        cx: &mut Context<Self>,
2268    ) {
2269        let Some(workspace) = self.workspace.upgrade() else {
2270            return;
2271        };
2272        window.defer(cx, move |window, cx| {
2273            workspace.update(cx, |workspace, cx| {
2274                if let Some(panel) = workspace.focus_panel::<ChatPanel>(window, cx) {
2275                    panel.update(cx, |panel, cx| {
2276                        panel
2277                            .select_channel(channel_id, None, cx)
2278                            .detach_and_notify_err(window, cx);
2279                    });
2280                }
2281            });
2282        });
2283    }
2284
2285    fn copy_channel_link(&mut self, channel_id: ChannelId, cx: &mut Context<Self>) {
2286        let channel_store = self.channel_store.read(cx);
2287        let Some(channel) = channel_store.channel_for_id(channel_id) else {
2288            return;
2289        };
2290        let item = ClipboardItem::new_string(channel.link(cx));
2291        cx.write_to_clipboard(item)
2292    }
2293
2294    fn render_signed_out(&mut self, cx: &mut Context<Self>) -> Div {
2295        let collab_blurb = "Work with your team in realtime with collaborative editing, voice, shared notes and more.";
2296
2297        v_flex()
2298            .gap_6()
2299            .p_4()
2300            .child(Label::new(collab_blurb))
2301            .child(
2302                v_flex()
2303                    .gap_2()
2304                    .child(
2305                        Button::new("sign_in", "Sign in")
2306                            .icon_color(Color::Muted)
2307                            .icon(IconName::Github)
2308                            .icon_position(IconPosition::Start)
2309                            .style(ButtonStyle::Filled)
2310                            .full_width()
2311                            .on_click(cx.listener(|this, _, window, cx| {
2312                                let client = this.client.clone();
2313                                cx.spawn_in(window, async move |_, cx| {
2314                                    client
2315                                        .connect(true, cx)
2316                                        .await
2317                                        .into_response()
2318                                        .notify_async_err(cx);
2319                                })
2320                                .detach()
2321                            })),
2322                    )
2323                    .child(
2324                        div().flex().w_full().items_center().child(
2325                            Label::new("Sign in to enable collaboration.")
2326                                .color(Color::Muted)
2327                                .size(LabelSize::Small),
2328                        ),
2329                    ),
2330            )
2331    }
2332
2333    fn render_list_entry(
2334        &mut self,
2335        ix: usize,
2336        window: &mut Window,
2337        cx: &mut Context<Self>,
2338    ) -> AnyElement {
2339        let entry = &self.entries[ix];
2340
2341        let is_selected = self.selection == Some(ix);
2342        match entry {
2343            ListEntry::Header(section) => {
2344                let is_collapsed = self.collapsed_sections.contains(section);
2345                self.render_header(*section, is_selected, is_collapsed, cx)
2346                    .into_any_element()
2347            }
2348            ListEntry::Contact { contact, calling } => self
2349                .render_contact(contact, *calling, is_selected, cx)
2350                .into_any_element(),
2351            ListEntry::ContactPlaceholder => self
2352                .render_contact_placeholder(is_selected, cx)
2353                .into_any_element(),
2354            ListEntry::IncomingRequest(user) => self
2355                .render_contact_request(user, true, is_selected, cx)
2356                .into_any_element(),
2357            ListEntry::OutgoingRequest(user) => self
2358                .render_contact_request(user, false, is_selected, cx)
2359                .into_any_element(),
2360            ListEntry::Channel {
2361                channel,
2362                depth,
2363                has_children,
2364            } => self
2365                .render_channel(channel, *depth, *has_children, is_selected, ix, cx)
2366                .into_any_element(),
2367            ListEntry::ChannelEditor { depth } => self
2368                .render_channel_editor(*depth, window, cx)
2369                .into_any_element(),
2370            ListEntry::ChannelInvite(channel) => self
2371                .render_channel_invite(channel, is_selected, cx)
2372                .into_any_element(),
2373            ListEntry::CallParticipant {
2374                user,
2375                peer_id,
2376                is_pending,
2377                role,
2378            } => self
2379                .render_call_participant(user, *peer_id, *is_pending, *role, is_selected, cx)
2380                .into_any_element(),
2381            ListEntry::ParticipantProject {
2382                project_id,
2383                worktree_root_names,
2384                host_user_id,
2385                is_last,
2386            } => self
2387                .render_participant_project(
2388                    *project_id,
2389                    worktree_root_names,
2390                    *host_user_id,
2391                    *is_last,
2392                    is_selected,
2393                    window,
2394                    cx,
2395                )
2396                .into_any_element(),
2397            ListEntry::ParticipantScreen { peer_id, is_last } => self
2398                .render_participant_screen(*peer_id, *is_last, is_selected, window, cx)
2399                .into_any_element(),
2400            ListEntry::ChannelNotes { channel_id } => self
2401                .render_channel_notes(*channel_id, is_selected, window, cx)
2402                .into_any_element(),
2403            ListEntry::ChannelChat { channel_id } => self
2404                .render_channel_chat(*channel_id, is_selected, window, cx)
2405                .into_any_element(),
2406        }
2407    }
2408
2409    fn render_signed_in(&mut self, _: &mut Window, cx: &mut Context<Self>) -> Div {
2410        self.channel_store.update(cx, |channel_store, _| {
2411            channel_store.initialize();
2412        });
2413        v_flex()
2414            .size_full()
2415            .child(
2416                list(
2417                    self.list_state.clone(),
2418                    cx.processor(Self::render_list_entry),
2419                )
2420                .size_full(),
2421            )
2422            .child(
2423                v_flex()
2424                    .child(div().mx_2().border_primary(cx).border_t_1())
2425                    .child(
2426                        v_flex()
2427                            .p_2()
2428                            .child(self.render_filter_input(&self.filter_editor, cx)),
2429                    ),
2430            )
2431    }
2432
2433    fn render_filter_input(
2434        &self,
2435        editor: &Entity<Editor>,
2436        cx: &mut Context<Self>,
2437    ) -> impl IntoElement {
2438        let settings = ThemeSettings::get_global(cx);
2439        let text_style = TextStyle {
2440            color: if editor.read(cx).read_only(cx) {
2441                cx.theme().colors().text_disabled
2442            } else {
2443                cx.theme().colors().text
2444            },
2445            font_family: settings.ui_font.family.clone(),
2446            font_features: settings.ui_font.features.clone(),
2447            font_fallbacks: settings.ui_font.fallbacks.clone(),
2448            font_size: rems(0.875).into(),
2449            font_weight: settings.ui_font.weight,
2450            font_style: FontStyle::Normal,
2451            line_height: relative(1.3),
2452            ..Default::default()
2453        };
2454
2455        EditorElement::new(
2456            editor,
2457            EditorStyle {
2458                local_player: cx.theme().players().local(),
2459                text: text_style,
2460                ..Default::default()
2461            },
2462        )
2463    }
2464
2465    fn render_header(
2466        &self,
2467        section: Section,
2468        is_selected: bool,
2469        is_collapsed: bool,
2470        cx: &mut Context<Self>,
2471    ) -> impl IntoElement {
2472        let mut channel_link = None;
2473        let mut channel_tooltip_text = None;
2474        let mut channel_icon = None;
2475
2476        let text = match section {
2477            Section::ActiveCall => {
2478                let channel_name = maybe!({
2479                    let channel_id = ActiveCall::global(cx).read(cx).channel_id(cx)?;
2480
2481                    let channel = self.channel_store.read(cx).channel_for_id(channel_id)?;
2482
2483                    channel_link = Some(channel.link(cx));
2484                    (channel_icon, channel_tooltip_text) = match channel.visibility {
2485                        proto::ChannelVisibility::Public => {
2486                            (Some("icons/public.svg"), Some("Copy public channel link."))
2487                        }
2488                        proto::ChannelVisibility::Members => {
2489                            (Some("icons/hash.svg"), Some("Copy private channel link."))
2490                        }
2491                    };
2492
2493                    Some(channel.name.as_ref())
2494                });
2495
2496                if let Some(name) = channel_name {
2497                    SharedString::from(name.to_string())
2498                } else {
2499                    SharedString::from("Current Call")
2500                }
2501            }
2502            Section::ContactRequests => SharedString::from("Requests"),
2503            Section::Contacts => SharedString::from("Contacts"),
2504            Section::Channels => SharedString::from("Channels"),
2505            Section::ChannelInvites => SharedString::from("Invites"),
2506            Section::Online => SharedString::from("Online"),
2507            Section::Offline => SharedString::from("Offline"),
2508        };
2509
2510        let button = match section {
2511            Section::ActiveCall => channel_link.map(|channel_link| {
2512                let channel_link_copy = channel_link.clone();
2513                IconButton::new("channel-link", IconName::Copy)
2514                    .icon_size(IconSize::Small)
2515                    .size(ButtonSize::None)
2516                    .visible_on_hover("section-header")
2517                    .on_click(move |_, _, cx| {
2518                        let item = ClipboardItem::new_string(channel_link_copy.clone());
2519                        cx.write_to_clipboard(item)
2520                    })
2521                    .tooltip(Tooltip::text("Copy channel link"))
2522                    .into_any_element()
2523            }),
2524            Section::Contacts => Some(
2525                IconButton::new("add-contact", IconName::Plus)
2526                    .on_click(
2527                        cx.listener(|this, _, window, cx| this.toggle_contact_finder(window, cx)),
2528                    )
2529                    .tooltip(Tooltip::text("Search for new contact"))
2530                    .into_any_element(),
2531            ),
2532            Section::Channels => Some(
2533                IconButton::new("add-channel", IconName::Plus)
2534                    .on_click(cx.listener(|this, _, window, cx| this.new_root_channel(window, cx)))
2535                    .tooltip(Tooltip::text("Create a channel"))
2536                    .into_any_element(),
2537            ),
2538            _ => None,
2539        };
2540
2541        let can_collapse = match section {
2542            Section::ActiveCall | Section::Channels | Section::Contacts => false,
2543            Section::ChannelInvites
2544            | Section::ContactRequests
2545            | Section::Online
2546            | Section::Offline => true,
2547        };
2548
2549        h_flex().w_full().group("section-header").child(
2550            ListHeader::new(text)
2551                .when(can_collapse, |header| {
2552                    header.toggle(Some(!is_collapsed)).on_toggle(cx.listener(
2553                        move |this, _, _, cx| {
2554                            this.toggle_section_expanded(section, cx);
2555                        },
2556                    ))
2557                })
2558                .inset(true)
2559                .end_slot::<AnyElement>(button)
2560                .toggle_state(is_selected),
2561        )
2562    }
2563
2564    fn render_contact(
2565        &self,
2566        contact: &Arc<Contact>,
2567        calling: bool,
2568        is_selected: bool,
2569        cx: &mut Context<Self>,
2570    ) -> impl IntoElement {
2571        let online = contact.online;
2572        let busy = contact.busy || calling;
2573        let github_login = contact.user.github_login.clone();
2574        let item = ListItem::new(github_login.clone())
2575            .indent_level(1)
2576            .indent_step_size(px(20.))
2577            .toggle_state(is_selected)
2578            .child(
2579                h_flex()
2580                    .w_full()
2581                    .justify_between()
2582                    .child(Label::new(github_login.clone()))
2583                    .when(calling, |el| {
2584                        el.child(Label::new("Calling").color(Color::Muted))
2585                    })
2586                    .when(!calling, |el| {
2587                        el.child(
2588                            IconButton::new("contact context menu", IconName::Ellipsis)
2589                                .icon_color(Color::Muted)
2590                                .visible_on_hover("")
2591                                .on_click(cx.listener({
2592                                    let contact = contact.clone();
2593                                    move |this, event: &ClickEvent, window, cx| {
2594                                        this.deploy_contact_context_menu(
2595                                            event.position(),
2596                                            contact.clone(),
2597                                            window,
2598                                            cx,
2599                                        );
2600                                    }
2601                                })),
2602                        )
2603                    }),
2604            )
2605            .on_secondary_mouse_down(cx.listener({
2606                let contact = contact.clone();
2607                move |this, event: &MouseDownEvent, window, cx| {
2608                    this.deploy_contact_context_menu(event.position, contact.clone(), window, cx);
2609                }
2610            }))
2611            .start_slot(
2612                // todo handle contacts with no avatar
2613                Avatar::new(contact.user.avatar_uri.clone())
2614                    .indicator::<AvatarAvailabilityIndicator>(if online {
2615                        Some(AvatarAvailabilityIndicator::new(match busy {
2616                            true => ui::CollaboratorAvailability::Busy,
2617                            false => ui::CollaboratorAvailability::Free,
2618                        }))
2619                    } else {
2620                        None
2621                    }),
2622            );
2623
2624        div()
2625            .id(github_login.clone())
2626            .group("")
2627            .child(item)
2628            .tooltip(move |_, cx| {
2629                let text = if !online {
2630                    format!(" {} is offline", &github_login)
2631                } else if busy {
2632                    format!(" {} is on a call", &github_login)
2633                } else {
2634                    let room = ActiveCall::global(cx).read(cx).room();
2635                    if room.is_some() {
2636                        format!("Invite {} to join call", &github_login)
2637                    } else {
2638                        format!("Call {}", &github_login)
2639                    }
2640                };
2641                Tooltip::simple(text, cx)
2642            })
2643    }
2644
2645    fn render_contact_request(
2646        &self,
2647        user: &Arc<User>,
2648        is_incoming: bool,
2649        is_selected: bool,
2650        cx: &mut Context<Self>,
2651    ) -> impl IntoElement {
2652        let github_login = user.github_login.clone();
2653        let user_id = user.id;
2654        let is_response_pending = self.user_store.read(cx).is_contact_request_pending(user);
2655        let color = if is_response_pending {
2656            Color::Muted
2657        } else {
2658            Color::Default
2659        };
2660
2661        let controls = if is_incoming {
2662            vec![
2663                IconButton::new("decline-contact", IconName::Close)
2664                    .on_click(cx.listener(move |this, _, window, cx| {
2665                        this.respond_to_contact_request(user_id, false, window, cx);
2666                    }))
2667                    .icon_color(color)
2668                    .tooltip(Tooltip::text("Decline invite")),
2669                IconButton::new("accept-contact", IconName::Check)
2670                    .on_click(cx.listener(move |this, _, window, cx| {
2671                        this.respond_to_contact_request(user_id, true, window, cx);
2672                    }))
2673                    .icon_color(color)
2674                    .tooltip(Tooltip::text("Accept invite")),
2675            ]
2676        } else {
2677            let github_login = github_login.clone();
2678            vec![
2679                IconButton::new("remove_contact", IconName::Close)
2680                    .on_click(cx.listener(move |this, _, window, cx| {
2681                        this.remove_contact(user_id, &github_login, window, cx);
2682                    }))
2683                    .icon_color(color)
2684                    .tooltip(Tooltip::text("Cancel invite")),
2685            ]
2686        };
2687
2688        ListItem::new(github_login.clone())
2689            .indent_level(1)
2690            .indent_step_size(px(20.))
2691            .toggle_state(is_selected)
2692            .child(
2693                h_flex()
2694                    .w_full()
2695                    .justify_between()
2696                    .child(Label::new(github_login.clone()))
2697                    .child(h_flex().children(controls)),
2698            )
2699            .start_slot(Avatar::new(user.avatar_uri.clone()))
2700    }
2701
2702    fn render_channel_invite(
2703        &self,
2704        channel: &Arc<Channel>,
2705        is_selected: bool,
2706        cx: &mut Context<Self>,
2707    ) -> ListItem {
2708        let channel_id = channel.id;
2709        let response_is_pending = self
2710            .channel_store
2711            .read(cx)
2712            .has_pending_channel_invite_response(channel);
2713        let color = if response_is_pending {
2714            Color::Muted
2715        } else {
2716            Color::Default
2717        };
2718
2719        let controls = [
2720            IconButton::new("reject-invite", IconName::Close)
2721                .on_click(cx.listener(move |this, _, _, cx| {
2722                    this.respond_to_channel_invite(channel_id, false, cx);
2723                }))
2724                .icon_color(color)
2725                .tooltip(Tooltip::text("Decline invite")),
2726            IconButton::new("accept-invite", IconName::Check)
2727                .on_click(cx.listener(move |this, _, _, cx| {
2728                    this.respond_to_channel_invite(channel_id, true, cx);
2729                }))
2730                .icon_color(color)
2731                .tooltip(Tooltip::text("Accept invite")),
2732        ];
2733
2734        ListItem::new(("channel-invite", channel.id.0 as usize))
2735            .toggle_state(is_selected)
2736            .child(
2737                h_flex()
2738                    .w_full()
2739                    .justify_between()
2740                    .child(Label::new(channel.name.clone()))
2741                    .child(h_flex().children(controls)),
2742            )
2743            .start_slot(
2744                Icon::new(IconName::Hash)
2745                    .size(IconSize::Small)
2746                    .color(Color::Muted),
2747            )
2748    }
2749
2750    fn render_contact_placeholder(&self, is_selected: bool, cx: &mut Context<Self>) -> ListItem {
2751        ListItem::new("contact-placeholder")
2752            .child(Icon::new(IconName::Plus))
2753            .child(Label::new("Add a Contact"))
2754            .toggle_state(is_selected)
2755            .on_click(cx.listener(|this, _, window, cx| this.toggle_contact_finder(window, cx)))
2756    }
2757
2758    fn render_channel(
2759        &self,
2760        channel: &Channel,
2761        depth: usize,
2762        has_children: bool,
2763        is_selected: bool,
2764        ix: usize,
2765        cx: &mut Context<Self>,
2766    ) -> impl IntoElement {
2767        let channel_id = channel.id;
2768
2769        let is_active = maybe!({
2770            let call_channel = ActiveCall::global(cx)
2771                .read(cx)
2772                .room()?
2773                .read(cx)
2774                .channel_id()?;
2775            Some(call_channel == channel_id)
2776        })
2777        .unwrap_or(false);
2778        let channel_store = self.channel_store.read(cx);
2779        let is_public = channel_store
2780            .channel_for_id(channel_id)
2781            .map(|channel| channel.visibility)
2782            == Some(proto::ChannelVisibility::Public);
2783        let disclosed =
2784            has_children.then(|| self.collapsed_channels.binary_search(&channel.id).is_err());
2785
2786        let has_messages_notification = channel_store.has_new_messages(channel_id);
2787        let has_notes_notification = channel_store.has_channel_buffer_changed(channel_id);
2788
2789        const FACEPILE_LIMIT: usize = 3;
2790        let participants = self.channel_store.read(cx).channel_participants(channel_id);
2791
2792        let face_pile = if participants.is_empty() {
2793            None
2794        } else {
2795            let extra_count = participants.len().saturating_sub(FACEPILE_LIMIT);
2796            let result = Facepile::new(
2797                participants
2798                    .iter()
2799                    .map(|user| Avatar::new(user.avatar_uri.clone()).into_any_element())
2800                    .take(FACEPILE_LIMIT)
2801                    .chain(if extra_count > 0 {
2802                        Some(
2803                            Label::new(format!("+{extra_count}"))
2804                                .ml_2()
2805                                .into_any_element(),
2806                        )
2807                    } else {
2808                        None
2809                    })
2810                    .collect::<SmallVec<_>>(),
2811            );
2812
2813            Some(result)
2814        };
2815
2816        let width = self.width.unwrap_or(px(240.));
2817        let root_id = channel.root_id();
2818
2819        div()
2820            .h_6()
2821            .id(channel_id.0 as usize)
2822            .group("")
2823            .flex()
2824            .w_full()
2825            .when(!channel.is_root_channel(), |el| {
2826                el.on_drag(channel.clone(), move |channel, _, _, cx| {
2827                    cx.new(|_| DraggedChannelView {
2828                        channel: channel.clone(),
2829                        width,
2830                    })
2831                })
2832            })
2833            .drag_over::<Channel>({
2834                move |style, dragged_channel: &Channel, _window, cx| {
2835                    if dragged_channel.root_id() == root_id {
2836                        style.bg(cx.theme().colors().ghost_element_hover)
2837                    } else {
2838                        style
2839                    }
2840                }
2841            })
2842            .on_drop(
2843                cx.listener(move |this, dragged_channel: &Channel, window, cx| {
2844                    if dragged_channel.root_id() != root_id {
2845                        return;
2846                    }
2847                    this.move_channel(dragged_channel.id, channel_id, window, cx);
2848                }),
2849            )
2850            .child(
2851                ListItem::new(channel_id.0 as usize)
2852                    // Add one level of depth for the disclosure arrow.
2853                    .indent_level(depth + 1)
2854                    .indent_step_size(px(20.))
2855                    .toggle_state(is_selected || is_active)
2856                    .toggle(disclosed)
2857                    .on_toggle(cx.listener(move |this, _, window, cx| {
2858                        this.toggle_channel_collapsed(channel_id, window, cx)
2859                    }))
2860                    .on_click(cx.listener(move |this, _, window, cx| {
2861                        if is_active {
2862                            this.open_channel_notes(channel_id, window, cx)
2863                        } else {
2864                            this.join_channel(channel_id, window, cx)
2865                        }
2866                    }))
2867                    .on_secondary_mouse_down(cx.listener(
2868                        move |this, event: &MouseDownEvent, window, cx| {
2869                            this.deploy_channel_context_menu(
2870                                event.position,
2871                                channel_id,
2872                                ix,
2873                                window,
2874                                cx,
2875                            )
2876                        },
2877                    ))
2878                    .start_slot(
2879                        div()
2880                            .relative()
2881                            .child(
2882                                Icon::new(if is_public {
2883                                    IconName::Public
2884                                } else {
2885                                    IconName::Hash
2886                                })
2887                                .size(IconSize::Small)
2888                                .color(Color::Muted),
2889                            )
2890                            .children(has_notes_notification.then(|| {
2891                                div()
2892                                    .w_1p5()
2893                                    .absolute()
2894                                    .right(px(-1.))
2895                                    .top(px(-1.))
2896                                    .child(Indicator::dot().color(Color::Info))
2897                            })),
2898                    )
2899                    .child(
2900                        h_flex()
2901                            .id(channel_id.0 as usize)
2902                            .child(Label::new(channel.name.clone()))
2903                            .children(face_pile.map(|face_pile| face_pile.p_1())),
2904                    ),
2905            )
2906            .child(
2907                h_flex().absolute().right(rems(0.)).h_full().child(
2908                    h_flex()
2909                        .h_full()
2910                        .gap_1()
2911                        .px_1()
2912                        .child(
2913                            IconButton::new("channel_chat", IconName::Chat)
2914                                .style(ButtonStyle::Filled)
2915                                .shape(ui::IconButtonShape::Square)
2916                                .icon_size(IconSize::Small)
2917                                .icon_color(if has_messages_notification {
2918                                    Color::Default
2919                                } else {
2920                                    Color::Muted
2921                                })
2922                                .on_click(cx.listener(move |this, _, window, cx| {
2923                                    this.join_channel_chat(channel_id, window, cx)
2924                                }))
2925                                .tooltip(Tooltip::text("Open channel chat"))
2926                                .visible_on_hover(""),
2927                        )
2928                        .child(
2929                            IconButton::new("channel_notes", IconName::Reader)
2930                                .style(ButtonStyle::Filled)
2931                                .shape(ui::IconButtonShape::Square)
2932                                .icon_size(IconSize::Small)
2933                                .icon_color(if has_notes_notification {
2934                                    Color::Default
2935                                } else {
2936                                    Color::Muted
2937                                })
2938                                .on_click(cx.listener(move |this, _, window, cx| {
2939                                    this.open_channel_notes(channel_id, window, cx)
2940                                }))
2941                                .tooltip(Tooltip::text("Open channel notes"))
2942                                .visible_on_hover(""),
2943                        ),
2944                ),
2945            )
2946            .tooltip({
2947                let channel_store = self.channel_store.clone();
2948                move |_window, cx| {
2949                    cx.new(|_| JoinChannelTooltip {
2950                        channel_store: channel_store.clone(),
2951                        channel_id,
2952                        has_notes_notification,
2953                    })
2954                    .into()
2955                }
2956            })
2957    }
2958
2959    fn render_channel_editor(
2960        &self,
2961        depth: usize,
2962        _window: &mut Window,
2963        _cx: &mut Context<Self>,
2964    ) -> impl IntoElement {
2965        let item = ListItem::new("channel-editor")
2966            .inset(false)
2967            // Add one level of depth for the disclosure arrow.
2968            .indent_level(depth + 1)
2969            .indent_step_size(px(20.))
2970            .start_slot(
2971                Icon::new(IconName::Hash)
2972                    .size(IconSize::Small)
2973                    .color(Color::Muted),
2974            );
2975
2976        if let Some(pending_name) = self
2977            .channel_editing_state
2978            .as_ref()
2979            .and_then(|state| state.pending_name())
2980        {
2981            item.child(Label::new(pending_name))
2982        } else {
2983            item.child(self.channel_name_editor.clone())
2984        }
2985    }
2986}
2987
2988fn render_tree_branch(
2989    is_last: bool,
2990    overdraw: bool,
2991    window: &mut Window,
2992    cx: &mut App,
2993) -> impl IntoElement {
2994    let rem_size = window.rem_size();
2995    let line_height = window.text_style().line_height_in_pixels(rem_size);
2996    let width = rem_size * 1.5;
2997    let thickness = px(1.);
2998    let color = cx.theme().colors().text;
2999
3000    canvas(
3001        |_, _, _| {},
3002        move |bounds, _, window, _| {
3003            let start_x = (bounds.left() + bounds.right() - thickness) / 2.;
3004            let start_y = (bounds.top() + bounds.bottom() - thickness) / 2.;
3005            let right = bounds.right();
3006            let top = bounds.top();
3007
3008            window.paint_quad(fill(
3009                Bounds::from_corners(
3010                    point(start_x, top),
3011                    point(
3012                        start_x + thickness,
3013                        if is_last {
3014                            start_y
3015                        } else {
3016                            bounds.bottom() + if overdraw { px(1.) } else { px(0.) }
3017                        },
3018                    ),
3019                ),
3020                color,
3021            ));
3022            window.paint_quad(fill(
3023                Bounds::from_corners(point(start_x, start_y), point(right, start_y + thickness)),
3024                color,
3025            ));
3026        },
3027    )
3028    .w(width)
3029    .h(line_height)
3030}
3031
3032impl Render for CollabPanel {
3033    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3034        v_flex()
3035            .key_context(self.dispatch_context(window, cx))
3036            .on_action(cx.listener(CollabPanel::cancel))
3037            .on_action(cx.listener(CollabPanel::select_next))
3038            .on_action(cx.listener(CollabPanel::select_previous))
3039            .on_action(cx.listener(CollabPanel::confirm))
3040            .on_action(cx.listener(CollabPanel::insert_space))
3041            .on_action(cx.listener(CollabPanel::remove_selected_channel))
3042            .on_action(cx.listener(CollabPanel::show_inline_context_menu))
3043            .on_action(cx.listener(CollabPanel::rename_selected_channel))
3044            .on_action(cx.listener(CollabPanel::collapse_selected_channel))
3045            .on_action(cx.listener(CollabPanel::expand_selected_channel))
3046            .on_action(cx.listener(CollabPanel::start_move_selected_channel))
3047            .on_action(cx.listener(CollabPanel::move_channel_up))
3048            .on_action(cx.listener(CollabPanel::move_channel_down))
3049            .track_focus(&self.focus_handle)
3050            .size_full()
3051            .child(if !self.client.status().borrow().is_connected() {
3052                self.render_signed_out(cx)
3053            } else {
3054                self.render_signed_in(window, cx)
3055            })
3056            .children(self.context_menu.as_ref().map(|(menu, position, _)| {
3057                deferred(
3058                    anchored()
3059                        .position(*position)
3060                        .anchor(gpui::Corner::TopLeft)
3061                        .child(menu.clone()),
3062                )
3063                .with_priority(1)
3064            }))
3065    }
3066}
3067
3068impl EventEmitter<PanelEvent> for CollabPanel {}
3069
3070impl Panel for CollabPanel {
3071    fn position(&self, _window: &Window, cx: &App) -> DockPosition {
3072        CollaborationPanelSettings::get_global(cx).dock
3073    }
3074
3075    fn position_is_valid(&self, position: DockPosition) -> bool {
3076        matches!(position, DockPosition::Left | DockPosition::Right)
3077    }
3078
3079    fn set_position(
3080        &mut self,
3081        position: DockPosition,
3082        _window: &mut Window,
3083        cx: &mut Context<Self>,
3084    ) {
3085        settings::update_settings_file::<CollaborationPanelSettings>(
3086            self.fs.clone(),
3087            cx,
3088            move |settings, _| settings.dock = Some(position),
3089        );
3090    }
3091
3092    fn size(&self, _window: &Window, cx: &App) -> Pixels {
3093        self.width
3094            .unwrap_or_else(|| CollaborationPanelSettings::get_global(cx).default_width)
3095    }
3096
3097    fn set_size(&mut self, size: Option<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
3098        self.width = size;
3099        cx.notify();
3100        cx.defer_in(window, |this, _, cx| {
3101            this.serialize(cx);
3102        });
3103    }
3104
3105    fn icon(&self, _window: &Window, cx: &App) -> Option<ui::IconName> {
3106        CollaborationPanelSettings::get_global(cx)
3107            .button
3108            .then_some(ui::IconName::UserGroup)
3109    }
3110
3111    fn icon_tooltip(&self, _window: &Window, _cx: &App) -> Option<&'static str> {
3112        Some("Collab Panel")
3113    }
3114
3115    fn toggle_action(&self) -> Box<dyn gpui::Action> {
3116        Box::new(ToggleFocus)
3117    }
3118
3119    fn persistent_name() -> &'static str {
3120        "CollabPanel"
3121    }
3122
3123    fn activation_priority(&self) -> u32 {
3124        6
3125    }
3126}
3127
3128impl Focusable for CollabPanel {
3129    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
3130        self.filter_editor.focus_handle(cx).clone()
3131    }
3132}
3133
3134impl PartialEq for ListEntry {
3135    fn eq(&self, other: &Self) -> bool {
3136        match self {
3137            ListEntry::Header(section_1) => {
3138                if let ListEntry::Header(section_2) = other {
3139                    return section_1 == section_2;
3140                }
3141            }
3142            ListEntry::CallParticipant { user: user_1, .. } => {
3143                if let ListEntry::CallParticipant { user: user_2, .. } = other {
3144                    return user_1.id == user_2.id;
3145                }
3146            }
3147            ListEntry::ParticipantProject {
3148                project_id: project_id_1,
3149                ..
3150            } => {
3151                if let ListEntry::ParticipantProject {
3152                    project_id: project_id_2,
3153                    ..
3154                } = other
3155                {
3156                    return project_id_1 == project_id_2;
3157                }
3158            }
3159            ListEntry::ParticipantScreen {
3160                peer_id: peer_id_1, ..
3161            } => {
3162                if let ListEntry::ParticipantScreen {
3163                    peer_id: peer_id_2, ..
3164                } = other
3165                {
3166                    return peer_id_1 == peer_id_2;
3167                }
3168            }
3169            ListEntry::Channel {
3170                channel: channel_1, ..
3171            } => {
3172                if let ListEntry::Channel {
3173                    channel: channel_2, ..
3174                } = other
3175                {
3176                    return channel_1.id == channel_2.id;
3177                }
3178            }
3179            ListEntry::ChannelNotes { channel_id } => {
3180                if let ListEntry::ChannelNotes {
3181                    channel_id: other_id,
3182                } = other
3183                {
3184                    return channel_id == other_id;
3185                }
3186            }
3187            ListEntry::ChannelChat { channel_id } => {
3188                if let ListEntry::ChannelChat {
3189                    channel_id: other_id,
3190                } = other
3191                {
3192                    return channel_id == other_id;
3193                }
3194            }
3195            ListEntry::ChannelInvite(channel_1) => {
3196                if let ListEntry::ChannelInvite(channel_2) = other {
3197                    return channel_1.id == channel_2.id;
3198                }
3199            }
3200            ListEntry::IncomingRequest(user_1) => {
3201                if let ListEntry::IncomingRequest(user_2) = other {
3202                    return user_1.id == user_2.id;
3203                }
3204            }
3205            ListEntry::OutgoingRequest(user_1) => {
3206                if let ListEntry::OutgoingRequest(user_2) = other {
3207                    return user_1.id == user_2.id;
3208                }
3209            }
3210            ListEntry::Contact {
3211                contact: contact_1, ..
3212            } => {
3213                if let ListEntry::Contact {
3214                    contact: contact_2, ..
3215                } = other
3216                {
3217                    return contact_1.user.id == contact_2.user.id;
3218                }
3219            }
3220            ListEntry::ChannelEditor { depth } => {
3221                if let ListEntry::ChannelEditor { depth: other_depth } = other {
3222                    return depth == other_depth;
3223                }
3224            }
3225            ListEntry::ContactPlaceholder => {
3226                if let ListEntry::ContactPlaceholder = other {
3227                    return true;
3228                }
3229            }
3230        }
3231        false
3232    }
3233}
3234
3235struct DraggedChannelView {
3236    channel: Channel,
3237    width: Pixels,
3238}
3239
3240impl Render for DraggedChannelView {
3241    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3242        let ui_font = ThemeSettings::get_global(cx).ui_font.family.clone();
3243        h_flex()
3244            .font_family(ui_font)
3245            .bg(cx.theme().colors().background)
3246            .w(self.width)
3247            .p_1()
3248            .gap_1()
3249            .child(
3250                Icon::new(
3251                    if self.channel.visibility == proto::ChannelVisibility::Public {
3252                        IconName::Public
3253                    } else {
3254                        IconName::Hash
3255                    },
3256                )
3257                .size(IconSize::Small)
3258                .color(Color::Muted),
3259            )
3260            .child(Label::new(self.channel.name.clone()))
3261    }
3262}
3263
3264struct JoinChannelTooltip {
3265    channel_store: Entity<ChannelStore>,
3266    channel_id: ChannelId,
3267    #[allow(unused)]
3268    has_notes_notification: bool,
3269}
3270
3271impl Render for JoinChannelTooltip {
3272    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3273        tooltip_container(window, cx, |container, _, cx| {
3274            let participants = self
3275                .channel_store
3276                .read(cx)
3277                .channel_participants(self.channel_id);
3278
3279            container
3280                .child(Label::new("Join channel"))
3281                .children(participants.iter().map(|participant| {
3282                    h_flex()
3283                        .gap_2()
3284                        .child(Avatar::new(participant.avatar_uri.clone()))
3285                        .child(Label::new(participant.github_login.clone()))
3286                }))
3287        })
3288    }
3289}