diff --git a/Cargo.lock b/Cargo.lock index 9cbee49675..2d9715685f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4991,6 +4991,7 @@ dependencies = [ "objc2 0.6.4", "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", + "windows 0.61.3", "x11", ] diff --git a/crates/webview/Cargo.toml b/crates/webview/Cargo.toml index aa6c985c6d..60d2924816 100644 --- a/crates/webview/Cargo.toml +++ b/crates/webview/Cargo.toml @@ -39,3 +39,6 @@ objc2-foundation = { version = "0.3", default-features = false, features = ["std gdkx11 = "0.18" gtk = "0.18" x11 = { version = "2.21", features = ["xlib"] } + +[target.'cfg(target_os = "windows")'.dependencies] +windows = { version = "0.61", features = ["Win32_Foundation", "Win32_Graphics_Gdi", "Win32_UI_HiDpi"] } diff --git a/crates/webview/src/lib.rs b/crates/webview/src/lib.rs index 0c739f1d3a..4fb932549c 100644 --- a/crates/webview/src/lib.rs +++ b/crates/webview/src/lib.rs @@ -6,6 +6,8 @@ mod composition; mod linux; #[cfg(target_os = "macos")] mod macos; +#[cfg(target_os = "windows")] +mod windows; #[cfg(all(feature = "gpui-fast", target_os = "macos"))] use composition::NativeWebViewSurface; @@ -56,7 +58,8 @@ impl WebViewHandle { /// /// With the `gpui-fast` feature, macOS and Linux host the native view in a window /// composition surface, so deferred GPUI overlays render above the page. Without it, the -/// native view covers GPUI content in its bounds and extends past a container that clips it. +/// native view covers GPUI content in its bounds. On Windows it can still clip to its +/// container; elsewhere it extends past a container that clips it. /// /// [experimental] pub struct WebView { @@ -68,6 +71,8 @@ pub struct WebView { zoom: Cell, /// Whether the last geometry update failed, so each failure is logged once until it recovers. geometry_failed: Cell, + #[cfg(target_os = "windows")] + clip: windows::NativeClip, #[cfg(all(feature = "gpui-fast", any(target_os = "macos", target_os = "linux")))] composition: Option, /// The GPUI scale factor the page zoom was last matched to. @@ -116,6 +121,8 @@ impl WebView { bounds: Bounds::default(), zoom: Cell::new(1.0), geometry_failed: Cell::new(false), + #[cfg(target_os = "windows")] + clip: windows::NativeClip::default(), webview: Rc::new(webview), #[cfg(all(feature = "gpui-fast", target_os = "macos"))] composition, @@ -172,13 +179,17 @@ impl WebView { .set_bounds(&self.webview, bounds) .map_err(|error| wry::Error::Io(std::io::Error::other(error))); } + #[cfg(target_os = "windows")] + self.clip + .clear(&self.webview) + .map_err(|error| wry::Error::Io(std::io::Error::other(error)))?; self.webview.set_bounds(bounds) } /// Apply full document bounds and an inherited clip without changing the DOM viewport. /// Empty clips hide the native surface while preserving the loaded document. - /// Partial clipping requires native window composition; without it, the native view - /// takes the full document bounds and extends past the clip. + /// Partial clipping is supported on Windows and with native window composition. + /// Otherwise, the native view takes the full document bounds and extends past the clip. pub fn set_geometry( &self, document: Bounds, @@ -203,6 +214,12 @@ impl WebView { self.webview.set_visible(true)?; return Ok(()); } + #[cfg(target_os = "windows")] + if visible != document { + self.clip.set_geometry(&self.webview, document, visible)?; + self.set_native_visible(true)?; + return Ok(()); + } #[cfg(target_os = "linux")] let rect = linux::device_bounds(document, self.scale_factor.get()); #[cfg(not(target_os = "linux"))] diff --git a/crates/webview/src/windows.rs b/crates/webview/src/windows.rs new file mode 100644 index 0000000000..ebdb002956 --- /dev/null +++ b/crates/webview/src/windows.rs @@ -0,0 +1,137 @@ +use std::cell::Cell; + +use ::windows::Win32::{ + Foundation::HWND, + Graphics::Gdi::{CreateRectRgn, DeleteObject, HRGN, SetWindowRgn}, + UI::HiDpi::GetDpiForWindow, +}; +use anyhow::{Context as _, Result}; +use gpui::{Bounds, Pixels}; +use wry::{ + Rect, WebViewExtWindows as _, + dpi::{LogicalPosition, LogicalSize}, +}; + +type ClipRect = [i32; 4]; + +#[derive(Default)] +pub(super) struct NativeClip(Cell>); + +impl NativeClip { + pub(super) fn set_geometry( + &self, + webview: &wry::WebView, + document: Bounds, + visible: Bounds, + ) -> Result<()> { + let hwnd = host_window(webview)?; + // SAFETY: Wry owns the child HWND on this UI thread. + let dpi = unsafe { GetDpiForWindow(hwnd) }; + anyhow::ensure!(dpi != 0, "cannot read WebView host DPI"); + let (bounds, clip) = window_geometry(document, visible, f64::from(dpi) / 96.); + webview.set_bounds(bounds)?; + self.apply(hwnd, clip) + } + + pub(super) fn clear(&self, webview: &wry::WebView) -> Result<()> { + if self.0.get().is_some() { + self.apply(host_window(webview)?, None)?; + } + Ok(()) + } + + fn apply(&self, hwnd: HWND, clip: Option) -> Result<()> { + if self.0.get() == clip { + return Ok(()); + } + // SAFETY: Coordinates are local to the Wry child HWND and are in device pixels. + // On success Windows owns the region; on failure the caller still owns it. + unsafe { + let region = if let Some([left, top, right, bottom]) = clip { + let region = CreateRectRgn(left, top, right, bottom); + anyhow::ensure!(!region.is_invalid(), "cannot create WebView clip region"); + Some(region) + } else { + None:: + }; + if SetWindowRgn(hwnd, region, true) == 0 { + if let Some(region) = region { + let _ = DeleteObject(region.into()); + } + anyhow::bail!("cannot set WebView clip region"); + } + } + self.0.set(clip); + Ok(()) + } +} + +fn host_window(webview: &wry::WebView) -> Result { + let mut hwnd = HWND::default(); + // SAFETY: Wry creates the controller with its own child HWND as the parent. + unsafe { webview.controller().ParentWindow(&mut hwnd) }.context("cannot get WebView host")?; + anyhow::ensure!(!hwnd.0.is_null(), "WebView has no host window"); + Ok(hwnd) +} + +fn window_geometry( + document: Bounds, + visible: Bounds, + scale: f64, +) -> (Rect, Option) { + let position = |x: Pixels, y: Pixels| { + LogicalPosition::new(f64::from(x), f64::from(y)).to_physical::(scale) + }; + let origin = position(document.left(), document.top()); + let size = LogicalSize::new( + f64::from(document.size.width), + f64::from(document.size.height), + ) + .to_physical::(scale); + let start = position(visible.left(), visible.top()); + let end = position(visible.right(), visible.bottom()); + // Wry rounds the window origin and extent independently. For a fully visible + // far edge, use that extent instead of subtracting two rounded positions. + let clip = [ + (start.x - origin.x).clamp(0, size.width), + (start.y - origin.y).clamp(0, size.height), + if visible.right() >= document.right() { + size.width + } else { + (end.x - origin.x).clamp(0, size.width) + }, + if visible.bottom() >= document.bottom() { + size.height + } else { + (end.y - origin.y).clamp(0, size.height) + }, + ]; + ( + Rect { + position: origin.into(), + size: size.into(), + }, + (clip != [0, 0, size.width, size.height]).then_some(clip), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use gpui::{point, px, size}; + use wry::dpi::PhysicalSize; + + #[test] + fn fractional_dpi_keeps_the_document_size_and_fully_visible_edge() { + let origin = point(px(0.5), px(0.5)); + let document = Bounds::new(origin, size(px(80.5), px(40.5))); + let visible = Bounds::new(point(px(10.5), origin.y), size(px(70.5), px(30.))); + let (bounds, clip) = window_geometry(document, visible, 1.25); + assert_eq!( + bounds.size.to_physical::(1.25), + PhysicalSize::new(101, 51) + ); + assert_eq!(clip, Some([12, 0, 101, 37])); + assert_eq!(window_geometry(document, document, 1.25).1, None); + } +}