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 dispatcher and Metal renderer with iOS (#64990)

Anthony Eid40180d9c40e2
diff --git a/Cargo.lock b/Cargo.lock
index da2a5543fe0..51656b167f5 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -7605,20 +7605,26 @@ name = "gpui_apple"
version = "0.1.0"
dependencies = [
"anyhow",
+ "async-task",
"block2 0.6.2",
"cbindgen",
- "cocoa 0.26.0",
"core-foundation 0.10.0",
+ "core-graphics 0.24.0",
"core-video",
"derive_more",
+ "dispatch2",
"etagere",
"foreign-types 0.5.0",
"gpui",
+ "gpui_util",
"image",
+ "libc",
"log",
+ "mach2 0.5.0",
"metal",
- "objc",
"objc2 0.6.3",
+ "objc2-foundation 0.3.2",
+ "objc2-quartz-core 0.3.2",
"parking_lot",
]
@@ -7673,7 +7679,6 @@ dependencies = [
"accesskit",
"accesskit_macos",
"anyhow",
- "async-task",
"block2 0.6.2",
"cocoa 0.26.0",
"collections",
@@ -7690,9 +7695,7 @@ dependencies = [
"gpui_util",
"image",
"itertools 0.14.0",
- "libc",
"log",
- "mach2 0.5.0",
"objc",
"objc2 0.6.3",
"objc2-app-kit 0.3.2",
diff --git a/Cargo.toml b/Cargo.toml
index c52733570bc..9388515ba58 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -624,6 +624,7 @@ derive_more = { version = "2.1.1", features = [
dialoguer = { version = "0.12", default-features = false }
diffy = "0.4.2"
dirs = "6.0"
+dispatch2 = "0.3.1"
documented = "0.10"
dotenvy = "0.15.0"
dunce = "1.0"
@@ -757,6 +758,7 @@ objc2-foundation = { version = "=0.3.2", default-features = false, features = [
"objc2-core-foundation",
"std",
] }
+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",
"dispatch2",
diff --git a/crates/gpui/Cargo.toml b/crates/gpui/Cargo.toml
index f57ed006930..c345f09b14a 100644
--- a/crates/gpui/Cargo.toml
+++ b/crates/gpui/Cargo.toml
@@ -118,8 +118,10 @@ getrandom = { version = "0.3.4", features = ["wasm_js"] }
uuid = { workspace = true, features = ["js"] }
-[target.'cfg(target_os = "macos")'.dependencies]
+[target.'cfg(any(target_os = "macos", target_os = "ios"))'.dependencies]
core-video.workspace = true
+
+[target.'cfg(target_os = "macos")'.dependencies]
objc2-core-foundation.workspace = true
objc2-core-video.workspace = true
# WARNING: If you change this, you must also publish a new version of zed-font-kit to crates.io
diff --git a/crates/gpui/src/elements/surface.rs b/crates/gpui/src/elements/surface.rs
index ac1c247b47e..fb07280927b 100644
--- a/crates/gpui/src/elements/surface.rs
+++ b/crates/gpui/src/elements/surface.rs
@@ -2,19 +2,19 @@ use crate::{
App, Bounds, Element, ElementId, GlobalElementId, InspectorElementId, IntoElement, LayoutId,
ObjectFit, Pixels, Style, StyleRefinement, Styled, Window,
};
-#[cfg(target_os = "macos")]
+#[cfg(any(target_os = "macos", target_os = "ios"))]
use core_video::pixel_buffer::CVPixelBuffer;
use refineable::Refineable;
/// A source of a surface's content.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SurfaceSource {
- /// A macOS image buffer from CoreVideo
- #[cfg(target_os = "macos")]
+ /// A CoreVideo image buffer
+ #[cfg(any(target_os = "macos", target_os = "ios"))]
Surface(CVPixelBuffer),
}
-#[cfg(target_os = "macos")]
+#[cfg(any(target_os = "macos", target_os = "ios"))]
impl From<CVPixelBuffer> for SurfaceSource {
fn from(value: CVPixelBuffer) -> Self {
SurfaceSource::Surface(value)
@@ -29,7 +29,7 @@ pub struct Surface {
}
/// Create a new surface element.
-#[cfg(target_os = "macos")]
+#[cfg(any(target_os = "macos", target_os = "ios"))]
pub fn surface(source: impl Into<SurfaceSource>) -> Surface {
Surface {
source: source.into(),
@@ -86,14 +86,22 @@ impl Element for Surface {
&mut self,
_global_id: Option<&GlobalElementId>,
_inspector_id: Option<&InspectorElementId>,
- #[cfg_attr(not(target_os = "macos"), allow(unused_variables))] bounds: Bounds<Pixels>,
+ #[cfg_attr(
+ not(any(target_os = "macos", target_os = "ios")),
+ allow(unused_variables)
+ )]
+ bounds: Bounds<Pixels>,
_: &mut Self::RequestLayoutState,
_: &mut Self::PrepaintState,
- #[cfg_attr(not(target_os = "macos"), allow(unused_variables))] window: &mut Window,
+ #[cfg_attr(
+ not(any(target_os = "macos", target_os = "ios")),
+ allow(unused_variables)
+ )]
+ window: &mut Window,
_: &mut App,
) {
match &self.source {
- #[cfg(target_os = "macos")]
+ #[cfg(any(target_os = "macos", target_os = "ios"))]
SurfaceSource::Surface(surface) => {
let size = crate::size(surface.get_width().into(), surface.get_height().into());
let new_bounds = self.object_fit.get_bounds(bounds, size);
diff --git a/crates/gpui/src/scene.rs b/crates/gpui/src/scene.rs
index ea0f5d7e31a..160587a4ad9 100644
--- a/crates/gpui/src/scene.rs
+++ b/crates/gpui/src/scene.rs
@@ -769,7 +769,7 @@ pub struct PaintSurface {
pub order: DrawOrder,
pub bounds: Bounds<ScaledPixels>,
pub content_mask: ContentMask<ScaledPixels>,
- #[cfg(target_os = "macos")]
+ #[cfg(any(target_os = "macos", target_os = "ios"))]
pub image_buffer: core_video::pixel_buffer::CVPixelBuffer,
}
diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs
index 52d729f75ad..d936678ab7c 100644
--- a/crates/gpui/src/window.rs
+++ b/crates/gpui/src/window.rs
@@ -29,7 +29,7 @@ use crate::gestures::{GestureTuning, RecognizedTouchGesture, TouchGestureRecogni
use crate::interactive::TouchEvent;
use anyhow::{Context as _, Result, anyhow};
use collections::{FxHashMap, FxHashSet};
-#[cfg(target_os = "macos")]
+#[cfg(any(target_os = "macos", target_os = "ios"))]
use core_video::pixel_buffer::CVPixelBuffer;
use derive_more::{Deref, DerefMut};
use futures::channel::oneshot;
@@ -4973,7 +4973,7 @@ impl Window {
/// Paint a surface into the scene for the next frame at the current z-index.
///
/// This method should only be called as part of the paint phase of element drawing.
- #[cfg(target_os = "macos")]
+ #[cfg(any(target_os = "macos", target_os = "ios"))]
pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVPixelBuffer) {
use crate::PaintSurface;
diff --git a/crates/gpui_apple/Cargo.toml b/crates/gpui_apple/Cargo.toml
index 33ec05f7b4b..9e2a11438b0 100644
--- a/crates/gpui_apple/Cargo.toml
+++ b/crates/gpui_apple/Cargo.toml
@@ -21,24 +21,30 @@ runtime_shaders = []
[dependencies]
gpui.workspace = true
-[target.'cfg(target_os = "macos")'.dependencies]
+[target.'cfg(any(target_os = "macos", target_os = "ios"))'.dependencies]
anyhow.workspace = true
+async-task.workspace = true
block2.workspace = true
-cocoa.workspace = true
core-foundation.workspace = true
+core-graphics.workspace = true
core-video.workspace = true
derive_more.workspace = true
+dispatch2.workspace = true
etagere.workspace = true
foreign-types.workspace = true
+gpui_util.workspace = true
image.workspace = true
+libc.workspace = true
log.workspace = true
+mach2.workspace = true
metal.workspace = true
-objc.workspace = true
objc2.workspace = true
+objc2-foundation = { workspace = true, features = ["NSThread"] }
+objc2-quartz-core.workspace = true
parking_lot.workspace = true
-[target.'cfg(target_os = "macos")'.build-dependencies]
+[target.'cfg(any(target_os = "macos", target_os = "ios"))'.build-dependencies]
cbindgen.workspace = true
-[target.'cfg(target_os = "macos")'.dev-dependencies]
+[target.'cfg(any(target_os = "macos", target_os = "ios"))'.dev-dependencies]
gpui = { workspace = true, features = ["test-support"] }
diff --git a/crates/gpui_apple/build.rs b/crates/gpui_apple/build.rs
index 993ba061eb8..530959482d1 100644
--- a/crates/gpui_apple/build.rs
+++ b/crates/gpui_apple/build.rs
@@ -1,12 +1,12 @@
#![allow(clippy::disallowed_methods, reason = "build scripts are exempt")]
fn main() {
- #[cfg(target_os = "macos")]
- macos_build::run();
+ #[cfg(any(target_os = "macos", target_os = "ios"))]
+ apple_build::run();
}
-#[cfg(target_os = "macos")]
-mod macos_build {
+#[cfg(any(target_os = "macos", target_os = "ios"))]
+mod apple_build {
use std::{
env,
path::{Path, PathBuf},
@@ -125,6 +125,26 @@ mod macos_build {
#[cfg(not(feature = "runtime_shaders"))]
fn compile_metal_shaders(header_path: &Path) {
use std::process::{self, Command};
+
+ // Build scripts run on the host, so the target platform must come from
+ // Cargo's environment rather than `cfg!`. The target environment, not the
+ // target name, identifies simulators: `x86_64-apple-ios` has no `-sim` suffix.
+ let target_os = env::var("CARGO_CFG_TARGET_OS")
+ .expect("Cargo sets CARGO_CFG_TARGET_OS for build scripts");
+ let target_env = env::var("CARGO_CFG_TARGET_ENV")
+ .expect("Cargo sets CARGO_CFG_TARGET_ENV for build scripts");
+ let (sdk, minimum_version_argument) = match (target_os.as_str(), target_env.as_str()) {
+ ("macos", _) => ("macosx", "-mmacosx-version-min=10.15.7"),
+ ("ios", "sim") => ("iphonesimulator", "-mios-simulator-version-min=15.0"),
+ ("ios", "") => ("iphoneos", "-mios-version-min=15.0"),
+ _ => {
+ println!(
+ "cargo::error=unsupported Metal shader target: target_os={target_os}, target_env={target_env}"
+ );
+ process::exit(1);
+ }
+ };
+
let shader_path = "./src/shaders.metal";
let air_output_path = PathBuf::from(env::var("OUT_DIR").unwrap()).join("shaders.air");
let metallib_output_path =
@@ -141,10 +161,10 @@ mod macos_build {
let output = Command::new("xcrun")
.args([
"-sdk",
- "macosx",
+ sdk,
"metal",
"-gline-tables-only",
- "-mmacosx-version-min=10.15.7",
+ minimum_version_argument,
"-MO",
"-c",
])
@@ -163,7 +183,7 @@ mod macos_build {
}
let output = Command::new("xcrun")
- .args(["-sdk", "macosx", "metallib"])
+ .args(["-sdk", sdk, "metallib"])
.arg(&air_output_path)
.arg("-o")
.arg(metallib_output_path)
diff --git a/crates/gpui_macos/src/dispatcher.rs b/crates/gpui_apple/src/dispatcher.rs
similarity index 92%
rename from crates/gpui_macos/src/dispatcher.rs
rename to crates/gpui_apple/src/dispatcher.rs
index a50288cd647..8acecc6dc97 100644
--- a/crates/gpui_macos/src/dispatcher.rs
+++ b/crates/gpui_apple/src/dispatcher.rs
@@ -13,27 +13,21 @@ use mach2::{
};
use async_task::Runnable;
-use objc::{
- class, msg_send,
- runtime::{BOOL, YES},
- sel, sel_impl,
-};
use objc2::{rc::Retained, runtime::ProtocolObject};
-use objc2_foundation::{NSActivityOptions, NSObjectProtocol, NSProcessInfo, NSString};
+use objc2_foundation::{NSActivityOptions, NSObjectProtocol, NSProcessInfo, NSString, NSThread};
use std::{ffi::c_void, ptr::NonNull, time::Duration};
-pub(crate) struct MacDispatcher;
+pub struct AppleDispatcher;
-impl MacDispatcher {
+impl AppleDispatcher {
pub fn new() -> Self {
Self
}
}
-impl PlatformDispatcher for MacDispatcher {
+impl PlatformDispatcher for AppleDispatcher {
fn is_main_thread(&self) -> bool {
- let is_main_thread: BOOL = unsafe { msg_send![class!(NSThread), isMainThread] };
- is_main_thread == YES
+ NSThread::isMainThread_class()
}
fn dispatch(&self, runnable: RunnableVariant, priority: Priority) {
@@ -80,22 +74,22 @@ impl PlatformDispatcher for MacDispatcher {
}
fn prevent_app_nap(&self, reason: &str) -> ActivityGuard {
- MacActivity::begin(
+ AppleActivity::begin(
reason,
NSActivityOptions::UserInitiatedAllowingIdleSystemSleep,
)
}
}
-pub(crate) struct MacActivity {
+pub struct AppleActivity {
activity: Retained<ProtocolObject<dyn NSObjectProtocol>>,
}
// The activity token returned by NSProcessInfo is thread-safe
-unsafe impl Send for MacActivity {}
+unsafe impl Send for AppleActivity {}
-impl MacActivity {
- pub(crate) fn begin(reason: &str, options: NSActivityOptions) -> ActivityGuard {
+impl AppleActivity {
+ pub fn begin(reason: &str, options: NSActivityOptions) -> ActivityGuard {
let activity = Self {
activity: NSProcessInfo::processInfo()
.beginActivityWithOptions_reason(options, &NSString::from_str(reason)),
@@ -104,7 +98,7 @@ impl MacActivity {
}
}
-impl Drop for MacActivity {
+impl Drop for AppleActivity {
fn drop(&mut self) {
unsafe { NSProcessInfo::processInfo().endActivity(&self.activity) };
}
diff --git a/crates/gpui_apple/src/gpui_apple.rs b/crates/gpui_apple/src/gpui_apple.rs
index 208d297ea10..63fb1b14497 100644
--- a/crates/gpui_apple/src/gpui_apple.rs
+++ b/crates/gpui_apple/src/gpui_apple.rs
@@ -1,8 +1,12 @@
-#![cfg(target_os = "macos")]
-//! Shared Apple platform support for GPUI.
+#![cfg(any(target_os = "macos", target_os = "ios"))]
+//! Shared Apple rendering and task dispatch for GPUI.
//!
-//! This crate contains the Metal renderer and GPU resource management shared
-//! by GPUI's Apple platform backends.
+//! 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.
+mod dispatcher;
mod metal_atlas;
pub mod metal_renderer;
+
+pub use dispatcher::{AppleActivity, AppleDispatcher};
diff --git a/crates/gpui_apple/src/metal_atlas.rs b/crates/gpui_apple/src/metal_atlas.rs
index 0e8b800ac4c..a635bc463a8 100644
--- a/crates/gpui_apple/src/metal_atlas.rs
+++ b/crates/gpui_apple/src/metal_atlas.rs
@@ -12,10 +12,10 @@ use std::borrow::Cow;
pub struct MetalAtlas(Mutex<AtlasState<MetalAtlasTextures>>);
impl MetalAtlas {
- pub(crate) fn new(device: Device, is_apple_gpu: bool) -> Self {
+ pub(crate) fn new(device: Device, supports_shared_storage: bool) -> Self {
MetalAtlas(Mutex::new(AtlasState::new(MetalAtlasTextures {
device: AssertSend(device),
- is_apple_gpu,
+ supports_shared_storage,
monochrome_textures: Default::default(),
polychrome_textures: Default::default(),
})))
@@ -32,7 +32,7 @@ impl MetalAtlas {
struct MetalAtlasTextures {
device: AssertSend<Device>,
- is_apple_gpu: bool,
+ supports_shared_storage: bool,
monochrome_textures: AtlasTextureList<MetalAtlasTexture>,
polychrome_textures: AtlasTextureList<MetalAtlasTexture>,
}
@@ -156,7 +156,7 @@ impl MetalAtlasTextures {
texture_descriptor.set_usage(usage);
// Shared memory mode can be used only on Apple GPU families
// https://developer.apple.com/documentation/metal/mtlresourceoptions/storagemodeshared
- texture_descriptor.set_storage_mode(if self.is_apple_gpu {
+ texture_descriptor.set_storage_mode(if self.supports_shared_storage {
metal::MTLStorageMode::Shared
} else {
metal::MTLStorageMode::Managed
diff --git a/crates/gpui_apple/src/metal_renderer.rs b/crates/gpui_apple/src/metal_renderer.rs
index eddb3c1939f..df6b17a9b0a 100644
--- a/crates/gpui_apple/src/metal_renderer.rs
+++ b/crates/gpui_apple/src/metal_renderer.rs
@@ -1,11 +1,7 @@
use crate::metal_atlas::MetalAtlas;
use anyhow::{Context as _, Result};
use block2::RcBlock;
-use cocoa::{
- base::{NO, YES},
- foundation::{NSSize, NSUInteger},
- quartzcore::AutoresizingMask,
-};
+use core_graphics::geometry::CGSize;
use gpui::{
AtlasTextureId, Background, Bounds, ContentMask, DevicePixels, PaintSurface, Path, Point,
PrimitiveBatch, ScaledPixels, Scene, Size, point, size,
@@ -22,8 +18,8 @@ use core_video::{
use foreign_types::{ForeignType, ForeignTypeRef};
use metal::{
CAMetalLayer, CommandQueue, MTLGPUFamily, MTLPixelFormat, MTLResourceOptions, NSRange,
+ NSUInteger,
};
-use objc::{self, msg_send, sel, sel_impl};
use parking_lot::Mutex;
use std::{cell::Cell, ffi::c_void, mem, mem::MaybeUninit, ops::Range, ptr, slice, sync::Arc};
@@ -153,9 +149,32 @@ impl MetalRenderer {
/// Creates a new MetalRenderer with a CAMetalLayer for window-based rendering.
pub fn new(instance_buffer_pool: Arc<Mutex<InstanceBufferPool>>, transparent: bool) -> Self {
let device = Self::create_device();
-
let layer = metal::MetalLayer::new();
- layer.set_device(&device);
+ Self::configure_layer(&layer, &device, transparent);
+ Self::new_internal(device, Some(layer), !transparent, instance_buffer_pool)
+ }
+
+ /// Creates a renderer for a CAMetalLayer owned by a platform view, such as
+ /// the backing layer UIKit creates for a view whose `layerClass` is
+ /// `CAMetalLayer`. The renderer retains the layer.
+ pub fn from_layer(
+ instance_buffer_pool: Arc<Mutex<InstanceBufferPool>>,
+ layer: &objc2_quartz_core::CAMetalLayer,
+ transparent: bool,
+ ) -> Self {
+ let device = Self::create_device();
+ // Both types bind the same Objective-C class, so this only changes which
+ // Rust wrapper views the live layer. `to_owned` retains it.
+ let layer = unsafe {
+ metal::MetalLayerRef::from_ptr(ptr::from_ref(layer).cast_mut().cast::<CAMetalLayer>())
+ }
+ .to_owned();
+ Self::configure_layer(&layer, &device, transparent);
+ Self::new_internal(device, Some(layer), !transparent, instance_buffer_pool)
+ }
+
+ fn configure_layer(layer: &metal::MetalLayerRef, device: &metal::DeviceRef, transparent: bool) {
+ layer.set_device(device);
layer.set_pixel_format(MTLPixelFormat::BGRA8Unorm);
// Support direct-to-display rendering if the window is not transparent
// https://developer.apple.com/documentation/metal/managing-your-game-window-for-metal-in-macos
@@ -164,17 +183,18 @@ impl MetalRenderer {
// Allow texture reading for visual tests (captures screenshots without ScreenCaptureKit)
#[cfg(any(test, feature = "test-support"))]
layer.set_framebuffer_only(false);
- unsafe {
- let _: () = msg_send![&*layer, setAllowsNextDrawableTimeout: NO];
- let _: () = msg_send![&*layer, setNeedsDisplayOnBoundsChange: YES];
- let _: () = msg_send![
- &*layer,
- setAutoresizingMask: AutoresizingMask::WIDTH_SIZABLE
- | AutoresizingMask::HEIGHT_SIZABLE
- ];
- }
-
- Self::new_internal(device, Some(layer), !transparent, instance_buffer_pool)
+ // metal-rs doesn't bind these setters, so view the same object through
+ // objc2's typed CAMetalLayer binding.
+ let objc2_layer: &objc2_quartz_core::CAMetalLayer = unsafe { &*layer.as_ptr().cast() };
+ objc2_layer.setAllowsNextDrawableTimeout(false);
+ objc2_layer.setNeedsDisplayOnBoundsChange(true);
+ // UIKit sizes a view's backing layer itself; only AppKit-hosted
+ // layers need to track their superlayer's bounds.
+ #[cfg(target_os = "macos")]
+ objc2_layer.setAutoresizingMask(
+ objc2_quartz_core::CAAutoresizingMask::LayerWidthSizable
+ | objc2_quartz_core::CAAutoresizingMask::LayerHeightSizable,
+ );
}
/// Creates a new headless MetalRenderer for offscreen rendering without a window.
@@ -187,6 +207,7 @@ impl MetalRenderer {
Self::new_internal(device, None, true, instance_buffer_pool)
}
+ #[cfg(target_os = "macos")]
fn create_device() -> metal::Device {
// Prefer low‐power integrated GPUs on Intel Mac. On Apple
// Silicon, there is only ever one GPU, so this is equivalent to
@@ -202,13 +223,22 @@ impl MetalRenderer {
log::error!(
"Unable to enumerate Metal devices; attempting to use system default device"
);
- metal::Device::system_default().unwrap_or_else(|| {
- log::error!("unable to access a compatible graphics device");
- std::process::exit(1);
- })
+ Self::system_default_device()
}
}
+ #[cfg(target_os = "ios")]
+ fn create_device() -> metal::Device {
+ Self::system_default_device()
+ }
+
+ fn system_default_device() -> metal::Device {
+ metal::Device::system_default().unwrap_or_else(|| {
+ log::error!("unable to access a compatible graphics device");
+ std::process::exit(1);
+ })
+ }
+
fn new_internal(
device: metal::Device,
layer: Option<metal::MetalLayer>,
@@ -233,7 +263,9 @@ impl MetalRenderer {
// Shared memory can be used only if CPU and GPU share the same memory space.
// https://developer.apple.com/documentation/metal/setting-resource-storage-modes
- let is_unified_memory = device.has_unified_memory();
+ // iOS does not support managed resources. Its simulator may report a
+ // non-unified host GPU even though resources must still use shared storage.
+ let is_unified_memory = cfg!(target_os = "ios") || device.has_unified_memory();
// Apple GPU families support memoryless textures, which can significantly reduce
// memory usage by keeping render targets in on-chip tile memory instead of
// allocating backing store in system memory.
@@ -326,7 +358,8 @@ impl MetalRenderer {
);
let command_queue = device.new_command_queue();
- let sprite_atlas = Arc::new(MetalAtlas::new(device.clone(), is_apple_gpu));
+ 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();
@@ -382,16 +415,7 @@ impl MetalRenderer {
pub fn update_drawable_size(&mut self, size: Size<DevicePixels>) {
if let Some(layer) = &self.layer {
- let ns_size = NSSize {
- width: size.width.0 as f64,
- height: size.height.0 as f64,
- };
- unsafe {
- let _: () = msg_send![
- layer.as_ref(),
- setDrawableSize: ns_size
- ];
- }
+ layer.set_drawable_size(CGSize::new(size.width.0 as f64, size.height.0 as f64));
}
self.update_path_intermediate_textures(size);
}
@@ -592,15 +616,22 @@ impl MetalRenderer {
texture_descriptor.set_usage(
metal::MTLTextureUsage::RenderTarget | metal::MTLTextureUsage::ShaderRead,
);
- texture_descriptor.set_storage_mode(metal::MTLStorageMode::Managed);
+ // Like the atlas, only Apple GPUs can create shared textures on macOS;
+ // Intel Macs cannot, even with unified memory. iOS has no managed storage.
+ let uses_shared_storage = cfg!(target_os = "ios") || self.is_apple_gpu;
+ texture_descriptor.set_storage_mode(if uses_shared_storage {
+ metal::MTLStorageMode::Shared
+ } else {
+ metal::MTLStorageMode::Managed
+ });
let target_texture = self.device.new_texture(&texture_descriptor);
let command_buffer = self.render_frame(scene, &target_texture, size)?;
- // On discrete GPUs (non-unified memory), Managed textures require an
- // explicit blit synchronize before the CPU can read back the rendered
- // data. Without this, get_bytes returns stale zeros.
- if !self.is_unified_memory {
+ // Managed textures require an explicit blit synchronize before the CPU
+ // can read back the rendered data. Without this, get_bytes returns
+ // stale zeros.
+ if !uses_shared_storage {
let blit = command_buffer.new_blit_command_encoder();
blit.synchronize_resource(&target_texture);
blit.end_encoding();
diff --git a/crates/gpui_macos/Cargo.toml b/crates/gpui_macos/Cargo.toml
index 3f57a8ccf8b..cb64044ee2a 100644
--- a/crates/gpui_macos/Cargo.toml
+++ b/crates/gpui_macos/Cargo.toml
@@ -27,7 +27,6 @@ gpui.workspace = true
accesskit.workspace = true
accesskit_macos.workspace = true
anyhow.workspace = true
-async-task.workspace = true
block2.workspace = true
cocoa.workspace = true
collections.workspace = true
@@ -36,7 +35,7 @@ core-foundation-sys.workspace = true
core-graphics.workspace = true
core-text.workspace = true
ctor.workspace = true
-dispatch2 = "0.3.1"
+dispatch2.workspace = true
# WARNING: If you change this, you must also publish a new version of zed-font-kit to crates.io
font-kit = { git = "https://github.com/zed-industries/font-kit", rev = "94b0f28166665e8fd2f53ff6d268a14955c82269", package = "zed-font-kit", version = "0.14.1-zed", optional = true }
foreign-types.workspace = true
@@ -45,9 +44,7 @@ gpui_apple.workspace = true
gpui_util.workspace = true
image.workspace = true
itertools.workspace = true
-libc.workspace = true
log.workspace = true
-mach2.workspace = true
objc.workspace = true
objc2.workspace = true
objc2-app-kit.workspace = true
diff --git a/crates/gpui_macos/src/gpui_macos.rs b/crates/gpui_macos/src/gpui_macos.rs
index 1e393e48759..6e2d04dc812 100644
--- a/crates/gpui_macos/src/gpui_macos.rs
+++ b/crates/gpui_macos/src/gpui_macos.rs
@@ -4,7 +4,6 @@
//! macOS screens have a y axis that goes up from the bottom of the screen and
//! an origin at the bottom left of the main display.
-mod dispatcher;
mod display;
mod display_link;
mod events;
@@ -45,9 +44,9 @@ use std::{
ops::Range,
};
-pub(crate) use dispatcher::*;
pub(crate) use display::*;
pub(crate) use display_link::*;
+pub(crate) use gpui_apple::{AppleActivity, AppleDispatcher};
pub(crate) use keyboard::*;
pub(crate) use platform::*;
pub(crate) use window::*;
diff --git a/crates/gpui_macos/src/platform.rs b/crates/gpui_macos/src/platform.rs
index bda04696c23..92fcf9568df 100644
--- a/crates/gpui_macos/src/platform.rs
+++ b/crates/gpui_macos/src/platform.rs
@@ -1,5 +1,5 @@
use crate::{
- BoolExt, MacActivity, MacDispatcher, MacDisplay, MacKeyboardLayout, MacKeyboardMapper,
+ AppleActivity, AppleDispatcher, BoolExt, MacDisplay, MacKeyboardLayout, MacKeyboardMapper,
MacWindow, events::key_to_native, ns_string, pasteboard::Pasteboard, renderer,
set_active_window_cursor_style,
};
@@ -208,7 +208,7 @@ pub(crate) struct MacPlatformState {
impl MacPlatform {
pub fn new(headless: bool) -> Self {
let marker = MainThreadMarker::new().expect("Mac platform not created on main thread");
- let dispatcher = Arc::new(MacDispatcher::new());
+ let dispatcher = Arc::new(AppleDispatcher::new());
#[cfg(feature = "font-kit")]
let text_system = Arc::new(crate::MacTextSystem::new());
@@ -1031,7 +1031,7 @@ impl Platform for MacPlatform {
}
fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>> {
- Task::ready(Ok(MacActivity::begin(
+ Task::ready(Ok(AppleActivity::begin(
reason,
NSActivityOptions::UserInitiated,
)))