diff --git a/src/Bermuda.Fdc3.Tests/ContentWindowFitTests.cs b/src/Bermuda.Fdc3.Tests/ContentWindowFitTests.cs new file mode 100644 index 0000000..fa0a514 --- /dev/null +++ b/src/Bermuda.Fdc3.Tests/ContentWindowFitTests.cs @@ -0,0 +1,142 @@ +using Bermuda.IpcContract; + +namespace Bermuda.Fdc3.Tests; + +/// +/// The sizing rules behind window.setContentSize: DPI conversion, the +/// caption strip added on top of the content, and clamping to min/max and the +/// monitor work area. +/// +public class ContentWindowFitTests +{ + private static readonly ContentWindowFit.Scales Identity = new(1, 1, 1, 1, 1); + private static readonly ContentWindowFit.Constraints Unconstrained = new(0, 0, double.PositiveInfinity, double.PositiveInfinity); + private static readonly ContentWindowFit.Area Desktop = new(0, 0, 2000, 1200); + + [Fact] + public void Css_pixels_become_dips_and_the_caption_strip_is_added() + { + // Client title bar: 3px resize border each side, 40px caption + 3px bottom border. + var fit = Fit(400, 240, chrome: new ContentWindowFit.Chrome(6, 43)); + + Assert.Equal(10, fit.Left); + Assert.Equal(20, fit.Top); + Assert.Equal(406, fit.Width); + Assert.Equal(283, fit.Height); + } + + [Fact] + public void Matching_raster_and_dip_scales_cancel_so_dpi_does_not_double_the_window() + { + var fit = Fit(400, 240, scales: new ContentWindowFit.Scales(1, 1.5, 1.5, 1.5, 1.5), chrome: new ContentWindowFit.Chrome(6, 43)); + + Assert.Equal(406, fit.Width); + Assert.Equal(283, fit.Height); + } + + [Fact] + public void A_raster_scale_above_the_dip_scale_grows_the_window() + { + var fit = Fit(100, 80, scales: new ContentWindowFit.Scales(1, 2, 2, 1, 1)); + + Assert.Equal(200, fit.Width); + Assert.Equal(160, fit.Height); + } + + [Fact] + public void Page_zoom_scales_the_content_before_chrome_is_added() + { + var fit = Fit(100, 80, scales: new ContentWindowFit.Scales(2, 1, 1, 1, 1), chrome: new ContentWindowFit.Chrome(6, 43)); + + Assert.Equal(206, fit.Width); + Assert.Equal(203, fit.Height); + } + + [Theory] + [InlineData(0)] + [InlineData(-1)] + public void A_non_positive_zoom_is_treated_as_one(double zoom) + { + var fit = Fit(100, 80, scales: new ContentWindowFit.Scales(zoom, 1, 1, 1, 1)); + + Assert.Equal(100, fit.Width); + Assert.Equal(80, fit.Height); + } + + [Fact] + public void A_non_positive_content_size_is_ignored() + { + Assert.Null(ContentWindowFit.Fit( + new ContentSize(0, 240), + Identity, + default, + Unconstrained, + Desktop, + 10, + 20)); + } + + [Fact] + public void A_huge_content_size_is_clamped_to_the_work_area_and_pulled_on_screen() + { + var fit = Fit(100_000, 100_000, work: new ContentWindowFit.Area(50, 80, 800, 600), left: 900, top: 900); + + Assert.Equal(800, fit.Width); + Assert.Equal(600, fit.Height); + Assert.Equal(50, fit.Left); + Assert.Equal(80, fit.Top); + } + + [Fact] + public void Position_is_left_alone_when_the_fitted_window_already_fits() + { + var fit = Fit(100, 80, left: 40, top: 60); + + Assert.Equal(40, fit.Left); + Assert.Equal(60, fit.Top); + } + + [Fact] + public void Min_and_max_constraints_bound_the_outer_size() + { + var small = Fit(100, 80, constraints: new ContentWindowFit.Constraints(500, 400, double.PositiveInfinity, double.PositiveInfinity)); + Assert.Equal(500, small.Width); + Assert.Equal(400, small.Height); + + var large = Fit(1000, 800, constraints: new ContentWindowFit.Constraints(0, 0, 300, 200)); + Assert.Equal(300, large.Width); + Assert.Equal(200, large.Height); + } + + [Fact] + public void A_minimum_larger_than_the_work_area_does_not_push_the_window_off_screen() + { + var fit = Fit(100, 80, constraints: new ContentWindowFit.Constraints(900, 900, double.PositiveInfinity, double.PositiveInfinity), work: new ContentWindowFit.Area(0, 0, 800, 600)); + + Assert.Equal(800, fit.Width); + Assert.Equal(600, fit.Height); + } + + private static ContentWindowFit.Placement Fit( + int width, + int height, + ContentWindowFit.Scales? scales = null, + ContentWindowFit.Chrome chrome = default, + ContentWindowFit.Constraints? constraints = null, + ContentWindowFit.Area? work = null, + double left = 10, + double top = 20) + { + var placement = ContentWindowFit.Fit( + new ContentSize(width, height), + scales ?? Identity, + chrome, + constraints ?? Unconstrained, + work ?? Desktop, + left, + top); + + Assert.NotNull(placement); + return placement.Value; + } +} diff --git a/src/Bermuda.Fdc3.Tests/IpcDispatchTests.cs b/src/Bermuda.Fdc3.Tests/IpcDispatchTests.cs index cef6337..a210070 100644 --- a/src/Bermuda.Fdc3.Tests/IpcDispatchTests.cs +++ b/src/Bermuda.Fdc3.Tests/IpcDispatchTests.cs @@ -18,6 +18,7 @@ public class IpcDispatchTests [InlineData("fdc3.getInfo", typeof(IFdc3Commands))] [InlineData("fdc3.raiseIntent", typeof(IFdc3Commands))] // "Async" suffix dropped [InlineData("fdc3.getIntentResult", typeof(IFdc3Commands))] + [InlineData("window.setContentSize", typeof(IWindowCommands))] public void Commands_are_named_from_their_interface_methods(string name, Type declaringInterface) { var command = IpcContract.IpcContract.Find(name); @@ -82,6 +83,35 @@ public async Task Command_errors_propagate_unwrapped() Assert.Equal(Fdc3Errors.NoChannelFound, error.Message); } + [Fact] + public async Task Window_setContentSize_binds_a_camelCase_payload() + { + var window = new RecordingWindow(); + + var result = await Invoke(window, "window.setContentSize", """{ "width": 480, "height": 320 }"""); + + Assert.Null(result); + Assert.Equal(new ContentSize(480, 320), window.Applied); + } + + [Fact] + public async Task Window_setContentSize_without_a_payload_is_InvalidArguments() + { + var window = new RecordingWindow(); + + var error = await Assert.ThrowsAsync(() => Invoke(window, "window.setContentSize", null)); + + Assert.Equal("InvalidArguments", error.Message); + Assert.Null(window.Applied); + } + + private sealed class RecordingWindow : IWindowCommands + { + public ContentSize? Applied { get; private set; } + + public void SetContentSize(ContentSize size) => Applied = size; + } + private static Task Invoke(object target, string name, string? payload) => IpcContract.IpcContract.Find(name)!.InvokeAsync( target, diff --git a/src/Bermuda.IpcContract/ContentWindowFit.cs b/src/Bermuda.IpcContract/ContentWindowFit.cs new file mode 100644 index 0000000..1287d02 --- /dev/null +++ b/src/Bermuda.IpcContract/ContentWindowFit.cs @@ -0,0 +1,98 @@ +namespace Bermuda.IpcContract; + +/// +/// Turns a reported by a page into an outer window +/// placement. The host measures DPI, page zoom, the caption strip and the +/// monitor work area; this applies them. Pure so the rules can be tested +/// without a window. +/// +public static class ContentWindowFit +{ + /// + /// is the WebView zoom (1 = 100%). + /// / are physical pixels + /// per CSS pixel; / are physical + /// pixels per device-independent pixel. On a per-monitor-aware window those + /// two scales match, so they cancel and a CSS pixel is one DIP before zoom. + /// + public readonly record struct Scales(double PageZoom, double RasterX, double RasterY, double DipX, double DipY); + + /// Host chrome around the page, in DIPs: caption strip plus any resize border the page does not cover. + public readonly record struct Chrome(double Width, double Height); + + /// Outer-window min/max in DIPs. Non-positive or non-finite limits are treated as unset. + public readonly record struct Constraints(double MinWidth, double MinHeight, double MaxWidth, double MaxHeight); + + /// Monitor work area in DIPs. + public readonly record struct Area(double Left, double Top, double Width, double Height); + + /// Outer window placement in DIPs. + public readonly record struct Placement(double Left, double Top, double Width, double Height); + + /// + /// Returns null when is non-positive, so a page + /// that reports 0 while it is hidden does not collapse the window. + /// + public static Placement? Fit( + ContentSize content, + Scales scales, + Chrome chrome, + Constraints constraints, + Area workArea, + double currentLeft, + double currentTop) + { + var contentW = CssToDip(content.Width, scales.PageZoom, scales.RasterX, scales.DipX); + var contentH = CssToDip(content.Height, scales.PageZoom, scales.RasterY, scales.DipY); + if (contentW <= 0 || contentH <= 0) return null; + + var desiredW = Math.Ceiling(contentW + NonNegative(chrome.Width)); + var desiredH = Math.Ceiling(contentH + NonNegative(chrome.Height)); + + var clampToWork = workArea.Width > 0 && workArea.Height > 0 + && double.IsFinite(workArea.Width) && double.IsFinite(workArea.Height); + + var maxW = Cap(constraints.MaxWidth, clampToWork ? workArea.Width : double.PositiveInfinity); + var maxH = Cap(constraints.MaxHeight, clampToWork ? workArea.Height : double.PositiveInfinity); + // A minimum larger than the work area (or the maximum) would push the + // window off the monitor, so the smaller limit wins. + var minW = Math.Min(NonNegative(constraints.MinWidth), maxW); + var minH = Math.Min(NonNegative(constraints.MinHeight), maxH); + + var width = Math.Clamp(desiredW, minW, maxW); + var height = Math.Clamp(desiredH, minH, maxH); + + var left = currentLeft; + var top = currentTop; + if (clampToWork) + { + var maxLeft = workArea.Left + workArea.Width - width; + var maxTop = workArea.Top + workArea.Height - height; + left = maxLeft >= workArea.Left ? Math.Clamp(left, workArea.Left, maxLeft) : workArea.Left; + top = maxTop >= workArea.Top ? Math.Clamp(top, workArea.Top, maxTop) : workArea.Top; + } + + return new Placement(left, top, width, height); + } + + /// CSS pixels → DIPs. See for what the scales mean. + public static double CssToDip(double cssPixels, double pageZoom, double rasterScale, double dipScale) + { + if (!double.IsFinite(cssPixels) || cssPixels <= 0) return 0; + if (!double.IsFinite(pageZoom) || pageZoom <= 0) pageZoom = 1; + if (!double.IsFinite(dipScale) || dipScale <= 0) dipScale = 1; + if (!double.IsFinite(rasterScale) || rasterScale <= 0) rasterScale = dipScale; + return cssPixels * pageZoom * rasterScale / dipScale; + } + + private static double Cap(double constraint, double workLimit) + { + var cap = double.IsFinite(constraint) && constraint > 0 ? constraint : double.PositiveInfinity; + if (double.IsFinite(workLimit) && workLimit > 0) + cap = Math.Min(cap, workLimit); + return cap; + } + + private static double NonNegative(double value) => + double.IsFinite(value) && value > 0 ? value : 0; +} diff --git a/src/Bermuda.IpcContract/IpcModels.cs b/src/Bermuda.IpcContract/IpcModels.cs index ec54c20..c8a5381 100644 --- a/src/Bermuda.IpcContract/IpcModels.cs +++ b/src/Bermuda.IpcContract/IpcModels.cs @@ -24,6 +24,31 @@ public interface IHostCommands SimulateNotificationActivationResult SimulateNotificationActivation(SimulateNotificationActivationRequest request); } +/// +/// CSS-pixel size of the page content a window should fit. Width and height are +/// the content box the page measured (a ResizeObserver border box), not +/// the outer window. +/// +public sealed record ContentSize(int Width, int Height); + +/// +/// Per-window commands (window.*) on the invoke() channel. +/// The host window the page is shown in implements them. Nothing is resized +/// until a page calls window.setContentSize. +/// +[IpcCommands("window")] +public interface IWindowCommands +{ + /// + /// Sizes this window so its content area fits . + /// The host converts those CSS pixels to device-independent pixels, adds + /// the caption strip (and the resize border kept outside the page), then + /// clamps to the monitor work area and the window's min/max. A non-positive + /// size is ignored. + /// + void SetContentSize(ContentSize size); +} + /// /// A postMessage request from the web side to HostBridge. Payload /// is deliberately untyped (its shape depends on Command). diff --git a/src/Bermuda.Web/e2e/fdc3.spec.ts b/src/Bermuda.Web/e2e/fdc3.spec.ts index c4c9510..b03783c 100644 --- a/src/Bermuda.Web/e2e/fdc3.spec.ts +++ b/src/Bermuda.Web/e2e/fdc3.spec.ts @@ -82,6 +82,11 @@ test.describe('FDC3', () => { expect(opened.appId).toBe('fdc3-probe') await expect(probe.locator('#status')).toHaveText('fdc3 ready') await expect(probe.locator('#received li')).toHaveText(['probe-7']) + // The probe opts in to content sizing, so the window leaves the default 1280×768. + await expect.poll(async () => probe.evaluate(async () => await window.chrome.webview.hostObjects.windowController.Width), { + message: 'probe window should shrink to its content', + }).toBeLessThan(800) + await expect.poll(async () => probe.evaluate(async () => await window.chrome.webview.hostObjects.windowController.Height)).toBeLessThan(600) } finally { const closed = probe.waitForEvent('close') await probe.evaluate(() => window.chrome.webview.hostObjects.windowController.Close()).catch(() => {}) diff --git a/src/Bermuda.Web/e2e/host-api.spec.ts b/src/Bermuda.Web/e2e/host-api.spec.ts index bec14f8..22d6d8d 100644 --- a/src/Bermuda.Web/e2e/host-api.spec.ts +++ b/src/Bermuda.Web/e2e/host-api.spec.ts @@ -56,6 +56,11 @@ test.describe('invoke() commands', () => { expect(result.error).toBe('Unknown command: definitelyNotACommand') }) + test('window.setContentSize without a payload is rejected', async ({ page }) => { + const result = await inPage<{ error: string }>(page, "return await bermudaHost.invoke('window.setContentSize')") + expect(result.error).toBe('InvalidArguments') + }) + test('concurrent invocations are correlated to the right caller', async ({ page }) => { const results = await inPage( page, @@ -206,6 +211,81 @@ test.describe('window control', () => { expect(state.bounds.height).toBe(700) }) + // Client title bar chrome: 3px resize border on each side, 40px caption + 3px bottom border + // (MainWindow.ClientCaptionHeight / ClientResizeBorder). DPI cancels when the + // WebView and the window share a scale, so the outer size is content + chrome. + test('setContentSize adds the caption strip to the reported content size', async ({ page }) => { + const client = await inPage(page, 'return await bermudaHost.window.usesClientTitleBar()') + const state = await inPage( + page, + `await bermudaHost.window.setContentSize({ width: 400, height: 240 }) + return await bermudaHost.window.getState()`, + ) + + expect(state.isMaximized).toBe(false) + if (client) { + // ±2: Windows can snap the outer size to a physical pixel at fractional DPI. + expect(state.bounds.width).toBeGreaterThanOrEqual(404) + expect(state.bounds.width).toBeLessThanOrEqual(408) + expect(state.bounds.height).toBeGreaterThanOrEqual(281) + expect(state.bounds.height).toBeLessThanOrEqual(285) + } else { + expect(state.bounds.width).toBeGreaterThan(400) + expect(state.bounds.height).toBeGreaterThan(240) + } + }) + + test('setContentSize clamps a huge content size to the work area', async ({ page }) => { + const bounds = await inPage<{ width: number; height: number }>( + page, + `await bermudaHost.window.setContentSize({ width: 100000, height: 100000 }) + return (await bermudaHost.window.getState()).bounds`, + ) + + expect(bounds.width).toBeGreaterThan(200) + expect(bounds.height).toBeGreaterThan(100) + expect(bounds.width).toBeLessThan(10_000) + expect(bounds.height).toBeLessThan(10_000) + }) + + test('setContentSize ignores a non-positive size', async ({ page }) => { + const before = await getState(page) + await inPage(page, 'await bermudaHost.window.setContentSize({ width: 0, height: 240 })') + expect((await getState(page)).bounds).toEqual(before.bounds) + }) + + test('observeContentSize reports the element through ResizeObserver', async ({ page }) => { + const client = await inPage(page, 'return await bermudaHost.window.usesClientTitleBar()') + const bounds = await inPage<{ width: number; height: number }>( + page, + `const el = document.createElement('div') + el.style.cssText = 'width:400px;height:240px;position:fixed;left:0;top:0' + document.body.appendChild(el) + const stop = bermudaHost.window.observeContentSize(el) + try { + for (let i = 0; i < 40; i++) { + const state = await bermudaHost.window.getState() + if (${client ? 'state.bounds.width >= 404 && state.bounds.width <= 408 && state.bounds.height >= 281 && state.bounds.height <= 285' : 'state.bounds.width > 400 && state.bounds.height > 240'}) return state.bounds + await new Promise(r => setTimeout(r, 50)) + } + return (await bermudaHost.window.getState()).bounds + } finally { + stop() + el.remove() + }`, + ) + + if (client) { + expect(bounds.width).toBeGreaterThanOrEqual(404) + expect(bounds.width).toBeLessThanOrEqual(408) + expect(bounds.height).toBeGreaterThanOrEqual(281) + expect(bounds.height).toBeLessThanOrEqual(285) + } else { + expect(bounds.width).toBeGreaterThan(400) + expect(bounds.height).toBeGreaterThan(240) + } + }) + test('Move sets the window position', async ({ page }) => { await inPage(page, 'await chrome.webview.hostObjects.windowController.Restore()') await inPage(page, 'await chrome.webview.hostObjects.windowController.Move(120, 80)') diff --git a/src/Bermuda.Web/public/fdc3-probe.html b/src/Bermuda.Web/public/fdc3-probe.html index aaf9a94..97a4510 100644 --- a/src/Bermuda.Web/public/fdc3-probe.html +++ b/src/Bermuda.Web/public/fdc3-probe.html @@ -8,11 +8,19 @@ FDC3 probe + -

