Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: validate local inference runtimes and prepare Wayland targets

Richie McIlroy880291f2b9f3
diff --git a/Cargo.lock b/Cargo.lock
index 6f98ac0d9..c6491320b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1342,6 +1342,7 @@ version = "0.1.0"
dependencies = [
"anyhow",
"bytemuck",
+ "libloading 0.9.0",
"ndarray 0.16.1",
"ort",
"tracing",
@@ -9005,10 +9006,14 @@ dependencies = [
"core-graphics 0.24.0",
"image 0.24.9",
"objc",
+ "rustix 1.1.2",
"serde",
"specta",
"tokio",
"tracing",
+ "uuid",
+ "wayland-client",
+ "wayland-protocols",
"windows 0.60.0",
"workspace-hack",
"x11rb",
@@ -9584,6 +9589,12 @@ dependencies = [
"digest",
]
+[[package]]
+name = "sha1_smol"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d"
+
[[package]]
name = "sha2"
version = "0.10.9"
@@ -12041,6 +12052,7 @@ dependencies = [
"getrandom 0.3.3",
"js-sys",
"serde",
+ "sha1_smol",
"wasm-bindgen",
]
diff --git a/apps/desktop-gpui/Cargo.lock b/apps/desktop-gpui/Cargo.lock
index 504a5feea..45b260128 100644
--- a/apps/desktop-gpui/Cargo.lock
+++ b/apps/desktop-gpui/Cargo.lock
@@ -1451,6 +1451,7 @@ version = "0.1.0"
dependencies = [
"anyhow",
"bytemuck",
+ "libloading 0.9.0",
"ndarray 0.16.1",
"ort",
"tracing",
@@ -1592,6 +1593,7 @@ dependencies = [
"tracing-subscriber",
"tray-icon",
"unicode-segmentation",
+ "wayland-client",
"wgpu 25.0.2",
"whisper-rs",
"windows-sys 0.59.0",
@@ -4552,6 +4554,7 @@ dependencies = [
"util_macros",
"uuid",
"waker-fn",
+ "wayland-client",
"web-time",
"windows 0.61.3",
"zed-font-kit",
@@ -9293,10 +9296,14 @@ dependencies = [
"core-graphics 0.24.0",
"image 0.24.9",
"objc",
+ "rustix 1.1.4",
"serde",
"specta",
"tokio",
"tracing",
+ "uuid",
+ "wayland-client",
+ "wayland-protocols",
"windows 0.60.0",
"workspace-hack",
"x11rb",
diff --git a/apps/desktop-gpui/Cargo.toml b/apps/desktop-gpui/Cargo.toml
index 623a243ca..83aa68e18 100644
--- a/apps/desktop-gpui/Cargo.toml
+++ b/apps/desktop-gpui/Cargo.toml
@@ -23,7 +23,7 @@ name = "Cap GPUI"
identifier = "so.cap.desktop.gpui"
icon = ["assets/dock-icon.png"]
category = "public.app-category.productivity"
-osx_minimum_system_version = "11.0"
+osx_minimum_system_version = "12.3"
osx_info_plist_exts = ["resources/Info.plist"]
osx_url_schemes = ["cap-desktop"]
@@ -188,6 +188,7 @@ windows-sys = { version = "0.59", features = [
[target.'cfg(target_os = "linux")'.dependencies]
ashpd = { version = "0.11", default-features = false, features = ["tokio"] }
+wayland-client = "0.31"
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
raw-window-handle = "0.6"
diff --git a/apps/desktop-gpui/patches/zed-linux.patch b/apps/desktop-gpui/patches/zed-linux.patch
index e84a49f5d..8229cb962 100644
--- a/apps/desktop-gpui/patches/zed-linux.patch
+++ b/apps/desktop-gpui/patches/zed-linux.patch
@@ -1,5 +1,57 @@
+diff --git a/crates/gpui/Cargo.toml b/crates/gpui/Cargo.toml
+--- a/crates/gpui/Cargo.toml
++++ b/crates/gpui/Cargo.toml
+@@ -29,7 +29,7 @@
+ bench = ["test-support", "dep:criterion", "dep:hdrhistogram"]
+ inspector = ["gpui_macros/inspector"]
+ leak-detection = ["backtrace"]
+-wayland = []
++wayland = ["dep:wayland-client"]
+ x11 = [
+ "scap?/x11",
+ ]
+@@ -110,6 +110,9 @@
+ uuid = { workspace = true, features = ["js"] }
+
+
++[target.'cfg(target_os = "linux")'.dependencies]
++wayland-client = { version = "0.31.11", optional = true }
++
+ [target.'cfg(target_os = "macos")'.dependencies]
+ block = "0.1"
+ cocoa.workspace = true
+diff --git a/crates/gpui/src/platform.rs b/crates/gpui/src/platform.rs
+--- a/crates/gpui/src/platform.rs
++++ b/crates/gpui/src/platform.rs
+@@ -795,6 +795,10 @@
+
+ #[expect(missing_docs)]
+ pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
++ #[cfg(all(target_os = "linux", feature = "wayland"))]
++ fn wayland_surface(&self) -> Option<wayland_client::protocol::wl_surface::WlSurface> {
++ None
++ }
+ fn bounds(&self) -> Bounds<Pixels>;
+ fn is_maximized(&self) -> bool;
+ fn window_bounds(&self) -> WindowBounds;
+diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs
+--- a/crates/gpui/src/window.rs
++++ b/crates/gpui/src/window.rs
+@@ -1931,6 +1931,13 @@
+ self.handle
+ }
+
++ /// Returns the native Wayland proxy, which tracks destruction without borrowing a raw pointer.
++ #[cfg(all(target_os = "linux", feature = "wayland"))]
++ pub fn wayland_surface(&self) -> Option<wayland_client::protocol::wl_surface::WlSurface> {
++ self.platform_window.wayland_surface()
++ }
++
++
+ /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
+ pub fn refresh(&mut self) {
+ if self.invalidator.not_drawing() {
diff --git a/crates/gpui_linux/src/linux/platform.rs b/crates/gpui_linux/src/linux/platform.rs
-index 876f931663fa..062af4e8c9b9 100644
--- a/crates/gpui_linux/src/linux/platform.rs
+++ b/crates/gpui_linux/src/linux/platform.rs
@@ -87,6 +87,9 @@
@@ -12,22 +64,46 @@ index 876f931663fa..062af4e8c9b9 100644
fn read_from_primary(&self) -> Option<ClipboardItem>;
fn read_from_clipboard(&self) -> Option<ClipboardItem>;
fn active_window(&self) -> Option<AnyWindowHandle>;
-@@ -735,6 +738,10 @@
- self.inner.write_to_clipboard(item)
- }
+@@ -733,6 +736,10 @@
-+ fn try_write_to_clipboard(&self, item: ClipboardItem) -> anyhow::Result<()> {
-+ self.inner.try_write_to_clipboard(item)
+ fn write_to_clipboard(&self, item: ClipboardItem) {
+ self.inner.write_to_clipboard(item)
+ }
+
- fn read_from_primary(&self) -> Option<ClipboardItem> {
- self.inner.read_from_primary()
++ fn try_write_to_clipboard(&self, item: ClipboardItem) -> anyhow::Result<()> {
++ self.inner.try_write_to_clipboard(item)
}
+
+ fn read_from_primary(&self) -> Option<ClipboardItem> {
diff --git a/crates/gpui_linux/src/linux/wayland/client.rs b/crates/gpui_linux/src/linux/wayland/client.rs
-index fdc40a3de87e..c41fa8d6aebb 100644
--- a/crates/gpui_linux/src/linux/wayland/client.rs
+++ b/crates/gpui_linux/src/linux/wayland/client.rs
-@@ -1121,6 +1121,30 @@
+@@ -200,6 +200,7 @@
+
+ #[derive(Clone)]
+ pub struct Globals {
++ pub registry: wl_registry::WlRegistry,
+ pub qh: QueueHandle<WaylandClientStatePtr>,
+ pub activation: Option<xdg_activation_v1::XdgActivationV1>,
+ pub compositor: wl_compositor::WlCompositor,
+@@ -232,6 +233,7 @@
+ ) -> Self {
+ let dialog_v = XdgWmDialogV1::interface().version;
+ Globals {
++ registry: globals.registry().clone(),
+ activation: globals.bind(&qh, 1..=1, ()).ok(),
+ compositor: globals
+ .bind(
+@@ -662,7 +664,7 @@
+ global.name,
+ wl_output_version(global.version),
+ &qh,
+- (),
++ global.name,
+ );
+ in_progress_outputs.insert(output.id(), InProgressOutput::default());
+ wl_outputs.insert(output.id(), output);
+@@ -1121,6 +1123,30 @@
}
}
@@ -58,7 +134,16 @@ index fdc40a3de87e..c41fa8d6aebb 100644
fn read_from_primary(&self) -> Option<gpui::ClipboardItem> {
self.0.borrow_mut().clipboard.read_primary()
}
-@@ -1301,6 +1325,25 @@
+@@ -1262,7 +1288,7 @@
+ name,
+ wl_output_version(version),
+ qh,
+- (),
++ name,
+ );
+
+ state
+@@ -1301,6 +1327,25 @@
delegate_noop!(WaylandClientStatePtr: ignore wp_viewporter::WpViewporter);
delegate_noop!(WaylandClientStatePtr: ignore wp_viewport::WpViewport);
@@ -84,8 +169,22 @@ index fdc40a3de87e..c41fa8d6aebb 100644
impl Dispatch<WlCallback, ObjectId> for WaylandClientStatePtr {
fn event(
state: &mut WaylandClientStatePtr,
+@@ -1353,12 +1398,12 @@
+ }
+ }
+
+-impl Dispatch<wl_output::WlOutput, ()> for WaylandClientStatePtr {
++impl Dispatch<wl_output::WlOutput, u32> for WaylandClientStatePtr {
+ fn event(
+ this: &mut Self,
+ output: &wl_output::WlOutput,
+ event: <wl_output::WlOutput as Proxy>::Event,
+- _: &(),
++ _: &u32,
+ _: &Connection,
+ _: &QueueHandle<Self>,
+ ) {
diff --git a/crates/gpui_linux/src/linux/wayland/clipboard.rs b/crates/gpui_linux/src/linux/wayland/clipboard.rs
-index dfedf53f6dfa..fb40a8b391f1 100644
--- a/crates/gpui_linux/src/linux/wayland/clipboard.rs
+++ b/crates/gpui_linux/src/linux/wayland/clipboard.rs
@@ -1,6 +1,6 @@
@@ -117,6 +216,17 @@ index dfedf53f6dfa..fb40a8b391f1 100644
- pub fn send(&self, _mime_type: String, fd: OwnedFd) {
- if let Some(text) = self.contents.as_ref().and_then(|contents| contents.text()) {
- self.send_internal(fd, text.as_bytes().to_owned());
+- }
+- }
+-
+- pub fn send_primary(&self, _mime_type: String, fd: OwnedFd) {
+- if let Some(text) = self
+- .primary_contents
+- .as_ref()
+- .and_then(|contents| contents.text())
+- {
+- self.send_internal(fd, text.as_bytes().to_owned());
+- }
+ pub(crate) fn mime_types(&self, item: &ClipboardItem) -> anyhow::Result<Vec<String>> {
+ let has_text = item
+ .entries()
@@ -182,16 +292,9 @@ index dfedf53f6dfa..fb40a8b391f1 100644
+ Err(error) => {
+ log::error!("Failed to prepare primary clipboard MIME type {mime_type}: {error}")
+ }
- }
- }
-
-- pub fn send_primary(&self, _mime_type: String, fd: OwnedFd) {
-- if let Some(text) = self
-- .primary_contents
-- .as_ref()
-- .and_then(|contents| contents.text())
-- {
-- self.send_internal(fd, text.as_bytes().to_owned());
++ }
++ }
++
+ fn bytes_for_mime(item: &ClipboardItem, mime_type: &str) -> anyhow::Result<Option<Vec<u8>>> {
+ if TEXT_MIME_TYPES.contains(&mime_type) {
+ return Ok(text_bytes(item));
@@ -203,7 +306,7 @@ index dfedf53f6dfa..fb40a8b391f1 100644
+ return Ok(Some(
+ format!("copy\n{}", file_uris(item)?.join("\n")).into_bytes(),
+ ));
- }
++ }
+ for entry in item.entries() {
+ if let ClipboardEntry::Image(image) = entry
+ && image.format().mime_type() == mime_type
@@ -378,28 +481,38 @@ index dfedf53f6dfa..fb40a8b391f1 100644
+ .unwrap()
)
- .unwrap();
+- }
+-}
+ .unwrap(),
+ "copy\nfile:///tmp/one.txt\nfile:///tmp/two.txt"
+ );
- }
- }
++ }
++}
diff --git a/crates/gpui_linux/src/linux/wayland/window.rs b/crates/gpui_linux/src/linux/wayland/window.rs
-index 993b2ff3fadc..e8916c11025f 100644
--- a/crates/gpui_linux/src/linux/wayland/window.rs
+++ b/crates/gpui_linux/src/linux/wayland/window.rs
-@@ -7,7 +7,7 @@
+@@ -7,15 +7,15 @@
};
-
+
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;
+-use wayland_client::WEnum;
+ use wayland_client::{
+ Proxy,
+ protocol::{wl_output, wl_seat, wl_surface},
+ };
++use wayland_client::{WEnum, globals::GlobalListContents};
+ use wayland_protocols::wp::viewporter::client::wp_viewport;
+ use wayland_protocols::xdg::decoration::zv1::client::zxdg_toplevel_decoration_v1;
+ use wayland_protocols::xdg::shell::client::xdg_popup;
@@ -93,7 +93,126 @@
tiling: Tiling,
}
-
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum VisibilityPhase {
+ Visible,
@@ -523,7 +636,11 @@ index 993b2ff3fadc..e8916c11025f 100644
surface_state: WaylandSurfaceState,
acknowledged_first_configure: bool,
parent: Option<WaylandWindowStatePtr>,
-@@ -110,6 +229,8 @@
+@@ -107,9 +226,12 @@
+ viewport: Option<wp_viewport::WpViewport>,
+ outputs: HashMap<ObjectId, Output>,
+ display: Option<(ObjectId, Output)>,
++ preferred_output: Option<wl_output::WlOutput>,
globals: Globals,
renderer: WgpuRenderer,
bounds: Bounds<Pixels>,
@@ -532,9 +649,44 @@ index 993b2ff3fadc..e8916c11025f 100644
scale: f32,
input_handler: Option<PlatformInputHandler>,
decorations: WindowDecorations,
-@@ -575,7 +696,11 @@
+@@ -539,6 +661,26 @@
+ }
+
+ impl WaylandWindowState {
++ fn fullscreen_output(&self) -> Option<&wl_output::WlOutput> {
++ self.preferred_output.as_ref().filter(|output| {
++ let Some(global_name) = output.data::<u32>() else {
++ return false;
++ };
++ output.is_alive()
++ && self
++ .globals
++ .registry
++ .data::<GlobalListContents>()
++ .is_some_and(|globals| {
++ globals.with_list(|list| {
++ list.iter().any(|global| {
++ global.name == *global_name && global.interface == "wl_output"
++ })
++ })
++ })
++ })
++ }
++
+ pub(crate) fn new(
+ handle: AnyWindowHandle,
+ surface: wl_surface::WlSurface,
+@@ -551,6 +693,7 @@
+ compositor_gpu: Option<CompositorGpuHint>,
+ options: WindowParams,
+ parent: Option<WaylandWindowStatePtr>,
++ preferred_output: Option<wl_output::WlOutput>,
+ ) -> anyhow::Result<Self> {
+ let renderer = {
+ let raw_window = RawWindow {
+@@ -575,7 +718,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
@@ -544,11 +696,11 @@ index 993b2ff3fadc..e8916c11025f 100644
+ {
xdg_state.toplevel.set_title(title.to_string());
}
-
-@@ -591,7 +716,16 @@
+
+@@ -591,7 +738,16 @@
.set_max_size(max_texture_size, max_texture_size);
}
-
+
- Ok(Self {
+ let mut state = Self {
+ visibility: RetainedVisibility::default(),
@@ -563,8 +715,11 @@ index 993b2ff3fadc..e8916c11025f 100644
surface_state,
acknowledged_first_configure: false,
parent,
-@@ -605,6 +739,8 @@
+@@ -603,8 +759,11 @@
+ globals,
+ outputs: HashMap::default(),
display: None,
++ preferred_output,
renderer,
bounds: options.bounds,
+ fixed_outer_size: (!options.is_resizable).then_some(options.bounds.size),
@@ -572,7 +727,7 @@ index 993b2ff3fadc..e8916c11025f 100644
scale: 1.0,
input_handler: None,
decorations: WindowDecorations::Client,
-@@ -626,7 +762,30 @@
+@@ -626,7 +785,30 @@
window_controls: WindowControls::default(),
client_inset: None,
accesskit_adapter: None,
@@ -602,9 +757,9 @@ index 993b2ff3fadc..e8916c11025f 100644
+ self.fixed_geometry_size = Some(geometry_size);
+ }
}
-
+
pub fn is_transparent(&self) -> bool {
-@@ -680,6 +839,34 @@
+@@ -680,6 +862,34 @@
impl Drop for WaylandWindow {
fn drop(&mut self) {
let mut state = self.0.state.borrow_mut();
@@ -639,19 +794,36 @@ index 993b2ff3fadc..e8916c11025f 100644
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 @@
+@@ -713,7 +923,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 @@
+@@ -754,7 +964,7 @@
+ &params,
+ parent.clone(),
+ popup_grab,
+- target_output,
++ target_output.clone(),
+ )?;
+
+ if let Some(fractional_scale_manager) = globals.fractional_scale_manager.as_ref() {
+@@ -779,6 +989,7 @@
+ compositor_gpu,
+ params,
+ parent,
++ target_output,
+ )?)),
+ callbacks: Rc::new(RefCell::new(Callbacks::default())),
+ });
+@@ -838,8 +1049,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())
@@ -761,7 +933,7 @@ index 993b2ff3fadc..e8916c11025f 100644
+ xdg.toplevel.set_maximized();
+ }
+ if state.fullscreen {
-+ xdg.toplevel.set_fullscreen(None);
++ xdg.toplevel.set_fullscreen(state.fullscreen_output());
+ }
+ if let Some(decoration) = &xdg.decoration {
+ decoration.set_mode(state.decorations.to_xdg());
@@ -802,7 +974,7 @@ index 993b2ff3fadc..e8916c11025f 100644
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 @@
+@@ -882,6 +1238,17 @@
pub fn handle_xdg_surface_event(&self, event: xdg_surface::Event) {
if let xdg_surface::Event::Configure { serial } = event {
{
@@ -820,7 +992,7 @@ index 993b2ff3fadc..e8916c11025f 100644
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 @@
+@@ -901,6 +1268,7 @@
state.fullscreen = configure.fullscreen;
state.maximized = configure.maximized;
state.tiling = configure.tiling;
@@ -828,10 +1000,10 @@ index 993b2ff3fadc..e8916c11025f 100644
// Limit interactive resizes to once per vblank
if configure.resizing && state.resize_throttle {
state.surface_state.ack_configure(serial);
-@@ -945,6 +1289,43 @@
+@@ -945,6 +1313,43 @@
window_geometry.size.height,
);
-
+
+ if matches!(state.visibility.phase, VisibilityPhase::Configuring(_))
+ && !state.acknowledged_first_configure
+ {
@@ -872,7 +1044,7 @@ index 993b2ff3fadc..e8916c11025f 100644
let request_frame_callback = !state.acknowledged_first_configure;
if request_frame_callback {
state.acknowledged_first_configure = true;
-@@ -958,7 +1339,11 @@
+@@ -958,7 +1363,11 @@
if let zxdg_toplevel_decoration_v1::Event::Configure { mode } = event {
match mode {
WEnum::Value(zxdg_toplevel_decoration_v1::Mode::ServerSide) => {
@@ -885,7 +1057,7 @@ index 993b2ff3fadc..e8916c11025f 100644
let callback = self.callbacks.borrow_mut().appearance_changed.take();
if let Some(mut fun) = callback {
fun();
-@@ -966,7 +1351,11 @@
+@@ -966,7 +1375,11 @@
}
}
WEnum::Value(zxdg_toplevel_decoration_v1::Mode::ClientSide) => {
@@ -898,7 +1070,7 @@ index 993b2ff3fadc..e8916c11025f 100644
// Update background to be transparent
let callback = self.callbacks.borrow_mut().appearance_changed.take();
if let Some(mut fun) = callback {
-@@ -1271,6 +1660,7 @@
+@@ -1271,6 +1684,7 @@
}
if let Some(scale) = scale {
state.scale = scale;
@@ -906,19 +1078,30 @@ index 993b2ff3fadc..e8916c11025f 100644
}
let device_bounds = state.bounds.to_device_pixels(state.scale);
state.renderer.update_drawable_size(device_bounds.size);
-@@ -1466,7 +1856,7 @@
+@@ -1428,6 +1842,10 @@
+ }
+
+ impl PlatformWindow for WaylandWindow {
++ fn wayland_surface(&self) -> Option<wl_surface::WlSurface> {
++ Some(self.0.surface())
++ }
++
+ fn bounds(&self) -> Bounds<Pixels> {
+ self.borrow().bounds
+ }
+@@ -1466,7 +1884,7 @@
}
-
+
fn resize(&mut self, size: Size<Pixels>) {
- let state = self.borrow();
+ let mut state = self.borrow_mut();
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 @@
+@@ -1486,6 +1904,11 @@
return;
}
-
+
+ if state.fixed_outer_size.is_some() {
+ state.fixed_outer_size = Some(size);
+ state.update_size_constraints();
@@ -927,7 +1110,7 @@ index 993b2ff3fadc..e8916c11025f 100644
// 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 @@
+@@ -1566,6 +1989,20 @@
_answers: &[PromptButton],
) -> Option<Receiver<usize>> {
None
@@ -946,11 +1129,11 @@ index 993b2ff3fadc..e8916c11025f 100644
+ ) -> anyhow::Result<Receiver<anyhow::Result<(u64, bool)>>> {
+ self.0.request_visibility(visible)
}
-
+
fn activate(&self) {
-@@ -1596,7 +2005,9 @@
+@@ -1596,7 +2033,9 @@
}
-
+
fn set_title(&mut self, title: &str) {
- if let Some(toplevel) = self.borrow().surface_state.toplevel() {
+ let mut state = self.borrow_mut();
@@ -959,8 +1142,17 @@ index 993b2ff3fadc..e8916c11025f 100644
toplevel.set_title(title.to_string());
}
}
-@@ -1706,6 +2117,13 @@
-
+@@ -1650,7 +2089,7 @@
+ let state = self.borrow();
+ if let Some(toplevel) = state.surface_state.toplevel() {
+ if !state.fullscreen {
+- toplevel.set_fullscreen(None);
++ toplevel.set_fullscreen(state.fullscreen_output());
+ } else {
+ toplevel.unset_fullscreen();
+ }
+@@ -1706,6 +2145,13 @@
+
fn draw(&self, scene: &Scene) {
let mut state = self.borrow_mut();
+ if !state
@@ -970,12 +1162,12 @@ index 993b2ff3fadc..e8916c11025f 100644
+ {
+ return;
+ }
-
+
if state.renderer.device_lost() {
let raw_window = RawWindow {
-@@ -1730,6 +2148,12 @@
+@@ -1730,6 +2176,12 @@
}
-
+
state.renderer_presented = state.renderer.draw(scene);
+ if state.renderer_presented
+ && let VisibilityPhase::Configuring(transition) = state.visibility.phase
@@ -983,11 +1175,11 @@ index 993b2ff3fadc..e8916c11025f 100644
+ 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 @@
-
+@@ -1738,6 +2190,13 @@
+
fn completed_frame(&self) {
let mut state = self.borrow_mut();
+ if !state
@@ -997,11 +1189,11 @@ index 993b2ff3fadc..e8916c11025f 100644
+ {
+ 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 @@
-
+@@ -1776,6 +2235,9 @@
+
fn start_window_resize(&self, edge: gpui::ResizeEdge) {
let state = self.borrow();
+ if state.fixed_outer_size.is_some() {
@@ -1010,7 +1202,7 @@ index 993b2ff3fadc..e8916c11025f 100644
if let Some(toplevel) = state.surface_state.toplevel() {
toplevel.resize(
&state.globals.seat,
-@@ -1835,7 +2269,13 @@
+@@ -1835,7 +2297,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.
@@ -1023,9 +1215,9 @@ index 993b2ff3fadc..e8916c11025f 100644
+ state.surface.commit();
+ }
}
-
+
fn window_decorations(&self) -> Decorations {
-@@ -1854,6 +2294,7 @@
+@@ -1854,6 +2322,7 @@
Some(decoration) => {
decoration.set_mode(decorations.to_xdg());
state.decorations = decorations;
@@ -1033,7 +1225,7 @@ index 993b2ff3fadc..e8916c11025f 100644
update_window(state);
}
None => {
-@@ -1863,6 +2304,7 @@
+@@ -1863,6 +2332,7 @@
);
}
state.decorations = WindowDecorations::Client;
@@ -1041,7 +1233,7 @@ index 993b2ff3fadc..e8916c11025f 100644
update_window(state);
}
}
-@@ -1876,6 +2318,7 @@
+@@ -1876,6 +2346,7 @@
let mut state = self.borrow_mut();
if Some(inset) != state.client_inset {
state.client_inset = Some(inset);
@@ -1049,8 +1241,8 @@ index 993b2ff3fadc..e8916c11025f 100644
update_window(state);
}
}
-@@ -2082,3 +2525,337 @@
-
+@@ -2082,3 +2553,337 @@
+
bounds
}
+
@@ -1388,7 +1580,6 @@ index 993b2ff3fadc..e8916c11025f 100644
+ }
+}
diff --git a/crates/gpui_linux/src/linux/x11/client.rs b/crates/gpui_linux/src/linux/x11/client.rs
-index 0c8c9b4e20b8..701ae28fe440 100644
--- a/crates/gpui_linux/src/linux/x11/client.rs
+++ b/crates/gpui_linux/src/linux/x11/client.rs
@@ -811,11 +811,12 @@
@@ -1454,7 +1645,6 @@ index 0c8c9b4e20b8..701ae28fe440 100644
fn active_window(&self) -> Option<AnyWindowHandle> {
diff --git a/crates/gpui_linux/src/linux/x11/clipboard.rs b/crates/gpui_linux/src/linux/x11/clipboard.rs
-index 706e7b096588..591535333fa2 100644
--- a/crates/gpui_linux/src/linux/x11/clipboard.rs
+++ b/crates/gpui_linux/src/linux/x11/clipboard.rs
@@ -22,6 +22,7 @@
@@ -1545,10 +1735,12 @@ index 706e7b096588..591535333fa2 100644
}];
self.inner.write(data, selection, wait)
}
-@@ -1138,6 +1182,66 @@
+@@ -1136,6 +1180,66 @@
+ Error::Unknown {
+ description: error.to_string(),
}
- }
-
++}
++
+fn file_uri_list_to_clipboard_data(paths: &[PathBuf], atoms: Atoms) -> Result<Vec<ClipboardData>> {
+ if paths.is_empty() {
+ return Err(Error::unknown("clipboard file list is empty"));
@@ -1607,28 +1799,167 @@ index 706e7b096588..591535333fa2 100644
+ format: atoms.NAUTILUS_FILE_LIST,
+ },
+ ])
-+}
-+
+ }
+
/// Clipboard selection
- ///
- /// Linux has a concept of clipboard "selections" which tend to be used in different contexts. This
diff --git a/crates/gpui_linux/src/linux/x11/window.rs b/crates/gpui_linux/src/linux/x11/window.rs
--- a/crates/gpui_linux/src/linux/x11/window.rs
+++ b/crates/gpui_linux/src/linux/x11/window.rs
-@@ -1013,2 +1013,2 @@
+@@ -1010,10 +1010,14 @@
+
+ impl X11WindowStatePtr {
+ pub fn should_close(&self) -> bool {
- let mut cb = self.callbacks.borrow_mut();
- if let Some(mut should_close) = cb.should_close.take() {
+ let should_close = self.callbacks.borrow_mut().should_close.take();
+ if let Some(mut should_close) = should_close {
-@@ -1016 +1016,5 @@
+ let result = (should_close)();
- cb.should_close = Some(should_close);
+ let mut callbacks = self.callbacks.borrow_mut();
+ if callbacks.should_close.is_none() {
+ callbacks.should_close = Some(should_close);
+ }
+ drop(callbacks);
-@@ -1131,2 +1135,2 @@
+ result
+ } else {
+ true
+@@ -1128,8 +1132,8 @@
+ }
+ }
+
- let mut callbacks = self.callbacks.borrow_mut();
- if let Some(fun) = callbacks.close.take() {
+ let close = self.callbacks.borrow_mut().close.take();
+ if let Some(fun) = close {
+ fun()
+ }
+ }
+diff --git a/crates/gpui_wgpu/src/gpui_wgpu.rs b/crates/gpui_wgpu/src/gpui_wgpu.rs
+--- a/crates/gpui_wgpu/src/gpui_wgpu.rs
++++ b/crates/gpui_wgpu/src/gpui_wgpu.rs
+@@ -1,4 +1,5 @@
+ mod cosmic_text_system;
++mod surface_frame;
+ mod wgpu_atlas;
+ mod wgpu_context;
+ mod wgpu_renderer;
+diff --git a/crates/gpui_wgpu/src/surface_frame.rs b/crates/gpui_wgpu/src/surface_frame.rs
+new file mode 100644
+--- /dev/null
++++ b/crates/gpui_wgpu/src/surface_frame.rs
+@@ -0,0 +1,34 @@
++pub(super) struct SurfaceFrame {
++ frame: Option<wgpu::SurfaceTexture>,
++ texture: TextureCleanup,
++}
++
++impl SurfaceFrame {
++ pub(super) fn new(frame: wgpu::SurfaceTexture) -> Self {
++ Self {
++ texture: TextureCleanup(frame.texture.clone()),
++ frame: Some(frame),
++ }
++ }
++
++ pub(super) fn texture(&self) -> &wgpu::Texture {
++ &self.texture.0
++ }
++
++ pub(super) fn present(mut self) {
++ if let Some(frame) = self.frame.take() {
++ frame.present();
++ }
++ }
++}
++
++struct TextureCleanup(wgpu::Texture);
++
++impl Drop for TextureCleanup {
++ fn drop(&mut self) {
++ // wgpu 29 can retain an acquired texture after device loss. Release its raw
++ // resources after present/discard, before the owning surface is destroyed.
++ // https://github.com/gfx-rs/wgpu/issues/9277
++ self.0.destroy();
++ }
++}
+diff --git a/crates/gpui_wgpu/src/wgpu_renderer.rs b/crates/gpui_wgpu/src/wgpu_renderer.rs
+--- a/crates/gpui_wgpu/src/wgpu_renderer.rs
++++ b/crates/gpui_wgpu/src/wgpu_renderer.rs
+@@ -1,3 +1,4 @@
++use crate::surface_frame::SurfaceFrame;
+ use crate::{CompositorGpuHint, WgpuAtlas, WgpuContext};
+ use bytemuck::{Pod, Zeroable};
+ use gpui::{
+@@ -1118,24 +1119,15 @@
+
+ self.atlas.before_frame();
+
+- let frame = match self
++ let (frame, suboptimal) = 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();
+- if let Some(surface) = &resources.surface {
+- surface.configure(&resources.device, &surface_config);
+- }
+- return false;
+- }
++ wgpu::CurrentSurfaceTexture::Success(frame) => (SurfaceFrame::new(frame), false),
++ wgpu::CurrentSurfaceTexture::Suboptimal(frame) => (SurfaceFrame::new(frame), true),
+ wgpu::CurrentSurfaceTexture::Lost | wgpu::CurrentSurfaceTexture::Outdated => {
+ let surface_config = self.surface_config.clone();
+ let resources = self.resources_mut();
+@@ -1158,7 +1150,7 @@
+ self.ensure_intermediate_textures();
+
+ let frame_view = frame
+- .texture
++ .texture()
+ .create_view(&wgpu::TextureViewDescriptor::default());
+
+ let gamma_params = GammaParams {
+@@ -1330,8 +1322,7 @@
+ "instance buffer size grew too large: {}",
+ self.instance_buffer_capacity
+ );
+- frame.present();
+- return true;
++ return self.present_frame(frame, suboptimal);
+ }
+ self.grow_instance_buffer();
+ continue;
+@@ -1340,9 +1331,22 @@
+ self.resources()
+ .queue
+ .submit(std::iter::once(encoder.finish()));
+- frame.present();
+- return true;
+- }
++ return self.present_frame(frame, suboptimal);
++ }
++ }
++
++ fn present_frame(&mut self, frame: SurfaceFrame, suboptimal: bool) -> bool {
++ frame.present();
++ if self.device_lost() {
++ return false;
++ }
++ if suboptimal {
++ let resources = self.resources();
++ if let Some(surface) = &resources.surface {
++ surface.configure(&resources.device, &self.surface_config);
++ }
++ }
++ true
+ }
+
+ fn draw_quads(
diff --git a/apps/desktop/src-tauri/src/captions.rs b/apps/desktop/src-tauri/src/captions.rs
index cf76122e0..dd261cc6d 100644
--- a/apps/desktop/src-tauri/src/captions.rs
+++ b/apps/desktop/src-tauri/src/captions.rs
@@ -53,11 +53,16 @@ impl Default for CaptionData {
}
lazy_static::lazy_static! {
- static ref WHISPER_CONTEXT: Arc<Mutex<Option<Arc<WhisperContext>>>> = Arc::new(Mutex::new(None));
+ static ref WHISPER_CONTEXT: Arc<Mutex<Option<CachedWhisperContext>>> = Arc::new(Mutex::new(None));
static ref MODEL_DOWNLOADS: Mutex<HashMap<String, ActiveModelDownload>> = Mutex::new(HashMap::new());
static ref TRANSCRIPTION_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
}
+struct CachedWhisperContext {
+ model_path: String,
+ context: Arc<WhisperContext>,
+}
+
#[cfg(not(all(target_os = "macos", target_arch = "x86_64")))]
lazy_static::lazy_static! {
static ref PARAKEET_CONTEXT: Mutex<Option<CachedParakeetContext>> = Mutex::new(None);
@@ -103,6 +108,22 @@ async fn invalidate_parakeet_cache_for_dir(model_dir: &Path) {
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
async fn invalidate_parakeet_cache_for_dir(_model_dir: &Path) {}
+async fn invalidate_whisper_cache_for_path(model_path: &Path) {
+ let cached_context = {
+ let mut context = WHISPER_CONTEXT.lock().await;
+ if context
+ .as_ref()
+ .is_some_and(|cached| Path::new(&cached.model_path) == model_path)
+ {
+ tracing::info!("Releasing deleted Whisper model from cache");
+ context.take()
+ } else {
+ None
+ }
+ };
+ drop(cached_context);
+}
+
pub async fn release_ml_models() {
{
let mut ctx = WHISPER_CONTEXT.lock().await;
@@ -689,11 +710,14 @@ fn lock_transcription_worker_slot() -> std::sync::MutexGuard<'static, ()> {
}
fn get_whisper_context_blocking(model_path: &str) -> Result<Arc<WhisperContext>, String> {
+ cap_utils::local_captions::ensure_whisper_cpu_support()?;
let mut context_guard = WHISPER_CONTEXT.blocking_lock();
- if let Some(ref existing) = *context_guard {
+ if let Some(ref existing) = *context_guard
+ && existing.model_path == model_path
+ {
log::info!("Reusing cached Whisper context");
- return Ok(existing.clone());
+ return Ok(existing.context.clone());
}
log::info!("Initializing Whisper context with model: {model_path}");
@@ -701,7 +725,10 @@ fn get_whisper_context_blocking(model_path: &str) -> Result<Arc<WhisperContext>,
.map_err(|e| format!("Failed to load Whisper model: {e}"))?;
let ctx_arc = Arc::new(ctx);
- *context_guard = Some(ctx_arc.clone());
+ *context_guard = Some(CachedWhisperContext {
+ model_path: model_path.to_string(),
+ context: ctx_arc.clone(),
+ });
Ok(ctx_arc)
}
@@ -1228,6 +1255,7 @@ fn process_with_parakeet(
model
} else {
tracing::info!("Loading Parakeet TDT model from: {model_dir}");
+ cap_camera_effects::initialize_onnx_runtime().map_err(|error| format!("{error:#}"))?;
let model = ParakeetTDT::from_pretrained(model_dir, None).map_err(|e| format!("{e}"))?;
let loaded_model = Arc::new(std::sync::Mutex::new(model));
@@ -2246,6 +2274,8 @@ pub async fn delete_whisper_model(app: AppHandle, model_path: String) -> Result<
.await
.map_err(|e| format!("Failed to delete model file: {e}"))?;
+ invalidate_whisper_cache_for_path(&validated_path).await;
+
Ok(())
}
diff --git a/crates/camera-effects/Cargo.toml b/crates/camera-effects/Cargo.toml
index 48975431f..1645e02bb 100644
--- a/crates/camera-effects/Cargo.toml
+++ b/crates/camera-effects/Cargo.toml
@@ -13,6 +13,9 @@ tracing.workspace = true
bytemuck = { version = "1.7", features = ["derive"] }
ndarray = "0.16"
+[target.'cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))'.dependencies]
+libloading = "0.9"
+
[target.'cfg(target_os = "linux")'.dependencies]
ort = { version = "2.0.0-rc.12", default-features = false, features = ["std", "ndarray", "load-dynamic", "api-23"] }
diff --git a/crates/camera-effects/src/lib.rs b/crates/camera-effects/src/lib.rs
index 1e9df1798..40e66e09d 100644
--- a/crates/camera-effects/src/lib.rs
+++ b/crates/camera-effects/src/lib.rs
@@ -13,6 +13,10 @@ pub fn onnx_runtime_library_path() -> Option<std::path::PathBuf> {
segmentation::onnx_runtime_library_path()
}
+pub fn initialize_onnx_runtime() -> anyhow::Result<()> {
+ segmentation::init_runtime()
+}
+
static BLUR_DISABLED: AtomicBool = AtomicBool::new(false);
static BLUR_SESSION_OBSERVER: OnceLock<fn(bool)> = OnceLock::new();
diff --git a/crates/camera-effects/src/segmentation.rs b/crates/camera-effects/src/segmentation.rs
index cf88201c7..fe6161375 100644
--- a/crates/camera-effects/src/segmentation.rs
+++ b/crates/camera-effects/src/segmentation.rs
@@ -108,16 +108,75 @@ fn create_session() -> anyhow::Result<Session> {
}
#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]
-fn init_runtime() -> anyhow::Result<()> {
+pub(crate) fn init_runtime() -> anyhow::Result<()> {
let path = onnx_runtime_library_path().context("Failed to find ONNX Runtime library")?;
+ let (library, path) = preflight_runtime(&path)?;
let _ = ort::init_from(&path)
.with_context(|| format!("Failed to load ONNX Runtime from {}", path.display()))?
.commit();
+ drop(library);
Ok(())
}
+#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]
+fn preflight_runtime(path: &std::path::Path) -> anyhow::Result<(libloading::Library, PathBuf)> {
+ let path = if path.is_absolute() {
+ path.to_path_buf()
+ } else {
+ let executable = std::env::current_exe().context("Failed to locate current executable")?;
+ let executable_relative = executable
+ .parent()
+ .context("Current executable has no parent directory")?
+ .join(path);
+ if executable_relative.exists() {
+ executable_relative
+ } else {
+ path.to_path_buf()
+ }
+ };
+
+ // ort rc.12 constructs loader errors through its not-yet-loaded API, which
+ // recursively enters its initialization lock. Validate before entering ort,
+ // retaining this handle until ort has acquired its own reference.
+ let library = unsafe { libloading::Library::new(&path) }
+ .with_context(|| format!("Failed to load ONNX Runtime from {}", path.display()))?;
+ unsafe {
+ let get_api_base = library
+ .get::<unsafe extern "C" fn() -> *const ort::sys::OrtApiBase>(b"OrtGetApiBase\0")
+ .context("ONNX Runtime is missing OrtGetApiBase")?;
+ let base = get_api_base()
+ .as_ref()
+ .context("ONNX Runtime returned a null API base")?;
+ let version = (base.GetVersionString)();
+ anyhow::ensure!(!version.is_null(), "ONNX Runtime returned a null version");
+ let version = std::ffi::CStr::from_ptr(version)
+ .to_str()
+ .context("ONNX Runtime returned an invalid version string")?;
+ validate_runtime_version(version)?;
+ anyhow::ensure!(
+ !(base.GetApi)(ort::sys::ORT_API_VERSION).is_null(),
+ "ONNX Runtime {version} does not provide API version {}",
+ ort::sys::ORT_API_VERSION
+ );
+ }
+ Ok((library, path))
+}
+
+#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]
+fn validate_runtime_version(version: &str) -> anyhow::Result<()> {
+ let mut parts = version.split('.');
+ let major = parts.next().and_then(|part| part.parse::<u32>().ok());
+ let minor = parts.next().and_then(|part| part.parse::<u32>().ok());
+ anyhow::ensure!(
+ major == Some(1) && minor.is_some_and(|minor| minor >= ort::MINOR_VERSION),
+ "Unsupported ONNX Runtime version {version:?}; expected 1.{}.x or newer compatible 1.x runtime",
+ ort::MINOR_VERSION
+ );
+ Ok(())
+}
+
#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]
pub(crate) fn onnx_runtime_library_path() -> Option<PathBuf> {
std::env::var_os("ORT_DYLIB_PATH")
@@ -130,7 +189,7 @@ pub(crate) fn onnx_runtime_library_path() -> Option<PathBuf> {
}
#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
-fn init_runtime() -> anyhow::Result<()> {
+pub(crate) fn init_runtime() -> anyhow::Result<()> {
Ok(())
}
@@ -214,6 +273,74 @@ fn try_register_directml(
mod tests {
use super::{MODEL_CHANNEL_SIZE, populate_rgb_planes};
+ #[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]
+ #[test]
+ fn runtime_version_requires_compatible_major_and_api() {
+ for minor in [ort::MINOR_VERSION, ort::MINOR_VERSION + 1] {
+ super::validate_runtime_version(&format!("1.{minor}.0")).unwrap();
+ }
+ let older = format!("1.{}.0", ort::MINOR_VERSION.saturating_sub(1));
+ for version in ["", "1", &older, "2.24.2", "x.24.2", "1.invalid.0"] {
+ assert!(
+ super::validate_runtime_version(version).is_err(),
+ "{version}"
+ );
+ }
+ }
+
+ #[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]
+ #[test]
+ fn runtime_load_failures_remain_retryable() {
+ const CHILD_ENV: &str = "CAP_CAMERA_EFFECTS_LOADER_TEST_CHILD";
+ if let Some(path) = std::env::var_os(CHILD_ENV) {
+ assert!(crate::initialize_onnx_runtime().is_err());
+ std::fs::write(&path, b"invalid ONNX Runtime library").unwrap();
+ assert!(crate::initialize_onnx_runtime().is_err());
+ return;
+ }
+
+ let unique = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos();
+ let directory =
+ std::env::temp_dir().join(format!("cap-onnx-loader-{}-{unique}", std::process::id()));
+ std::fs::create_dir(&directory).unwrap();
+ let path = directory.join(super::ORT_LIBRARY_NAME);
+ let mut child = std::process::Command::new(std::env::current_exe().unwrap())
+ .args([
+ "--exact",
+ "segmentation::tests::runtime_load_failures_remain_retryable",
+ "--test-threads=1",
+ ])
+ .env(CHILD_ENV, &path)
+ .env("ORT_DYLIB_PATH", &path)
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::piped())
+ .spawn()
+ .unwrap();
+ let started = std::time::Instant::now();
+ let timed_out = loop {
+ if child.try_wait().unwrap().is_some() {
+ break false;
+ }
+ if started.elapsed() >= std::time::Duration::from_secs(10) {
+ child.kill().unwrap();
+ break true;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(10));
+ };
+ let output = child.wait_with_output().unwrap();
+ std::fs::remove_dir_all(directory).unwrap();
+ assert!(!timed_out, "ONNX Runtime loader did not return after 10s");
+ assert!(
+ output.status.success(),
+ "ONNX Runtime loader child failed: {}\n{}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ }
+
#[test]
fn rgba_pixels_are_written_to_normalized_rgb_planes() {
let mut input = vec![f32::NAN; 3 * MODEL_CHANNEL_SIZE];
diff --git a/crates/scap-targets/Cargo.toml b/crates/scap-targets/Cargo.toml
index 0baa4fd2d..767c0bb5a 100644
--- a/crates/scap-targets/Cargo.toml
+++ b/crates/scap-targets/Cargo.toml
@@ -39,3 +39,7 @@ windows = { workspace = true, features = [
[target.'cfg(target_os = "linux")'.dependencies]
x11rb = { version = "0.13.2", features = ["randr"] }
+rustix = { version = "1.1", features = ["event"] }
+wayland-client = "0.31"
+wayland-protocols = { version = "0.32", features = ["client", "unstable"] }
+uuid = { version = "1", features = ["v5"] }
diff --git a/crates/scap-targets/src/platform/linux.rs b/crates/scap-targets/src/platform/linux.rs
index 6f3ecefac..1dbb6c3b9 100644
--- a/crates/scap-targets/src/platform/linux.rs
+++ b/crates/scap-targets/src/platform/linux.rs
@@ -13,6 +13,8 @@ use crate::bounds::{
LogicalBounds, LogicalPosition, LogicalSize, PhysicalBounds, PhysicalPosition, PhysicalSize,
};
+mod wayland;
+
#[derive(Clone, Copy)]
pub struct DisplayImpl {
id: u32,
@@ -21,6 +23,8 @@ pub struct DisplayImpl {
width: u32,
height: u32,
refresh_rate: f64,
+ logical_bounds: Option<LogicalBounds>,
+ wayland_uuid: Option<uuid::Uuid>,
}
impl DisplayImpl {
@@ -32,10 +36,15 @@ impl DisplayImpl {
width: 0,
height: 0,
refresh_rate: 60.0,
+ logical_bounds: None,
+ wayland_uuid: None,
})
}
pub fn list() -> Vec<Self> {
+ if prefers_wayland() {
+ return wayland_displays();
+ }
let Ok((conn, screen_num)) = x11_connection() else {
return wayland_displays();
};
@@ -59,6 +68,8 @@ impl DisplayImpl {
width: monitor.width.into(),
height: monitor.height.into(),
refresh_rate: 60.0,
+ logical_bounds: None,
+ wayland_uuid: None,
})
.collect::<Vec<_>>()
})
@@ -75,9 +86,15 @@ impl DisplayImpl {
width: screen.width_in_pixels.into(),
height: screen.height_in_pixels.into(),
refresh_rate: 60.0,
+ logical_bounds: None,
+ wayland_uuid: None,
}]
}
+ pub fn wayland_uuid(&self) -> Option<uuid::Uuid> {
+ self.wayland_uuid
+ }
+
pub fn raw_id(&self) -> DisplayIdImpl {
DisplayIdImpl(self.id)
}
@@ -90,10 +107,16 @@ impl DisplayImpl {
}
pub fn logical_size(&self) -> Option<LogicalSize> {
- Some(LogicalSize::new(self.width.into(), self.height.into()))
+ Some(self.logical_bounds.map_or_else(
+ || LogicalSize::new(self.width.into(), self.height.into()),
+ |bounds| bounds.size(),
+ ))
}
pub fn logical_bounds(&self) -> Option<LogicalBounds> {
+ if let Some(bounds) = self.logical_bounds {
+ return Some(bounds);
+ }
Some(LogicalBounds::new(
LogicalPosition::new(self.x.into(), self.y.into()),
self.logical_size()?,
@@ -162,6 +185,9 @@ pub struct WindowSelectionMetadata {
impl WindowImpl {
pub fn list() -> Vec<Self> {
+ if prefers_wayland() {
+ return wayland_windows();
+ }
let Ok((conn, screen_num)) = x11_connection() else {
return wayland_windows();
};
@@ -214,6 +240,9 @@ impl WindowImpl {
}
pub fn logical_size(&self) -> Option<LogicalSize> {
+ if is_wayland_portal_window(self.0) {
+ return DisplayImpl::primary().logical_size();
+ }
let size = self.physical_size()?;
Some(LogicalSize::new(size.width(), size.height()))
}
@@ -239,6 +268,9 @@ impl WindowImpl {
}
pub fn logical_bounds(&self) -> Option<LogicalBounds> {
+ if is_wayland_portal_window(self.0) {
+ return DisplayImpl::primary().logical_bounds();
+ }
let bounds = self.physical_bounds()?;
Some(LogicalBounds::new(
LogicalPosition::new(bounds.position().x(), bounds.position().y()),
@@ -332,15 +364,7 @@ fn wayland_displays() -> Vec<DisplayImpl> {
return Vec::new();
}
- let (width, height) = wayland_display_size();
- vec![DisplayImpl {
- id: 0,
- x: 0,
- y: 0,
- width,
- height,
- refresh_rate: 60.0,
- }]
+ wayland::displays().unwrap_or_default()
}
fn wayland_windows() -> Vec<WindowImpl> {
@@ -351,23 +375,20 @@ fn wayland_windows() -> Vec<WindowImpl> {
}
}
-fn wayland_display_size() -> (u32, u32) {
- let width = env::var("CAP_WAYLAND_OUTPUT_WIDTH")
- .ok()
- .and_then(|value| value.parse().ok())
- .filter(|value| *value > 0)
- .unwrap_or(1920);
- let height = env::var("CAP_WAYLAND_OUTPUT_HEIGHT")
- .ok()
- .and_then(|value| value.parse().ok())
- .filter(|value| *value > 0)
- .unwrap_or(1080);
+fn prefers_wayland() -> bool {
+ prefers_wayland_environment(
+ env::var_os("WAYLAND_DISPLAY").is_some(),
+ env::var_os("DISPLAY").is_some(),
+ env::var("XDG_SESSION_TYPE").ok().as_deref(),
+ )
+}
- (width, height)
+fn prefers_wayland_environment(wayland: bool, x11: bool, session: Option<&str>) -> bool {
+ wayland && (!x11 || session.is_some_and(|session| session.eq_ignore_ascii_case("wayland")))
}
fn is_wayland_portal_window(window: Window) -> bool {
- window == 0 && x11_connection().is_err() && env::var_os("WAYLAND_DISPLAY").is_some()
+ window == 0 && prefers_wayland()
}
fn intern_atom(conn: &RustConnection, name: &str) -> Option<Atom> {
@@ -459,6 +480,9 @@ fn process_name(pid: u32) -> Option<String> {
}
fn get_cursor_position() -> Option<PhysicalPosition> {
+ if prefers_wayland() {
+ return None;
+ }
let (conn, screen_num) = x11_connection().ok()?;
let root = conn.setup().roots[screen_num].root;
let reply = conn.query_pointer(root).ok()?.reply().ok()?;
diff --git a/crates/scap-targets/src/platform/linux/wayland.rs b/crates/scap-targets/src/platform/linux/wayland.rs
new file mode 100644
index 000000000..c4b8bcdbf
--- /dev/null
+++ b/crates/scap-targets/src/platform/linux/wayland.rs
@@ -0,0 +1,473 @@
+use std::{
+ collections::BTreeMap,
+ env,
+ os::unix::net::UnixStream,
+ path::PathBuf,
+ time::{Duration, Instant},
+};
+
+use rustix::event::{PollFd, PollFlags, Timespec, poll};
+use wayland_client::{
+ Connection, Dispatch, EventQueue, QueueHandle, WEnum,
+ protocol::{wl_callback, wl_output, wl_registry},
+};
+use wayland_protocols::xdg::xdg_output::zv1::client::{zxdg_output_manager_v1, zxdg_output_v1};
+
+use super::{DisplayImpl, LogicalBounds, LogicalPosition, LogicalSize};
+
+#[derive(Clone, Copy, Default)]
+struct OutputGeometry {
+ position: (i32, i32),
+ mode: Option<(i32, i32, i32)>,
+ scale: i32,
+ rotated: bool,
+ uuid: Option<uuid::Uuid>,
+}
+
+#[derive(Clone, Copy, Default)]
+struct LogicalGeometry {
+ position: Option<(i32, i32)>,
+ size: Option<(i32, i32)>,
+ uuid: Option<uuid::Uuid>,
+}
+
+#[derive(Default)]
+struct OutputState {
+ pending: OutputGeometry,
+ committed: Option<OutputGeometry>,
+ logical_pending: LogicalGeometry,
+ logical_committed: Option<LogicalGeometry>,
+ xdg_version: Option<u32>,
+}
+
+impl OutputState {
+ fn commit_output(&mut self) {
+ self.committed = Some(self.pending);
+ if self.xdg_version.is_some_and(|version| version >= 3) {
+ self.logical_committed = Some(self.logical_pending);
+ }
+ }
+
+ fn display(&self, id: u32) -> Option<DisplayImpl> {
+ let geometry = self.committed?;
+ let (mut width, mut height, refresh) = geometry.mode?;
+ if width <= 0 || height <= 0 {
+ return None;
+ }
+ if geometry.rotated {
+ std::mem::swap(&mut width, &mut height);
+ }
+ let (position, size) = if self.xdg_version.is_some() {
+ let logical = self.logical_committed?;
+ (logical.position?, logical.size?)
+ } else {
+ let scale = geometry.scale.max(1);
+ (geometry.position, (width / scale, height / scale))
+ };
+ if size.0 <= 0 || size.1 <= 0 {
+ return None;
+ }
+ Some(DisplayImpl {
+ id,
+ x: position.0,
+ y: position.1,
+ width: width as u32,
+ height: height as u32,
+ refresh_rate: if refresh > 0 {
+ f64::from(refresh) / 1000.0
+ } else {
+ 60.0
+ },
+ wayland_uuid: geometry
+ .uuid
+ .or_else(|| self.logical_committed.and_then(|logical| logical.uuid)),
+ logical_bounds: Some(LogicalBounds::new(
+ LogicalPosition::new(position.0.into(), position.1.into()),
+ LogicalSize::new(size.0.into(), size.1.into()),
+ )),
+ })
+ }
+}
+
+#[derive(Default)]
+struct State {
+ globals: BTreeMap<u32, (String, u32)>,
+ outputs: BTreeMap<u32, OutputState>,
+ synced: bool,
+}
+
+pub(super) fn displays() -> Option<Vec<DisplayImpl>> {
+ let display = PathBuf::from(env::var_os("WAYLAND_DISPLAY")?);
+ let socket = if display.is_absolute() {
+ display
+ } else {
+ let runtime = PathBuf::from(env::var_os("XDG_RUNTIME_DIR")?);
+ if !runtime.is_absolute() {
+ return None;
+ }
+ runtime.join(display)
+ };
+ let connection = Connection::from_socket(UnixStream::connect(socket).ok()?).ok()?;
+ query(&connection, Duration::from_millis(250))
+}
+
+fn output_uuid(name: &str) -> Option<uuid::Uuid> {
+ (!name.is_empty()).then(|| uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_DNS, name.as_bytes()))
+}
+
+fn query(connection: &Connection, timeout: Duration) -> Option<Vec<DisplayImpl>> {
+ let deadline = Instant::now() + timeout;
+ let mut queue = connection.new_event_queue::<State>();
+ let handle = queue.handle();
+ let registry = connection.display().get_registry(&handle, ());
+ let mut state = State::default();
+ roundtrip(connection, &mut queue, &mut state, deadline)?;
+
+ let manager = state
+ .globals
+ .iter()
+ .find(|(_, (interface, _))| interface == "zxdg_output_manager_v1")
+ .map(|(&name, (_, version))| {
+ let version = (*version).min(3);
+ (
+ registry.bind::<zxdg_output_manager_v1::ZxdgOutputManagerV1, _, _>(
+ name,
+ version,
+ &handle,
+ (),
+ ),
+ version,
+ )
+ });
+ let mut legacy_outputs = Vec::new();
+ for (&name, (interface, version)) in &state.globals {
+ if interface != "wl_output" {
+ continue;
+ }
+ let version = (*version).min(4);
+ let output = registry.bind::<wl_output::WlOutput, _, _>(name, version, &handle, name);
+ let mut output_state = OutputState::default();
+ if let Some((manager, manager_version)) = &manager {
+ // XDG v3 batches geometry through wl_output.done, unavailable on wl_output v1.
+ if version >= 2 || *manager_version < 3 {
+ let _xdg_output = manager.get_xdg_output(&output, &handle, name);
+ output_state.xdg_version = Some(*manager_version);
+ }
+ }
+ if version < 2 {
+ legacy_outputs.push(name);
+ }
+ state.outputs.insert(name, output_state);
+ }
+ roundtrip(connection, &mut queue, &mut state, deadline)?;
+ for name in legacy_outputs {
+ if let Some(output) = state.outputs.get_mut(&name) {
+ output.commit_output();
+ }
+ }
+ Some(
+ state
+ .outputs
+ .values()
+ .enumerate()
+ .filter_map(|(index, output)| output.display(index as u32))
+ .collect(),
+ )
+}
+
+fn roundtrip(
+ connection: &Connection,
+ queue: &mut EventQueue<State>,
+ state: &mut State,
+ deadline: Instant,
+) -> Option<()> {
+ state.synced = false;
+ let _callback = connection.display().sync(&queue.handle(), ());
+ loop {
+ queue.dispatch_pending(state).ok()?;
+ if state.synced {
+ return Some(());
+ }
+ let remaining = deadline.saturating_duration_since(Instant::now());
+ if remaining.is_zero() {
+ return None;
+ }
+ connection.flush().ok()?;
+ let Some(guard) = queue.prepare_read() else {
+ continue;
+ };
+ let mut fds = [PollFd::new(connection, PollFlags::IN)];
+ let timeout = Timespec::try_from(remaining).ok()?;
+ match poll(&mut fds, Some(&timeout)) {
+ Ok(0) => return None,
+ Ok(_) if fds[0].revents().contains(PollFlags::IN) => {
+ guard.read().ok()?;
+ }
+ Err(rustix::io::Errno::INTR) => continue,
+ _ => return None,
+ }
+ }
+}
+
+impl Dispatch<wl_registry::WlRegistry, ()> for State {
+ fn event(
+ state: &mut Self,
+ _: &wl_registry::WlRegistry,
+ event: wl_registry::Event,
+ _: &(),
+ _: &Connection,
+ _: &QueueHandle<Self>,
+ ) {
+ match event {
+ wl_registry::Event::Global {
+ name,
+ interface,
+ version,
+ } => {
+ state.globals.insert(name, (interface, version));
+ }
+ wl_registry::Event::GlobalRemove { name } => {
+ state.globals.remove(&name);
+ state.outputs.remove(&name);
+ }
+ _ => {}
+ }
+ }
+}
+
+impl Dispatch<wl_callback::WlCallback, ()> for State {
+ fn event(
+ state: &mut Self,
+ _: &wl_callback::WlCallback,
+ _: wl_callback::Event,
+ _: &(),
+ _: &Connection,
+ _: &QueueHandle<Self>,
+ ) {
+ state.synced = true;
+ }
+}
+
+impl Dispatch<wl_output::WlOutput, u32> for State {
+ fn event(
+ state: &mut Self,
+ _: &wl_output::WlOutput,
+ event: wl_output::Event,
+ name: &u32,
+ _: &Connection,
+ _: &QueueHandle<Self>,
+ ) {
+ let Some(output) = state.outputs.get_mut(name) else {
+ return;
+ };
+ match event {
+ wl_output::Event::Geometry {
+ x, y, transform, ..
+ } => {
+ output.pending.position = (x, y);
+ output.pending.rotated = matches!(
+ transform,
+ WEnum::Value(
+ wl_output::Transform::_90
+ | wl_output::Transform::_270
+ | wl_output::Transform::Flipped90
+ | wl_output::Transform::Flipped270
+ )
+ );
+ }
+ wl_output::Event::Mode {
+ flags: WEnum::Value(flags),
+ width,
+ height,
+ refresh,
+ } if flags.contains(wl_output::Mode::Current) => {
+ output.pending.mode = Some((width, height, refresh));
+ }
+ wl_output::Event::Name { name } => output.pending.uuid = output_uuid(&name),
+ wl_output::Event::Scale { factor } => output.pending.scale = factor,
+ wl_output::Event::Done => output.commit_output(),
+ _ => {}
+ }
+ }
+}
+
+impl Dispatch<zxdg_output_manager_v1::ZxdgOutputManagerV1, ()> for State {
+ fn event(
+ _: &mut Self,
+ _: &zxdg_output_manager_v1::ZxdgOutputManagerV1,
+ _: zxdg_output_manager_v1::Event,
+ _: &(),
+ _: &Connection,
+ _: &QueueHandle<Self>,
+ ) {
+ }
+}
+
+impl Dispatch<zxdg_output_v1::ZxdgOutputV1, u32> for State {
+ fn event(
+ state: &mut Self,
+ _: &zxdg_output_v1::ZxdgOutputV1,
+ event: zxdg_output_v1::Event,
+ name: &u32,
+ _: &Connection,
+ _: &QueueHandle<Self>,
+ ) {
+ let Some(output) = state.outputs.get_mut(name) else {
+ return;
+ };
+ match event {
+ zxdg_output_v1::Event::LogicalPosition { x, y } => {
+ output.logical_pending.position = Some((x, y));
+ }
+ zxdg_output_v1::Event::LogicalSize { width, height } => {
+ output.logical_pending.size = Some((width, height));
+ }
+ zxdg_output_v1::Event::Name { name } => {
+ output.logical_pending.uuid = output_uuid(&name);
+ }
+ zxdg_output_v1::Event::Done => {
+ output.logical_committed = Some(output.logical_pending);
+ }
+ _ => {}
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn scaled_output() -> OutputState {
+ let mut output = OutputState {
+ pending: OutputGeometry {
+ mode: Some((1920, 1080, 59940)),
+ scale: 2,
+ ..Default::default()
+ },
+ xdg_version: Some(3),
+ logical_pending: LogicalGeometry {
+ position: Some((-960, 120)),
+ size: Some((960, 540)),
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+ output.commit_output();
+ output
+ }
+
+ #[test]
+ fn output_uuid_matches_gpui_name_identity_and_ignores_persisted_index() {
+ let mut output = scaled_output();
+ output.pending.uuid = output_uuid("HEADLESS-2");
+ output.commit_output();
+ let first = output.display(0).unwrap();
+ let second = output.display(8).unwrap();
+ let expected = uuid::Uuid::parse_str("db1cfde6-a307-5263-bfaa-7643e0b07250").unwrap();
+ assert_eq!(first.wayland_uuid(), Some(expected));
+ assert_eq!(second.wayland_uuid(), Some(expected));
+ assert_ne!(first.raw_id(), second.raw_id());
+ assert_ne!(output_uuid("HEADLESS-1"), output_uuid("HEADLESS-2"));
+ }
+
+ #[test]
+ fn output_uuid_uses_committed_core_name_then_xdg_fallback() {
+ let mut output = scaled_output();
+ output.logical_pending.uuid = output_uuid("HEADLESS-2");
+ assert_eq!(output.display(0).unwrap().wayland_uuid(), None);
+ output.commit_output();
+ assert_eq!(
+ output.display(0).unwrap().wayland_uuid(),
+ output_uuid("HEADLESS-2")
+ );
+ output.pending.uuid = output_uuid("HEADLESS-1");
+ assert_eq!(
+ output.display(0).unwrap().wayland_uuid(),
+ output_uuid("HEADLESS-2")
+ );
+ output.commit_output();
+ assert_eq!(
+ output.display(0).unwrap().wayland_uuid(),
+ output_uuid("HEADLESS-1")
+ );
+ }
+
+ #[test]
+ fn unnamed_output_has_no_uuid() {
+ assert_eq!(output_uuid(""), None);
+ assert_eq!(scaled_output().display(0).unwrap().wayland_uuid(), None);
+ }
+
+ #[test]
+ fn scaled_output_preserves_logical_and_physical_geometry() {
+ let display = scaled_output().display(0).unwrap();
+ assert_eq!(display.physical_size().unwrap().width(), 1920.0);
+ assert_eq!(display.logical_size().unwrap().width(), 960.0);
+ assert_eq!(display.logical_bounds().unwrap().position().x(), -960.0);
+ assert_eq!(display.logical_bounds().unwrap().position().y(), 120.0);
+ assert_eq!(display.refresh_rate(), 59.94);
+ }
+
+ #[test]
+ fn fractional_and_rotated_outputs_use_completed_xdg_geometry() {
+ let mut output = scaled_output();
+ output.pending.rotated = true;
+ output.logical_pending.size = Some((720, 1280));
+ assert_eq!(
+ output.display(0).unwrap().logical_size().unwrap().width(),
+ 960.0
+ );
+ output.commit_output();
+ let display = output.display(0).unwrap();
+ assert_eq!(display.physical_size().unwrap().width(), 1080.0);
+ assert_eq!(display.physical_size().unwrap().height(), 1920.0);
+ assert_eq!(display.logical_size().unwrap().width(), 720.0);
+ assert_eq!(display.logical_size().unwrap().height(), 1280.0);
+ }
+
+ #[test]
+ fn incomplete_and_invalid_geometry_is_not_reported() {
+ assert!(OutputState::default().display(0).is_none());
+ let mut output = scaled_output();
+ output.logical_pending.size = Some((0, 540));
+ output.commit_output();
+ assert!(output.display(0).is_none());
+ }
+
+ #[test]
+ fn core_output_scale_is_used_without_xdg_output() {
+ let mut output = scaled_output();
+ output.xdg_version = None;
+ assert_eq!(
+ output.display(0).unwrap().logical_size().unwrap().width(),
+ 960.0
+ );
+ }
+
+ #[test]
+ fn stalled_compositor_query_times_out() {
+ let (client, _server) = UnixStream::pair().unwrap();
+ let connection = Connection::from_socket(client).unwrap();
+ let started = Instant::now();
+ assert!(query(&connection, Duration::from_millis(20)).is_none());
+ assert!(started.elapsed() < Duration::from_secs(1));
+ }
+
+ #[test]
+ fn wayland_session_does_not_use_xwayland_dimensions() {
+ assert!(super::super::prefers_wayland_environment(
+ true,
+ true,
+ Some("wayland")
+ ));
+ assert!(super::super::prefers_wayland_environment(true, false, None));
+ assert!(!super::super::prefers_wayland_environment(
+ true,
+ true,
+ Some("x11")
+ ));
+ assert!(!super::super::prefers_wayland_environment(
+ false, true, None
+ ));
+ }
+}
diff --git a/crates/utils/src/lib.rs b/crates/utils/src/lib.rs
index 62f66283b..8587bafe4 100644
--- a/crates/utils/src/lib.rs
+++ b/crates/utils/src/lib.rs
@@ -16,6 +16,7 @@ pub mod linux_package;
pub mod linux_recording_stop;
#[cfg(any(target_os = "linux", test))]
pub mod linux_runtime;
+pub mod local_captions;
#[cfg(target_os = "macos")]
pub mod macos_qos;
diff --git a/crates/utils/src/local_captions.rs b/crates/utils/src/local_captions.rs
new file mode 100644
index 000000000..eca2bd66e
--- /dev/null
+++ b/crates/utils/src/local_captions.rs
@@ -0,0 +1,44 @@
+pub fn ensure_whisper_cpu_support() -> Result<(), &'static str> {
+ #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
+ {
+ validate_whisper_cpu_features(
+ std::is_x86_feature_detected!("avx2"),
+ std::is_x86_feature_detected!("fma"),
+ std::is_x86_feature_detected!("f16c"),
+ )
+ }
+ #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
+ {
+ Ok(())
+ }
+}
+
+#[cfg(any(target_arch = "x86", target_arch = "x86_64", test))]
+fn validate_whisper_cpu_features(avx2: bool, fma: bool, f16c: bool) -> Result<(), &'static str> {
+ // whisper-rs-sys 0.9.0 compiles its x86 engine with these instructions;
+ // entering that native code on an older CPU raises an uncatchable SIGILL.
+ if avx2 && fma && f16c {
+ Ok(())
+ } else {
+ Err("Whisper local captions require a CPU with AVX2, FMA, and F16C support.")
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::validate_whisper_cpu_features;
+
+ #[test]
+ fn unsupported_instruction_sets_are_rejected() {
+ for mask in 0..7 {
+ assert!(
+ validate_whisper_cpu_features(mask & 1 != 0, mask & 2 != 0, mask & 4 != 0).is_err()
+ );
+ }
+ }
+
+ #[test]
+ fn supported_instruction_set_is_accepted() {
+ assert!(validate_whisper_cpu_features(true, true, true).is_ok());
+ }
+}
diff --git a/scripts/prepare-gpui-dependency.sh b/scripts/prepare-gpui-dependency.sh
index 906b1a2ea..298404074 100755
--- a/scripts/prepare-gpui-dependency.sh
+++ b/scripts/prepare-gpui-dependency.sh
@@ -11,18 +11,29 @@ patch_files=(
base_revision="5d1f83d9f27a19bec1fb241dc33b42238af9cf8d"
remote="https://github.com/wingleeio/zed.git"
-verify_checkout() {
+verify_checkout() (
if ! git -C "$zed_dir" merge-base --is-ancestor "$base_revision" HEAD; then
echo "error: $zed_dir does not contain GPUI base $base_revision" >&2
exit 1
fi
- for patch_file in "${patch_files[@]}"; do
- if ! git -C "$zed_dir" apply --reverse --check --unidiff-zero "$patch_file"; then
+ verification_dir="$(mktemp -d "${TMPDIR:-/tmp}/cap-gpui-verify.XXXXXX")"
+ trap 'rm -rf -- "$verification_dir"' EXIT
+ git init --quiet "$verification_dir"
+ git -C "$zed_dir" apply --numstat -z "${patch_files[@]}" > "$verification_dir/patch-paths"
+ while IFS=$'\t' read -r -d '' added removed patched_path; do
+ if [[ -e "$zed_dir/$patched_path" ]]; then
+ mkdir -p "$verification_dir/$(dirname "$patched_path")"
+ cp -p "$zed_dir/$patched_path" "$verification_dir/$patched_path"
+ fi
+ done < "$verification_dir/patch-paths"
+ for ((patch_index=${#patch_files[@]}-1; patch_index>=0; patch_index--)); do
+ patch_file="${patch_files[patch_index]}"
+ if ! git -C "$verification_dir" apply --reverse --unidiff-zero "$patch_file"; then
echo "error: $zed_dir does not contain Cap's pinned GPUI patch: $patch_file" >&2
exit 1
fi
done
-}
+)
if [[ -e "$zed_dir/.git" ]]; then
verify_checkout
diff --git a/scripts/prepare-gpui-dependency.test.mjs b/scripts/prepare-gpui-dependency.test.mjs
index d8d89c29e..1e05556b8 100644
--- a/scripts/prepare-gpui-dependency.test.mjs
+++ b/scripts/prepare-gpui-dependency.test.mjs
@@ -2,6 +2,7 @@ import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import {
copyFileSync,
+ existsSync,
mkdirSync,
mkdtempSync,
readdirSync,
@@ -76,3 +77,127 @@ test("GPUI patches remain applicable after a Windows-style Git checkout", (t) =>
);
}
});
+
+test("dependency verification handles overlapping patches without changing the checkout", async (t) => {
+ const fixture = mkdtempSync(path.join(tmpdir(), "cap-gpui-patch-stack-"));
+ t.after(() => rmSync(fixture, { recursive: true, force: true }));
+ const emptyConfig = path.join(fixture, "empty.gitconfig");
+ writeFileSync(emptyConfig, "");
+ const env = {
+ ...Object.fromEntries(
+ Object.entries(process.env).filter(([key]) => !key.startsWith("GIT_")),
+ ),
+ GIT_CONFIG_NOSYSTEM: "1",
+ GIT_CONFIG_GLOBAL: emptyConfig,
+ GIT_ATTR_NOSYSTEM: "1",
+ };
+ const run = (cwd, command, args) => {
+ const result = spawnSync(command, args, {
+ cwd,
+ env,
+ encoding: "utf8",
+ timeout: 30_000,
+ });
+ assert.ifError(result.error);
+ return result;
+ };
+ const git = (cwd, ...args) => {
+ const result = run(cwd, "git", args);
+ assert.equal(result.status, 0, result.stderr);
+ return result.stdout;
+ };
+ const upstream = path.join(fixture, "upstream");
+ const cap = path.join(fixture, "Cap checkout");
+ const zed = path.join(fixture, "zed-cap");
+ mkdirSync(upstream);
+ mkdirSync(path.join(cap, "scripts"), { recursive: true });
+ mkdirSync(path.join(cap, patchDirectory), { recursive: true });
+ git(upstream, "init", "--quiet");
+ git(upstream, "config", "user.name", "Fixture");
+ git(upstream, "config", "user.email", "[email protected]");
+ const commit = () => {
+ git(upstream, "add", "--all");
+ git(upstream, "commit", "--quiet", "-m", "Fixture state");
+ };
+ writeFileSync(path.join(upstream, "renderer.rs"), "base\n");
+ writeFileSync(path.join(upstream, "windows.rs"), "base\n");
+ commit();
+ const base = git(upstream, "rev-parse", "HEAD").trim();
+ const patch = (name) => {
+ git(upstream, "add", "--all");
+ writeFileSync(
+ path.join(cap, patchDirectory, name),
+ git(upstream, "diff", "--cached", "--binary"),
+ );
+ commit();
+ };
+ writeFileSync(path.join(upstream, "renderer.rs"), "shared renderer\n");
+ writeFileSync(path.join(upstream, "temporary.rs"), "intermediate\n");
+ patch("zed-gpui.patch");
+ writeFileSync(path.join(upstream, "windows.rs"), "Windows renderer\n");
+ patch("zed-windows.patch");
+ writeFileSync(path.join(upstream, "renderer.rs"), "Linux renderer\n");
+ rmSync(path.join(upstream, "temporary.rs"));
+ patch("zed-linux.patch");
+ const script = path.join(cap, "scripts/prepare-gpui-dependency.sh");
+ writeFileSync(
+ script,
+ readFileSync(
+ path.join(repositoryRoot, "scripts/prepare-gpui-dependency.sh"),
+ "utf8",
+ )
+ .replace("5d1f83d9f27a19bec1fb241dc33b42238af9cf8d", base)
+ .replace("https://github.com/wingleeio/zed.git", upstream),
+ );
+
+ await t.test("fresh preparation validates the complete ordered stack", () => {
+ const result = run(cap, "bash", [script]);
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(
+ readFileSync(path.join(zed, "renderer.rs"), "utf8"),
+ "Linux renderer\n",
+ );
+ assert.equal(existsSync(path.join(zed, "temporary.rs")), false);
+ });
+
+ writeFileSync(path.join(zed, "unrelated.txt"), "preserve staged work\n");
+ git(zed, "add", "unrelated.txt");
+ writeFileSync(path.join(zed, "unrelated.txt"), "preserve unstaged work\n");
+ const fingerprint = () => ({
+ index: readFileSync(path.join(zed, ".git/index")),
+ renderer: readFileSync(path.join(zed, "renderer.rs")),
+ unrelated: readFileSync(path.join(zed, "unrelated.txt")),
+ status: git(zed, "status", "--porcelain"),
+ head: git(zed, "rev-parse", "HEAD"),
+ });
+
+ await t.test(
+ "repeat verification preserves source, index, and unrelated work",
+ () => {
+ const before = fingerprint();
+ for (let repeat = 0; repeat < 2; repeat++) {
+ const result = run(cap, "bash", [script]);
+ assert.equal(result.status, 0, result.stderr);
+ assert.deepEqual(fingerprint(), before);
+ }
+ },
+ );
+
+ await t.test(
+ "a missing final patch fails without repairing or overwriting files",
+ () => {
+ git(
+ zed,
+ "apply",
+ "--reverse",
+ path.join(cap, patchDirectory, "zed-linux.patch"),
+ );
+ const before = fingerprint();
+ const result = run(cap, "bash", [script]);
+ assert.equal(result.status, 1);
+ assert.match(result.stderr, /does not contain Cap's pinned GPUI patch/);
+ assert.deepEqual(fingerprint(), before);
+ assert.equal(existsSync(path.join(zed, "temporary.rs")), true);
+ },
+ );
+});