Fix focus handle leak (#26090)

This fixes a major performance issue in the current git beta.
This PR also removes the PopoverButton component, which was easy to
misuse.

Release Notes:

- Git Beta: Fix frame drops caused by opening the git panel

---------

Co-authored-by: Mikayla Maki <mikayla.c.maki@gmail.com>
This commit is contained in:
Conrad Irwin 2025-03-04 17:50:26 -07:00 committed by GitHub
parent fe18c73a07
commit 674fb7621f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 276 additions and 459 deletions

View file

@ -1,18 +1,16 @@
use anyhow::{Context as _, Result};
use anyhow::Context as _;
use fuzzy::{StringMatch, StringMatchCandidate};
use git::repository::Branch;
use gpui::{
rems, App, AsyncApp, Context, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable,
rems, App, Context, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable,
InteractiveElement, IntoElement, ParentElement, Render, SharedString, Styled, Subscription,
Task, Window,
};
use picker::{Picker, PickerDelegate};
use project::{Project, ProjectPath};
use std::sync::Arc;
use ui::{
prelude::*, HighlightedLabel, ListItem, ListItemSpacing, PopoverMenuHandle, TriggerablePopover,
};
use ui::{prelude::*, HighlightedLabel, ListItem, ListItemSpacing, PopoverMenuHandle};
use util::ResultExt;
use workspace::notifications::DetachAndPromptErr;
use workspace::{ModalView, Workspace};
@ -31,35 +29,16 @@ pub fn open(
cx: &mut Context<Workspace>,
) {
let project = workspace.project().clone();
let this = cx.entity();
let style = BranchListStyle::Modal;
cx.spawn_in(window, |_, mut cx| async move {
// Modal branch picker has a longer trailoff than a popover one.
let delegate = BranchListDelegate::new(project.clone(), style, 70, &cx).await?;
this.update_in(&mut cx, move |workspace, window, cx| {
workspace.toggle_modal(window, cx, |window, cx| {
let picker = cx.new(|cx| Picker::uniform_list(delegate, window, cx));
let _subscription = cx.subscribe(&picker, |_, _, _, cx| {
cx.emit(DismissEvent);
});
let mut list = BranchList::new(project, style, 34., cx);
list._subscription = Some(_subscription);
list.picker = Some(picker);
list
})
})?;
Ok(())
workspace.toggle_modal(window, cx, |window, cx| {
BranchList::new(project, style, 34., window, cx)
})
.detach_and_prompt_err("Failed to read branches", window, cx, |_, _, _| None)
}
pub fn popover(project: Entity<Project>, window: &mut Window, cx: &mut App) -> Entity<BranchList> {
cx.new(|cx| {
let mut list = BranchList::new(project, BranchListStyle::Popover, 15., cx);
list.reload_branches(window, cx);
let list = BranchList::new(project, BranchListStyle::Popover, 15., window, cx);
list.focus_handle(cx).focus(window);
list
})
}
@ -72,59 +51,54 @@ enum BranchListStyle {
pub struct BranchList {
rem_width: f32,
popover_handle: PopoverMenuHandle<Self>,
default_focus_handle: FocusHandle,
project: Entity<Project>,
style: BranchListStyle,
pub picker: Option<Entity<Picker<BranchListDelegate>>>,
_subscription: Option<Subscription>,
}
impl TriggerablePopover for BranchList {
fn menu_handle(
&mut self,
_window: &mut Window,
_cx: &mut gpui::Context<Self>,
) -> PopoverMenuHandle<Self> {
self.popover_handle.clone()
}
pub popover_handle: PopoverMenuHandle<Self>,
pub picker: Entity<Picker<BranchListDelegate>>,
_subscription: Subscription,
}
impl BranchList {
fn new(project: Entity<Project>, style: BranchListStyle, rem_width: f32, cx: &mut App) -> Self {
fn new(
project_handle: Entity<Project>,
style: BranchListStyle,
rem_width: f32,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let popover_handle = PopoverMenuHandle::default();
Self {
project,
picker: None,
rem_width,
popover_handle,
default_focus_handle: cx.focus_handle(),
style,
_subscription: None,
}
}
let project = project_handle.read(cx);
let all_branches_request = project
.visible_worktrees(cx)
.next()
.map(|worktree| project.branches(ProjectPath::root_path(worktree.read(cx).id()), cx))
.context("No worktrees found");
fn reload_branches(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let project = self.project.clone();
let style = self.style;
cx.spawn_in(window, |this, mut cx| async move {
let delegate = BranchListDelegate::new(project, style, 20, &cx).await?;
let picker =
cx.new_window_entity(|window, cx| Picker::uniform_list(delegate, window, cx))?;
let all_branches = all_branches_request?.await?;
this.update(&mut cx, |branch_list, cx| {
let subscription =
cx.subscribe(&picker, |_, _, _: &DismissEvent, cx| cx.emit(DismissEvent));
branch_list.picker = Some(picker);
branch_list._subscription = Some(subscription);
cx.notify();
this.update_in(&mut cx, |this, window, cx| {
this.picker.update(cx, |picker, cx| {
picker.delegate.all_branches = Some(all_branches);
picker.refresh(window, cx);
})
})?;
anyhow::Ok(())
})
.detach_and_log_err(cx);
let delegate = BranchListDelegate::new(project_handle.clone(), style, 20);
let picker = cx.new(|cx| Picker::uniform_list(delegate, window, cx));
let _subscription = cx.subscribe(&picker, |_, _, _, cx| {
cx.emit(DismissEvent);
});
Self {
picker,
rem_width,
popover_handle,
_subscription,
}
}
}
impl ModalView for BranchList {}
@ -132,10 +106,7 @@ impl EventEmitter<DismissEvent> for BranchList {}
impl Focusable for BranchList {
fn focus_handle(&self, cx: &App) -> FocusHandle {
self.picker
.as_ref()
.map(|picker| picker.focus_handle(cx))
.unwrap_or_else(|| self.default_focus_handle.clone())
self.picker.focus_handle(cx)
}
}
@ -143,24 +114,13 @@ impl Render for BranchList {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
v_flex()
.w(rems(self.rem_width))
.map(|parent| match self.picker.as_ref() {
Some(picker) => parent.child(picker.clone()).on_mouse_down_out({
let picker = picker.clone();
cx.listener(move |_, _, window, cx| {
picker.update(cx, |this, cx| {
this.cancel(&Default::default(), window, cx);
})
.child(self.picker.clone())
.on_mouse_down_out({
cx.listener(move |this, _, window, cx| {
this.picker.update(cx, |this, cx| {
this.cancel(&Default::default(), window, cx);
})
}),
None => parent.child(
h_flex()
.id("branch-picker-error")
.on_click(
cx.listener(|this, _, window, cx| this.reload_branches(window, cx)),
)
.child("Could not load branches.")
.child("Click to retry"),
),
})
})
}
}
@ -184,7 +144,7 @@ impl BranchEntry {
pub struct BranchListDelegate {
matches: Vec<BranchEntry>,
all_branches: Vec<Branch>,
all_branches: Option<Vec<Branch>>,
project: Entity<Project>,
style: BranchListStyle,
selected_index: usize,
@ -194,33 +154,20 @@ pub struct BranchListDelegate {
}
impl BranchListDelegate {
async fn new(
fn new(
project: Entity<Project>,
style: BranchListStyle,
branch_name_trailoff_after: usize,
cx: &AsyncApp,
) -> Result<Self> {
let all_branches_request = cx.update(|cx| {
let project = project.read(cx);
let first_worktree = project
.visible_worktrees(cx)
.next()
.context("No worktrees found")?;
let project_path = ProjectPath::root_path(first_worktree.read(cx).id());
anyhow::Ok(project.branches(project_path, cx))
})??;
let all_branches = all_branches_request.await?;
Ok(Self {
) -> Self {
Self {
matches: vec![],
project,
style,
all_branches,
all_branches: None,
selected_index: 0,
last_query: Default::default(),
branch_name_trailoff_after,
})
}
}
pub fn branch_count(&self) -> usize {
@ -261,32 +208,31 @@ impl PickerDelegate for BranchListDelegate {
window: &mut Window,
cx: &mut Context<Picker<Self>>,
) -> Task<()> {
let Some(mut all_branches) = self.all_branches.clone() else {
return Task::ready(());
};
cx.spawn_in(window, move |picker, mut cx| async move {
let candidates = picker.update(&mut cx, |picker, _| {
const RECENT_BRANCHES_COUNT: usize = 10;
let mut branches = picker.delegate.all_branches.clone();
if query.is_empty() {
if branches.len() > RECENT_BRANCHES_COUNT {
// Truncate list of recent branches
// Do a partial sort to show recent-ish branches first.
branches.select_nth_unstable_by(RECENT_BRANCHES_COUNT - 1, |lhs, rhs| {
rhs.priority_key().cmp(&lhs.priority_key())
});
branches.truncate(RECENT_BRANCHES_COUNT);
}
branches.sort_unstable_by(|lhs, rhs| {
rhs.is_head.cmp(&lhs.is_head).then(lhs.name.cmp(&rhs.name))
const RECENT_BRANCHES_COUNT: usize = 10;
if query.is_empty() {
if all_branches.len() > RECENT_BRANCHES_COUNT {
// Truncate list of recent branches
// Do a partial sort to show recent-ish branches first.
all_branches.select_nth_unstable_by(RECENT_BRANCHES_COUNT - 1, |lhs, rhs| {
rhs.priority_key().cmp(&lhs.priority_key())
});
all_branches.truncate(RECENT_BRANCHES_COUNT);
}
branches
.into_iter()
.enumerate()
.map(|(ix, command)| StringMatchCandidate::new(ix, &command.name))
.collect::<Vec<StringMatchCandidate>>()
});
let Some(candidates) = candidates.log_err() else {
return;
};
all_branches.sort_unstable_by(|lhs, rhs| {
rhs.is_head.cmp(&lhs.is_head).then(lhs.name.cmp(&rhs.name))
});
}
let candidates = all_branches
.into_iter()
.enumerate()
.map(|(ix, command)| StringMatchCandidate::new(ix, &command.name))
.collect::<Vec<StringMatchCandidate>>();
let matches: Vec<BranchEntry> = if query.is_empty() {
candidates
.into_iter()

View file

@ -5,7 +5,7 @@ use crate::git_panel::{commit_message_editor, GitPanel};
use git::{Commit, ShowCommitEditor};
use panel::{panel_button, panel_editor_style, panel_filled_button};
use project::Project;
use ui::{prelude::*, KeybindingHint, PopoverButton, Tooltip, TriggerablePopover};
use ui::{prelude::*, KeybindingHint, PopoverMenu, Tooltip};
use editor::{Editor, EditorElement};
use gpui::*;
@ -265,12 +265,20 @@ impl CommitModal {
}))
.style(ButtonStyle::Transparent);
let branch_picker = PopoverButton::new(
self.branch_list.clone(),
Corner::BottomLeft,
branch_picker_button,
Tooltip::for_action_title("Switch Branch", &zed_actions::git::Branch),
);
let branch_picker = PopoverMenu::new("popover-button")
.menu({
let branch_list = self.branch_list.clone();
move |_window, _cx| Some(branch_list.clone())
})
.trigger_with_tooltip(
branch_picker_button,
Tooltip::for_action_title("Switch Branch", &zed_actions::git::Branch),
)
.anchor(Corner::BottomLeft)
.offset(gpui::Point {
x: px(0.0),
y: px(-2.0),
});
let close_kb_hint =
if let Some(close_kb) = ui::KeyBinding::for_action(&menu::Cancel, window, cx) {
@ -305,12 +313,7 @@ impl CommitModal {
.w_full()
.h(px(self.properties.footer_height))
.gap_1()
.child(
h_flex()
.gap_1()
.child(branch_picker.render(window, cx))
.children(co_authors),
)
.child(h_flex().gap_1().child(branch_picker).children(co_authors))
.child(div().flex_1())
.child(
h_flex()
@ -351,7 +354,7 @@ impl Render for CommitModal {
.on_action(
cx.listener(|this, _: &zed_actions::git::Branch, window, cx| {
this.branch_list.update(cx, |branch_list, cx| {
branch_list.menu_handle(window, cx).toggle(window, cx);
branch_list.popover_handle.toggle(window, cx);
})
}),
)

View file

@ -1,7 +1,6 @@
use crate::branch_picker::{self, BranchList};
use crate::branch_picker::{self};
use crate::git_panel_settings::StatusStyle;
use crate::remote_output_toast::{RemoteAction, RemoteOutputToast};
use crate::repository_selector::RepositorySelectorPopoverMenu;
use crate::{
git_panel_settings::GitPanelSettings, git_status_icon, repository_selector::RepositorySelector,
};
@ -41,8 +40,8 @@ use std::{collections::HashSet, sync::Arc, time::Duration, usize};
use strum::{IntoEnumIterator, VariantNames};
use time::OffsetDateTime;
use ui::{
prelude::*, ButtonLike, Checkbox, ContextMenu, ElevationIndex, PopoverButton, PopoverMenu,
Scrollbar, ScrollbarState, Tooltip,
prelude::*, ButtonLike, Checkbox, ContextMenu, ElevationIndex, PopoverMenu, Scrollbar,
ScrollbarState, Tooltip,
};
use util::{maybe, post_inc, ResultExt, TryFutureExt};
@ -206,7 +205,6 @@ pub struct GitPanel {
pending_commit: Option<Task<()>>,
pending_serialization: Task<Option<()>>,
pub(crate) project: Entity<Project>,
repository_selector: Entity<RepositorySelector>,
scroll_handle: UniformListScrollHandle,
scrollbar_state: ScrollbarState,
selected_entry: Option<usize>,
@ -311,9 +309,6 @@ impl GitPanel {
let scrollbar_state =
ScrollbarState::new(scroll_handle.clone()).parent_entity(&cx.entity());
let repository_selector =
cx.new(|cx| RepositorySelector::new(project.clone(), window, cx));
let mut git_panel = Self {
pending_remote_operations: Default::default(),
remote_operation_id: 0,
@ -333,7 +328,6 @@ impl GitPanel {
pending_commit: None,
pending_serialization: Task::ready(None),
project,
repository_selector,
scroll_handle,
scrollbar_state,
selected_entry: None,
@ -2039,14 +2033,13 @@ impl GitPanel {
.display_name(project, cx)
.trim_end_matches("/"),
));
let branches = branch_picker::popover(self.project.clone(), window, cx);
let footer = v_flex()
.child(PanelRepoFooter::new(
"footer-button",
display_name,
branch,
Some(git_panel),
Some(branches),
))
.child(
panel_editor_container(window, cx)
@ -3072,7 +3065,6 @@ pub struct PanelRepoFooter {
//
// For now just take an option here, and we won't bind handlers to buttons in previews.
git_panel: Option<Entity<GitPanel>>,
branches: Option<Entity<BranchList>>,
}
impl PanelRepoFooter {
@ -3081,14 +3073,12 @@ impl PanelRepoFooter {
active_repository: SharedString,
branch: Option<Branch>,
git_panel: Option<Entity<GitPanel>>,
branches: Option<Entity<BranchList>>,
) -> Self {
Self {
id: id.into(),
active_repository,
branch,
git_panel,
branches,
}
}
@ -3102,7 +3092,6 @@ impl PanelRepoFooter {
active_repository,
branch,
git_panel: None,
branches: None,
}
}
@ -3324,7 +3313,7 @@ impl PanelRepoFooter {
}
impl RenderOnce for PanelRepoFooter {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let active_repo = self.active_repository.clone();
let overflow_menu_id: SharedString = format!("overflow-menu-{}", active_repo).into();
let repo_selector_trigger = Button::new("repo-selector", active_repo)
@ -3333,29 +3322,36 @@ impl RenderOnce for PanelRepoFooter {
.label_size(LabelSize::Small)
.color(Color::Muted);
let repo_selector = if let Some(panel) = self.git_panel.clone() {
let repo_selector = panel.read(cx).repository_selector.clone();
let repo_count = repo_selector.read(cx).repositories_len(cx);
let single_repo = repo_count == 1;
let project = self
.git_panel
.as_ref()
.map(|panel| panel.read(cx).project.clone());
RepositorySelectorPopoverMenu::new(
panel.read(cx).repository_selector.clone(),
let single_repo = project
.as_ref()
.map(|project| project.read(cx).all_repositories(cx).len() == 1)
.unwrap_or(true);
let repo_selector = PopoverMenu::new("repository-switcher")
.menu({
let project = project.clone();
move |window, cx| {
let project = project.clone()?;
Some(cx.new(|cx| RepositorySelector::new(project, window, cx)))
}
})
.trigger_with_tooltip(
repo_selector_trigger.disabled(single_repo).truncate(true),
Tooltip::text("Switch active repository"),
)
.into_any_element()
} else {
// for rendering preview, we don't have git_panel there
repo_selector_trigger.into_any_element()
};
.attach(gpui::Corner::BottomLeft)
.into_any_element();
let branch = self.branch.clone();
let branch_name = branch
.as_ref()
.map_or(" (no branch)".into(), |branch| branch.name.clone());
let branches = self.branches.clone();
let branch_selector_button = Button::new("branch-selector", branch_name)
.style(ButtonStyle::Transparent)
.size(ButtonSize::None)
@ -3369,18 +3365,17 @@ impl RenderOnce for PanelRepoFooter {
window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
});
let branch_selector = if let Some(branches) = branches {
PopoverButton::new(
branches,
Corner::BottomLeft,
let branch_selector = PopoverMenu::new("popover-button")
.menu(move |window, cx| Some(branch_picker::popover(project.clone()?, window, cx)))
.trigger_with_tooltip(
branch_selector_button,
Tooltip::for_action_title("Switch Branch", &zed_actions::git::Branch),
)
.render(window, cx)
.into_any_element()
} else {
branch_selector_button.into_any_element()
};
.anchor(Corner::TopLeft)
.offset(gpui::Point {
x: px(0.0),
y: px(-2.0),
});
let spinner = self
.git_panel

View file

@ -1,6 +1,6 @@
use gpui::{
AnyElement, AnyView, App, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable,
Subscription, Task, WeakEntity,
AnyElement, App, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, Subscription,
Task, WeakEntity,
};
use picker::{Picker, PickerDelegate};
use project::{
@ -8,7 +8,7 @@ use project::{
Project,
};
use std::sync::Arc;
use ui::{prelude::*, ListItem, ListItemSpacing, PopoverMenu, PopoverMenuHandle, PopoverTrigger};
use ui::{prelude::*, ListItem, ListItemSpacing};
pub struct RepositorySelector {
picker: Entity<Picker<RepositorySelectorDelegate>>,
@ -47,10 +47,6 @@ impl RepositorySelector {
}
}
pub(crate) fn repositories_len(&self, cx: &App) -> usize {
self.picker.read(cx).delegate.repository_entries.len()
}
fn handle_project_git_event(
&mut self,
git_store: &Entity<GitStore>,
@ -82,54 +78,6 @@ impl Render for RepositorySelector {
}
}
#[derive(IntoElement)]
pub struct RepositorySelectorPopoverMenu<T, TT>
where
T: PopoverTrigger + ButtonCommon,
TT: Fn(&mut Window, &mut App) -> AnyView + 'static,
{
repository_selector: Entity<RepositorySelector>,
trigger: T,
tooltip: TT,
handle: Option<PopoverMenuHandle<RepositorySelector>>,
}
impl<T, TT> RepositorySelectorPopoverMenu<T, TT>
where
T: PopoverTrigger + ButtonCommon,
TT: Fn(&mut Window, &mut App) -> AnyView + 'static,
{
pub fn new(repository_selector: Entity<RepositorySelector>, trigger: T, tooltip: TT) -> Self {
Self {
repository_selector,
trigger,
tooltip,
handle: None,
}
}
pub fn with_handle(mut self, handle: PopoverMenuHandle<RepositorySelector>) -> Self {
self.handle = Some(handle);
self
}
}
impl<T, TT> RenderOnce for RepositorySelectorPopoverMenu<T, TT>
where
T: PopoverTrigger + ButtonCommon,
TT: Fn(&mut Window, &mut App) -> AnyView + 'static,
{
fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
let repository_selector = self.repository_selector.clone();
PopoverMenu::new("repository-switcher")
.menu(move |_window, _cx| Some(repository_selector.clone()))
.trigger_with_tooltip(self.trigger, self.tooltip)
.attach(gpui::Corner::BottomLeft)
.when_some(self.handle.clone(), |menu, handle| menu.with_handle(handle))
}
}
pub struct RepositorySelectorDelegate {
project: WeakEntity<Project>,
repository_selector: WeakEntity<RepositorySelector>,