diff --git a/Cargo.lock b/Cargo.lock index 3593559003f..e35f4cf7de5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7572,6 +7572,7 @@ dependencies = [ "raw-window-handle", "scheduler", "semver", + "serde_json", "smallvec", "strum 0.28.0", "uuid", diff --git a/crates/cli/src/cli.rs b/crates/cli/src/cli.rs index d7ad0b347ed..5ffe0af3265 100644 --- a/crates/cli/src/cli.rs +++ b/crates/cli/src/cli.rs @@ -72,6 +72,8 @@ pub enum CliRequest { SetOpenBehavior { behavior: CliBehaviorSetting, }, + /// Print a diagnostic snapshot of the app's GPUI and platform state. + DebugState, } #[derive(Debug, Serialize, Deserialize)] diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index a14495666dd..6d1bacdf645 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -128,6 +128,10 @@ struct Args { /// Will attempt to give the correct command to run #[arg(long)] system_specs: bool, + /// Print a JSON snapshot of the running Zed's GPUI and platform state + /// (windows, displays, frame scheduling, cursor), for debugging. + #[arg(long)] + debug_state: bool, /// Open the project in a dev container. /// /// Automatically triggers "Reopen in Dev Container" if a `.devcontainer/` @@ -684,7 +688,11 @@ fn run() -> Result<()> { cwd: env::current_dir().ok(), }; - tx.send(open_request)?; + tx.send(if args.debug_state { + CliRequest::DebugState + } else { + open_request + })?; while let Ok(response) = rx.recv() { match response { diff --git a/crates/gpui/src/app.rs b/crates/gpui/src/app.rs index cee926ba211..f102819ae5c 100644 --- a/crates/gpui/src/app.rs +++ b/crates/gpui/src/app.rs @@ -1732,6 +1732,66 @@ impl App { .cloned() } + /// Returns a diagnostic snapshot of app, display, and window state. + /// + /// This is for inspecting a running app that is misbehaving in a way that + /// is hard to reproduce. The layout is not stable and varies by platform; + /// do not parse it for program logic. A window that is being updated when + /// this is called is listed by ID only. + pub fn debug_state(&self) -> serde_json::Value { + let displays = self + .platform + .displays() + .into_iter() + .map(|display| { + serde_json::json!({ + "id": u64::from(display.id()), + "uuid": display.uuid().ok().map(|uuid| uuid.to_string()), + "bounds": display.bounds(), + "visible_bounds": display.visible_bounds(), + "refresh_interval_seconds": display + .refresh_interval() + .map(|interval| interval.as_secs_f64()), + }) + }) + .collect::>(); + let windows = self + .windows + .iter() + .map(|(window_id, window)| match window { + Some(window) => window.debug_state(), + None => serde_json::json!({ "id": window_id.as_u64(), "updating": true }), + }) + .collect::>(); + serde_json::json!({ + "compositor": self.platform.compositor_name(), + "thermal_state": format!("{:?}", self.platform.thermal_state()), + "power_mode": { + "cached": format!("{:?}", self.power_mode), + "platform": format!("{:?}", self.platform.power_mode()), + }, + "window_appearance": format!("{:?}", self.platform.window_appearance()), + "cursor_visible": self.platform.is_cursor_visible(), + "active_window_id": self + .platform + .active_window() + .map(|handle| handle.window_id().as_u64()), + "window_stack": self.platform.window_stack().map(|stack| { + stack + .into_iter() + .map(|handle| handle.window_id().as_u64()) + .collect::>() + }), + "primary_display_id": self + .platform + .primary_display() + .map(|display| u64::from(display.id())), + "displays": displays, + "windows": windows, + "platform": self.platform.debug_state(), + }) + } + /// Returns the current thermal state of the system. pub fn thermal_state(&self) -> ThermalState { self.platform.thermal_state() diff --git a/crates/gpui/src/platform.rs b/crates/gpui/src/platform.rs index 916f2d4dc7e..1f344f2f46a 100644 --- a/crates/gpui/src/platform.rs +++ b/crates/gpui/src/platform.rs @@ -538,6 +538,11 @@ pub trait Platform: 'static { fn on_will_open_app_menu(&self, callback: Box); fn on_validate_app_menu_command(&self, callback: Box bool>); + /// Platform-specific diagnostic state, for [`App::debug_state`]. + fn debug_state(&self) -> serde_json::Value { + serde_json::Value::Null + } + fn thermal_state(&self) -> ThermalState; fn on_thermal_state_change(&self, callback: Box); fn prevent_idle_sleep(&self, reason: &str) -> Task>; @@ -1332,6 +1337,10 @@ pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle { fn zoom(&self); fn toggle_fullscreen(&self); fn is_fullscreen(&self) -> bool; + /// Platform-specific diagnostic state, for [`App::debug_state`]. + fn debug_state(&self) -> serde_json::Value { + serde_json::Value::Null + } fn frame_waker(&self) -> Option> { None } @@ -3041,7 +3050,9 @@ impl From<&str> for PromptButton { } /// The style of the cursor (pointer) -#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)] +#[derive( + Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema, EnumIter, +)] pub enum CursorStyle { /// The default cursor #[default] diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs index 7b87bf6b63a..ba3f41af87a 100644 --- a/crates/gpui/src/window.rs +++ b/crates/gpui/src/window.rs @@ -2524,6 +2524,65 @@ impl Window { } } + /// This window's part of [`App::debug_state`]. + /// + /// Values GPUI caches are reported next to what the platform reports now, + /// so a stale cache shows up as a mismatch. + pub(crate) fn debug_state(&self) -> serde_json::Value { + let platform_window = &self.platform_window; + serde_json::json!({ + "id": self.handle.window_id().as_u64(), + "title": platform_window.get_title(), + "bounds": platform_window.bounds(), + "window_bounds": format!("{:?}", platform_window.window_bounds()), + "content_size": platform_window.content_size(), + "viewport_size": self.viewport_size, + "scale_factor": { + "cached": self.scale_factor, + "platform": platform_window.scale_factor(), + }, + "display_id": { + "cached": self.display_id.map(u64::from), + "platform": platform_window.display().map(|display| u64::from(display.id())), + }, + "active": { + "cached": self.active.get(), + "platform": platform_window.is_active(), + }, + "hovered": { + "cached": self.hovered.get(), + "platform": platform_window.is_hovered(), + }, + "visibility": { + "cached": format!("{:?}", self.visibility), + "platform": format!("{:?}", platform_window.visibility()), + }, + "appearance": { + "cached": format!("{:?}", self.appearance), + "platform": format!("{:?}", platform_window.appearance()), + }, + "is_fullscreen": platform_window.is_fullscreen(), + "is_maximized": platform_window.is_maximized(), + "mouse_position": { + "cached": self.mouse_position, + "platform": platform_window.mouse_position(), + }, + "modifiers": { + "cached": self.modifiers, + "platform": platform_window.modifiers(), + }, + "cursor_style": self.rendered_frame.cursor_style(self), + "frame": { + "dirty": self.invalidator.is_dirty(), + "needs_present": self.needs_present.get(), + "refreshing": self.refreshing, + "next_frame_callbacks": self.next_frame_callbacks.borrow().len(), + }, + "gpu": platform_window.gpu_specs(), + "platform": platform_window.debug_state(), + }) + } + /// Whether the platform is presenting this window's frames (see /// [`WindowVisibility`]). pub fn visibility(&self) -> WindowVisibility { @@ -8484,6 +8543,34 @@ mod tests { } } + /// A stale cache is only visible if the snapshot reports GPUI's cached + /// value separately from what the platform reports now. + #[gpui::test] + fn test_debug_state_reports_cached_and_platform_values(cx: &mut TestAppContext) { + use crate::WindowVisibility; + + let window = cx.add_window(|_, _| EmptyView); + let window_id = window.window_id().as_u64(); + let window_state = |cx: &mut TestAppContext| { + let state = cx.update(|cx| cx.debug_state()); + state["windows"] + .as_array() + .and_then(|windows| windows.iter().find(|window| window["id"] == window_id)) + .cloned() + .expect("the open window is listed") + }; + + let state = window_state(cx); + assert_eq!(state["visibility"]["cached"], "Visible"); + assert_eq!(state["visibility"]["platform"], "Visible"); + + cx.test_window(window.into()) + .simulate_visibility_change(WindowVisibility::Hidden); + let state = window_state(cx); + assert_eq!(state["visibility"]["cached"], "Hidden"); + assert_eq!(state["visibility"]["platform"], "Hidden"); + } + /// Visibility transitions reach observers exactly once each, with the new /// state already stored on the window, and never wake the platform for a /// frame: the platform requests one itself when it resumes presenting. diff --git a/crates/gpui_apple/src/display_link.rs b/crates/gpui_apple/src/display_link.rs index 83d420594ec..8d1ede1168c 100644 --- a/crates/gpui_apple/src/display_link.rs +++ b/crates/gpui_apple/src/display_link.rs @@ -91,6 +91,10 @@ impl MetalFrameSource { pub fn set_paused(&self, paused: bool) { self.link.setPaused(paused); } + + pub fn is_paused(&self) -> bool { + self.link.isPaused() + } } impl Drop for MetalFrameSource { diff --git a/crates/gpui_apple/src/metal_renderer.rs b/crates/gpui_apple/src/metal_renderer.rs index 9b98a23a41f..076494a3d45 100644 --- a/crates/gpui_apple/src/metal_renderer.rs +++ b/crates/gpui_apple/src/metal_renderer.rs @@ -498,6 +498,14 @@ impl MetalRenderer { }; } + pub fn is_display_link_attached(&self) -> bool { + matches!(self.display_link_mode, DisplayLinkMode::Attached { .. }) + } + + pub fn presents_with_transaction(&self) -> bool { + self.presents_with_transaction + } + pub fn set_presents_with_transaction(&mut self, presents_with_transaction: bool) { self.presents_with_transaction = presents_with_transaction; if let Some(layer) = &self.layer { diff --git a/crates/gpui_macos/Cargo.toml b/crates/gpui_macos/Cargo.toml index b4f9ddee9ce..c6362c40247 100644 --- a/crates/gpui_macos/Cargo.toml +++ b/crates/gpui_macos/Cargo.toml @@ -55,6 +55,7 @@ parking_lot.workspace = true raw-window-handle.workspace = true scheduler.workspace = true semver.workspace = true +serde_json.workspace = true smallvec.workspace = true strum.workspace = true uuid.workspace = true diff --git a/crates/gpui_macos/src/display_link.rs b/crates/gpui_macos/src/display_link.rs index 90a25979a1e..d6847185e68 100644 --- a/crates/gpui_macos/src/display_link.rs +++ b/crates/gpui_macos/src/display_link.rs @@ -331,6 +331,20 @@ impl MetalFrames { self.woken.set(false); } + pub fn debug_state(&self) -> serde_json::Value { + let paused = self + .source + .try_borrow() + .ok() + .and_then(|source| source.as_ref().map(MetalFrameSource::is_paused)); + serde_json::json!({ + "kind": "CAMetalDisplayLink", + "attached": self.is_attached(), + "paused": paused, + "woken": self.woken.get(), + }) + } + /// Ends an update, pausing the link if GPUI neither used its drawable nor /// asked for another frame while it ran. Returns whether it paused. pub fn end_frame(&self, used_drawable: bool) -> bool { @@ -382,6 +396,14 @@ impl WindowFrameSource { Ok(()) } + pub fn debug_state(&self) -> serde_json::Value { + serde_json::json!({ + "kind": "CVDisplayLink", + "attached": self.registration.is_some(), + "display_id": self.registration.map(|(display_id, _)| display_id), + }) + } + pub fn take_signal(&self) -> Option<(Instant, FrameRequestSource)> { self.signal.take() } diff --git a/crates/gpui_macos/src/platform.rs b/crates/gpui_macos/src/platform.rs index 7d02fcbcba6..d42ac63f2a9 100644 --- a/crates/gpui_macos/src/platform.rs +++ b/crates/gpui_macos/src/platform.rs @@ -32,9 +32,10 @@ use objc2::{ use objc2_app_kit::{ NSAppearance, NSAppearanceNameAqua, NSAppearanceNameDarkAqua, NSAppearanceNameVibrantDark, NSAppearanceNameVibrantLight, NSApplication, NSApplicationActivationPolicy, - NSControlStateValueOn, NSCursor, NSDocumentController, NSEventModifierFlags, NSMenu, - NSMenuItem, NSModalResponse, NSModalResponseOK, NSOpenPanel, NSSavePanel, NSScroller, - NSScrollerStyle, NSWorkspace, NSWorkspaceDidWakeNotification, NSWorkspaceWillSleepNotification, + NSApplicationOcclusionState, NSControlStateValueOn, NSCursor, NSDocumentController, + NSEventModifierFlags, NSMenu, NSMenuItem, NSModalResponse, NSModalResponseOK, NSOpenPanel, + NSSavePanel, NSScroller, NSScrollerStyle, NSWorkspace, NSWorkspaceDidWakeNotification, + NSWorkspaceWillSleepNotification, }; use objc2_foundation::{ NSActivityOptions, NSArray, NSBundle, NSError, NSInteger, NSProcessInfo, NSString, NSURL, @@ -55,6 +56,7 @@ use std::{ atomic::{AtomicBool, Ordering}, }, }; +use strum::IntoEnumIterator as _; const MAC_PLATFORM_IVAR: &CStr = c"platform"; static mut APP_CLASS: *const AnyClass = ptr::null(); @@ -1081,6 +1083,34 @@ impl Platform for MacPlatform { self.ensure_system_power_observers(); } + fn debug_state(&self) -> serde_json::Value { + let app = NSApplication::sharedApplication(self.1); + let key_window: *mut AnyObject = unsafe { msg_send![&*app, keyWindow] }; + let main_window: *mut AnyObject = unsafe { msg_send![&*app, mainWindow] }; + let window_number = |window: *mut AnyObject| -> Option { + (!window.is_null()).then(|| unsafe { msg_send![window, windowNumber] }) + }; + // AppKit's cursor for this app, mapped back to the style GPUI would + // have set it from. `None` when it is not one GPUI sets. + let current_cursor = Retained::as_ptr(&NSCursor::currentCursor()).cast::(); + let current_cursor_style = CursorStyle::iter().find(|style| { + // SAFETY: The platform is only used on the main thread. + let cursor = unsafe { crate::window::native_cursor(*style) }; + ptr::eq(cursor, current_cursor) + }); + serde_json::json!({ + "current_cursor_style": current_cursor_style, + "app_is_active": app.isActive(), + "app_is_hidden": app.isHidden(), + "app_occlusion_state_visible": app + .occlusionState() + .contains(NSApplicationOcclusionState::Visible), + "key_window_number": window_number(key_window), + "main_window_number": window_number(main_window), + "low_power_mode": NSProcessInfo::processInfo().isLowPowerModeEnabled(), + }) + } + fn thermal_state(&self) -> ThermalState { process_info::thermal_state() } diff --git a/crates/gpui_macos/src/window.rs b/crates/gpui_macos/src/window.rs index bdf3f130243..b3492c084c1 100644 --- a/crates/gpui_macos/src/window.rs +++ b/crates/gpui_macos/src/window.rs @@ -2229,6 +2229,56 @@ impl PlatformWindow for MacWindow { None } + fn debug_state(&self) -> serde_json::Value { + let state = self.0.lock(); + let window = state.native_window(); + let screen: *mut AnyObject = unsafe { msg_send![state.native_window, screen] }; + let frame = window.frame(); + let layer = state.renderer.layer().map(|layer| { + let drawable_size = layer.drawableSize(); + serde_json::json!({ + "drawable_size": [drawable_size.width, drawable_size.height], + "contents_scale": layer.contentsScale(), + }) + }); + serde_json::json!({ + "window_number": window.windowNumber(), + "occlusion_state_visible": window + .occlusionState() + .contains(NSWindowOcclusionState::Visible), + "is_visible": window.isVisible(), + "is_key_window": window.isKeyWindow(), + "is_main_window": window.isMainWindow(), + "is_miniaturized": window.isMiniaturized(), + "is_on_active_space": window.isOnActiveSpace(), + "screen_display_id": display_id_for_screen(screen), + "frame": [frame.origin.x, frame.origin.y, frame.size.width, frame.size.height], + "backing_scale_factor": window.backingScaleFactor(), + "frame_source": match &state.frame_source { + FrameSource::Metal(metal_frames) => metal_frames.debug_state(), + FrameSource::DisplayLink(Some(frame_source)) => frame_source.debug_state(), + FrameSource::DisplayLink(None) => serde_json::json!({ + "kind": "CVDisplayLink", + "attached": false, + }), + }, + "renderer": { + "display_link_attached": state.renderer.is_display_link_attached(), + "presents_with_transaction": state.renderer.presents_with_transaction(), + "layer": layer, + }, + "request_frame_callback_installed": state.request_frame_callback.is_some(), + "last_reported_visibility": state + .last_visibility + .map(|visibility| format!("{visibility:?}")), + "activated_at_least_once": state.activated_least_once, + "cursor": { + "cached_style": state.cursor_style, + "cached_visible": state.cursor_visible.load(Ordering::Relaxed), + }, + }) + } + fn update_ime_position(&self, _bounds: Bounds) { let executor = self.0.lock().foreground_executor.clone(); executor @@ -2621,17 +2671,13 @@ fn add_mouse_tracking_area(native_view: &NSView) { native_view.addTrackingArea(&tracking_area); } -extern "C" fn reset_cursor_rects(this: &AnyObject, _: Sel) { - // SAFETY: AppKit invokes cursor-rect updates on the main thread for GPUIView instances, - // whose WINDOW_STATE_IVAR is initialized when the view is created. The cursor registered - // below is a valid NSCursor. +/// # Safety +/// +/// Must be called on the AppKit main thread. +pub(crate) unsafe fn native_cursor(style: CursorStyle) -> *mut AnyObject { + // SAFETY: Each selector is an `NSCursor` class method returning a cursor. unsafe { - let _: () = msg_send![super(this, class!(NSView)), resetCursorRects]; - - let window_state = get_window_state(this); - let cursor_style = window_state.lock().cursor_style; - - let cursor: *mut AnyObject = match cursor_style { + match style { CursorStyle::Arrow => msg_send![class!(NSCursor), arrowCursor], CursorStyle::IBeam => msg_send![class!(NSCursor), IBeamCursor], CursorStyle::Crosshair => msg_send![class!(NSCursor), crosshairCursor], @@ -2665,7 +2711,21 @@ extern "C" fn reset_cursor_rects(this: &AnyObject, _: Sel) { CursorStyle::DragLink => msg_send![class!(NSCursor), dragLinkCursor], CursorStyle::DragCopy => msg_send![class!(NSCursor), dragCopyCursor], CursorStyle::ContextualMenu => msg_send![class!(NSCursor), contextualMenuCursor], - }; + } + } +} + +extern "C" fn reset_cursor_rects(this: &AnyObject, _: Sel) { + // SAFETY: AppKit invokes cursor-rect updates on the main thread for GPUIView instances, + // whose WINDOW_STATE_IVAR is initialized when the view is created. The cursor registered + // below is a valid NSCursor. + unsafe { + let _: () = msg_send![super(this, class!(NSView)), resetCursorRects]; + + let window_state = get_window_state(this); + let cursor_style = window_state.lock().cursor_style; + + let cursor = native_cursor(cursor_style); let bounds: NSRect = msg_send![this, bounds]; let _: () = msg_send![this, addCursorRect: bounds, cursor: cursor]; diff --git a/crates/zed/src/zed/open_listener.rs b/crates/zed/src/zed/open_listener.rs index 8a31382c4bd..c4b08f4b804 100644 --- a/crates/zed/src/zed/open_listener.rs +++ b/crates/zed/src/zed/open_listener.rs @@ -695,6 +695,23 @@ pub async fn handle_cli_connection( // resolve_open_behavior debug_panic!("unexpected SetOpenBehavior message"); } + CliRequest::DebugState => { + // Deliberately does not activate the app: activation redraws + // windows and would disturb the state being inspected. + let state = cx.update(|cx| cx.debug_state()); + let response = match serde_json::to_string_pretty(&state) { + Ok(message) => CliResponse::Stdout { message }, + Err(error) => CliResponse::Stderr { + message: format!("failed to serialize debug state: {error}"), + }, + }; + let status = match response { + CliResponse::Stdout { .. } => 0, + _ => 1, + }; + responses.send(response).log_err(); + responses.send(CliResponse::Exit { status }).log_err(); + } } } }