wry icon indicating copy to clipboard operation
wry copied to clipboard

Webview::set_bounds silently repositions the WebView2 child HWND; position is parent-relative but undocumented

Open madebybigb opened this issue 2 months ago • 3 comments

Summary

Webview::set_bounds() repositions the WebView2 child HWND on Windows, and the Rect's position is relative to the parent window's client area — not screen coordinates. Neither is documented, and the existing doc comment implies the call is a no-op outside build_as_child, which is not what happens on Windows.

Tauri amplifies this: tauri-runtime-wry's WebviewMessage::SetBounds handler stores

b.x_rate = position.x / window_size.width;
b.y_rate = position.y / window_size.height;

and re-derives position = x_rate * new_window_width on every later resize. So one set_bounds call carrying an absolute-looking position permanently offsets the webview for the life of the process, even after the window moves or resizes.

(tauri-runtime-wry 2.12.1, lib.rs:3733.)

Reproduction

wry 0.57.0, Windows 11, WebView2.

Given a popup window at screen (1012, 121), size 244x114:

webview.set_bounds(dpi::Rect {
    // This is a SCREEN position, but set_bounds wants parent-client-relative.
    position: dpi::Position::Physical(dpi::PhysicalPosition::new(1012, 121)),
    size:     dpi::Size::Physical(dpi::PhysicalSize::new(244, 114)),
})?;

The webview is not moved to that screen location. It is moved to client (1012, 121) inside the 244x114 parent, i.e. entirely off-screen, and the window renders as a correctly-sized blank panel.

For a webview that fills its window the position must be (0, 0):

webview.set_bounds(dpi::Rect {
    position: dpi::Position::Physical(dpi::PhysicalPosition::new(0, 0)),
    size:     dpi::Size::Physical(dpi::PhysicalSize::new(244, 114)),
})?;

Measured evidence

From a real Tauri 2.12.1 app on wry 0.57.0 (CompanionBar), reading the actual HWNDs from a separate process with EnumChildWindows + GetWindowRect, offsets relative to the parent window:

Calling set_bounds with the popup's absolute screen rect:

popup window  rect=(1012,121) 244x114
  WRY_WEBVIEW size=195x96 offset=(991,-17)      <- outside the parent entirely

Calling it with position (0, 0):

popup window  rect=(1012,180) 244x338
  WRY_WEBVIEW size=244x338 offset=(0,0)

(The 195x96 is a second-order effect of tauri-runtime-wry re-applying the cached x_rate/y_rate on the next resize.)

Source

src/webview2/mod.rs::set_bounds_inner (wry 0.57.0, line 1526; the SetWindowPos is at 1539):

pub fn set_bounds_inner(
    &self,
    size: PhysicalSize<i32>,
    position: PhysicalPosition<i32>,
) -> Result<()> {
    unsafe {
        self.controller.SetBounds(RECT {
            top: 0,
            left: 0,
            right: size.width,
            bottom: size.height,
        })?;

        SetWindowPos(
            self.hwnd,
            None,
            position.x,
            position.y,
            size.width,
            size.height,
            SWP_ASYNCWINDOWPOS | SWP_NOACTIVATE | SWP_NOZORDER,
        )?;
    }

    Ok(())
}

The two calls disagree about position: SetBounds ignores it and always uses the origin, while SetWindowPos applies it as a child-window offset.

Webview::bounds() is already parent-relative on both paths — GetClientRect + MapWindowPoints(hwnd -> parent) for child webviews, ICoreWebView2Controller::Bounds otherwise — so set_bounds and bounds agree with each other; it is the documentation that does not say so.

Current docs

/// Set the webview bounds.
///
/// This is only effective if the webview was created as a child
/// or created using [`WebViewBuilderExtUnix::build_gtk`] with [`gtk::Fixed`].
pub fn set_bounds(&self, bounds: Rect) -> Result<()>

On Windows the WebView2 child HWND exists for every webview, so the call always takes effect regardless of how the webview was built.

What would help

  1. State the coordinate space of Rect::position in the set_bounds docs (parent-client-relative), matching bounds().
  2. Correct the "only effective if the webview was created as a child" note for Windows, or scope it to the platforms where it holds.
  3. Consider whether SetBounds honouring position — or splitting into set_size / set_position — would remove the trap. Right now a caller who passes screen coordinates gets a silent, catastrophic result rather than an error.