FDC3 probe

-

waiting for window.fdc3…

-
    +
    +

    FDC3 probe

    +

    waiting for window.fdc3…

    +
      +
      + + diff --git a/src/Bermuda.Web/src/bridge/index.ts b/src/Bermuda.Web/src/bridge/index.ts index f81e61a..b8e7fdc 100644 --- a/src/Bermuda.Web/src/bridge/index.ts +++ b/src/Bermuda.Web/src/bridge/index.ts @@ -1,4 +1,5 @@ import type { + ContentSize, HostResponse, IpcRequest, NotificationActivation, @@ -14,6 +15,7 @@ import type { } from '../ipc/__generated__/ipc' export type { + ContentSize, NotificationActivation, ShowNotificationRequest, ShowNotificationResult, @@ -92,6 +94,41 @@ const windowApi = { setOverlay: (iconPng: string, description = '') => windowController().SetOverlayIcon(iconPng, description), /** Sets the taskbar progress bar's state ('none' hides it). */ setProgressState: (state: TaskbarProgressState) => windowController().SetProgressState(state), + /** + * Ask the host to fit this window to a content box measured in CSS pixels. + * Opt-in: the host does not resize until a page calls this. The host converts + * DPI, adds the caption strip and clamps to the monitor work area. + */ + setContentSize: (size: ContentSize): Promise => invoke('window.setContentSize', size), + /** + * Opt in to content-driven sizing. Observes `element`'s border box and reports + * it through `setContentSize`. The element should have an intrinsic size — a + * box stretched to the viewport will chase the window as it resizes. Returns + * a function that stops observing. No-op outside the host. + */ + observeContentSize: (element: Element): (() => void) => { + if (!window.chrome?.webview || typeof ResizeObserver === 'undefined') return () => {} + + let lastWidth = -1 + let lastHeight = -1 + const report = (width: number, height: number) => { + const reportedWidth = Math.ceil(width) + const reportedHeight = Math.ceil(height) + if (reportedWidth < 1 || reportedHeight < 1 || (reportedWidth === lastWidth && reportedHeight === lastHeight)) return + lastWidth = reportedWidth + lastHeight = reportedHeight + void invoke('window.setContentSize', { width: reportedWidth, height: reportedHeight }) + } + + const observer = new ResizeObserver(entries => { + const entry = entries[entries.length - 1] + if (!entry) return + const box = entry.borderBoxSize?.[0] + report(box ? box.inlineSize : entry.contentRect.width, box ? box.blockSize : entry.contentRect.height) + }) + observer.observe(element) + return () => observer.disconnect() + }, } as const export type WindowApi = typeof windowApi diff --git a/src/Bermuda.Web/src/ipc/__generated__/ipc.d.ts b/src/Bermuda.Web/src/ipc/__generated__/ipc.d.ts index ca23371..663733b 100644 --- a/src/Bermuda.Web/src/ipc/__generated__/ipc.d.ts +++ b/src/Bermuda.Web/src/ipc/__generated__/ipc.d.ts @@ -4,6 +4,11 @@ // and the [IpcHostObject] classes they mark (e.g. src/Bermuda/WindowScriptHost.cs). // +export interface ContentSize { + height: number; + width: number; +} + export interface Fdc3AddContextListenerRequest { channelId?: string | null; contextType?: string | null; @@ -311,6 +316,9 @@ export interface IpcMethods { sendIntentResult: (payload: Fdc3SendIntentResultRequest, ) => Promise; unsubscribe: (payload: Fdc3ListenerIdRequest, ) => Promise; }; + window: { + setContentSize: (payload: ContentSize, ) => Promise; + }; } export interface IpcHostObjects { diff --git a/src/Bermuda/HostBridge.cs b/src/Bermuda/HostBridge.cs index 887d7d8..c2a4dfa 100644 --- a/src/Bermuda/HostBridge.cs +++ b/src/Bermuda/HostBridge.cs @@ -17,10 +17,11 @@ namespace Bermuda; /// This window's current FDC3 connection, read per call because a page reload /// reconnects as a new instance (see MainWindow.OnContentLoading). /// +/// The window showing the page, for window.* commands. /// Enables dev/test-only commands (MainWindow: when CDP_PORT is set). [ClassInterface(ClassInterfaceType.AutoDual)] [ComVisible(true)] -public class HostBridge(Func fdc3, bool testHooks = false) : IHostCommands +public class HostBridge(Func fdc3, IWindowCommands window, bool testHooks = false) : IHostCommands { /// Web preset (camelCase, case-insensitive) with enums as camelCase strings, matching the generated TS unions. public static JsonSerializerOptions PayloadJson { get; } = new(JsonSerializerDefaults.Web) @@ -87,5 +88,6 @@ public SimulateNotificationActivationResult SimulateNotificationActivation(Simul private object TargetFor(Type commands) => commands == typeof(IFdc3Commands) ? fdc3() : commands == typeof(IHostCommands) ? this + : commands == typeof(IWindowCommands) ? window : throw new InvalidOperationException($"No handler for {commands.Name}."); } diff --git a/src/Bermuda/MainWindow.xaml.cs b/src/Bermuda/MainWindow.xaml.cs index 8adcf38..daaf788 100644 --- a/src/Bermuda/MainWindow.xaml.cs +++ b/src/Bermuda/MainWindow.xaml.cs @@ -4,6 +4,7 @@ using System.Text.Json.Serialization; using System.Windows; using System.Windows.Interop; +using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shell; using Bermuda.Fdc3; @@ -13,7 +14,7 @@ namespace Bermuda; -public partial class MainWindow : Window, IWindowController, IFdc3AppSink +public partial class MainWindow : Window, IWindowController, IWindowCommands, IFdc3AppSink { // The web side speaks camelCase (the generated TS shapes in // src/ipc/__generated__/ipc.d.ts); System.Text.Json's default is to keep @@ -70,6 +71,7 @@ public MainWindow(IConfiguration configuration, DesktopAgent fdc3, string fdc3Ap // A remote debugging port already means "dev/test run"; test-only commands ride on that. _bridge = new HostBridge( () => _fdc3Connection ?? throw new InvalidOperationException("FDC3 not connected yet."), + this, testHooks: _cdpPort > 0); // TITLE_BAR=client (default) lets the web app draw the title bar; TITLE_BAR=native @@ -430,6 +432,103 @@ public void SetProgressValue(double value) }); } + // IWindowCommands. Opt-in: only a page that reports a content size is resized. + public void SetContentSize(ContentSize size) + { + ApplyWindowAction(() => + { + if (_closed) return; + + // A maximized window has no content-sized bounds to write. Leave a + // minimized window minimized; Width/Height are its restore size. + if (base.WindowState != WindowState.Minimized) + base.WindowState = WindowState.Normal; + + var dpi = VisualTreeHelper.GetDpi(this); + // WebView2's rasterization scale tracks this window's DPI, so the + // same DpiScale converts CSS pixels to DIPs (page zoom aside) and + // the monitor work area from physical pixels back to DIPs. + var fit = ContentWindowFit.Fit( + size, + new ContentWindowFit.Scales(PageZoom, dpi.DpiScaleX, dpi.DpiScaleY, dpi.DpiScaleX, dpi.DpiScaleY), + ContentChrome(), + new ContentWindowFit.Constraints(MinWidth, MinHeight, MaxWidth, MaxHeight), + MonitorWorkArea(dpi), + base.Left, + base.Top); + if (fit is not { } placement + || !double.IsFinite(placement.Width) || !double.IsFinite(placement.Height) + || placement.Width <= 0 || placement.Height <= 0) + return; + if (Math.Abs(base.Width - placement.Width) < 0.5 + && Math.Abs(base.Height - placement.Height) < 0.5 + && Math.Abs(base.Left - placement.Left) < 0.5 + && Math.Abs(base.Top - placement.Top) < 0.5) + return; + + base.Width = placement.Width; + base.Height = placement.Height; + base.Left = placement.Left; + base.Top = placement.Top; + }); + } + + // ZoomFactor is 1 until the WebView exists, and again if it isn't a finite zoom. + private double PageZoom + { + get + { + var zoom = _webView.ZoomFactor; + return zoom > 0 && double.IsFinite(zoom) ? zoom : 1; + } + } + + // Extra outer size, in DIPs, so the WebView's content box matches the reported content. + private ContentWindowFit.Chrome ContentChrome() + { + if (_clientTitleBar) + { + // The page starts below the caption strip and inside the resize border + // (see ApplyClientTitleBar). Neither is part of the content box. + return new ContentWindowFit.Chrome(ClientResizeBorder * 2, ClientCaptionHeight + ClientResizeBorder); + } + + var frame = SystemParameters.WindowNonClientFrameThickness; + return new ContentWindowFit.Chrome(frame.Left + frame.Right, frame.Top + frame.Bottom); + } + + // Work area of the monitor this window is on, converted from physical pixels to DIPs. + private ContentWindowFit.Area MonitorWorkArea(DpiScale dpi) + { + var hwnd = NativeWindowHandle; + if (hwnd != IntPtr.Zero) + { + var monitor = MonitorFromWindow(hwnd, MonitorDefaultToNearest); + if (monitor != IntPtr.Zero) + { + var info = new Win32MonitorInfo { cbSize = Marshal.SizeOf() }; + if (GetMonitorInfo(monitor, ref info)) + { + var scaleX = dpi.DpiScaleX > 0 ? dpi.DpiScaleX : 1; + var scaleY = dpi.DpiScaleY > 0 ? dpi.DpiScaleY : 1; + var width = (info.rcWork.Right - info.rcWork.Left) / scaleX; + var height = (info.rcWork.Bottom - info.rcWork.Top) / scaleY; + if (width > 0 && height > 0) + { + return new ContentWindowFit.Area( + info.rcWork.Left / scaleX, + info.rcWork.Top / scaleY, + width, + height); + } + } + } + } + + var work = SystemParameters.WorkArea; + return new ContentWindowFit.Area(work.Left, work.Top, work.Width, work.Height); + } + [DllImport("user32.dll", EntryPoint = "GetForegroundWindow")] private static extern IntPtr NativeGetForegroundWindow(); @@ -453,4 +552,30 @@ private bool IsWindowForeground() { return NativeWindowHandle != IntPtr.Zero && NativeGetForegroundWindow() == NativeWindowHandle; } + + private const uint MonitorDefaultToNearest = 2; + + [DllImport("user32.dll")] + private static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint dwFlags); + + [DllImport("user32.dll", CharSet = CharSet.Auto)] + private static extern bool GetMonitorInfo(IntPtr hMonitor, ref Win32MonitorInfo lpmi); + + [StructLayout(LayoutKind.Sequential, Pack = 4)] + private struct Win32Rect + { + public int Left; + public int Top; + public int Right; + public int Bottom; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 4)] + private struct Win32MonitorInfo + { + public int cbSize; + public Win32Rect rcMonitor; + public Win32Rect rcWork; + public uint dwFlags; + } }