Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

build: wire Linux capture dependencies and GPUI patches

Richie McIlroy6a7ca6ebd5c3
diff --git a/Cargo.lock b/Cargo.lock
index ebda8bf77..12784ec9c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1203,6 +1203,7 @@ dependencies = [
"cap-project",
"cap-recording",
"cap-timestamp",
+ "cap-utils",
"chrono",
"cidre",
"clap",
@@ -1439,6 +1440,7 @@ version = "0.6.0"
dependencies = [
"aho-corasick",
"anyhow",
+ "ashpd",
"async-stream",
"axum",
"base64 0.22.1",
@@ -1460,6 +1462,7 @@ dependencies = [
"cap-project",
"cap-recording",
"cap-rendering",
+ "cap-timestamp",
"cap-utils",
"chrono",
"cidre",
@@ -1475,7 +1478,9 @@ dependencies = [
"flume",
"futures",
"futures-intrusive",
+ "gdkwayland-sys",
"global-hotkey",
+ "gtk",
"image 0.25.8",
"kameo",
"keyed_priority_queue",
@@ -1546,6 +1551,7 @@ dependencies = [
"tracing-opentelemetry",
"tracing-subscriber",
"uuid",
+ "wayland-sys",
"webview2-com",
"wgpu",
"whisper-rs",
@@ -2020,6 +2026,7 @@ dependencies = [
"windows 0.58.0",
"windows-sys 0.52.0",
"workspace-hack",
+ "zbus",
]
[[package]]
diff --git a/apps/cli/Cargo.toml b/apps/cli/Cargo.toml
index b4d2d76c7..73f5de61d 100644
--- a/apps/cli/Cargo.toml
+++ b/apps/cli/Cargo.toml
@@ -12,6 +12,7 @@ cap-editor = { path = "../../crates/editor" }
cap-export = { path = "../../crates/export" }
cap-media-info = { path = "../../crates/media-info" }
cap-timestamp = { path = "../../crates/timestamp" }
+cap-utils = { path = "../../crates/utils" }
relative-path = "1.9.3"
cap-automation = { path = "../../crates/automation" }
cap-camera = { path = "../../crates/camera" }
diff --git a/apps/desktop-gpui/Cargo.lock b/apps/desktop-gpui/Cargo.lock
index c6ed95126..89b135e3d 100644
--- a/apps/desktop-gpui/Cargo.lock
+++ b/apps/desktop-gpui/Cargo.lock
@@ -1522,6 +1522,7 @@ name = "cap-desktop-gpui"
version = "0.6.0"
dependencies = [
"anyhow",
+ "ashpd 0.11.1",
"base64 0.22.1",
"cap-camera",
"cap-camera-effects",
@@ -1950,6 +1951,7 @@ dependencies = [
"windows 0.58.0",
"windows-sys 0.52.0",
"workspace-hack",
+ "zbus",
]
[[package]]
diff --git a/apps/desktop-gpui/Cargo.toml b/apps/desktop-gpui/Cargo.toml
index 890ee0684..d1cbcda50 100644
--- a/apps/desktop-gpui/Cargo.toml
+++ b/apps/desktop-gpui/Cargo.toml
@@ -185,6 +185,9 @@ windows-sys = { version = "0.59", features = [
"Win32_UI_WindowsAndMessaging",
] }
+[target.'cfg(target_os = "linux")'.dependencies]
+ashpd = { version = "0.11", default-features = false, features = ["tokio"] }
+
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
raw-window-handle = "0.6"
x11rb = "0.13"
diff --git a/apps/desktop-gpui/patches/zed-gpui.patch b/apps/desktop-gpui/patches/zed-gpui.patch
index d8f31f816..a1e26a858 100644
--- a/apps/desktop-gpui/patches/zed-gpui.patch
+++ b/apps/desktop-gpui/patches/zed-gpui.patch
@@ -1,25 +1,87 @@
+diff --git a/crates/gpui/src/platform.rs b/crates/gpui/src/platform.rs
+index 20600c3eb519..11bf6cfb0a00 100644
+--- a/crates/gpui/src/platform.rs
++++ b/crates/gpui/src/platform.rs
+@@ -812,6 +812,17 @@
+ detail: Option<&str>,
+ answers: &[PromptButton],
+ ) -> Option<oneshot::Receiver<usize>>;
++ /// `None` forbids capture-time hiding because this backend has no visibility fence.
++ fn retained_visibility(&self) -> Option<bool> {
++ None
++ }
++ /// Retains the window and renderer state until the compositor acknowledges the change.
++ fn set_retained_visibility(
++ &self,
++ _visible: bool,
++ ) -> Result<oneshot::Receiver<Result<(u64, bool)>>> {
++ anyhow::bail!("Retained window visibility is unsupported by this backend")
++ }
+ fn activate(&self);
+ /// Requests that the operating system draw attention to this window.
+ fn request_attention(&self) {}
diff --git a/crates/gpui/src/scene.rs b/crates/gpui/src/scene.rs
-index afb2171476..6cc35624a4 100644
+index afb2171476d5..6cc35624a4e1 100644
--- a/crates/gpui/src/scene.rs
+++ b/crates/gpui/src/scene.rs
-@@ -830,0 +831,4 @@ pub struct PaintSurface {
+@@ -828,6 +828,10 @@
+ pub order: DrawOrder,
+ pub bounds: Bounds<ScaledPixels>,
+ pub content_mask: ContentMask<ScaledPixels>,
+ pub corner_radii: Corners<ScaledPixels>,
+ /// Normalized sub-rect of the source texture to sample, for object-fit
+ /// crops. The full texture is `(0,0)..(1,1)`.
+ pub source_uv: Bounds<f32>,
+ #[cfg(target_os = "macos")]
+ pub image_buffer: core_video::pixel_buffer::CVPixelBuffer,
+ }
diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs
-index 0480dc9574..484179d778 100644
+index 0480dc957438..aabf36147842 100644
--- a/crates/gpui/src/window.rs
+++ b/crates/gpui/src/window.rs
-@@ -1519,0 +1520 @@ impl Window {
+@@ -1517,13 +1517,17 @@
+ // Throttle frame rate based on conditions:
+ // - Thermal pressure (Serious/Critical): cap to ~60fps
+ // - Inactive window (not focused): cap to ~30fps to save energy
+ let will_draw = invalidator.is_dirty() || request_frame_options.force_render;
-@@ -1526 +1527,4 @@ impl Window {
+ let min_frame_interval = if !request_frame_options.force_render
+ && !request_frame_options.require_presentation
+ && next_frame_callbacks.borrow().is_empty()
+ {
+ None
+ } else if !active.get() {
- Some(Duration::from_micros(33333))
+ // The skip below returns before the dirty check, so without
+ // this an unrelated pending next-frame callback caps fresh
+ // content at 30fps -- video playback in an unfocused window.
+ (!will_draw).then_some(Duration::from_micros(33333))
-@@ -4544,0 +4549,18 @@ impl Window {
+ } else if let Some(ThermalState::Critical | ThermalState::Serious) = thermal_state {
+ Some(Duration::from_micros(16667))
+ } else {
+@@ -2447,6 +2451,19 @@
+ self.platform_window.window_controls()
+ }
+
++ /// This is retained state; capture still needs a completed visibility receipt.
++ pub fn retained_visibility(&self) -> Option<bool> {
++ self.platform_window.retained_visibility()
++ }
++
++ /// The receipt acknowledges compositor processing, not physical presentation.
++ pub fn set_retained_visibility(
++ &mut self,
++ visible: bool,
++ ) -> anyhow::Result<futures::channel::oneshot::Receiver<anyhow::Result<(u64, bool)>>> {
++ self.platform_window.set_retained_visibility(visible)
++ }
++
+ /// Updates the window's title at the platform level.
+ pub fn set_window_title(&mut self, title: &str) {
+ self.platform_window.set_title(title);
+@@ -4542,16 +4559,56 @@
+ /// This method should only be called as part of the paint phase of element drawing.
+ #[cfg(target_os = "macos")]
+ pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVPixelBuffer) {
+ self.paint_surface_fitted(bounds, bounds, Corners::default(), image_buffer);
+ }
+
@@ -38,7 +100,10 @@ index 0480dc9574..484179d778 100644
+ corner_radii: Corners<Pixels>,
+ image_buffer: CVPixelBuffer,
+ ) {
-@@ -4549 +4571,20 @@ impl Window {
+ use crate::PaintSurface;
+
+ self.invalidator.debug_assert_paint();
+
- let bounds = self.snap_bounds(bounds);
+ let source_uv = if visible == fitted {
+ Bounds {
@@ -60,31 +125,54 @@ index 0480dc9574..484179d778 100644
+ }
+ };
+ let bounds = self.snap_bounds(visible);
-@@ -4550,0 +4592 @@ impl Window {
+ let content_mask = self.snapped_content_mask();
+ let corner_radii = corner_radii.scale(self.scale_factor());
-@@ -4554,0 +4597,2 @@ impl Window {
+ self.next_frame.scene.insert_primitive(PaintSurface {
+ order: 0,
+ bounds,
+ content_mask,
+ corner_radii,
+ source_uv,
+ image_buffer,
+ });
+ }
diff --git a/crates/gpui_macos/src/metal_renderer.rs b/crates/gpui_macos/src/metal_renderer.rs
-index c93a383c38..1d35af12f6 100644
+index c93a383c38c6..1d35af12f64b 100644
--- a/crates/gpui_macos/src/metal_renderer.rs
+++ b/crates/gpui_macos/src/metal_renderer.rs
-@@ -10,3 +10,3 @@ use gpui::{
+@@ -7,17 +7,18 @@
+ quartzcore::AutoresizingMask,
+ };
+ use gpui::{
- AtlasTextureId, BackdropBlur, Background, Bounds, ContentMask, DevicePixels, DrawOrder,
- MonochromeSprite, PaintSurface, Path, Point, PolychromeSprite, PrimitiveBatch, Quad,
- ScaledPixels, Scene, Shadow, Size, Surface, Underline, point, size,
+ AtlasTextureId, BackdropBlur, Background, Bounds, ContentMask, Corners, DevicePixels,
+ DrawOrder, MonochromeSprite, PaintSurface, Path, Point, PolychromeSprite, PrimitiveBatch, Quad,
+ ScaledPixels, Scene, Shadow, Size, Underline, point, size,
-@@ -19,2 +19,3 @@ use core_video::{
+ };
+ #[cfg(any(test, feature = "test-support"))]
+ use image::RgbaImage;
+
+ use core_foundation::base::TCFType;
+ use core_video::{
- metal_texture::CVMetalTextureGetTexture, metal_texture_cache::CVMetalTextureCache,
- pixel_buffer::kCVPixelFormatType_420YpCbCr8BiPlanarFullRange,
+ metal_texture::{CVMetalTexture, CVMetalTextureGetTexture},
+ metal_texture_cache::CVMetalTextureCache,
+ pixel_buffer::{kCVPixelFormatType_32BGRA, kCVPixelFormatType_420YpCbCr8BiPlanarFullRange},
-@@ -50,0 +52 @@ const SCRATCH_RELEASE_AFTER_FRAMES: u32 = 30;
+ };
+ use foreign_types::{ForeignType, ForeignTypeRef};
+ use metal::{
+@@ -48,17 +49,12 @@
+ /// out popover close/reopen and brief path-free frames, short enough that a
+ /// few seconds of activity reclaims the memory.
+ const SCRATCH_RELEASE_AFTER_FRAMES: u32 = 30;
+const SURFACE_ERROR_LOG_INTERVAL: std::time::Duration = std::time::Duration::from_secs(5);
-@@ -55,7 +57 @@ pub(crate) type Renderer = MetalRenderer;
+
+ pub(crate) type Context = Arc<Mutex<InstanceBufferPool>>;
+ pub(crate) type Renderer = MetalRenderer;
+
-pub(crate) unsafe fn new_renderer(
- context: self::Context,
- _native_window: *mut c_void,
@@ -93,11 +181,27 @@ index c93a383c38..1d35af12f6 100644
- transparent: bool,
-) -> Renderer {
+pub(crate) fn new_renderer(context: self::Context, transparent: bool) -> Result<Renderer> {
-@@ -173,0 +170 @@ pub(crate) struct MetalRenderer {
+ MetalRenderer::new(context, transparent)
+ }
+
+@@ -171,11 +167,13 @@
+ path_free_frames: u32,
+ /// Last time `COMET_GPU_STATS` logged.
+ stats_last_log: Option<std::time::Instant>,
+ surface_error_last_log: Option<std::time::Instant>,
-@@ -178,0 +176 @@ pub(crate) struct MetalRenderer {
+ quads_pipeline_state: metal::RenderPipelineState,
+ underlines_pipeline_state: metal::RenderPipelineState,
+ monochrome_sprites_pipeline_state: metal::RenderPipelineState,
+ polychrome_sprites_pipeline_state: metal::RenderPipelineState,
+ surfaces_pipeline_state: metal::RenderPipelineState,
+ bgra_surfaces_pipeline_state: metal::RenderPipelineState,
-@@ -211,2 +209,5 @@ impl MetalRenderer {
+ unit_vertices: metal::Buffer,
+ #[allow(clippy::arc_with_non_send_sync)]
+ instance_buffer_pool: Arc<Mutex<InstanceBufferPool>>,
+@@ -208,8 +206,11 @@
+
+ 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();
+ pub fn new(
@@ -105,25 +209,50 @@ index c93a383c38..1d35af12f6 100644
+ transparent: bool,
+ ) -> Result<Self> {
+ let device = Self::create_device()?;
-@@ -242,2 +243,2 @@ impl MetalRenderer {
+
+ let layer = metal::MetalLayer::new();
+ layer.set_device(&device);
+@@ -239,12 +240,12 @@
+ /// This renderer can render scenes to images without requiring a CAMetalLayer,
+ /// window, or AppKit. Use `render_scene_to_image()` to render scenes.
+ #[cfg(any(test, feature = "test-support"))]
- pub fn new_headless(instance_buffer_pool: Arc<Mutex<InstanceBufferPool>>) -> Self {
- let device = Self::create_device();
+ pub fn new_headless(instance_buffer_pool: Arc<Mutex<InstanceBufferPool>>) -> Result<Self> {
+ let device = Self::create_device()?;
-@@ -247 +248 @@ impl MetalRenderer {
+ Self::new_internal(device, None, true, instance_buffer_pool)
+ }
+
- fn create_device() -> metal::Device {
+ fn create_device() -> Result<metal::Device> {
-@@ -255 +256 @@ impl MetalRenderer {
+ // Prefer low‐power integrated GPUs on Intel Mac. On Apple
+ // Silicon, there is only ever one GPU, so this is equivalent to
+ // `metal::Device::system_default()`.
+@@ -252,17 +253,15 @@
+ .into_iter()
+ .min_by_key(|d| (d.is_removable(), !d.is_low_power()))
+ {
- d
+ Ok(d)
-@@ -262,4 +263,2 @@ impl MetalRenderer {
+ } else {
+ // For some reason `all()` can return an empty list, see https://github.com/zed-industries/zed/issues/37689
+ // In that case, we fall back to the system default device.
+ 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);
- })
+ metal::Device::system_default()
+ .ok_or_else(|| anyhow::anyhow!("unable to access a compatible graphics device"))
-@@ -274,9 +273,2 @@ impl MetalRenderer {
+ }
+ }
+
+@@ -271,15 +270,8 @@
+ layer: Option<metal::MetalLayer>,
+ opaque: bool,
+ instance_buffer_pool: Arc<Mutex<InstanceBufferPool>>,
- ) -> Self {
- #[cfg(feature = "runtime_shaders")]
- let library = device
@@ -135,31 +264,85 @@ index c93a383c38..1d35af12f6 100644
- .expect("error building metal library");
+ ) -> Result<Self> {
+ let library = build_shader_library(&device)?;
-@@ -327 +319 @@ impl MetalRenderer {
+
+ fn to_float2_bits(point: PointF) -> u64 {
+ let mut output = point.y.to_bits() as u64;
+@@ -324,7 +316,7 @@
+ "path_rasterization_fragment",
+ MTLPixelFormat::BGRA8Unorm,
+ PATH_SAMPLE_COUNT,
- );
+ )?;
-@@ -335 +327 @@ impl MetalRenderer {
+ let path_sprites_pipeline_state = build_path_sprite_pipeline_state(
+ &device,
+ &library,
+@@ -332,7 +324,7 @@
+ "path_sprite_vertex",
+ "path_sprite_fragment",
+ MTLPixelFormat::BGRA8Unorm,
- );
+ )?;
-@@ -343 +335 @@ impl MetalRenderer {
+ let shadows_pipeline_state = build_pipeline_state(
+ &device,
+ &library,
+@@ -340,7 +332,7 @@
+ "shadow_vertex",
+ "shadow_fragment",
+ MTLPixelFormat::BGRA8Unorm,
- );
+ )?;
-@@ -353 +345 @@ impl MetalRenderer {
+ // Blending DISABLED: the blur REPLACES the region with the blurred
+ // snapshot verbatim (fragments outside the rounded rect discard).
+ let backdrop_blur_pipeline_state = build_pipeline_state_no_blend(
+@@ -350,7 +342,7 @@
+ "backdrop_blur_vertex",
+ "backdrop_blur_fragment",
+ MTLPixelFormat::BGRA8Unorm,
- );
+ )?;
-@@ -361 +353 @@ impl MetalRenderer {
+ let quads_pipeline_state = build_pipeline_state(
+ &device,
+ &library,
+@@ -358,7 +350,7 @@
+ "quad_vertex",
+ "quad_fragment",
+ MTLPixelFormat::BGRA8Unorm,
- );
+ )?;
-@@ -369 +361 @@ impl MetalRenderer {
+ let underlines_pipeline_state = build_pipeline_state(
+ &device,
+ &library,
+@@ -366,7 +358,7 @@
+ "underline_vertex",
+ "underline_fragment",
+ MTLPixelFormat::BGRA8Unorm,
- );
+ )?;
-@@ -377 +369 @@ impl MetalRenderer {
+ let monochrome_sprites_pipeline_state = build_pipeline_state(
+ &device,
+ &library,
+@@ -374,7 +366,7 @@
+ "monochrome_sprite_vertex",
+ "monochrome_sprite_fragment",
+ MTLPixelFormat::BGRA8Unorm,
- );
+ )?;
-@@ -385 +377 @@ impl MetalRenderer {
+ let polychrome_sprites_pipeline_state = build_pipeline_state(
+ &device,
+ &library,
+@@ -382,7 +374,7 @@
+ "polychrome_sprite_vertex",
+ "polychrome_sprite_fragment",
+ MTLPixelFormat::BGRA8Unorm,
- );
+ )?;
-@@ -393 +385,9 @@ impl MetalRenderer {
+ let surfaces_pipeline_state = build_pipeline_state(
+ &device,
+ &library,
+@@ -390,14 +382,24 @@
+ "surface_vertex",
+ "surface_fragment",
+ MTLPixelFormat::BGRA8Unorm,
- );
+ )?;
+ let bgra_surfaces_pipeline_state = build_pipeline_state(
@@ -170,24 +353,49 @@ index c93a383c38..1d35af12f6 100644
+ "surface_bgra_fragment",
+ MTLPixelFormat::BGRA8Unorm,
+ )?;
-@@ -397,2 +397,4 @@ impl MetalRenderer {
+
+ let command_queue = device.new_command_queue();
+ let sprite_atlas = Arc::new(MetalAtlas::new(device.clone(), is_apple_gpu));
- let core_video_texture_cache =
- CVMetalTextureCache::new(None, device.clone(), None).unwrap();
+-
+- Self {
+ let core_video_texture_cache = CVMetalTextureCache::new(None, device.clone(), None)
+ .map_err(|status| {
+ anyhow::anyhow!("failed to create Core Video Metal texture cache: {status}")
+ })?;
-@@ -400 +402 @@ impl MetalRenderer {
-- Self {
++
+ Ok(Self {
-@@ -417,0 +420 @@ impl MetalRenderer {
+ device,
+ layer,
+ presents_with_transaction: false,
+@@ -415,11 +417,13 @@
+ blur_free_frames: 0,
+ path_free_frames: 0,
+ stats_last_log: None,
+ surface_error_last_log: None,
-@@ -422,0 +426 @@ impl MetalRenderer {
+ quads_pipeline_state,
+ underlines_pipeline_state,
+ monochrome_sprites_pipeline_state,
+ polychrome_sprites_pipeline_state,
+ surfaces_pipeline_state,
+ bgra_surfaces_pipeline_state,
-@@ -432 +436 @@ impl MetalRenderer {
+ unit_vertices,
+ instance_buffer_pool,
+ sprite_atlas,
+@@ -429,7 +433,7 @@
+ path_sample_count: PATH_SAMPLE_COUNT,
+ #[cfg(any(test, feature = "test-support"))]
+ headless_render_target: None,
- }
+ })
-@@ -489,3 +493,7 @@ impl MetalRenderer {
+ }
+
+ pub fn layer(&self) -> Option<&metal::MetalLayerRef> {
+@@ -486,9 +490,13 @@
+ self.path_intermediate_msaa_texture = None;
+ return;
+ }
- if self.path_intermediate_texture.as_ref().is_some_and(|texture| {
- texture.width() == size.width.0 as u64 && texture.height() == size.height.0 as u64
- }) {
@@ -198,34 +406,82 @@ index c93a383c38..1d35af12f6 100644
+ texture.width() == size.width.0 as u64 && texture.height() == size.height.0 as u64
+ })
+ {
-@@ -921,0 +930 @@ impl MetalRenderer {
+ return;
+ }
+
+@@ -919,6 +927,7 @@
+ let command_buffer = command_queue.new_command_buffer();
+ let alpha = if self.opaque { 1. } else { 0. };
+ let mut instance_offset = 0;
+ let mut retained_surface_textures = CommandBufferResources::default();
-@@ -1141,0 +1151 @@ impl MetalRenderer {
+
+ // Big scratch textures are only worth holding while they're in use:
+ // after a run of frames that don't need them, drop them and let the
+@@ -1139,6 +1148,7 @@
+ &mut instance_offset,
+ viewport_size,
+ command_encoder,
+ &mut retained_surface_textures,
-@@ -1172,0 +1183,2 @@ impl MetalRenderer {
+ ),
+ PrimitiveBatch::SubpixelSprites { .. } => unreachable!(),
+ };
+@@ -1170,6 +1180,8 @@
+ self.instance_buffer_pool.lock().note_usage(instance_offset);
+ self.maybe_log_gpu_stats();
+
+ retained_surface_textures.retain_until_completion(command_buffer);
+
-@@ -1196,3 +1208 @@ impl MetalRenderer {
+ Ok(command_buffer.to_owned())
+ }
+
+@@ -1193,9 +1205,7 @@
+ self.stats_last_log = Some(now);
+
+ let texture_bytes = |texture: &Option<metal::Texture>| {
- texture
- .as_ref()
- .map_or(0, |t| t.width() * t.height() * 4)
+ texture.as_ref().map_or(0, |t| t.width() * t.height() * 4)
-@@ -1385,2 +1395 @@ impl MetalRenderer {
+ };
+ let backdrop_bytes =
+ texture_bytes(&self.backdrop_scratch) + texture_bytes(&self.backdrop_blurred);
+@@ -1382,8 +1392,7 @@
+ }
+ }
+ let kernel: *mut objc::runtime::Object = unsafe {
- let alloc: *mut objc::runtime::Object =
- msg_send![class!(MPSImageGaussianBlur), alloc];
+ let alloc: *mut objc::runtime::Object = msg_send![class!(MPSImageGaussianBlur), alloc];
-@@ -1444,2 +1453,4 @@ impl MetalRenderer {
+ let kernel: *mut objc::runtime::Object = msg_send![
+ alloc,
+ initWithDevice: self.device.as_ptr() as *mut objc::runtime::Object
+@@ -1441,8 +1450,10 @@
+ mem::size_of_val(&source_rect) as u64,
+ source_rect.as_ptr() as *const _,
+ );
- command_encoder
- .set_fragment_texture(BackdropBlurInputIndex::SourceTexture as u64, Some(source_texture));
+ command_encoder.set_fragment_texture(
+ BackdropBlurInputIndex::SourceTexture as u64,
+ Some(source_texture),
+ );
-@@ -1896,0 +1908 @@ impl MetalRenderer {
+
+ let blur_bytes_len = mem::size_of_val(blurs);
+ let buffer_contents =
+@@ -1894,8 +1905,8 @@
+ instance_offset: &mut usize,
+ viewport_size: Size<DevicePixels>,
+ command_encoder: &metal::RenderCommandEncoderRef,
+ retained_surface_textures: &mut CommandBufferResources<CVMetalTexture>,
-@@ -1898 +1909,0 @@ impl MetalRenderer {
+ ) -> bool {
- command_encoder.set_render_pipeline_state(&self.surfaces_pipeline_state);
-@@ -1916,8 +1927,3 @@ impl MetalRenderer {
+ command_encoder.set_vertex_buffer(
+ SurfaceInputIndex::Vertices as u64,
+ Some(&self.unit_vertices),
+@@ -1913,41 +1924,112 @@
+ DevicePixels::from(surface.image_buffer.get_height() as i32),
+ );
+
- assert_eq!(
- surface.image_buffer.get_pixel_format(),
- kCVPixelFormatType_420YpCbCr8BiPlanarFullRange
@@ -237,7 +493,12 @@ index c93a383c38..1d35af12f6 100644
+ let pixel_format = surface.image_buffer.get_pixel_format();
+ if pixel_format == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange {
+ let y_texture = match self.core_video_texture_cache.create_texture_from_image(
-@@ -1930,5 +1936,10 @@ impl MetalRenderer {
+ surface.image_buffer.as_concrete_TypeRef(),
+ 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
@@ -253,7 +514,12 @@ index c93a383c38..1d35af12f6 100644
+ }
+ };
+ let cb_cr_texture = match self.core_video_texture_cache.create_texture_from_image(
-@@ -1941,2 +1952,67 @@ impl MetalRenderer {
+ surface.image_buffer.as_concrete_TypeRef(),
+ None,
+ MTLPixelFormat::RG8Unorm,
+ surface.image_buffer.get_width_of_plane(1),
+ surface.image_buffer.get_height_of_plane(1),
+ 1,
- )
- .unwrap();
+ ) {
@@ -323,17 +589,28 @@ index c93a383c38..1d35af12f6 100644
+ ));
+ continue;
+ }
-@@ -1945 +2021 @@ impl MetalRenderer {
+
+ align_offset(instance_offset);
- let next_offset = *instance_offset + mem::size_of::<Surface>();
+ let next_offset = *instance_offset + mem::size_of::<SurfaceBounds>();
-@@ -1954,0 +2031,6 @@ impl MetalRenderer {
-+ // The fragment reads corner radii from the same instance record.
-+ command_encoder.set_fragment_buffer(
+ if next_offset > instance_buffer.size {
+ return false;
+ }
+
+ command_encoder.set_vertex_buffer(
+ SurfaceInputIndex::Surfaces as u64,
+ Some(&instance_buffer.metal_buffer),
+ *instance_offset as u64,
+ );
-@@ -1960,9 +2041,0 @@ impl MetalRenderer {
++ // The fragment reads corner radii from the same instance record.
++ command_encoder.set_fragment_buffer(
+ SurfaceInputIndex::Surfaces as u64,
+ Some(&instance_buffer.metal_buffer),
+ *instance_offset as u64,
+@@ -1957,15 +2039,6 @@
+ 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());
@@ -343,10 +620,22 @@ index c93a383c38..1d35af12f6 100644
- let texture = CVMetalTextureGetTexture(cb_cr_texture.as_concrete_TypeRef());
- Some(metal::TextureRef::from_ptr(texture as *mut _))
- });
-@@ -1978,0 +2052,2 @@ impl MetalRenderer {
+
+ unsafe {
+ let buffer_contents = (instance_buffer.metal_buffer.contents() as *mut u8)
+@@ -1976,6 +2049,8 @@
+ SurfaceBounds {
+ bounds: surface.bounds,
+ content_mask: surface.content_mask,
+ corner_radii: surface.corner_radii,
+ source_uv: surface.source_uv,
-@@ -1987,0 +2063,50 @@ impl MetalRenderer {
+ },
+ );
+ }
+@@ -1985,6 +2060,56 @@
+ }
+ true
+ }
+
+ fn log_surface_texture_error(&mut self, error: std::fmt::Arguments<'_>) {
+ let now = std::time::Instant::now();
@@ -397,7 +686,13 @@ index c93a383c38..1d35af12f6 100644
+ last_log.is_none_or(|last_log| {
+ now.saturating_duration_since(last_log) >= SURFACE_ERROR_LOG_INTERVAL
+ })
-@@ -2016,0 +2142,15 @@ fn new_command_encoder_for_texture<'a>(
+ }
+
+ fn new_command_encoder_for_texture<'a>(
+@@ -2014,6 +2139,21 @@
+ command_encoder
+ }
+
+fn build_shader_library(device: &metal::DeviceRef) -> Result<metal::Library> {
+ #[cfg(feature = "runtime_shaders")]
+ {
@@ -413,125 +708,221 @@ index c93a383c38..1d35af12f6 100644
+ }
+}
+
-@@ -2024 +2164 @@ fn build_pipeline_state(
+ fn build_pipeline_state(
+ device: &metal::DeviceRef,
+ library: &metal::LibraryRef,
+@@ -2021,19 +2161,30 @@
+ vertex_fn_name: &str,
+ fragment_fn_name: &str,
+ pixel_format: metal::MTLPixelFormat,
-) -> metal::RenderPipelineState {
+) -> Result<metal::RenderPipelineState> {
-@@ -2027 +2167,5 @@ fn build_pipeline_state(
+ let vertex_fn = library
+ .get_function(vertex_fn_name, None)
- .expect("error locating vertex function");
+ .map_err(|error| {
+ anyhow::anyhow!(
+ "failed to locate Metal vertex function {vertex_fn_name} for {label}: {error}"
+ )
+ })?;
-@@ -2030 +2174,5 @@ fn build_pipeline_state(
+ let fragment_fn = library
+ .get_function(fragment_fn_name, None)
- .expect("error locating fragment function");
+ .map_err(|error| {
+ anyhow::anyhow!(
+ "failed to locate Metal fragment function {fragment_fn_name} for {label}: {error}"
+ )
+ })?;
-@@ -2036 +2184,4 @@ fn build_pipeline_state(
+
+ let descriptor = metal::RenderPipelineDescriptor::new();
+ descriptor.set_label(label);
+ descriptor.set_vertex_function(Some(vertex_fn.as_ref()));
+ descriptor.set_fragment_function(Some(fragment_fn.as_ref()));
- let color_attachment = descriptor.color_attachments().object_at(0).unwrap();
+ let color_attachment = descriptor
+ .color_attachments()
+ .object_at(0)
+ .ok_or_else(|| anyhow::anyhow!("Metal pipeline {label} has no color attachment"))?;
-@@ -2053 +2204 @@ fn build_pipeline_state(
+ color_attachment.set_pixel_format(pixel_format);
+ color_attachment.set_blending_enabled(true);
+ color_attachment.set_rgb_blend_operation(metal::MTLBlendOperation::Add);
+@@ -2050,7 +2201,7 @@
+
+ device
+ .new_render_pipeline_state(&descriptor)
- .expect("could not create render pipeline state")
+ .map_err(|error| anyhow::anyhow!("failed to create Metal pipeline {label}: {error}"))
-@@ -2063 +2214 @@ fn build_pipeline_state_no_blend(
+ }
+
+ fn build_pipeline_state_no_blend(
+@@ -2060,25 +2211,36 @@
+ vertex_fn_name: &str,
+ fragment_fn_name: &str,
+ pixel_format: metal::MTLPixelFormat,
-) -> metal::RenderPipelineState {
+) -> Result<metal::RenderPipelineState> {
-@@ -2066 +2217,5 @@ fn build_pipeline_state_no_blend(
+ let vertex_fn = library
+ .get_function(vertex_fn_name, None)
- .expect("error locating vertex function");
+ .map_err(|error| {
+ anyhow::anyhow!(
+ "failed to locate Metal vertex function {vertex_fn_name} for {label}: {error}"
+ )
+ })?;
-@@ -2069 +2224,5 @@ fn build_pipeline_state_no_blend(
+ let fragment_fn = library
+ .get_function(fragment_fn_name, None)
- .expect("error locating fragment function");
+ .map_err(|error| {
+ anyhow::anyhow!(
+ "failed to locate Metal fragment function {fragment_fn_name} for {label}: {error}"
+ )
+ })?;
-@@ -2075 +2234,4 @@ fn build_pipeline_state_no_blend(
+
+ let descriptor = metal::RenderPipelineDescriptor::new();
+ descriptor.set_label(label);
+ descriptor.set_vertex_function(Some(vertex_fn.as_ref()));
+ descriptor.set_fragment_function(Some(fragment_fn.as_ref()));
- let color_attachment = descriptor.color_attachments().object_at(0).unwrap();
+ let color_attachment = descriptor
+ .color_attachments()
+ .object_at(0)
+ .ok_or_else(|| anyhow::anyhow!("Metal pipeline {label} has no color attachment"))?;
-@@ -2081 +2243 @@ fn build_pipeline_state_no_blend(
+ color_attachment.set_pixel_format(pixel_format);
+ color_attachment.set_blending_enabled(false);
+
+ device
+ .new_render_pipeline_state(&descriptor)
- .expect("could not create render pipeline state")
+ .map_err(|error| anyhow::anyhow!("failed to create Metal pipeline {label}: {error}"))
-@@ -2110 +2272 @@ fn build_path_sprite_pipeline_state(
+ }
+
+ /// The draw order of a batch's first primitive — where the backdrop-blur
+@@ -2107,19 +2269,30 @@
+ vertex_fn_name: &str,
+ fragment_fn_name: &str,
+ pixel_format: metal::MTLPixelFormat,
-) -> metal::RenderPipelineState {
+) -> Result<metal::RenderPipelineState> {
-@@ -2113 +2275,5 @@ fn build_path_sprite_pipeline_state(
+ let vertex_fn = library
+ .get_function(vertex_fn_name, None)
- .expect("error locating vertex function");
+ .map_err(|error| {
+ anyhow::anyhow!(
+ "failed to locate Metal vertex function {vertex_fn_name} for {label}: {error}"
+ )
+ })?;
-@@ -2116 +2282,5 @@ fn build_path_sprite_pipeline_state(
+ let fragment_fn = library
+ .get_function(fragment_fn_name, None)
- .expect("error locating fragment function");
+ .map_err(|error| {
+ anyhow::anyhow!(
+ "failed to locate Metal fragment function {fragment_fn_name} for {label}: {error}"
+ )
+ })?;
-@@ -2122 +2292,4 @@ fn build_path_sprite_pipeline_state(
+
+ let descriptor = metal::RenderPipelineDescriptor::new();
+ descriptor.set_label(label);
+ descriptor.set_vertex_function(Some(vertex_fn.as_ref()));
+ descriptor.set_fragment_function(Some(fragment_fn.as_ref()));
- let color_attachment = descriptor.color_attachments().object_at(0).unwrap();
+ let color_attachment = descriptor
+ .color_attachments()
+ .object_at(0)
+ .ok_or_else(|| anyhow::anyhow!("Metal pipeline {label} has no color attachment"))?;
-@@ -2136 +2309 @@ fn build_path_sprite_pipeline_state(
+ color_attachment.set_pixel_format(pixel_format);
+ color_attachment.set_blending_enabled(true);
+ color_attachment.set_rgb_blend_operation(metal::MTLBlendOperation::Add);
+@@ -2133,7 +2306,7 @@
+
+ device
+ .new_render_pipeline_state(&descriptor)
- .expect("could not create render pipeline state")
+ .map_err(|error| anyhow::anyhow!("failed to create Metal pipeline {label}: {error}"))
-@@ -2147 +2320 @@ fn build_path_rasterization_pipeline_state(
+ }
+
+ fn build_path_rasterization_pipeline_state(
+@@ -2144,13 +2317,21 @@
+ fragment_fn_name: &str,
+ pixel_format: metal::MTLPixelFormat,
+ path_sample_count: u32,
-) -> metal::RenderPipelineState {
+) -> Result<metal::RenderPipelineState> {
-@@ -2150 +2323,5 @@ fn build_path_rasterization_pipeline_state(
+ let vertex_fn = library
+ .get_function(vertex_fn_name, None)
- .expect("error locating vertex function");
+ .map_err(|error| {
+ anyhow::anyhow!(
+ "failed to locate Metal vertex function {vertex_fn_name} for {label}: {error}"
+ )
+ })?;
-@@ -2153 +2330,5 @@ fn build_path_rasterization_pipeline_state(
+ let fragment_fn = library
+ .get_function(fragment_fn_name, None)
- .expect("error locating fragment function");
+ .map_err(|error| {
+ anyhow::anyhow!(
+ "failed to locate Metal fragment function {fragment_fn_name} for {label}: {error}"
+ )
+ })?;
-@@ -2163 +2344,4 @@ fn build_path_rasterization_pipeline_state(
+
+ let descriptor = metal::RenderPipelineDescriptor::new();
+ descriptor.set_label(label);
+@@ -2160,7 +2341,10 @@
+ descriptor.set_raster_sample_count(path_sample_count as _);
+ descriptor.set_alpha_to_coverage_enabled(false);
+ }
- let color_attachment = descriptor.color_attachments().object_at(0).unwrap();
+ let color_attachment = descriptor
+ .color_attachments()
+ .object_at(0)
+ .ok_or_else(|| anyhow::anyhow!("Metal pipeline {label} has no color attachment"))?;
-@@ -2175 +2359 @@ fn build_path_rasterization_pipeline_state(
+ color_attachment.set_pixel_format(pixel_format);
+ color_attachment.set_blending_enabled(true);
+ color_attachment.set_rgb_blend_operation(metal::MTLBlendOperation::Add);
+@@ -2172,7 +2356,7 @@
+
+ device
+ .new_render_pipeline_state(&descriptor)
- .expect("could not create render pipeline state")
+ .map_err(|error| anyhow::anyhow!("failed to create Metal pipeline {label}: {error}"))
-@@ -2246 +2430 @@ pub struct PathSprite {
+ }
+
+ // Align to multiples of 256 make Metal happy.
+@@ -2243,11 +2427,13 @@
+ pub bounds: Bounds<ScaledPixels>,
+ }
+
-#[derive(Clone, Debug, Eq, PartialEq)]
+#[derive(Clone, Debug, PartialEq)]
-@@ -2250,0 +2435,2 @@ pub struct SurfaceBounds {
+ #[repr(C)]
+ pub struct SurfaceBounds {
+ pub bounds: Bounds<ScaledPixels>,
+ pub content_mask: ContentMask<ScaledPixels>,
+ pub corner_radii: Corners<ScaledPixels>,
+ pub source_uv: Bounds<f32>,
-@@ -2260 +2446 @@ impl MetalHeadlessRenderer {
+ }
+
+ #[cfg(any(test, feature = "test-support"))]
+@@ -2257,10 +2443,10 @@
+
+ #[cfg(any(test, feature = "test-support"))]
+ impl MetalHeadlessRenderer {
- pub fn new() -> Self {
+ pub fn new() -> Result<Self> {
-@@ -2262,2 +2448,2 @@ impl MetalHeadlessRenderer {
+ let instance_buffer_pool = Arc::new(Mutex::new(InstanceBufferPool::default()));
- let renderer = MetalRenderer::new_headless(instance_buffer_pool);
- Self { renderer }
+ let renderer = MetalRenderer::new_headless(instance_buffer_pool)?;
+ Ok(Self { renderer })
-@@ -2285,0 +2472,79 @@ impl gpui::PlatformHeadlessRenderer for MetalHeadlessRenderer {
+ }
+ }
+
+@@ -2280,6 +2466,85 @@
+
+ fn sprite_atlas(&self) -> Arc<dyn gpui::PlatformAtlas> {
+ self.renderer.sprite_atlas().clone()
++ }
++}
++
+#[cfg(test)]
+mod renderer_hardening_tests {
+ use super::*;
@@ -608,24 +999,52 @@ index c93a383c38..1d35af12f6 100644
+ assert!(surface_error_log_due(None, last_log));
+ assert!(!surface_error_log_due(Some(last_log), before_interval));
+ assert!(surface_error_log_due(Some(last_log), at_interval));
-+ }
-+}
-+
-@@ -2372 +2637,2 @@ mod backdrop_blur_tests {
+ }
+ }
+
+@@ -2369,7 +2634,8 @@
+ fn render(scene: &mut Scene) -> RgbaImage {
+ scene.finish();
+ let mut renderer =
- MetalRenderer::new_headless(Arc::new(Mutex::new(InstanceBufferPool::default())));
+ MetalRenderer::new_headless(Arc::new(Mutex::new(InstanceBufferPool::default())))
+ .expect("failed to initialize headless renderer");
-@@ -2454 +2720,4 @@ mod backdrop_blur_tests {
+ renderer
+ .render_scene_to_image(scene, size(DevicePixels(VIEW_W), DevicePixels(VIEW_H)))
+ .expect("render_scene_to_image failed")
+@@ -2451,7 +2717,10 @@
+ let b = render(&mut scene);
+
+ let diff = max_abs_diff(&a, &b, 0, 168, 152, 312);
- assert!(diff <= 3, "vignette or shift at window edge: max diff {diff}");
+ assert!(
+ diff <= 3,
+ "vignette or shift at window edge: max diff {diff}"
+ );
+ }
+
+ #[test]
+diff --git a/crates/gpui_macos/src/platform.rs b/crates/gpui_macos/src/platform.rs
+index b25067935e5f..c60ef0b4ec97 100644
+--- a/crates/gpui_macos/src/platform.rs
++++ b/crates/gpui_macos/src/platform.rs
+@@ -666,7 +666,7 @@
+ foreground_executor,
+ background_executor,
+ renderer_context,
+- )))
++ )?))
+ }
+
+ fn window_appearance(&self) -> WindowAppearance {
diff --git a/crates/gpui_macos/src/shaders.metal b/crates/gpui_macos/src/shaders.metal
-index 97bad184dc..71a05aca4f 100644
+index 97bad184dc58..e087c0dc8a54 100644
--- a/crates/gpui_macos/src/shaders.metal
+++ b/crates/gpui_macos/src/shaders.metal
-@@ -883,3 +883,4 @@ vertex SurfaceVertexOutput surface_vertex(
+@@ -880,16 +880,30 @@
+ to_device_position(unit_vertex, surface.bounds, viewport_size);
+ float4 clip_distance = distance_from_clip_rect(unit_vertex, surface.bounds,
+ surface.content_mask.bounds);
- // We are going to copy the whole texture, so the texture position corresponds
- // to the current vertex of the unit triangle.
- float2 texture_position = unit_vertex;
@@ -633,7 +1052,12 @@ index 97bad184dc..71a05aca4f 100644
+ float2(surface.source_uv.origin.x, surface.source_uv.origin.y) +
+ unit_vertex * float2(surface.source_uv.size.width,
+ surface.source_uv.size.height);
-@@ -891,0 +893,11 @@ vertex SurfaceVertexOutput surface_vertex(
+ return SurfaceVertexOutput{
+ device_position,
+ texture_position,
+ {clip_distance.x, clip_distance.y, clip_distance.z, clip_distance.w}};
+ }
+
+float surface_corner_alpha(float2 position, SurfaceBounds surface) {
+ float max_radius = max(
+ max(surface.corner_radii.top_left, surface.corner_radii.top_right),
@@ -645,10 +1069,16 @@ index 97bad184dc..71a05aca4f 100644
+ return saturate(0.5 - distance);
+}
+
-@@ -892,0 +905,2 @@ fragment float4 surface_fragment(SurfaceFragmentInput input [[stage_in]],
+ fragment float4 surface_fragment(SurfaceFragmentInput input [[stage_in]],
+ constant SurfaceBounds *surfaces
+ [[buffer(SurfaceInputIndex_Surfaces)]],
-@@ -907 +921,15 @@ fragment float4 surface_fragment(SurfaceFragmentInput input [[stage_in]],
+ texture2d<float> y_texture
+ [[texture(SurfaceInputIndex_YTexture)]],
+ texture2d<float> cb_cr_texture
+@@ -904,7 +918,21 @@
+ y_texture.sample(texture_sampler, input.texture_position).r,
+ cb_cr_texture.sample(texture_sampler, input.texture_position).rg, 1.0);
+
- return ycbcrToRGBTransform * ycbcr;
+ float4 color = ycbcrToRGBTransform * ycbcr;
+ color.a *= surface_corner_alpha(input.position.xy, surfaces[0]);
@@ -665,18 +1095,36 @@ index 97bad184dc..71a05aca4f 100644
+ color_texture.sample(texture_sampler, input.texture_position).rgb, 1.0);
+ color.a *= surface_corner_alpha(input.position.xy, surfaces[0]);
+ return color;
+ }
+
+ float4 hsla_to_rgba(Hsla hsla) {
diff --git a/crates/gpui_macos/src/window.rs b/crates/gpui_macos/src/window.rs
-index 8a3aa5ea06..aacd697be5 100644
+index 8a3aa5ea067d..aacd697be58d 100644
--- a/crates/gpui_macos/src/window.rs
+++ b/crates/gpui_macos/src/window.rs
-@@ -7 +6,0 @@ use crate::{
+@@ -4,7 +4,6 @@
+ kTISPropertyInputSourceIsASCIICapable, kTISPropertyInputSourceType, kTISTypeKeyboardInputMode,
+ ns_string, renderer,
+ };
-#[cfg(any(test, feature = "test-support"))]
-@@ -776 +775,3 @@ impl MacWindow {
+ use anyhow::Result;
+ use block::ConcreteBlock;
+ use cocoa::{
+@@ -773,7 +772,9 @@
+ foreground_executor: ForegroundExecutor,
+ background_executor: BackgroundExecutor,
+ renderer_context: renderer::Context,
- ) -> Self {
+ ) -> Result<Self> {
+ let renderer =
+ objc::rc::autoreleasepool(|| renderer::new_renderer(renderer_context, false))?;
-@@ -896,7 +897 @@ impl MacWindow {
+ unsafe {
+ let pool = NSAutoreleasePool::new(nil);
+
+@@ -893,13 +894,7 @@
+ cursor_style: CursorStyle::Arrow,
+ cursor_visible,
+ frame_source: None,
- renderer: renderer::new_renderer(
- renderer_context,
- native_window as *mut _,
@@ -685,82 +1133,36 @@ index 8a3aa5ea06..aacd697be5 100644
- false,
- ),
+ renderer,
-@@ -1101 +1096 @@ impl MacWindow {
+ request_frame_callback: None,
+ event_callback: None,
+ activate_callback: None,
+@@ -1098,7 +1093,7 @@
+
+ pool.drain();
+
- window
+ Ok(window)
-@@ -3135 +3130,2 @@ unsafe fn remove_layer_background(layer: id) {
+ }
+ }
+
+@@ -3132,7 +3127,8 @@
+ let hit: BOOL = msg_send![description, containsString: blur_test];
+ if hit == YES {
+ let radius: id = msg_send![class!(NSNumber), numberWithDouble: 60.0f64];
- let _: () = msg_send![filter, setValue: radius forKey: ns_string("inputRadius")];
+ let _: () =
+ msg_send![filter, setValue: radius forKey: ns_string("inputRadius")];
-diff --git a/crates/gpui_windows/src/directx_atlas.rs b/crates/gpui_windows/src/directx_atlas.rs
---- a/crates/gpui_windows/src/directx_atlas.rs
-+++ b/crates/gpui_windows/src/directx_atlas.rs
-@@ -110,0 +111,9 @@ impl PlatformAtlas for DirectXAtlas {
-+ let cached_texture_index = if id.kind == AtlasTextureKind::Polychrome {
-+ textures.textures.iter().position(|entry| {
-+ entry
-+ .as_ref()
-+ .is_some_and(|entry| entry.live_atlas_keys == 0)
-+ })
-+ } else {
-+ None
-+ };
-@@ -119 +129,7 @@ impl PlatformAtlas for DirectXAtlas {
-- if texture.is_unreferenced() {
-+ if texture.is_unreferenced() && id.kind == AtlasTextureKind::Polychrome {
-+ *texture_slot = Some(texture);
-+ if let Some(index) = cached_texture_index {
-+ textures.textures[index] = None;
-+ textures.free_list.push(index);
-+ }
-+ } else if texture.is_unreferenced() {
-@@ -420 +435,33 @@ mod tests {
--}
-+
-+ #[test]
-+ fn test_reuses_one_unreferenced_polychrome_texture() {
-+ let Some(atlas) = create_atlas() else {
-+ return;
-+ };
-+
-+ let small = Size {
-+ width: DevicePixels(64),
-+ height: DevicePixels(64),
-+ };
-+ let large = Size {
-+ width: DevicePixels(1280),
-+ height: DevicePixels(720),
-+ };
-+ let small_key = make_image_key(10);
-+ let first_key = make_image_key(11);
-+ let second_key = make_image_key(12);
-+
-+ insert_tile(&atlas, &small_key, small);
-+ atlas.remove(&small_key);
-+ let first = insert_tile(&atlas, &first_key, large);
-+ atlas.remove(&first_key);
-+ let second = insert_tile(&atlas, &second_key, large);
-+
-+ assert_eq!(first.texture_id, second.texture_id);
-+ let state = atlas.0.lock();
-+ assert_eq!(
-+ state.polychrome_textures.textures.iter().flatten().count(),
-+ 1
-+ );
-+ }
-+}
-diff --git a/crates/gpui_macos/src/platform.rs b/crates/gpui_macos/src/platform.rs
-index b25067935e..c60ef0b4ec 100644
---- a/crates/gpui_macos/src/platform.rs
-+++ b/crates/gpui_macos/src/platform.rs
-@@ -669 +669 @@ impl Platform for MacPlatform {
-- )))
-+ )?))
+ let _: () = msg_send![layer, setFilters: filters];
+ break;
+ }
diff --git a/crates/gpui_platform/src/gpui_platform.rs b/crates/gpui_platform/src/gpui_platform.rs
-index 1d2fea90b4..c2e070e721 100644
+index 1d2fea90b477..c2e070e721fe 100644
--- a/crates/gpui_platform/src/gpui_platform.rs
+++ b/crates/gpui_platform/src/gpui_platform.rs
-@@ -67,3 +67,7 @@ pub fn current_headless_renderer() -> Option<Box<dyn gpui::PlatformHeadlessRende
+@@ -64,9 +64,13 @@
+ pub fn current_headless_renderer() -> Option<Box<dyn gpui::PlatformHeadlessRenderer>> {
+ #[cfg(target_os = "macos")]
+ {
- Some(Box::new(
- gpui_macos::metal_renderer::MetalHeadlessRenderer::new(),
- ))
@@ -771,3 +1173,117 @@ index 1d2fea90b4..c2e070e721 100644
+ None
+ }
+ }
+ }
+
+ #[cfg(not(target_os = "macos"))]
+diff --git a/crates/gpui_wgpu/src/wgpu_renderer.rs b/crates/gpui_wgpu/src/wgpu_renderer.rs
+index 587315debfa8..e58084906c1f 100644
+--- a/crates/gpui_wgpu/src/wgpu_renderer.rs
++++ b/crates/gpui_wgpu/src/wgpu_renderer.rs
+@@ -108,7 +108,7 @@
+ struct WgpuResources {
+ device: Arc<wgpu::Device>,
+ queue: Arc<wgpu::Queue>,
+- surface: wgpu::Surface<'static>,
++ surface: Option<wgpu::Surface<'static>>,
+ pipelines: WgpuPipelines,
+ bind_group_layouts: WgpuBindGroupLayouts,
+ atlas_sampler: wgpu::Sampler,
+@@ -449,7 +449,7 @@
+ let resources = WgpuResources {
+ device,
+ queue,
+- surface,
++ surface: Some(surface),
+ pipelines,
+ bind_group_layouts,
+ atlas_sampler,
+@@ -982,9 +982,9 @@
+ texture.destroy();
+ }
+
+- resources
+- .surface
+- .configure(&resources.device, &surface_config);
++ if let Some(surface) = &resources.surface {
++ surface.configure(&resources.device, &surface_config);
++ }
+
+ // Invalidate intermediate textures - they will be lazily recreated
+ // in draw() after we confirm the surface is healthy. This avoids
+@@ -1040,9 +1040,9 @@
+ let Some(resources) = self.resources.as_mut() else {
+ return;
+ };
+- resources
+- .surface
+- .configure(&resources.device, &surface_config);
++ if let Some(surface) = &resources.surface {
++ surface.configure(&resources.device, &surface_config);
++ }
+ resources.pipelines = Self::create_pipelines(
+ &resources.device,
+ &resources.bind_group_layouts,
+@@ -1118,24 +1118,30 @@
+
+ self.atlas.before_frame();
+
+- let frame = match self.resources().surface.get_current_texture() {
++ let frame = match self
++ .resources()
++ .surface
++ .as_ref()
++ .expect("Configured surface missing")
++ .get_current_texture()
++ {
+ wgpu::CurrentSurfaceTexture::Success(frame) => frame,
+ wgpu::CurrentSurfaceTexture::Suboptimal(frame) => {
+ // Textures must be destroyed before the surface can be reconfigured.
+ drop(frame);
+ let surface_config = self.surface_config.clone();
+ let resources = self.resources_mut();
+- resources
+- .surface
+- .configure(&resources.device, &surface_config);
++ if let Some(surface) = &resources.surface {
++ surface.configure(&resources.device, &surface_config);
++ }
+ return false;
+ }
+ wgpu::CurrentSurfaceTexture::Lost | wgpu::CurrentSurfaceTexture::Outdated => {
+ let surface_config = self.surface_config.clone();
+ let resources = self.resources_mut();
+- resources
+- .surface
+- .configure(&resources.device, &surface_config);
++ if let Some(surface) = &resources.surface {
++ surface.configure(&resources.device, &surface_config);
++ }
+ return false;
+ }
+ wgpu::CurrentSurfaceTexture::Timeout | wgpu::CurrentSurfaceTexture::Occluded => {
+@@ -1687,6 +1693,15 @@
+ })
+ }
+
++ /// Dropping the returned surface retires WSI presentation without discarding the atlas.
++ #[cfg(not(target_family = "wasm"))]
++ pub fn take_surface_for_visibility(&mut self) -> Option<wgpu::Surface<'static>> {
++ self.surface_configured = false;
++ self.resources
++ .as_mut()
++ .and_then(|resources| resources.surface.take())
++ }
++
+ /// Mark the surface as unconfigured so rendering is skipped until a new
+ /// surface is provided via [`replace_surface`](Self::replace_surface).
+ ///
+@@ -1745,7 +1760,7 @@
+ .as_mut()
+ .expect("GPU resources not available");
+ surface.configure(&res.device, &self.surface_config);
+- res.surface = surface;
++ res.surface = Some(surface);
+
+ // Invalidate intermediate textures — they'll be recreated lazily.
+ res.invalidate_intermediate_textures();
diff --git a/apps/desktop-gpui/patches/zed-linux.patch b/apps/desktop-gpui/patches/zed-linux.patch
index 93d8da1d6..0052e2c87 100644
--- a/apps/desktop-gpui/patches/zed-linux.patch
+++ b/apps/desktop-gpui/patches/zed-linux.patch
@@ -1,17 +1,226 @@
+diff --git a/crates/gpui_linux/src/linux/wayland/client.rs b/crates/gpui_linux/src/linux/wayland/client.rs
+index fdc40a3de87e..09c7fb416e8a 100644
+--- a/crates/gpui_linux/src/linux/wayland/client.rs
++++ b/crates/gpui_linux/src/linux/wayland/client.rs
+@@ -1301,6 +1301,25 @@
+ delegate_noop!(WaylandClientStatePtr: ignore wp_viewporter::WpViewporter);
+ delegate_noop!(WaylandClientStatePtr: ignore wp_viewport::WpViewport);
+
++impl Dispatch<WlCallback, super::window::VisibilitySync> for WaylandClientStatePtr {
++ fn event(
++ this: &mut WaylandClientStatePtr,
++ _: &WlCallback,
++ event: wl_callback::Event,
++ sync: &super::window::VisibilitySync,
++ _: &Connection,
++ _: &QueueHandle<Self>,
++ ) {
++ if let wl_callback::Event::Done { .. } = event {
++ let client = this.get_client();
++ let window = get_window(&mut client.borrow_mut(), &sync.surface);
++ if let Some(window) = window {
++ window.visibility_processed(sync);
++ }
++ }
++ }
++}
++
+ impl Dispatch<WlCallback, ObjectId> for WaylandClientStatePtr {
+ fn event(
+ state: &mut WaylandClientStatePtr,
diff --git a/crates/gpui_linux/src/linux/wayland/window.rs b/crates/gpui_linux/src/linux/wayland/window.rs
-index 993b2ff3fa..c59ee3927c 100644
+index 993b2ff3fadc..e8916c11025f 100644
--- a/crates/gpui_linux/src/linux/wayland/window.rs
+++ b/crates/gpui_linux/src/linux/wayland/window.rs
-@@ -112,0 +113,2 @@ pub struct WaylandWindowState {
+@@ -7,7 +7,7 @@
+ };
+
+ use collections::{FxHashMap, HashMap};
+-use futures::channel::oneshot::Receiver;
++use futures::{FutureExt, channel::oneshot::Receiver};
+
+ use raw_window_handle as rwh;
+ use wayland_backend::client::ObjectId;
+@@ -93,7 +93,126 @@
+ tiling: Tiling,
+ }
+
++#[derive(Clone, Copy, Debug, PartialEq, Eq)]
++enum VisibilityPhase {
++ Visible,
++ Draining(u64),
++ Unmapping(u64),
++ Hidden,
++ Configuring(u64),
++ Remapping(u64),
++}
++
++impl VisibilityPhase {
++ fn can_acknowledge_configure(self) -> bool {
++ !matches!(self, Self::Unmapping(_) | Self::Hidden)
++ }
++
++ fn can_draw(self, configured: bool) -> bool {
++ configured
++ && matches!(
++ self,
++ Self::Visible | Self::Configuring(_) | Self::Remapping(_)
++ )
++ }
++}
++
++struct RetainedVisibility {
++ sequence: u64,
++ desired: bool,
++ phase: VisibilityPhase,
++ waiter: Option<(
++ u64,
++ futures::channel::oneshot::Sender<anyhow::Result<(u64, bool)>>,
++ )>,
++}
++
++impl Default for RetainedVisibility {
++ fn default() -> Self {
++ Self {
++ sequence: 0,
++ desired: true,
++ phase: VisibilityPhase::Visible,
++ waiter: None,
++ }
++ }
++}
++
++impl RetainedVisibility {
++ fn request(&mut self, visible: bool) -> Receiver<anyhow::Result<(u64, bool)>> {
++ if let Some((_, waiter)) = self.waiter.take() {
++ let _ = waiter.send(Err(anyhow::anyhow!("Window visibility request superseded")));
++ }
++ self.sequence = self.sequence.wrapping_add(1);
++ self.desired = visible;
++ let (sender, receiver) = futures::channel::oneshot::channel();
++ self.waiter = Some((self.sequence, sender));
++ receiver
++ }
++
++ fn begin_unmap(&mut self) -> u64 {
++ self.sequence = self.sequence.wrapping_add(1);
++ let transition = self.sequence;
++ self.phase = VisibilityPhase::Draining(transition);
++ transition
++ }
++
++ fn complete(&mut self) {
++ let visible = self.phase == VisibilityPhase::Visible;
++ if !matches!(
++ self.phase,
++ VisibilityPhase::Visible | VisibilityPhase::Hidden
++ ) || visible != self.desired
++ {
++ return;
++ }
++ if let Some((generation, waiter)) = self.waiter.take() {
++ let _ = waiter.send(Ok((generation, visible)));
++ }
++ }
++
++ fn processed(&mut self, transition: u64, visible: bool) -> bool {
++ let expected = if visible {
++ VisibilityPhase::Remapping(transition)
++ } else {
++ VisibilityPhase::Unmapping(transition)
++ };
++ if self.phase != expected {
++ return false;
++ }
++ self.phase = if visible {
++ VisibilityPhase::Visible
++ } else {
++ VisibilityPhase::Hidden
++ };
++ true
++ }
++
++ fn fail_restore(&mut self, error: anyhow::Error) -> u64 {
++ self.fail(error);
++ self.desired = false;
++ self.begin_unmap()
++ }
++
++ fn fail(&mut self, error: anyhow::Error) {
++ if let Some((_, waiter)) = self.waiter.take() {
++ let _ = waiter.send(Err(error));
++ }
++ }
++}
++
++#[derive(Clone, Debug)]
++pub(crate) struct VisibilitySync {
++ pub surface: ObjectId,
++ pub transition: u64,
++ pub visible: bool,
++}
++
+ pub struct WaylandWindowState {
++ visibility: RetainedVisibility,
++ retiring_surface: Option<futures::future::Shared<gpui::Task<()>>>,
++ title: String,
++ minimum_size: Option<Size<Pixels>>,
+ surface_state: WaylandSurfaceState,
+ acknowledged_first_configure: bool,
+ parent: Option<WaylandWindowStatePtr>,
+@@ -110,6 +229,8 @@
+ globals: Globals,
+ renderer: WgpuRenderer,
+ bounds: Bounds<Pixels>,
+ fixed_outer_size: Option<Size<Pixels>>,
+ fixed_geometry_size: Option<Size<i32>>,
-@@ -594 +596 @@ impl WaylandWindowState {
+ scale: f32,
+ input_handler: Option<PlatformInputHandler>,
+ decorations: WindowDecorations,
+@@ -575,7 +696,11 @@
+ };
+
+ if let WaylandSurfaceState::Xdg(ref xdg_state) = surface_state {
+- if let Some(title) = options.titlebar.and_then(|titlebar| titlebar.title) {
++ if let Some(title) = options
++ .titlebar
++ .as_ref()
++ .and_then(|titlebar| titlebar.title.as_ref())
++ {
+ xdg_state.toplevel.set_title(title.to_string());
+ }
+
+@@ -591,7 +716,16 @@
+ .set_max_size(max_texture_size, max_texture_size);
+ }
+
- Ok(Self {
+ let mut state = Self {
-@@ -607,0 +610,2 @@ impl WaylandWindowState {
++ visibility: RetainedVisibility::default(),
++ retiring_surface: None,
++ title: options
++ .titlebar
++ .as_ref()
++ .and_then(|titlebar| titlebar.title.as_ref())
++ .map(ToString::to_string)
++ .unwrap_or_default(),
++ minimum_size: options.window_min_size,
+ surface_state,
+ acknowledged_first_configure: false,
+ parent,
+@@ -605,6 +739,8 @@
+ display: None,
+ renderer,
+ bounds: options.bounds,
+ fixed_outer_size: (!options.is_resizable).then_some(options.bounds.size),
+ fixed_geometry_size: None,
-@@ -629 +633,24 @@ impl WaylandWindowState {
+ scale: 1.0,
+ input_handler: None,
+ decorations: WindowDecorations::Client,
+@@ -626,7 +762,30 @@
+ window_controls: WindowControls::default(),
+ client_inset: None,
+ accesskit_adapter: None,
- })
+ };
+ state.update_size_constraints();
@@ -37,44 +246,458 @@ index 993b2ff3fa..c59ee3927c 100644
+ toplevel.set_max_size(geometry_size.width, geometry_size.height);
+ self.fixed_geometry_size = Some(geometry_size);
+ }
-@@ -903,0 +931 @@ impl WaylandWindowStatePtr {
+ }
+
+ pub fn is_transparent(&self) -> bool {
+@@ -680,6 +839,34 @@
+ impl Drop for WaylandWindow {
+ fn drop(&mut self) {
+ let mut state = self.0.state.borrow_mut();
++ state.visibility.fail(anyhow::anyhow!(
++ "Window closed during visibility transition"
++ ));
++ state.visibility.phase = VisibilityPhase::Hidden;
++ let retirement = state.retiring_surface.take();
++ let executor = state.globals.executor.clone();
++ drop(state);
++ if let Some(retirement) = retirement {
++ let window = self.0.clone();
++ executor
++ .spawn(async move {
++ retirement.await;
++ window.destroy_window();
++ })
++ .detach();
++ } else {
++ self.0.destroy_window();
++ }
++ }
++}
++
++impl WaylandWindowStatePtr {
++ fn destroy_window(&self) {
++ let mut state = self.state.borrow_mut();
++ state.visibility.fail(anyhow::anyhow!(
++ "Window closed during visibility transition"
++ ));
++ state.visibility.phase = VisibilityPhase::Hidden;
+ let surface_id = state.surface.id();
+ if let Some(parent) = state.parent.as_ref() {
+ parent.state.borrow_mut().children.remove(&surface_id);
+@@ -713,7 +900,7 @@
+ // The wl_surface itself should always be destroyed last.
+ state.surface.destroy();
+
+- let state_ptr = self.0.clone();
++ let state_ptr = self.clone();
+ state
+ .globals
+ .executor
+@@ -838,8 +1025,153 @@
+ state.children.values().any(|&blocking| blocking)
+ }
+
++ fn visibility_supported(&self) -> bool {
++ let state = self.state.borrow();
++ matches!(&state.surface_state, WaylandSurfaceState::Xdg(xdg) if xdg.dialog.is_none())
++ && state.children.is_empty()
++ }
++
++ fn request_visibility(
++ &self,
++ visible: bool,
++ ) -> anyhow::Result<Receiver<anyhow::Result<(u64, bool)>>> {
++ anyhow::ensure!(
++ self.visibility_supported(),
++ "Close child dialogs and popups before hiding this window"
++ );
++ let receiver = self.state.borrow_mut().visibility.request(visible);
++ self.advance_visibility();
++ Ok(receiver)
++ }
++
++ fn visibility_sync(state: &WaylandWindowState, transition: u64, visible: bool) {
++ let connection = wayland_client::Connection::from_backend(
++ state
++ .surface
++ .backend()
++ .upgrade()
++ .expect("Live surface connection required"),
++ );
++ connection.display().sync(
++ &state.globals.qh,
++ VisibilitySync {
++ surface: state.surface.id(),
++ transition,
++ visible,
++ },
++ );
++ }
++
++ fn unmap_surface(&self, transition: u64) {
++ let mut state = self.state.borrow_mut();
++ let surface = state.renderer.take_surface_for_visibility();
++ let background = state
++ .client
++ .get_client()
++ .borrow()
++ .common
++ .background_executor
++ .clone();
++ let foreground = state.globals.executor.clone();
++ let window = self.clone();
++ let retirement = background
++ .spawn(async move {
++ drop(surface);
++ })
++ .shared();
++ state.retiring_surface = Some(retirement.clone());
++ drop(state);
++ foreground
++ .spawn(async move {
++ retirement.await;
++ let mut state = window.state.borrow_mut();
++ state.retiring_surface = None;
++ if state.visibility.phase != VisibilityPhase::Draining(transition) {
++ return;
++ }
++ state.surface.attach(None, 0, 0);
++ state.surface.commit();
++ state.visibility.phase = VisibilityPhase::Unmapping(transition);
++ Self::visibility_sync(&state, transition, false);
++ })
++ .detach();
++ }
++
++ fn advance_visibility(&self) {
++ let mut state = self.state.borrow_mut();
++ state.visibility.complete();
++ match (state.visibility.phase, state.visibility.desired) {
++ (VisibilityPhase::Visible, false) => {
++ let transition = state.visibility.begin_unmap();
++ drop(state);
++ self.unmap_surface(transition);
++ }
++ (VisibilityPhase::Hidden, true) => {
++ state.visibility.sequence = state.visibility.sequence.wrapping_add(1);
++ let transition = state.visibility.sequence;
++ state.visibility.phase = VisibilityPhase::Configuring(transition);
++ state.acknowledged_first_configure = false;
++ state.in_progress_configure = None;
++ state.renderer_presented = false;
++ state.resize_throttle = false;
++ state.fixed_geometry_size = None;
++ if let WaylandSurfaceState::Xdg(xdg) = &state.surface_state {
++ xdg.toplevel.set_title(state.title.clone());
++ if let Some(app_id) = &state.app_id {
++ xdg.toplevel.set_app_id(app_id.clone());
++ }
++ let parent = state.parent.as_ref().and_then(|parent| parent.toplevel());
++ xdg.toplevel.set_parent(parent.as_ref());
++ if let Some(minimum) = state.minimum_size {
++ xdg.toplevel.set_min_size(
++ f32::from(minimum.width) as i32,
++ f32::from(minimum.height) as i32,
++ );
++ }
++ let maximum = state.renderer.max_texture_size() as i32;
++ xdg.toplevel.set_max_size(maximum, maximum);
++ if state.maximized {
++ xdg.toplevel.set_maximized();
++ }
++ if state.fullscreen {
++ xdg.toplevel.set_fullscreen(None);
++ }
++ if let Some(decoration) = &xdg.decoration {
++ decoration.set_mode(state.decorations.to_xdg());
++ }
++ }
++ state.update_size_constraints();
++ state.surface.commit();
++ }
++ _ => {}
++ }
++ }
++
++ pub(crate) fn visibility_processed(&self, sync: &VisibilitySync) {
++ let mut state = self.state.borrow_mut();
++ if state.surface.id() != sync.surface
++ || !state.visibility.processed(sync.transition, sync.visible)
++ {
++ return;
++ }
++ if !sync.visible {
++ state.acknowledged_first_configure = false;
++ state.in_progress_configure = None;
++ state.renderer_presented = false;
++ }
++ drop(state);
++ self.advance_visibility();
++ }
++
+ pub fn frame(&self) {
+ let mut state = self.state.borrow_mut();
++ if !state
++ .visibility
++ .phase
++ .can_draw(state.acknowledged_first_configure)
++ {
++ return;
++ }
+ state.surface.frame(&state.globals.qh, state.surface.id());
+ state.resize_throttle = false;
+ let force_render = state.force_render_after_recovery;
+@@ -882,6 +1214,17 @@
+ pub fn handle_xdg_surface_event(&self, event: xdg_surface::Event) {
+ if let xdg_surface::Event::Configure { serial } = event {
+ {
++ let state = self.state.borrow();
++ // The null-buffer commit invalidates old serials before its sync callback arrives.
++ if !state.visibility.phase.can_acknowledge_configure() {
++ return;
++ }
++ if matches!(state.visibility.phase, VisibilityPhase::Draining(_)) {
++ state.surface_state.ack_configure(serial);
++ return;
++ }
++ }
++ {
+ let mut state = self.state.borrow_mut();
+ if let Some(window_controls) = state.in_progress_window_controls.take() {
+ state.window_controls = window_controls;
+@@ -901,6 +1244,7 @@
+ state.fullscreen = configure.fullscreen;
+ state.maximized = configure.maximized;
+ state.tiling = configure.tiling;
+ state.update_size_constraints();
-@@ -961 +989,5 @@ impl WaylandWindowStatePtr {
+ // Limit interactive resizes to once per vblank
+ if configure.resizing && state.resize_throttle {
+ state.surface_state.ack_configure(serial);
+@@ -945,6 +1289,43 @@
+ window_geometry.size.height,
+ );
+
++ if matches!(state.visibility.phase, VisibilityPhase::Configuring(_))
++ && !state.acknowledged_first_configure
++ {
++ let raw = RawWindow {
++ window: state.surface.id().as_ptr().cast::<c_void>(),
++ display: state
++ .surface
++ .backend()
++ .upgrade()
++ .unwrap()
++ .display_ptr()
++ .cast::<c_void>(),
++ };
++ let result = if state.renderer.device_lost() {
++ state.renderer.recover(&raw)
++ } else {
++ let gpu = state.client.get_client().borrow().gpu_context.clone();
++ let gpu = gpu.borrow();
++ gpu.as_ref()
++ .ok_or_else(|| anyhow::anyhow!("GPU unavailable during window restore"))
++ .and_then(|gpu| {
++ let config = WgpuSurfaceConfig {
++ size: state.renderer.viewport_size(),
++ transparent: state.is_transparent(),
++ preferred_present_mode: Some(wgpu::PresentMode::Mailbox),
++ };
++ state.renderer.replace_surface(&raw, config, &gpu.instance)
++ })
++ };
++ if let Err(error) = result {
++ let transition = state.visibility.fail_restore(error);
++ drop(state);
++ self.unmap_surface(transition);
++ return;
++ }
++ state.force_render_after_recovery = true;
++ }
+ let request_frame_callback = !state.acknowledged_first_configure;
+ if request_frame_callback {
+ state.acknowledged_first_configure = true;
+@@ -958,7 +1339,11 @@
+ if let zxdg_toplevel_decoration_v1::Event::Configure { mode } = event {
+ match mode {
+ WEnum::Value(zxdg_toplevel_decoration_v1::Mode::ServerSide) => {
- self.state.borrow_mut().decorations = WindowDecorations::Server;
+ {
+ let mut state = self.state.borrow_mut();
+ state.decorations = WindowDecorations::Server;
+ state.update_size_constraints();
+ }
-@@ -969 +1001,5 @@ impl WaylandWindowStatePtr {
+ let callback = self.callbacks.borrow_mut().appearance_changed.take();
+ if let Some(mut fun) = callback {
+ fun();
+@@ -966,7 +1351,11 @@
+ }
+ }
+ WEnum::Value(zxdg_toplevel_decoration_v1::Mode::ClientSide) => {
- self.state.borrow_mut().decorations = WindowDecorations::Client;
+ {
+ let mut state = self.state.borrow_mut();
+ state.decorations = WindowDecorations::Client;
+ state.update_size_constraints();
+ }
-@@ -1273,0 +1310 @@ impl WaylandWindowStatePtr {
+ // Update background to be transparent
+ let callback = self.callbacks.borrow_mut().appearance_changed.take();
+ if let Some(mut fun) = callback {
+@@ -1271,6 +1660,7 @@
+ }
+ if let Some(scale) = scale {
+ state.scale = scale;
+ state.update_size_constraints();
-@@ -1469 +1506 @@ impl PlatformWindow for WaylandWindow {
+ }
+ let device_bounds = state.bounds.to_device_pixels(state.scale);
+ state.renderer.update_drawable_size(device_bounds.size);
+@@ -1466,7 +1856,7 @@
+ }
+
+ fn resize(&mut self, size: Size<Pixels>) {
- let state = self.borrow();
+ let mut state = self.borrow_mut();
-@@ -1488,0 +1526,5 @@ impl PlatformWindow for WaylandWindow {
+ let state_ptr = self.0.clone();
+
+ // A popup's placement is the compositor's, so a resize re-runs the positioner and the
+@@ -1486,6 +1876,11 @@
+ return;
+ }
+
+ if state.fixed_outer_size.is_some() {
+ state.fixed_outer_size = Some(size);
+ state.update_size_constraints();
+ }
+
-@@ -1778,0 +1821,3 @@ impl PlatformWindow for WaylandWindow {
+ // Keep window geometry consistent with configure handling. On Wayland, window geometry is
+ // surface-local: resizing should not attempt to translate the window; the compositor
+ // controls placement. We also account for client-side decoration insets and tiling.
+@@ -1566,6 +1961,20 @@
+ _answers: &[PromptButton],
+ ) -> Option<Receiver<usize>> {
+ None
++ }
++
++ fn retained_visibility(&self) -> Option<bool> {
++ self.0.visibility_supported().then(|| {
++ let state = self.borrow();
++ state.visibility.phase == VisibilityPhase::Visible && state.acknowledged_first_configure
++ })
++ }
++
++ fn set_retained_visibility(
++ &self,
++ visible: bool,
++ ) -> anyhow::Result<Receiver<anyhow::Result<(u64, bool)>>> {
++ self.0.request_visibility(visible)
+ }
+
+ fn activate(&self) {
+@@ -1596,7 +2005,9 @@
+ }
+
+ fn set_title(&mut self, title: &str) {
+- if let Some(toplevel) = self.borrow().surface_state.toplevel() {
++ let mut state = self.borrow_mut();
++ state.title = title.to_owned();
++ if let Some(toplevel) = state.surface_state.toplevel() {
+ toplevel.set_title(title.to_string());
+ }
+ }
+@@ -1706,6 +2117,13 @@
+
+ fn draw(&self, scene: &Scene) {
+ let mut state = self.borrow_mut();
++ if !state
++ .visibility
++ .phase
++ .can_draw(state.acknowledged_first_configure)
++ {
++ return;
++ }
+
+ if state.renderer.device_lost() {
+ let raw_window = RawWindow {
+@@ -1730,6 +2148,12 @@
+ }
+
+ state.renderer_presented = state.renderer.draw(scene);
++ if state.renderer_presented
++ && let VisibilityPhase::Configuring(transition) = state.visibility.phase
++ {
++ state.visibility.phase = VisibilityPhase::Remapping(transition);
++ WaylandWindowStatePtr::visibility_sync(&state, transition, true);
++ }
+
+ if state.renderer.needs_redraw() {
+ state.force_render_after_recovery = true;
+@@ -1738,6 +2162,13 @@
+
+ fn completed_frame(&self) {
+ let mut state = self.borrow_mut();
++ if !state
++ .visibility
++ .phase
++ .can_draw(state.acknowledged_first_configure)
++ {
++ return;
++ }
+
+ // Work around a bug in old versions of wlroots where committing without a buffer attached
+ // can cause invalid synchronization that leads to graphical corruption.
+@@ -1776,6 +2207,9 @@
+
+ fn start_window_resize(&self, edge: gpui::ResizeEdge) {
+ let state = self.borrow();
+ if state.fixed_outer_size.is_some() {
+ return;
+ }
-@@ -1856,0 +1902 @@ impl PlatformWindow for WaylandWindow {
+ if let Some(toplevel) = state.surface_state.toplevel() {
+ toplevel.resize(
+ &state.globals.seat,
+@@ -1835,7 +2269,13 @@
+ // Commit so the new input region applies immediately. Otherwise it
+ // waits for the next frame, which could be the very click we want to
+ // allow passing through.
+- state.surface.commit();
++ if state
++ .visibility
++ .phase
++ .can_draw(state.acknowledged_first_configure)
++ {
++ state.surface.commit();
++ }
+ }
+
+ fn window_decorations(&self) -> Decorations {
+@@ -1854,6 +2294,7 @@
+ Some(decoration) => {
+ decoration.set_mode(decorations.to_xdg());
+ state.decorations = decorations;
+ state.update_size_constraints();
-@@ -1865,0 +1912 @@ impl PlatformWindow for WaylandWindow {
+ update_window(state);
+ }
+ None => {
+@@ -1863,6 +2304,7 @@
+ );
+ }
+ state.decorations = WindowDecorations::Client;
+ state.update_size_constraints();
-@@ -1878,0 +1926 @@ impl PlatformWindow for WaylandWindow {
+ update_window(state);
+ }
+ }
+@@ -1876,6 +2318,7 @@
+ let mut state = self.borrow_mut();
+ if Some(inset) != state.client_inset {
+ state.client_inset = Some(inset);
+ state.update_size_constraints();
-@@ -2084,0 +2133,90 @@ fn inset_by_tiling(mut bounds: Bounds<Pixels>, inset: Pixels, tiling: Tiling) ->
+ update_window(state);
+ }
+ }
+@@ -2082,3 +2525,337 @@
+
+ bounds
+ }
+
+fn fixed_window_geometry_size(
+ outer_size: Size<Pixels>,
@@ -165,3 +788,247 @@ index 993b2ff3fa..c59ee3927c 100644
+ );
+ }
+}
++
++#[cfg(test)]
++mod retained_visibility_tests {
++ use super::{RetainedVisibility, VisibilityPhase};
++ use futures::executor::block_on;
++
++ #[test]
++ fn configure_acknowledgements_remain_valid_while_draining() {
++ assert!(VisibilityPhase::Visible.can_acknowledge_configure());
++ assert!(VisibilityPhase::Draining(1).can_acknowledge_configure());
++ assert!(!VisibilityPhase::Draining(1).can_draw(true));
++ }
++
++ #[test]
++ fn queued_configures_are_discarded_after_the_unmap_commit() {
++ for phase in [VisibilityPhase::Unmapping(1), VisibilityPhase::Hidden] {
++ assert!(!phase.can_acknowledge_configure());
++ assert!(!phase.can_draw(true));
++ }
++ }
++
++ #[test]
++ fn a_fresh_restore_configure_is_required_before_drawing() {
++ for phase in [
++ VisibilityPhase::Configuring(2),
++ VisibilityPhase::Remapping(2),
++ ] {
++ assert!(phase.can_acknowledge_configure());
++ assert!(!phase.can_draw(false));
++ assert!(phase.can_draw(true));
++ }
++ }
++
++ #[test]
++ fn normal_unmap_still_begins_draining_before_acknowledgement() {
++ let mut visibility = RetainedVisibility::default();
++ let mut hidden = visibility.request(false);
++ let transition = visibility.begin_unmap();
++
++ assert_eq!(transition, 2);
++ assert_eq!(visibility.phase, VisibilityPhase::Draining(transition));
++ assert!(visibility.phase.can_acknowledge_configure());
++ assert!(!visibility.phase.can_draw(true));
++ visibility.complete();
++ assert!(hidden.try_recv().unwrap().is_none());
++ assert!(!visibility.processed(transition, false));
++
++ visibility.phase = VisibilityPhase::Unmapping(transition);
++ assert!(visibility.processed(transition, false));
++ visibility.complete();
++ assert_eq!(block_on(hidden).unwrap().unwrap(), (1, false));
++ }
++
++ #[test]
++ fn failed_restore_reports_error_and_unmaps_without_automatic_retry() {
++ let mut visibility = RetainedVisibility {
++ sequence: 2,
++ phase: VisibilityPhase::Configuring(2),
++ ..Default::default()
++ };
++ let shown = visibility.request(true);
++ let transition = visibility.fail_restore(anyhow::anyhow!("transient renderer failure"));
++
++ assert_eq!(
++ block_on(shown).unwrap().unwrap_err().to_string(),
++ "transient renderer failure"
++ );
++ assert_eq!(visibility.phase, VisibilityPhase::Draining(transition));
++ assert!(!visibility.desired);
++ assert!(!visibility.phase.can_draw(true));
++ assert!(!visibility.processed(transition, false));
++
++ visibility.phase = VisibilityPhase::Unmapping(transition);
++ assert!(!visibility.phase.can_acknowledge_configure());
++ assert!(visibility.processed(transition, false));
++ visibility.complete();
++ assert_eq!(visibility.phase, VisibilityPhase::Hidden);
++ assert!(!visibility.desired);
++ assert!(visibility.waiter.is_none());
++ }
++
++ #[test]
++ fn show_after_restore_failure_waits_for_unmap_and_fresh_presentation() {
++ let mut visibility = RetainedVisibility {
++ sequence: 2,
++ phase: VisibilityPhase::Configuring(2),
++ ..Default::default()
++ };
++ let failed = visibility.request(true);
++ let unmap = visibility.fail_restore(anyhow::anyhow!("transient renderer failure"));
++ assert!(block_on(failed).unwrap().is_err());
++ let mut shown = visibility.request(true);
++ visibility.complete();
++ assert!(shown.try_recv().unwrap().is_none());
++ assert!(!visibility.processed(unmap, true));
++
++ visibility.phase = VisibilityPhase::Unmapping(unmap);
++ assert!(visibility.processed(unmap, false));
++ visibility.complete();
++ assert_eq!(visibility.phase, VisibilityPhase::Hidden);
++ assert!(visibility.desired);
++ assert!(shown.try_recv().unwrap().is_none());
++
++ visibility.sequence = visibility.sequence.wrapping_add(1);
++ let remap = visibility.sequence;
++ visibility.phase = VisibilityPhase::Configuring(remap);
++ assert!(!visibility.phase.can_draw(false));
++ assert!(!visibility.processed(remap, true));
++ visibility.complete();
++ assert!(shown.try_recv().unwrap().is_none());
++
++ visibility.phase = VisibilityPhase::Remapping(remap);
++ assert!(visibility.processed(remap, true));
++ visibility.complete();
++ assert_eq!(block_on(shown).unwrap().unwrap(), (5, true));
++ }
++
++ #[test]
++ fn hide_after_restore_failure_waits_for_the_cleanup_sync() {
++ let mut visibility = RetainedVisibility {
++ sequence: 2,
++ phase: VisibilityPhase::Configuring(2),
++ ..Default::default()
++ };
++ let failed = visibility.request(true);
++ let transition = visibility.fail_restore(anyhow::anyhow!("transient renderer failure"));
++ assert!(block_on(failed).unwrap().is_err());
++ let mut hidden = visibility.request(false);
++
++ visibility.complete();
++ assert!(hidden.try_recv().unwrap().is_none());
++ assert!(!visibility.processed(transition, false));
++ visibility.phase = VisibilityPhase::Unmapping(transition);
++ assert!(visibility.processed(transition, false));
++ visibility.complete();
++ assert_eq!(block_on(hidden).unwrap().unwrap(), (5, false));
++ }
++
++ #[test]
++ fn repeated_restore_failures_require_new_explicit_requests() {
++ let mut visibility = RetainedVisibility {
++ phase: VisibilityPhase::Hidden,
++ desired: false,
++ ..Default::default()
++ };
++
++ for _ in 0..3 {
++ let shown = visibility.request(true);
++ visibility.sequence = visibility.sequence.wrapping_add(1);
++ visibility.phase = VisibilityPhase::Configuring(visibility.sequence);
++ let transition = visibility.fail_restore(anyhow::anyhow!("renderer still unavailable"));
++ assert!(block_on(shown).unwrap().is_err());
++ assert!(!visibility.desired);
++ assert!(visibility.waiter.is_none());
++
++ visibility.phase = VisibilityPhase::Unmapping(transition);
++ assert!(visibility.processed(transition, false));
++ visibility.complete();
++ assert_eq!(visibility.phase, VisibilityPhase::Hidden);
++ assert!(!visibility.desired);
++ assert!(visibility.waiter.is_none());
++ }
++ }
++
++ #[test]
++ fn unmap_receipt_waits_for_matching_compositor_transition() {
++ let mut visibility = RetainedVisibility::default();
++ let mut receipt = visibility.request(false);
++ visibility.phase = VisibilityPhase::Unmapping(2);
++ visibility.complete();
++ assert!(receipt.try_recv().unwrap().is_none());
++ assert!(!visibility.processed(1, false));
++ assert!(!visibility.processed(2, true));
++ assert!(visibility.processed(2, false));
++ visibility.complete();
++ assert_eq!(block_on(receipt).unwrap().unwrap(), (1, false));
++ }
++
++ #[test]
++ fn hide_then_restore_keeps_physical_unmap_before_remap() {
++ let mut visibility = RetainedVisibility::default();
++ let hidden = visibility.request(false);
++ visibility.phase = VisibilityPhase::Unmapping(2);
++ let mut shown = visibility.request(true);
++ assert!(block_on(hidden).unwrap().is_err());
++ assert!(visibility.processed(2, false));
++ visibility.complete();
++ assert!(shown.try_recv().unwrap().is_none());
++ visibility.phase = VisibilityPhase::Remapping(4);
++ assert!(visibility.processed(4, true));
++ visibility.complete();
++ assert_eq!(block_on(shown).unwrap().unwrap(), (2, true));
++ }
++
++ #[test]
++ fn configure_without_first_present_cannot_acknowledge_restore() {
++ let mut visibility = RetainedVisibility {
++ phase: VisibilityPhase::Hidden,
++ desired: false,
++ ..Default::default()
++ };
++ let mut shown = visibility.request(true);
++ visibility.phase = VisibilityPhase::Configuring(2);
++ assert!(!visibility.processed(2, true));
++ visibility.complete();
++ assert!(shown.try_recv().unwrap().is_none());
++ visibility.phase = VisibilityPhase::Remapping(2);
++ assert!(visibility.processed(2, true));
++ visibility.complete();
++ assert!(block_on(shown).unwrap().unwrap().1);
++ }
++
++ #[test]
++ fn queued_draw_and_completed_frame_are_blocked_through_unmap() {
++ for phase in [
++ VisibilityPhase::Draining(1),
++ VisibilityPhase::Unmapping(1),
++ VisibilityPhase::Hidden,
++ ] {
++ assert!(!phase.can_draw(true));
++ assert!(!phase.can_draw(false));
++ }
++ assert!(!VisibilityPhase::Configuring(1).can_draw(false));
++ assert!(VisibilityPhase::Configuring(1).can_draw(true));
++ }
++
++ #[test]
++ fn close_never_fabricates_a_visibility_acknowledgement() {
++ let mut visibility = RetainedVisibility::default();
++ let receipt = visibility.request(false);
++ visibility.fail(anyhow::anyhow!("window closed"));
++ assert!(block_on(receipt).unwrap().is_err());
++ }
++
++ #[test]
++ fn a_late_unmap_cannot_override_a_new_remap() {
++ let mut visibility = RetainedVisibility {
++ phase: VisibilityPhase::Remapping(8),
++ ..Default::default()
++ };
++ assert!(!visibility.processed(6, false));
++ assert_eq!(visibility.phase, VisibilityPhase::Remapping(8));
++ }
++}
diff --git a/apps/desktop-gpui/patches/zed-windows.patch b/apps/desktop-gpui/patches/zed-windows.patch
index 856b1cbd6..df95e6d8e 100644
--- a/apps/desktop-gpui/patches/zed-windows.patch
+++ b/apps/desktop-gpui/patches/zed-windows.patch
@@ -1,6 +1,84 @@
+diff --git a/crates/gpui_windows/src/directx_atlas.rs b/crates/gpui_windows/src/directx_atlas.rs
+index 62386997f5ef..d49ec1836eae 100644
+--- a/crates/gpui_windows/src/directx_atlas.rs
++++ b/crates/gpui_windows/src/directx_atlas.rs
+@@ -108,6 +108,15 @@
+ AtlasTextureKind::Polychrome => &mut lock.polychrome_textures,
+ AtlasTextureKind::Subpixel => &mut lock.subpixel_textures,
+ };
++ let cached_texture_index = if id.kind == AtlasTextureKind::Polychrome {
++ textures.textures.iter().position(|entry| {
++ entry
++ .as_ref()
++ .is_some_and(|entry| entry.live_atlas_keys == 0)
++ })
++ } else {
++ None
++ };
+
+ let Some(texture_slot) = textures.textures.get_mut(id.index as usize) else {
+ return;
+@@ -116,7 +125,13 @@
+ if let Some(mut texture) = texture_slot.take() {
+ texture.allocator.deallocate(tile.tile_id.into());
+ texture.decrement_ref_count();
+- if texture.is_unreferenced() {
++ if texture.is_unreferenced() && id.kind == AtlasTextureKind::Polychrome {
++ *texture_slot = Some(texture);
++ if let Some(index) = cached_texture_index {
++ textures.textures[index] = None;
++ textures.free_list.push(index);
++ }
++ } else if texture.is_unreferenced() {
+ textures.free_list.push(texture.id.index as usize);
+ } else {
+ *texture_slot = Some(texture);
+@@ -417,4 +432,36 @@
+ let tile_b = insert_tile(&atlas, &big_key_b, big);
+ assert_eq!(tile_b.texture_id, keeper_tile.texture_id);
+ }
+-}
++
++ #[test]
++ fn test_reuses_one_unreferenced_polychrome_texture() {
++ let Some(atlas) = create_atlas() else {
++ return;
++ };
++
++ let small = Size {
++ width: DevicePixels(64),
++ height: DevicePixels(64),
++ };
++ let large = Size {
++ width: DevicePixels(1280),
++ height: DevicePixels(720),
++ };
++ let small_key = make_image_key(10);
++ let first_key = make_image_key(11);
++ let second_key = make_image_key(12);
++
++ insert_tile(&atlas, &small_key, small);
++ atlas.remove(&small_key);
++ let first = insert_tile(&atlas, &first_key, large);
++ atlas.remove(&first_key);
++ let second = insert_tile(&atlas, &second_key, large);
++
++ assert_eq!(first.texture_id, second.texture_id);
++ let state = atlas.0.lock();
++ assert_eq!(
++ state.polychrome_textures.textures.iter().flatten().count(),
++ 1
++ );
++ }
++}
+diff --git a/crates/gpui_windows/src/directx_renderer.rs b/crates/gpui_windows/src/directx_renderer.rs
+index 8a350682e239..35b504e0fb09 100644
--- a/crates/gpui_windows/src/directx_renderer.rs
+++ b/crates/gpui_windows/src/directx_renderer.rs
-@@ -1985,0 +1986,38 @@
+@@ -1983,3 +1983,41 @@
+ ))
+ }
+ }
+
+#[cfg(test)]
+mod tests {
@@ -39,9 +117,154 @@
+ }
+ }
+}
+diff --git a/crates/gpui_windows/src/events.rs b/crates/gpui_windows/src/events.rs
+index b293763bd9ed..07e584557093 100644
+--- a/crates/gpui_windows/src/events.rs
++++ b/crates/gpui_windows/src/events.rs
+@@ -714,6 +714,18 @@
+ return None;
+ }
+
++ if self.custom_frame && !self.state.is_maximized() {
++ let dpi = unsafe { GetDpiForWindow(handle) };
++ let (frame, top) =
++ custom_frame_insets(get_frame_thicknessx(dpi), dpi, windows_build_number());
++ let params = unsafe { &mut *(lparam.0 as *mut NCCALCSIZE_PARAMS) };
++ params.rgrc[0].left += frame;
++ params.rgrc[0].top += top;
++ params.rgrc[0].right -= frame;
++ params.rgrc[0].bottom -= frame;
++ return Some(0);
++ }
++
+ unsafe {
+ let params = lparam.0 as *mut NCCALCSIZE_PARAMS;
+ let saved_top = (*params).rgrc[0].top;
+@@ -844,20 +856,12 @@
+ .context("unable to set maximized window position after dpi has changed")
+ .log_err();
+ }
+-
+- // SetWindowPos may not send WM_SIZE for maximized windows in some cases,
+- // so we manually update the size to ensure proper rendering
+- let device_size = size(DevicePixels(width), DevicePixels(height));
+- self.handle_size_change(device_size, new_scale_factor, true);
+ }
+ } else {
+ // For non-maximized windows, use the suggested RECT from the system
+ let rect = unsafe { &*(lparam.0 as *const RECT) };
+ let width = rect.right - rect.left;
+ let height = rect.bottom - rect.top;
+- // this will emit `WM_SIZE` and `WM_MOVE` right here
+- // even before this function returns
+- // the new size is handled in `WM_SIZE`
+ unsafe {
+ SetWindowPos(
+ handle,
+@@ -871,6 +875,21 @@
+ .context("unable to set window position after dpi has changed")
+ .log_err();
+ }
++ }
++
++ // SetWindowPos can omit a final WM_SIZE; its outer bounds also include native captions.
++ let mut client_rect = RECT::default();
++ if !unsafe { IsIconic(handle) }.as_bool()
++ && unsafe { GetClientRect(handle, &mut client_rect) }
++ .context("unable to get client bounds after dpi has changed")
++ .log_err()
++ .is_some()
++ {
++ let device_size = size(
++ DevicePixels((client_rect.right - client_rect.left).max(1)),
++ DevicePixels((client_rect.bottom - client_rect.top).max(1)),
++ );
++ self.handle_size_change(device_size, self.state.scale_factor.get(), true);
+ }
+
+ Some(0)
+@@ -1650,6 +1669,32 @@
+ Capslock { on }
+ }
+
++fn custom_frame_insets(frame: i32, dpi: u32, windows_build: u32) -> (i32, i32) {
++ let top = if windows_build >= 22000 {
++ (dpi as f32 / 96.).round() as i32
++ } else {
++ 0
++ };
++ (frame, top)
++}
++
++fn windows_build_number() -> u32 {
++ use windows::Win32::System::SystemInformation::OSVERSIONINFOW;
++
++ static BUILD: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
++ *BUILD.get_or_init(|| {
++ let mut version = OSVERSIONINFOW {
++ dwOSVersionInfoSize: std::mem::size_of::<OSVERSIONINFOW>() as u32,
++ ..Default::default()
++ };
++ if unsafe { windows::Wdk::System::SystemServices::RtlGetVersion(&mut version) }.is_ok() {
++ version.dwBuildNumber
++ } else {
++ 0
++ }
++ })
++}
++
+ // there is some additional non-visible space when talking about window
+ // borders on Windows:
+ // - SM_CXSIZEFRAME: The resize handle.
+@@ -1688,3 +1733,40 @@
+ .log_err();
+ }
+ }
++
++#[cfg(test)]
++mod tests {
++ use super::custom_frame_insets;
++
++ #[test]
++ fn windows_10_has_no_top_inset_at_any_scale() {
++ for build in [19045, 21999] {
++ for (frame, dpi) in [(8, 96), (10, 120), (12, 144), (16, 192), (24, 288)] {
++ assert_eq!(custom_frame_insets(frame, dpi, build), (frame, 0));
++ }
++ }
++ }
++
++ #[test]
++ fn windows_11_preserves_the_first_client_row_at_each_scale() {
++ for build in [22000, 22621, 26100] {
++ for (frame, dpi, top) in [
++ (8, 96, 1),
++ (10, 120, 1),
++ (12, 144, 2),
++ (14, 168, 2),
++ (16, 192, 2),
++ (20, 240, 3),
++ (24, 288, 3),
++ ] {
++ assert_eq!(custom_frame_insets(frame, dpi, build), (frame, top));
++ }
++ }
++ }
++
++ #[test]
++ fn unknown_windows_build_does_not_restore_a_native_titlebar() {
++ assert_eq!(custom_frame_insets(8, 96, 0), (8, 0));
++ assert_eq!(custom_frame_insets(16, 192, 0), (16, 0));
++ }
++}
+diff --git a/crates/gpui_windows/src/shaders.hlsl b/crates/gpui_windows/src/shaders.hlsl
+index 483f03993855..78b1adad2ea6 100644
--- a/crates/gpui_windows/src/shaders.hlsl
+++ b/crates/gpui_windows/src/shaders.hlsl
-@@ -36,0 +37,11 @@
+@@ -34,6 +34,17 @@
+ float right;
+ float bottom;
+ float left;
+};
+
+struct EdgeFadeParams {
@@ -53,7 +276,13 @@
+ float right_x;
+ float band_left;
+ float band_right;
-@@ -94,0 +106,17 @@
+ };
+
+ struct Hsla {
+@@ -92,6 +103,23 @@
+
+ static const float M_PI_F = 3.141592653f;
+ static const float3 GRAYSCALE_FACTORS = float3(0.2126f, 0.7152f, 0.0722f);
+
+float edge_fade_alpha(float2 position, EdgeFadeParams fade) {
+ float ramp = 1.0;
@@ -71,39 +300,106 @@
+ }
+ return ramp * ramp;
+}
-@@ -504,0 +533 @@
+
+ float4 to_device_position_impl(float2 position) {
+ float2 device_position = position / global_viewport_size * float2(2.0, -2.0) + float2(-1.0, 1.0);
+@@ -502,6 +530,7 @@
+ Hsla border_color;
+ Corners corner_radii;
+ Edges border_widths;
+ EdgeFadeParams fade;
-@@ -556,0 +586,2 @@
+ };
+
+ struct QuadVertexOutput {
+@@ -554,6 +583,8 @@
+ Quad quad = quads[input.quad_id];
+ float4 background_color = gradient_color(quad.background, input.position.xy, quad.bounds,
+ input.background_solid, input.background_color0, input.background_color1);
+ float fade_alpha = edge_fade_alpha(input.position.xy, quad.fade);
+ background_color.a *= fade_alpha;
-@@ -663,0 +695 @@
+
+ bool unrounded = quad.corner_radii.top_left == 0.0 &&
+ quad.corner_radii.top_right == 0.0 &&
+@@ -661,6 +692,7 @@
+ float4 color = background_color;
+ if (border_sdf < antialias_threshold) {
+ float4 border_color = input.border_color;
+ border_color.a *= fade_alpha;
-@@ -1211,0 +1244 @@
+ // Dashed border logic when border_style == 1
+ if (quad.border_style == 1) {
+ // Position along the perimeter in "dash space", where each dash
+@@ -1209,6 +1241,7 @@
+ Bounds bounds;
+ Bounds content_mask;
+ Corners corner_radii;
+ EdgeFadeParams fade;
-@@ -1256 +1289 @@
+ AtlasTile tile;
+ };
+
+@@ -1253,6 +1286,6 @@
+ float3 grayscale = dot(color.rgb, GRAYSCALE_FACTORS);
+ color = float4(grayscale, sample.a);
+ }
- color.a *= sprite.opacity * saturate(0.5 - distance);
+ color.a *= sprite.opacity * saturate(0.5 - distance) * edge_fade_alpha(input.position.xy, sprite.fade);
+ return color;
+ }
+diff --git a/crates/gpui_windows/src/window.rs b/crates/gpui_windows/src/window.rs
+index 49a935bafe42..c0bbefae0955 100644
--- a/crates/gpui_windows/src/window.rs
+++ b/crates/gpui_windows/src/window.rs
-@@ -95,0 +96 @@
+@@ -93,6 +93,7 @@
+ system_settings: WindowsSystemSettings,
+ pub(crate) handle: AnyWindowHandle,
+ pub(crate) hide_title_bar: bool,
+ pub(crate) custom_frame: bool,
-@@ -216 +217,5 @@
+ pub(crate) is_movable: bool,
+ pub(crate) is_resizable: bool,
+ pub(crate) is_minimizable: bool,
+@@ -213,7 +214,11 @@
+ };
+ (
+ calculate_client_rect(
- placement.rcNormalPosition,
+ translate_rect(
+ placement.rcNormalPosition,
+ workspace_offset(self.hwnd, self.display.get(), self.scale_factor.get()),
+ 1,
+ ),
-@@ -265,0 +271 @@
+ &self.border_offset,
+ self.scale_factor.get(),
+ ),
+@@ -263,6 +268,7 @@
+ state,
+ handle: context.handle,
+ hide_title_bar: context.hide_title_bar,
+ custom_frame: context.custom_frame,
-@@ -388,0 +395 @@
+ is_movable: context.is_movable,
+ is_resizable: context.is_resizable,
+ is_minimizable: context.is_minimizable,
+@@ -386,6 +392,7 @@
+ inner: Option<Result<Rc<WindowsWindowInner>>>,
+ handle: AnyWindowHandle,
+ hide_title_bar: bool,
+ custom_frame: bool,
-@@ -405,0 +413,4 @@
+ display: WindowsDisplay,
+ is_movable: bool,
+ is_resizable: bool,
+@@ -403,6 +410,10 @@
+ directx_devices: DirectXDevices,
+ invalidate_devices: Arc<AtomicBool>,
+ parent_hwnd: Option<HWND>,
+}
+
+fn custom_frame_enabled(normal_window: bool, transparent_titlebar: Option<bool>) -> bool {
+ normal_window && transparent_titlebar == Some(true)
-@@ -452,0 +464,7 @@
+ }
+
+ impl WindowsWindow {
+@@ -450,6 +461,13 @@
+ .as_ref()
+ .map(|titlebar| titlebar.appears_transparent)
+ .unwrap_or(true);
+ let custom_frame = custom_frame_enabled(
+ params.kind == WindowKind::Normal,
+ params
@@ -111,24 +407,55 @@
+ .as_ref()
+ .map(|titlebar| titlebar.appears_transparent),
+ );
-@@ -463 +481 @@
+ let window_name = HSTRING::from(
+ params
+ .titlebar
+@@ -460,9 +478,14 @@
+ );
+
+ let (mut dwexstyle, dwstyle) = if params.kind == WindowKind::PopUp {
- (WS_EX_TOOLWINDOW, WINDOW_STYLE(0x0))
+ (WS_EX_TOOLWINDOW, WS_POPUP)
-@@ -465,0 +484,5 @@
+ } else {
+ let mut dwstyle = WS_SYSMENU;
+ if hide_title_bar && !custom_frame {
+ dwstyle |= WS_POPUP;
+ } else {
+ dwstyle |= WS_CAPTION;
+ }
-@@ -482,0 +506,3 @@
+
+ if params.is_resizable {
+ dwstyle |= WS_THICKFRAME | WS_MAXIMIZEBOX;
+@@ -480,6 +503,9 @@
+
+ (dwexstyle, dwstyle)
+ };
+ if custom_frame {
+ dwexstyle |= WS_EX_WINDOWEDGE;
+ }
-@@ -499,0 +526 @@
+ if !disable_direct_composition {
+ dwexstyle |= WS_EX_NOREDIRECTIONBITMAP;
+ }
+@@ -497,6 +523,7 @@
+ inner: None,
+ handle,
+ hide_title_bar,
+ custom_frame,
-@@ -550,0 +578 @@
+ display,
+ is_movable: params.is_movable,
+ is_resizable: params.is_resizable,
+@@ -548,6 +575,7 @@
+ params.bounds,
+ this.state.scale_factor.get(),
+ &this.state.border_offset,
+ params.window_min_size,
-@@ -621,2 +649,30 @@
+ )?;
+ if params.show {
+ unsafe { SetWindowPlacement(hwnd, &placement)? };
+@@ -618,8 +646,36 @@
+
+ fn resize(&mut self, size: Size<Pixels>) {
+ let hwnd = self.0.hwnd;
- let bounds = gpui::bounds(self.bounds().origin, size).to_device_pixels(self.scale_factor());
- let rect = calculate_window_rect(bounds, &self.state.border_offset);
+ let size = size.to_device_pixels(self.scale_factor());
@@ -161,15 +488,23 @@
+ if !movable {
+ flags |= SWP_NOMOVE;
+ }
-@@ -631,2 +687,2 @@
+
+ self.0
+ .executor
+@@ -628,13 +684,42 @@
+ SetWindowPos(
+ hwnd,
+ None,
- bounds.origin.x.0,
- bounds.origin.y.0,
+ rect.left,
+ rect.top,
-@@ -635 +691 @@
+ rect.right - rect.left,
+ rect.bottom - rect.top,
- SWP_NOMOVE,
+ flags,
-@@ -637,0 +694,29 @@
+ )
+ .context("unable to set window content size")
+ .log_err();
+ }
+ })
@@ -199,9 +534,21 @@
+ LPARAM(position as isize),
+ )
+ .context("unable to start window move")
-@@ -1510,0 +1596 @@
+ .log_err();
+ }
+ })
+@@ -1508,6 +1593,7 @@
+ initial_bounds: Bounds<Pixels>,
+ scale_factor: f32,
+ border_offset: &WindowBorderOffset,
+ minimum_size: Option<Size<Pixels>>,
-@@ -1524 +1610,10 @@
+ ) -> Result<WINDOWPLACEMENT> {
+ let mut placement = WINDOWPLACEMENT {
+ length: std::mem::size_of::<WINDOWPLACEMENT>() as u32,
+@@ -1521,8 +1607,71 @@
+ display.default_bounds()
+ };
+ let bounds = bounds.to_device_pixels(scale_factor);
- placement.rcNormalPosition = calculate_window_rect(bounds, border_offset);
+ let mut rect = calculate_window_rect(bounds, border_offset);
+ if !is_tool_window(hwnd) {
@@ -213,7 +560,7 @@
+ }
+ placement.rcNormalPosition =
+ translate_rect(rect, workspace_offset(hwnd, display, scale_factor), -1);
-@@ -1525,0 +1621,54 @@
+ Ok(placement)
+}
+
+fn is_tool_window(hwnd: HWND) -> bool {
@@ -268,12 +615,18 @@
+ right: left + width,
+ bottom: top + height,
+ }
-@@ -1612,2 +1761,2 @@
+ }
+
+ fn dwm_set_window_composition_attribute(hwnd: HWND, backdrop_type: u32) {
+@@ -1609,9 +1758,89 @@
+
+ #[cfg(test)]
+ mod tests {
- use super::ClickState;
- use gpui::{DevicePixels, MouseButton, point};
+ use super::{ClickState, custom_frame_enabled, fit_window_rect, translate_rect};
+ use gpui::{Bounds, DevicePixels, MouseButton, point, size};
-@@ -1614,0 +1764,80 @@
+ use std::time::Duration;
+ use windows::Win32::Foundation::RECT;
+
+ #[test]
@@ -354,109 +707,6 @@
+ assert_eq!(translate_rect(workspace, offset, 1), screen);
+ }
+ }
---- a/crates/gpui_windows/src/events.rs
-+++ b/crates/gpui_windows/src/events.rs
-@@ -716,0 +717,12 @@
-+ if self.custom_frame && !self.state.is_maximized() {
-+ let dpi = unsafe { GetDpiForWindow(handle) };
-+ let (frame, top) =
-+ custom_frame_insets(get_frame_thicknessx(dpi), dpi, windows_build_number());
-+ let params = unsafe { &mut *(lparam.0 as *mut NCCALCSIZE_PARAMS) };
-+ params.rgrc[0].left += frame;
-+ params.rgrc[0].top += top;
-+ params.rgrc[0].right -= frame;
-+ params.rgrc[0].bottom -= frame;
-+ return Some(0);
-+ }
-+
-@@ -847,5 +858,0 @@
--
-- // SetWindowPos may not send WM_SIZE for maximized windows in some cases,
-- // so we manually update the size to ensure proper rendering
-- let device_size = size(DevicePixels(width), DevicePixels(height));
-- self.handle_size_change(device_size, new_scale_factor, true);
-@@ -858,3 +864,0 @@
-- // this will emit `WM_SIZE` and `WM_MOVE` right here
-- // even before this function returns
-- // the new size is handled in `WM_SIZE`
-@@ -873,0 +878,15 @@
-+ }
-+
-+ // SetWindowPos can omit a final WM_SIZE; its outer bounds also include native captions.
-+ let mut client_rect = RECT::default();
-+ if !unsafe { IsIconic(handle) }.as_bool()
-+ && unsafe { GetClientRect(handle, &mut client_rect) }
-+ .context("unable to get client bounds after dpi has changed")
-+ .log_err()
-+ .is_some()
-+ {
-+ let device_size = size(
-+ DevicePixels((client_rect.right - client_rect.left).max(1)),
-+ DevicePixels((client_rect.bottom - client_rect.top).max(1)),
-+ );
-+ self.handle_size_change(device_size, self.state.scale_factor.get(), true);
-@@ -1652,0 +1672,26 @@
-+fn custom_frame_insets(frame: i32, dpi: u32, windows_build: u32) -> (i32, i32) {
-+ let top = if windows_build >= 22000 {
-+ (dpi as f32 / 96.).round() as i32
-+ } else {
-+ 0
-+ };
-+ (frame, top)
-+}
-+
-+fn windows_build_number() -> u32 {
-+ use windows::Win32::System::SystemInformation::OSVERSIONINFOW;
-+
-+ static BUILD: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
-+ *BUILD.get_or_init(|| {
-+ let mut version = OSVERSIONINFOW {
-+ dwOSVersionInfoSize: std::mem::size_of::<OSVERSIONINFOW>() as u32,
-+ ..Default::default()
-+ };
-+ if unsafe { windows::Wdk::System::SystemServices::RtlGetVersion(&mut version) }.is_ok() {
-+ version.dwBuildNumber
-+ } else {
-+ 0
-+ }
-+ })
-+}
-+
-@@ -1690,0 +1736,37 @@
-+
-+#[cfg(test)]
-+mod tests {
-+ use super::custom_frame_insets;
-+
-+ #[test]
-+ fn windows_10_has_no_top_inset_at_any_scale() {
-+ for build in [19045, 21999] {
-+ for (frame, dpi) in [(8, 96), (10, 120), (12, 144), (16, 192), (24, 288)] {
-+ assert_eq!(custom_frame_insets(frame, dpi, build), (frame, 0));
-+ }
-+ }
-+ }
-+
-+ #[test]
-+ fn windows_11_preserves_the_first_client_row_at_each_scale() {
-+ for build in [22000, 22621, 26100] {
-+ for (frame, dpi, top) in [
-+ (8, 96, 1),
-+ (10, 120, 1),
-+ (12, 144, 2),
-+ (14, 168, 2),
-+ (16, 192, 2),
-+ (20, 240, 3),
-+ (24, 288, 3),
-+ ] {
-+ assert_eq!(custom_frame_insets(frame, dpi, build), (frame, top));
-+ }
-+ }
-+ }
-+
-+ #[test]
-+ fn unknown_windows_build_does_not_restore_a_native_titlebar() {
-+ assert_eq!(custom_frame_insets(8, 96, 0), (8, 0));
-+ assert_eq!(custom_frame_insets(16, 192, 0), (16, 0));
-+ }
-+}
+
+ #[test]
+ fn test_double_click_interval() {
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index 8f0ebdc60..9ecd55089 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -87,6 +87,7 @@ cap-editor = { path = "../../../crates/editor" }
cap-media = { path = "../../../crates/media" }
cap-flags = { path = "../../../crates/flags" }
cap-recording = { path = "../../../crates/recording" }
+cap-timestamp = { path = "../../../crates/timestamp" }
cap-export = { path = "../../../crates/export" }
cap-automation = { path = "../../../crates/automation" }
cap-cli-install = { path = "../../../crates/cli-install", features = ["specta"] }
@@ -153,6 +154,10 @@ parakeet-rs = "0.3.4"
[target.'cfg(target_os = "linux")'.dependencies]
libappindicator = "0.9.0"
+gtk = "0.18"
+gdkwayland-sys = "0.18.2"
+wayland-sys = { version = "0.31.7", features = ["client", "dlopen"] }
+ashpd = { version = "0.11.0", default-features = false, features = ["tokio"] }
notify-rust = "4.11"
[target.'cfg(target_os= "windows")'.dependencies]
diff --git a/crates/recording/Cargo.toml b/crates/recording/Cargo.toml
index 75a2488cc..c1097b4c3 100644
--- a/crates/recording/Cargo.toml
+++ b/crates/recording/Cargo.toml
@@ -41,6 +41,7 @@ futures = { workspace = true }
anyhow = { workspace = true }
serde_json = "1"
+libc = "0.2"
chrono = "0.4.38"
uuid = { version = "1.18.1", features = ["v4"] }
tracing.workspace = true
@@ -75,7 +76,6 @@ core-graphics = "0.24.0"
core-foundation = "0.10.0"
coreaudio-rs = { version = "0.11.3", features = ["audio_unit"] }
foreign-types-shared = "0.3"
-libc = "0.2"
scap-screencapturekit = { path = "../scap-screencapturekit" }
cap-enc-avfoundation = { path = "../enc-avfoundation" }
diff --git a/crates/utils/Cargo.toml b/crates/utils/Cargo.toml
index f2c93a91c..7cbcff5b0 100644
--- a/crates/utils/Cargo.toml
+++ b/crates/utils/Cargo.toml
@@ -7,6 +7,9 @@ edition = "2024"
nix = { version = "0.29.0", features = ["fs"] }
libc = "0.2"
+[target.'cfg(target_os = "linux")'.dependencies]
+zbus = { version = "5.18.0", default-features = false, features = ["tokio"] }
+
[target.'cfg(windows)'.dependencies]
windows = { version = "0.58.0", features = [
"Win32_Foundation",