Note that the x_rate/y_rate caching in tauri-runtime-wry may warrant a separate report in tauri-apps/tauri; this report is filed against wry because the SetWindowPos behaviour originates there.

madebybigb avatar Oct 04 '26 19:10 madebybigb

The expected behavior is:

  • in WRY, WebView::set_bounds should only operate on a WebView created using WebViewBuilder::build_as_child aka does not fill the whole window and in that case, the bounds are parent relative. Same thing for WebView::bounds getter, it should be parent-relative for Child WebViews, no-op for a webview that fills a Window.
  • in Tauri, we have two distinct types for this, a WebviewWindow and a Webview type, the former fills the window with a webview, the latter creates a child webview inside a Window that can be any size with any resize ratio, and calling Webview::set_bounds or Webview::bounds in Tauri, should also be operating on parent-relative coordinates.

I am not sure I quite follow your report, sometimes you are talking about tauri and sometimes you are talking about wry.

Please provide a minimal reproduction if any of the above expected behaviors are broken, so that I can investigate properly. Can you also provide links to the documentation that needs to be improved?

amrbashir avatar Oct 07 '26 01:10 amrbashir

Thanks for the clarification. I investigated the behavior on Windows 11 using a minimal reproduction with tao and the upstream Wry dev branch (commit 8d287db).

I confirmed that the child WebView behavior is consistent with your expected semantics:

  • set_bounds() positions the WRY_WEBVIEW container HWND (a WS_CHILD window created for both build() and build_as_child()) in parent-client-relative coordinates.
  • bounds() returns the same parent-client-relative coordinates.
  • Passing screen coordinates instead of parent-client-relative coordinates moves the child WebView outside its parent. This explains the original reproduction.

However, I found a separate inconsistency on Windows.

1. set_bounds() on a full-window WebView

For a WebView created with build() rather than build_as_child(), calling set_bounds() currently moves and resizes the underlying child HWND on Windows.

Minimal reproduction:

webview.set_bounds(dpi::Rect {
    position: dpi::Position::Physical(
        dpi::PhysicalPosition::new(100, 80)
    ),
    size: dpi::Size::Physical(
        dpi::PhysicalSize::new(400, 300)
    ),
})?;

Observed on Windows 11 (100% DPI scaling), positions relative to the parent's client area:

Actual HWND bounds()
Full-window WebView (100, 80), 400x300 (0, 0), 400x300
Child WebView (100, 80), 400x300 (100, 80), 400x300

The full-window WebView is physically repositioned, while bounds() continues to report an origin of (0, 0).

After resizing the parent window, the full-window WebView returns to (0, 0) and fills the parent again.

This behavior appears inconsistent with the expected no-op semantics for full-window WebViews.

2. Potential fix

One possible approach is to make the public set_bounds() method return early when self.is_child is false, while keeping internal operations such as resize_to_parent and reparent independent of that guard.

However, I noticed that PR #1920 also modifies the full-window set_bounds behavior as part of its frame-inset implementation.

I would like to avoid conflicting with that work and would appreciate your thoughts on the intended behavior before proposing an implementation change.

3. Additional finding: reparent() and bounds()

I also found another issue during testing.

After calling reparent() on a child WebView, the HWND is correctly moved under the new parent, but bounds() continues to calculate coordinates relative to the old parent.

For example, after reparenting a child WebView positioned at (10, 10) into a new parent window:

  • Actual child HWND position relative to the new parent: (10, 10)
  • bounds() result: (-740, 530) — i.e. the position relative to the old parent's client area

Calling set_bounds() after reparenting moves the HWND correctly, but bounds() still returns incorrect coordinates.

The current implementation appears to update self.parent only for non-child WebViews.

I believe this may deserve a separate issue, but I wanted to mention it here first.

Questions

  1. Should set_bounds() be a no-op for full-window WebViews on Windows, consistent with macOS (which already guards on is_child)?
  2. Would you prefer a separate issue for the reparent() / bounds() inconsistency?
  3. Should I prepare a minimal fix (verified with the reproduction below) after confirming the intended behavior?

I have not modified the Wry repository.

Full reproduction program (tao + wry, Windows only)

Cargo.toml:

[dependencies]
wry = { git = "https://github.com/tauri-apps/wry", rev = "8d287db" }
tao = "0.37"
windows = { version = "0.62", features = [
  "Win32_Foundation",
  "Win32_Graphics_Gdi",
  "Win32_UI_WindowsAndMessaging",
] }

