Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix(desktop): restore native Windows and Linux window behavior
Richie McIlroy597728932a0d
diff --git a/apps/desktop-gpui/assets/icons/caption-close-windows.svg b/apps/desktop-gpui/assets/icons/caption-close-windows.svgnew file mode 100644index 000000000..81697c141--- /dev/null+++ b/apps/desktop-gpui/assets/icons/caption-close-windows.svg@@ -0,0 +1,3 @@+<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 10 10" fill="none">+ <path d="M5 5.70898L0.854492 9.85449C0.756836 9.95215 0.639648 10.001 0.50293 10.001C0.359701 10.001 0.239258 9.95378 0.141602 9.85938C0.0472005 9.76172 0 9.64128 0 9.49805C0 9.36133 0.0488281 9.24414 0.146484 9.14648L4.29199 5.00098L0.146484 0.855469C0.0488281 0.757812 0 0.638997 0 0.499023C0 0.430664 0.0130208 0.36556 0.0390625 0.303711C0.0651042 0.241862 0.100911 0.189779 0.146484 0.147461C0.192057 0.101888 0.245768 0.0660807 0.307617 0.0400391C0.369466 0.0139974 0.43457 0.000976562 0.50293 0.000976562C0.639648 0.000976562 0.756836 0.0498047 0.854492 0.147461L5 4.29297L9.14551 0.147461C9.24316 0.0498047 9.36198 0.000976562 9.50195 0.000976562C9.57031 0.000976562 9.63379 0.0139974 9.69238 0.0400391C9.75423 0.0660807 9.80794 0.101888 9.85352 0.147461C9.89909 0.193034 9.9349 0.246745 9.96094 0.308594C9.98698 0.367188 10 0.430664 10 0.499023C10 0.638997 9.95117 0.757812 9.85352 0.855469L5.70801 5.00098L9.85352 9.14648C9.95117 9.24414 10 9.36133 10 9.49805C10 9.56641 9.98698 9.63151 9.96094 9.69336C9.9349 9.75521 9.89909 9.80892 9.85352 9.85449C9.8112 9.90007 9.75911 9.93587 9.69727 9.96191C9.63542 9.98796 9.57031 10.001 9.50195 10.001C9.36198 10.001 9.24316 9.95215 9.14551 9.85449L5 5.70898Z" fill="currentColor" fill-opacity="0.8956"/>+</svg>diff --git a/apps/desktop-gpui/assets/icons/caption-maximize-windows.svg b/apps/desktop-gpui/assets/icons/caption-maximize-windows.svgnew file mode 100644index 000000000..2b1021921--- /dev/null+++ b/apps/desktop-gpui/assets/icons/caption-maximize-windows.svg@@ -0,0 +1,3 @@+<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 10 10" fill="none">+ <path d="M1.47461 10.001C1.2793 10.001 1.09212 9.96191 0.913086 9.88379C0.734049 9.80241 0.576172 9.69499 0.439453 9.56152C0.30599 9.4248 0.198568 9.26693 0.117188 9.08789C0.0390625 8.90885 0 8.72168 0 8.52637V1.47559C0 1.28027 0.0390625 1.0931 0.117188 0.914062C0.198568 0.735026 0.30599 0.578776 0.439453 0.445312C0.576172 0.308594 0.734049 0.201172 0.913086 0.123047C1.09212 0.0416667 1.2793 0.000976562 1.47461 0.000976562H8.52539C8.7207 0.000976562 8.90788 0.0416667 9.08691 0.123047C9.26595 0.201172 9.4222 0.308594 9.55566 0.445312C9.69238 0.578776 9.7998 0.735026 9.87793 0.914062C9.95931 1.0931 10 1.28027 10 1.47559V8.52637C10 8.72168 9.95931 8.90885 9.87793 9.08789C9.7998 9.26693 9.69238 9.4248 9.55566 9.56152C9.4222 9.69499 9.26595 9.80241 9.08691 9.88379C8.90788 9.96191 8.7207 10.001 8.52539 10.001H1.47461ZM8.50098 9C8.56934 9 8.63281 8.98698 8.69141 8.96094C8.75326 8.9349 8.80697 8.89909 8.85254 8.85352C8.89811 8.80794 8.93392 8.75586 8.95996 8.69727C8.986 8.63542 8.99902 8.57031 8.99902 8.50195V1.5C8.99902 1.43164 8.986 1.36816 8.95996 1.30957C8.93392 1.24772 8.89811 1.19401 8.85254 1.14844C8.80697 1.10286 8.75326 1.06706 8.69141 1.04102C8.63281 1.01497 8.56934 1.00195 8.50098 1.00195H1.49902C1.43066 1.00195 1.36556 1.01497 1.30371 1.04102C1.24512 1.06706 1.19303 1.10286 1.14746 1.14844C1.10189 1.19401 1.06608 1.24772 1.04004 1.30957C1.014 1.36816 1.00098 1.43164 1.00098 1.5V8.50195C1.00098 8.57031 1.014 8.63542 1.04004 8.69727C1.06608 8.75586 1.10189 8.80794 1.14746 8.85352C1.19303 8.89909 1.24512 8.9349 1.30371 8.96094C1.36556 8.98698 1.43066 9 1.49902 9H8.50098Z" fill="currentColor" fill-opacity="0.8956"/>+</svg>diff --git a/apps/desktop-gpui/assets/icons/caption-minimize-windows.svg b/apps/desktop-gpui/assets/icons/caption-minimize-windows.svgnew file mode 100644index 000000000..d6d32e0bc--- /dev/null+++ b/apps/desktop-gpui/assets/icons/caption-minimize-windows.svg@@ -0,0 +1,3 @@+<svg xmlns="http://www.w3.org/2000/svg" width="10" height="1" viewBox="0 0 10 1" fill="none">+ <path d="M0.498047 1.00098C0.429688 1.00098 0.364583 0.987956 0.302734 0.961914C0.244141 0.935872 0.192057 0.900065 0.146484 0.854492C0.100911 0.808919 0.0651042 0.756836 0.0390625 0.698242C0.0130208 0.636393 0 0.571289 0 0.50293C0 0.43457 0.0130208 0.371094 0.0390625 0.3125C0.0651042 0.250651 0.100911 0.19694 0.146484 0.151367C0.192057 0.102539 0.244141 0.0651042 0.302734 0.0390625C0.364583 0.0130208 0.429688 0 0.498047 0H9.50195C9.57031 0 9.63379 0.0130208 9.69238 0.0390625C9.75423 0.0651042 9.80794 0.102539 9.85352 0.151367C9.89909 0.19694 9.9349 0.250651 9.96094 0.3125C9.98698 0.371094 10 0.43457 10 0.50293C10 0.571289 9.98698 0.636393 9.96094 0.698242C9.9349 0.756836 9.89909 0.808919 9.85352 0.854492C9.80794 0.900065 9.75423 0.935872 9.69238 0.961914C9.63379 0.987956 9.57031 1.00098 9.50195 1.00098H0.498047Z" fill="currentColor" fill-opacity="0.8956"/>+</svg>diff --git a/apps/desktop-gpui/assets/icons/caption-restore-windows.svg b/apps/desktop-gpui/assets/icons/caption-restore-windows.svgnew file mode 100644index 000000000..25ccb4ea4--- /dev/null+++ b/apps/desktop-gpui/assets/icons/caption-restore-windows.svg@@ -0,0 +1,3 @@+<svg xmlns="http://www.w3.org/2000/svg" width="10" height="11" viewBox="0 0 10 11" fill="none">+ <path d="M8.99902 2.98096C8.99902 2.71077 8.94531 2.45687 8.83789 2.21924C8.73047 1.97835 8.58398 1.77002 8.39844 1.59424C8.21615 1.4152 8.00293 1.27523 7.75879 1.17432C7.5179 1.07015 7.264 1.01807 6.99707 1.01807H2.08496C2.13704 0.868327 2.21029 0.731608 2.30469 0.60791C2.39909 0.484212 2.50814 0.378418 2.63184 0.290527C2.75553 0.202637 2.89062 0.135905 3.03711 0.090332C3.18685 0.0415039 3.34147 0.0170898 3.50098 0.0170898H6.99707C7.41048 0.0170898 7.79948 0.0968424 8.16406 0.256348C8.52865 0.412598 8.84603 0.625814 9.11621 0.895996C9.38965 1.16618 9.60449 1.48356 9.76074 1.84814C9.92025 2.21273 10 2.60173 10 3.01514V6.51611C10 6.67562 9.97559 6.83024 9.92676 6.97998C9.88118 7.12646 9.81445 7.26156 9.72656 7.38525C9.63867 7.50895 9.53288 7.618 9.40918 7.7124C9.28548 7.8068 9.14876 7.88005 8.99902 7.93213V2.98096ZM1.47461 10.0171C1.2793 10.0171 1.09212 9.97803 0.913086 9.8999C0.734049 9.81852 0.576172 9.7111 0.439453 9.57764C0.30599 9.44092 0.198568 9.28304 0.117188 9.104C0.0390625 8.92497 0 8.73779 0 8.54248V3.49365C0 3.29508 0.0390625 3.10791 0.117188 2.93213C0.198568 2.75309 0.30599 2.59684 0.439453 2.46338C0.576172 2.32666 0.732422 2.21924 0.908203 2.14111C1.08724 2.05973 1.27604 2.01904 1.47461 2.01904H6.52344C6.72201 2.01904 6.91081 2.05973 7.08984 2.14111C7.26888 2.21924 7.42513 2.32503 7.55859 2.4585C7.69206 2.59196 7.79785 2.74821 7.87598 2.92725C7.95736 3.10628 7.99805 3.29508 7.99805 3.49365V8.54248C7.99805 8.74105 7.95736 8.92985 7.87598 9.10889C7.79785 9.28467 7.69043 9.44092 7.55371 9.57764C7.42025 9.7111 7.264 9.81852 7.08496 9.8999C6.90918 9.97803 6.72201 10.0171 6.52344 10.0171H1.47461ZM6.49902 9.01611C6.56738 9.01611 6.63086 9.00309 6.68945 8.97705C6.7513 8.95101 6.80501 8.9152 6.85059 8.86963C6.89941 8.82406 6.93685 8.77197 6.96289 8.71338C6.98893 8.65153 7.00195 8.58643 7.00195 8.51807V3.51807C7.00195 3.44971 6.98893 3.3846 6.96289 3.32275C6.93685 3.2609 6.90104 3.20719 6.85547 3.16162C6.8099 3.11605 6.75618 3.08024 6.69434 3.0542C6.63249 3.02816 6.56738 3.01514 6.49902 3.01514H1.49902C1.43066 3.01514 1.36556 3.02816 1.30371 3.0542C1.24512 3.08024 1.19303 3.11768 1.14746 3.1665C1.10189 3.21208 1.06608 3.26579 1.04004 3.32764C1.014 3.38623 1.00098 3.44971 1.00098 3.51807V8.51807C1.00098 8.58643 1.014 8.65153 1.04004 8.71338C1.06608 8.77197 1.10189 8.82406 1.14746 8.86963C1.19303 8.9152 1.24512 8.95101 1.30371 8.97705C1.36556 9.00309 1.43066 9.01611 1.49902 9.01611H6.49902Z" fill="currentColor" fill-opacity="0.8956"/>+</svg>diff --git a/apps/desktop-gpui/patches/zed-linux.patch b/apps/desktop-gpui/patches/zed-linux.patchnew file mode 100644index 000000000..93d8da1d6--- /dev/null+++ b/apps/desktop-gpui/patches/zed-linux.patch@@ -0,0 +1,167 @@+diff --git a/crates/gpui_linux/src/linux/wayland/window.rs b/crates/gpui_linux/src/linux/wayland/window.rs+index 993b2ff3fa..c59ee3927c 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 {++ fixed_outer_size: Option<Size<Pixels>>,++ fixed_geometry_size: Option<Size<i32>>,+@@ -594 +596 @@ impl WaylandWindowState {+- Ok(Self {++ let mut state = Self {+@@ -607,0 +610,2 @@ impl WaylandWindowState {++ fixed_outer_size: (!options.is_resizable).then_some(options.bounds.size),++ fixed_geometry_size: None,+@@ -629 +633,24 @@ impl WaylandWindowState {+- })++ };++ state.update_size_constraints();++ Ok(state)++ }++++ fn update_size_constraints(&mut self) {++ let Some(outer_size) = self.fixed_outer_size else {++ return;++ };++ let geometry_size = fixed_window_geometry_size(++ outer_size,++ self.inset(),++ self.tiling,++ self.renderer.max_texture_size(),++ self.scale,++ );++ if self.fixed_geometry_size == Some(geometry_size) {++ return;++ }++ if let Some(toplevel) = self.surface_state.toplevel() {++ toplevel.set_min_size(geometry_size.width, geometry_size.height);++ toplevel.set_max_size(geometry_size.width, geometry_size.height);++ self.fixed_geometry_size = Some(geometry_size);++ }+@@ -903,0 +931 @@ impl WaylandWindowStatePtr {++ state.update_size_constraints();+@@ -961 +989,5 @@ impl WaylandWindowStatePtr {+- 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 {+- 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 {++ state.update_size_constraints();+@@ -1469 +1506 @@ impl PlatformWindow for WaylandWindow {+- let state = self.borrow();++ let mut state = self.borrow_mut();+@@ -1488,0 +1526,5 @@ impl PlatformWindow for WaylandWindow {++ 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 {++ if state.fixed_outer_size.is_some() {++ return;++ }+@@ -1856,0 +1902 @@ impl PlatformWindow for WaylandWindow {++ state.update_size_constraints();+@@ -1865,0 +1912 @@ impl PlatformWindow for WaylandWindow {++ state.update_size_constraints();+@@ -1878,0 +1926 @@ impl PlatformWindow for WaylandWindow {++ state.update_size_constraints();+@@ -2084,0 +2133,90 @@ fn inset_by_tiling(mut bounds: Bounds<Pixels>, inset: Pixels, tiling: Tiling) ->++++fn fixed_window_geometry_size(++ outer_size: Size<Pixels>,++ inset: Pixels,++ tiling: Tiling,++ max_texture_size: u32,++ scale: f32,++) -> Size<i32> {++ let limit = (max_texture_size as f32 / scale.max(f32::EPSILON)).max(1.0);++ let outer_size = outer_size.map(|value| px(f32::from(value).clamp(1.0, limit)));++ inset_by_tiling(++ Bounds {++ origin: Point::default(),++ size: outer_size,++ },++ inset,++ tiling,++ )++ .size++ .map(|value| (f32::from(value) as i32).max(1))++}++++#[cfg(test)]++mod tests {++ use super::*;++++ #[test]++ fn fixed_size_tracks_programmatic_expansion_in_logical_pixels() {++ for height in [395.0, 440.0, 520.0, 395.0] {++ assert_eq!(++ fixed_window_geometry_size(++ size(px(330.0), px(height)),++ px(0.0),++ Tiling::default(),++ 8192,++ 2.0,++ ),++ size(330, height as i32),++ );++ }++ }++++ #[test]++ fn fixed_size_uses_the_same_insets_as_xdg_window_geometry() {++ for tiling in [++ Tiling::default(),++ Tiling::tiled(),++ Tiling {++ top: true,++ left: true,++ ..Tiling::default()++ },++ ] {++ let outer = size(px(330.0), px(395.0));++ let constrained = fixed_window_geometry_size(outer, px(8.0), tiling, 8192, 2.0);++ assert_eq!(++ compute_outer_size(++ px(8.0),++ Some(constrained.map(|value| px(value as f32))),++ tiling,++ ),++ Some(outer),++ );++ }++ }++++ #[test]++ fn fixed_size_stays_positive_and_within_the_scaled_texture_limit() {++ assert_eq!(++ fixed_window_geometry_size(++ size(px(10000.0), px(10000.0)),++ px(8.0),++ Tiling::default(),++ 8192,++ 2.0,++ ),++ size(4080, 4080),++ );++ assert_eq!(++ fixed_window_geometry_size(++ size(px(0.0), px(10.0)),++ px(8.0),++ Tiling::default(),++ 8192,++ 1.0,++ ),++ size(1, 1),++ );++ }++}diff --git a/apps/desktop-gpui/patches/zed-windows.patch b/apps/desktop-gpui/patches/zed-windows.patchnew file mode 100644index 000000000..06c1a5a17--- /dev/null+++ b/apps/desktop-gpui/patches/zed-windows.patch@@ -0,0 +1,345 @@+--- a/crates/gpui_windows/src/directx_renderer.rs++++ b/crates/gpui_windows/src/directx_renderer.rs+@@ -1985,0 +1986,38 @@++++#[cfg(test)]++mod tests {++ use super::shader_resources::{RawShaderBytes, ShaderModule, ShaderTarget};++ use gpui::{PolychromeSprite, Quad};++ use windows::{Win32::Graphics::Direct3D::Fxc::D3DDisassemble, core::PCSTR};++++ #[test]++ fn compiled_shader_strides_match_uploaded_primitives() {++ for (module, stride) in [++ (ShaderModule::Quad, size_of::<Quad>()),++ (++ ShaderModule::PolychromeSprite,++ size_of::<PolychromeSprite>(),++ ),++ ] {++ for target in [ShaderTarget::Vertex, ShaderTarget::Fragment] {++ let shader = RawShaderBytes::new(module, target).unwrap();++ let bytes = shader.as_bytes();++ let assembly = unsafe {++ D3DDisassemble(bytes.as_ptr().cast(), bytes.len(), 0, PCSTR::null()).unwrap()++ };++ let text = unsafe {++ std::slice::from_raw_parts(++ assembly.GetBufferPointer().cast::<u8>(),++ assembly.GetBufferSize(),++ )++ };++ let text = String::from_utf8_lossy(text);++ let declaration = format!("dcl_resource_structured t1, {stride}");++ assert!(++ text.lines().any(|line| line.trim() == declaration),++ "{module:?} {target:?} does not match Rust's {stride}-byte stride"++ );++ }++ }++ }++}+--- a/crates/gpui_windows/src/shaders.hlsl++++ b/crates/gpui_windows/src/shaders.hlsl+@@ -36,0 +37,11 @@++};++++struct EdgeFadeParams {++ float top_y;++ float bottom_y;++ float band_top;++ float band_bottom;++ float left_x;++ float right_x;++ float band_left;++ float band_right;+@@ -94,0 +106,17 @@++++float edge_fade_alpha(float2 position, EdgeFadeParams fade) {++ float ramp = 1.0;++ if (fade.band_top > 0.0) {++ ramp = min(ramp, saturate((position.y - fade.top_y) / fade.band_top));++ }++ if (fade.band_bottom > 0.0) {++ ramp = min(ramp, saturate((fade.bottom_y - position.y) / fade.band_bottom));++ }++ if (fade.band_left > 0.0) {++ ramp = min(ramp, saturate((position.x - fade.left_x) / fade.band_left));++ }++ if (fade.band_right > 0.0) {++ ramp = min(ramp, saturate((fade.right_x - position.x) / fade.band_right));++ }++ return ramp * ramp;++}+@@ -504,0 +533 @@++ EdgeFadeParams fade;+@@ -556,0 +586,2 @@++ float fade_alpha = edge_fade_alpha(input.position.xy, quad.fade);++ background_color.a *= fade_alpha;+@@ -663,0 +695 @@++ border_color.a *= fade_alpha;+@@ -1211,0 +1244 @@++ EdgeFadeParams fade;+@@ -1256 +1289 @@+- color.a *= sprite.opacity * saturate(0.5 - distance);++ color.a *= sprite.opacity * saturate(0.5 - distance) * edge_fade_alpha(input.position.xy, sprite.fade);+--- a/crates/gpui_windows/src/window.rs++++ b/crates/gpui_windows/src/window.rs+@@ -216 +216,5 @@+- placement.rcNormalPosition,++ translate_rect(++ placement.rcNormalPosition,++ workspace_offset(self.hwnd, self.display.get(), self.scale_factor.get()),++ 1,++ ),+@@ -463 +467 @@+- (WS_EX_TOOLWINDOW, WINDOW_STYLE(0x0))++ (WS_EX_TOOLWINDOW, WS_POPUP)+@@ -465,0 +470,5 @@++ if hide_title_bar {++ dwstyle |= WS_POPUP;++ } else {++ dwstyle |= WS_CAPTION;++ }+@@ -550,0 +560 @@++ params.window_min_size,+@@ -621,2 +631,30 @@+- 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());++ let mut rect = RECT::default();++ if unsafe { GetWindowRect(hwnd, &mut rect) }++ .log_err()++ .is_none()++ {++ return;++ }++ rect.right = rect.left + size.width.0 + self.state.border_offset.width_offset.get();++ rect.bottom = rect.top + size.height.0 + self.state.border_offset.height_offset.get();++ let movable = !is_tool_window(hwnd) && !self.state.is_fullscreen();++ if movable {++ rect = fit_window_rect(++ rect,++ self.state++ .display++ .get()++ .visible_bounds()++ .to_device_pixels(self.scale_factor()),++ minimum_outer_size(++ self.state.min_size,++ self.scale_factor(),++ &self.state.border_offset,++ ),++ );++ }++ let mut flags = SWP_NOACTIVATE | SWP_NOZORDER;++ if !movable {++ flags |= SWP_NOMOVE;++ }+@@ -631,2 +669,2 @@+- bounds.origin.x.0,+- bounds.origin.y.0,++ rect.left,++ rect.top,+@@ -635 +673 @@+- SWP_NOMOVE,++ flags,+@@ -637,0 +676,29 @@++ .log_err();++ }++ })++ .detach();++ }++++ fn start_window_move(&self) {++ if !self.is_movable {++ return;++ }++ let this = self.0.clone();++ self.executor++ .spawn(async move {++ let mut cursor = POINT::default();++ unsafe {++ if GetAsyncKeyState(VK_LBUTTON.0 as i32) >= 0++ || GetCursorPos(&mut cursor).log_err().is_none()++ {++ return;++ }++ ReleaseCapture().log_err();++ let position = (cursor.x as u16 as u32) | ((cursor.y as u16 as u32) << 16);++ PostMessageW(++ Some(this.hwnd),++ WM_SYSCOMMAND,++ WPARAM((SC_MOVE | HTCAPTION) as usize),++ LPARAM(position as isize),++ )++ .context("unable to start window move")+@@ -1510,0 +1578 @@++ minimum_size: Option<Size<Pixels>>,+@@ -1524 +1592,10 @@+- placement.rcNormalPosition = calculate_window_rect(bounds, border_offset);++ let mut rect = calculate_window_rect(bounds, border_offset);++ if !is_tool_window(hwnd) {++ rect = fit_window_rect(++ rect,++ display.visible_bounds().to_device_pixels(scale_factor),++ minimum_outer_size(minimum_size, scale_factor, border_offset),++ );++ }++ placement.rcNormalPosition =++ translate_rect(rect, workspace_offset(hwnd, display, scale_factor), -1);+@@ -1525,0 +1603,54 @@++}++++fn is_tool_window(hwnd: HWND) -> bool {++ unsafe { get_window_long(hwnd, GWL_EXSTYLE) as u32 & WS_EX_TOOLWINDOW.0 != 0 }++}++++fn workspace_offset(hwnd: HWND, display: WindowsDisplay, scale_factor: f32) -> Point<DevicePixels> {++ if is_tool_window(hwnd) {++ return point(DevicePixels(0), DevicePixels(0));++ }++ display++ .visible_bounds()++ .to_device_pixels(scale_factor)++ .origin++ - display.physical_bounds().origin++}++++fn translate_rect(mut rect: RECT, offset: Point<DevicePixels>, direction: i32) -> RECT {++ rect.left += offset.x.0 * direction;++ rect.right += offset.x.0 * direction;++ rect.top += offset.y.0 * direction;++ rect.bottom += offset.y.0 * direction;++ rect++}++++fn minimum_outer_size(++ minimum: Option<Size<Pixels>>,++ scale_factor: f32,++ border_offset: &WindowBorderOffset,++) -> Size<DevicePixels> {++ let minimum = minimum.unwrap_or_default().to_device_pixels(scale_factor);++ size(++ DevicePixels((minimum.width.0 + border_offset.width_offset.get()).max(1)),++ DevicePixels((minimum.height.0 + border_offset.height_offset.get()).max(1)),++ )++}++++fn fit_window_rect(rect: RECT, work: Bounds<DevicePixels>, minimum: Size<DevicePixels>) -> RECT {++ let width =++ (rect.right - rect.left).clamp(minimum.width.0, work.size.width.0.max(minimum.width.0));++ let height =++ (rect.bottom - rect.top).clamp(minimum.height.0, work.size.height.0.max(minimum.height.0));++ let left = rect++ .left++ .clamp(work.left().0, (work.right().0 - width).max(work.left().0));++ let top = rect++ .top++ .clamp(work.top().0, (work.bottom().0 - height).max(work.top().0));++ RECT {++ left,++ top,++ right: left + width,++ bottom: top + height,++ }+@@ -1612,2 +1743,2 @@+- use super::ClickState;+- use gpui::{DevicePixels, MouseButton, point};++ use super::{ClickState, fit_window_rect, translate_rect};++ use gpui::{Bounds, DevicePixels, MouseButton, point, size};+@@ -1614,0 +1746,66 @@++ use windows::Win32::Foundation::RECT;++++ #[test]++ fn expanded_window_moves_above_bottom_taskbar() {++ let work = Bounds {++ origin: point(DevicePixels(0), DevicePixels(0)),++ size: size(DevicePixels(1280), DevicePixels(760)),++ };++ let rect = fit_window_rect(++ RECT {++ left: 467,++ top: 199,++ right: 1083,++ bottom: 867,++ },++ work,++ size(DevicePixels(1), DevicePixels(1)),++ );++ assert_eq!(++ (rect.left, rect.top, rect.right, rect.bottom),++ (467, 92, 1083, 760)++ );++ }++++ #[test]++ fn oversized_settings_shrink_but_editor_minimum_is_preserved() {++ let work = Bounds {++ origin: point(DevicePixels(-1280), DevicePixels(0)),++ size: size(DevicePixels(1280), DevicePixels(760)),++ };++ let requested = RECT {++ left: -1100,++ top: -15,++ right: -302,++ bottom: 799,++ };++ let settings = fit_window_rect(requested, work, size(DevicePixels(796), DevicePixels(599)));++ assert_eq!(++ (settings.left, settings.top, settings.right, settings.bottom),++ (-1100, 0, -302, 760)++ );++ let editor = fit_window_rect(requested, work, size(DevicePixels(1296), DevicePixels(839)));++ assert_eq!(++ (editor.left, editor.top, editor.right, editor.bottom),++ (-1280, 0, 16, 839)++ );++ }++++ #[test]++ fn top_and_left_taskbar_workspace_coordinates_round_trip() {++ let screen = RECT {++ left: -1800,++ top: 80,++ right: -900,++ bottom: 700,++ };++ for offset in [++ point(DevicePixels(0), DevicePixels(40)),++ point(DevicePixels(60), DevicePixels(0)),++ ] {++ let workspace = translate_rect(screen, offset, -1);++ assert_eq!(workspace.left, screen.left - offset.x.0);++ assert_eq!(workspace.top, screen.top - offset.y.0);++ assert_eq!(translate_rect(workspace, offset, 1), screen);++ }++ }+--- a/crates/gpui_windows/src/events.rs++++ b/crates/gpui_windows/src/events.rs+@@ -847,5 +846,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 +852,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 +866,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);diff --git a/apps/desktop-gpui/src/app_windows.rs b/apps/desktop-gpui/src/app_windows.rsindex a07107f0a..655475184 100644--- a/apps/desktop-gpui/src/app_windows.rs+++ b/apps/desktop-gpui/src/app_windows.rs@@ -383,6 +383,10 @@ pub fn show_main_window(cx: &mut App) {// focus gate; here the reshow *is* the trigger, so a recording// made a moment ago is in the list without a restart.view.refresh_recents(window, cx);+ #[cfg(target_os = "linux")]+ if let Err(error) = platform::set_x11_window_visible(window, true) {+ tracing::warn!(%error, "could not show the X11 main window");+ }platform::native_window(window)}).ok()@@ -454,7 +458,13 @@ pub fn heal_main_window_style(cx: &mut App) {pub fn hide_main_window(cx: &mut App) {let main = cx.global::<AppWindows>().main;let native = main- .update(cx, |_, window, _| platform::native_window(window))+ .update(cx, |_, window, _| {+ #[cfg(target_os = "linux")]+ if let Err(error) = platform::set_x11_window_visible(window, false) {+ tracing::warn!(%error, "could not hide the X11 main window");+ }+ platform::native_window(window)+ }).ok().flatten();cx.spawn(async move |cx| {@@ -603,7 +613,7 @@ pub fn open_settings(page: Page, cx: &mut App) {// hand-draws its own.)titlebar: Some(gpui::TitlebarOptions {title: Some("Cap Settings".into()),- appears_transparent: true,+ appears_transparent: !cfg!(target_os = "windows"),traffic_light_position: Some(settings_window::TRAFFIC_LIGHTS),}),// A normal window, not a panel: the Tauri Settings window is an@@ -748,7 +758,7 @@ pub fn open_onboarding(cx: &mut App) {window_bounds: Some(WindowBounds::Windowed(bounds)),titlebar: Some(gpui::TitlebarOptions {title: Some("Welcome to Cap".into()),- appears_transparent: true,+ appears_transparent: !cfg!(target_os = "windows"),traffic_light_position: Some(onboarding_window::TRAFFIC_LIGHTS),}),kind: WindowKind::Normal,@@ -882,7 +892,7 @@ pub fn open_mode_select(cx: &mut App) -> bool {// `TitleBarStyle::Overlay`).titlebar: Some(gpui::TitlebarOptions {title: Some("Cap Mode Selection".into()),- appears_transparent: true,+ appears_transparent: !cfg!(target_os = "windows"),traffic_light_position: mode_select_window::TRAFFIC_LIGHTS,}),// An ordinary window that activates the dock icon@@ -997,7 +1007,7 @@ pub fn open_teleprompter(cx: &mut App) {// buttons, moved, as on the settings window.titlebar: Some(gpui::TitlebarOptions {title: Some("Cap Teleprompter".into()),- appears_transparent: true,+ appears_transparent: !cfg!(target_os = "windows"),traffic_light_position: Some(teleprompter_window::TRAFFIC_LIGHTS),}),// `alwaysOnTop: true` + `visibleOnAllWorkspaces: true` are applied@@ -1589,6 +1599,8 @@ fn open_overlay(// one overlay has to hold focus for it to arrive.let focus_handle = view.focus_handle();window.focus(&focus_handle, cx);+ #[cfg(any(target_os = "linux", target_os = "windows"))]+ window.activate_window();}window.refresh();})@@ -2084,10 +2096,27 @@ pub fn open_camera_window(cx: &mut App) {origin: point(px(x), px(y)),size: size(px(width), px(height)),})),+ #[cfg(not(target_os = "linux"))]titlebar: None,+ #[cfg(target_os = "linux")]+ titlebar: Some(gpui::TitlebarOptions {+ title: Some("Cap Camera".into()),+ ..Default::default()+ }),+ #[cfg(target_os = "linux")]+ app_id: Some("Cap".into()),+ #[cfg(target_os = "linux")]+ window_decorations: Some(gpui::WindowDecorations::Client),// Non-activating panel, same as the bar: the bubble is clickable// without stealing focus from what is being recorded.+ #[cfg(not(target_os = "linux"))]kind: WindowKind::PopUp,+ #[cfg(target_os = "linux")]+ kind: if cap_recording::screenshot::uses_wayland_portal() {+ WindowKind::Floating+ } else {+ WindowKind::PopUp+ },focus: false,show: true,is_resizable: false,@@ -2163,6 +2192,9 @@ fn camera_frame(cx: &mut App) -> Option<CameraFrame> {handle.update(cx, |_, window, _| {let native = platform::native_window(window)?;+ #[cfg(target_os = "windows")]+ let frame = platform::window_logical_frame(&native);+ #[cfg(not(target_os = "windows"))]let frame = platform::window_frame(&native);let origin = window.bounds().origin;Some(CameraFrame {@@ -2186,11 +2218,20 @@ fn move_camera_window(camera: CameraFrame, to: (f32, f32), cx: &mut App) {if dx.abs() < 0.5 && dy.abs() < 0.5 {return;}+ #[cfg(not(target_os = "windows"))]let (frame_x, frame_y, width, height) = camera.frame;+ #[cfg(target_os = "windows")]+ let (_, _, width, height) = camera.frame;+ #[cfg(target_os = "windows")]+ let (x, y) = (f64::from(to.0), f64::from(to.1));// gpui +y is down, AppKit +y is up.+ #[cfg(not(target_os = "windows"))]let (x, y) = (frame_x + dx, frame_y - dy);let native = camera.native;cx.spawn(async move |_| {+ #[cfg(target_os = "windows")]+ platform::set_window_logical_frame(&native, x, y, width, height);+ #[cfg(not(target_os = "windows"))]platform::set_window_frame(&native, x, y, width, height);}).detach();@@ -2416,7 +2457,7 @@ pub fn open_editor(project_path: PathBuf, cx: &mut App) {// left group reserves an `h-full w-16` spacer for them.titlebar: Some(gpui::TitlebarOptions {title: Some("Cap Editor".into()),- appears_transparent: true,+ appears_transparent: !cfg!(target_os = "windows"),traffic_light_position: editor_window::TRAFFIC_LIGHTS,}),// An ordinary window that activates the dock icon@@ -2458,6 +2499,8 @@ pub fn open_editor(project_path: PathBuf, cx: &mut App) {handle.update(cx, |view, window, cx| {platform::kick_display_link(window);+ #[cfg(target_os = "windows")]+ platform::maximize_if_larger_than_work_area(window, cx);view.focus_root(window, cx);tracing::info!(number = platform::window_number(window),@@ -3599,7 +3642,7 @@ pub fn open_screenshot_editor(path: PathBuf, cx: &mut App) {window_bounds: Some(WindowBounds::Windowed(bounds)),titlebar: Some(gpui::TitlebarOptions {title: Some("Cap Screenshot Editor".into()),- appears_transparent: true,+ appears_transparent: !cfg!(target_os = "windows"),traffic_light_position: None,}),kind: WindowKind::Normal,diff --git a/apps/desktop-gpui/src/assets.rs b/apps/desktop-gpui/src/assets.rsindex 7af985b8a..03be91d21 100644--- a/apps/desktop-gpui/src/assets.rs+++ b/apps/desktop-gpui/src/assets.rs@@ -47,6 +47,10 @@ const ICONS: &[(&str, &[u8])] = assets!("icons":"camera.svg","caret-down.svg","captions.svg",+ "caption-close-windows.svg",+ "caption-maximize-windows.svg",+ "caption-minimize-windows.svg",+ "caption-restore-windows.svg","circle.svg","check.svg","clapperboard.svg",diff --git a/apps/desktop-gpui/src/camera_window.rs b/apps/desktop-gpui/src/camera_window.rsindex 6ab01a30f..353fad823 100644--- a/apps/desktop-gpui/src/camera_window.rs+++ b/apps/desktop-gpui/src/camera_window.rs@@ -442,10 +442,11 @@ impl CameraPreviewView {frame: Arc<gpui::RenderImage>,dims: (usize, usize),cx: &mut Context<Self>,- ) {- self.latest_frame = Some(frame);+ ) -> Option<Arc<gpui::RenderImage>> {+ let previous = self.latest_frame.replace(frame);self.frame_dims = Some(dims);cx.notify();+ previous}fn set_chrome(&mut self, radius: f32, size: f32, cx: &mut Context<Self>) {@@ -509,6 +510,7 @@ impl Render for CameraPreviewView {container = container.child(gpui::img(image).size_full()+ .rounded(px(radius)).object_fit(gpui::ObjectFit::Cover),);}@@ -659,6 +661,13 @@ impl CameraWindow {// `document.documentElement.classList.toggle("dark", true)`// (`camera.tsx:128`): the bubble is always dark, whatever the app// theme preference says.+ #[cfg(target_os = "windows")]+ platform::apply_window_theme(+ window,+ platform::ForcedAppearance::Dark,+ cx.foreground_executor(),+ );+ #[cfg(not(target_os = "windows"))]platform::apply_window_theme(window, platform::ForcedAppearance::Dark);let theme = Theme::dark();let state = store::load().camera_window.unwrap_or_default();@@ -790,9 +799,12 @@ impl CameraWindow {let first_frame = self.frame_dims.is_none();let dims_changed = self.frame_dims != Some(frame.dims);self.frame_dims = Some(frame.dims);- self.preview.update(cx, |preview, cx| {+ let previous = self.preview.update(cx, |preview, cx| {preview.set_frame(frame.image, frame.dims, cx)});+ if let Some(previous) = previous {+ let _ = window.drop_image(previous);+ }if dims_changed {self.apply_window_size(window, cx);cx.notify();@@ -997,6 +1009,23 @@ impl CameraWindow {}}+ #[cfg(target_os = "windows")]+ if let Some(native) = platform::native_window(window) {+ cx.spawn(async move |_, _| {+ platform::set_window_logical_frame(+ &native,+ f64::from(new_x),+ f64::from(new_y),+ f64::from(width),+ f64::from(height),+ );+ })+ .detach();+ } else {+ window.resize(size(px(width), px(height)));+ }++ #[cfg(not(target_os = "windows"))]if let Some(native) = platform::native_window(window) {let (frame_x, frame_y, _, frame_height) = platform::window_frame(&native);// AppKit y grows upward: keep the gpui-space top edge, then applydiff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rsindex 1888df56d..13b984fda 100644--- a/apps/desktop-gpui/src/main.rs+++ b/apps/desktop-gpui/src/main.rs@@ -174,6 +174,14 @@ fn init_logging() -> Option<tracing_appender::non_blocking::WorkerGuard> {}fn main() {+ #[cfg(target_os = "linux")]+ if let Some(config) = cap_utils::linux_package::appimage_alsa_config_path() {+ // Logging starts a worker thread, so configure the process environment first.+ unsafe {+ std::env::set_var("ALSA_CONFIG_PATH", config);+ }+ }+let _log_guard = init_logging();// A relaunch means "run the code I just built": take over from any@@ -234,7 +242,25 @@ fn main() {// traffic lights -- the whole shell is custom-drawn. In gpui a// `None` titlebar drops NSClosable/NSMiniaturizable/NSResizable// from the style mask, which is the equivalent.+ #[cfg(not(any(target_os = "linux", target_os = "windows")))]titlebar: None,+ #[cfg(target_os = "windows")]+ titlebar: Some(gpui::TitlebarOptions {+ title: Some("Cap".into()),+ appears_transparent: true,+ ..Default::default()+ }),+ #[cfg(target_os = "linux")]+ titlebar: Some(gpui::TitlebarOptions {+ title: Some("Cap".into()),+ ..Default::default()+ }),+ #[cfg(target_os = "linux")]+ app_id: Some("Cap".into()),+ #[cfg(target_os = "linux")]+ window_min_size: Some(size(px(MAIN_WINDOW_WIDTH), px(MAIN_WINDOW_HEIGHT))),+ #[cfg(target_os = "linux")]+ window_decorations: Some(gpui::WindowDecorations::Client),// Stays `Normal` and gets its panel treatment (level 100,// all Spaces) from `platform::apply_panel_behavior` below.// `WindowKind::Floating` is not the answer: it allocates an@@ -348,6 +374,10 @@ fn main() {shadow: true,},);+ #[cfg(target_os = "linux")]+ if let Err(error) = platform::remove_x11_window_decorations(window) {+ tracing::warn!(%error, "could not remove X11 main window decorations");+ }tracing::info!(number = platform::window_number(window),"main window opened"diff --git a/apps/desktop-gpui/src/main_window.rs b/apps/desktop-gpui/src/main_window.rsindex 1b1344d7a..07a854424 100644--- a/apps/desktop-gpui/src/main_window.rs+++ b/apps/desktop-gpui/src/main_window.rs@@ -405,6 +405,9 @@ impl MainWindow {cx: &mut Context<Self>,) -> Self {crate::theme::bind_window(window, cx);+ #[cfg(target_os = "windows")]+ cx.observe_window_activation(window, |_, _, cx| cx.notify())+ .detach();let theme = Theme::for_window(window, cx, true);let mut previous_phase = Phase::Idle;cx.observe_in(&session, window, move |this, session, window, cx| {@@ -1130,12 +1133,28 @@ impl MainWindow {let to = self.window_size();tracing::info!(expanded = self.expanded, "toggling main window size");+ #[cfg(target_os = "linux")]+ let uses_wayland = matches!(+ raw_window_handle::HasWindowHandle::window_handle(window),+ Ok(handle) if matches!(handle.as_raw(), raw_window_handle::RawWindowHandle::Wayland(_))+ );+// Matches `resizeMainWindow`: 180ms, ease-out cubic.//// Assigning over the previous task drops it, which cancels a toggle// that is still in flight -- otherwise two animations would fight over// `resize` and the window could settle at an interpolated size.self.resize_task = Some(cx.spawn_in(window, async move |this, cx| {+ #[cfg(target_os = "linux")]+ if uses_wayland {+ // Intermediate sizes and half-pixel center shifts accumulate compositor rounding drift.+ let height = to.1 + (to.1 - MAIN_WINDOW_HEIGHT).rem_euclid(2.);+ let _ = this.update_in(cx, |_this, window, _cx| {+ window.resize(gpui::size(px(to.0), px(height)));+ });+ return;+ }+let start = std::time::Instant::now();loop {@@ -2083,7 +2102,7 @@ impl MainWindow {fn render_header(&self, _window: &Window, cx: &mut Context<Self>) -> impl IntoElement {let theme = self.theme;- div()+ let header = div().flex().flex_row().items_center()@@ -2094,8 +2113,101 @@ impl MainWindow {// `divide-y divide-gray-5` between header and body..border_b_1().border_color(theme.header_border())- .child(self.render_traffic_lights(cx))- .child(self.render_header_actions(cx))+ .when(!cfg!(target_os = "windows"), |header| {+ header.child(self.render_traffic_lights(cx))+ })+ .child(self.render_header_actions(cx));++ #[cfg(target_os = "windows")]+ let header = header.child(self.render_windows_caption_controls(_window, cx));++ header+ }++ #[cfg(target_os = "windows")]+ fn render_windows_caption_controls(+ &self,+ window: &Window,+ cx: &mut Context<Self>,+ ) -> impl IntoElement {+ let dark = self.theme.is_dark();+ let foreground = Theme::with_alpha(+ rgb(if dark { 0xffffff } else { 0x12161f }),+ if window.is_window_active() { 0.8 } else { 0.4 },+ );+ let hover = gpui::rgba(if dark { 0xffffff0d } else { 0x0000000d });+ let pressed = gpui::rgba(if dark { 0xe9e9e908 } else { 0x00000008 });+ let button = |id: &'static str, icon: &'static str, height: f32| {+ div()+ .id(id)+ .group(id)+ .tab_index(0)+ .w(px(46.))+ .h_full()+ .flex_shrink_0()+ .flex()+ .items_center()+ .justify_center()+ .cursor_default()+ .hover(move |style| {+ style.bg(if id == "caption-close" {+ rgb(0xc42b1c)+ } else {+ hover+ })+ })+ .active(move |style| {+ style.bg(if id == "caption-close" {+ gpui::rgba(0xc42b1ce6)+ } else {+ pressed+ })+ })+ .child(+ svg()+ .path(icon)+ .id("caption-glyph")+ .w(px(10.))+ .h(px(height))+ .text_color(foreground)+ .when(id == "caption-close", |icon| {+ icon.group_hover("caption-close", |style| {+ style.text_color(gpui::white())+ })+ .group_active("caption-close", |style| style.text_color(gpui::white()))+ }),+ )+ };++ div()+ .flex()+ .h_full()+ .flex_shrink_0()+ .child(+ button("caption-minimize", "icons/caption-minimize-windows.svg", 1.)+ .on_click(|_, window, _| window.minimize_window()),+ )+ .child(+ button(+ "caption-maximize",+ if self.expanded {+ "icons/caption-restore-windows.svg"+ } else {+ "icons/caption-maximize-windows.svg"+ },+ if self.expanded { 11. } else { 10. },+ )+ .on_click(cx.listener(|this, _, window, cx| {+ this.toggle_expanded(window, cx);+ })),+ )+ .child(+ button("caption-close", "icons/caption-close-windows.svg", 10.).on_click(+ cx.listener(|_, _, _, cx| {+ cx.defer(app_windows::request_close_main);+ }),+ ),+ )}/// `CaptionControlsMacOS`: 14px circles (`size-3.5`), 10px apart@@ -2199,7 +2311,7 @@ impl MainWindow {ui::IconButton::header(&theme, id, path).icon_size(px(size))};- div()+ let actions = div().flex().flex_1().items_center()@@ -2213,17 +2325,15 @@ impl MainWindow {},)),)- // The drag handle, and *only* this. The Tauri header puts- // `data-tauri-drag-region` on the header and this spacer but not on- // the buttons; putting the handler on the header root instead makes- // every mouse-down in the header start a window drag, which eats- // the button clicks before they are delivered.+ // Keep drag handlers off the header root: starting native dragging+ // on a button's mouse-down consumes its later click..child(div().id("drag-region").flex_1().min_w_0().h_full()+ .when(cfg!(target_os = "windows"), |region| region.h(px(20.))).on_mouse_down(gpui::MouseButton::Left, |_, window, _| {window.start_window_move();}),@@ -2300,7 +2410,31 @@ impl MainWindow {},)),),- )+ );++ #[cfg(target_os = "windows")]+ let actions = {+ let drag_strip = |id: &'static str| {+ div()+ .id(id)+ .absolute()+ .left_0()+ .right_0()+ .h(px(6.))+ .on_mouse_down(gpui::MouseButton::Left, |_, window, cx| {+ window.start_window_move();+ cx.stop_propagation();+ })+ };++ actions+ .relative()+ .h_full()+ .child(drag_strip("header-drag-top").top_0())+ .child(drag_strip("header-drag-bottom").bottom_0())+ };++ actions}/// Page root: `px-[13px] gap-2 pb-[8px]`.diff --git a/apps/desktop-gpui/src/menus.rs b/apps/desktop-gpui/src/menus.rsindex 19c1678e6..e92abd8e7 100644--- a/apps/desktop-gpui/src/menus.rs+++ b/apps/desktop-gpui/src/menus.rs@@ -97,6 +97,13 @@ pub fn init(cx: &mut App) {cx.on_action(|_: &Minimize, cx: &mut App| with_key_native(cx, platform::minimize_native));cx.on_action(|_: &Zoom, cx: &mut App| with_key_native(cx, platform::zoom_native));cx.on_action(|_: &ToggleFullscreen, cx: &mut App| {+ #[cfg(target_os = "windows")]+ if let Some(handle) = cx.active_window() {+ cx.defer(move |cx| {+ let _ = handle.update(cx, |_, window, _| window.toggle_fullscreen());+ });+ }+ #[cfg(not(target_os = "windows"))]with_key_native(cx, platform::toggle_fullscreen_native)});diff --git a/apps/desktop-gpui/src/platform.rs b/apps/desktop-gpui/src/platform.rsindex ad226139d..32d454358 100644--- a/apps/desktop-gpui/src/platform.rs+++ b/apps/desktop-gpui/src/platform.rs@@ -1542,7 +1542,13 @@ mod mac {}}-#[cfg(not(target_os = "macos"))]+#[cfg(target_os = "windows")]+mod windows;++#[cfg(target_os = "windows")]+pub use windows::*;++#[cfg(not(any(target_os = "macos", target_os = "windows")))]mod stub {use gpui::Window;@@ -1664,6 +1670,52 @@ mod stub {}pub fn hide_native(_native: &NativeWindow) {}pub fn show_native(_native: &NativeWindow) {}++ #[cfg(target_os = "linux")]+ pub fn remove_x11_window_decorations(window: &Window) -> anyhow::Result<()> {+ use raw_window_handle::{HasWindowHandle, RawWindowHandle};+ use x11rb::connection::Connection;+ use x11rb::protocol::xproto::{ConnectionExt, PropMode};+ use x11rb::wrapper::ConnectionExt as _;++ let window_id = match HasWindowHandle::window_handle(window)?.as_raw() {+ RawWindowHandle::Xlib(handle) => u32::try_from(handle.window)?,+ RawWindowHandle::Xcb(handle) => handle.window.get(),+ _ => return Ok(()),+ };+ let (connection, _) = x11rb::connect(None)?;+ let atom = connection+ .intern_atom(false, b"_MOTIF_WM_HINTS")?+ .reply()?+ .atom;+ connection+ .change_property32(PropMode::REPLACE, window_id, atom, atom, &[2, 0, 0, 0, 0])?+ .check()?;+ connection.flush()?;+ Ok(())+ }++ #[cfg(target_os = "linux")]+ pub fn set_x11_window_visible(window: &Window, visible: bool) -> anyhow::Result<()> {+ use raw_window_handle::{HasWindowHandle, RawWindowHandle};+ use x11rb::connection::Connection;+ use x11rb::protocol::xproto::ConnectionExt;++ let window_id = match HasWindowHandle::window_handle(window)?.as_raw() {+ RawWindowHandle::Xlib(handle) => u32::try_from(handle.window)?,+ RawWindowHandle::Xcb(handle) => handle.window.get(),+ _ => return Ok(()),+ };+ let (connection, _) = x11rb::connect(None)?;+ if visible {+ connection.map_window(window_id)?.check()?;+ } else {+ connection.unmap_window(window_id)?.check()?;+ }+ connection.flush()?;+ Ok(())+ }+pub fn window_frame(_native: &NativeWindow) -> (f64, f64, f64, f64) {(0., 0., 0., 0.)}@@ -1793,7 +1845,7 @@ mod stub {pub fn show_about_panel(_name: &str, _version: &str) {}}-#[cfg(not(target_os = "macos"))]+#[cfg(not(any(target_os = "macos", target_os = "windows")))]pub use stub::*;#[cfg(test)]diff --git a/apps/desktop-gpui/src/platform/windows.rs b/apps/desktop-gpui/src/platform/windows.rsnew file mode 100644index 000000000..5b4a8e1ee--- /dev/null+++ b/apps/desktop-gpui/src/platform/windows.rs@@ -0,0 +1,685 @@+use std::ffi::c_void;+use std::path::{Path, PathBuf};++use gpui::{ForegroundExecutor, Window, WindowAppearance};+use raw_window_handle::{HasWindowHandle, RawWindowHandle};+use windows_sys::Win32::Foundation::{HWND, RECT};+use windows_sys::Win32::UI::WindowsAndMessaging::{+ DefWindowProcW, GetForegroundWindow, GetWindowDisplayAffinity, GetWindowRect, HWND_NOTOPMOST,+ HWND_TOP, HWND_TOPMOST, IsIconic, IsWindowVisible, IsZoomed, PostMessageW, SW_HIDE,+ SW_MAXIMIZE, SW_MINIMIZE, SW_RESTORE, SW_SHOW, SW_SHOWNOACTIVATE, SWP_ASYNCWINDOWPOS,+ SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOSIZE, SWP_NOZORDER, SWP_SHOWWINDOW, SetForegroundWindow,+ SetWindowDisplayAffinity, SetWindowPos, ShowWindowAsync, WDA_EXCLUDEFROMCAPTURE, WDA_NONE,+ WM_CLOSE, WM_NCACTIVATE,+};++use super::{ForcedAppearance, MaterialKind, PanelBehavior};++mod capture_exclusion;++#[derive(Clone, Copy)]+pub struct NativeWindow(isize);++impl NativeWindow {+ fn hwnd(self) -> HWND {+ self.0 as HWND+ }+}++#[derive(Clone, Copy, Debug, PartialEq)]+struct Rect {+ x: f64,+ y: f64,+ width: f64,+ height: f64,+}++impl Rect {+ fn is_valid(self) -> bool {+ self.x.is_finite()+ && self.y.is_finite()+ && self.width.is_finite()+ && self.height.is_finite()+ && self.width > 0.+ && self.height > 0.+ }+}++#[derive(Clone, Copy, Debug)]+struct DisplayGeometry {+ physical: Rect,+ logical: Rect,+}++fn native_handle(window: &Window) -> Option<isize> {+ let handle = HasWindowHandle::window_handle(window).ok()?;+ let RawWindowHandle::Win32(handle) = handle.as_raw() else {+ return None;+ };+ Some(handle.hwnd.get())+}++pub fn native_window(window: &Window) -> Option<NativeWindow> {+ native_handle(window).map(NativeWindow)+}++#[link(name = "dwmapi")]+unsafe extern "system" {+ fn DwmSetWindowAttribute(hwnd: HWND, attribute: u32, value: *const c_void, size: u32) -> i32;+}++pub fn apply_window_theme(+ window: &Window,+ appearance: ForcedAppearance,+ executor: &ForegroundExecutor,+) {+ const DWMWA_USE_IMMERSIVE_DARK_MODE: u32 = 20;+ let Some(native) = native_window(window) else {+ return;+ };+ let dark = i32::from(match appearance {+ ForcedAppearance::System => matches!(+ window.appearance(),+ WindowAppearance::Dark | WindowAppearance::VibrantDark+ ),+ ForcedAppearance::Light => false,+ ForcedAppearance::Dark => true,+ });+ executor+ .spawn(async move {+ let result = unsafe {+ DwmSetWindowAttribute(+ native.hwnd(),+ DWMWA_USE_IMMERSIVE_DARK_MODE,+ std::ptr::addr_of!(dark).cast(),+ std::mem::size_of_val(&dark) as u32,+ )+ };+ if result < 0 {+ tracing::debug!(result, "native window theme is not supported");+ return;+ }+ unsafe {+ // As in Tao, redraw the nonclient colors without changing OS focus.+ let active = GetForegroundWindow() == native.hwnd();+ DefWindowProcW(native.hwnd(), WM_NCACTIVATE, usize::from(!active), 0);+ DefWindowProcW(native.hwnd(), WM_NCACTIVATE, usize::from(active), 0);+ }+ })+ .detach();+}++pub fn window_is_dark(_window: &Window) -> Option<bool> {+ None+}++pub fn debug_titlebar_state(_window: &Window) -> Option<String> {+ None+}++pub fn install_window_material(_native: &NativeWindow, _radius: f64) -> Option<MaterialKind> {+ None+}++pub fn recording_controls_level() -> isize {+ 1+}++pub fn target_overlay_level() -> isize {+ 1+}++pub fn teleprompter_level() -> isize {+ 1+}++pub fn set_window_alpha(_native: &NativeWindow, _alpha: f64) -> f64 {+ 1.+}++pub fn set_window_capture_hidden(native: &NativeWindow, hidden: bool) -> usize {+ let streamed = hidden+ .then(capture_exclusion::streamed_display_reason)+ .flatten();+ if let Some(reason) = &streamed {+ tracing::debug!(%reason, "keeping window visible on streamed desktop");+ }+ let affinity = if hidden && streamed.is_none() {+ WDA_EXCLUDEFROMCAPTURE+ } else {+ WDA_NONE+ };+ unsafe {+ if SetWindowDisplayAffinity(native.hwnd(), affinity) == 0 {+ return 0;+ }+ let mut current = WDA_NONE;+ if GetWindowDisplayAffinity(native.hwnd(), &mut current) == 0 {+ return affinity as usize;+ }+ current as usize+ }+}++pub fn restore_borderless_style(_native: &NativeWindow) {}++pub fn remove_popup_window_chrome(_native: &NativeWindow) {}++fn to_rect(x: f64, y: f64, width: f64, height: f64) -> Rect {+ Rect {+ x,+ y,+ width,+ height,+ }+}++fn display_geometries() -> Vec<DisplayGeometry> {+ scap_targets::Display::list()+ .into_iter()+ .filter_map(|display| {+ let physical = display.raw_handle().physical_bounds()?;+ let logical = display.raw_handle().logical_bounds()?;+ let geometry = DisplayGeometry {+ physical: to_rect(+ physical.position().x(),+ physical.position().y(),+ physical.size().width(),+ physical.size().height(),+ ),+ logical: to_rect(+ logical.position().x(),+ logical.position().y(),+ logical.size().width(),+ logical.size().height(),+ ),+ };+ (geometry.physical.is_valid() && geometry.logical.is_valid()).then_some(geometry)+ })+ .collect()+}++fn intersection_area(first: Rect, second: Rect) -> f64 {+ if !first.is_valid() || !second.is_valid() {+ return 0.;+ }+ let width = (first.x + first.width).min(second.x + second.width) - first.x.max(second.x);+ let height = (first.y + first.height).min(second.y + second.height) - first.y.max(second.y);+ if width > 0. && height > 0. {+ width * height+ } else {+ 0.+ }+}++fn center_distance_squared(first: Rect, second: Rect) -> f64 {+ let dx = first.x + first.width / 2. - (second.x + second.width / 2.);+ let dy = first.y + first.height / 2. - (second.y + second.height / 2.);+ dx.mul_add(dx, dy * dy)+}++fn select_physical_display(rect: Rect, displays: &[DisplayGeometry]) -> Option<DisplayGeometry> {+ displays+ .iter()+ .max_by(|first, second| {+ intersection_area(rect, first.physical)+ .total_cmp(&intersection_area(rect, second.physical))+ .then_with(|| {+ center_distance_squared(rect, second.physical)+ .total_cmp(¢er_distance_squared(rect, first.physical))+ })+ })+ .copied()+}++fn select_logical_display(+ rect: Rect,+ displays: &[DisplayGeometry],+ exact: bool,+) -> Option<DisplayGeometry> {+ if exact+ && let Some(display) = displays.iter().find(|display| {+ let bounds = display.logical;+ (rect.x - bounds.x).abs() <= 1.+ && (rect.y - bounds.y).abs() <= 1.+ && (rect.width - bounds.width).abs() <= 1.+ && (rect.height - bounds.height).abs() <= 1.+ })+ {+ return Some(*display);+ }+ displays+ .iter()+ .max_by(|first, second| {+ intersection_area(rect, first.logical)+ .total_cmp(&intersection_area(rect, second.logical))+ .then_with(|| {+ center_distance_squared(rect, second.logical)+ .total_cmp(¢er_distance_squared(rect, first.logical))+ })+ })+ .copied()+}++fn physical_to_logical(rect: Rect, display: DisplayGeometry) -> Rect {+ let scale_x = display.logical.width / display.physical.width;+ let scale_y = display.logical.height / display.physical.height;+ Rect {+ x: display.logical.x + (rect.x - display.physical.x) * scale_x,+ y: display.logical.y + (rect.y - display.physical.y) * scale_y,+ width: rect.width * scale_x,+ height: rect.height * scale_y,+ }+}++fn logical_to_physical(rect: Rect, display: DisplayGeometry) -> Rect {+ let scale_x = display.physical.width / display.logical.width;+ let scale_y = display.physical.height / display.logical.height;+ Rect {+ x: display.physical.x + (rect.x - display.logical.x) * scale_x,+ y: display.physical.y + (rect.y - display.logical.y) * scale_y,+ width: rect.width * scale_x,+ height: rect.height * scale_y,+ }+}++fn window_physical_frame(native: &NativeWindow) -> Option<Rect> {+ let mut rect = RECT {+ left: 0,+ top: 0,+ right: 0,+ bottom: 0,+ };+ unsafe {+ (GetWindowRect(native.hwnd(), &mut rect) != 0).then(|| {+ to_rect(+ rect.left as f64,+ rect.top as f64,+ (rect.right - rect.left) as f64,+ (rect.bottom - rect.top) as f64,+ )+ })+ }+}++fn set_physical_frame(native: &NativeWindow, rect: Rect) {+ if !rect.is_valid() {+ return;+ }+ unsafe {+ SetWindowPos(+ native.hwnd(),+ HWND_TOP,+ rect.x.round() as i32,+ rect.y.round() as i32,+ rect.width.round() as i32,+ rect.height.round() as i32,+ SWP_NOACTIVATE | SWP_NOZORDER | SWP_ASYNCWINDOWPOS,+ );+ }+}++pub fn window_frame(native: &NativeWindow) -> (f64, f64, f64, f64) {+ window_physical_frame(native)+ .map(|rect| (rect.x, rect.y, rect.width, rect.height))+ .unwrap_or_default()+}++pub fn set_window_frame(native: &NativeWindow, x: f64, y: f64, width: f64, height: f64) {+ set_physical_frame(native, to_rect(x, y, width, height));+}++pub fn window_logical_frame(native: &NativeWindow) -> (f64, f64, f64, f64) {+ let Some(physical) = window_physical_frame(native) else {+ return (0., 0., 0., 0.);+ };+ let displays = display_geometries();+ let logical = select_physical_display(physical, &displays)+ .map(|display| physical_to_logical(physical, display))+ .unwrap_or(physical);+ (logical.x, logical.y, logical.width, logical.height)+}++pub fn set_window_logical_frame(native: &NativeWindow, x: f64, y: f64, width: f64, height: f64) {+ let logical = to_rect(x, y, width, height);+ if !logical.is_valid() {+ return;+ }+ let displays = display_geometries();+ let physical = select_logical_display(logical, &displays, false)+ .map(|display| logical_to_physical(logical, display))+ .unwrap_or(logical);+ set_physical_frame(native, physical);+}++pub fn place_overlay_panel(+ native: &NativeWindow,+ x: f64,+ y: f64,+ width: f64,+ height: f64,+ _level: isize,+) {+ let logical = to_rect(x, y, width, height);+ if !logical.is_valid() {+ return;+ }+ let displays = display_geometries();+ let physical = select_logical_display(logical, &displays, true)+ .map(|display| logical_to_physical(logical, display))+ .unwrap_or(logical);+ if !physical.is_valid() {+ return;+ }+ unsafe {+ SetWindowPos(+ native.hwnd(),+ HWND_TOPMOST,+ physical.x.round() as i32,+ physical.y.round() as i32,+ physical.width.round() as i32,+ physical.height.round() as i32,+ SWP_NOACTIVATE | SWP_SHOWWINDOW | SWP_ASYNCWINDOWPOS,+ );+ }+}++pub fn apply_panel_behavior(window: &Window, behavior: PanelBehavior) {+ let _ = (behavior.join_all_spaces, behavior.shadow);+ let Some(native) = native_window(window) else {+ return;+ };+ let insert_after = if behavior.level > 0 {+ HWND_TOPMOST+ } else {+ HWND_NOTOPMOST+ };+ unsafe {+ SetWindowPos(+ native.hwnd(),+ insert_after,+ 0,+ 0,+ 0,+ 0,+ SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_ASYNCWINDOWPOS,+ );+ }+}++pub fn kick_display_link(_window: &Window) {}++pub fn hide_native(native: &NativeWindow) {+ unsafe {+ ShowWindowAsync(native.hwnd(), SW_HIDE);+ }+}++pub fn show_native(native: &NativeWindow) {+ unsafe {+ let command = if IsIconic(native.hwnd()) != 0 {+ SW_RESTORE+ } else {+ SW_SHOW+ };+ ShowWindowAsync(native.hwnd(), command);+ }+}++pub fn order_front_native(native: &NativeWindow) {+ unsafe {+ SetWindowPos(+ native.hwnd(),+ HWND_TOP,+ 0,+ 0,+ 0,+ 0,+ SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_ASYNCWINDOWPOS,+ );+ }+}++fn overlap_is_visible(first: Rect, second: Rect) -> bool {+ const MIN_VISIBLE: f64 = 80.;+ if !first.is_valid() || !second.is_valid() {+ return false;+ }+ let overlap_width =+ (first.x + first.width).min(second.x + second.width) - first.x.max(second.x);+ let overlap_height =+ (first.y + first.height).min(second.y + second.height) - first.y.max(second.y);+ overlap_width >= MIN_VISIBLE.min(first.width) && overlap_height >= MIN_VISIBLE.min(first.height)+}++pub fn frame_is_on_screen(x: f64, y: f64, width: f64, height: f64) -> bool {+ let frame = to_rect(x, y, width, height);+ if !frame.is_valid() {+ return false;+ }+ let displays = display_geometries();+ if displays.is_empty() {+ return true;+ }+ displays+ .iter()+ .any(|display| overlap_is_visible(frame, display.physical))+}++pub fn close_native(native: &NativeWindow) {+ unsafe {+ PostMessageW(native.hwnd(), WM_CLOSE, 0, 0);+ }+}++pub fn minimize_native(native: &NativeWindow) {+ unsafe {+ ShowWindowAsync(native.hwnd(), SW_MINIMIZE);+ }+}++pub fn zoom_native(native: &NativeWindow) {+ unsafe {+ let command = if IsZoomed(native.hwnd()) != 0 {+ SW_RESTORE+ } else {+ SW_MAXIMIZE+ };+ ShowWindowAsync(native.hwnd(), command);+ }+}++pub fn maximize_if_larger_than_work_area(window: &Window, cx: &gpui::App) {+ let Some(native) = native_window(window) else {+ return;+ };+ let Some(display) = window.display(cx) else {+ return;+ };+ let (_, _, width, height) = window_logical_frame(&native);+ let work = display.visible_bounds().size;+ if width > f64::from(f32::from(work.width)) || height > f64::from(f32::from(work.height)) {+ unsafe {+ ShowWindowAsync(native.hwnd(), SW_MAXIMIZE);+ }+ }+}++pub fn window_is_visible(window: &Window) -> bool {+ native_handle(window).is_some_and(|hwnd| unsafe { IsWindowVisible(hwnd as HWND) != 0 })+}++pub fn show_window_without_focus(window: &Window) {+ let Some(native) = native_window(window) else {+ return;+ };+ unsafe {+ ShowWindowAsync(native.hwnd(), SW_SHOWNOACTIVATE);+ SetWindowPos(+ native.hwnd(),+ HWND_TOP,+ 0,+ 0,+ 0,+ 0,+ SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_SHOWWINDOW | SWP_ASYNCWINDOWPOS,+ );+ }+}++pub fn window_number(window: &Window) -> Option<isize> {+ native_handle(window)+}++pub fn open_image_panel(extensions: &[&str]) -> Option<PathBuf> {+ let mut dialog = rfd::FileDialog::new();+ if !extensions.is_empty() {+ dialog = dialog.add_filter("Images", extensions);+ }+ dialog.pick_file()+}++pub fn open_audio_panel() -> Option<PathBuf> {+ rfd::FileDialog::new()+ .add_filter("Audio", &["mp3", "wav", "m4a", "ogg", "flac", "aac"])+ .pick_file()+}++pub fn confirm_dialog(+ title: &str,+ message: &str,+ accept: &str,+ cancel: &str,+ warning: bool,+) -> bool {+ let level = if warning {+ rfd::MessageLevel::Warning+ } else {+ rfd::MessageLevel::Info+ };+ let result = rfd::MessageDialog::new()+ .set_title(title)+ .set_description(message)+ .set_buttons(rfd::MessageButtons::OkCancelCustom(+ accept.to_string(),+ cancel.to_string(),+ ))+ .set_level(level)+ .show();+ super::confirmation_accepted(result, accept)+}++pub fn alert_dialog(title: &str, message: &str) {+ let _ = rfd::MessageDialog::new()+ .set_title(title)+ .set_description(message)+ .set_buttons(rfd::MessageButtons::Ok)+ .set_level(rfd::MessageLevel::Info)+ .show();+}++pub fn activate_app() {}++pub fn focus_capture_target_window(id: &scap_targets::WindowId) -> bool {+ let Some(window) = scap_targets::Window::from_id(id) else {+ return false;+ };+ let hwnd = window.raw_handle().inner().0 as HWND;+ if hwnd.is_null() {+ return false;+ }+ unsafe {+ if IsIconic(hwnd) != 0 {+ ShowWindowAsync(hwnd, SW_RESTORE);+ }+ SetForegroundWindow(hwnd) != 0+ }+}++pub fn install_url_scheme_handler() {}++pub fn set_dock_icon(_png: &[u8]) {}++pub fn save_file_panel(suggested: &str, extensions: &[&str]) -> Option<PathBuf> {+ let mut dialog = rfd::FileDialog::new().set_file_name(suggested);+ if !extensions.is_empty() {+ dialog = dialog.add_filter("Export", extensions);+ }+ dialog.save_file()+}++pub fn copy_file_to_clipboard(_path: &Path) -> Result<(), String> {+ Err("Copy to clipboard is not available yet on Windows".into())+}++pub fn copy_image_to_clipboard(path: &Path) -> Result<(), String> {+ copy_file_to_clipboard(path)+}++pub fn desktop_picture_path() -> Option<PathBuf> {+ None+}++pub fn set_activation_policy(_regular: bool) -> bool {+ false+}++pub fn activation_policy() -> isize {+ -1+}++pub fn show_about_panel(_name: &str, _version: &str) {}++pub fn escape_hotkey_events() -> flume::Receiver<()> {+ flume::unbounded().1+}++pub fn register_escape_hotkey() {}++pub fn unregister_escape_hotkey() {}++#[cfg(test)]+mod tests {+ use super::{Rect, logical_to_physical, overlap_is_visible, physical_to_logical, to_rect};++ fn display(physical: Rect, logical: Rect) -> super::DisplayGeometry {+ super::DisplayGeometry { physical, logical }+ }++ #[test]+ fn converts_negative_mixed_dpi_monitor_coordinates() {+ let display = display(+ to_rect(-2560., -120., 2560., 1440.),+ to_rect(-1706.6666667, -80., 1706.6666667, 960.),+ );+ let logical = physical_to_logical(to_rect(-1280., 600., 1280., 720.), display);+ assert!((logical.x + 853.3333333).abs() < 0.01);+ assert!((logical.y - 400.).abs() < 0.01);+ assert!((logical.width - 853.3333333).abs() < 0.01);+ assert!((logical.height - 480.).abs() < 0.01);+ let physical = logical_to_physical(logical, display);+ assert!((physical.x + 1280.).abs() < 0.01);+ assert!((physical.y - 600.).abs() < 0.01);+ assert!((physical.width - 1280.).abs() < 0.01);+ assert!((physical.height - 720.).abs() < 0.01);+ }++ #[test]+ fn visible_frame_requires_grabbable_overlap() {+ let monitor = to_rect(-1920., 0., 1920., 1080.);+ assert!(overlap_is_visible(+ to_rect(-1910., 20., 100., 100.),+ monitor+ ));+ assert!(!overlap_is_visible(to_rect(-1990., 20., 70., 70.), monitor));+ assert!(!overlap_is_visible(+ to_rect(-1900., 1070., 500., 100.),+ monitor+ ));+ assert!(overlap_is_visible(+ to_rect(-1900., 1070., 500., 10.),+ monitor+ ));+ assert!(!overlap_is_visible(to_rect(0., 0., 0., 100.), monitor));+ }+}diff --git a/apps/desktop-gpui/src/platform/windows/capture_exclusion.rs b/apps/desktop-gpui/src/platform/windows/capture_exclusion.rsnew file mode 100644index 000000000..62a19c7bc--- /dev/null+++ b/apps/desktop-gpui/src/platform/windows/capture_exclusion.rs@@ -0,0 +1,290 @@+use std::ffi::c_void;++use windows_sys::Win32::UI::WindowsAndMessaging::{GetSystemMetrics, SM_REMOTESESSION};++const ENV_OVERRIDE: &str = "CAP_WINDOW_CAPTURE_EXCLUSION";+const SMBIOS_MARKERS: &[&str] = &[+ "qemu",+ "kvm",+ "vmware",+ "virtualbox",+ "innotek",+ "xen",+ "bochs",+ "parallels",+ "virtual machine",+ "hvm domu",+ "amazon ec2",+ "google compute engine",+ "openstack",+ "shadow",+];+const VIRTUAL_DISPLAY_MARKERS: &[&str] = &[+ "parsec",+ "spacedesk",+ "iddsample",+ "virtual display",+ "usbmmidd",+ "amyuni",+ "shadow",+];++#[repr(C)]+struct DisplayDevice {+ size: u32,+ name: [u16; 32],+ description: [u16; 128],+ state_flags: u32,+ id: [u16; 128],+ key: [u16; 128],+}++#[link(name = "advapi32")]+unsafe extern "system" {+ fn RegGetValueW(+ key: *mut c_void,+ subkey: *const u16,+ value: *const u16,+ flags: u32,+ value_type: *mut u32,+ data: *mut c_void,+ data_size: *mut u32,+ ) -> i32;+}++#[link(name = "user32")]+unsafe extern "system" {+ fn EnumDisplayDevicesW(+ device: *const u16,+ index: u32,+ display: *mut DisplayDevice,+ flags: u32,+ ) -> i32;+}++fn exclusion_override(value: &str) -> Option<bool> {+ match value.trim().to_ascii_lowercase().as_str() {+ "on" | "always" | "1" => Some(true),+ "off" | "never" | "0" => Some(false),+ _ => None,+ }+}++// Match Tauri's streamed-desktop policy: WDA exclusion also hides controls from+// Shadow/RDP viewers, not just from the recording being made.+pub(super) fn streamed_display_reason() -> Option<String> {+ match std::env::var(ENV_OVERRIDE)+ .ok()+ .and_then(|value| exclusion_override(&value))+ {+ Some(true) => return None,+ Some(false) => return Some(format!("{ENV_OVERRIDE} env override")),+ None => {}+ }+ if unsafe { GetSystemMetrics(SM_REMOTESESSION) } != 0 {+ return Some("remote desktop session (SM_REMOTESESSION)".to_string());+ }+ if let Some(vendor) = hypervisor_guest() {+ return Some(format!("hypervisor guest ({vendor})"));+ }+ for value in [+ "SystemManufacturer",+ "SystemProductName",+ "SystemFamily",+ "BIOSVendor",+ ] {+ if let Some(text) = bios_value(value)+ && let Some(marker) = find_marker(&text, SMBIOS_MARKERS)+ {+ return Some(format!(+ "virtual machine SMBIOS ({value}=\"{text}\" matched \"{marker}\")"+ ));+ }+ }+ virtual_display_adapter().map(|device| format!("virtual display adapter ({device})"))+}++#[cfg(target_arch = "x86_64")]+fn hypervisor_guest() -> Option<String> {+ use std::arch::x86_64::__cpuid;++ if __cpuid(1).ecx & (1 << 31) == 0 {+ return None;+ }+ let hypervisor = __cpuid(0x4000_0000);+ let mut vendor = [0u8; 12];+ vendor[0..4].copy_from_slice(&hypervisor.ebx.to_le_bytes());+ vendor[4..8].copy_from_slice(&hypervisor.ecx.to_le_bytes());+ vendor[8..12].copy_from_slice(&hypervisor.edx.to_le_bytes());+ let privileges = if &vendor == b"Microsoft Hv" && hypervisor.eax >= 0x4000_0003 {+ __cpuid(0x4000_0003).ebx+ } else {+ 0+ };+ if is_hyperv_root(&vendor, hypervisor.eax, privileges) {+ return None;+ }+ let vendor = String::from_utf8_lossy(&vendor)+ .trim_matches([char::from(0), ' '])+ .to_string();+ Some(if vendor.is_empty() {+ "unknown hypervisor".to_string()+ } else {+ vendor+ })+}++#[cfg(any(target_arch = "x86_64", test))]+fn is_hyperv_root(vendor: &[u8; 12], maximum_leaf: u32, privileges: u32) -> bool {+ // VBS/WSL2 exposes Hyper-V on physical hosts; CreatePartitions identifies+ // the root partition, which must retain ordinary capture exclusion.+ vendor == b"Microsoft Hv" && maximum_leaf >= 0x4000_0003 && privileges & 1 != 0+}++#[cfg(not(target_arch = "x86_64"))]+fn hypervisor_guest() -> Option<String> {+ None+}++fn bios_value(value: &str) -> Option<String> {+ const HKEY_LOCAL_MACHINE: *mut c_void = 0x8000_0002u32 as i32 as isize as *mut c_void;+ const STRING_FLAGS: u32 = 0x1000_0006;+ let subkey: Vec<u16> = "HARDWARE\\DESCRIPTION\\System\\BIOS\0"+ .encode_utf16()+ .collect();+ let value: Vec<u16> = value.encode_utf16().chain([0]).collect();+ let mut byte_count = 0u32;+ if unsafe {+ RegGetValueW(+ HKEY_LOCAL_MACHINE,+ subkey.as_ptr(),+ value.as_ptr(),+ STRING_FLAGS,+ std::ptr::null_mut(),+ std::ptr::null_mut(),+ &mut byte_count,+ )+ } != 0+ || byte_count == 0+ || byte_count > 65_536+ || !byte_count.is_multiple_of(2)+ {+ return None;+ }+ let mut data = vec![0u16; byte_count as usize / 2];+ if unsafe {+ RegGetValueW(+ HKEY_LOCAL_MACHINE,+ subkey.as_ptr(),+ value.as_ptr(),+ STRING_FLAGS,+ std::ptr::null_mut(),+ data.as_mut_ptr().cast(),+ &mut byte_count,+ )+ } != 0+ {+ return None;+ }+ Some(wide_text(&data))+}++fn virtual_display_adapter() -> Option<String> {+ let mut index = 0u32;+ loop {+ let mut display = DisplayDevice {+ size: std::mem::size_of::<DisplayDevice>() as u32,+ name: [0; 32],+ description: [0; 128],+ state_flags: 0,+ id: [0; 128],+ key: [0; 128],+ };+ if unsafe { EnumDisplayDevicesW(std::ptr::null(), index, &mut display, 0) } == 0 {+ return None;+ }+ index += 1;+ if display.state_flags & 1 == 0 {+ continue;+ }+ let name = wide_text(&display.description);+ if let Some(marker) = find_marker(&name, VIRTUAL_DISPLAY_MARKERS) {+ return Some(format!("\"{name}\" matched \"{marker}\""));+ }+ }+}++fn wide_text(value: &[u16]) -> String {+ let end = value+ .iter()+ .position(|character| *character == 0)+ .unwrap_or(value.len());+ String::from_utf16_lossy(&value[..end])+}++fn find_marker(text: &str, markers: &[&'static str]) -> Option<&'static str> {+ let lower = text.to_ascii_lowercase();+ markers+ .iter()+ .copied()+ .find(|marker| lower.contains(marker))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn overrides_preserve_auto_and_explicit_choices() {+ for value in ["on", " ALWAYS ", "1"] {+ assert_eq!(exclusion_override(value), Some(true));+ }+ for value in ["off", " NEVER ", "0"] {+ assert_eq!(exclusion_override(value), Some(false));+ }+ for value in ["", "auto", "unknown"] {+ assert_eq!(exclusion_override(value), None);+ }+ }++ #[test]+ fn known_streamed_displays_match_but_physical_hardware_does_not() {+ for value in [+ "Shadow Computer",+ "Amazon EC2",+ "QEMU Standard PC",+ "Virtual Machine",+ ] {+ assert!(find_marker(value, SMBIOS_MARKERS).is_some(), "{value}");+ }+ for value in ["Parsec Virtual Display Adapter", "Shadow", "spacedesk"] {+ assert!(+ find_marker(value, VIRTUAL_DISPLAY_MARKERS).is_some(),+ "{value}"+ );+ }+ for value in [+ "Dell Inc.",+ "LENOVO",+ "NVIDIA GeForce RTX 3080",+ "AMD Radeon RX 7900 XTX",+ ] {+ assert_eq!(find_marker(value, SMBIOS_MARKERS), None);+ assert_eq!(find_marker(value, VIRTUAL_DISPLAY_MARKERS), None);+ }+ }++ #[test]+ fn hyperv_root_is_not_mistaken_for_a_guest() {+ assert!(is_hyperv_root(b"Microsoft Hv", 0x4000_0003, 1));+ assert!(!is_hyperv_root(b"Microsoft Hv", 0x4000_0003, 0));+ assert!(!is_hyperv_root(b"Microsoft Hv", 0x4000_0002, 1));+ assert!(!is_hyperv_root(b"VMwareVMware", 0x4000_0003, 1));+ }++ #[test]+ fn display_description_ends_at_first_null() {+ assert_eq!(wide_text(&[83, 104, 97, 100, 111, 119, 0, 88]), "Shadow");+ assert_eq!(std::mem::size_of::<DisplayDevice>(), 840);+ }+}diff --git a/apps/desktop-gpui/src/theme.rs b/apps/desktop-gpui/src/theme.rsindex e6ed855af..07711e4ae 100644--- a/apps/desktop-gpui/src/theme.rs+++ b/apps/desktop-gpui/src/theme.rs@@ -67,15 +67,23 @@ fn forced_appearance(preference: AppTheme) -> ForcedAppearance {/// `window.set_theme(...)` — native chrome (traffic lights, materials, menus)/// follows the preference, not only the painted palette.pub fn apply_native(window: &Window, cx: &App) {- platform::apply_window_theme(window, forced_appearance(current_preference(cx)));+ let appearance = forced_appearance(current_preference(cx));+ #[cfg(target_os = "windows")]+ platform::apply_window_theme(window, appearance, cx.foreground_executor());+ #[cfg(not(target_os = "windows"))]+ platform::apply_window_theme(window, appearance);}/// Force the native appearance and invalidate on OS theme changes so a System/// preference picks up a light/dark flip without waiting for another event.pub fn bind_window<T: 'static>(window: &mut Window, cx: &mut Context<T>) {apply_native(window, cx);- cx.observe_window_appearance(window, |_, _, cx| cx.notify())- .detach();+ cx.observe_window_appearance(window, |_, _window, cx| {+ #[cfg(target_os = "windows")]+ _window.defer(cx, |window, cx| apply_native(window, cx));+ cx.notify();+ })+ .detach();}/// What the shell paints *over* a native window material, resolved for onediff --git a/apps/desktop/src-tauri/build.rs b/apps/desktop/src-tauri/build.rsindex 261851f6b..822939282 100644--- a/apps/desktop/src-tauri/build.rs+++ b/apps/desktop/src-tauri/build.rs@@ -1,3 +1,9 @@fn main() {+ if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows")+ && std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc")+ {+ // Export preview command dispatch can exhaust the default 1 MiB UI stack before reaching a Tokio worker.+ println!("cargo:rustc-link-arg-bin=cap-desktop=/STACK:16777216");+ }tauri_build::build();}diff --git a/apps/desktop/src/components/titlebar/controls/CaptionControlsWindows11.tsx b/apps/desktop/src/components/titlebar/controls/CaptionControlsWindows11.tsxindex d55b689bd..422dc6e7b 100644--- a/apps/desktop/src/components/titlebar/controls/CaptionControlsWindows11.tsx+++ b/apps/desktop/src/components/titlebar/controls/CaptionControlsWindows11.tsx@@ -94,7 +94,7 @@ export default function (disabled={!titlebarState.closable}class={cx("max-h-20 w-[46px] rounded-none bg-transparent hover:text-gray-1",- "hover:bg-[#c42b1c] dark:hover:bg-[#c42b1c active:bg-[#c42b1c]/90 dark:active:bg-[#c42b1c]/90",+ "hover:bg-[#c42b1c] dark:hover:bg-[#c42b1c] active:bg-[#c42b1c]/90 dark:active:bg-[#c42b1c]/90","disabled:hover:bg-transparent dark:disabled:hover:bg-transparent disabled:text-black-transparent-40",)}>diff --git a/scripts/prepare-gpui-dependency.sh b/scripts/prepare-gpui-dependency.shindex 445b5fa36..906b1a2ea 100755--- a/scripts/prepare-gpui-dependency.sh+++ b/scripts/prepare-gpui-dependency.sh@@ -3,7 +3,11 @@ set -euo pipefailrepo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"zed_dir="$repo_root/../zed-cap"-patch_file="$repo_root/apps/desktop-gpui/patches/zed-gpui.patch"+patch_files=(+ "$repo_root/apps/desktop-gpui/patches/zed-gpui.patch"+ "$repo_root/apps/desktop-gpui/patches/zed-windows.patch"+ "$repo_root/apps/desktop-gpui/patches/zed-linux.patch"+)base_revision="5d1f83d9f27a19bec1fb241dc33b42238af9cf8d"remote="https://github.com/wingleeio/zed.git"@@ -12,10 +16,12 @@ verify_checkout() {echo "error: $zed_dir does not contain GPUI base $base_revision" >&2exit 1fi- if ! git -C "$zed_dir" apply --reverse --check --unidiff-zero "$patch_file"; then- echo "error: $zed_dir does not contain Cap's pinned GPUI patch" >&2- exit 1- fi+ for patch_file in "${patch_files[@]}"; do+ if ! git -C "$zed_dir" apply --reverse --check --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@@ -38,7 +44,9 @@ git init --quiet "$temporary_dir"git -C "$temporary_dir" remote add origin "$remote"git -C "$temporary_dir" fetch --quiet --depth 1 origin "$base_revision"git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD-git -C "$temporary_dir" apply --unidiff-zero "$patch_file"+for patch_file in "${patch_files[@]}"; do+ git -C "$temporary_dir" apply --unidiff-zero "$patch_file"+donemv "$temporary_dir" "$zed_dir"trap - EXITverify_checkout