Eliminate GPUI View, ViewContext, and WindowContext types (#22632)

There's still a bit more work to do on this, but this PR is compiling
(with warnings) after eliminating the key types. When the tasks below
are complete, this will be the new narrative for GPUI:

- `Entity<T>` - This replaces `View<T>`/`Model<T>`. It represents a unit
of state, and if `T` implements `Render`, then `Entity<T>` implements
`Element`.
- `&mut App` This replaces `AppContext` and represents the app.
- `&mut Context<T>` This replaces `ModelContext` and derefs to `App`. It
is provided by the framework when updating an entity.
- `&mut Window` Broken out of `&mut WindowContext` which no longer
exists. Every method that once took `&mut WindowContext` now takes `&mut
Window, &mut App` and every method that took `&mut ViewContext<T>` now
takes `&mut Window, &mut Context<T>`

Not pictured here are the two other failed attempts. It's been quite a
month!

Tasks:

- [x] Remove `View`, `ViewContext`, `WindowContext` and thread through
`Window`
- [x] [@cole-miller @mikayla-maki] Redraw window when entities change
- [x] [@cole-miller @mikayla-maki] Get examples and Zed running
- [x] [@cole-miller @mikayla-maki] Fix Zed rendering
- [x] [@mikayla-maki] Fix todo! macros and comments
- [x] Fix a bug where the editor would not be redrawn because of view
caching
- [x] remove publicness window.notify() and replace with
`AppContext::notify`
- [x] remove `observe_new_window_models`, replace with
`observe_new_models` with an optional window
- [x] Fix a bug where the project panel would not be redrawn because of
the wrong refresh() call being used
- [x] Fix the tests
- [x] Fix warnings by eliminating `Window` params or using `_`
- [x] Fix conflicts
- [x] Simplify generic code where possible
- [x] Rename types
- [ ] Update docs

### issues post merge

- [x] Issues switching between normal and insert mode
- [x] Assistant re-rendering failure
- [x] Vim test failures
- [x] Mac build issue



Release Notes:

- N/A

---------

Co-authored-by: Antonio Scandurra <me@as-cii.com>
Co-authored-by: Cole Miller <cole@zed.dev>
Co-authored-by: Mikayla <mikayla@zed.dev>
Co-authored-by: Joseph <joseph@zed.dev>
Co-authored-by: max <max@zed.dev>
Co-authored-by: Michael Sloan <michael@zed.dev>
Co-authored-by: Mikayla Maki <mikaylamaki@Mikaylas-MacBook-Pro.local>
Co-authored-by: Mikayla <mikayla.c.maki@gmail.com>
Co-authored-by: joão <joao@zed.dev>
This commit is contained in:
Nathan Sobo 2025-01-25 20:02:45 -07:00 committed by GitHub
parent 21b4a0d50e
commit 6fca1d2b0b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
648 changed files with 36248 additions and 28208 deletions

View file

@ -1,33 +1,20 @@
use crate::Empty;
use crate::{
seal::Sealed, AnyElement, AnyModel, AnyWeakModel, AppContext, Bounds, ContentMask, Element,
ElementId, Entity, EntityId, Flatten, FocusHandle, FocusableView, GlobalElementId, IntoElement,
LayoutId, Model, PaintIndex, Pixels, PrepaintStateIndex, Render, Style, StyleRefinement,
TextStyle, ViewContext, VisualContext, WeakModel, WindowContext,
AnyElement, AnyEntity, AnyWeakEntity, App, Bounds, ContentMask, Context, Element, ElementId,
Entity, EntityId, GlobalElementId, IntoElement, LayoutId, PaintIndex, Pixels,
PrepaintStateIndex, Render, Style, StyleRefinement, TextStyle, WeakEntity,
};
use anyhow::{Context, Result};
use crate::{Empty, Window};
use anyhow::Result;
use collections::FxHashSet;
use refineable::Refineable;
use std::mem;
use std::{
any::{type_name, TypeId},
fmt,
hash::{Hash, Hasher},
ops::Range,
};
/// A view is a piece of state that can be presented on screen by implementing the [Render] trait.
/// Views implement [Element] and can composed with other views, and every window is created with a root view.
pub struct View<V> {
/// A view is just a [Model] whose type implements `Render`, and the model is accessible via this field.
pub model: Model<V>,
}
impl<V> Sealed for View<V> {}
use std::{any::TypeId, fmt, ops::Range};
struct AnyViewState {
prepaint_range: Range<PrepaintStateIndex>,
paint_range: Range<PaintIndex>,
cache_key: ViewCacheKey,
accessed_entities: FxHashSet<EntityId>,
}
#[derive(Default)]
@ -37,61 +24,7 @@ struct ViewCacheKey {
text_style: TextStyle,
}
impl<V: 'static> Entity<V> for View<V> {
type Weak = WeakView<V>;
fn entity_id(&self) -> EntityId {
self.model.entity_id
}
fn downgrade(&self) -> Self::Weak {
WeakView {
model: self.model.downgrade(),
}
}
fn upgrade_from(weak: &Self::Weak) -> Option<Self>
where
Self: Sized,
{
let model = weak.model.upgrade()?;
Some(View { model })
}
}
impl<V: 'static> View<V> {
/// Convert this strong view reference into a weak view reference.
pub fn downgrade(&self) -> WeakView<V> {
Entity::downgrade(self)
}
/// Updates the view's state with the given function, which is passed a mutable reference and a context.
pub fn update<C, R>(
&self,
cx: &mut C,
f: impl FnOnce(&mut V, &mut ViewContext<V>) -> R,
) -> C::Result<R>
where
C: VisualContext,
{
cx.update_view(self, f)
}
/// Obtain a read-only reference to this view's state.
pub fn read<'a>(&self, cx: &'a AppContext) -> &'a V {
self.model.read(cx)
}
/// Gets a [FocusHandle] for this view when its state implements [FocusableView].
pub fn focus_handle(&self, cx: &AppContext) -> FocusHandle
where
V: FocusableView,
{
self.read(cx).focus_handle(cx)
}
}
impl<V: Render> Element for View<V> {
impl<V: Render> Element for Entity<V> {
type RequestLayoutState = AnyElement;
type PrepaintState = ();
@ -102,10 +35,11 @@ impl<V: Render> Element for View<V> {
fn request_layout(
&mut self,
_id: Option<&GlobalElementId>,
cx: &mut WindowContext,
window: &mut Window,
cx: &mut App,
) -> (LayoutId, Self::RequestLayoutState) {
let mut element = self.update(cx, |view, cx| view.render(cx).into_any_element());
let layout_id = element.request_layout(cx);
let mut element = self.update(cx, |view, cx| view.render(window, cx).into_any_element());
let layout_id = element.request_layout(window, cx);
(layout_id, element)
}
@ -114,10 +48,11 @@ impl<V: Render> Element for View<V> {
_id: Option<&GlobalElementId>,
_: Bounds<Pixels>,
element: &mut Self::RequestLayoutState,
cx: &mut WindowContext,
window: &mut Window,
cx: &mut App,
) {
cx.set_view_id(self.entity_id());
element.prepaint(cx);
window.set_view_id(self.entity_id());
element.prepaint(window, cx);
}
fn paint(
@ -126,110 +61,31 @@ impl<V: Render> Element for View<V> {
_: Bounds<Pixels>,
element: &mut Self::RequestLayoutState,
_: &mut Self::PrepaintState,
cx: &mut WindowContext,
window: &mut Window,
cx: &mut App,
) {
element.paint(cx);
element.paint(window, cx);
}
}
impl<V> Clone for View<V> {
fn clone(&self) -> Self {
Self {
model: self.model.clone(),
}
}
}
impl<T> std::fmt::Debug for View<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct(&format!("View<{}>", type_name::<T>()))
.field("entity_id", &self.model.entity_id)
.finish_non_exhaustive()
}
}
impl<V> Hash for View<V> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.model.hash(state);
}
}
impl<V> PartialEq for View<V> {
fn eq(&self, other: &Self) -> bool {
self.model == other.model
}
}
impl<V> Eq for View<V> {}
/// A weak variant of [View] which does not prevent the view from being released.
pub struct WeakView<V> {
pub(crate) model: WeakModel<V>,
}
impl<V: 'static> WeakView<V> {
/// Gets the entity id associated with this handle.
pub fn entity_id(&self) -> EntityId {
self.model.entity_id
}
/// Obtain a strong handle for the view if it hasn't been released.
pub fn upgrade(&self) -> Option<View<V>> {
Entity::upgrade_from(self)
}
/// Updates this view's state if it hasn't been released.
/// Returns an error if this view has been released.
pub fn update<C, R>(
&self,
cx: &mut C,
f: impl FnOnce(&mut V, &mut ViewContext<V>) -> R,
) -> Result<R>
where
C: VisualContext,
Result<C::Result<R>>: Flatten<R>,
{
let view = self.upgrade().context("error upgrading view")?;
Ok(view.update(cx, f)).flatten()
}
/// Assert that the view referenced by this handle has been released.
#[cfg(any(test, feature = "test-support"))]
pub fn assert_released(&self) {
self.model.assert_released()
}
}
impl<V> Clone for WeakView<V> {
fn clone(&self) -> Self {
Self {
model: self.model.clone(),
}
}
}
impl<V> Hash for WeakView<V> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.model.hash(state);
}
}
impl<V> PartialEq for WeakView<V> {
fn eq(&self, other: &Self) -> bool {
self.model == other.model
}
}
impl<V> Eq for WeakView<V> {}
/// A dynamically-typed handle to a view, which can be downcast to a [View] for a specific type.
#[derive(Clone, Debug)]
pub struct AnyView {
model: AnyModel,
render: fn(&AnyView, &mut WindowContext) -> AnyElement,
model: AnyEntity,
render: fn(&AnyView, &mut Window, &mut App) -> AnyElement,
cached_style: Option<StyleRefinement>,
}
impl<V: Render> From<Entity<V>> for AnyView {
fn from(value: Entity<V>) -> Self {
AnyView {
model: value.into_any(),
render: any_view::render::<V>,
cached_style: None,
}
}
}
impl AnyView {
/// Indicate that this view should be cached when using it as an element.
/// When using this method, the view's previous layout and paint will be recycled from the previous frame if [ViewContext::notify] has not been called since it was rendered.
@ -249,9 +105,9 @@ impl AnyView {
/// Convert this to a [View] of a specific type.
/// If this handle does not contain a view of the specified type, returns itself in an `Err` variant.
pub fn downcast<T: 'static>(self) -> Result<View<T>, Self> {
pub fn downcast<T: 'static>(self) -> Result<Entity<T>, Self> {
match self.model.downcast() {
Ok(model) => Ok(View { model }),
Ok(model) => Ok(model),
Err(model) => Err(Self {
model,
render: self.render,
@ -271,16 +127,6 @@ impl AnyView {
}
}
impl<V: Render> From<View<V>> for AnyView {
fn from(value: View<V>) -> Self {
AnyView {
model: value.model.into_any(),
render: any_view::render::<V>,
cached_style: None,
}
}
}
impl PartialEq for AnyView {
fn eq(&self, other: &Self) -> bool {
self.model == other.model
@ -300,16 +146,17 @@ impl Element for AnyView {
fn request_layout(
&mut self,
_id: Option<&GlobalElementId>,
cx: &mut WindowContext,
window: &mut Window,
cx: &mut App,
) -> (LayoutId, Self::RequestLayoutState) {
if let Some(style) = self.cached_style.as_ref() {
let mut root_style = Style::default();
root_style.refine(style);
let layout_id = cx.request_layout(root_style, None);
let layout_id = window.request_layout(root_style, None, cx);
(layout_id, None)
} else {
let mut element = (self.render)(self, cx);
let layout_id = element.request_layout(cx);
let mut element = (self.render)(self, window, cx);
let layout_id = element.request_layout(window, cx);
(layout_id, Some(element))
}
}
@ -319,53 +166,64 @@ impl Element for AnyView {
global_id: Option<&GlobalElementId>,
bounds: Bounds<Pixels>,
element: &mut Self::RequestLayoutState,
cx: &mut WindowContext,
window: &mut Window,
cx: &mut App,
) -> Option<AnyElement> {
cx.set_view_id(self.entity_id());
window.set_view_id(self.entity_id());
if self.cached_style.is_some() {
cx.with_element_state::<AnyViewState, _>(global_id.unwrap(), |element_state, cx| {
let content_mask = cx.content_mask();
let text_style = cx.text_style();
window.with_element_state::<AnyViewState, _>(
global_id.unwrap(),
|element_state, window| {
let content_mask = window.content_mask();
let text_style = window.text_style();
if let Some(mut element_state) = element_state {
if element_state.cache_key.bounds == bounds
&& element_state.cache_key.content_mask == content_mask
&& element_state.cache_key.text_style == text_style
&& !cx.window.dirty_views.contains(&self.entity_id())
&& !cx.window.refreshing
{
let prepaint_start = cx.prepaint_index();
cx.reuse_prepaint(element_state.prepaint_range.clone());
let prepaint_end = cx.prepaint_index();
element_state.prepaint_range = prepaint_start..prepaint_end;
return (None, element_state);
if let Some(mut element_state) = element_state {
if element_state.cache_key.bounds == bounds
&& element_state.cache_key.content_mask == content_mask
&& element_state.cache_key.text_style == text_style
&& !window.dirty_views.contains(&self.entity_id())
&& !window.refreshing
{
let prepaint_start = window.prepaint_index();
window.reuse_prepaint(element_state.prepaint_range.clone());
cx.entities
.extend_accessed(&element_state.accessed_entities);
let prepaint_end = window.prepaint_index();
element_state.prepaint_range = prepaint_start..prepaint_end;
return (None, element_state);
}
}
}
let refreshing = mem::replace(&mut cx.window.refreshing, true);
let prepaint_start = cx.prepaint_index();
let mut element = (self.render)(self, cx);
element.layout_as_root(bounds.size.into(), cx);
element.prepaint_at(bounds.origin, cx);
let prepaint_end = cx.prepaint_index();
cx.window.refreshing = refreshing;
let refreshing = mem::replace(&mut window.refreshing, true);
let prepaint_start = window.prepaint_index();
let (mut element, accessed_entities) = cx.detect_accessed_entities(|cx| {
let mut element = (self.render)(self, window, cx);
element.layout_as_root(bounds.size.into(), window, cx);
element.prepaint_at(bounds.origin, window, cx);
element
});
let prepaint_end = window.prepaint_index();
window.refreshing = refreshing;
(
Some(element),
AnyViewState {
prepaint_range: prepaint_start..prepaint_end,
paint_range: PaintIndex::default()..PaintIndex::default(),
cache_key: ViewCacheKey {
bounds,
content_mask,
text_style,
(
Some(element),
AnyViewState {
accessed_entities,
prepaint_range: prepaint_start..prepaint_end,
paint_range: PaintIndex::default()..PaintIndex::default(),
cache_key: ViewCacheKey {
bounds,
content_mask,
text_style,
},
},
},
)
})
)
},
)
} else {
let mut element = element.take().unwrap();
element.prepaint(cx);
element.prepaint(window, cx);
Some(element)
}
}
@ -376,35 +234,39 @@ impl Element for AnyView {
_bounds: Bounds<Pixels>,
_: &mut Self::RequestLayoutState,
element: &mut Self::PrepaintState,
cx: &mut WindowContext,
window: &mut Window,
cx: &mut App,
) {
if self.cached_style.is_some() {
cx.with_element_state::<AnyViewState, _>(global_id.unwrap(), |element_state, cx| {
let mut element_state = element_state.unwrap();
window.with_element_state::<AnyViewState, _>(
global_id.unwrap(),
|element_state, window| {
let mut element_state = element_state.unwrap();
let paint_start = cx.paint_index();
let paint_start = window.paint_index();
if let Some(element) = element {
let refreshing = mem::replace(&mut cx.window.refreshing, true);
element.paint(cx);
cx.window.refreshing = refreshing;
} else {
cx.reuse_paint(element_state.paint_range.clone());
}
if let Some(element) = element {
let refreshing = mem::replace(&mut window.refreshing, true);
element.paint(window, cx);
window.refreshing = refreshing;
} else {
window.reuse_paint(element_state.paint_range.clone());
}
let paint_end = cx.paint_index();
element_state.paint_range = paint_start..paint_end;
let paint_end = window.paint_index();
element_state.paint_range = paint_start..paint_end;
((), element_state)
})
((), element_state)
},
)
} else {
element.as_mut().unwrap().paint(cx);
element.as_mut().unwrap().paint(window, cx);
}
}
}
impl<V: 'static + Render> IntoElement for View<V> {
type Element = View<V>;
impl<V: 'static + Render> IntoElement for Entity<V> {
type Element = Entity<V>;
fn into_element(self) -> Self::Element {
self
@ -421,8 +283,8 @@ impl IntoElement for AnyView {
/// A weak, dynamically-typed view handle that does not prevent the view from being released.
pub struct AnyWeakView {
model: AnyWeakModel,
render: fn(&AnyView, &mut WindowContext) -> AnyElement,
model: AnyWeakEntity,
render: fn(&AnyView, &mut Window, &mut App) -> AnyElement,
}
impl AnyWeakView {
@ -437,10 +299,10 @@ impl AnyWeakView {
}
}
impl<V: 'static + Render> From<WeakView<V>> for AnyWeakView {
fn from(view: WeakView<V>) -> Self {
Self {
model: view.model.into(),
impl<V: 'static + Render> From<WeakEntity<V>> for AnyWeakView {
fn from(view: WeakEntity<V>) -> Self {
AnyWeakView {
model: view.into(),
render: any_view::render::<V>,
}
}
@ -461,14 +323,15 @@ impl std::fmt::Debug for AnyWeakView {
}
mod any_view {
use crate::{AnyElement, AnyView, IntoElement, Render, WindowContext};
use crate::{AnyElement, AnyView, App, IntoElement, Render, Window};
pub(crate) fn render<V: 'static + Render>(
view: &AnyView,
cx: &mut WindowContext,
window: &mut Window,
cx: &mut App,
) -> AnyElement {
let view = view.clone().downcast::<V>().unwrap();
view.update(cx, |view, cx| view.render(cx).into_any_element())
view.update(cx, |view, cx| view.render(window, cx).into_any_element())
}
}
@ -476,7 +339,7 @@ mod any_view {
pub struct EmptyView;
impl Render for EmptyView {
fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
Empty
}
}