src/main.rs:

//! Repro for tauri-apps/wry#1875: measure what WebView::set_bounds / bounds do on Windows
//! for a full-window webview (build) vs a child webview (build_as_child).
use std::time::{Duration, Instant};

use tao::{
  dpi::{PhysicalPosition, PhysicalSize},
  event::{Event, StartCause},
  event_loop::{ControlFlow, EventLoop},
  platform::windows::WindowExtWindows,
  window::{Window, WindowBuilder},
};
use windows::{
  core::w,
  Win32::{
    Foundation::{HWND, POINT, RECT},
    Graphics::Gdi::{ClientToScreen, ScreenToClient},
    UI::WindowsAndMessaging::{FindWindowExW, GetClientRect, GetWindowRect},
  },
};
use wry::{dpi, Rect, WebView, WebViewBuilder, WebViewExtWindows};

fn hwnd_of(w: &Window) -> HWND {
  HWND(w.hwnd() as _)
}

fn dump(label: &str, step: &str, win: &Window, wv: &WebView) {
  unsafe {
    let parent = hwnd_of(win);
    let mut wr = RECT::default();
    let _ = GetWindowRect(parent, &mut wr);
    let mut cr = RECT::default();
    let _ = GetClientRect(parent, &mut cr);
    let mut origin = POINT::default();
    let _ = ClientToScreen(parent, &mut origin);
    println!(
      "[{step}] {label}: parent outer=({},{}) {}x{} | client origin(screen)=({},{}) client={}x{} | scale={}",
      wr.left, wr.top, wr.right - wr.left, wr.bottom - wr.top,
      origin.x, origin.y, cr.right, cr.bottom, win.scale_factor()
    );
    match FindWindowExW(Some(parent), None, w!("WRY_WEBVIEW"), None) {
      Ok(c) => {
        let mut r = RECT::default();
        let _ = GetWindowRect(c, &mut r);
        let mut p = POINT { x: r.left, y: r.top };
        let _ = ScreenToClient(parent, &mut p);
        println!(
          "[{step}] {label}:   WRY_WEBVIEW hwnd screen=({},{}) parent-client-rel=({},{}) {}x{}",
          r.left, r.top, p.x, p.y, r.right - r.left, r.bottom - r.top
        );
      }
      Err(_) => println!("[{step}] {label}:   WRY_WEBVIEW not a direct child of this window"),
    }
    let mut cb = RECT::default();
    let _ = wv.controller().Bounds(&mut cb);
    println!(
      "[{step}] {label}:   controller.Bounds=({},{})-({},{})",
      cb.left, cb.top, cb.right, cb.bottom
    );
    match wv.bounds() {
      Ok(b) => {
        let p: dpi::PhysicalPosition<i32> = b.position.to_physical(win.scale_factor());
        let s: dpi::PhysicalSize<i32> = b.size.to_physical(win.scale_factor());
        println!("[{step}] {label}:   wv.bounds()=({},{}) {}x{}", p.x, p.y, s.width, s.height);
      }
      Err(e) => println!("[{step}] {label}:   wv.bounds() error {e}"),
    }
  }
}

fn rect(x: i32, y: i32, w: u32, h: u32) -> Rect {
  Rect {
    position: dpi::PhysicalPosition::new(x, y).into(),
    size: dpi::PhysicalSize::new(w, h).into(),
  }
}

