Fix flickering (#9012)

See https://zed.dev/channel/gpui-536

Fixes https://github.com/zed-industries/zed/issues/9010
Fixes https://github.com/zed-industries/zed/issues/8883
Fixes https://github.com/zed-industries/zed/issues/8640
Fixes https://github.com/zed-industries/zed/issues/8598
Fixes https://github.com/zed-industries/zed/issues/8579
Fixes https://github.com/zed-industries/zed/issues/8363
Fixes https://github.com/zed-industries/zed/issues/8207


### Problem

After transitioning Zed to GPUI 2, we started noticing that interacting
with the mouse on many UI elements would lead to a pretty annoying
flicker. The main issue with the old approach was that hover state was
calculated based on the previous frame. That is, when computing whether
a given element was hovered in the current frame, we would use
information about the same element in the previous frame.

However, inspecting the previous frame tells us very little about what
should be hovered in the current frame, as elements in the current frame
may have changed significantly.

### Solution

This pull request's main contribution is the introduction of a new
`after_layout` phase when redrawing the window. The key idea is that
we'll give every element a chance to register a hitbox (see
`ElementContext::insert_hitbox`) before painting anything. Then, during
the `paint` phase, elements can determine whether they're the topmost
and draw their hover state accordingly.

We are also removing the ability to give an arbitrary z-index to
elements. Instead, we will follow the much simpler painter's algorithm.
That is, an element that gets painted after will be drawn on top of an
element that got painted earlier. Elements can still escape their
current "stacking context" by using the new `ElementContext::defer_draw`
method (see `Overlay` for an example). Elements drawn using this method
will still be logically considered as being children of their original
parent (for keybinding, focus and cache invalidation purposes) but their
layout and paint passes will be deferred until the currently-drawn
element is done.

With these changes we also reworked geometry batching within the
`Scene`. The new approach uses an AABB tree to determine geometry
occlusion, which allows the GPU to render non-overlapping geometry in
parallel.

### Performance

Performance is slightly better than on `main` even though this new
approach is more correct and we're maintaining an extra data structure
(the AABB tree).


![before_after](https://github.com/zed-industries/zed/assets/482957/c8120b07-1dbd-4776-834a-d040e569a71e)

Release Notes:

- Fixed a bug that was causing popovers to flicker.

---------

Co-authored-by: Nathan Sobo <nathan@zed.dev>
Co-authored-by: Thorsten <thorsten@zed.dev>
This commit is contained in:
Antonio Scandurra 2024-03-11 10:45:57 +01:00 committed by GitHub
parent 9afd78b35e
commit 4700d33728
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
74 changed files with 6434 additions and 6301 deletions

View file

@ -122,9 +122,6 @@ impl RenderOnce for Avatar {
.size(image_size)
.bg(cx.theme().colors().ghost_element_background),
)
.children(
self.indicator
.map(|indicator| div().z_index(1).child(indicator)),
)
.children(self.indicator.map(|indicator| div().child(indicator)))
}
}

View file

