Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions crates/webview/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }
23 changes: 20 additions & 3 deletions crates/webview/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 {
Expand All @@ -68,6 +71,8 @@ pub struct WebView {
zoom: Cell<f64>,
/// Whether the last geometry update failed, so each failure is logged once until it recovers.
geometry_failed: Cell<bool>,
#[cfg(target_os = "windows")]
clip: windows::NativeClip,
#[cfg(all(feature = "gpui-fast", any(target_os = "macos", target_os = "linux")))]
composition: Option<NativeWebViewSurface>,
/// The GPUI scale factor the page zoom was last matched to.
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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<Pixels>,
Expand All @@ -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"))]
Expand Down
137 changes: 137 additions & 0 deletions crates/webview/src/windows.rs
Original file line number Diff line number Diff line change
@@ -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<Option<ClipRect>>);

impl NativeClip {
pub(super) fn set_geometry(
&self,
webview: &wry::WebView,
document: Bounds<Pixels>,
visible: Bounds<Pixels>,
) -> 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<ClipRect>) -> 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::<HRGN>
};
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<HWND> {
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<Pixels>,
visible: Bounds<Pixels>,
scale: f64,
) -> (Rect, Option<ClipRect>) {
let position = |x: Pixels, y: Pixels| {
LogicalPosition::new(f64::from(x), f64::from(y)).to_physical::<i32>(scale)
};
let origin = position(document.left(), document.top());
let size = LogicalSize::new(
f64::from(document.size.width),
f64::from(document.size.height),
)
.to_physical::<i32>(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::<i32>(1.25),
PhysicalSize::new(101, 51)
);
assert_eq!(clip, Some([12, 0, 101, 37]));
assert_eq!(window_geometry(document, document, 1.25).1, None);
}
}
Loading