inspector.rs

  1use anyhow::{Context as _, anyhow};
  2use gpui::{App, DivInspectorState, Inspector, InspectorElementId, IntoElement, Window};
  3use std::{cell::OnceCell, path::Path, sync::Arc};
  4use title_bar::platform_title_bar::PlatformTitleBar;
  5use ui::{Label, Tooltip, prelude::*};
  6use util::{ResultExt as _, command::new_smol_command};
  7use workspace::AppState;
  8
  9use crate::div_inspector::DivInspector;
 10
 11pub fn init(app_state: Arc<AppState>, cx: &mut App) {
 12    cx.on_action(|_: &zed_actions::dev::ToggleInspector, cx| {
 13        let Some(active_window) = cx
 14            .active_window()
 15            .context("no active window to toggle inspector")
 16            .log_err()
 17        else {
 18            return;
 19        };
 20        // This is deferred to avoid double lease due to window already being updated.
 21        cx.defer(move |cx| {
 22            active_window
 23                .update(cx, |_, window, cx| window.toggle_inspector(cx))
 24                .log_err();
 25        });
 26    });
 27
 28    // Project used for editor buffers with LSP support
 29    let project = project::Project::local(
 30        app_state.client.clone(),
 31        app_state.node_runtime.clone(),
 32        app_state.user_store.clone(),
 33        app_state.languages.clone(),
 34        app_state.fs.clone(),
 35        None,
 36        cx,
 37    );
 38
 39    let div_inspector = OnceCell::new();
 40    cx.register_inspector_element(move |id, state: &DivInspectorState, window, cx| {
 41        let div_inspector = div_inspector
 42            .get_or_init(|| cx.new(|cx| DivInspector::new(project.clone(), window, cx)));
 43        div_inspector.update(cx, |div_inspector, cx| {
 44            div_inspector.update_inspected_element(&id, state.clone(), window, cx);
 45            div_inspector.render(window, cx).into_any_element()
 46        })
 47    });
 48
 49    cx.set_inspector_renderer(Box::new(render_inspector));
 50}
 51
 52fn render_inspector(
 53    inspector: &mut Inspector,
 54    window: &mut Window,
 55    cx: &mut Context<Inspector>,
 56) -> AnyElement {
 57    let ui_font = theme::setup_ui_font(window, cx);
 58    let colors = cx.theme().colors();
 59    let inspector_id = inspector.active_element_id();
 60    let toolbar_height = PlatformTitleBar::height(window);
 61
 62    v_flex()
 63        .size_full()
 64        .bg(colors.panel_background)
 65        .text_color(colors.text)
 66        .font(ui_font)
 67        .border_l_1()
 68        .border_color(colors.border)
 69        .child(
 70            h_flex()
 71                .justify_between()
 72                .pr_2()
 73                .pl_1()
 74                .mt_px()
 75                .h(toolbar_height)
 76                .border_b_1()
 77                .border_color(colors.border_variant)
 78                .child(
 79                    IconButton::new("pick-mode", IconName::MagnifyingGlass)
 80                        .tooltip(Tooltip::text("Start inspector pick mode"))
 81                        .selected_icon_color(Color::Selected)
 82                        .toggle_state(inspector.is_picking())
 83                        .on_click(cx.listener(|inspector, _, window, _cx| {
 84                            inspector.start_picking();
 85                            window.refresh();
 86                        })),
 87                )
 88                .child(h_flex().justify_end().child(Label::new("GPUI Inspector"))),
 89        )
 90        .child(
 91            v_flex()
 92                .id("gpui-inspector-content")
 93                .overflow_y_scroll()
 94                .px_2()
 95                .py_0p5()
 96                .gap_2()
 97                .when_some(inspector_id, |this, inspector_id| {
 98                    this.child(render_inspector_id(inspector_id, cx))
 99                })
100                .children(inspector.render_inspector_states(window, cx)),
101        )
102        .into_any_element()
103}
104
105fn render_inspector_id(inspector_id: &InspectorElementId, cx: &App) -> Div {
106    let source_location = inspector_id.path.source_location;
107    // For unknown reasons, for some elements the path is absolute.
108    let source_location_string = source_location.to_string();
109    let source_location_string = source_location_string
110        .strip_prefix(env!("ZED_REPO_DIR"))
111        .and_then(|s| s.strip_prefix("/"))
112        .map(|s| s.to_string())
113        .unwrap_or(source_location_string);
114
115    v_flex()
116        .child(
117            h_flex()
118                .justify_between()
119                .child(Label::new("Element ID").size(LabelSize::Large))
120                .child(
121                    div()
122                        .id("instance-id")
123                        .text_ui(cx)
124                        .tooltip(Tooltip::text(
125                            "Disambiguates elements from the same source location",
126                        ))
127                        .child(format!("Instance {}", inspector_id.instance_id)),
128                ),
129        )
130        .child(
131            div()
132                .id("source-location")
133                .text_ui(cx)
134                .bg(cx.theme().colors().editor_foreground.opacity(0.025))
135                .underline()
136                .font_buffer(cx)
137                .text_xs()
138                .child(source_location_string)
139                .tooltip(Tooltip::text("Click to open by running Zed CLI"))
140                .on_click(move |_, _window, cx| {
141                    cx.background_spawn(open_zed_source_location(source_location))
142                        .detach_and_log_err(cx);
143                }),
144        )
145        .child(
146            div()
147                .id("global-id")
148                .text_ui(cx)
149                .min_h_20()
150                .tooltip(Tooltip::text(
151                    "GlobalElementId of the nearest ancestor with an ID",
152                ))
153                .child(inspector_id.path.global_id.to_string()),
154        )
155}
156
157async fn open_zed_source_location(
158    location: &'static std::panic::Location<'static>,
159) -> anyhow::Result<()> {
160    let mut path = Path::new(env!("ZED_REPO_DIR")).to_path_buf();
161    path.push(Path::new(location.file()));
162    let path_arg = format!(
163        "{}:{}:{}",
164        path.display(),
165        location.line(),
166        location.column()
167    );
168
169    let output = new_smol_command("zed")
170        .arg(&path_arg)
171        .output()
172        .await
173        .with_context(|| format!("running zed to open {path_arg} failed"))?;
174
175    if !output.status.success() {
176        Err(anyhow!(
177            "running zed to open {path_arg} failed with stderr: {}",
178            String::from_utf8_lossy(&output.stderr)
179        ))
180    } else {
181        Ok(())
182    }
183}