fn main() -> wry::Result<()> {
  let event_loop = EventLoop::new();
  let win_full = WindowBuilder::new()
    .with_title("A: full-window build()")
    .with_inner_size(PhysicalSize::new(640, 480))
    .with_position(PhysicalPosition::new(100, 100))
    .build(&event_loop)
    .unwrap();
  let win_child = WindowBuilder::new()
    .with_title("B: build_as_child()")
    .with_inner_size(PhysicalSize::new(640, 480))
    .with_position(PhysicalPosition::new(800, 100))
    .build(&event_loop)
    .unwrap();
  let win_c = WindowBuilder::new()
    .with_title("C: reparent target")
    .with_inner_size(PhysicalSize::new(640, 480))
    .with_position(PhysicalPosition::new(100, 650))
    .build(&event_loop)
    .unwrap();

  let html = "<body style='margin:0;background:#c33;color:#fff;font:20px sans-serif'>webview</body>";
  let wv_full = WebViewBuilder::new().with_html(html).build(&win_full)?;
  let wv_child = WebViewBuilder::new()
    .with_html(html)
    .with_bounds(rect(20, 20, 300, 200))
    .build_as_child(&win_child)?;

  let start = Instant::now();
  let mut step = 0u32;

  event_loop.run(move |event, _, control_flow| {
    *control_flow = ControlFlow::WaitUntil(Instant::now() + Duration::from_millis(100));
    if !matches!(event, Event::NewEvents(StartCause::ResumeTimeReached { .. })) {
      return;
    }
    let due = Duration::from_millis(1500 + 700 * step as u64);
    if start.elapsed() < due {
      return;
    }
    let both = |s: &str| {
      dump("A full ", s, &win_full, &wv_full);
      dump("B child", s, &win_child, &wv_child);
    };
    match step {
      0 => both("0 initial"),
      1 => {
        println!("--- set_bounds((100,80) 400x300) on both");
        wv_full.set_bounds(rect(100, 80, 400, 300)).unwrap();
        wv_child.set_bounds(rect(100, 80, 400, 300)).unwrap();
      }
      2 => both("1 after set_bounds"),
      3 => {
        println!("--- resize both parents to inner 800x560");
        win_full.set_inner_size(PhysicalSize::new(800, 560));
        win_child.set_inner_size(PhysicalSize::new(800, 560));
      }
      4 => both("2 after parent resize"),
      5 => {
        println!("--- move both parents by (+50,+30)");
        win_full.set_outer_position(PhysicalPosition::new(150, 130));
        win_child.set_outer_position(PhysicalPosition::new(850, 130));
      }
      6 => both("3 after parent move"),
      7 => {
        unsafe {
          let mut o = POINT::default();
          let _ = ClientToScreen(hwnd_of(&win_child), &mut o);
          println!("--- B: set_bounds with SCREEN coords of client origin ({},{}) 300x200 (reporter's mistake)", o.x, o.y);
          wv_child.set_bounds(rect(o.x, o.y, 300, 200)).unwrap();
        }
      }
      8 => dump("B child", "4 screen coords", &win_child, &wv_child),
      9 => {
        println!("--- B: set_bounds((10,10) 300x200), then reparent child webview into window C");
        wv_child.set_bounds(rect(10, 10, 300, 200)).unwrap();
        wv_child.reparent(win_c.hwnd() as isize).unwrap();
      }
      10 => {
        dump("B child (in C)", "5 after reparent", &win_c, &wv_child);
        println!("--- B (in C): set_bounds((40,40) 300x200)");
        wv_child.set_bounds(rect(40, 40, 300, 200)).unwrap();
      }
      11 => dump("B child (in C)", "6 after set_bounds in C", &win_c, &wv_child),
      _ => *control_flow = ControlFlow::Exit,
    }
    step += 1;
  });
}

Output:

