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