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,5 +1,5 @@
use assets::Assets;
use gpui::{prelude::*, rgb, App, KeyBinding, StyleRefinement, View, WindowOptions};
use gpui::{prelude::*, rgb, Application, Entity, KeyBinding, StyleRefinement, WindowOptions};
use language::{language_settings::AllLanguageSettings, LanguageRegistry};
use markdown::{Markdown, MarkdownStyle};
use node_runtime::NodeRuntime;
@ -7,7 +7,7 @@ use settings::SettingsStore;
use std::sync::Arc;
use theme::LoadThemes;
use ui::prelude::*;
use ui::{div, WindowContext};
use ui::{div, App, Window};
const MARKDOWN_EXAMPLE: &str = r#"
# Markdown Example Document
@ -99,7 +99,7 @@ Remember, markdown processors may have slight differences and extensions, so alw
pub fn main() {
env_logger::init();
App::new().with_assets(Assets).run(|cx| {
Application::new().with_assets(Assets).run(|cx| {
let store = SettingsStore::test(cx);
cx.set_global(store);
language::init(cx);
@ -118,8 +118,8 @@ pub fn main() {
Assets.load_fonts(cx).unwrap();
cx.activate(true);
cx.open_window(WindowOptions::default(), |cx| {
cx.new_view(|cx| {
cx.open_window(WindowOptions::default(), |window, cx| {
cx.new(|cx| {
let markdown_style = MarkdownStyle {
base_text_style: gpui::TextStyle {
font_family: "Zed Plex Sans".into(),
@ -164,6 +164,7 @@ pub fn main() {
MARKDOWN_EXAMPLE.to_string(),
markdown_style,
language_registry,
window,
cx,
)
})
@ -173,7 +174,7 @@ pub fn main() {
}
struct MarkdownExample {
markdown: View<Markdown>,
markdown: Entity<Markdown>,
}
impl MarkdownExample {
@ -181,16 +182,17 @@ impl MarkdownExample {
text: String,
style: MarkdownStyle,
language_registry: Arc<LanguageRegistry>,
cx: &mut WindowContext,
window: &mut Window,
cx: &mut App,
) -> Self {
let markdown =
cx.new_view(|cx| Markdown::new(text, style, Some(language_registry), None, cx));
cx.new(|cx| Markdown::new(text, style, Some(language_registry), None, window, cx));
Self { markdown }
}
}
impl Render for MarkdownExample {
fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div()
.id("markdown-example")
.debug_selector(|| "foo".into())

View file

@ -1,5 +1,5 @@
use assets::Assets;
use gpui::{rgb, App, KeyBinding, Length, StyleRefinement, View, WindowOptions};
use gpui::{rgb, Application, Entity, KeyBinding, Length, StyleRefinement, WindowOptions};
use language::{language_settings::AllLanguageSettings, LanguageRegistry};
use markdown::{Markdown, MarkdownStyle};
use node_runtime::NodeRuntime;
@ -19,7 +19,7 @@ wow so cool
pub fn main() {
env_logger::init();
App::new().with_assets(Assets).run(|cx| {
Application::new().with_assets(Assets).run(|cx| {
let store = SettingsStore::test(cx);
cx.set_global(store);
language::init(cx);
@ -35,8 +35,8 @@ pub fn main() {
Assets.load_fonts(cx).unwrap();
cx.activate(true);
let _ = cx.open_window(WindowOptions::default(), |cx| {
cx.new_view(|cx| {
let _ = cx.open_window(WindowOptions::default(), |window, cx| {
cx.new(|cx| {
let markdown_style = MarkdownStyle {
base_text_style: gpui::TextStyle {
font_family: "Zed Mono".into(),
@ -86,8 +86,15 @@ pub fn main() {
break_style: Default::default(),
heading: Default::default(),
};
let markdown = cx.new_view(|cx| {
Markdown::new(MARKDOWN_EXAMPLE.into(), markdown_style, None, None, cx)
let markdown = cx.new(|cx| {
Markdown::new(
MARKDOWN_EXAMPLE.into(),
markdown_style,
None,
None,
window,
cx,
)
});
HelloWorld { markdown }
@ -96,11 +103,11 @@ pub fn main() {
});
}
struct HelloWorld {
markdown: View<Markdown>,
markdown: Entity<Markdown>,
}
impl Render for HelloWorld {
fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div()
.flex()
.bg(rgb(0x2e7d32))

View file

@ -3,11 +3,11 @@ pub mod parser;
use crate::parser::CodeBlockKind;
use futures::FutureExt;
use gpui::{
actions, point, quad, AnyElement, AppContext, Bounds, ClipboardItem, CursorStyle,
DispatchPhase, Edges, FocusHandle, FocusableView, FontStyle, FontWeight, GlobalElementId,
Hitbox, Hsla, KeyContext, Length, MouseDownEvent, MouseEvent, MouseMoveEvent, MouseUpEvent,
Point, Render, Stateful, StrikethroughStyle, StyleRefinement, StyledText, Task, TextLayout,
TextRun, TextStyle, TextStyleRefinement, View,
actions, point, quad, AnyElement, App, Bounds, ClipboardItem, CursorStyle, DispatchPhase,
Edges, Entity, FocusHandle, Focusable, FontStyle, FontWeight, GlobalElementId, Hitbox, Hsla,
KeyContext, Length, MouseDownEvent, MouseEvent, MouseMoveEvent, MouseUpEvent, Point, Render,
Stateful, StrikethroughStyle, StyleRefinement, StyledText, Task, TextLayout, TextRun,
TextStyle, TextStyleRefinement,
};
use language::{Language, LanguageRegistry, Rope};
use parser::{parse_links_only, parse_markdown, MarkdownEvent, MarkdownTag, MarkdownTagEnd};
@ -78,7 +78,8 @@ impl Markdown {
style: MarkdownStyle,
language_registry: Option<Arc<LanguageRegistry>>,
fallback_code_block_language: Option<String>,
cx: &ViewContext<Self>,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let focus_handle = cx.focus_handle();
let mut this = Self {
@ -98,7 +99,7 @@ impl Markdown {
copy_code_block_buttons: true,
},
};
this.parse(cx);
this.parse(window, cx);
this
}
@ -107,7 +108,8 @@ impl Markdown {
style: MarkdownStyle,
language_registry: Option<Arc<LanguageRegistry>>,
fallback_code_block_language: Option<String>,
cx: &ViewContext<Self>,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let focus_handle = cx.focus_handle();
let mut this = Self {
@ -127,7 +129,7 @@ impl Markdown {
copy_code_block_buttons: true,
},
};
this.parse(cx);
this.parse(window, cx);
this
}
@ -135,12 +137,12 @@ impl Markdown {
&self.source
}
pub fn append(&mut self, text: &str, cx: &ViewContext<Self>) {
pub fn append(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
self.source.push_str(text);
self.parse(cx);
self.parse(window, cx);
}
pub fn reset(&mut self, source: String, cx: &ViewContext<Self>) {
pub fn reset(&mut self, source: String, window: &mut Window, cx: &mut Context<Self>) {
if source == self.source() {
return;
}
@ -150,14 +152,14 @@ impl Markdown {
self.pending_parse = None;
self.should_reparse = false;
self.parsed_markdown = ParsedMarkdown::default();
self.parse(cx);
self.parse(window, cx);
}
pub fn parsed_markdown(&self) -> &ParsedMarkdown {
&self.parsed_markdown
}
fn copy(&self, text: &RenderedText, cx: &ViewContext<Self>) {
fn copy(&self, text: &RenderedText, _: &mut Window, cx: &mut Context<Self>) {
if self.selection.end <= self.selection.start {
return;
}
@ -165,7 +167,7 @@ impl Markdown {
cx.write_to_clipboard(ClipboardItem::new_string(text));
}
fn parse(&mut self, cx: &ViewContext<Self>) {
fn parse(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.source.is_empty() {
return;
}
@ -190,14 +192,14 @@ impl Markdown {
});
self.should_reparse = false;
self.pending_parse = Some(cx.spawn(|this, mut cx| {
self.pending_parse = Some(cx.spawn_in(window, |this, mut cx| {
async move {
let parsed = parsed.await?;
this.update(&mut cx, |this, cx| {
this.update_in(&mut cx, |this, window, cx| {
this.parsed_markdown = parsed;
this.pending_parse.take();
if this.should_reparse {
this.parse(cx);
this.parse(window, cx);
}
cx.notify();
})
@ -215,9 +217,9 @@ impl Markdown {
}
impl Render for Markdown {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
MarkdownElement::new(
cx.view().clone(),
cx.model().clone(),
self.style.clone(),
self.language_registry.clone(),
self.fallback_code_block_language.clone(),
@ -225,8 +227,8 @@ impl Render for Markdown {
}
}
impl FocusableView for Markdown {
fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
impl Focusable for Markdown {
fn focus_handle(&self, _cx: &App) -> FocusHandle {
self.focus_handle.clone()
}
}
@ -282,7 +284,7 @@ impl ParsedMarkdown {
}
pub struct MarkdownElement {
markdown: View<Markdown>,
markdown: Entity<Markdown>,
style: MarkdownStyle,
language_registry: Option<Arc<LanguageRegistry>>,
fallback_code_block_language: Option<String>,
@ -290,7 +292,7 @@ pub struct MarkdownElement {
impl MarkdownElement {
fn new(
markdown: View<Markdown>,
markdown: Entity<Markdown>,
style: MarkdownStyle,
language_registry: Option<Arc<LanguageRegistry>>,
fallback_code_block_language: Option<String>,
@ -303,7 +305,12 @@ impl MarkdownElement {
}
}
fn load_language(&self, name: &str, cx: &mut WindowContext) -> Option<Arc<Language>> {
fn load_language(
&self,
name: &str,
window: &mut Window,
cx: &mut App,
) -> Option<Arc<Language>> {
let language_test = self.language_registry.as_ref()?.language_for_name(name);
let language_name = match language_test.now_or_never() {
@ -325,11 +332,12 @@ impl MarkdownElement {
Some(language) => language,
None => {
let markdown = self.markdown.downgrade();
cx.spawn(|mut cx| async move {
language.await;
markdown.update(&mut cx, |_, cx| cx.notify())
})
.detach_and_log_err(cx);
window
.spawn(cx, |mut cx| async move {
language.await;
markdown.update(&mut cx, |_, cx| cx.notify())
})
.detach_and_log_err(cx);
None
}
}
@ -339,7 +347,8 @@ impl MarkdownElement {
&self,
bounds: Bounds<Pixels>,
rendered_text: &RenderedText,
cx: &mut WindowContext,
window: &mut Window,
cx: &mut App,
) {
let selection = self.markdown.read(cx).selection;
let selection_start = rendered_text.position_for_source_index(selection.start);
@ -349,7 +358,7 @@ impl MarkdownElement {
selection_start.zip(selection_end)
{
if start_position.y == end_position.y {
cx.paint_quad(quad(
window.paint_quad(quad(
Bounds::from_corners(
start_position,
point(end_position.x, end_position.y + end_line_height),
@ -360,7 +369,7 @@ impl MarkdownElement {
Hsla::transparent_black(),
));
} else {
cx.paint_quad(quad(
window.paint_quad(quad(
Bounds::from_corners(
start_position,
point(bounds.right(), start_position.y + start_line_height),
@ -372,7 +381,7 @@ impl MarkdownElement {
));
if end_position.y > start_position.y + start_line_height {
cx.paint_quad(quad(
window.paint_quad(quad(
Bounds::from_corners(
point(bounds.left(), start_position.y + start_line_height),
point(bounds.right(), end_position.y),
@ -384,7 +393,7 @@ impl MarkdownElement {
));
}
cx.paint_quad(quad(
window.paint_quad(quad(
Bounds::from_corners(
point(bounds.left(), end_position.y),
point(end_position.x, end_position.y + end_line_height),
@ -402,25 +411,26 @@ impl MarkdownElement {
&self,
hitbox: &Hitbox,
rendered_text: &RenderedText,
cx: &mut WindowContext,
window: &mut Window,
cx: &mut App,
) {
let is_hovering_link = hitbox.is_hovered(cx)
let is_hovering_link = hitbox.is_hovered(window)
&& !self.markdown.read(cx).selection.pending
&& rendered_text
.link_for_position(cx.mouse_position())
.link_for_position(window.mouse_position())
.is_some();
if is_hovering_link {
cx.set_cursor_style(CursorStyle::PointingHand, hitbox);
window.set_cursor_style(CursorStyle::PointingHand, hitbox);
} else {
cx.set_cursor_style(CursorStyle::IBeam, hitbox);
window.set_cursor_style(CursorStyle::IBeam, hitbox);
}
self.on_mouse_event(cx, {
self.on_mouse_event(window, cx, {
let rendered_text = rendered_text.clone();
let hitbox = hitbox.clone();
move |markdown, event: &MouseDownEvent, phase, cx| {
if hitbox.is_hovered(cx) {
move |markdown, event: &MouseDownEvent, phase, window, cx| {
if hitbox.is_hovered(window) {
if phase.bubble() {
if let Some(link) = rendered_text.link_for_position(event.position) {
markdown.pressed_link = Some(link.clone());
@ -442,8 +452,8 @@ impl MarkdownElement {
reversed: false,
pending: true,
};
cx.focus(&markdown.focus_handle);
cx.prevent_default()
window.focus(&markdown.focus_handle);
window.prevent_default()
}
cx.notify();
@ -455,11 +465,11 @@ impl MarkdownElement {
}
}
});
self.on_mouse_event(cx, {
self.on_mouse_event(window, cx, {
let rendered_text = rendered_text.clone();
let hitbox = hitbox.clone();
let was_hovering_link = is_hovering_link;
move |markdown, event: &MouseMoveEvent, phase, cx| {
move |markdown, event: &MouseMoveEvent, phase, window, cx| {
if phase.capture() {
return;
}
@ -473,7 +483,7 @@ impl MarkdownElement {
markdown.autoscroll_request = Some(source_index);
cx.notify();
} else {
let is_hovering_link = hitbox.is_hovered(cx)
let is_hovering_link = hitbox.is_hovered(window)
&& rendered_text.link_for_position(event.position).is_some();
if is_hovering_link != was_hovering_link {
cx.notify();
@ -481,9 +491,9 @@ impl MarkdownElement {
}
}
});
self.on_mouse_event(cx, {
self.on_mouse_event(window, cx, {
let rendered_text = rendered_text.clone();
move |markdown, event: &MouseUpEvent, phase, cx| {
move |markdown, event: &MouseUpEvent, phase, _, cx| {
if phase.bubble() {
if let Some(pressed_link) = markdown.pressed_link.take() {
if Some(&pressed_link) == rendered_text.link_for_position(event.position) {
@ -504,22 +514,27 @@ impl MarkdownElement {
});
}
fn autoscroll(&self, rendered_text: &RenderedText, cx: &mut WindowContext) -> Option<()> {
fn autoscroll(
&self,
rendered_text: &RenderedText,
window: &mut Window,
cx: &mut App,
) -> Option<()> {
let autoscroll_index = self
.markdown
.update(cx, |markdown, _| markdown.autoscroll_request.take())?;
let (position, line_height) = rendered_text.position_for_source_index(autoscroll_index)?;
let text_style = self.style.base_text_style.clone();
let font_id = cx.text_system().resolve_font(&text_style.font());
let font_size = text_style.font_size.to_pixels(cx.rem_size());
let em_width = cx
let font_id = window.text_system().resolve_font(&text_style.font());
let font_size = text_style.font_size.to_pixels(window.rem_size());
let em_width = window
.text_system()
.typographic_bounds(font_id, font_size, 'm')
.unwrap()
.size
.width;
cx.request_autoscroll(Bounds::from_corners(
window.request_autoscroll(Bounds::from_corners(
point(position.x - 3. * em_width, position.y - 3. * line_height),
point(position.x + 3. * em_width, position.y + 3. * line_height),
));
@ -528,14 +543,16 @@ impl MarkdownElement {
fn on_mouse_event<T: MouseEvent>(
&self,
cx: &mut WindowContext,
mut f: impl 'static + FnMut(&mut Markdown, &T, DispatchPhase, &mut ViewContext<Markdown>),
window: &mut Window,
_cx: &mut App,
mut f: impl 'static
+ FnMut(&mut Markdown, &T, DispatchPhase, &mut Window, &mut Context<Markdown>),
) {
cx.on_mouse_event({
window.on_mouse_event({
let markdown = self.markdown.downgrade();
move |event, phase, cx| {
move |event, phase, window, cx| {
markdown
.update(cx, |markdown, cx| f(markdown, event, phase, cx))
.update(cx, |markdown, cx| f(markdown, event, phase, window, cx))
.log_err();
}
});
@ -553,7 +570,8 @@ impl Element for MarkdownElement {
fn request_layout(
&mut self,
_id: Option<&GlobalElementId>,
cx: &mut WindowContext,
window: &mut Window,
cx: &mut App,
) -> (gpui::LayoutId, Self::RequestLayoutState) {
let mut builder = MarkdownElementBuilder::new(
self.style.base_text_style.clone(),
@ -605,7 +623,7 @@ impl Element for MarkdownElement {
}
MarkdownTag::CodeBlock(kind) => {
let language = if let CodeBlockKind::Fenced(language) = kind {
self.load_language(language.as_ref(), cx)
self.load_language(language.as_ref(), window, cx)
} else {
None
};
@ -694,14 +712,14 @@ impl Element for MarkdownElement {
IconButton::new(id, IconName::Copy)
.icon_color(Color::Muted)
.shape(ui::IconButtonShape::Square)
.tooltip(|cx| Tooltip::text("Copy Code Block", cx))
.tooltip(Tooltip::text("Copy Code Block"))
.on_click({
let code = without_fences(
parsed_markdown.source()[range.clone()].trim(),
)
.to_string();
move |_, cx| {
move |_, _, cx| {
cx.write_to_clipboard(ClipboardItem::new_string(
code.clone(),
))
@ -774,8 +792,8 @@ impl Element for MarkdownElement {
}
}
let mut rendered_markdown = builder.build();
let child_layout_id = rendered_markdown.element.request_layout(cx);
let layout_id = cx.request_layout(gpui::Style::default(), [child_layout_id]);
let child_layout_id = rendered_markdown.element.request_layout(window, cx);
let layout_id = window.request_layout(gpui::Style::default(), [child_layout_id], cx);
(layout_id, rendered_markdown)
}
@ -784,14 +802,15 @@ impl Element for MarkdownElement {
_id: Option<&GlobalElementId>,
bounds: Bounds<Pixels>,
rendered_markdown: &mut Self::RequestLayoutState,
cx: &mut WindowContext,
window: &mut Window,
cx: &mut App,
) -> Self::PrepaintState {
let focus_handle = self.markdown.read(cx).focus_handle.clone();
cx.set_focus_handle(&focus_handle);
window.set_focus_handle(&focus_handle, cx);
let hitbox = cx.insert_hitbox(bounds, false);
rendered_markdown.element.prepaint(cx);
self.autoscroll(&rendered_markdown.text, cx);
let hitbox = window.insert_hitbox(bounds, false);
rendered_markdown.element.prepaint(window, cx);
self.autoscroll(&rendered_markdown.text, window, cx);
hitbox
}
@ -801,25 +820,26 @@ impl Element for MarkdownElement {
bounds: Bounds<Pixels>,
rendered_markdown: &mut Self::RequestLayoutState,
hitbox: &mut Self::PrepaintState,
cx: &mut WindowContext,
window: &mut Window,
cx: &mut App,
) {
let mut context = KeyContext::default();
context.add("Markdown");
cx.set_key_context(context);
let view = self.markdown.clone();
cx.on_action(std::any::TypeId::of::<crate::Copy>(), {
window.set_key_context(context);
let model = self.markdown.clone();
window.on_action(std::any::TypeId::of::<crate::Copy>(), {
let text = rendered_markdown.text.clone();
move |_, phase, cx| {
move |_, phase, window, cx| {
let text = text.clone();
if phase == DispatchPhase::Bubble {
view.update(cx, move |this, cx| this.copy(&text, cx))
model.update(cx, move |this, cx| this.copy(&text, window, cx))
}
}
});
self.paint_mouse_listeners(hitbox, &rendered_markdown.text, cx);
rendered_markdown.element.paint(cx);
self.paint_selection(bounds, &rendered_markdown.text, cx);
self.paint_mouse_listeners(hitbox, &rendered_markdown.text, window, cx);
rendered_markdown.element.paint(window, cx);
self.paint_selection(bounds, &rendered_markdown.text, window, cx);
}
}