[0 initial] A full : parent outer=(100,100) 656x519 | client origin(screen)=(108,131) client=640x480 | scale=1
[0 initial] A full :   WRY_WEBVIEW hwnd screen=(108,131) parent-client-rel=(0,0) 640x480
[0 initial] A full :   controller.Bounds=(0,0)-(640,480)
[0 initial] A full :   wv.bounds()=(0,0) 640x480
[0 initial] B child: parent outer=(800,100) 656x519 | client origin(screen)=(808,131) client=640x480 | scale=1
[0 initial] B child:   WRY_WEBVIEW hwnd screen=(828,151) parent-client-rel=(20,20) 300x200
[0 initial] B child:   controller.Bounds=(0,0)-(300,200)
[0 initial] B child:   wv.bounds()=(20,20) 300x200
--- set_bounds((100,80) 400x300) on both
[1 after set_bounds] A full : parent outer=(100,100) 656x519 | client origin(screen)=(108,131) client=640x480 | scale=1
[1 after set_bounds] A full :   WRY_WEBVIEW hwnd screen=(208,211) parent-client-rel=(100,80) 400x300
[1 after set_bounds] A full :   controller.Bounds=(0,0)-(400,300)
[1 after set_bounds] A full :   wv.bounds()=(0,0) 400x300
[1 after set_bounds] B child: parent outer=(800,100) 656x519 | client origin(screen)=(808,131) client=640x480 | scale=1
[1 after set_bounds] B child:   WRY_WEBVIEW hwnd screen=(908,211) parent-client-rel=(100,80) 400x300
[1 after set_bounds] B child:   controller.Bounds=(0,0)-(400,300)
[1 after set_bounds] B child:   wv.bounds()=(100,80) 400x300
--- resize both parents to inner 800x560
[2 after parent resize] A full : parent outer=(100,100) 816x599 | client origin(screen)=(108,131) client=800x560 | scale=1
[2 after parent resize] A full :   WRY_WEBVIEW hwnd screen=(108,131) parent-client-rel=(0,0) 800x560
[2 after parent resize] A full :   controller.Bounds=(0,0)-(800,560)
[2 after parent resize] A full :   wv.bounds()=(0,0) 800x560
[2 after parent resize] B child: parent outer=(800,100) 816x599 | client origin(screen)=(808,131) client=800x560 | scale=1
[2 after parent resize] B child:   WRY_WEBVIEW hwnd screen=(908,211) parent-client-rel=(100,80) 400x300
[2 after parent resize] B child:   controller.Bounds=(0,0)-(400,300)
[2 after parent resize] B child:   wv.bounds()=(100,80) 400x300
--- move both parents by (+50,+30)
[3 after parent move] A full : parent outer=(150,130) 816x599 | client origin(screen)=(158,161) client=800x560 | scale=1
[3 after parent move] A full :   WRY_WEBVIEW hwnd screen=(158,161) parent-client-rel=(0,0) 800x560
[3 after parent move] A full :   controller.Bounds=(0,0)-(800,560)
[3 after parent move] A full :   wv.bounds()=(0,0) 800x560
[3 after parent move] B child: parent outer=(850,130) 816x599 | client origin(screen)=(858,161) client=800x560 | scale=1
[3 after parent move] B child:   WRY_WEBVIEW hwnd screen=(958,241) parent-client-rel=(100,80) 400x300
[3 after parent move] B child:   controller.Bounds=(0,0)-(400,300)
[3 after parent move] B child:   wv.bounds()=(100,80) 400x300
--- B: set_bounds with SCREEN coords of client origin (858,161) 300x200 (reporter's mistake)
[4 screen coords] B child: parent outer=(850,130) 816x599 | client origin(screen)=(858,161) client=800x560 | scale=1
[4 screen coords] B child:   WRY_WEBVIEW hwnd screen=(1716,322) parent-client-rel=(858,161) 300x200
[4 screen coords] B child:   controller.Bounds=(0,0)-(300,200)
[4 screen coords] B child:   wv.bounds()=(858,161) 300x200
--- B: set_bounds((10,10) 300x200), then reparent child webview into window C
[5 after reparent] B child (in C): parent outer=(100,650) 656x519 | client origin(screen)=(108,681) client=640x480 | scale=1
[5 after reparent] B child (in C):   WRY_WEBVIEW hwnd screen=(118,691) parent-client-rel=(10,10) 300x200
[5 after reparent] B child (in C):   controller.Bounds=(0,0)-(300,200)
[5 after reparent] B child (in C):   wv.bounds()=(-740,530) 300x200
--- B (in C): set_bounds((40,40) 300x200)
[6 after set_bounds in C] B child (in C): parent outer=(100,650) 656x519 | client origin(screen)=(108,681) client=640x480 | scale=1
[6 after set_bounds in C] B child (in C):   WRY_WEBVIEW hwnd screen=(148,721) parent-client-rel=(40,40) 300x200
[6 after set_bounds in C] B child (in C):   controller.Bounds=(0,0)-(300,200)
[6 after set_bounds in C] B child (in C):   wv.bounds()=(-710,560) 300x200

Thanks for your time!

TakahiroNago avatar Nov 14 '26 17:11 TakahiroNago

A downstream case for the bounds docs. On a Windows laptop, our Tauri child WebView rendered at roughly 80% of the intended size and shifted toward the top-left. The rectangle from getBoundingClientRect() was already relative to the parent client area, but we passed its CSS pixels as logical window units. We changed the caller to convert the rectangle with the measuring WebView's devicePixelRatio and pass a physical position and size. Our path is Window::add_child followed by set_position and set_size. IsctCompanion report and patch

For the child case, it would help to document both the parent-client-area origin and how logical and physical units are interpreted. Callers positioning a child over a DOM element need both pieces of information. Wry's current bounds docs

OHNope avatar Nov 23 '26 12:11 OHNope