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.

Optimize GPUI inspector's runtime cost by an order of magnitude (#64309)

Kirill Bulatovb0f53ad23be8
diff --git a/Cargo.lock b/Cargo.lock
index e138b408e70..eedc24dbdd9 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -7693,6 +7693,7 @@ name = "gpui_platform"
version = "0.1.0"
dependencies = [
"console_error_panic_hook",
+ "criterion",
"gpui",
"gpui_linux",
"gpui_macos",
@@ -8909,12 +8910,18 @@ dependencies = [
"anyhow",
"command_palette_hooks",
"editor",
+ "fs",
+ "futures 0.3.34",
"fuzzy",
"gpui",
"language",
+ "paths",
"project",
"serde_json",
"serde_json_lenient",
+ "settings",
+ "snippet_provider",
+ "theme",
"theme_settings",
"ui",
"util",
diff --git a/crates/gpui/src/app.rs b/crates/gpui/src/app.rs
index 27562e5e530..5f91a9d7ed1 100644
--- a/crates/gpui/src/app.rs
+++ b/crates/gpui/src/app.rs
@@ -2897,11 +2897,13 @@ impl App {
/// Registers a renderer specific to an inspector state.
#[cfg(any(feature = "inspector", debug_assertions))]
- pub fn register_inspector_element<T: 'static, R: crate::IntoElement>(
+ pub fn register_inspector_element<T: 'static, R: crate::IntoElement, F>(
&mut self,
- f: impl 'static + Fn(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
- ) {
- self.inspector_element_registry.register(f);
+ factory: impl 'static + Fn(&mut Window, &mut App) -> F,
+ ) where
+ F: 'static + FnMut(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
+ {
+ self.inspector_element_registry.register(factory);
}
/// Initializes gpui's default colors for the application.
diff --git a/crates/gpui/src/element.rs b/crates/gpui/src/element.rs
index 986037094d4..b29b26a777e 100644
--- a/crates/gpui/src/element.rs
+++ b/crates/gpui/src/element.rs
@@ -305,13 +305,17 @@ impl<E: Element> Drawable<E> {
let inspector_id;
#[cfg(any(feature = "inspector", debug_assertions))]
{
- inspector_id = self.element.source_location().map(|source| {
- let path = crate::InspectorElementPath {
- global_id: GlobalElementId(Arc::from(&*window.element_id_stack)),
- source_location: source,
- };
- window.build_inspector_element_id(path)
- });
+ inspector_id = if window.inspector_enabled() {
+ self.element.source_location().map(|source| {
+ let path = crate::InspectorElementPath {
+ global_id: GlobalElementId(Arc::from(&*window.element_id_stack)),
+ source_location: source,
+ };
+ window.build_inspector_element_id(path)
+ })
+ } else {
+ None
+ };
}
#[cfg(not(any(feature = "inspector", debug_assertions)))]
{
diff --git a/crates/gpui/src/inspector.rs b/crates/gpui/src/inspector.rs
index 12995f03a8a..d353690e319 100644
--- a/crates/gpui/src/inspector.rs
+++ b/crates/gpui/src/inspector.rs
@@ -22,7 +22,7 @@ pub use conditional::*;
mod conditional {
use super::*;
use crate::{AnyElement, App, Context, Empty, IntoElement, Render, Window};
- use collections::{FxHashMap, TypeIdHashMap};
+ use collections::{FxHashMap, TypeIdHashMap, hash_map::Entry};
use std::any::{Any, TypeId};
/// `GlobalElementId` qualified by source location of element construction.
@@ -60,6 +60,7 @@ mod conditional {
pub struct Inspector {
active_element: Option<InspectedElement>,
pub(crate) pick_depth: Option<f32>,
+ renderers: TypeIdHashMap<InspectorElementRenderer>,
}
struct InspectedElement {
@@ -81,6 +82,7 @@ mod conditional {
Self {
active_element: None,
pick_depth: Some(0.0),
+ renderers: TypeIdHashMap::default(),
}
}
@@ -161,22 +163,29 @@ mod conditional {
let mut elements = Vec::new();
if let Some(active_element) = self.active_element.take() {
for (type_id, state) in &active_element.states {
- if let Some(render_inspector) = cx
- .inspector_element_registry
- .renderers_by_type_id
- .remove(type_id)
- {
- let mut element = (render_inspector)(
- active_element.id.clone(),
- state.as_ref(),
- window,
- cx,
- );
- elements.push(element);
- cx.inspector_element_registry
- .renderers_by_type_id
- .insert(*type_id, render_inspector);
- }
+ let renderer = match self.renderers.entry(*type_id) {
+ Entry::Occupied(entry) => entry.into_mut(),
+ Entry::Vacant(entry) => {
+ let Some(factory) = cx
+ .inspector_element_registry
+ .factories_by_type_id
+ .remove(type_id)
+ else {
+ continue;
+ };
+ let renderer = factory(window, cx);
+ cx.inspector_element_registry
+ .factories_by_type_id
+ .insert(*type_id, factory);
+ entry.insert(renderer)
+ }
+ };
+ elements.push(renderer(
+ active_element.id.clone(),
+ state.as_ref(),
+ window,
+ cx,
+ ));
}
self.active_element = Some(active_element);
@@ -200,26 +209,34 @@ mod conditional {
#[derive(Default)]
pub(crate) struct InspectorElementRegistry {
- renderers_by_type_id: FxHashMap<
- TypeId,
- Box<dyn Fn(InspectorElementId, &dyn Any, &mut Window, &mut App) -> AnyElement>,
- >,
+ factories_by_type_id:
+ FxHashMap<TypeId, Box<dyn Fn(&mut Window, &mut App) -> InspectorElementRenderer>>,
}
impl InspectorElementRegistry {
- pub fn register<T: 'static, R: IntoElement>(
+ pub fn register<T: 'static, R: IntoElement, F>(
&mut self,
- f: impl 'static + Fn(InspectorElementId, &T, &mut Window, &mut App) -> R,
- ) {
- self.renderers_by_type_id.insert(
+ factory: impl 'static + Fn(&mut Window, &mut App) -> F,
+ ) where
+ F: 'static + FnMut(InspectorElementId, &T, &mut Window, &mut App) -> R,
+ {
+ self.factories_by_type_id.insert(
TypeId::of::<T>(),
- Box::new(move |id, value, window, cx| {
- let value = value.downcast_ref().unwrap();
- f(id, value, window, cx).into_any_element()
+ Box::new(move |window, cx| {
+ let mut renderer = factory(window, cx);
+ Box::new(move |id, value, window, cx| {
+ let value = value
+ .downcast_ref()
+ .expect("registered inspector state type");
+ renderer(id, value, window, cx).into_any_element()
+ })
}),
);
}
}
+
+ type InspectorElementRenderer =
+ Box<dyn FnMut(InspectorElementId, &dyn Any, &mut Window, &mut App) -> AnyElement>;
}
/// Provides definitions used by `#[derive_inspector_reflection]`.
diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs
index 62d1d5d7ee0..a2dc8e128e0 100644
--- a/crates/gpui/src/window.rs
+++ b/crates/gpui/src/window.rs
@@ -6777,7 +6777,13 @@ impl Window {
pub fn toggle_inspector(&mut self, cx: &mut App) {
self.inspector = match self.inspector {
None => Some(cx.new(|_| Inspector::new())),
- Some(_) => None,
+ Some(_) => {
+ self.rendered_frame.next_inspector_instance_ids = FxHashMap::default();
+ self.rendered_frame.inspector_hitboxes = FxHashMap::default();
+ self.next_frame.next_inspector_instance_ids = FxHashMap::default();
+ self.next_frame.inspector_hitboxes = FxHashMap::default();
+ None
+ }
};
self.refresh();
}
@@ -6797,22 +6803,24 @@ impl Window {
#[cfg(any(feature = "inspector", debug_assertions))]
pub fn with_inspector_state<T: 'static, R>(
&mut self,
- _inspector_id: Option<&crate::InspectorElementId>,
+ inspector_id: Option<&crate::InspectorElementId>,
cx: &mut App,
f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
- ) -> R {
- if let Some(inspector_id) = _inspector_id
- && let Some(inspector) = &self.inspector
- {
- let inspector = inspector.clone();
- let active_element_id = inspector.read(cx).active_element_id();
- if Some(inspector_id) == active_element_id {
- return inspector.update(cx, |inspector, _cx| {
- inspector.with_active_element_state(self, f)
- });
- }
+ ) -> Option<R> {
+ let inspector_id = inspector_id?;
+ let inspector = self.inspector.as_ref()?;
+ if inspector.read(cx).active_element_id() != Some(inspector_id) {
+ return None;
}
- f(&mut None, self)
+ let inspector = inspector.clone();
+ Some(inspector.update(cx, |inspector, _cx| {
+ inspector.with_active_element_state(self, f)
+ }))
+ }
+
+ #[cfg(any(feature = "inspector", debug_assertions))]
+ pub(crate) fn inspector_enabled(&self) -> bool {
+ self.inspector.is_some()
}
#[cfg(any(feature = "inspector", debug_assertions))]
@@ -8653,3 +8661,165 @@ mod tests {
.unwrap();
}
}
+
+#[cfg(all(test, any(feature = "inspector", debug_assertions)))]
+mod inspector_tests {
+ use super::*;
+ use crate::{
+ DivInspectorState, InspectorElementId, MouseDownEvent, StyleRefinement, TestAppContext, div,
+ };
+
+ #[gpui::test]
+ fn inspector_only_tracks_its_open_window(cx: &mut TestAppContext) {
+ let windows = [
+ cx.add_window(|_, cx| InspectorTestRoot {
+ child: cx.new(|_| InspectorTestView::default()),
+ }),
+ cx.add_window(|_, cx| InspectorTestRoot {
+ child: cx.new(|_| InspectorTestView::default()),
+ }),
+ ];
+ for window in windows {
+ assert_closed_inspector(window.into(), cx);
+ }
+ for _ in 0..2 {
+ cx.update_window(windows[0].into(), |root, window, cx| {
+ let root = root.downcast::<InspectorTestRoot>().expect("test root");
+ let child_widths = root.read(cx).child.read(cx).child_widths.clone();
+ window.toggle_inspector(cx);
+ window.draw(cx).clear(cx);
+ assert_eq!(child_widths.borrow().as_slice(), &[px(10.); 3]);
+ let path = window
+ .rendered_frame
+ .next_inspector_instance_ids
+ .iter()
+ .find_map(|(path, count)| (*count == 3).then(|| path.clone()))
+ .expect("anonymous siblings share an inspector path");
+ let selected_id = InspectorElementId {
+ path,
+ instance_id: 1,
+ };
+ let position = window
+ .rendered_frame
+ .hitboxes
+ .iter()
+ .find(|hitbox| {
+ window.rendered_frame.inspector_hitboxes.get(&hitbox.id)
+ == Some(&selected_id)
+ })
+ .expect("middle sibling is pickable")
+ .bounds
+ .center();
+ window.simulate_mouse_move(position, cx);
+ window.dispatch_event(
+ PlatformInput::MouseDown(MouseDownEvent {
+ position,
+ button: MouseButton::Left,
+ modifiers: Modifiers::default(),
+ click_count: 1,
+ first_mouse: false,
+ }),
+ cx,
+ );
+ window.dispatch_event(
+ PlatformInput::MouseUp(MouseUpEvent {
+ position,
+ button: MouseButton::Left,
+ modifiers: Modifiers::default(),
+ click_count: 1,
+ }),
+ cx,
+ );
+ assert!(!window.is_inspector_picking(cx));
+ assert_eq!(
+ window
+ .inspector
+ .as_ref()
+ .expect("open inspector")
+ .read(cx)
+ .active_element_id(),
+ Some(&selected_id)
+ );
+ window.draw(cx).clear(cx);
+ window.with_inspector_state::<DivInspectorState, _>(
+ Some(&selected_id),
+ cx,
+ |state, _| {
+ let state = state.as_mut().expect("selected div has style state");
+ assert_eq!(
+ state.base_style.size.width,
+ Some(crate::Length::from(px(10.)))
+ );
+ state.base_style.size.width = Some(crate::Length::from(px(25.)));
+ },
+ );
+ window.refresh();
+ window.draw(cx).clear(cx);
+ assert_eq!(
+ child_widths.borrow().as_slice(),
+ &[px(10.), px(25.), px(10.)]
+ );
+ })
+ .expect("pick and edit a cached child");
+ assert_closed_inspector(windows[1].into(), cx);
+ windows[0]
+ .update(cx, |_, window, cx| window.toggle_inspector(cx))
+ .expect("close inspector");
+ assert_closed_inspector(windows[0].into(), cx);
+ }
+ }
+
+ struct InspectorTestRoot {
+ child: Entity<InspectorTestView>,
+ }
+
+ impl Render for InspectorTestRoot {
+ fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
+ self.child
+ .clone()
+ .cached(StyleRefinement::default().size(px(100.)))
+ }
+ }
+
+ #[derive(Default)]
+ struct InspectorTestView {
+ child_widths: Rc<RefCell<Vec<Pixels>>>,
+ }
+
+ impl Render for InspectorTestView {
+ fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
+ let child_widths = self.child_widths.clone();
+ div()
+ .on_children_prepainted(move |bounds, _, _| {
+ *child_widths.borrow_mut() =
+ bounds.iter().map(|bounds| bounds.size.width).collect();
+ })
+ .with_dynamic_prepaint_order(|_, _| SmallVec::from_iter([2, 0, 1]))
+ .id("inspector-root")
+ .flex()
+ .children((0..3).map(|_| div().size(px(10.)).flex_shrink_0()))
+ }
+ }
+
+ fn assert_closed_inspector(window: AnyWindowHandle, cx: &mut TestAppContext) {
+ cx.update_window(window, |root, window, cx| {
+ window.draw(cx).clear(cx);
+ window.draw(cx).clear(cx);
+ let root = root.downcast::<InspectorTestRoot>().expect("test root");
+ assert_eq!(
+ root.read(cx)
+ .child
+ .read(cx)
+ .child_widths
+ .borrow()
+ .as_slice(),
+ &[px(10.); 3]
+ );
+ for frame in [&window.rendered_frame, &window.next_frame] {
+ assert_eq!(frame.next_inspector_instance_ids.capacity(), 0);
+ assert_eq!(frame.inspector_hitboxes.capacity(), 0);
+ }
+ })
+ .expect("closed inspector has no bookkeeping and no style overrides");
+ }
+}
diff --git a/crates/gpui_platform/Cargo.toml b/crates/gpui_platform/Cargo.toml
index 57629a79935..ccb9905909b 100644
--- a/crates/gpui_platform/Cargo.toml
+++ b/crates/gpui_platform/Cargo.toml
@@ -15,15 +15,24 @@ path = "src/gpui_platform.rs"
default = []
bench-support = ["gpui/bench-support", "gpui_macos/bench-support"]
font-kit = ["gpui_macos/font-kit"]
+inspector = ["gpui/inspector"]
test-support = ["gpui/test-support", "gpui_macos/test-support", "gpui_windows/test-support"]
screen-capture = ["gpui/screen-capture", "gpui_macos/screen-capture", "gpui_windows/screen-capture", "gpui_linux/screen-capture"]
runtime_shaders = ["gpui_macos/runtime_shaders"]
wayland = ["gpui_linux/wayland"]
x11 = ["gpui_linux/x11"]
+[[bench]]
+name = "inspector_render"
+harness = false
+required-features = ["bench-support"]
+
[dependencies]
gpui.workspace = true
+[dev-dependencies]
+criterion.workspace = true
+
[target.'cfg(target_os = "macos")'.dependencies]
gpui_macos.workspace = true
diff --git a/crates/gpui_platform/benches/inspector_render.rs b/crates/gpui_platform/benches/inspector_render.rs
new file mode 100644
index 00000000000..811155ffb4a
--- /dev/null
+++ b/crates/gpui_platform/benches/inspector_render.rs
@@ -0,0 +1,345 @@
+use std::{cell::Cell, fmt, rc::Rc, time::Duration};
+
+use gpui::{
+ BenchAppContext, Bounds, Context, InteractiveElement as _, IntoElement, ParentElement as _,
+ Pixels, Render, SharedString, StatefulInteractiveElement as _, Styled as _, Window, div,
+ prelude::FluentBuilder as _, px, rgb, size,
+};
+
+const COLUMN_COUNT: usize = 100;
+const NODE_SIZE: f32 = 6.0;
+const ROW_HEIGHT: f32 = 24.0;
+const PANEL_WIDTH: f32 = 320.0;
+
+#[derive(Default)]
+struct RenderWork {
+ rendered_frames: Cell<usize>,
+ prepainted_children: Cell<usize>,
+ invalid_children: Cell<usize>,
+}
+
+impl RenderWork {
+ fn record_children(&self, bounds: &[Bounds<Pixels>], valid: impl Fn(&Bounds<Pixels>) -> bool) {
+ self.prepainted_children
+ .set(self.prepainted_children.get() + bounds.len());
+ self.invalid_children.set(
+ self.invalid_children.get() + bounds.iter().filter(|bounds| !valid(bounds)).count(),
+ );
+ }
+}
+
+struct ClosedInspectorInput {
+ scale: usize,
+ unit: &'static str,
+ open_close_cycles: usize,
+ other_window_inspected: bool,
+}
+
+impl fmt::Display for ClosedInspectorInput {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(
+ formatter,
+ "{}-{}-{}-cycles",
+ self.scale, self.unit, self.open_close_cycles
+ )?;
+ if self.other_window_inspected {
+ write!(formatter, "-other-window")?;
+ }
+ Ok(())
+ }
+}
+
+fn closed_inspector_inputs(
+ unit: &'static str,
+ scales: impl IntoIterator<Item = usize>,
+) -> Vec<ClosedInspectorInput> {
+ let lifecycles = if cfg!(feature = "inspector") {
+ vec![(0, false), (2, false), (0, true), (2, true)]
+ } else {
+ vec![(0, false)]
+ };
+ scales
+ .into_iter()
+ .flat_map(|scale| {
+ lifecycles
+ .iter()
+ .map(
+ move |&(open_close_cycles, other_window_inspected)| ClosedInspectorInput {
+ scale,
+ unit,
+ open_close_cycles,
+ other_window_inspected,
+ },
+ )
+ })
+ .collect()
+}
+
+#[gpui::bench(
+ inputs = closed_inspector_inputs("nodes", [100, 1_000, 10_000]),
+ input_name = "case",
+ group = "closed_inspector_grid",
+ fps = 120
+)]
+fn bare_grid(input: &ClosedInspectorInput, cx: &mut BenchAppContext) {
+ assert_eq!(input.scale % COLUMN_COUNT, 0);
+ measure_closed_inspector(
+ input,
+ cx,
+ |work| BareGrid {
+ node_count: input.scale,
+ alternate: false,
+ work,
+ },
+ |grid| grid.alternate = !grid.alternate,
+ );
+}
+
+#[gpui::bench(
+ inputs = closed_inspector_inputs("rows", [50, 500]),
+ input_name = "case",
+ group = "closed_inspector_panel",
+ fps = 120
+)]
+fn panel(input: &ClosedInspectorInput, cx: &mut BenchAppContext) {
+ measure_closed_inspector(
+ input,
+ cx,
+ |work| Panel::new(input.scale, work),
+ |panel| panel.selected_row = (panel.selected_row + 1) % panel.labels.len(),
+ );
+}
+
+fn measure_closed_inspector<V: Render + 'static>(
+ input: &ClosedInspectorInput,
+ cx: &mut BenchAppContext,
+ build_view: impl FnOnce(Rc<RenderWork>) -> V,
+ mut update_view: impl FnMut(&mut V),
+) {
+ assert!(!cfg!(debug_assertions), "use --profile release-fast");
+ let expected_children = input.scale;
+
+ let work = Rc::new(RenderWork::default());
+ let mut window = cx.add_empty_window();
+ let view = window.update(|window, cx| {
+ assert!(!window.is_inspector_picking(cx));
+ window.replace_root(cx, |_, _| build_view(work.clone()))
+ });
+ cx.run_until_idle();
+ for _ in 0..input.open_close_cycles {
+ for open in [true, false] {
+ window.update(|window, cx| {
+ #[cfg(feature = "inspector")]
+ window.toggle_inspector(cx);
+ assert_eq!(window.is_inspector_picking(cx), open);
+ window.refresh();
+ });
+ cx.run_until_idle();
+ }
+ }
+ let mut other_window = input.other_window_inspected.then(|| {
+ let mut window = cx.add_empty_window();
+ window.update(|window, cx| {
+ #[cfg(feature = "inspector")]
+ window.toggle_inspector(cx);
+ assert!(window.is_inspector_picking(cx));
+ });
+ window
+ });
+ cx.run_until_idle();
+ let other_frames_before = other_window.as_mut().map(|window| {
+ window.update(|window, _| {
+ window
+ .frame_duration_snapshot()
+ .draw_duration_histogram
+ .len()
+ })
+ });
+ assert!(work.rendered_frames.get() > 0);
+ assert_eq!(
+ work.prepainted_children.get(),
+ work.rendered_frames.get() * expected_children
+ );
+ assert_eq!(work.invalid_children.get(), 0);
+ work.rendered_frames.set(0);
+ work.prepainted_children.set(0);
+
+ let frames_before = window.update(|window, _| window.frame_duration_snapshot());
+ let mut updated_frames = 0;
+ cx.bench_renderer(view, |view, _, cx| {
+ update_view(view);
+ updated_frames += 1;
+ cx.notify();
+ });
+ let frames_after = window.update(|window, cx| {
+ assert!(!window.is_inspector_picking(cx));
+ window.frame_duration_snapshot()
+ });
+
+ let other_frames_after = other_window.as_mut().map(|window| {
+ window.update(|window, cx| {
+ assert!(window.is_inspector_picking(cx));
+ window
+ .frame_duration_snapshot()
+ .draw_duration_histogram
+ .len()
+ })
+ });
+ assert_eq!(other_frames_after, other_frames_before);
+ assert!(updated_frames > 0);
+ assert_eq!(work.rendered_frames.get(), updated_frames);
+ assert_eq!(
+ work.prepainted_children.get(),
+ updated_frames * expected_children
+ );
+ assert_eq!(work.invalid_children.get(), 0);
+ assert_eq!(
+ frames_after.draw_duration_histogram.len() - frames_before.draw_duration_histogram.len(),
+ updated_frames as u64
+ );
+ assert_eq!(
+ frames_after.dirty_to_present_histogram.len()
+ - frames_before.dirty_to_present_histogram.len(),
+ updated_frames as u64
+ );
+}
+
+struct BareGrid {
+ node_count: usize,
+ alternate: bool,
+ work: Rc<RenderWork>,
+}
+
+impl Render for BareGrid {
+ fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
+ self.work
+ .rendered_frames
+ .set(self.work.rendered_frames.get() + 1);
+ let background = rgb(if self.alternate { 0x334455 } else { 0x445566 });
+
+ div()
+ .id("bare-grid")
+ .flex()
+ .flex_col()
+ .size(px(COLUMN_COUNT as f32 * NODE_SIZE))
+ .children((0..self.node_count / COLUMN_COUNT).map(|row_index| {
+ let work = self.work.clone();
+ div()
+ .on_children_prepainted(move |bounds, _, _| {
+ work.record_children(&bounds, |bounds| {
+ bounds.size == size(px(NODE_SIZE), px(NODE_SIZE))
+ });
+ })
+ .id(("row", row_index))
+ .flex()
+ .h(px(NODE_SIZE))
+ .flex_shrink_0()
+ .children((0..COLUMN_COUNT).map(|column_index| {
+ div()
+ .id(("node", column_index))
+ .size(px(NODE_SIZE))
+ .flex_shrink_0()
+ .bg(background)
+ .border_1()
+ .border_color(rgb(0x8899aa))
+ .rounded(px(2.0))
+ .when(column_index % 2 == 0, |element| element.cursor_pointer())
+ }))
+ }))
+ }
+}
+
+struct Panel {
+ labels: Vec<SharedString>,
+ counts: Vec<SharedString>,
+ selected_row: usize,
+ work: Rc<RenderWork>,
+}
+
+impl Panel {
+ fn new(row_count: usize, work: Rc<RenderWork>) -> Self {
+ Panel {
+ labels: (0..row_count)
+ .map(|index| {
+ SharedString::from(format!("crates/module_{}/src/file_{index}.rs", index % 17))
+ })
+ .collect(),
+ counts: (0..row_count)
+ .map(|index| SharedString::from(((index * 7) % 100).to_string()))
+ .collect(),
+ selected_row: 0,
+ work,
+ }
+ }
+}
+
+impl Render for Panel {
+ fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
+ self.work
+ .rendered_frames
+ .set(self.work.rendered_frames.get() + 1);
+ let work = self.work.clone();
+ let selected_row = self.selected_row;
+
+ div()
+ .on_children_prepainted(move |bounds, _, _| {
+ work.record_children(&bounds, |bounds| bounds.size.height == px(ROW_HEIGHT));
+ })
+ .id("panel")
+ .flex()
+ .flex_col()
+ .w(px(PANEL_WIDTH))
+ .h(px(ROW_HEIGHT * self.labels.len() as f32))
+ .bg(rgb(0x1b1f24))
+ .children(self.labels.iter().zip(&self.counts).enumerate().map(
+ |(index, (label, count))| {
+ div()
+ .id(("row", index))
+ .flex()
+ .items_center()
+ .gap_2()
+ .px_2()
+ .h(px(ROW_HEIGHT))
+ .flex_shrink_0()
+ .rounded_sm()
+ .cursor_pointer()
+ .hover(|style| style.bg(rgb(0x2a3038)))
+ .active(|style| style.bg(rgb(0x343c46)))
+ .when(index == selected_row, |row| row.bg(rgb(0x1f4f82)))
+ .on_click(|_, _, _| {})
+ .child(
+ div()
+ .size_4()
+ .flex_shrink_0()
+ .rounded_sm()
+ .bg(rgb(if index % 3 == 0 { 0x6aa1ff } else { 0x8fbf6a })),
+ )
+ .child(
+ div()
+ .flex_1()
+ .overflow_hidden()
+ .text_sm()
+ .text_color(rgb(0xd0d4da))
+ .child(label.clone()),
+ )
+ .child(
+ div()
+ .text_xs()
+ .text_color(rgb(0x8a919c))
+ .child(count.clone()),
+ )
+ },
+ ))
+ }
+}
+
+gpui::bench_group! {
+ name = benches;
+ config = criterion::Criterion::default()
+ .sample_size(30)
+ .warm_up_time(Duration::from_secs(1))
+ .measurement_time(Duration::from_secs(5))
+ .without_plots();
+ targets = bare_grid, panel
+}
+gpui::bench_main!(benches);
diff --git a/crates/inspector_ui/Cargo.toml b/crates/inspector_ui/Cargo.toml
index ec1f01195c8..e3dd67de2e3 100644
--- a/crates/inspector_ui/Cargo.toml
+++ b/crates/inspector_ui/Cargo.toml
@@ -27,3 +27,15 @@ util.workspace = true
util_macros.workspace = true
workspace.workspace = true
zed_actions.workspace = true
+
+[dev-dependencies]
+fs = { workspace = true, features = ["test-support"] }
+futures.workspace = true
+gpui = { workspace = true, features = ["test-support"] }
+language = { workspace = true, features = ["test-support"] }
+paths.workspace = true
+project = { workspace = true, features = ["test-support"] }
+settings = { workspace = true, features = ["test-support"] }
+snippet_provider.workspace = true
+theme.workspace = true
+workspace = { workspace = true, features = ["test-support"] }
diff --git a/crates/inspector_ui/src/div_inspector.rs b/crates/inspector_ui/src/div_inspector.rs
index 78c76ee3e52..803386224c6 100644
--- a/crates/inspector_ui/src/div_inspector.rs
+++ b/crates/inspector_ui/src/div_inspector.rs
@@ -5,7 +5,8 @@ use editor::{
use fuzzy::StringMatch;
use gpui::{
AsyncWindowContext, DivInspectorState, Entity, InspectorElementId, IntoElement,
- StyleRefinement, Task, Window, inspector_reflection::FunctionReflection, styled_reflection,
+ StyleRefinement, Subscription, Task, WeakEntity, Window,
+ inspector_reflection::FunctionReflection, styled_reflection,
};
use language::language_settings::SoftWrap;
use language::{
@@ -47,6 +48,7 @@ pub(crate) struct DivInspector {
rust_completion: Option<String>,
/// Range that will be replaced by the completion if selected.
rust_completion_replace_range: Option<Range<Anchor>>,
+ _initialization_task: Task<()>,
}
enum State {
@@ -60,6 +62,7 @@ enum State {
rust_style_editor: Entity<Editor>,
json_style_buffer: Entity<Buffer>,
json_style_editor: Entity<Editor>,
+ _subscriptions: [Subscription; 2],
},
LoadError {
message: SharedString,
@@ -73,7 +76,7 @@ impl DivInspector {
cx: &mut Context<Self>,
) -> DivInspector {
// Open the buffers once, so they can then be used for each editor.
- cx.spawn_in(window, {
+ let initialization_task = cx.spawn_in(window, {
let languages = project.read(cx).languages().clone();
let project = project.clone();
async move |this, cx| {
@@ -104,10 +107,11 @@ impl DivInspector {
// `update_inspected_element`. This avoids continuing to show
// "Loading..." until the user moves the mouse to a different element.
if let Some(id) = this.inspector_id.take() {
- let inspector_state =
- window.with_inspector_state(Some(&id), cx, |state, _window| {
+ let inspector_state = window
+ .with_inspector_state(Some(&id), cx, |state, _window| {
state.clone()
- });
+ })
+ .flatten();
if let Some(inspector_state) = inspector_state {
this.update_inspected_element(&id, inspector_state, window, cx);
cx.notify();
@@ -129,8 +133,7 @@ impl DivInspector {
}
}
}
- })
- .detach();
+ });
DivInspector {
state: State::Loading,
@@ -143,6 +146,7 @@ impl DivInspector {
rust_completion: None,
rust_completion_replace_range: None,
json_style_error: None,
+ _initialization_task: initialization_task,
}
}
@@ -180,7 +184,7 @@ impl DivInspector {
let rust_style_editor = self.create_editor(rust_style_buffer.clone(), window, cx);
rust_style_editor.update(cx, {
- let div_inspector = cx.entity();
+ let div_inspector = cx.weak_entity();
|rust_style_editor, _cx| {
rust_style_editor.set_completion_provider(Some(Rc::new(
RustStyleCompletionProvider { div_inspector },
@@ -200,7 +204,7 @@ impl DivInspector {
}
};
- cx.subscribe_in(&json_style_editor, window, {
+ let json_subscription = cx.subscribe_in(&json_style_editor, window, {
let id = id.clone();
let rust_style_buffer = rust_style_buffer.clone();
move |this, editor, event: &EditorEvent, window, cx| {
@@ -247,10 +251,9 @@ impl DivInspector {
}
}
}
- })
- .detach();
+ });
- cx.subscribe(&rust_style_editor, {
+ let rust_subscription = cx.subscribe(&rust_style_editor, {
let json_style_buffer = json_style_buffer.clone();
let rust_style_buffer = rust_style_buffer.clone();
move |this, _editor, event: &EditorEvent, cx| {
@@ -258,8 +261,7 @@ impl DivInspector {
this.update_json_style_from_rust(&json_style_buffer, &rust_style_buffer, cx);
}
}
- })
- .detach();
+ });
self.unconvertible_style = style.subtract(&rust_style);
self.json_style_overrides = StyleRefinement::default();
@@ -268,6 +270,7 @@ impl DivInspector {
rust_style_editor,
json_style_buffer,
json_style_editor,
+ _subscriptions: [json_subscription, rust_subscription],
};
}
@@ -638,7 +641,7 @@ fn is_not_identifier_char(c: char) -> bool {
}
struct RustStyleCompletionProvider {
- div_inspector: Entity<DivInspector>,
+ div_inspector: WeakEntity<DivInspector>,
}
impl CompletionProvider for RustStyleCompletionProvider {
@@ -655,9 +658,15 @@ impl CompletionProvider for RustStyleCompletionProvider {
return Task::ready(Ok(Vec::new()));
};
- self.div_inspector.update(cx, |div_inspector, _cx| {
- div_inspector.rust_completion_replace_range = Some(replace_range.clone());
- });
+ if self
+ .div_inspector
+ .update(cx, |div_inspector, _cx| {
+ div_inspector.rust_completion_replace_range = Some(replace_range.clone());
+ })
+ .is_err()
+ {
+ return Task::ready(Ok(Vec::new()));
+ }
Task::ready(Ok(vec![CompletionResponse {
completions: STYLE_METHODS
@@ -699,9 +708,11 @@ impl CompletionProvider for RustStyleCompletionProvider {
let div_inspector = self.div_inspector.clone();
let rust_completion = mat.as_ref().map(|mat| mat.string.clone());
cx.defer(move |cx| {
- div_inspector.update(cx, |div_inspector, cx| {
- div_inspector.handle_rust_completion_selection_change(rust_completion, cx);
- });
+ div_inspector
+ .update(cx, |div_inspector, cx| {
+ div_inspector.handle_rust_completion_selection_change(rust_completion, cx);
+ })
+ .ok();
});
}
@@ -734,3 +745,298 @@ fn completion_replace_range(snapshot: &BufferSnapshot, anchor: &Anchor) -> Optio
None
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use fs::FakeFs;
+ use futures::{FutureExt as _, channel::oneshot};
+ use gpui::{
+ AnyWeakEntity, Focusable as _, Modifiers, TestAppContext, VisualTestContext, point,
+ };
+ use language::{LanguageConfig, LanguageName, LanguageQueries, LoadedLanguage};
+ use settings::SettingsStore;
+ use snippet_provider::SnippetProvider;
+ use std::{
+ cell::RefCell,
+ collections::BTreeSet,
+ path::PathBuf,
+ sync::{
+ Arc,
+ atomic::{AtomicBool, Ordering},
+ },
+ };
+
+ #[gpui::test]
+ async fn test_drop_during_initialization(cx: &mut TestAppContext) {
+ let (fs, watcher_baseline) = test_fs(cx);
+ let project = Project::test(fs.clone(), [], cx).await;
+ let weak_project = project.downgrade();
+ let weak_lsp_store = project.read_with(cx, |project, _| project.lsp_store().downgrade());
+ let (finish_loading, loading_gate) = oneshot::channel::<()>();
+ let loading_gate = loading_gate.shared();
+ let loading_started = Arc::new(AtomicBool::new(false));
+ project.read_with(cx, |project, _| {
+ project.languages().register_language(
+ LanguageName::from("Rust"),
+ None,
+ Arc::default(),
+ false,
+ None,
+ Arc::new({
+ let loading_started = loading_started.clone();
+ move || {
+ let loading_gate = loading_gate.clone();
+ let loading_started = loading_started.clone();
+ Box::pin(async move {
+ loading_started.store(true, Ordering::SeqCst);
+ loading_gate.await?;
+ Ok(LoadedLanguage {
+ config: LanguageConfig {
+ name: LanguageName::from("Rust"),
+ ..LanguageConfig::default()
+ },
+ queries: LanguageQueries::default(),
+ context_provider: None,
+ toolchain_provider: None,
+ manifest_name: None,
+ })
+ })
+ }
+ }),
+ );
+ });
+
+ let cx = cx.add_empty_window();
+ let div_inspector =
+ cx.new_window_entity(|window, cx| DivInspector::new(project, window, cx));
+ let weak_inspector = div_inspector.downgrade();
+ cx.run_until_parked();
+
+ assert!(loading_started.load(Ordering::SeqCst));
+ assert_inspector_watchers(&fs, &watcher_baseline);
+ let weak_json_buffer = div_inspector.read_with(cx, |div_inspector, cx| {
+ assert!(matches!(div_inspector.state, State::Loading));
+ div_inspector
+ .project
+ .read(cx)
+ .buffer_store()
+ .read(cx)
+ .buffers()
+ .next()
+ .expect("initialization must load the JSON buffer before Rust")
+ .downgrade()
+ });
+
+ cx.update(|_, _| drop(div_inspector));
+ flush_teardown(cx);
+
+ assert!(weak_inspector.upgrade().is_none());
+ assert!(weak_project.upgrade().is_none());
+ assert!(weak_lsp_store.upgrade().is_none());
+ assert!(weak_json_buffer.upgrade().is_none());
+ assert_eq!(watched_paths(&fs), watcher_baseline);
+
+ finish_loading
+ .send(())
+ .expect("language loader must still be waiting");
+ cx.run_until_parked();
+ assert!(weak_inspector.upgrade().is_none());
+ assert!(weak_project.upgrade().is_none());
+ assert!(weak_lsp_store.upgrade().is_none());
+ assert_eq!(watched_paths(&fs), watcher_baseline);
+ }
+
+ #[gpui::test]
+ async fn test_close_focused_inspector_and_reopen_same_element(cx: &mut TestAppContext) {
+ let (fs, watcher_baseline) = test_fs(cx);
+ let pending_project = Rc::new(RefCell::new(None::<Entity<Project>>));
+ let inspectors = Rc::new(RefCell::new(Vec::new()));
+ cx.update({
+ let pending_project = pending_project.clone();
+ let inspectors = inspectors.clone();
+ move |cx| {
+ cx.set_inspector_renderer(Box::new(|inspector, window, cx| {
+ v_flex()
+ .size_full()
+ .children(inspector.render_inspector_states(window, cx))
+ .into_any_element()
+ }));
+ cx.register_inspector_element(move |window, cx| {
+ let project = pending_project.borrow_mut().take().expect("fresh project");
+ let inspector = cx.new(|cx| DivInspector::new(project, window, cx));
+ inspectors.borrow_mut().push(inspector.downgrade());
+ move |id, state: &DivInspectorState, window: &mut Window, cx: &mut App| {
+ inspector.update(cx, |inspector, cx| {
+ inspector.update_inspected_element(&id, state.clone(), window, cx);
+ inspector.render(window, cx).into_any_element()
+ })
+ }
+ });
+ }
+ });
+ let first_window = cx.add_window(|_, _| InspectorTarget);
+ let second_window = cx.add_window(|_, _| InspectorTarget);
+ let mut second = VisualTestContext::from_window(second_window.into(), cx);
+ let mut selected_id = None;
+ let mut resources = Vec::new();
+ let mut surviving_resources = Vec::new();
+ let mut surviving_editor = None;
+ let mut active_baseline = watcher_baseline.clone();
+ let windows = [second_window, first_window, first_window];
+ for (generation, window) in windows.into_iter().enumerate() {
+ let cx = &mut VisualTestContext::from_window(window.into(), cx);
+ let project = Project::test(fs.clone(), [], cx).await;
+ project.read_with(cx, |project, _| {
+ project.languages().register_test_language(LanguageConfig {
+ name: LanguageName::from("Rust"),
+ ..LanguageConfig::default()
+ });
+ });
+ *pending_project.borrow_mut() = Some(project);
+ cx.update(|window, cx| {
+ window.toggle_inspector(cx);
+ window.draw(cx).clear(cx);
+ });
+ let position = point(px(5.), px(5.));
+ cx.simulate_mouse_move(position, None, Modifiers::default());
+ cx.simulate_click(position, Modifiers::default());
+ cx.update(|window, cx| window.draw(cx).clear(cx));
+ cx.run_until_parked();
+ assert_eq!(inspectors.borrow().len(), generation + 1);
+ let weak_inspector = inspectors
+ .borrow()
+ .last()
+ .expect("rendered inspector")
+ .clone();
+ let (weak_entities, rust_editor, focus_handle) = weak_inspector
+ .read_with(cx, |inspector, cx| {
+ let id = inspector.inspector_id.clone().expect("picked element");
+ if generation > 0
+ && let Some(previous_id) = selected_id.replace(id.clone())
+ {
+ assert_eq!(id, previous_id);
+ }
+ let State::Ready {
+ rust_style_buffer,
+ rust_style_editor,
+ json_style_buffer,
+ json_style_editor,
+ ..
+ } = &inspector.state
+ else {
+ panic!("picked element must have initialized editors");
+ };
+ let editor = if generation == 2 {
+ json_style_editor
+ } else {
+ rust_style_editor
+ };
+ (
+ [
+ AnyWeakEntity::from(weak_inspector.clone()),
+ AnyWeakEntity::from(inspector.project.downgrade()),
+ AnyWeakEntity::from(inspector.project.read(cx).lsp_store().downgrade()),
+ AnyWeakEntity::from(rust_style_editor.downgrade()),
+ AnyWeakEntity::from(json_style_editor.downgrade()),
+ AnyWeakEntity::from(rust_style_buffer.downgrade()),
+ AnyWeakEntity::from(json_style_buffer.downgrade()),
+ ],
+ rust_style_editor.downgrade(),
+ editor.focus_handle(cx),
+ )
+ })
+ .expect("live inspector");
+ cx.update(|window, cx| {
+ window.focus(&focus_handle, cx);
+ window.draw(cx).clear(cx);
+ assert!(focus_handle.is_focused(window));
+ });
+ assert_inspector_watchers(&fs, &active_baseline);
+ resources.extend(weak_entities);
+ if generation == 0 {
+ surviving_editor = Some(rust_editor);
+ surviving_resources = resources.clone();
+ active_baseline = watched_paths(&fs);
+ continue;
+ }
+ cx.update(|window, cx| {
+ if generation == 1 {
+ window.toggle_inspector(cx);
+ window.draw(cx).clear(cx);
+ } else {
+ window.remove_window();
+ }
+ });
+ flush_teardown(&mut second);
+ second.update(|window, cx| window.draw(cx).clear(cx));
+ let editor = surviving_editor.as_ref().expect("second window editor");
+ let text = |cx: &TestAppContext| {
+ editor
+ .read_with(cx, |editor, cx| editor.text(cx))
+ .expect("live editor")
+ };
+ let before = text(&second);
+ second.simulate_input(" ");
+ assert_eq!(text(&second).len(), before.len() + 1);
+ resources.retain(AnyWeakEntity::is_upgradable);
+ assert_eq!(resources, surviving_resources);
+ assert_eq!(watched_paths(&fs), active_baseline);
+ }
+ second.update(|window, cx| {
+ window.toggle_inspector(cx);
+ window.draw(cx).clear(cx);
+ });
+ flush_teardown(&mut second);
+ assert!(resources.iter().all(|entity| !entity.is_upgradable()));
+ assert_eq!(watched_paths(&fs), watcher_baseline);
+ }
+
+ fn test_fs(cx: &mut TestAppContext) -> (Arc<FakeFs>, Vec<PathBuf>) {
+ cx.update(|cx| {
+ let settings = SettingsStore::test(cx);
+ cx.set_global(settings);
+ theme_settings::init(theme::LoadThemes::JustBase, cx);
+ editor::init(cx);
+ });
+ let fs = FakeFs::new(cx.executor());
+ cx.update(|cx| {
+ drop(SnippetProvider::new(fs.clone(), BTreeSet::new(), cx));
+ });
+ cx.run_until_parked();
+ let watcher_baseline = watched_paths(&fs);
+ assert!(!watcher_baseline.is_empty());
+ (fs, watcher_baseline)
+ }
+
+ fn watched_paths(fs: &FakeFs) -> Vec<PathBuf> {
+ let mut paths = fs.watched_paths();
+ paths.sort();
+ paths
+ }
+
+ fn assert_inspector_watchers(fs: &FakeFs, baseline: &[PathBuf]) {
+ let mut expected = baseline.to_vec();
+ expected.extend([
+ paths::tasks_file().clone(),
+ paths::debug_scenarios_file().clone(),
+ PathBuf::from(ZED_INSPECTOR_STYLE_JSON),
+ ]);
+ expected.sort();
+ assert_eq!(watched_paths(fs), expected);
+ }
+
+ fn flush_teardown(cx: &mut VisualTestContext) {
+ cx.run_until_parked();
+ cx.update(|_, _| {});
+ cx.run_until_parked();
+ }
+
+ struct InspectorTarget;
+
+ impl Render for InspectorTarget {
+ fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
+ div().id("inspected-element").size(px(100.))
+ }
+ }
+}
diff --git a/crates/inspector_ui/src/inspector.rs b/crates/inspector_ui/src/inspector.rs
index 84f3d2195d3..d2b6179ee7b 100644
--- a/crates/inspector_ui/src/inspector.rs
+++ b/crates/inspector_ui/src/inspector.rs
@@ -1,6 +1,6 @@
use anyhow::{Context as _, anyhow};
use gpui::{App, DivInspectorState, Inspector, InspectorElementId, IntoElement, TaskExt, Window};
-use std::{cell::OnceCell, path::Path, sync::Arc};
+use std::{path::Path, sync::Arc};
use ui::{Label, Tooltip, prelude::*, utils::platform_title_bar_height};
use util::{ResultExt as _, command::new_command};
use workspace::AppState;
@@ -24,29 +24,28 @@ pub fn init(app_state: Arc<AppState>, cx: &mut App) {
});
});
- // Project used for editor buffers with LSP support
- let project = project::Project::local(
- app_state.client.clone(),
- app_state.node_runtime.clone(),
- app_state.user_store.clone(),
- app_state.languages.clone(),
- app_state.fs.clone(),
- None,
- project::LocalProjectFlags {
- init_worktree_trust: false,
- ..Default::default()
- },
- cx,
- );
-
- let div_inspector = OnceCell::new();
- cx.register_inspector_element(move |id, state: &DivInspectorState, window, cx| {
- let div_inspector = div_inspector
- .get_or_init(|| cx.new(|cx| DivInspector::new(project.clone(), window, cx)));
- div_inspector.update(cx, |div_inspector, cx| {
- div_inspector.update_inspected_element(&id, state.clone(), window, cx);
- div_inspector.render(window, cx).into_any_element()
- })
+ cx.register_inspector_element(move |window, cx| {
+ // Project used for editor buffers with LSP support
+ let project = project::Project::local(
+ app_state.client.clone(),
+ app_state.node_runtime.clone(),
+ app_state.user_store.clone(),
+ app_state.languages.clone(),
+ app_state.fs.clone(),
+ None,
+ project::LocalProjectFlags {
+ init_worktree_trust: false,
+ watch_global_configs: false,
+ },
+ cx,
+ );
+ let div_inspector = cx.new(|cx| DivInspector::new(project, window, cx));
+ move |id, state: &DivInspectorState, window: &mut Window, cx: &mut App| {
+ div_inspector.update(cx, |div_inspector, cx| {
+ div_inspector.update_inspected_element(&id, state.clone(), window, cx);
+ div_inspector.render(window, cx).into_any_element()
+ })
+ }
});
cx.set_inspector_renderer(Box::new(render_inspector));
diff --git a/crates/lsp/src/lsp.rs b/crates/lsp/src/lsp.rs
index 65674864875..2b602d2cd05 100644
--- a/crates/lsp/src/lsp.rs
+++ b/crates/lsp/src/lsp.rs
@@ -1222,7 +1222,7 @@ impl LanguageServer {
Some(async move {
log::debug!("language server shutdown started");
- select! {
+ let shutdown_timed_out = select! {
request_result = shutdown_request.fuse() => {
match request_result {
ConnectionResult::Timeout => {
@@ -1236,19 +1236,32 @@ impl LanguageServer {
},
ConnectionResult::Result(Ok(())) => {}
}
+ false
}
_ = timer => {
log::info!("timeout waiting for language server {name} (id {server_id}) to shutdown");
+ true
},
- }
+ };
response_handlers.lock().take();
Self::notify_internal::<notification::Exit>(&notification_serializers, ()).ok();
notification_serializers.close();
- output_done.recv().await;
- server.lock().take().map(|mut child| child.kill());
+ if !shutdown_timed_out {
+ select! {
+ _ = output_done.recv().fuse() => {},
+ _ = timer => {
+ log::info!("timeout draining output for language server {name} (id {server_id}) during shutdown");
+ },
+ }
+ }
drop(tasks);
+ if let Some(mut child) = server.lock().take()
+ && let Err(error) = child.kill()
+ {
+ log::warn!("failed to kill language server {name} (id {server_id}): {error}");
+ }
log::debug!("language server shutdown finished");
Some(())
})
@@ -2154,7 +2167,7 @@ impl FakeLanguageServer {
mod tests {
use super::*;
use gpui::TestAppContext;
- use std::str::FromStr;
+ use std::{io, str::FromStr, task::Context};
#[ctor::ctor(unsafe)]
fn init_logger() {
@@ -2247,6 +2260,50 @@ mod tests {
fake.receive_notification::<notification::Exit>().await;
}
+ #[gpui::test]
+ async fn test_shutdown_bounds_output_drain(cx: &mut TestAppContext) {
+ for remaining_flushes in [Some(0), Some(1), None] {
+ let (server, mut stdout, output) = shutdown_test_server(remaining_flushes, cx);
+ let io_handlers = Arc::downgrade(&server.io_handlers);
+ let mut shutdown = cx
+ .executor()
+ .spawn(server.shutdown().expect("shutdown must start"));
+ drop(server);
+ cx.run_until_parked();
+ let mut expected = if remaining_flushes == Some(0) {
+ Vec::new()
+ } else {
+ framed_test_message(r#"{"jsonrpc":"2.0","id":0,"method":"shutdown"}"#)
+ };
+ assert_eq!(output.lock().bytes, expected);
+ assert_eq!((&mut shutdown).now_or_never(), None);
+ cx.executor().advance_clock(Duration::from_secs(4));
+ if remaining_flushes != Some(0) {
+ stdout
+ .write_all(&framed_test_message(
+ r#"{"jsonrpc":"2.0","id":0,"result":null}"#,
+ ))
+ .await
+ .expect("shutdown response must reach stdout");
+ }
+ cx.run_until_parked();
+ if remaining_flushes.is_none() {
+ expected.extend(framed_test_message(r#"{"jsonrpc":"2.0","method":"exit"}"#));
+ } else {
+ assert!(output.lock().blocked);
+ cx.executor().advance_clock(Duration::from_millis(999));
+ cx.run_until_parked();
+ assert_eq!((&mut shutdown).now_or_never(), None);
+ assert!(io_handlers.upgrade().is_some());
+ cx.executor().advance_clock(Duration::from_millis(1));
+ cx.run_until_parked();
+ }
+ assert_eq!(shutdown.now_or_never(), Some(Some(())));
+ assert_eq!(output.lock().bytes, expected);
+ assert!(io_handlers.upgrade().is_none());
+ }
+ }
+
#[gpui::test]
async fn test_subscription_leaks_handlers_after_server_drop(cx: &mut TestAppContext) {
cx.update(|cx| {
@@ -2530,4 +2587,79 @@ mod tests {
}];
assert_eq!(workspace_folders, expected_workspace_folders);
}
+
+ struct ShutdownTestOutput {
+ bytes: Vec<u8>,
+ remaining_flushes: Option<usize>,
+ blocked: bool,
+ }
+
+ struct ShutdownTestWriter(Arc<Mutex<ShutdownTestOutput>>);
+
+ impl AsyncWrite for ShutdownTestWriter {
+ fn poll_write(
+ self: Pin<&mut Self>,
+ _cx: &mut Context<'_>,
+ bytes: &[u8],
+ ) -> Poll<io::Result<usize>> {
+ let mut output = self.0.lock();
+ if output.remaining_flushes == Some(0) {
+ output.blocked = true;
+ return Poll::Pending;
+ }
+ output.bytes.extend_from_slice(bytes);
+ Poll::Ready(Ok(bytes.len()))
+ }
+
+ fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
+ if let Some(remaining_flushes) = &mut self.0.lock().remaining_flushes {
+ *remaining_flushes = remaining_flushes.saturating_sub(1);
+ }
+ Poll::Ready(Ok(()))
+ }
+
+ fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
+ Poll::Ready(Ok(()))
+ }
+ }
+
+ fn shutdown_test_server(
+ remaining_flushes: Option<usize>,
+ cx: &mut TestAppContext,
+ ) -> (
+ LanguageServer,
+ async_pipe::PipeWriter,
+ Arc<Mutex<ShutdownTestOutput>>,
+ ) {
+ let (stdout_writer, stdout_reader) = async_pipe::pipe();
+ let output = Arc::new(Mutex::new(ShutdownTestOutput {
+ bytes: Vec::new(),
+ remaining_flushes,
+ blocked: false,
+ }));
+ let server = LanguageServer::new_internal(
+ LanguageServerId(0),
+ LanguageServerName::from("shutdown-test"),
+ ShutdownTestWriter(output.clone()),
+ stdout_reader,
+ None::<async_pipe::PipeReader>,
+ Arc::new(Mutex::new(None)),
+ None,
+ None,
+ LanguageServerBinary {
+ path: PathBuf::from("shutdown-test"),
+ arguments: Vec::new(),
+ env: None,
+ },
+ FakeLanguageServer::root_path(),
+ None,
+ &mut cx.to_async(),
+ |_| false,
+ );
+ (server, stdout_writer, output)
+ }
+
+ fn framed_test_message(payload: &str) -> Vec<u8> {
+ format!("Content-Length: {}\r\n\r\n{payload}", payload.len()).into_bytes()
+ }
}