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,17 +1,16 @@
use crate::{Toast, Workspace};
use anyhow::Context;
use anyhow::Context as _;
use anyhow::{anyhow, Result};
use gpui::{
svg, AnyView, AppContext, AsyncWindowContext, ClipboardItem, DismissEvent, EventEmitter,
Global, PromptLevel, Render, ScrollHandle, Task, View, ViewContext, VisualContext,
WindowContext,
svg, AnyView, App, AppContext as _, AsyncWindowContext, ClipboardItem, Context, DismissEvent,
Entity, EventEmitter, Global, PromptLevel, Render, ScrollHandle, Task,
};
use std::rc::Rc;
use std::{any::TypeId, time::Duration};
use ui::{prelude::*, Tooltip};
use util::ResultExt;
pub fn init(cx: &mut AppContext) {
pub fn init(cx: &mut App) {
cx.set_global(GlobalAppNotifications {
app_notifications: Vec::new(),
})
@ -59,8 +58,8 @@ impl Workspace {
pub fn show_notification<V: Notification>(
&mut self,
id: NotificationId,
cx: &mut ViewContext<Self>,
build_notification: impl FnOnce(&mut ViewContext<Self>) -> View<V>,
cx: &mut Context<Self>,
build_notification: impl FnOnce(&mut Context<Self>) -> Entity<V>,
) {
self.show_notification_without_handling_dismiss_events(&id, cx, |cx| {
let notification = build_notification(cx);
@ -83,8 +82,8 @@ impl Workspace {
pub(crate) fn show_notification_without_handling_dismiss_events(
&mut self,
id: &NotificationId,
cx: &mut ViewContext<Self>,
build_notification: impl FnOnce(&mut ViewContext<Self>) -> AnyView,
cx: &mut Context<Self>,
build_notification: impl FnOnce(&mut Context<Self>) -> AnyView,
) {
self.dismiss_notification(id, cx);
self.notifications
@ -92,20 +91,20 @@ impl Workspace {
cx.notify();
}
pub fn show_error<E>(&mut self, err: &E, cx: &mut ViewContext<Self>)
pub fn show_error<E>(&mut self, err: &E, cx: &mut Context<Self>)
where
E: std::fmt::Debug + std::fmt::Display,
{
self.show_notification(workspace_error_notification_id(), cx, |cx| {
cx.new_view(|_cx| ErrorMessagePrompt::new(format!("Error: {err}")))
cx.new(|_| ErrorMessagePrompt::new(format!("Error: {err}")))
});
}
pub fn show_portal_error(&mut self, err: String, cx: &mut ViewContext<Self>) {
pub fn show_portal_error(&mut self, err: String, cx: &mut Context<Self>) {
struct PortalError;
self.show_notification(NotificationId::unique::<PortalError>(), cx, |cx| {
cx.new_view(|_cx| {
cx.new(|_| {
ErrorMessagePrompt::new(err.to_string()).with_link_button(
"See docs",
"https://zed.dev/docs/linux#i-cant-open-any-files",
@ -114,7 +113,7 @@ impl Workspace {
});
}
pub fn dismiss_notification(&mut self, id: &NotificationId, cx: &mut ViewContext<Self>) {
pub fn dismiss_notification(&mut self, id: &NotificationId, cx: &mut Context<Self>) {
self.notifications.retain(|(existing_id, _)| {
if existing_id == id {
cx.notify();
@ -125,15 +124,15 @@ impl Workspace {
});
}
pub fn show_toast(&mut self, toast: Toast, cx: &mut ViewContext<Self>) {
pub fn show_toast(&mut self, toast: Toast, cx: &mut Context<Self>) {
self.dismiss_notification(&toast.id, cx);
self.show_notification(toast.id.clone(), cx, |cx| {
cx.new_view(|_cx| match toast.on_click.as_ref() {
cx.new(|_| match toast.on_click.as_ref() {
Some((click_msg, on_click)) => {
let on_click = on_click.clone();
simple_message_notification::MessageNotification::new(toast.msg.clone())
.with_click_message(click_msg.clone())
.on_click(move |cx| on_click(cx))
.on_click(move |window, cx| on_click(window, cx))
}
None => simple_message_notification::MessageNotification::new(toast.msg.clone()),
})
@ -153,16 +152,16 @@ impl Workspace {
}
}
pub fn dismiss_toast(&mut self, id: &NotificationId, cx: &mut ViewContext<Self>) {
pub fn dismiss_toast(&mut self, id: &NotificationId, cx: &mut Context<Self>) {
self.dismiss_notification(id, cx);
}
pub fn clear_all_notifications(&mut self, cx: &mut ViewContext<Self>) {
pub fn clear_all_notifications(&mut self, cx: &mut Context<Self>) {
self.notifications.clear();
cx.notify();
}
pub fn show_initial_notifications(&mut self, cx: &mut ViewContext<Self>) {
pub fn show_initial_notifications(&mut self, cx: &mut Context<Self>) {
// Allow absence of the global so that tests don't need to initialize it.
let app_notifications = cx
.try_global::<GlobalAppNotifications>()
@ -190,7 +189,7 @@ impl LanguageServerPrompt {
}
}
async fn select_option(this: View<Self>, ix: usize, mut cx: AsyncWindowContext) {
async fn select_option(this: Entity<Self>, ix: usize, mut cx: AsyncWindowContext) {
util::maybe!(async move {
let potential_future = this.update(&mut cx, |this, _| {
this.request.take().map(|request| request.respond(ix))
@ -211,7 +210,7 @@ impl LanguageServerPrompt {
}
impl Render for LanguageServerPrompt {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let Some(request) = &self.request else {
return div().id("language_server_prompt_notification");
};
@ -227,7 +226,7 @@ impl Render for LanguageServerPrompt {
.group("language_server_prompt_notification")
.occlude()
.w_full()
.max_h(vh(0.8, cx))
.max_h(vh(0.8, window))
.elevation_3(cx)
.overflow_y_scroll()
.track_scroll(&self.scroll_handle)
@ -251,30 +250,32 @@ impl Render for LanguageServerPrompt {
IconButton::new("copy", IconName::Copy)
.on_click({
let message = request.message.clone();
move |_, cx| {
move |_, _, cx| {
cx.write_to_clipboard(
ClipboardItem::new_string(message.clone()),
)
}
})
.tooltip(|cx| Tooltip::text("Copy Description", cx)),
.tooltip(Tooltip::text("Copy Description")),
)
.child(IconButton::new("close", IconName::Close).on_click(
cx.listener(|_, _, cx| cx.emit(gpui::DismissEvent)),
cx.listener(|_, _, _, cx| cx.emit(gpui::DismissEvent)),
)),
),
)
.child(Label::new(request.message.to_string()).size(LabelSize::Small))
.children(request.actions.iter().enumerate().map(|(ix, action)| {
let this_handle = cx.view().clone();
let this_handle = cx.model().clone();
Button::new(ix, action.title.clone())
.size(ButtonSize::Large)
.on_click(move |_, cx| {
.on_click(move |_, window, cx| {
let this_handle = this_handle.clone();
cx.spawn(|cx| async move {
LanguageServerPrompt::select_option(this_handle, ix, cx).await
})
.detach()
window
.spawn(cx, |cx| async move {
LanguageServerPrompt::select_option(this_handle, ix, cx)
.await
})
.detach()
})
})),
)
@ -315,7 +316,7 @@ impl ErrorMessagePrompt {
}
impl Render for ErrorMessagePrompt {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
h_flex()
.id("error_message_prompt_notification")
.occlude()
@ -334,7 +335,7 @@ impl Render for ErrorMessagePrompt {
.justify_between()
.child(
svg()
.size(cx.text_style().font_size)
.size(window.text_style().font_size)
.flex_none()
.mr_2()
.mt(px(-2.0))
@ -344,8 +345,9 @@ impl Render for ErrorMessagePrompt {
}),
)
.child(
ui::IconButton::new("close", ui::IconName::Close)
.on_click(cx.listener(|_, _, cx| cx.emit(gpui::DismissEvent))),
ui::IconButton::new("close", ui::IconName::Close).on_click(
cx.listener(|_, _, _, cx| cx.emit(gpui::DismissEvent)),
),
),
)
.child(
@ -360,7 +362,7 @@ impl Render for ErrorMessagePrompt {
elm.child(
div().mt_2().child(
ui::Button::new("error_message_prompt_notification_button", label)
.on_click(move |_, cx| cx.open_url(&url)),
.on_click(move |_, _, cx| cx.open_url(&url)),
),
)
}),
@ -375,16 +377,15 @@ pub mod simple_message_notification {
use gpui::{
div, AnyElement, DismissEvent, EventEmitter, ParentElement, Render, SharedString, Styled,
ViewContext,
};
use ui::prelude::*;
pub struct MessageNotification {
content: Box<dyn Fn(&mut ViewContext<Self>) -> AnyElement>,
on_click: Option<Arc<dyn Fn(&mut ViewContext<Self>)>>,
build_content: Box<dyn Fn(&mut Window, &mut Context<Self>) -> AnyElement>,
on_click: Option<Arc<dyn Fn(&mut Window, &mut Context<Self>)>>,
click_message: Option<SharedString>,
secondary_click_message: Option<SharedString>,
secondary_on_click: Option<Arc<dyn Fn(&mut ViewContext<Self>)>>,
secondary_on_click: Option<Arc<dyn Fn(&mut Window, &mut Context<Self>)>>,
}
impl EventEmitter<DismissEvent> for MessageNotification {}
@ -395,15 +396,15 @@ pub mod simple_message_notification {
S: Into<SharedString>,
{
let message = message.into();
Self::new_from_builder(move |_| Label::new(message.clone()).into_any_element())
Self::new_from_builder(move |_, _| Label::new(message.clone()).into_any_element())
}
pub fn new_from_builder<F>(content: F) -> MessageNotification
where
F: 'static + Fn(&mut ViewContext<Self>) -> AnyElement,
F: 'static + Fn(&mut Window, &mut Context<Self>) -> AnyElement,
{
Self {
content: Box::new(content),
build_content: Box::new(content),
on_click: None,
click_message: None,
secondary_on_click: None,
@ -421,7 +422,7 @@ pub mod simple_message_notification {
pub fn on_click<F>(mut self, on_click: F) -> Self
where
F: 'static + Fn(&mut ViewContext<Self>),
F: 'static + Fn(&mut Window, &mut Context<Self>),
{
self.on_click = Some(Arc::new(on_click));
self
@ -437,19 +438,19 @@ pub mod simple_message_notification {
pub fn on_secondary_click<F>(mut self, on_click: F) -> Self
where
F: 'static + Fn(&mut ViewContext<Self>),
F: 'static + Fn(&mut Window, &mut Context<Self>),
{
self.secondary_on_click = Some(Arc::new(on_click));
self
}
pub fn dismiss(&mut self, cx: &mut ViewContext<Self>) {
pub fn dismiss(&mut self, cx: &mut Context<Self>) {
cx.emit(DismissEvent);
}
}
impl Render for MessageNotification {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
v_flex()
.p_3()
.gap_2()
@ -459,10 +460,10 @@ pub mod simple_message_notification {
.gap_4()
.justify_between()
.items_start()
.child(div().max_w_96().child((self.content)(cx)))
.child(div().max_w_96().child((self.build_content)(window, cx)))
.child(
IconButton::new("close", IconName::Close)
.on_click(cx.listener(|this, _, cx| this.dismiss(cx))),
.on_click(cx.listener(|this, _, _, cx| this.dismiss(cx))),
),
)
.child(
@ -475,9 +476,9 @@ pub mod simple_message_notification {
.icon_position(IconPosition::Start)
.icon_size(IconSize::Small)
.icon_color(Color::Success)
.on_click(cx.listener(|this, _, cx| {
.on_click(cx.listener(|this, _, window, cx| {
if let Some(on_click) = this.on_click.as_ref() {
(on_click)(cx)
(on_click)(window, cx)
};
this.dismiss(cx)
}))
@ -489,9 +490,9 @@ pub mod simple_message_notification {
.icon_position(IconPosition::Start)
.icon_size(IconSize::Small)
.icon_color(Color::Error)
.on_click(cx.listener(|this, _, cx| {
.on_click(cx.listener(|this, _, window, cx| {
if let Some(on_click) = this.secondary_on_click.as_ref() {
(on_click)(cx)
(on_click)(window, cx)
};
this.dismiss(cx)
}))
@ -505,7 +506,7 @@ pub mod simple_message_notification {
struct GlobalAppNotifications {
app_notifications: Vec<(
NotificationId,
Rc<dyn Fn(&mut ViewContext<Workspace>) -> AnyView>,
Rc<dyn Fn(&mut Context<Workspace>) -> AnyView>,
)>,
}
@ -515,7 +516,7 @@ impl GlobalAppNotifications {
pub fn insert(
&mut self,
id: NotificationId,
build_notification: Rc<dyn Fn(&mut ViewContext<Workspace>) -> AnyView>,
build_notification: Rc<dyn Fn(&mut Context<Workspace>) -> AnyView>,
) {
self.remove(&id);
self.app_notifications.push((id, build_notification))
@ -532,11 +533,11 @@ impl GlobalAppNotifications {
/// exist. If the notification is dismissed within any workspace, it will be removed from all.
pub fn show_app_notification<V: Notification + 'static>(
id: NotificationId,
cx: &mut AppContext,
build_notification: impl Fn(&mut ViewContext<Workspace>) -> View<V> + 'static,
cx: &mut App,
build_notification: impl Fn(&mut Context<Workspace>) -> Entity<V> + 'static,
) -> Result<()> {
// Handle dismiss events by removing the notification from all workspaces.
let build_notification: Rc<dyn Fn(&mut ViewContext<Workspace>) -> AnyView> = Rc::new({
let build_notification: Rc<dyn Fn(&mut Context<Workspace>) -> AnyView> = Rc::new({
let id = id.clone();
move |cx| {
let notification = build_notification(cx);
@ -559,7 +560,7 @@ pub fn show_app_notification<V: Notification + 'static>(
for window in cx.windows() {
if let Some(workspace_window) = window.downcast::<Workspace>() {
let notify_result = workspace_window.update(cx, |workspace, cx| {
let notify_result = workspace_window.update(cx, |workspace, _window, cx| {
workspace.show_notification_without_handling_dismiss_events(&id, cx, |cx| {
build_notification(cx)
});
@ -585,7 +586,7 @@ pub fn show_app_notification<V: Notification + 'static>(
}
}
pub fn dismiss_app_notification(id: &NotificationId, cx: &mut AppContext) {
pub fn dismiss_app_notification(id: &NotificationId, cx: &mut App) {
cx.global_mut::<GlobalAppNotifications>().remove(id);
for window in cx.windows() {
if let Some(workspace_window) = window.downcast::<Workspace>() {
@ -593,7 +594,7 @@ pub fn dismiss_app_notification(id: &NotificationId, cx: &mut AppContext) {
// This spawn is necessary in order to dismiss the notification on which the click
// occurred, because in that case we're already in the middle of an update.
cx.spawn(move |mut cx| async move {
workspace_window.update(&mut cx, |workspace, cx| {
workspace_window.update(&mut cx, |workspace, _window, cx| {
workspace.dismiss_notification(&id, cx)
})
})
@ -605,16 +606,13 @@ pub fn dismiss_app_notification(id: &NotificationId, cx: &mut AppContext) {
pub trait NotifyResultExt {
type Ok;
fn notify_err(
self,
workspace: &mut Workspace,
cx: &mut ViewContext<Workspace>,
) -> Option<Self::Ok>;
fn notify_err(self, workspace: &mut Workspace, cx: &mut Context<Workspace>)
-> Option<Self::Ok>;
fn notify_async_err(self, cx: &mut AsyncWindowContext) -> Option<Self::Ok>;
/// Notifies the active workspace if there is one, otherwise notifies all workspaces.
fn notify_app_err(self, cx: &mut AppContext) -> Option<Self::Ok>;
fn notify_app_err(self, cx: &mut App) -> Option<Self::Ok>;
}
impl<T, E> NotifyResultExt for std::result::Result<T, E>
@ -623,7 +621,7 @@ where
{
type Ok = T;
fn notify_err(self, workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) -> Option<T> {
fn notify_err(self, workspace: &mut Workspace, cx: &mut Context<Workspace>) -> Option<T> {
match self {
Ok(value) => Some(value),
Err(err) => {
@ -639,7 +637,7 @@ where
Ok(value) => Some(value),
Err(err) => {
log::error!("{err:?}");
cx.update_root(|view, cx| {
cx.update_root(|view, _, cx| {
if let Ok(workspace) = view.downcast::<Workspace>() {
workspace.update(cx, |workspace, cx| workspace.show_error(&err, cx))
}
@ -650,7 +648,7 @@ where
}
}
fn notify_app_err(self, cx: &mut AppContext) -> Option<T> {
fn notify_app_err(self, cx: &mut App) -> Option<T> {
match self {
Ok(value) => Some(value),
Err(err) => {
@ -659,7 +657,7 @@ where
show_app_notification(workspace_error_notification_id(), cx, {
let message = message.clone();
move |cx| {
cx.new_view({
cx.new({
let message = message.clone();
move |_cx| ErrorMessagePrompt::new(message)
})
@ -674,7 +672,7 @@ where
}
pub trait NotifyTaskExt {
fn detach_and_notify_err(self, cx: &mut WindowContext);
fn detach_and_notify_err(self, window: &mut Window, cx: &mut App);
}
impl<R, E> NotifyTaskExt for Task<std::result::Result<R, E>>
@ -682,8 +680,12 @@ where
E: std::fmt::Debug + std::fmt::Display + Sized + 'static,
R: 'static,
{
fn detach_and_notify_err(self, cx: &mut WindowContext) {
cx.spawn(|mut cx| async move { self.await.notify_async_err(&mut cx) })
fn detach_and_notify_err(self, window: &mut Window, cx: &mut App) {
window
.spawn(
cx,
|mut cx| async move { self.await.notify_async_err(&mut cx) },
)
.detach();
}
}
@ -692,15 +694,17 @@ pub trait DetachAndPromptErr<R> {
fn prompt_err(
self,
msg: &str,
cx: &mut WindowContext,
f: impl FnOnce(&anyhow::Error, &mut WindowContext) -> Option<String> + 'static,
window: &Window,
cx: &App,
f: impl FnOnce(&anyhow::Error, &mut Window, &mut App) -> Option<String> + 'static,
) -> Task<Option<R>>;
fn detach_and_prompt_err(
self,
msg: &str,
cx: &mut WindowContext,
f: impl FnOnce(&anyhow::Error, &mut WindowContext) -> Option<String> + 'static,
window: &Window,
cx: &App,
f: impl FnOnce(&anyhow::Error, &mut Window, &mut App) -> Option<String> + 'static,
);
}
@ -711,17 +715,19 @@ where
fn prompt_err(
self,
msg: &str,
cx: &mut WindowContext,
f: impl FnOnce(&anyhow::Error, &mut WindowContext) -> Option<String> + 'static,
window: &Window,
cx: &App,
f: impl FnOnce(&anyhow::Error, &mut Window, &mut App) -> Option<String> + 'static,
) -> Task<Option<R>> {
let msg = msg.to_owned();
cx.spawn(|mut cx| async move {
window.spawn(cx, |mut cx| async move {
let result = self.await;
if let Err(err) = result.as_ref() {
log::error!("{err:?}");
if let Ok(prompt) = cx.update(|cx| {
let detail = f(err, cx).unwrap_or_else(|| format!("{err}. Please try again."));
cx.prompt(PromptLevel::Critical, &msg, Some(&detail), &["Ok"])
if let Ok(prompt) = cx.update(|window, cx| {
let detail =
f(err, window, cx).unwrap_or_else(|| format!("{err}. Please try again."));
window.prompt(PromptLevel::Critical, &msg, Some(&detail), &["Ok"], cx)
}) {
prompt.await.ok();
}
@ -734,9 +740,10 @@ where
fn detach_and_prompt_err(
self,
msg: &str,
cx: &mut WindowContext,
f: impl FnOnce(&anyhow::Error, &mut WindowContext) -> Option<String> + 'static,
window: &Window,
cx: &App,
f: impl FnOnce(&anyhow::Error, &mut Window, &mut App) -> Option<String> + 'static,
) {
self.prompt_err(msg, cx, f).detach();
self.prompt_err(msg, window, cx, f).detach();
}
}