Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
gpui_macos: Migrate `get_sources` to `objc2` (#64031)
tidely86b2cf96623a
diff --git a/Cargo.lock b/Cargo.lockindex b11b119e4fd..6ecfcb83758 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -6974,8 +6974,8 @@ dependencies = ["libc","log","rustversion",- "windows-link 0.1.3",- "windows-result 0.3.4",+ "windows-link 0.2.1",+ "windows-result 0.4.1",][[package]]@@ -7660,6 +7660,7 @@ dependencies = ["objc2 0.6.3","objc2-app-kit 0.3.2","objc2-foundation 0.3.2",+ "objc2-screen-capture-kit","objc2-user-notifications","parking_lot","pathfinder_geometry",@@ -8481,7 +8482,7 @@ dependencies = ["js-sys","log","wasm-bindgen",- "windows-core 0.57.0",+ "windows-core 0.62.2",][[package]]@@ -11879,6 +11880,19 @@ dependencies = ["objc2 0.6.3",]+[[package]]+name = "objc2-core-graphics"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807"+dependencies = [+ "bitflags 2.13.1",+ "dispatch2",+ "objc2 0.6.3",+ "objc2-core-foundation",+ "objc2-io-surface",+]+[[package]]name = "objc2-core-image"version = "0.2.2"@@ -11952,6 +11966,17 @@ dependencies = ["objc2-core-foundation",]+[[package]]+name = "objc2-io-surface"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d"+dependencies = [+ "bitflags 2.13.1",+ "objc2 0.6.3",+ "objc2-core-foundation",+]+[[package]]name = "objc2-metal"version = "0.2.2"@@ -12015,6 +12040,18 @@ dependencies = ["objc2-metal 0.3.2",]+[[package]]+name = "objc2-screen-capture-kit"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "74b7c5390f477482f001bc354d6571a70db7e4f8d5288e860c45521fbce11394"+dependencies = [+ "block2 0.6.2",+ "objc2 0.6.3",+ "objc2-core-graphics",+ "objc2-foundation 0.3.2",+]+[[package]]name = "objc2-user-notifications"version = "0.3.2"@@ -19080,7 +19117,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2fb391ac70462b3097a755618fbf9c8f95ecc1eb379a414f7b46f202ed10db1f"dependencies = ["cc",- "windows-targets 0.48.5",+ "windows-targets 0.52.6",][[package]]diff --git a/Cargo.toml b/Cargo.tomlindex 23a6ad28d97..cb9bd7f4706 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -704,6 +704,7 @@ objc2-app-kit = { version = "0.3.2", default-features = false, features = ["NSPanel","NSResponder","NSSavePanel",+ "NSScreen","NSView","NSWindow","NSWorkspace",@@ -736,6 +737,12 @@ objc2-foundation = { version = "=0.3.2", default-features = false, features = ["objc2-core-foundation","std",] }+objc2-screen-capture-kit = { version = "=0.3.2", default-features = false, features = [+ "block2",+ "objc2-core-graphics",+ "SCShareableContent",+ "std"+] }objc2-user-notifications = "0.3"open = "5.0.0"ordered-float = "5"diff --git a/crates/gpui_macos/Cargo.toml b/crates/gpui_macos/Cargo.tomlindex 22bc2ab6854..a628f3579b5 100644--- a/crates/gpui_macos/Cargo.toml+++ b/crates/gpui_macos/Cargo.toml@@ -54,6 +54,7 @@ objc.workspace = trueobjc2.workspace = trueobjc2-app-kit.workspace = trueobjc2-foundation.workspace = true+objc2-screen-capture-kit.workspace = trueobjc2-user-notifications.workspace = trueparking_lot.workspace = truepathfinder_geometry.workspace = truediff --git a/crates/gpui_macos/src/platform.rs b/crates/gpui_macos/src/platform.rsindex ee2f4b3af73..c3ae3b3b18c 100644--- a/crates/gpui_macos/src/platform.rs+++ b/crates/gpui_macos/src/platform.rs@@ -638,7 +638,7 @@ impl Platform for MacPlatform {fn screen_capture_sources(&self,) -> oneshot::Receiver<Result<Vec<Rc<dyn gpui::ScreenCaptureSource>>>> {- crate::screen_capture::get_sources()+ crate::screen_capture::get_sources(self.1)}fn active_window(&self) -> Option<AnyWindowHandle> {diff --git a/crates/gpui_macos/src/screen_capture.rs b/crates/gpui_macos/src/screen_capture.rsindex 5ece21a34c8..076731efb96 100644--- a/crates/gpui_macos/src/screen_capture.rs+++ b/crates/gpui_macos/src/screen_capture.rs@@ -1,8 +1,8 @@-use crate::ns_string;use anyhow::{Result, anyhow};use block::ConcreteBlock;+use block2::RcBlock;use cocoa::{- base::{YES, id, nil},+ base::{id, nil},foundation::NSArray,};use collections::HashMap;@@ -26,13 +26,15 @@ use objc::{runtime::{Class, Object, Sel},sel, sel_impl,};+use objc2::{MainThreadMarker, rc::Retained};+use objc2_app_kit::NSScreen;+use objc2_foundation::{NSError, NSNumber, NSString};+use objc2_screen_capture_kit::{SCDisplay, SCShareableContent};use std::{cell::RefCell, ffi::c_void, mem, ptr, rc::Rc};-use crate::NSStringExt;-#[derive(Clone)]pub struct MacScreenCaptureSource {- sc_display: id,+ sc_display: Retained<SCDisplay>,meta: Option<ScreenMeta>,}@@ -52,7 +54,12 @@ const SCStreamOutputTypeScreen: NSInteger = 0;impl ScreenCaptureSource for MacScreenCaptureSource {fn metadata(&self) -> Result<SourceMetadata> {let (display_id, size) = unsafe {- let display_id: CGDirectDisplayID = msg_send![self.sc_display, displayID];+ // SAFETY: `SCDisplay` is an Objective-C object, so objc2's object pointer has the+ // same ABI as objc 0.2's `id`. This only casts a borrowed pointer; it does not+ // transfer ownership or change the retain count. `self.sc_display` remains alive+ // for the entire message send, and `displayID` does not retain the receiver.+ let sc_display: id = Retained::as_ptr(&self.sc_display).cast_mut().cast();+ let display_id: CGDirectDisplayID = msg_send![sc_display, displayID];let display_mode_ref = CGDisplayCopyDisplayMode(display_id);let width = CGDisplayModeGetPixelWidth(display_mode_ref);let height = CGDisplayModeGetPixelHeight(display_mode_ref);@@ -83,6 +90,14 @@ impl ScreenCaptureSource for MacScreenCaptureSource {frame_callback: Box<dyn Fn(ScreenCaptureFrame) + Send>,) -> oneshot::Receiver<Result<Box<dyn ScreenCaptureStream>>> {unsafe {+ // SAFETY: `SCDisplay` is an Objective-C object, so objc2's object pointer has the+ // same ABI as objc 0.2's `id`. The cast removes pointer constness only because the+ // legacy `id` alias is mutable; it does not mutate the display, transfer ownership,+ // or change the retain count. The generated objc2 binding takes `display` as+ // `&SCDisplay`, confirming that this initializer borrows rather than consumes it.+ // `self.sc_display` remains alive through the call, and `SCContentFilter` must retain+ // the display or copy any state that it needs after initialization.+ let sc_display: id = Retained::as_ptr(&self.sc_display).cast_mut().cast();let stream: id = msg_send![class!(SCStream), alloc];let filter: id = msg_send![class!(SCContentFilter), alloc];let configuration: id = msg_send![class!(SCStreamConfiguration), alloc];@@ -90,7 +105,8 @@ impl ScreenCaptureSource for MacScreenCaptureSource {let output: id = msg_send![OUTPUT_CLASS, alloc];let excluded_windows = NSArray::array(nil);- let filter: id = msg_send![filter, initWithDisplay:self.sc_display excludingWindows:excluded_windows];+ let filter: id =+ msg_send![filter, initWithDisplay:sc_display excludingWindows:excluded_windows];let configuration: id = msg_send![configuration, init];let _: id = msg_send![configuration, setScalesToFit: true];let _: id = msg_send![configuration, setPixelFormat: 0x42475241];@@ -156,14 +172,6 @@ impl ScreenCaptureSource for MacScreenCaptureSource {}}-impl Drop for MacScreenCaptureSource {- fn drop(&mut self) {- unsafe {- let _: () = msg_send![self.sc_display, release];- }- }-}-impl ScreenCaptureStream for MacScreenCaptureStream {fn metadata(&self) -> Result<SourceMetadata> {Ok(self.meta.clone())@@ -201,87 +209,83 @@ struct ScreenMeta {is_main: bool,}-unsafe fn screen_id_to_human_label() -> HashMap<CGDirectDisplayID, ScreenMeta> {- let screens: id = msg_send![class!(NSScreen), screens];- let count: usize = msg_send![screens, count];+fn screen_id_to_human_label(marker: MainThreadMarker) -> HashMap<CGDirectDisplayID, ScreenMeta> {+ let screens = NSScreen::screens(marker);let mut map = HashMap::default();- let screen_number_key = unsafe { ns_string("NSScreenNumber") };- for i in 0..count {- let screen: id = msg_send![screens, objectAtIndex: i];- let device_desc: id = msg_send![screen, deviceDescription];- if device_desc == nil {- continue;- }- let nsnumber: id = msg_send![device_desc, objectForKey: screen_number_key];- if nsnumber == nil {- continue;- }-- let screen_id: u32 = msg_send![nsnumber, unsignedIntValue];+ let screen_number_key = NSString::from_str("NSScreenNumber");- let name: id = msg_send![screen, localizedName];- if name != nil {- let cstr: *const std::os::raw::c_char = msg_send![name, UTF8String];- let rust_str = unsafe {- std::ffi::CStr::from_ptr(cstr)- .to_string_lossy()- .into_owned()- };- map.insert(- screen_id,- ScreenMeta {- label: rust_str.into(),- is_main: i == 0,- },- );- }+ for (i, screen) in screens.iter().enumerate() {+ let description = screen.deviceDescription();+ let Some(obj) = description.objectForKey(&screen_number_key) else {+ continue;+ };+ let Some(screen_id) = obj.downcast_ref::<NSNumber>() else {+ continue;+ };+ let name = screen.localizedName().to_string();++ map.insert(+ screen_id.as_u32(),+ ScreenMeta {+ label: name.into(),+ is_main: i == 0,+ },+ );}+map}-pub(crate) fn get_sources() -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {- unsafe {- let (tx, rx) = oneshot::channel();- let tx = Rc::new(RefCell::new(Some(tx)));- let screen_id_to_label = screen_id_to_human_label();- let block = ConcreteBlock::new(move |shareable_content: id, error: id| {+pub(crate) fn get_sources(+ marker: MainThreadMarker,+) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {+ let (tx, rx) = oneshot::channel();+ let tx = Rc::new(RefCell::new(Some(tx)));+ let screen_id_to_label = screen_id_to_human_label(marker);++ let handler = RcBlock::new(+ move |content: *mut SCShareableContent, error: *mut NSError| {let Some(tx) = tx.borrow_mut().take() else {return;};- let result = if error == nil {- let displays: id = msg_send![shareable_content, displays];- let mut result = Vec::new();- for i in 0..displays.count() {- let display = displays.objectAtIndex(i);- let id: CGDirectDisplayID = msg_send![display, displayID];- let meta = screen_id_to_label.get(&id).cloned();- let source = MacScreenCaptureSource {- sc_display: msg_send![display, retain],- meta,- };- result.push(Rc::new(source) as Rc<dyn ScreenCaptureSource>);- }- Ok(result)- } else {- let msg: id = msg_send![error, localizedDescription];+ let result = if let Some(error) = unsafe { error.as_ref() } {Err(anyhow!(- "Screen share failed: {:?}",- NSStringExt::to_str(&msg)+ "Screen share failed: {}",+ error.localizedDescription()))+ } else if let Some(content) = unsafe { content.as_ref() } {+ // SAFETY: Marked unsafe conservatively by objc2+ let result = unsafe { content.displays() }+ .into_iter()+ .map(|display| {+ // SAFETY: Marked unsafe conservatively by objc2+ let id = unsafe { display.displayID() };+ let metadata = screen_id_to_label.get(&id).cloned();+ let source = MacScreenCaptureSource {+ sc_display: display,+ meta: metadata,+ };+ Rc::new(source) as Rc<dyn ScreenCaptureSource>+ })+ .collect::<Vec<_>>();++ Ok(result)+ } else {+ // The two pointers are mutually exclusive, this should never happen+ Err(anyhow!("Screen share failed"))};- tx.send(result).ok();- });- let block = block.copy();-- let _: () = msg_send![- class!(SCShareableContent),- getShareableContentExcludingDesktopWindows:YES- onScreenWindowsOnly:YES- completionHandler:block];- rx++ _ = tx.send(result);+ },+ );++ unsafe {+ SCShareableContent::getShareableContentExcludingDesktopWindows_onScreenWindowsOnly_completionHandler(true, true, &handler);}++ rx}#[ctor(unsafe)]