Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

gpui: Improve borrow and window error diagnostics (#66358)

Lukas Wirthc408f8efc41e
diff --git a/crates/gpui/src/app.rs b/crates/gpui/src/app.rs
index f321644eefb..e247dd45b4e 100644
--- a/crates/gpui/src/app.rs
+++ b/crates/gpui/src/app.rs
@@ -1,7 +1,7 @@
use scheduler::Instant;
use std::{
any::{TypeId, type_name},
- cell::{BorrowMutError, Cell, Ref, RefCell, RefMut},
+ cell::{Cell, Ref, RefCell, RefMut},
ffi::OsString,
marker::PhantomData,
mem,
@@ -87,22 +87,42 @@ pub struct AppCell {
borrow_origin: Cell<Option<(&'static std::panic::Location<'static>, &'static str)>>,
}
-impl AppCell {
- #[cold]
- #[track_caller]
- fn borrow_failed(&self, kind: &str) -> ! {
- let attempted = std::panic::Location::caller();
- if let Some((origin, existing_kind)) = self.borrow_origin.get() {
- panic!(
- "RefCell already borrowed: attempted {kind} App borrow at {attempted}; \
- existing {existing_kind} borrow group began at {origin}"
- );
+struct AppBorrowError {
+ attempted: &'static std::panic::Location<'static>,
+ kind: &'static str,
+ origin: Option<(&'static std::panic::Location<'static>, &'static str)>,
+}
+
+impl std::fmt::Display for AppBorrowError {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let Self {
+ attempted,
+ kind,
+ origin,
+ } = self;
+ write!(
+ formatter,
+ "RefCell already borrowed: attempted {kind} App borrow at {attempted}; "
+ )?;
+ match origin {
+ Some((origin, existing_kind)) => write!(
+ formatter,
+ "existing {existing_kind} borrow group began at {origin}"
+ ),
+ None => write!(formatter, "origin unavailable"),
}
- panic!(
- "RefCell already borrowed: attempted {kind} App borrow at {attempted}; origin unavailable"
- );
}
+}
+
+impl std::fmt::Debug for AppBorrowError {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ std::fmt::Display::fmt(self, formatter)
+ }
+}
+
+impl std::error::Error for AppBorrowError {}
+impl AppCell {
#[doc(hidden)]
#[track_caller]
pub fn borrow(&self) -> AppRef<'_> {
@@ -113,10 +133,16 @@ impl AppCell {
// Keep the first origin across overlapping shared borrows. The old
// origin may remain after release; the next group replaces it.
let starts_borrow_group = self.app.try_borrow_mut().is_ok();
- let borrow = match self.app.try_borrow() {
- Ok(borrow) => borrow,
- Err(_) => self.borrow_failed("shared"),
- };
+ let attempted = std::panic::Location::caller();
+ let borrow = self
+ .app
+ .try_borrow()
+ .map_err(|_error| AppBorrowError {
+ attempted,
+ kind: "shared",
+ origin: self.borrow_origin.get(),
+ })
+ .unwrap();
if starts_borrow_group {
self.borrow_origin
.set(Some((std::panic::Location::caller(), "shared")));
@@ -127,20 +153,27 @@ impl AppCell {
#[doc(hidden)]
#[track_caller]
pub fn borrow_mut(&self) -> AppRefMut<'_> {
- match self.try_borrow_mut() {
- Ok(borrow) => borrow,
- Err(_) => self.borrow_failed("mutable"),
- }
+ self.try_borrow_mut().unwrap()
}
#[doc(hidden)]
#[track_caller]
- pub fn try_borrow_mut(&self) -> Result<AppRefMut<'_>, BorrowMutError> {
+ pub fn try_borrow_mut(&self) -> Result<AppRefMut<'_>> {
if option_env!("TRACK_THREAD_BORROWS").is_some() {
let thread_id = std::thread::current().id();
eprintln!("borrowed {thread_id:?}");
}
- let borrow = self.app.try_borrow_mut()?;
+ let borrow = match self.app.try_borrow_mut() {
+ Ok(borrow) => borrow,
+ Err(_error) => {
+ return Err(AppBorrowError {
+ attempted: std::panic::Location::caller(),
+ kind: "mutable",
+ origin: self.borrow_origin.get(),
+ }
+ .into());
+ }
+ };
self.borrow_origin
.set(Some((std::panic::Location::caller(), "mutable")));
Ok(AppRefMut(borrow))
diff --git a/crates/gpui/src/app/async_context.rs b/crates/gpui/src/app/async_context.rs
index 7190dff709b..24aeff467b7 100644
--- a/crates/gpui/src/app/async_context.rs
+++ b/crates/gpui/src/app/async_context.rs
@@ -312,6 +312,7 @@ impl AsyncWindowContext {
/// A convenience method for [`App::update_window`].
#[inline(always)]
+ #[track_caller]
pub fn update<R>(&mut self, update: impl FnOnce(&mut Window, &mut App) -> R) -> Result<R> {
self.app
.update_window(self.window, |_, window, cx| update(window, cx))
@@ -319,6 +320,7 @@ impl AsyncWindowContext {
/// A convenience method for [`App::update_window`].
#[inline(always)]
+ #[track_caller]
pub fn update_root<R>(
&mut self,
update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
diff --git a/crates/gpui/src/gpui.rs b/crates/gpui/src/gpui.rs
index dbb8386d063..5b31a3557fb 100644
--- a/crates/gpui/src/gpui.rs
+++ b/crates/gpui/src/gpui.rs
@@ -210,6 +210,7 @@ pub trait AppContext {
T: 'static;
/// Update a window for the given handle.
+ #[track_caller]
fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
where
F: FnOnce(AnyView, &mut Window, &mut App) -> T;
diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs
index 3802130e5f6..c2ba13d506a 100644
--- a/crates/gpui/src/window.rs
+++ b/crates/gpui/src/window.rs
@@ -1755,19 +1755,43 @@ impl Window {
Box::new(move || {
log::info!("Accessibility activated");
active_flag.store(true, SeqCst);
- activation_sender.send_blocking(()).log_err();
+ activation_sender
+ .send_blocking(())
+ .with_context(|| {
+ format!(
+ "queuing accessibility activation for window {:?}",
+ handle.window_id()
+ )
+ })
+ .log_err();
Some(initial_tree.clone())
})
},
action: Box::new(move |request| {
- action_sender.send_blocking(request).log_err();
+ action_sender
+ .send_blocking(request)
+ .with_context(|| {
+ format!(
+ "queuing accessibility action for window {:?}",
+ handle.window_id()
+ )
+ })
+ .log_err();
}),
deactivation: {
let active_flag = a11y_active_flag.clone();
Box::new(move || {
log::info!("Accessibility deactivated");
active_flag.store(false, SeqCst);
- deactivation_sender.send_blocking(()).log_err();
+ deactivation_sender
+ .send_blocking(())
+ .with_context(|| {
+ format!(
+ "queuing accessibility deactivation for window {:?}",
+ handle.window_id()
+ )
+ })
+ .log_err();
})
},
});
@@ -1783,6 +1807,12 @@ impl Window {
while activation_receiver.recv().await.is_ok() {
handle
.update(&mut async_cx, |_, window, _| window.refresh())
+ .with_context(|| {
+ format!(
+ "handling accessibility activation for window {:?}",
+ handle.window_id()
+ )
+ })
.log_err();
}
})
@@ -1794,6 +1824,12 @@ impl Window {
while deactivation_receiver.recv().await.is_ok() {
handle
.update(&mut async_cx, |_, window, _| window.refresh())
+ .with_context(|| {
+ format!(
+ "handling accessibility deactivation for window {:?}",
+ handle.window_id()
+ )
+ })
.log_err();
}
})
@@ -1807,6 +1843,12 @@ impl Window {
.update(&mut async_cx, |_, window, cx| {
window.handle_a11y_action(request, cx);
})
+ .with_context(|| {
+ format!(
+ "handling accessibility action for window {:?}",
+ handle.window_id()
+ )
+ })
.log_err();
}
})
@@ -1825,6 +1867,7 @@ impl Window {
if cx.windows.contains_key(window_id) {
handle
.update(cx, |_, window, _| window.remove_window())
+ .with_context(|| format!("handling close for window {window_id:?}"))
.log_err();
}
SystemWindowTabController::remove_tab(cx, window_id);
@@ -1885,6 +1928,12 @@ impl Window {
let power_state = handle
.update(&mut cx, |_, _, cx| (cx.thermal_state(), cx.power_mode()))
+ .with_context(|| {
+ format!(
+ "reading power state for frame request for window {:?}",
+ handle.window_id()
+ )
+ })
.log_err();
// Keep presenting briefly after high-rate input to prevent display
@@ -1924,6 +1973,12 @@ impl Window {
.update(&mut cx, |_, window, _| {
window.platform_window.schedule_frame();
})
+ .with_context(|| {
+ format!(
+ "rescheduling throttled frame for window {:?}",
+ handle.window_id()
+ )
+ })
.log_err();
// The demand is still unserved; platforms that stop
// requesting frames for idle windows need a wakeup to retry.
@@ -1955,6 +2010,12 @@ impl Window {
callback(window, cx);
}
})
+ .with_context(|| {
+ format!(
+ "running next-frame callbacks for window {:?}",
+ handle.window_id()
+ )
+ })
.log_err();
}
@@ -1979,11 +2040,20 @@ impl Window {
window.present();
arena_clear_needed.clear(cx);
})
+ .with_context(|| {
+ format!(
+ "drawing and presenting frame for window {:?}",
+ handle.window_id()
+ )
+ })
.log_err();
})
} else if needs_present {
handle
.update(&mut cx, |_, window, _| window.present())
+ .with_context(|| {
+ format!("presenting frame for window {:?}", handle.window_id())
+ })
.log_err();
}
@@ -1995,6 +2065,12 @@ impl Window {
window.platform_window.schedule_frame();
}
})
+ .with_context(|| {
+ format!(
+ "scheduling follow-up frame for window {:?}",
+ handle.window_id()
+ )
+ })
.log_err();
// Platforms that stop requesting frames for idle windows only
@@ -2021,6 +2097,12 @@ impl Window {
move || {
handle
.update(&mut cx, |_, window, _| window.refresh())
+ .with_context(|| {
+ format!(
+ "handling visual viewport change for window {:?}",
+ handle.window_id()
+ )
+ })
.log_err();
}
}));
@@ -2029,6 +2111,9 @@ impl Window {
move |_| {
handle
.update(&mut cx, |_, window, _| window.refresh())
+ .with_context(|| {
+ format!("handling insets change for window {:?}", handle.window_id())
+ })
.log_err();
}
}));
@@ -2037,6 +2122,7 @@ impl Window {
move |_, _| {
handle
.update(&mut cx, |_, window, cx| window.bounds_changed(cx))
+ .with_context(|| format!("handling resize for window {:?}", handle.window_id()))
.log_err();
}
}));
@@ -2045,6 +2131,7 @@ impl Window {
move || {
handle
.update(&mut cx, |_, window, cx| window.bounds_changed(cx))
+ .with_context(|| format!("handling move for window {:?}", handle.window_id()))
.log_err();
}
}));
@@ -2063,6 +2150,12 @@ impl Window {
.spawn(async move {
handle
.update(&mut cx, |_, window, cx| window.appearance_changed(cx))
+ .with_context(|| {
+ format!(
+ "handling appearance change for window {:?}",
+ handle.window_id()
+ )
+ })
.log_err();
})
.detach();
@@ -2073,6 +2166,12 @@ impl Window {
move || {
handle
.update(&mut cx, |_, window, cx| window.button_layout_changed(cx))
+ .with_context(|| {
+ format!(
+ "handling button layout change for window {:?}",
+ handle.window_id()
+ )
+ })
.log_err();
}
}));
@@ -2094,6 +2193,12 @@ impl Window {
SystemWindowTabController::update_last_active(cx, window.handle.id);
})
+ .with_context(|| {
+ format!(
+ "handling active status change for window {:?}",
+ handle.window_id()
+ )
+ })
.log_err();
}
}));
@@ -2104,6 +2209,12 @@ impl Window {
.update(&mut cx, |_, window, cx| {
window.refresh_visibility(cx);
})
+ .with_context(|| {
+ format!(
+ "handling visibility change for window {:?}",
+ handle.window_id()
+ )
+ })
.log_err();
}
}));
@@ -2115,6 +2226,12 @@ impl Window {
window.hovered.set(active);
window.refresh();
})
+ .with_context(|| {
+ format!(
+ "handling hover status change for window {:?}",
+ handle.window_id()
+ )
+ })
.log_err();
}
}));
@@ -2123,6 +2240,9 @@ impl Window {
Box::new(move |event| {
handle
.update(&mut cx, |_, window, cx| window.dispatch_event(event, cx))
+ .with_context(|| {
+ format!("dispatching input for window {:?}", handle.window_id())
+ })
.log_err()
.unwrap_or(DispatchEventResult::default())
})
@@ -2139,6 +2259,12 @@ impl Window {
}
None
})
+ .with_context(|| {
+ format!(
+ "hit-testing window controls for window {:?}",
+ handle.window_id()
+ )
+ })
.log_err()
.unwrap_or(None)
})
@@ -2150,6 +2276,12 @@ impl Window {
.update(&mut cx, |_, _window, cx| {
SystemWindowTabController::move_tab_to_new_window(cx, handle.window_id());
})
+ .with_context(|| {
+ format!(
+ "moving tab to new window from window {:?}",
+ handle.window_id()
+ )
+ })
.log_err();
})
});
@@ -2160,6 +2292,9 @@ impl Window {
.update(&mut cx, |_, _window, cx| {
SystemWindowTabController::merge_all_windows(cx, handle.window_id());
})
+ .with_context(|| {
+ format!("merging all windows into window {:?}", handle.window_id())
+ })
.log_err();
})
});
@@ -2170,6 +2305,9 @@ impl Window {
.update(&mut cx, |_, _window, cx| {
SystemWindowTabController::select_next_tab(cx, handle.window_id());
})
+ .with_context(|| {
+ format!("selecting next tab for window {:?}", handle.window_id())
+ })
.log_err();
})
});
@@ -2180,6 +2318,9 @@ impl Window {
.update(&mut cx, |_, _window, cx| {
SystemWindowTabController::select_previous_tab(cx, handle.window_id())
})
+ .with_context(|| {
+ format!("selecting previous tab for window {:?}", handle.window_id())
+ })
.log_err();
})
});
@@ -2191,6 +2332,9 @@ impl Window {
let tab_bar_visible = window.platform_window.tab_bar_visible();
SystemWindowTabController::set_visible(cx, tab_bar_visible);
})
+ .with_context(|| {
+ format!("toggling tab bar for window {:?}", handle.window_id())
+ })
.log_err();
})
});
@@ -2621,6 +2765,7 @@ impl Window {
let node_id = window.focus_node_id_in_rendered_frame(focus_id);
window.dispatch_action_on_node(node_id, action.as_ref(), cx);
})
+ .with_context(|| format!("dispatching action for window {:?}", window.window_id()))
.log_err();
})
}
@@ -2872,6 +3017,12 @@ impl Window {
window.display_id = display_id;
moved.then_some(display_id)
})
+ .with_context(|| {
+ format!(
+ "handling display change for window {:?}",
+ handle.window_id()
+ )
+ })
.log_err()
.flatten();
let Some(display_id) = moved_to else {
@@ -2887,6 +3038,12 @@ impl Window {
}
handle
.update(cx, |_, window, cx| window.notify_display_observers(cx))
+ .with_context(|| {
+ format!(
+ "notifying display observers for window {:?}",
+ handle.window_id()
+ )
+ })
.log_err();
}
@@ -6008,6 +6165,12 @@ impl Window {
window.dispatch_recognized_touch_gesture(gesture, cx);
}
})
+ .with_context(|| {
+ format!(
+ "handling long-press timer for window {:?}",
+ cx.window_handle().window_id()
+ )
+ })
.log_err();
}));
}
@@ -6307,6 +6470,12 @@ impl Window {
window.pending_input_changed(cx);
window.replay_pending_input(to_replay, cx)
})
+ .with_context(|| {
+ format!(
+ "handling pending input timeout for window {:?}",
+ cx.window_handle().window_id()
+ )
+ })
.log_err();
});
(started_at, task)
@@ -7511,6 +7680,7 @@ impl<V: 'static + Render> WindowHandle<V> {
/// Updates the root view of this window.
///
/// This will fail if the window has been closed or if the root view's type does not match
+ #[track_caller]
pub fn update<C, R>(
&self,
cx: &mut C,
@@ -7640,6 +7810,7 @@ impl AnyWindowHandle {
/// Updates the state of the root view of this window.
///
/// This will fail if the window has been closed.
+ #[track_caller]
pub fn update<C, R>(
self,
cx: &mut C,