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