@ -243,7 +243,7 @@ impl ContextMenuItem {
impl Render for ContextMenu {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
div().elevation_2(cx).flex().flex_row().child(
div().occlude().elevation_2(cx).flex().flex_row().child(
v_flex()
.min_w(px(200.))
.track_focus(&self.focus_handle)

View file

@ -2,9 +2,9 @@ use std::{cell::RefCell, rc::Rc};
use gpui::{
overlay, point, prelude::FluentBuilder, px, rems, AnchorCorner, AnyElement, Bounds,
DismissEvent, DispatchPhase, Element, ElementContext, ElementId, InteractiveBounds,
IntoElement, LayoutId, ManagedView, MouseDownEvent, ParentElement, Pixels, Point, View,
VisualContext, WindowContext,
DismissEvent, DispatchPhase, Element, ElementContext, ElementId, HitboxId, IntoElement,
LayoutId, ManagedView, MouseDownEvent, ParentElement, Pixels, Point, View, VisualContext,
WindowContext,
};
use crate::{Clickable, Selectable};
@ -109,6 +109,21 @@ impl<M: ManagedView> PopoverMenu<M> {
}
})
}
fn with_element_state<R>(
&mut self,
cx: &mut ElementContext,
f: impl FnOnce(&mut Self, &mut PopoverMenuElementState<M>, &mut ElementContext) -> R,
) -> R {
cx.with_element_state::<PopoverMenuElementState<M>, _>(
Some(self.id.clone()),
|element_state, cx| {
let mut element_state = element_state.unwrap().unwrap_or_default();
let result = f(self, &mut element_state, cx);
(result, Some(element_state))
},
)
}
}
/// Creates a [`PopoverMenu`]
@ -123,114 +138,136 @@ pub fn popover_menu<M: ManagedView>(id: impl Into<ElementId>) -> PopoverMenu<M>
}
}
pub struct PopoverMenuState<M> {
pub struct PopoverMenuElementState<M> {
menu: Rc<RefCell<Option<View<M>>>>,
child_bounds: Option<Bounds<Pixels>>,
}
impl<M> Clone for PopoverMenuElementState<M> {
fn clone(&self) -> Self {
Self {
menu: Rc::clone(&self.menu),
child_bounds: self.child_bounds,
}
}
}
impl<M> Default for PopoverMenuElementState<M> {
fn default() -> Self {
Self {
menu: Rc::default(),
child_bounds: None,
}
}
}
pub struct PopoverMenuFrameState {
child_layout_id: Option<LayoutId>,
child_element: Option<AnyElement>,
child_bounds: Option<Bounds<Pixels>>,
menu_element: Option<AnyElement>,
menu: Rc<RefCell<Option<View<M>>>>,
}
impl<M: ManagedView> Element for PopoverMenu<M> {
type State = PopoverMenuState<M>;
type BeforeLayout = PopoverMenuFrameState;
type AfterLayout = Option<HitboxId>;
fn request_layout(
fn before_layout(&mut self, cx: &mut ElementContext) -> (gpui::LayoutId, Self::BeforeLayout) {
self.with_element_state(cx, |this, element_state, cx| {
let mut menu_layout_id = None;
let menu_element = element_state.menu.borrow_mut().as_mut().map(|menu| {
let mut overlay = overlay().snap_to_window().anchor(this.anchor);
if let Some(child_bounds) = element_state.child_bounds {
overlay = overlay.position(
this.resolved_attach().corner(child_bounds) + this.resolved_offset(cx),
);
}
let mut element = overlay.child(menu.clone()).into_any();
menu_layout_id = Some(element.before_layout(cx));
element
});
let mut child_element = this.child_builder.take().map(|child_builder| {
(child_builder)(element_state.menu.clone(), this.menu_builder.clone())
});
let child_layout_id = child_element
.as_mut()
.map(|child_element| child_element.before_layout(cx));
let layout_id = cx.request_layout(
&gpui::Style::default(),
menu_layout_id.into_iter().chain(child_layout_id),
);
(
layout_id,
PopoverMenuFrameState {
child_element,
child_layout_id,
menu_element,
},
)
})
}
fn after_layout(
&mut self,
element_state: Option<Self::State>,
_bounds: Bounds<Pixels>,
before_layout: &mut Self::BeforeLayout,
cx: &mut ElementContext,
) -> (gpui::LayoutId, Self::State) {
let mut menu_layout_id = None;
let (menu, child_bounds) = if let Some(element_state) = element_state {
(element_state.menu, element_state.child_bounds)
} else {
(Rc::default(), None)
};
let menu_element = menu.borrow_mut().as_mut().map(|menu| {
let mut overlay = overlay().snap_to_window().anchor(self.anchor);
if let Some(child_bounds) = child_bounds {
overlay = overlay.position(
self.resolved_attach().corner(child_bounds) + self.resolved_offset(cx),
);
) -> Option<HitboxId> {
self.with_element_state(cx, |_this, element_state, cx| {
if let Some(child) = before_layout.child_element.as_mut() {
child.after_layout(cx);
}
let mut element = overlay.child(menu.clone()).into_any();
menu_layout_id = Some(element.request_layout(cx));
element
});
if let Some(menu) = before_layout.menu_element.as_mut() {
menu.after_layout(cx);
}
let mut child_element = self
.child_builder
.take()
.map(|child_builder| (child_builder)(menu.clone(), self.menu_builder.clone()));
let child_layout_id = child_element
.as_mut()
.map(|child_element| child_element.request_layout(cx));
let layout_id = cx.request_layout(
&gpui::Style::default(),
menu_layout_id.into_iter().chain(child_layout_id),
);
(
layout_id,
PopoverMenuState {
menu,
child_element,
child_layout_id,
menu_element,
child_bounds,
},
)
before_layout.child_layout_id.map(|layout_id| {
let bounds = cx.layout_bounds(layout_id);
element_state.child_bounds = Some(bounds);
cx.insert_hitbox(bounds, false).id
})
})
}
fn paint(
&mut self,
_: Bounds<gpui::Pixels>,
element_state: &mut Self::State,
before_layout: &mut Self::BeforeLayout,
child_hitbox: &mut Option<HitboxId>,
cx: &mut ElementContext,
) {
if let Some(mut child) = element_state.child_element.take() {
child.paint(cx);
}
if let Some(child_layout_id) = element_state.child_layout_id.take() {
element_state.child_bounds = Some(cx.layout_bounds(child_layout_id));
}
if let Some(mut menu) = element_state.menu_element.take() {
menu.paint(cx);
if let Some(child_bounds) = element_state.child_bounds {
let interactive_bounds = InteractiveBounds {
bounds: child_bounds,
stacking_order: cx.stacking_order().clone(),
};
// Mouse-downing outside the menu dismisses it, so we don't
// want a click on the toggle to re-open it.
cx.on_mouse_event(move |e: &MouseDownEvent, phase, cx| {
if phase == DispatchPhase::Bubble
&& interactive_bounds.visibly_contains(&e.position, cx)
{
cx.stop_propagation()
}
})
self.with_element_state(cx, |_this, _element_state, cx| {
if let Some(mut child) = before_layout.child_element.take() {
child.paint(cx);
}
}
if let Some(mut menu) = before_layout.menu_element.take() {
menu.paint(cx);
if let Some(child_hitbox) = *child_hitbox {
// Mouse-downing outside the menu dismisses it, so we don't
// want a click on the toggle to re-open it.
cx.on_mouse_event(move |_: &MouseDownEvent, phase, cx| {
if phase == DispatchPhase::Bubble && child_hitbox.is_hovered(cx) {
cx.stop_propagation()
}
})
}
}
})
}
}
impl<M: ManagedView> IntoElement for PopoverMenu<M> {
type Element = Self;
fn element_id(&self) -> Option<gpui::ElementId> {
Some(self.id.clone())
}
fn into_element(self) -> Self::Element {
self
}

View file

@ -2,7 +2,7 @@ use std::{cell::RefCell, rc::Rc};
use gpui::{
overlay, AnchorCorner, AnyElement, Bounds, DismissEvent, DispatchPhase, Element,
ElementContext, ElementId, InteractiveBounds, IntoElement, LayoutId, ManagedView, MouseButton,
ElementContext, ElementId, Hitbox, IntoElement, LayoutId, ManagedView, MouseButton,
MouseDownEvent, ParentElement, Pixels, Point, View, VisualContext, WindowContext,
};
@ -37,6 +37,21 @@ impl<M: ManagedView> RightClickMenu<M> {
self.attach = Some(attach);
self
}
fn with_element_state<R>(
&mut self,
cx: &mut ElementContext,
f: impl FnOnce(&mut Self, &mut MenuHandleElementState<M>, &mut ElementContext) -> R,
) -> R {
cx.with_element_state::<MenuHandleElementState<M>, _>(
Some(self.id.clone()),
|element_state, cx| {
let mut element_state = element_state.unwrap().unwrap_or_default();
let result = f(self, &mut element_state, cx);
(result, Some(element_state))
},
)
}
}
/// Creates a [`RightClickMenu`]
@ -50,140 +65,172 @@ pub fn right_click_menu<M: ManagedView>(id: impl Into<ElementId>) -> RightClickM
}
}
pub struct MenuHandleState<M> {
pub struct MenuHandleElementState<M> {
menu: Rc<RefCell<Option<View<M>>>>,
position: Rc<RefCell<Point<Pixels>>>,
}
impl<M> Clone for MenuHandleElementState<M> {
fn clone(&self) -> Self {
Self {
menu: Rc::clone(&self.menu),
position: Rc::clone(&self.position),
}
}
}
impl<M> Default for MenuHandleElementState<M> {
fn default() -> Self {
Self {
menu: Rc::default(),
position: Rc::default(),
}
}
}
pub struct MenuHandleFrameState {
child_layout_id: Option<LayoutId>,
child_element: Option<AnyElement>,
menu_element: Option<AnyElement>,
}
impl<M: ManagedView> Element for RightClickMenu<M> {
type State = MenuHandleState<M>;
type BeforeLayout = MenuHandleFrameState;
type AfterLayout = Hitbox;
fn request_layout(
fn before_layout(&mut self, cx: &mut ElementContext) -> (gpui::LayoutId, Self::BeforeLayout) {
self.with_element_state(cx, |this, element_state, cx| {
let mut menu_layout_id = None;
let menu_element = element_state.menu.borrow_mut().as_mut().map(|menu| {
let mut overlay = overlay().snap_to_window();
if let Some(anchor) = this.anchor {
overlay = overlay.anchor(anchor);
}
overlay = overlay.position(*element_state.position.borrow());
let mut element = overlay.child(menu.clone()).into_any();
menu_layout_id = Some(element.before_layout(cx));
element
});
let mut child_element = this
.child_builder
.take()
.map(|child_builder| (child_builder)(element_state.menu.borrow().is_some()));
let child_layout_id = child_element
.as_mut()
.map(|child_element| child_element.before_layout(cx));
let layout_id = cx.request_layout(
&gpui::Style::default(),
menu_layout_id.into_iter().chain(child_layout_id),
);
(
layout_id,
MenuHandleFrameState {
child_element,
child_layout_id,
menu_element,
},
)
})
}
fn after_layout(
&mut self,
element_state: Option<Self::State>,
bounds: Bounds<Pixels>,
before_layout: &mut Self::BeforeLayout,
cx: &mut ElementContext,
) -> (gpui::LayoutId, Self::State) {
let (menu, position) = if let Some(element_state) = element_state {
(element_state.menu, element_state.position)
} else {
(Rc::default(), Rc::default())
};
) -> Hitbox {
cx.with_element_id(Some(self.id.clone()), |cx| {
let hitbox = cx.insert_hitbox(bounds, false);
let mut menu_layout_id = None;
let menu_element = menu.borrow_mut().as_mut().map(|menu| {
let mut overlay = overlay().snap_to_window();
if let Some(anchor) = self.anchor {
overlay = overlay.anchor(anchor);
if let Some(child) = before_layout.child_element.as_mut() {
child.after_layout(cx);
}
overlay = overlay.position(*position.borrow());
let mut element = overlay.child(menu.clone()).into_any();
menu_layout_id = Some(element.request_layout(cx));
element
});
if let Some(menu) = before_layout.menu_element.as_mut() {
menu.after_layout(cx);
}
let mut child_element = self
.child_builder
.take()
.map(|child_builder| (child_builder)(menu.borrow().is_some()));
let child_layout_id = child_element
.as_mut()
.map(|child_element| child_element.request_layout(cx));
let layout_id = cx.request_layout(
&gpui::Style::default(),
menu_layout_id.into_iter().chain(child_layout_id),
);
(
layout_id,
MenuHandleState {
menu,
position,
child_element,
child_layout_id,
menu_element,
},
)
hitbox
})
}
fn paint(
&mut self,
bounds: Bounds<gpui::Pixels>,
element_state: &mut Self::State,
_bounds: Bounds<gpui::Pixels>,
before_layout: &mut Self::BeforeLayout,
hitbox: &mut Self::AfterLayout,
cx: &mut ElementContext,
) {
if let Some(mut child) = element_state.child_element.take() {
child.paint(cx);
}
self.with_element_state(cx, |this, element_state, cx| {
if let Some(mut child) = before_layout.child_element.take() {
child.paint(cx);
}
if let Some(mut menu) = element_state.menu_element.take() {
menu.paint(cx);
return;
}
if let Some(mut menu) = before_layout.menu_element.take() {
menu.paint(cx);
return;
}
let Some(builder) = self.menu_builder.take() else {
return;
};
let menu = element_state.menu.clone();
let position = element_state.position.clone();
let attach = self.attach;
let child_layout_id = element_state.child_layout_id;
let child_bounds = cx.layout_bounds(child_layout_id.unwrap());
let Some(builder) = this.menu_builder.take() else {
return;
};
let interactive_bounds = InteractiveBounds {
bounds: bounds.intersect(&cx.content_mask().bounds),
stacking_order: cx.stacking_order().clone(),
};
cx.on_mouse_event(move |event: &MouseDownEvent, phase, cx| {
if phase == DispatchPhase::Bubble
&& event.button == MouseButton::Right
&& interactive_bounds.visibly_contains(&event.position, cx)
{
cx.stop_propagation();
cx.prevent_default();
let attach = this.attach;
let menu = element_state.menu.clone();
let position = element_state.position.clone();
let child_layout_id = before_layout.child_layout_id;
let child_bounds = cx.layout_bounds(child_layout_id.unwrap());
let new_menu = (builder)(cx);
let menu2 = menu.clone();
let previous_focus_handle = cx.focused();
let hitbox_id = hitbox.id;
cx.on_mouse_event(move |event: &MouseDownEvent, phase, cx| {
if phase == DispatchPhase::Bubble
&& event.button == MouseButton::Right
&& hitbox_id.is_hovered(cx)
{
cx.stop_propagation();
cx.prevent_default();
cx.subscribe(&new_menu, move |modal, _: &DismissEvent, cx| {
if modal.focus_handle(cx).contains_focused(cx) {
if let Some(previous_focus_handle) = previous_focus_handle.as_ref() {
cx.focus(previous_focus_handle);
let new_menu = (builder)(cx);
let menu2 = menu.clone();
let previous_focus_handle = cx.focused();
cx.subscribe(&new_menu, move |modal, _: &DismissEvent, cx| {
if modal.focus_handle(cx).contains_focused(cx) {
if let Some(previous_focus_handle) = previous_focus_handle.as_ref() {
cx.focus(previous_focus_handle);
}
}
*menu2.borrow_mut() = None;
cx.refresh();
})
.detach();
cx.focus_view(&new_menu);
*menu.borrow_mut() = Some(new_menu);
*position.borrow_mut() = if child_layout_id.is_some() {
if let Some(attach) = attach {
attach.corner(child_bounds)
} else {
cx.mouse_position()
}
}
*menu2.borrow_mut() = None;
cx.refresh();
})
.detach();
cx.focus_view(&new_menu);
*menu.borrow_mut() = Some(new_menu);
*position.borrow_mut() =
if let Some(attach) = attach.filter(|_| child_layout_id.is_some()) {
attach.corner(child_bounds)
} else {
cx.mouse_position()
};
cx.refresh();
}
});
cx.refresh();
}
});
})
}
}
impl<M: ManagedView> IntoElement for RightClickMenu<M> {
type Element = Self;
fn element_id(&self) -> Option<gpui::ElementId> {
Some(self.id.clone())
}
fn into_element(self) -> Self::Element {
self
}

View file

@ -123,7 +123,6 @@ impl RenderOnce for TabBar {
.absolute()
.top_0()
.left_0()
.z_index(1)
.size_full()
.border_b()
.border_color(cx.theme().colors().border),
@ -131,7 +130,6 @@ impl RenderOnce for TabBar {
.child(
h_flex()
.id("tabs")
.z_index(2)
.flex_grow()
.overflow_x_scroll()
.when_some(self.scroll_handle, |cx, scroll_handle| {

View file

@ -7,7 +7,6 @@ use crate::{ElevationIndex, UiTextSize};
fn elevated<E: Styled>(this: E, cx: &mut WindowContext, index: ElevationIndex) -> E {
this.bg(cx.theme().colors().elevated_surface_background)
.z_index(index.z_index())
.rounded(px(8.))
.border()
.border_color(cx.theme().colors().border_variant)

View file

@ -20,17 +20,6 @@ pub enum ElevationIndex {
}
impl ElevationIndex {
pub fn z_index(self) -> u16 {
match self {
ElevationIndex::Background => 0,
ElevationIndex::Surface => 42,
ElevationIndex::ElevatedSurface => 84,
ElevationIndex::Wash => 126,
ElevationIndex::ModalSurface => 168,
ElevationIndex::DraggedElement => 210,
}
}
pub fn shadow(self) -> SmallVec<[BoxShadow; 2]> {
match self {
ElevationIndex::Surface => smallvec![],
@ -75,16 +64,6 @@ pub enum LayerIndex {
ElevatedElement,
}
impl LayerIndex {
pub fn usize(&self) -> usize {
match *self {
LayerIndex::BehindElement => 0,
LayerIndex::Element => 100,
LayerIndex::ElevatedElement => 200,
}
}
}
/// An appropriate z-index for the given layer based on its intended usage.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ElementIndex {
@ -95,16 +74,3 @@ pub enum ElementIndex {
Content,
Overlay,
}
impl ElementIndex {
pub fn usize(&self) -> usize {
match *self {
ElementIndex::Effect => 0,
ElementIndex::Background => 100,
ElementIndex::Tint => 200,
ElementIndex::Highlight => 300,
ElementIndex::Content => 400,
ElementIndex::Overlay => 500,
}
}
}