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