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_apple: Share CoreText, Keychain, and thermal services (#65058)

Anthony Eid95d35c6efddf
diff --git a/Cargo.lock b/Cargo.lock
index bf7b2d1f2c5..9f390074738 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2819,15 +2819,6 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
-[[package]]
-name = "cgl"
-version = "0.3.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0ced0551234e87afee12411d535648dd89d2e7f34c78b753395567aff3d447ff"
-dependencies = [
- "libc",
-]
-
[[package]]
name = "chacha20"
version = "0.10.1"
@@ -3844,19 +3835,6 @@ dependencies = [
"libc",
]
-[[package]]
-name = "core-graphics2"
-version = "0.5.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4416167a69126e617f8d0a214af0e3c1dbdeffcb100ddf72dcd1a1ac9893c146"
-dependencies = [
- "bitflags 2.13.1",
- "block",
- "cfg-if",
- "core-foundation 0.10.0",
- "libc",
-]
-
[[package]]
name = "core-services"
version = "1.0.0"
@@ -3878,20 +3856,6 @@ dependencies = [
"libc",
]
-[[package]]
-name = "core-video"
-version = "0.5.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "139679cc63eb9504bdbe37e37874b0247136177655f0008588781e90863afa62"
-dependencies = [
- "block",
- "core-foundation 0.10.0",
- "core-graphics2",
- "io-surface",
- "libc",
- "metal",
-]
-
[[package]]
name = "core2"
version = "0.4.0"
@@ -7403,7 +7367,6 @@ dependencies = [
"bitflags 2.13.1",
"chrono",
"collections",
- "core-video",
"criterion",
"ctor",
"derive_more",
@@ -7479,13 +7442,16 @@ dependencies = [
"async-task",
"block2 0.6.2",
"cbindgen",
+ "collections",
"core-foundation 0.10.0",
+ "core-foundation-sys",
"core-graphics 0.24.0",
- "core-video",
+ "core-text",
"derive_more",
"dispatch2",
"etagere",
"foreign-types 0.5.0",
+ "futures 0.3.34",
"gpui",
"gpui_util",
"image",
@@ -7494,9 +7460,18 @@ dependencies = [
"mach2",
"metal",
"objc2 0.6.3",
+ "objc2-core-foundation",
+ "objc2-core-text",
+ "objc2-core-video",
"objc2-foundation 0.3.2",
+ "objc2-metal 0.3.2",
"objc2-quartz-core 0.3.2",
+ "objc2-security",
"parking_lot",
+ "pathfinder_geometry",
+ "smallvec",
+ "thiserror 2.0.17",
+ "zed-font-kit",
]
[[package]]
@@ -7555,8 +7530,6 @@ dependencies = [
"core-foundation 0.10.0",
"core-foundation-sys",
"core-graphics 0.24.0",
- "core-text",
- "core-video",
"ctor",
"dispatch2",
"foreign-types 0.5.0",
@@ -7572,18 +7545,17 @@ dependencies = [
"objc2-app-kit 0.3.2",
"objc2-core-graphics",
"objc2-core-media",
+ "objc2-core-video",
"objc2-foundation 0.3.2",
"objc2-screen-capture-kit",
"objc2-user-notifications",
"parking_lot",
- "pathfinder_geometry",
"raw-window-handle",
"scheduler",
"semver",
"smallvec",
"strum 0.28.0",
"uuid",
- "zed-font-kit",
]
[[package]]
@@ -8921,18 +8893,6 @@ version = "3.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f0fb0570afe1fed943c5c3d4102d5358592d8625fda6a0007fdbe65a92fba96"
-[[package]]
-name = "io-surface"
-version = "0.16.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "554b8c5d64ec09a3a520fe58e4d48a73e00ff32899cdcbe32a4877afd4968b8e"
-dependencies = [
- "cgl",
- "core-foundation 0.10.0",
- "core-foundation-sys",
- "leaky-cow",
-]
-
[[package]]
name = "iovec"
version = "0.1.4"
@@ -9828,21 +9788,6 @@ dependencies = [
"spin 0.9.8",
]
-[[package]]
-name = "leak"
-version = "0.1.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bd100e01f1154f2908dfa7d02219aeab25d0b9c7fa955164192e3245255a0c73"
-
-[[package]]
-name = "leaky-cow"
-version = "0.1.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "40a8225d44241fd324a8af2806ba635fc7c8a7e9a7de4d5cf3ef54e71f5926fc"
-dependencies = [
- "leak",
-]
-
[[package]]
name = "leb128"
version = "0.2.5"
@@ -10158,8 +10103,6 @@ dependencies = [
"async-trait",
"audio",
"collections",
- "core-foundation 0.10.0",
- "core-video",
"coreaudio-rs 0.12.1",
"cpal",
"futures 0.3.34",
@@ -10174,6 +10117,7 @@ dependencies = [
"log",
"nanoid",
"objc2-core-foundation",
+ "objc2-core-video",
"parking_lot",
"postage",
"rodio",
@@ -11829,6 +11773,16 @@ dependencies = [
"objc2-core-foundation",
]
+[[package]]
+name = "objc2-core-text"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d"
+dependencies = [
+ "bitflags 2.13.1",
+ "objc2-core-foundation",
+]
+
[[package]]
name = "objc2-core-video"
version = "0.3.2"
@@ -11840,6 +11794,7 @@ dependencies = [
"objc2-core-foundation",
"objc2-core-graphics",
"objc2-io-surface",
+ "objc2-metal 0.3.2",
]
[[package]]
@@ -11960,6 +11915,15 @@ dependencies = [
"objc2-foundation 0.3.2",
]
+[[package]]
+name = "objc2-security"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "709fe137109bd1e8b5a99390f77a7d8b2961dafc1a1c5db8f2e60329ad6d895a"
+dependencies = [
+ "objc2-core-foundation",
+]
+
[[package]]
name = "objc2-user-notifications"
version = "0.3.2"
diff --git a/Cargo.toml b/Cargo.toml
index 616a75fa126..eae064c0628 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -602,7 +602,6 @@ core-foundation-sys = "0.8.6"
core-graphics = "0.24"
core-services = "1"
core-text = "21"
-core-video = { version = "0.5", default-features = false, features = ["link"] }
coreaudio-rs = { version = "0.12", default-features = false }
cpal = { git = "https://github.com/RustAudio/cpal", rev = "e1612d5d98152f8dc2a62e1b51ef7cbf4f7f26b7" }
crash-handler = "0.8"
@@ -726,6 +725,7 @@ objc2-app-kit = { version = "0.3.2", default-features = false, features = [
objc2-core-foundation = { version = "=0.3.2", default-features = false }
objc2-core-graphics = { version = "=0.3.2", default-features = false, features = ["CGDirectDisplay"] }
objc2-core-media = { version = "=0.3.2", default-features = false, features = ["CMSampleBuffer", "objc2-core-video"] }
+objc2-core-text = { version = "0.3.2", default-features = false, features = ["std", "CTFont", "CTFontDescriptor"] }
objc2-core-video = { version = "=0.3.2", default-features = false, features = ["CVBuffer", "CVImageBuffer"] }
objc2-foundation = { version = "=0.3.2", default-features = false, features = [
"NSArray",
@@ -750,6 +750,7 @@ objc2-foundation = { version = "=0.3.2", default-features = false, features = [
"objc2-core-foundation",
"std",
] }
+objc2-security = { version = "0.3.2", default-features = false, features = ["std", "SecBase", "SecItem"] }
objc2-quartz-core = { version = "=0.3.2", default-features = false, features = ["std", "CALayer", "CAMetalLayer"] }
objc2-screen-capture-kit = { version = "=0.3.2", default-features = false, features = [
"block2",
diff --git a/crates/gpui/Cargo.toml b/crates/gpui/Cargo.toml
index e760cdd2c0c..4d978071f5e 100644
--- a/crates/gpui/Cargo.toml
+++ b/crates/gpui/Cargo.toml
@@ -42,8 +42,6 @@ x11 = [
]
screen-capture = [
"scap",
- "dep:objc2-core-foundation",
- "dep:objc2-core-video",
]
windows-manifest = ["dep:embed-resource"]
profiler = ["dep:hdrhistogram"]
@@ -134,11 +132,10 @@ uuid = { workspace = true, features = ["js"] }
[target.'cfg(any(target_os = "macos", target_os = "ios"))'.dependencies]
-core-video.workspace = true
+objc2-core-foundation.workspace = true
+objc2-core-video = { workspace = true, features = ["CVPixelBuffer"] }
[target.'cfg(target_os = "macos")'.dependencies]
-objc2-core-foundation = { workspace = true, optional = true }
-objc2-core-video = { workspace = true, optional = true }
log.workspace = true
objc2 = { workspace = true, optional = true }
objc2-metal = { version = "0.3", optional = true }
diff --git a/crates/gpui/src/app/headless_app_context.rs b/crates/gpui/src/app/headless_app_context.rs
index 6ac4bfe9f85..c7f7c913451 100644
--- a/crates/gpui/src/app/headless_app_context.rs
+++ b/crates/gpui/src/app/headless_app_context.rs
@@ -2,7 +2,7 @@
//!
//! This replaces the macOS-only `HeadlessMetalAppContext` with a platform-neutral
//! implementation backed by `TestPlatform`. Tests supply a real `PlatformTextSystem`
-//! (e.g. `DirectWriteTextSystem` on Windows, `MacTextSystem` on macOS) to get
+//! (e.g. `DirectWriteTextSystem` on Windows, `AppleTextSystem` on macOS) to get
//! accurate glyph measurements while keeping everything else deterministic.
//!
//! Optionally, a renderer factory can be provided to enable real GPU rendering
diff --git a/crates/gpui/src/elements/surface.rs b/crates/gpui/src/elements/surface.rs
index fb07280927b..acd29329109 100644
--- a/crates/gpui/src/elements/surface.rs
+++ b/crates/gpui/src/elements/surface.rs
@@ -3,7 +3,9 @@ use crate::{
ObjectFit, Pixels, Style, StyleRefinement, Styled, Window,
};
#[cfg(any(target_os = "macos", target_os = "ios"))]
-use core_video::pixel_buffer::CVPixelBuffer;
+use objc2_core_foundation::CFRetained;
+#[cfg(any(target_os = "macos", target_os = "ios"))]
+use objc2_core_video::{CVPixelBuffer, CVPixelBufferGetHeight, CVPixelBufferGetWidth};
use refineable::Refineable;
/// A source of a surface's content.
@@ -11,12 +13,12 @@ use refineable::Refineable;
pub enum SurfaceSource {
/// A CoreVideo image buffer
#[cfg(any(target_os = "macos", target_os = "ios"))]
- Surface(CVPixelBuffer),
+ Surface(CFRetained<CVPixelBuffer>),
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
-impl From<CVPixelBuffer> for SurfaceSource {
- fn from(value: CVPixelBuffer) -> Self {
+impl From<CFRetained<CVPixelBuffer>> for SurfaceSource {
+ fn from(value: CFRetained<CVPixelBuffer>) -> Self {
SurfaceSource::Surface(value)
}
}
@@ -103,7 +105,10 @@ impl Element for Surface {
match &self.source {
#[cfg(any(target_os = "macos", target_os = "ios"))]
SurfaceSource::Surface(surface) => {
- let size = crate::size(surface.get_width().into(), surface.get_height().into());
+ let size = crate::size(
+ CVPixelBufferGetWidth(surface).into(),
+ CVPixelBufferGetHeight(surface).into(),
+ );
let new_bounds = self.object_fit.get_bounds(bounds, size);
// TODO: Add support for corner_radii
window.paint_surface(new_bounds, surface.clone());
diff --git a/crates/gpui/src/scene.rs b/crates/gpui/src/scene.rs
index 160587a4ad9..be378132478 100644
--- a/crates/gpui/src/scene.rs
+++ b/crates/gpui/src/scene.rs
@@ -770,7 +770,7 @@ pub struct PaintSurface {
pub bounds: Bounds<ScaledPixels>,
pub content_mask: ContentMask<ScaledPixels>,
#[cfg(any(target_os = "macos", target_os = "ios"))]
- pub image_buffer: core_video::pixel_buffer::CVPixelBuffer,
+ pub image_buffer: objc2_core_foundation::CFRetained<objc2_core_video::CVPixelBuffer>,
}
impl From<PaintSurface> for Primitive {
diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs
index b6b304c56f3..567da8f39e6 100644
--- a/crates/gpui/src/window.rs
+++ b/crates/gpui/src/window.rs
@@ -29,14 +29,16 @@ use crate::gestures::{GestureTuning, RecognizedTouchGesture, TouchGestureRecogni
use crate::interactive::TouchEvent;
use anyhow::{Context as _, Result, anyhow};
use collections::{FxHashMap, FxHashSet};
-#[cfg(any(target_os = "macos", target_os = "ios"))]
-use core_video::pixel_buffer::CVPixelBuffer;
use derive_more::{Deref, DerefMut};
use futures::channel::oneshot;
use gpui_util::post_inc;
use gpui_util::{ResultExt, measure};
use itertools::FoldWhile::{Continue, Done};
use itertools::Itertools;
+#[cfg(any(target_os = "macos", target_os = "ios"))]
+use objc2_core_foundation::CFRetained;
+#[cfg(any(target_os = "macos", target_os = "ios"))]
+use objc2_core_video::CVPixelBuffer;
use parking_lot::RwLock;
use raw_window_handle::{HandleError, HasDisplayHandle, HasWindowHandle};
use refineable::Refineable;
@@ -5130,7 +5132,11 @@ impl Window {
///
/// This method should only be called as part of the paint phase of element drawing.
#[cfg(any(target_os = "macos", target_os = "ios"))]
- pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVPixelBuffer) {
+ pub fn paint_surface(
+ &mut self,
+ bounds: Bounds<Pixels>,
+ image_buffer: CFRetained<CVPixelBuffer>,
+ ) {
use crate::PaintSurface;
self.invalidator.debug_assert_paint();
diff --git a/crates/gpui_apple/Cargo.toml b/crates/gpui_apple/Cargo.toml
index 6b53075181b..23142d504f5 100644
--- a/crates/gpui_apple/Cargo.toml
+++ b/crates/gpui_apple/Cargo.toml
@@ -17,6 +17,7 @@ default = []
bench-support = ["gpui/bench-support"]
test-support = ["gpui/test-support"]
runtime_shaders = []
+font-kit = ["dep:font-kit", "dep:core-text", "dep:objc2-core-text", "dep:pathfinder_geometry"]
[dependencies]
gpui.workspace = true
@@ -25,13 +26,18 @@ gpui.workspace = true
anyhow.workspace = true
async-task.workspace = true
block2.workspace = true
+collections.workspace = true
core-foundation.workspace = true
+core-foundation-sys.workspace = true
core-graphics.workspace = true
-core-video = { workspace = true, features = ["metal"] }
+core-text = { workspace = true, optional = true }
derive_more.workspace = true
dispatch2.workspace = true
etagere.workspace = true
foreign-types.workspace = true
+futures.workspace = true
+# WARNING: If you change this, you must also publish a new version of zed-font-kit to crates.io
+font-kit = { workspace = true, optional = true, features = ["source"] }
gpui_util.workspace = true
image.workspace = true
libc.workspace = true
@@ -39,12 +45,21 @@ log.workspace = true
mach2.workspace = true
metal.workspace = true
objc2.workspace = true
-objc2-foundation = { workspace = true, features = ["NSThread"] }
+objc2-core-foundation = { workspace = true, features = ["std", "CFData", "CFDictionary", "CFString", "CFNumber", "CFBase"] }
+objc2-core-text = { workspace = true, optional = true }
+objc2-core-video = { workspace = true, features = ["CVPixelBuffer", "CVMetalTexture", "CVMetalTextureCache", "CVReturn", "objc2", "objc2-metal"] }
+objc2-metal = { version = "0.3", default-features = false, features = ["MTLDevice", "MTLPixelFormat", "MTLTexture"] }
+objc2-foundation = { workspace = true, features = ["NSThread", "NSNotification", "NSOperation", "NSProcessInfo", "block2"] }
objc2-quartz-core.workspace = true
+objc2-security.workspace = true
parking_lot.workspace = true
+pathfinder_geometry = { workspace = true, optional = true }
+smallvec.workspace = true
+thiserror.workspace = true
[target.'cfg(any(target_os = "macos", target_os = "ios"))'.build-dependencies]
cbindgen.workspace = true
[target.'cfg(any(target_os = "macos", target_os = "ios"))'.dev-dependencies]
gpui = { workspace = true, features = ["test-support"] }
+objc2-core-video = { workspace = true, features = ["CVBase"] }
diff --git a/crates/gpui_apple/src/gpui_apple.rs b/crates/gpui_apple/src/gpui_apple.rs
index 63fb1b14497..6f39e63b762 100644
--- a/crates/gpui_apple/src/gpui_apple.rs
+++ b/crates/gpui_apple/src/gpui_apple.rs
@@ -1,12 +1,21 @@
#![cfg(any(target_os = "macos", target_os = "ios"))]
-//! Shared Apple rendering and task dispatch for GPUI.
+//! Shared Apple rendering, task dispatch, and system services for GPUI.
//!
//! This crate renders GPUI scenes directly with Metal on Apple platforms. It
-//! owns GPU resources and shaders while leaving application lifecycle,
-//! windowing, and input to each platform backend.
+//! owns GPU resources, text rendering, Keychain access, and thermal notifications
+//! while leaving application lifecycle, windowing, and input to each platform backend.
mod dispatcher;
+pub mod keychain;
mod metal_atlas;
pub mod metal_renderer;
+pub mod thermal;
+
+#[cfg(feature = "font-kit")]
+mod open_type;
+#[cfg(feature = "font-kit")]
+mod text_system;
pub use dispatcher::{AppleActivity, AppleDispatcher};
+#[cfg(feature = "font-kit")]
+pub use text_system::AppleTextSystem;
diff --git a/crates/gpui_apple/src/keychain.rs b/crates/gpui_apple/src/keychain.rs
new file mode 100644
index 00000000000..292a1ed241f
--- /dev/null
+++ b/crates/gpui_apple/src/keychain.rs
@@ -0,0 +1,216 @@
+use objc2_core_foundation::{CFData, CFDictionary, CFRetained, CFString, CFType, kCFBooleanTrue};
+use objc2_security::{
+ SecItemAdd, SecItemCopyMatching, SecItemDelete, SecItemUpdate, errSecItemNotFound,
+ errSecSuccess, errSecUserCanceled, kSecAttrAccount, kSecAttrServer, kSecClass,
+ kSecClassInternetPassword, kSecReturnAttributes, kSecReturnData, kSecValueData,
+};
+use std::ptr;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum KeychainOperation {
+ Read,
+ Update,
+ Create,
+ Delete,
+}
+
+#[derive(Debug, thiserror::Error, PartialEq, Eq)]
+pub enum KeychainError {
+ #[error("keychain {operation:?} failed with OSStatus {status}")]
+ Security {
+ operation: KeychainOperation,
+ status: i32,
+ },
+ #[error("invalid keychain response: {0}")]
+ InvalidResponse(&'static str),
+}
+
+pub fn write_credentials(
+ server: &str,
+ account: &str,
+ password: &[u8],
+) -> Result<(), KeychainError> {
+ let server = CFString::from_str(server);
+ let account = CFString::from_str(account);
+ let password = CFData::from_bytes(password);
+ // SAFETY: Reading immutable constants exported by the Security framework.
+ let (class_key, server_key, account_key, data_key, internet_password) = unsafe {
+ (
+ kSecClass,
+ kSecAttrServer,
+ kSecAttrAccount,
+ kSecValueData,
+ kSecClassInternetPassword,
+ )
+ };
+ let query = CFDictionary::<CFString, CFType>::from_slices(
+ &[class_key, server_key],
+ &[internet_password, &server],
+ );
+ let attributes = CFDictionary::<CFString, CFType>::from_slices(
+ &[account_key, data_key],
+ &[&account, &password],
+ );
+ let mut operation = KeychainOperation::Update;
+ // SAFETY: Both dictionaries map Security attribute keys to CF values.
+ let mut status = unsafe { SecItemUpdate(query.as_opaque(), attributes.as_opaque()) };
+ if status == errSecItemNotFound {
+ operation = KeychainOperation::Create;
+ let attributes = CFDictionary::<CFString, CFType>::from_slices(
+ &[class_key, server_key, account_key, data_key],
+ &[internet_password, &server, &account, &password],
+ );
+ // SAFETY: The dictionary maps Security attribute keys to CF values, and a
+ // null result pointer asks Security not to return the new item.
+ status = unsafe { SecItemAdd(attributes.as_opaque(), ptr::null_mut()) };
+ }
+ check_status(operation, status)
+}
+
+pub fn read_credentials(server: &str) -> Result<Option<(String, Vec<u8>)>, KeychainError> {
+ let server = CFString::from_str(server);
+ // SAFETY: Reading immutable constants exported by Core Foundation and Security.
+ let (
+ true_value,
+ class_key,
+ server_key,
+ return_attributes_key,
+ return_data_key,
+ internet_password,
+ ) = unsafe {
+ (
+ kCFBooleanTrue,
+ kSecClass,
+ kSecAttrServer,
+ kSecReturnAttributes,
+ kSecReturnData,
+ kSecClassInternetPassword,
+ )
+ };
+ let true_value = true_value.ok_or(KeychainError::InvalidResponse(
+ "Core Foundation true value unavailable",
+ ))?;
+ let query = CFDictionary::<CFString, CFType>::from_slices(
+ &[
+ class_key,
+ server_key,
+ return_attributes_key,
+ return_data_key,
+ ],
+ &[internet_password, &server, true_value, true_value],
+ );
+ let mut result = ptr::null();
+ // SAFETY: The query maps Security attribute keys to CF values, and `result`
+ // is a valid out-pointer.
+ let status = unsafe { SecItemCopyMatching(query.as_opaque(), &mut result) };
+ if !read_status(status)? {
+ return Ok(None);
+ }
+ let result = ptr::NonNull::new(result.cast_mut())
+ .ok_or(KeychainError::InvalidResponse("keychain returned no item"))?;
+ // SAFETY: SecItemCopyMatching follows the Create rule, so we own this reference.
+ let result = unsafe { CFRetained::from_raw(result) }
+ .downcast::<CFDictionary>()
+ .map_err(|_| KeychainError::InvalidResponse("keychain item was not a dictionary"))?;
+ // SAFETY: Security returns CFType keys and values; each value is downcast below.
+ let result = unsafe { result.cast_unchecked::<CFType, CFType>() };
+ // SAFETY: Reading immutable constants exported by the Security framework.
+ let (account_key, data_key) = unsafe { (kSecAttrAccount, kSecValueData) };
+ let account = result
+ .get(account_key)
+ .ok_or(KeychainError::InvalidResponse(
+ "account was missing from keychain item",
+ ))?
+ .downcast::<CFString>()
+ .map_err(|_| KeychainError::InvalidResponse("account was not a string"))?;
+ let password = result
+ .get(data_key)
+ .ok_or(KeychainError::InvalidResponse(
+ "password was missing from keychain item",
+ ))?
+ .downcast::<CFData>()
+ .map_err(|_| KeychainError::InvalidResponse("password was not data"))?;
+ Ok(Some((account.to_string(), password.to_vec())))
+}
+
+pub fn delete_credentials(server: &str) -> Result<(), KeychainError> {
+ let server = CFString::from_str(server);
+ // SAFETY: Reading immutable constants exported by the Security framework.
+ let (class_key, server_key, internet_password) =
+ unsafe { (kSecClass, kSecAttrServer, kSecClassInternetPassword) };
+ let query = CFDictionary::<CFString, CFType>::from_slices(
+ &[class_key, server_key],
+ &[internet_password, &server],
+ );
+ // SAFETY: The query maps Security attribute keys to CF values.
+ let status = unsafe { SecItemDelete(query.as_opaque()) };
+ check_status(KeychainOperation::Delete, status)
+}
+
+fn read_status(status: i32) -> Result<bool, KeychainError> {
+ if status == errSecItemNotFound || status == errSecUserCanceled {
+ Ok(false)
+ } else {
+ check_status(KeychainOperation::Read, status)?;
+ Ok(true)
+ }
+}
+
+fn check_status(operation: KeychainOperation, status: i32) -> Result<(), KeychainError> {
+ if status == errSecSuccess {
+ Ok(())
+ } else {
+ Err(KeychainError::Security { operation, status })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use objc2_security::errSecAuthFailed;
+
+ #[test]
+ fn read_distinguishes_absence_and_cancellation_from_errors() {
+ assert!(read_status(errSecSuccess).unwrap());
+ assert!(!read_status(errSecItemNotFound).unwrap());
+ assert!(!read_status(errSecUserCanceled).unwrap());
+ assert_eq!(
+ read_status(errSecAuthFailed),
+ Err(KeychainError::Security {
+ operation: KeychainOperation::Read,
+ status: errSecAuthFailed,
+ })
+ );
+ }
+
+ #[test]
+ fn platform_error_keeps_native_operation_and_status() {
+ let error: anyhow::Error = check_status(KeychainOperation::Update, errSecAuthFailed)
+ .unwrap_err()
+ .into();
+ assert_eq!(
+ error.downcast_ref::<KeychainError>(),
+ Some(&KeychainError::Security {
+ operation: KeychainOperation::Update,
+ status: errSecAuthFailed,
+ })
+ );
+ }
+
+ #[test]
+ fn delete_preserves_macos_missing_item_error() {
+ assert_eq!(
+ check_status(KeychainOperation::Delete, errSecSuccess),
+ Ok(())
+ );
+ for status in [errSecItemNotFound, errSecUserCanceled, errSecAuthFailed] {
+ assert_eq!(
+ check_status(KeychainOperation::Delete, status),
+ Err(KeychainError::Security {
+ operation: KeychainOperation::Delete,
+ status,
+ })
+ );
+ }
+ }
+}
diff --git a/crates/gpui_apple/src/metal_renderer.rs b/crates/gpui_apple/src/metal_renderer.rs
index a2a78ed3033..e46620587fd 100644
--- a/crates/gpui_apple/src/metal_renderer.rs
+++ b/crates/gpui_apple/src/metal_renderer.rs
@@ -10,16 +10,17 @@ use gpui::{
use image::RgbaImage;
use objc2::runtime::AnyObject;
-use core_foundation::base::TCFType;
-use core_video::{
- metal_texture::CVMetalTextureGetTexture, metal_texture_cache::CVMetalTextureCache,
- pixel_buffer::kCVPixelFormatType_420YpCbCr8BiPlanarFullRange,
-};
use foreign_types::{ForeignType, ForeignTypeRef};
use metal::{
CAMetalLayer, CommandQueue, MTLGPUFamily, MTLPixelFormat, MTLResourceOptions, NSRange,
NSUInteger,
};
+use objc2_core_foundation::CFRetained;
+use objc2_core_video::{
+ CVMetalTexture, CVMetalTextureCache, CVMetalTextureGetTexture, CVPixelBufferGetHeight,
+ CVPixelBufferGetHeightOfPlane, CVPixelBufferGetPixelFormatType, CVPixelBufferGetWidth,
+ CVPixelBufferGetWidthOfPlane, kCVPixelFormatType_420YpCbCr8BiPlanarFullRange, kCVReturnSuccess,
+};
use parking_lot::Mutex;
use std::{cell::Cell, ffi::c_void, mem, mem::MaybeUninit, ops::Range, ptr, slice, sync::Arc};
@@ -127,7 +128,7 @@ pub struct MetalRenderer {
#[allow(clippy::arc_with_non_send_sync)]
instance_buffer_pool: Arc<Mutex<InstanceBufferPool>>,
sprite_atlas: Arc<MetalAtlas>,
- core_video_texture_cache: core_video::metal_texture_cache::CVMetalTextureCache,
+ core_video_texture_cache: CFRetained<CVMetalTextureCache>,
path_intermediate_texture: Option<metal::Texture>,
path_intermediate_msaa_texture: Option<metal::Texture>,
path_sample_count: u32,
@@ -362,8 +363,25 @@ impl MetalRenderer {
let command_queue = device.new_command_queue();
let supports_shared_storage = cfg!(target_os = "ios") || is_apple_gpu;
let sprite_atlas = Arc::new(MetalAtlas::new(device.clone(), supports_shared_storage));
- let core_video_texture_cache =
- CVMetalTextureCache::new(None, device.clone(), None).unwrap();
+ // metal and objc2-metal expose the same Objective-C device; the borrowed
+ // protocol object remains valid while `device` owns it.
+ let core_video_texture_cache = unsafe {
+ let mut cache = ptr::null_mut();
+ let status = CVMetalTextureCache::create(
+ None,
+ None,
+ &*device
+ .as_ptr()
+ .cast::<objc2::runtime::ProtocolObject<dyn objc2_metal::MTLDevice>>(),
+ None,
+ ptr::NonNull::from(&mut cache),
+ );
+ assert_eq!(
+ status, kCVReturnSuccess,
+ "failed to create CoreVideo Metal texture cache"
+ );
+ CFRetained::from_raw(ptr::NonNull::new(cache).expect("CoreVideo returned a null cache"))
+ };
Self {
device,
@@ -1192,52 +1210,59 @@ impl MetalRenderer {
);
for (index, surface) in surfaces.iter().enumerate() {
+ let image_buffer = &surface.image_buffer;
let texture_size = size(
- DevicePixels::from(surface.image_buffer.get_width() as i32),
- DevicePixels::from(surface.image_buffer.get_height() as i32),
+ DevicePixels::from(CVPixelBufferGetWidth(image_buffer) as i32),
+ DevicePixels::from(CVPixelBufferGetHeight(image_buffer) as i32),
);
assert_eq!(
- surface.image_buffer.get_pixel_format(),
+ CVPixelBufferGetPixelFormatType(image_buffer),
kCVPixelFormatType_420YpCbCr8BiPlanarFullRange
);
- let y_texture = self
- .core_video_texture_cache
- .create_texture_from_image(
- surface.image_buffer.as_concrete_TypeRef(),
+ let plane_texture = |plane, format| unsafe {
+ let mut texture = ptr::null_mut();
+ let status = CVMetalTextureCache::create_texture_from_image(
None,
- MTLPixelFormat::R8Unorm,
- surface.image_buffer.get_width_of_plane(0),
- surface.image_buffer.get_height_of_plane(0),
- 0,
- )
- .unwrap();
- let cb_cr_texture = self
- .core_video_texture_cache
- .create_texture_from_image(
- surface.image_buffer.as_concrete_TypeRef(),
+ &self.core_video_texture_cache,
+ image_buffer,
None,
- MTLPixelFormat::RG8Unorm,
- surface.image_buffer.get_width_of_plane(1),
- surface.image_buffer.get_height_of_plane(1),
- 1,
+ format,
+ CVPixelBufferGetWidthOfPlane(image_buffer, plane),
+ CVPixelBufferGetHeightOfPlane(image_buffer, plane),
+ plane,
+ ptr::NonNull::from(&mut texture),
+ );
+ assert_eq!(
+ status, kCVReturnSuccess,
+ "failed to create CoreVideo Metal texture"
+ );
+ CFRetained::<CVMetalTexture>::from_raw(
+ ptr::NonNull::new(texture).expect("CoreVideo returned a null texture"),
)
- .unwrap();
+ };
+ let y_texture = plane_texture(0, objc2_metal::MTLPixelFormat::R8Unorm);
+ let cb_cr_texture = plane_texture(1, objc2_metal::MTLPixelFormat::RG8Unorm);
command_encoder.set_vertex_bytes(
SurfaceInputIndex::TextureSize as u64,
mem::size_of_val(&texture_size) as u64,
&texture_size as *const Size<DevicePixels> as *const _,
);
- // let y_texture = y_texture.get_texture().unwrap().
command_encoder.set_fragment_texture(SurfaceInputIndex::YTexture as u64, unsafe {
- let texture = CVMetalTextureGetTexture(y_texture.as_concrete_TypeRef());
- Some(metal::TextureRef::from_ptr(texture as *mut _))
+ let texture = CVMetalTextureGetTexture(&y_texture)
+ .expect("CoreVideo returned no Metal texture");
+ Some(metal::TextureRef::from_ptr(
+ objc2::rc::Retained::as_ptr(&texture) as *mut _,
+ ))
});
command_encoder.set_fragment_texture(SurfaceInputIndex::CbCrTexture as u64, unsafe {
- let texture = CVMetalTextureGetTexture(cb_cr_texture.as_concrete_TypeRef());
- Some(metal::TextureRef::from_ptr(texture as *mut _))
+ let texture = CVMetalTextureGetTexture(&cb_cr_texture)
+ .expect("CoreVideo returned no Metal texture");
+ Some(metal::TextureRef::from_ptr(
+ objc2::rc::Retained::as_ptr(&texture) as *mut _,
+ ))
});
command_encoder.draw_primitives_instanced_base_instance(
@@ -1671,3 +1696,79 @@ impl gpui::PlatformHeadlessRenderer for MetalHeadlessRenderer {
self.renderer.sprite_atlas().clone()
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use objc2_core_foundation::{CFDictionary, CFType};
+ use objc2_core_video::{
+ CVPixelBufferCreate, CVPixelBufferGetBaseAddressOfPlane,
+ CVPixelBufferGetBytesPerRowOfPlane, CVPixelBufferLockBaseAddress, CVPixelBufferLockFlags,
+ CVPixelBufferUnlockBaseAddress, kCVPixelBufferIOSurfacePropertiesKey,
+ };
+
+ #[test]
+ fn render_core_video_surface() {
+ let attributes = CFDictionary::from_slices(
+ &[unsafe { kCVPixelBufferIOSurfacePropertiesKey }],
+ &[&*CFDictionary::<CFType, CFType>::empty()],
+ );
+ let mut image_buffer = ptr::null_mut();
+ assert_eq!(
+ unsafe {
+ CVPixelBufferCreate(
+ None,
+ 16,
+ 16,
+ kCVPixelFormatType_420YpCbCr8BiPlanarFullRange,
+ Some(attributes.as_opaque()),
+ ptr::NonNull::from(&mut image_buffer),
+ )
+ },
+ kCVReturnSuccess
+ );
+ let image_buffer =
+ unsafe { CFRetained::from_raw(ptr::NonNull::new(image_buffer).unwrap()) };
+ unsafe {
+ assert_eq!(
+ CVPixelBufferLockBaseAddress(&image_buffer, CVPixelBufferLockFlags::empty()),
+ kCVReturnSuccess
+ );
+ for plane in 0..2 {
+ let bytes = CVPixelBufferGetBaseAddressOfPlane(&image_buffer, plane).cast::<u8>();
+ let length = CVPixelBufferGetBytesPerRowOfPlane(&image_buffer, plane)
+ * CVPixelBufferGetHeightOfPlane(&image_buffer, plane);
+ slice::from_raw_parts_mut(bytes, length).fill(128);
+ }
+ assert_eq!(
+ CVPixelBufferUnlockBaseAddress(&image_buffer, CVPixelBufferLockFlags::empty()),
+ kCVReturnSuccess
+ );
+ }
+
+ let bounds = Bounds {
+ origin: Point::default(),
+ size: size(ScaledPixels(16.0), ScaledPixels(16.0)),
+ };
+ let mut scene = Scene::default();
+ scene.insert_primitive(PaintSurface {
+ order: 0,
+ bounds,
+ content_mask: ContentMask { bounds },
+ image_buffer: image_buffer.clone(),
+ });
+ drop(image_buffer);
+ scene.finish();
+
+ let mut renderer = MetalRenderer::new_headless(Arc::new(Mutex::new(Default::default())));
+ let image = renderer
+ .render_scene_to_image(&scene, size(DevicePixels(16), DevicePixels(16)))
+ .unwrap();
+ for image::Rgba([red, green, blue, alpha]) in image.pixels() {
+ assert!(red.abs_diff(128) <= 2);
+ assert!(green.abs_diff(128) <= 2);
+ assert!(blue.abs_diff(128) <= 2);
+ assert_eq!(*alpha, 255);
+ }
+ }
+}
diff --git a/crates/gpui_macos/src/open_type.rs b/crates/gpui_apple/src/open_type.rs
similarity index 68%
rename from crates/gpui_macos/src/open_type.rs
rename to crates/gpui_apple/src/open_type.rs
index 44891910380..d23a09b5a39 100644
--- a/crates/gpui_macos/src/open_type.rs
+++ b/crates/gpui_apple/src/open_type.rs
@@ -1,35 +1,29 @@
-#![allow(unused, non_upper_case_globals)]
-
-use cocoa::appkit::CGFloat;
use core_foundation::{
array::{
- CFArray, CFArrayAppendArray, CFArrayAppendValue, CFArrayCreateMutable, CFArrayGetCount,
- CFArrayGetValueAtIndex, CFArrayRef, CFMutableArrayRef, kCFTypeArrayCallBacks,
+ CFArray, CFArrayAppendValue, CFArrayCreateMutable, CFMutableArrayRef, kCFTypeArrayCallBacks,
},
base::{CFRelease, TCFType, kCFAllocatorDefault},
dictionary::{
CFDictionaryCreate, kCFTypeDictionaryKeyCallBacks, kCFTypeDictionaryValueCallBacks,
},
number::CFNumber,
- string::{CFString, CFStringRef},
+ string::CFString,
};
use core_foundation_sys::locale::CFLocaleCopyPreferredLanguages;
-use core_graphics::{display::CFDictionary, geometry::CGAffineTransform};
use core_text::font_descriptor::{
TraitAccessors, kCTFontFamilyNameAttribute, kCTFontItalicTrait, kCTFontSlantTrait,
- kCTFontTraitsAttribute, kCTFontWeightTrait, kCTFontWidthTrait,
+ kCTFontTraitsAttribute, kCTFontWeightTrait,
};
use core_text::{
- font::{CTFont, CTFontRef, cascade_list_for_languages},
+ font::{CTFont, cascade_list_for_languages},
font_descriptor::{
- CTFontDescriptor, CTFontDescriptorCopyAttributes, CTFontDescriptorCreateCopyWithFeature,
- CTFontDescriptorCreateWithAttributes, CTFontDescriptorCreateWithNameAndSize,
- CTFontDescriptorRef, kCTFontCascadeListAttribute, kCTFontFeatureSettingsAttribute,
+ CTFontDescriptor, CTFontDescriptorCreateWithAttributes, kCTFontCascadeListAttribute,
+ kCTFontFeatureSettingsAttribute,
},
};
use font_kit::font::Font as FontKitFont;
use gpui::{FontFallbacks, FontFeatures};
-use std::ptr;
+use objc2_core_text::{kCTFontOpenTypeFeatureTag, kCTFontOpenTypeFeatureValue};
pub fn apply_features_and_fallbacks(
font: &mut FontKitFont,
@@ -61,13 +55,21 @@ pub fn apply_features_and_fallbacks(
let new_descriptor = CTFontDescriptorCreateWithAttributes(attrs);
CFRelease(attrs as _);
let new_descriptor = CTFontDescriptor::wrap_under_create_rule(new_descriptor);
- let new_font = CTFontCreateCopyWithAttributes(
- font.native_font().as_concrete_TypeRef(),
- 0.0,
- std::ptr::null(),
- new_descriptor.as_concrete_TypeRef(),
+ // font-kit uses the older core-text wrappers. Borrow the same CF objects
+ // for the generated API, then transfer its create-rule ownership back.
+ let native_font = font.native_font();
+ let generated_font = &*native_font
+ .as_concrete_TypeRef()
+ .cast::<objc2_core_text::CTFont>();
+ let descriptor = &*new_descriptor
+ .as_concrete_TypeRef()
+ .cast::<objc2_core_text::CTFontDescriptor>();
+ let new_font = generated_font.copy_with_attributes(0.0, std::ptr::null(), Some(descriptor));
+ let new_font = CTFont::wrap_under_create_rule(
+ objc2_core_foundation::CFRetained::into_raw(new_font)
+ .as_ptr()
+ .cast(),
);
- let new_font = CTFont::wrap_under_create_rule(new_font);
*font = font_kit::font::Font::from_native_font(&new_font);
Ok(())
@@ -78,11 +80,13 @@ fn generate_feature_array(features: &FontFeatures) -> CFMutableArrayRef {
unsafe {
let feature_array = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
for (tag, value) in features.tag_value_list() {
- let keys = [kCTFontOpenTypeFeatureTag, kCTFontOpenTypeFeatureValue];
- let values = [
- CFString::new(tag).as_CFTypeRef(),
- CFNumber::from(*value as i32).as_CFTypeRef(),
+ let keys = [
+ kCTFontOpenTypeFeatureTag as *const _,
+ kCTFontOpenTypeFeatureValue as *const _,
];
+ let tag = CFString::new(tag);
+ let value = CFNumber::from(*value as i32);
+ let values = [tag.as_CFTypeRef(), value.as_CFTypeRef()];
let dict = CFDictionaryCreate(
kCFAllocatorDefault,
&keys as *const _ as _,
@@ -91,7 +95,6 @@ fn generate_feature_array(features: &FontFeatures) -> CFMutableArrayRef {
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks,
);
- values.into_iter().for_each(|value| CFRelease(value));
CFArrayAppendValue(feature_array, dict as _);
CFRelease(dict as _);
}
@@ -146,23 +149,17 @@ fn generate_fallback_array(fallbacks: &FontFallbacks, font: &mut FontKitFont) ->
CFRelease(fallback_desc as _);
}
- let font_ref = font.native_font().as_concrete_TypeRef();
- append_system_fallbacks(fallback_array, font_ref);
+ append_system_fallbacks(fallback_array, &font.native_font());
fallback_array
}
}
-fn append_system_fallbacks(fallback_array: CFMutableArrayRef, font_ref: CTFontRef) {
+fn append_system_fallbacks(fallback_array: CFMutableArrayRef, font: &CTFont) {
unsafe {
let preferred_languages: CFArray<CFString> =
CFArray::wrap_under_create_rule(CFLocaleCopyPreferredLanguages());
- let default_fallbacks = CTFontCopyDefaultCascadeListForLanguages(
- font_ref,
- preferred_languages.as_concrete_TypeRef(),
- );
- let default_fallbacks: CFArray<CTFontDescriptor> =
- CFArray::wrap_under_create_rule(default_fallbacks);
+ let default_fallbacks = cascade_list_for_languages(font, &preferred_languages);
for desc in default_fallbacks
.iter()
@@ -172,20 +169,3 @@ fn append_system_fallbacks(fallback_array: CFMutableArrayRef, font_ref: CTFontRe
}
}
}
-
-#[link(name = "CoreText", kind = "framework")]
-unsafe extern "C" {
- static kCTFontOpenTypeFeatureTag: CFStringRef;
- static kCTFontOpenTypeFeatureValue: CFStringRef;
-
- fn CTFontCreateCopyWithAttributes(
- font: CTFontRef,
- size: CGFloat,
- matrix: *const CGAffineTransform,
- attributes: CTFontDescriptorRef,
- ) -> CTFontRef;
- fn CTFontCopyDefaultCascadeListForLanguages(
- font: CTFontRef,
- languagePrefList: CFArrayRef,
- ) -> CFArrayRef;
-}
diff --git a/crates/gpui_macos/src/text_system.rs b/crates/gpui_apple/src/text_system.rs
similarity index 93%
rename from crates/gpui_macos/src/text_system.rs
rename to crates/gpui_apple/src/text_system.rs
index fbc48864ce5..3c0e17d63b6 100644
--- a/crates/gpui_macos/src/text_system.rs
+++ b/crates/gpui_apple/src/text_system.rs
@@ -1,18 +1,17 @@
use anyhow::anyhow;
-use cocoa::appkit::CGFloat;
use collections::{HashMap, HashSet};
use core_foundation::{
array::{CFArray, CFArrayRef},
attributed_string::CFMutableAttributedString,
- base::{CFRange, CFType, TCFType},
+ base::{CFRange, TCFType},
number::CFNumber,
string::CFString,
};
use core_graphics::{
- base::{CGGlyph, kCGImageAlphaPremultipliedLast},
+ base::{CGFloat, CGGlyph, kCGImageAlphaPremultipliedLast},
color_space::CGColorSpace,
context::{CGContext, CGTextDrawingMode},
- display::CGPoint,
+ geometry::CGPoint,
};
use core_text::{
font::CTFont,
@@ -35,9 +34,9 @@ use font_kit::{
};
use gpui::{
Bounds, DevicePixels, Font, FontFallbacks, FontFeatures, FontId, FontMetrics, FontRun,
- FontStyle, FontWeight, GlyphId, Hsla, LineLayout, Pixels, PlatformTextSystem,
- RenderGlyphParams, Result, Rgba, SUBPIXEL_VARIANTS_X, ShapedGlyph, ShapedRun, SharedString,
- Size, TextRenderingMode, point, px, size, swap_rgba_pa_to_bgra,
+ FontStyle, FontWeight, GlyphId, LineLayout, Pixels, PlatformTextSystem, RenderGlyphParams,
+ Result, SUBPIXEL_VARIANTS_X, ShapedGlyph, ShapedRun, SharedString, Size, TextRenderingMode,
+ point, px, size, swap_rgba_pa_to_bgra,
};
use parking_lot::{RwLock, RwLockUpgradableReadGuard};
use pathfinder_geometry::{
@@ -46,15 +45,22 @@ use pathfinder_geometry::{
vector::Vector2F,
};
use smallvec::SmallVec;
-use std::{borrow::Cow, char, convert::TryFrom, sync::Arc, sync::OnceLock};
+use std::{borrow::Cow, char, convert::TryFrom, sync::Arc};
+
+#[cfg(target_os = "macos")]
+use {
+ core_foundation::base::CFType,
+ gpui::{Hsla, Rgba},
+ std::sync::OnceLock,
+};
use crate::open_type::apply_features_and_fallbacks;
#[allow(non_upper_case_globals)]
const kCGImageAlphaOnly: u32 = 7;
-/// macOS text system using CoreText for font shaping.
-pub struct MacTextSystem(RwLock<MacTextSystemState>);
+/// Apple text system using CoreText for font shaping.
+pub struct AppleTextSystem(RwLock<AppleTextSystemState>);
#[derive(Clone, PartialEq, Eq, Hash)]
struct FontKey {
@@ -63,7 +69,7 @@ struct FontKey {
font_fallbacks: Option<FontFallbacks>,
}
-struct MacTextSystemState {
+struct AppleTextSystemState {
memory_source: MemSource,
system_source: SystemSource,
fonts: Vec<FontKitFont>,
@@ -73,10 +79,10 @@ struct MacTextSystemState {
postscript_names_by_font_id: HashMap<FontId, String>,
}
-impl MacTextSystem {
- /// Create a new MacTextSystem.
+impl AppleTextSystem {
+ /// Create a new AppleTextSystem.
pub fn new() -> Self {
- Self(RwLock::new(MacTextSystemState {
+ Self(RwLock::new(AppleTextSystemState {
memory_source: MemSource::empty(),
system_source: SystemSource::new(),
fonts: Vec::new(),
@@ -88,13 +94,13 @@ impl MacTextSystem {
}
}
-impl Default for MacTextSystem {
+impl Default for AppleTextSystem {
fn default() -> Self {
Self::new()
}
}
-impl PlatformTextSystem for MacTextSystem {
+impl PlatformTextSystem for AppleTextSystem {
fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
self.0.write().add_fonts(fonts)
}
@@ -215,6 +221,7 @@ impl PlatformTextSystem for MacTextSystem {
TextRenderingMode::Grayscale
}
+ #[cfg(target_os = "macos")]
fn glyph_dilation_for_color(&self, color: Hsla) -> u8 {
// When font smoothing is enabled, CoreGraphics thickens glyph strokes by an amount that
// depends on the foreground color's luminance. We replicate the logic used by CoreGraphics
@@ -229,6 +236,7 @@ impl PlatformTextSystem for MacTextSystem {
}
}
+#[cfg(target_os = "macos")]
fn font_smoothing_allowed_by_user() -> bool {
static ALLOWED: OnceLock<bool> = OnceLock::new();
*ALLOWED.get_or_init(|| {
@@ -252,7 +260,7 @@ fn font_smoothing_allowed_by_user() -> bool {
})
}
-impl MacTextSystemState {
+impl AppleTextSystemState {
fn add_fonts(&mut self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
let fonts = fonts
.into_iter()
@@ -499,7 +507,7 @@ impl MacTextSystemState {
cx.set_allows_font_subpixel_quantization(false);
cx.set_should_subpixel_quantize_fonts(false);
- if params.dilation > 0 {
+ if cfg!(target_os = "macos") && params.dilation > 0 {
let luminance = params.dilation as f64 * 0.25;
cx.set_should_smooth_fonts(true);
cx.set_gray_fill_color(luminance, 1.0);
@@ -766,12 +774,36 @@ mod lenient_font_attributes {
#[cfg(test)]
mod tests {
- use crate::MacTextSystem;
- use gpui::{FontRun, GlyphId, PlatformTextSystem, font, px};
+ use crate::AppleTextSystem;
+ use gpui::{FontFallbacks, FontFeatures, FontRun, GlyphId, PlatformTextSystem, font, px};
+ use std::sync::Arc;
+
+ #[test]
+ fn test_reload_family_with_features_and_fallbacks() {
+ let fonts = AppleTextSystem::new();
+ let mut font = font("Helvetica");
+ let original_id = fonts.font_id(&font).unwrap();
+ font.features = FontFeatures::disable_ligatures();
+ font.fallbacks = Some(FontFallbacks(Arc::new(vec!["Times".into()])));
+ let configured_id = fonts.font_id(&font).unwrap();
+ assert_ne!(original_id, configured_id);
+ assert_eq!(fonts.font_id(&font).unwrap(), configured_id);
+ assert!(fonts.glyph_for_char(configured_id, 'm').is_some());
+ let layout = fonts.layout_line(
+ "office",
+ px(16.),
+ &[FontRun {
+ font_id: configured_id,
+ len: 6,
+ }],
+ );
+ assert_eq!(layout.len, 6);
+ assert!(!layout.runs.is_empty());
+ }
#[test]
fn test_layout_line_bom_char() {
- let fonts = MacTextSystem::new();
+ let fonts = AppleTextSystem::new();
let font_id = fonts.font_id(&font("Helvetica")).unwrap();
let line = "\u{feff}";
let mut style = FontRun {
@@ -815,7 +847,7 @@ mod tests {
#[test]
fn test_layout_line_zwnj_insertion() {
- let fonts = MacTextSystem::new();
+ let fonts = AppleTextSystem::new();
let font_id = fonts.font_id(&font("Helvetica")).unwrap();
let text = "hello world";
@@ -866,7 +898,7 @@ mod tests {
#[test]
fn test_layout_line_zwnj_edge_cases() {
- let fonts = MacTextSystem::new();
+ let fonts = AppleTextSystem::new();
let font_id = fonts.font_id(&font("Helvetica")).unwrap();
let text = "hello";
diff --git a/crates/gpui_apple/src/thermal.rs b/crates/gpui_apple/src/thermal.rs
new file mode 100644
index 00000000000..24cc84e6baa
--- /dev/null
+++ b/crates/gpui_apple/src/thermal.rs
@@ -0,0 +1,113 @@
+use block2::RcBlock;
+use futures::{StreamExt, channel::mpsc};
+use gpui::{ForegroundExecutor, Task, ThermalState};
+use objc2::{rc::Retained, runtime::ProtocolObject};
+use objc2_foundation::{
+ NSNotification, NSNotificationCenter, NSObjectProtocol, NSProcessInfo,
+ NSProcessInfoThermalState, NSProcessInfoThermalStateDidChangeNotification,
+};
+
+pub fn thermal_state() -> ThermalState {
+ match NSProcessInfo::processInfo().thermalState() {
+ NSProcessInfoThermalState::Fair => ThermalState::Fair,
+ NSProcessInfoThermalState::Serious => ThermalState::Serious,
+ NSProcessInfoThermalState::Critical => ThermalState::Critical,
+ _ => ThermalState::Nominal,
+ }
+}
+
+pub struct ThermalObserver {
+ center: Retained<NSNotificationCenter>,
+ observer: Retained<ProtocolObject<dyn NSObjectProtocol>>,
+ _task: Task<()>,
+}
+
+impl ThermalObserver {
+ pub fn new(executor: &ForegroundExecutor, callback: Box<dyn FnMut()>) -> Self {
+ Self::with_center(NSNotificationCenter::defaultCenter(), executor, callback)
+ }
+
+ fn with_center(
+ center: Retained<NSNotificationCenter>,
+ executor: &ForegroundExecutor,
+ mut callback: Box<dyn FnMut()>,
+ ) -> Self {
+ let (sender, mut receiver) = mpsc::unbounded();
+ let block = RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
+ // NotificationCenter can call synchronously or off-thread. Never enter
+ // application code here: GPUI may already be borrowed on the main thread.
+ if sender.unbounded_send(()).is_err() {
+ log::debug!("thermal observer stopped before notification delivery");
+ }
+ });
+ let observer = unsafe {
+ center.addObserverForName_object_queue_usingBlock(
+ Some(NSProcessInfoThermalStateDidChangeNotification),
+ Some(&NSProcessInfo::processInfo()),
+ None,
+ &block,
+ )
+ };
+ let task = executor.spawn(async move {
+ while receiver.next().await.is_some() {
+ callback();
+ }
+ });
+ Self {
+ center,
+ observer,
+ _task: task,
+ }
+ }
+}
+
+impl Drop for ThermalObserver {
+ fn drop(&mut self) {
+ unsafe {
+ self.center.removeObserver(self.observer.as_ref());
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::{cell::Cell, rc::Rc};
+
+ // Tests run concurrently in one process, so they cannot share the default center.
+ fn post_thermal_notification(center: &NSNotificationCenter) {
+ unsafe {
+ center.postNotificationName_object(
+ NSProcessInfoThermalStateDidChangeNotification,
+ Some(&NSProcessInfo::processInfo()),
+ );
+ }
+ }
+
+ #[gpui::test]
+ fn notifications_are_deferred_and_cancelled_on_drop(cx: &mut gpui::TestAppContext) {
+ let center = NSNotificationCenter::new();
+ let calls = Rc::new(Cell::new(0));
+ let observer = ThermalObserver::with_center(
+ center.clone(),
+ &cx.foreground_executor,
+ Box::new({
+ let calls = calls.clone();
+ move || calls.set(calls.get() + 1)
+ }),
+ );
+ let post_notification = || post_thermal_notification(&center);
+ post_notification();
+ assert_eq!(calls.get(), 0);
+ cx.run_until_parked();
+ assert_eq!(calls.get(), 1);
+
+ post_notification();
+ drop(observer);
+ cx.run_until_parked();
+ assert_eq!(calls.get(), 1);
+ post_notification();
+ cx.run_until_parked();
+ assert_eq!(calls.get(), 1);
+ }
+}
diff --git a/crates/gpui_macos/Cargo.toml b/crates/gpui_macos/Cargo.toml
index 563f1432072..f136df4b87c 100644
--- a/crates/gpui_macos/Cargo.toml
+++ b/crates/gpui_macos/Cargo.toml
@@ -17,7 +17,7 @@ default = ["gpui/default"]
bench-support = ["gpui/bench-support", "gpui_apple/bench-support"]
test-support = ["gpui/test-support", "gpui_apple/test-support"]
runtime_shaders = ["gpui_apple/runtime_shaders"]
-font-kit = ["dep:font-kit", "dep:core-text", "dep:pathfinder_geometry"]
+font-kit = ["gpui_apple/font-kit"]
screen-capture = ["gpui/screen-capture", "dep:objc2-core-graphics", "dep:objc2-core-media", "dep:objc2-screen-capture-kit"]
[dependencies]
@@ -33,12 +33,8 @@ collections.workspace = true
core-foundation.workspace = true
core-foundation-sys.workspace = true
core-graphics.workspace = true
-core-text = { workspace = true, optional = true }
-core-video.workspace = true
ctor.workspace = true
dispatch2 = { workspace = true, features = ["block2", "objc2"] }
-# WARNING: If you change this, you must also publish a new version of zed-font-kit to crates.io
-font-kit = { workspace = true, optional = true, features = ["source"] }
foreign-types.workspace = true
futures.workspace = true
gpui_apple.workspace = true
@@ -51,11 +47,11 @@ objc2.workspace = true
objc2-app-kit.workspace = true
objc2-core-graphics = { workspace = true, optional = true }
objc2-core-media = { workspace = true, optional = true }
+objc2-core-video = { workspace = true, features = ["CVHostTime"] }
objc2-foundation.workspace = true
objc2-screen-capture-kit = { workspace = true, optional = true }
objc2-user-notifications.workspace = true
parking_lot.workspace = true
-pathfinder_geometry = { workspace = true, optional = true }
raw-window-handle.workspace = true
scheduler.workspace = true
semver.workspace = true
diff --git a/crates/gpui_macos/src/display_link.rs b/crates/gpui_macos/src/display_link.rs
index 6cbb688b9e0..81b1b5eca85 100644
--- a/crates/gpui_macos/src/display_link.rs
+++ b/crates/gpui_macos/src/display_link.rs
@@ -52,7 +52,6 @@
use anyhow::Result;
use core_graphics::display::CGDirectDisplayID;
-use core_video::host_time;
use dispatch2::{
_dispatch_source_type_data_add, DispatchObject, DispatchQueue, DispatchRetained, DispatchSource,
};
@@ -136,9 +135,9 @@ unsafe extern "C" fn display_link_output_callback(
) -> i32 {
let signal_at = PlatformFrameSignal::capture(|| {
// Instant cannot be constructed from Mach ticks, so sample both clock domains.
- let current_host_time = host_time::get_current_host_time();
+ let current_host_time = objc2_core_video::CVGetCurrentHostTime();
let received_at = Instant::now();
- let host_clock_frequency = host_time::get_host_clock_frequency();
+ let host_clock_frequency = objc2_core_video::CVGetHostClockFrequency();
// SAFETY: CoreVideo owns this timestamp for the lifetime of the callback.
let current_time = unsafe { current_time.as_ref() };
frame_request_instant(
diff --git a/crates/gpui_macos/src/gpui_macos.rs b/crates/gpui_macos/src/gpui_macos.rs
index 6e2d04dc812..a48dc8f098f 100644
--- a/crates/gpui_macos/src/gpui_macos.rs
+++ b/crates/gpui_macos/src/gpui_macos.rs
@@ -23,12 +23,6 @@ pub mod metal_renderer {
pub use gpui_apple::metal_renderer::MetalHeadlessRenderer;
}
-#[cfg(feature = "font-kit")]
-mod open_type;
-
-#[cfg(feature = "font-kit")]
-mod text_system;
-
mod platform;
mod window;
mod window_appearance;
@@ -51,9 +45,6 @@ pub(crate) use keyboard::*;
pub(crate) use platform::*;
pub(crate) use window::*;
-#[cfg(feature = "font-kit")]
-pub(crate) use text_system::*;
-
pub use platform::MacPlatform;
trait BoolExt {
diff --git a/crates/gpui_macos/src/platform.rs b/crates/gpui_macos/src/platform.rs
index 62921c501f8..f0538566e6f 100644
--- a/crates/gpui_macos/src/platform.rs
+++ b/crates/gpui_macos/src/platform.rs
@@ -20,14 +20,7 @@ use cocoa::{
NSArray, NSAutoreleasePool, NSBundle, NSInteger, NSProcessInfo, NSString, NSUInteger, NSURL,
},
};
-use core_foundation::{
- base::{CFRelease, CFType, CFTypeRef, OSStatus, TCFType},
- boolean::CFBoolean,
- data::CFData,
- dictionary::{CFDictionary, CFDictionaryRef, CFMutableDictionary},
- runloop::CFRunLoopRun,
- string::{CFString, CFStringRef},
-};
+use core_foundation::{base::CFRelease, runloop::CFRunLoopRun, string::CFStringRef};
use ctor::ctor;
use dispatch2::DispatchQueue;
use futures::channel::oneshot;
@@ -39,6 +32,10 @@ use gpui::{
ThermalState, WindowAppearance, WindowKind, WindowParams, WindowingRequest,
popup::PopupNotSupportedError,
};
+use gpui_apple::{
+ keychain,
+ thermal::{self, ThermalObserver},
+};
use gpui_util::{ResultExt, new_std_command};
use itertools::Itertools;
use objc::{
@@ -158,11 +155,6 @@ unsafe fn build_classes() {
on_keyboard_layout_change as extern "C" fn(&mut Object, Sel, id),
);
- decl.add_method(
- sel!(onThermalStateChange:),
- on_thermal_state_change as extern "C" fn(&mut Object, Sel, id),
- );
-
decl.add_method(
sel!(onScreenParametersChange:),
on_screen_parameters_change as extern "C" fn(&mut Object, Sel, id),
@@ -197,7 +189,7 @@ pub(crate) struct MacPlatformState {
find_pasteboard: Pasteboard,
reopen: Option<Box<dyn FnMut()>>,
on_keyboard_layout_change: Option<Box<dyn FnMut()>>,
- on_thermal_state_change: Option<Box<dyn FnMut()>>,
+ thermal_observer: Option<ThermalObserver>,
on_displays_changed: Option<Box<dyn FnMut()>>,
on_system_sleep: Option<Box<dyn FnMut()>>,
on_system_wake: Option<Box<dyn FnMut()>>,
@@ -239,7 +231,7 @@ impl MacPlatform {
let dispatcher = Arc::new(AppleDispatcher::new());
#[cfg(feature = "font-kit")]
- let text_system = Arc::new(crate::MacTextSystem::new());
+ let text_system = Arc::new(gpui_apple::AppleTextSystem::new());
#[cfg(not(feature = "font-kit"))]
let text_system = {
@@ -274,7 +266,7 @@ impl MacPlatform {
finish_launching: None,
dock_menu: None,
on_keyboard_layout_change: None,
- on_thermal_state_change: None,
+ thermal_observer: None,
on_displays_changed: None,
on_system_sleep: None,
on_system_wake: None,
@@ -1093,7 +1085,8 @@ impl Platform for MacPlatform {
}
fn on_thermal_state_change(&self, callback: Box<dyn FnMut()>) {
- self.0.lock().on_thermal_state_change = Some(callback);
+ let observer = ThermalObserver::new(&self.foreground_executor(), callback);
+ self.0.lock().thermal_observer = Some(observer);
}
fn on_system_sleep(&self, callback: Box<dyn FnMut()>) {
@@ -1107,17 +1100,7 @@ impl Platform for MacPlatform {
}
fn thermal_state(&self) -> ThermalState {
- unsafe {
- let process_info: id = msg_send![class!(NSProcessInfo), processInfo];
- let state: NSInteger = msg_send![process_info, thermalState];
- match state {
- 0 => ThermalState::Nominal,
- 1 => ThermalState::Fair,
- 2 => ThermalState::Serious,
- 3 => ThermalState::Critical,
- _ => ThermalState::Nominal,
- }
- }
+ thermal::thermal_state()
}
fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>> {
@@ -1270,105 +1253,20 @@ impl Platform for MacPlatform {
let url = url.to_string();
let username = username.to_string();
let password = password.to_vec();
- self.background_executor().spawn(async move {
- unsafe {
- use security::*;
-
- let url = CFString::from(url.as_str());
- let username = CFString::from(username.as_str());
- let password = CFData::from_buffer(&password);
-
- // First, check if there are already credentials for the given server. If so, then
- // update the username and password.
- let mut verb = "updating";
- let mut query_attrs = CFMutableDictionary::with_capacity(2);
- query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
- query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
-
- let mut attrs = CFMutableDictionary::with_capacity(4);
- attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
- attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
- attrs.set(kSecAttrAccount as *const _, username.as_CFTypeRef());
- attrs.set(kSecValueData as *const _, password.as_CFTypeRef());
-
- let mut status = SecItemUpdate(
- query_attrs.as_concrete_TypeRef(),
- attrs.as_concrete_TypeRef(),
- );
-
- // If there were no existing credentials for the given server, then create them.
- if status == errSecItemNotFound {
- verb = "creating";
- status = SecItemAdd(attrs.as_concrete_TypeRef(), ptr::null_mut());
- }
- anyhow::ensure!(status == errSecSuccess, "{verb} password failed: {status}");
- }
- Ok(())
- })
+ self.background_executor()
+ .spawn(async move { Ok(keychain::write_credentials(&url, &username, &password)?) })
}
fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
let url = url.to_string();
- self.background_executor().spawn(async move {
- let url = CFString::from(url.as_str());
- let cf_true = CFBoolean::true_value().as_CFTypeRef();
-
- unsafe {
- use security::*;
-
- // Find any credentials for the given server URL.
- let mut attrs = CFMutableDictionary::with_capacity(5);
- attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
- attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
- attrs.set(kSecReturnAttributes as *const _, cf_true);
- attrs.set(kSecReturnData as *const _, cf_true);
-
- let mut result = CFTypeRef::from(ptr::null());
- let status = SecItemCopyMatching(attrs.as_concrete_TypeRef(), &mut result);
- match status {
- security::errSecSuccess => {}
- security::errSecItemNotFound | security::errSecUserCanceled => return Ok(None),
- _ => anyhow::bail!("reading password failed: {status}"),
- }
-
- let result = CFType::wrap_under_create_rule(result)
- .downcast::<CFDictionary>()
- .context("keychain item was not a dictionary")?;
- let username = result
- .find(kSecAttrAccount as *const _)
- .context("account was missing from keychain item")?;
- let username = CFType::wrap_under_get_rule(*username)
- .downcast::<CFString>()
- .context("account was not a string")?;
- let password = result
- .find(kSecValueData as *const _)
- .context("password was missing from keychain item")?;
- let password = CFType::wrap_under_get_rule(*password)
- .downcast::<CFData>()
- .context("password was not a string")?;
-
- Ok(Some((username.to_string(), password.bytes().to_vec())))
- }
- })
+ self.background_executor()
+ .spawn(async move { Ok(keychain::read_credentials(&url)?) })
}
fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
let url = url.to_string();
-
- self.background_executor().spawn(async move {
- unsafe {
- use security::*;
-
- let url = CFString::from(url.as_str());
- let mut query_attrs = CFMutableDictionary::with_capacity(2);
- query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
- query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
-
- let status = SecItemDelete(query_attrs.as_concrete_TypeRef());
- anyhow::ensure!(status == errSecSuccess, "delete password failed: {status}");
- }
- Ok(())
- })
+ self.background_executor()
+ .spawn(async move { Ok(keychain::delete_credentials(&url)?) })
}
}
@@ -1427,14 +1325,6 @@ extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
object: nil
];
- let thermal_name = ns_string("NSProcessInfoThermalStateDidChangeNotification");
- let process_info: id = msg_send![class!(NSProcessInfo), processInfo];
- let _: () = msg_send![notification_center, addObserver: this as id
- selector: sel!(onThermalStateChange:)
- name: thermal_name
- object: process_info
- ];
-
// SAFETY: `this` is a live Objective-C object; only the pointer's type changes.
let observer = &*(this as *mut Object as *const AnyObject);
let platform = get_mac_platform(this);
@@ -1514,35 +1404,12 @@ extern "C" fn on_keyboard_layout_change(this: &mut Object, _: Sel, _: id) {
}
}
-extern "C" fn on_thermal_state_change(this: &mut Object, _: Sel, _: id) {
+extern "C" fn on_screen_parameters_change(this: &mut Object, _: Sel, _: id) {
// Defer to the next run loop iteration to avoid re-entrant borrows of the App RefCell,
// as NSNotificationCenter delivers this notification synchronously and it may fire while
// the App is already borrowed (same pattern as quit() above).
let platform = unsafe { get_mac_platform(this) };
let platform_ptr = platform as *const MacPlatform as *mut c_void;
- unsafe {
- DispatchQueue::main().exec_async_f(platform_ptr, on_thermal_state_change);
- }
-
- extern "C" fn on_thermal_state_change(context: *mut c_void) {
- let platform = unsafe { &*(context as *const MacPlatform) };
- let mut lock = platform.0.lock();
- if let Some(mut callback) = lock.on_thermal_state_change.take() {
- drop(lock);
- callback();
- platform
- .0
- .lock()
- .on_thermal_state_change
- .get_or_insert(callback);
- }
- }
-}
-
-extern "C" fn on_screen_parameters_change(this: &mut Object, _: Sel, _: id) {
- // Deferred for the same reason as `on_thermal_state_change`.
- let platform = unsafe { get_mac_platform(this) };
- let platform_ptr = platform as *const MacPlatform as *mut c_void;
unsafe {
DispatchQueue::main().exec_async_f(platform_ptr, on_screen_parameters_change);
}
@@ -1733,28 +1600,3 @@ unsafe extern "C" {
pub(super) static kTISPropertyInputSourceType: CFStringRef;
pub(super) static kTISTypeKeyboardInputMode: CFStringRef;
}
-
-mod security {
- #![allow(non_upper_case_globals)]
- use super::*;
-
- #[link(name = "Security", kind = "framework")]
- unsafe extern "C" {
- pub static kSecClass: CFStringRef;
- pub static kSecClassInternetPassword: CFStringRef;
- pub static kSecAttrServer: CFStringRef;
- pub static kSecAttrAccount: CFStringRef;
- pub static kSecValueData: CFStringRef;
- pub static kSecReturnAttributes: CFStringRef;
- pub static kSecReturnData: CFStringRef;
-
- pub fn SecItemAdd(attributes: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
- pub fn SecItemUpdate(query: CFDictionaryRef, attributes: CFDictionaryRef) -> OSStatus;
- pub fn SecItemDelete(query: CFDictionaryRef) -> OSStatus;
- pub fn SecItemCopyMatching(query: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
- }
-
- pub const errSecSuccess: OSStatus = 0;
- pub const errSecUserCanceled: OSStatus = -128;
- pub const errSecItemNotFound: OSStatus = -25300;
-}
diff --git a/crates/livekit_client/Cargo.toml b/crates/livekit_client/Cargo.toml
index 5d3a86b8cbf..022ab3484a4 100644
--- a/crates/livekit_client/Cargo.toml
+++ b/crates/livekit_client/Cargo.toml
@@ -60,9 +60,8 @@ webrtc-sys.workspace = true
scap.workspace = true
[target.'cfg(target_os = "macos")'.dependencies]
-core-foundation.workspace = true
-core-video.workspace = true
-objc2-core-foundation.workspace = true
+objc2-core-foundation = { workspace = true, features = ["CFDictionary", "CFNumber"] }
+objc2-core-video = { workspace = true, features = ["CVBase", "CVPixelBuffer", "CVPixelBufferIOSurface", "CVPixelBufferPool", "CVReturn"] }
coreaudio-rs = { workspace = true, features = ["core_audio"] }
[dev-dependencies]
diff --git a/crates/livekit_client/src/livekit_client/playback.rs b/crates/livekit_client/src/livekit_client/playback.rs
index 0dac4562253..4eaced66795 100644
--- a/crates/livekit_client/src/livekit_client/playback.rs
+++ b/crates/livekit_client/src/livekit_client/playback.rs
@@ -604,78 +604,97 @@ pub fn play_remote_video_track(
fn create_buffer_pool(
width: u32,
height: u32,
-) -> Result<core_video::pixel_buffer_pool::CVPixelBufferPool> {
- use core_foundation::{base::TCFType, number::CFNumber, string::CFString};
- use core_video::pixel_buffer;
- use core_video::{
- pixel_buffer::kCVPixelFormatType_420YpCbCr8BiPlanarFullRange,
- pixel_buffer_io_surface::kCVPixelBufferIOSurfaceCoreAnimationCompatibilityKey,
- pixel_buffer_pool::{self},
+) -> Result<objc2_core_foundation::CFRetained<objc2_core_video::CVPixelBufferPool>> {
+ use objc2_core_foundation::{CFDictionary, CFNumber, CFRetained};
+ use objc2_core_video::{
+ CVPixelBufferPool, kCVPixelBufferHeightKey,
+ kCVPixelBufferIOSurfaceCoreAnimationCompatibilityKey, kCVPixelBufferPixelFormatTypeKey,
+ kCVPixelBufferWidthKey, kCVPixelFormatType_420YpCbCr8BiPlanarFullRange, kCVReturnSuccess,
};
-
- let width_key: CFString =
- unsafe { CFString::wrap_under_get_rule(pixel_buffer::kCVPixelBufferWidthKey) };
- let height_key: CFString =
- unsafe { CFString::wrap_under_get_rule(pixel_buffer::kCVPixelBufferHeightKey) };
- let animation_key: CFString = unsafe {
- CFString::wrap_under_get_rule(kCVPixelBufferIOSurfaceCoreAnimationCompatibilityKey)
+ use std::ptr::{self, NonNull};
+
+ let buffer_attributes = CFDictionary::from_slices(
+ &unsafe {
+ [
+ kCVPixelBufferWidthKey,
+ kCVPixelBufferHeightKey,
+ kCVPixelBufferIOSurfaceCoreAnimationCompatibilityKey,
+ kCVPixelBufferPixelFormatTypeKey,
+ ]
+ },
+ &[
+ &*CFNumber::new_i32(width as i32),
+ &*CFNumber::new_i32(height as i32),
+ &*CFNumber::new_i32(1),
+ &*CFNumber::new_i64(kCVPixelFormatType_420YpCbCr8BiPlanarFullRange as i64),
+ ],
+ );
+ let mut pool = ptr::null_mut();
+ let status = unsafe {
+ CVPixelBufferPool::create(
+ None,
+ None,
+ Some(buffer_attributes.as_opaque()),
+ NonNull::from(&mut pool),
+ )
};
- let format_key: CFString =
- unsafe { CFString::wrap_under_get_rule(pixel_buffer::kCVPixelBufferPixelFormatTypeKey) };
-
- let yes: CFNumber = 1.into();
- let width: CFNumber = (width as i32).into();
- let height: CFNumber = (height as i32).into();
- let format: CFNumber = (kCVPixelFormatType_420YpCbCr8BiPlanarFullRange as i64).into();
-
- let buffer_attributes = core_foundation::dictionary::CFDictionary::from_CFType_pairs(&[
- (width_key, width.into_CFType()),
- (height_key, height.into_CFType()),
- (animation_key, yes.into_CFType()),
- (format_key, format.into_CFType()),
- ]);
-
- pixel_buffer_pool::CVPixelBufferPool::new(None, Some(&buffer_attributes)).map_err(|cv_return| {
- anyhow::anyhow!("failed to create pixel buffer pool: CVReturn({cv_return})",)
- })
+ anyhow::ensure!(
+ status == kCVReturnSuccess,
+ "failed to create pixel buffer pool: CVReturn({status})"
+ );
+ let pool = NonNull::new(pool).context("CoreVideo returned a null pixel buffer pool")?;
+ Ok(unsafe { CFRetained::from_raw(pool) })
}
#[cfg(target_os = "macos")]
-pub type RemoteVideoFrame = core_video::pixel_buffer::CVPixelBuffer;
+pub type RemoteVideoFrame = objc2_core_foundation::CFRetained<objc2_core_video::CVPixelBuffer>;
#[cfg(target_os = "macos")]
fn video_frame_buffer_from_webrtc(
- pool: core_video::pixel_buffer_pool::CVPixelBufferPool,
+ pool: objc2_core_foundation::CFRetained<objc2_core_video::CVPixelBufferPool>,
buffer: Box<dyn VideoBuffer>,
) -> Option<RemoteVideoFrame> {
- use core_foundation::base::TCFType;
- use core_video::{pixel_buffer::CVPixelBuffer, r#return::kCVReturnSuccess};
use livekit::webrtc::native::yuv_helper::i420_to_nv12;
+ use objc2_core_foundation::CFRetained;
+ use objc2_core_video::{
+ CVPixelBufferGetBaseAddressOfPlane, CVPixelBufferGetBytesPerRowOfPlane,
+ CVPixelBufferGetHeight, CVPixelBufferGetHeightOfPlane, CVPixelBufferGetWidth,
+ CVPixelBufferLockBaseAddress, CVPixelBufferLockFlags, CVPixelBufferPool,
+ CVPixelBufferUnlockBaseAddress, kCVReturnSuccess,
+ };
+ use std::ptr::{self, NonNull};
if let Some(native) = buffer.as_native() {
- let pixel_buffer = native.get_cv_pixel_buffer();
- if pixel_buffer.is_null() {
- return None;
- }
- return unsafe { Some(CVPixelBuffer::wrap_under_get_rule(pixel_buffer as _)) };
+ let pixel_buffer = NonNull::new(native.get_cv_pixel_buffer().cast())?;
+ return unsafe { Some(CFRetained::retain(pixel_buffer)) };
}
let i420_buffer = buffer.as_i420()?;
- let pixel_buffer = pool.create_pixel_buffer().log_err()?;
+ let mut pixel_buffer = ptr::null_mut();
+ let status = unsafe {
+ CVPixelBufferPool::create_pixel_buffer(None, &pool, NonNull::from(&mut pixel_buffer))
+ };
+ if status != kCVReturnSuccess {
+ log::error!("failed to create pixel buffer: CVReturn({status})");
+ return None;
+ }
+ let pixel_buffer = unsafe { CFRetained::from_raw(NonNull::new(pixel_buffer)?) };
let image_buffer = unsafe {
- if pixel_buffer.lock_base_address(0) != kCVReturnSuccess {
+ if CVPixelBufferLockBaseAddress(&pixel_buffer, CVPixelBufferLockFlags::empty())
+ != kCVReturnSuccess
+ {
return None;
}
- let dst_y = pixel_buffer.get_base_address_of_plane(0);
- let dst_y_stride = pixel_buffer.get_bytes_per_row_of_plane(0);
- let dst_y_len = pixel_buffer.get_height_of_plane(0) * dst_y_stride;
- let dst_uv = pixel_buffer.get_base_address_of_plane(1);
- let dst_uv_stride = pixel_buffer.get_bytes_per_row_of_plane(1);
- let dst_uv_len = pixel_buffer.get_height_of_plane(1) * dst_uv_stride;
- let width = pixel_buffer.get_width();
- let height = pixel_buffer.get_height();
+ let dst_y = CVPixelBufferGetBaseAddressOfPlane(&pixel_buffer, 0);
+ let dst_y_stride = CVPixelBufferGetBytesPerRowOfPlane(&pixel_buffer, 0);
+ let dst_y_len = CVPixelBufferGetHeightOfPlane(&pixel_buffer, 0) * dst_y_stride;
+ let dst_uv = CVPixelBufferGetBaseAddressOfPlane(&pixel_buffer, 1);
+ let dst_uv_stride = CVPixelBufferGetBytesPerRowOfPlane(&pixel_buffer, 1);
+ let dst_uv_len = CVPixelBufferGetHeightOfPlane(&pixel_buffer, 1) * dst_uv_stride;
+ let width = CVPixelBufferGetWidth(&pixel_buffer);
+ let height = CVPixelBufferGetHeight(&pixel_buffer);
let dst_y_buffer = std::slice::from_raw_parts_mut(dst_y as *mut u8, dst_y_len);
let dst_uv_buffer = std::slice::from_raw_parts_mut(dst_uv as *mut u8, dst_uv_len);
@@ -696,7 +715,9 @@ fn video_frame_buffer_from_webrtc(
height as i32,
);
- if pixel_buffer.unlock_base_address(0) != kCVReturnSuccess {
+ if CVPixelBufferUnlockBaseAddress(&pixel_buffer, CVPixelBufferLockFlags::empty())
+ != kCVReturnSuccess
+ {
return None;
}