@native-sdk/cli 0.4.1 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/assets/native-sdk.manifest +17 -1
  2. package/build/app.zig +40 -1
  3. package/build.zig +49 -3
  4. package/package.json +10 -9
  5. package/src/platform/macos/appkit_host.m +21 -6
  6. package/src/platform/windows/webview2_host.cpp +377 -72
  7. package/src/primitives/canvas/chart.zig +8 -7
  8. package/src/primitives/canvas/chart_tests.zig +2 -2
  9. package/src/primitives/canvas/commands.zig +27 -0
  10. package/src/primitives/canvas/gpu.zig +8 -0
  11. package/src/primitives/canvas/markdown_tests.zig +1 -1
  12. package/src/primitives/canvas/reference.zig +82 -3
  13. package/src/primitives/canvas/reference_tests.zig +155 -1
  14. package/src/primitives/canvas/serialization.zig +16 -3
  15. package/src/primitives/canvas/themes/geist.zig +6 -0
  16. package/src/primitives/canvas/tokens.zig +7 -0
  17. package/src/primitives/canvas/widget_builtin_tests.zig +191 -0
  18. package/src/primitives/canvas/widget_render.zig +29 -41
  19. package/src/primitives/canvas/widget_render_controls.zig +55 -42
  20. package/src/primitives/canvas/widget_render_style.zig +53 -0
  21. package/src/primitives/canvas/widget_render_surfaces.zig +19 -18
  22. package/src/primitives/canvas/widget_runtime_tests.zig +20 -21
  23. package/src/runtime/canvas_frame_packet_tests.zig +9 -1
  24. package/src/runtime/canvas_frame_patch_tests.zig +39 -1
  25. package/src/runtime/canvas_widget_control_tests.zig +4 -4
  26. package/src/runtime/ui_app.zig +78 -10
  27. package/src/runtime/ui_app_tests.zig +109 -0
  28. package/src/runtime/ui_app_window_tests.zig +93 -0
  29. package/src/tooling/package.zig +45 -0
  30. package/src/tooling/templates.zig +42 -1
  31. package/third_party/webview2/LICENSE.txt +27 -0
  32. package/third_party/webview2/README.md +19 -0
  33. package/third_party/webview2/arm64/WebView2Loader.dll +0 -0
  34. package/third_party/webview2/include/EventToken.h +12 -0
  35. package/third_party/webview2/include/WebView2.h +60636 -0
  36. package/third_party/webview2/x64/WebView2Loader.dll +0 -0
@@ -27,19 +27,22 @@
27
27
  #include <thread>
28
28
  #include <vector>
29
29
 
30
+ /* The WebView2 SDK header is vendored (third_party/webview2/include) and
31
+ * every first-party build graph puts it on the include path, so a build
32
+ * that cannot see it is misconfigured — fail it loudly instead of
33
+ * shipping a host whose WebView loads report WebViewNotFound at runtime.
34
+ * NATIVE_SDK_ALLOW_WEBVIEW2_STUB opts a hand-rolled build into the old
35
+ * stubbed layer (canvas apps are unaffected by the stub). */
30
36
  #if __has_include(<WebView2.h>) && __has_include(<wrl.h>)
31
37
  #include <WebView2.h>
32
38
  #include <wrl.h>
33
39
  #define NATIVE_SDK_HAS_WEBVIEW2 1
34
- using Microsoft::WRL::Callback;
35
40
  using Microsoft::WRL::ComPtr;
36
- #else
41
+ #elif defined(NATIVE_SDK_ALLOW_WEBVIEW2_STUB)
37
42
  #define NATIVE_SDK_HAS_WEBVIEW2 0
38
- /* Loud on purpose: without the WebView2 SDK header on the include path
39
- * the host builds with the embedded WebView layer stubbed out — canvas
40
- * apps are unaffected, but apps that load a WebView report
41
- * WebViewNotFound at start. */
42
43
  #pragma message("WebView2.h not found: building the Windows host without the embedded WebView layer (canvas apps unaffected; WebView loads will report WebViewNotFound)")
44
+ #else
45
+ #error "WebView2.h not found: add third_party/webview2/include to the include path, or define NATIVE_SDK_ALLOW_WEBVIEW2_STUB to build without the embedded WebView layer"
43
46
  #endif
44
47
 
45
48
  /* Media Foundation (the audio backend below) + WinHTTP (the audio cache
@@ -557,6 +560,9 @@ struct Host {
557
560
  int appearance_color_scheme = -1;
558
561
  int appearance_reduce_motion = -1;
559
562
  int appearance_high_contrast = -1;
563
+ /* Whether the CoInitializeEx in native_sdk_windows_create succeeded
564
+ * and native_sdk_windows_destroy owes the balancing CoUninitialize. */
565
+ bool com_initialized = false;
560
566
  AudioState audio;
561
567
  AudioSpectrumState spectrum;
562
568
  std::shared_ptr<HostLifetime> lifetime = std::make_shared<HostLifetime>();
@@ -1124,6 +1130,8 @@ static std::string extractHtmlClipboardFragment(const std::string &payload) {
1124
1130
  return payload;
1125
1131
  }
1126
1132
 
1133
+ static UINT dpiForWindow(HWND hwnd);
1134
+
1127
1135
  static void emit(Host *host, const Window &window, EventKind kind) {
1128
1136
  if (!host || !host->callback) return;
1129
1137
  RECT rect = {};
@@ -1131,9 +1139,14 @@ static void emit(Host *host, const Window &window, EventKind kind) {
1131
1139
  WindowsEvent event = {};
1132
1140
  event.kind = kind;
1133
1141
  event.window_id = window.id;
1134
- event.width = rect.right > rect.left ? (double)(rect.right - rect.left) : window.width;
1135
- event.height = rect.bottom > rect.top ? (double)(rect.bottom - rect.top) : window.height;
1136
- event.scale = 1.0;
1142
+ /* Window geometry crosses the runtime boundary in LOGICAL points:
1143
+ * the client rect is physical pixels, so divide by the window's
1144
+ * device scale. In a DPI-unaware process the reported DPI is 96 and
1145
+ * the two units coincide, so this stays the identity there. */
1146
+ const double scale = window.hwnd ? (double)dpiForWindow(window.hwnd) / 96.0 : 1.0;
1147
+ event.width = rect.right > rect.left ? (double)(rect.right - rect.left) / scale : window.width;
1148
+ event.height = rect.bottom > rect.top ? (double)(rect.bottom - rect.top) / scale : window.height;
1149
+ event.scale = scale;
1137
1150
  event.x = window.x;
1138
1151
  event.y = window.y;
1139
1152
  event.open = window.hwnd != nullptr;
@@ -1421,17 +1434,51 @@ static int webViewExtent(double value) {
1421
1434
  return value > 1 ? (int)(value + 0.5) : 1;
1422
1435
  }
1423
1436
 
1437
+ /* Explicit webview frames arrive from the runtime in LOGICAL points and
1438
+ * scale to physical pixels at the window's DPI, exactly like native view
1439
+ * frames. The auto-filling main webview is the one exception: its frame
1440
+ * is copied straight from the physical client rect (the top-level
1441
+ * WM_SIZE handler), so it passes through unscaled. */
1442
+ static double webViewFrameScale(const ChildWebView &webview) {
1443
+ if (!webview.frame_explicit || !webview.hwnd) return 1.0;
1444
+ return (double)dpiForWindow(webview.hwnd) / 96.0;
1445
+ }
1446
+
1424
1447
  static bool validChildWebViewFrame(double x, double y, double width, double height) {
1425
1448
  return x >= 0 && y >= 0 && width > 0 && height > 0;
1426
1449
  }
1427
1450
 
1428
- static int nativeViewCoord(double value) {
1451
+ static constexpr int nativeViewCoord(double value) {
1429
1452
  return value > 0 ? (int)(value + 0.5) : 0;
1430
1453
  }
1431
1454
 
1432
- static int nativeViewExtent(double value) {
1433
- return value > 0 ? (int)(value + 0.5) : 0;
1434
- }
1455
+ /* Compile-time proof of the accumulate-then-round frame policy (see
1456
+ * nativeViewPhysicalFrame): rounding each nesting level separately drifts
1457
+ * from the round of the logical sum — parent x=10.4 plus child x=10.4 at
1458
+ * scale 1.5 is round(15.6) + round(15.6) = 32, one pixel right of the
1459
+ * true origin round(20.8 * 1.5) = 31 — and an independently rounded
1460
+ * extent opens the same one-pixel seam against an edge derived from the
1461
+ * accumulated logical coordinates: origin 10.2 with width 10.2 at scale
1462
+ * 1.5 ends at round(15.3) + round(15.3) = 30, but the true right edge is
1463
+ * round(20.4 * 1.5) = 31. */
1464
+ static_assert(nativeViewCoord(10.4 * 1.5) + nativeViewCoord(10.4 * 1.5) == 32 && nativeViewCoord((10.4 + 10.4) * 1.5) == 31,
1465
+ "per-level rounding must drift so the accumulate-then-round policy is load-bearing");
1466
+ static_assert(nativeViewCoord(10.2 * 1.5) + nativeViewCoord(10.2 * 1.5) == 30 && nativeViewCoord((10.2 + 10.2) * 1.5) == 31,
1467
+ "independently rounded extents must open seams that edge-derived extents close");
1468
+
1469
+ /* A scaled window CONTENT extent rounded to whole physical pixels — the
1470
+ * same round-once policy as native view frames (see
1471
+ * nativeViewPhysicalFrame). Truncating instead would land fractional-DPI
1472
+ * windows one physical pixel short of the request: logical 726 at 125%
1473
+ * is 907.5 physical, which must become 908, not 907. Every conversion of
1474
+ * a scaled content size to a physical extent goes through here so the
1475
+ * standard-chrome and hidden-titlebar paths cannot drift apart. */
1476
+ static constexpr LONG physicalContentExtent(double value) {
1477
+ return (LONG)(value + 0.5);
1478
+ }
1479
+
1480
+ static_assert(physicalContentExtent(726 * 1.25) == 908 && (LONG)(726 * 1.25) == 907,
1481
+ "truncation must land a pixel short of the round so the rounding is load-bearing");
1435
1482
 
1436
1483
  static bool validNativeViewFrame(double x, double y, double width, double height) {
1437
1484
  return x >= 0 && y >= 0 && width >= 0 && height >= 0;
@@ -1507,17 +1554,53 @@ static void applySegmentedControlText(HWND hwnd, const std::string &text) {
1507
1554
  TabCtrl_SetCurSel(hwnd, 0);
1508
1555
  }
1509
1556
 
1510
- static POINT nativeViewAbsoluteOrigin(Host *host, const NativeView &view) {
1511
- POINT point = { nativeViewCoord(view.x), nativeViewCoord(view.y) };
1512
- if (!host || view.parent.empty()) return point;
1557
+ /* Scale for converting the runtime's LOGICAL view frames into physical
1558
+ * client pixels: the owning top-level window's DPI over 96. A
1559
+ * DPI-unaware process reports 96, so this is 1.0 there and view frames
1560
+ * pass through unchanged. */
1561
+ static double nativeViewFrameScale(Host *host, const NativeView &view) {
1562
+ if (!host) return 1.0;
1563
+ auto window = host->windows.find(view.window_id);
1564
+ if (window == host->windows.end() || !window->second.hwnd) return 1.0;
1565
+ return (double)dpiForWindow(window->second.hwnd) / 96.0;
1566
+ }
1567
+
1568
+ /* Absolute LOGICAL origin of a view: its own frame origin plus every
1569
+ * ancestor's, summed before any scaling or rounding. */
1570
+ static void nativeViewLogicalOrigin(Host *host, const NativeView &view, double *logical_x, double *logical_y) {
1571
+ *logical_x = view.x;
1572
+ *logical_y = view.y;
1573
+ if (!host || view.parent.empty()) return;
1513
1574
  auto parent = host->native_views.find(nativeViewKey(view.window_id, view.parent));
1514
1575
  while (parent != host->native_views.end()) {
1515
- point.x += nativeViewCoord(parent->second.x);
1516
- point.y += nativeViewCoord(parent->second.y);
1576
+ *logical_x += parent->second.x;
1577
+ *logical_y += parent->second.y;
1517
1578
  if (parent->second.parent.empty()) break;
1518
1579
  parent = host->native_views.find(nativeViewKey(parent->second.window_id, parent->second.parent));
1519
1580
  }
1520
- return point;
1581
+ }
1582
+
1583
+ /* Physical frame policy: every physical EDGE is the once-rounded product
1584
+ * of an ACCUMULATED logical coordinate and the window scale. Accumulating
1585
+ * before rounding matters because the sum of per-level rounds drifts from
1586
+ * the round of the sum at fractional scales (and at fractional logical
1587
+ * coordinates even at scale 1.0) — see the static_asserts beside
1588
+ * nativeViewCoord for the numeric proof. Width and height fall out as
1589
+ * edge differences (right = round((logical_x + width) * scale)) rather
1590
+ * than independently rounded extents, so frames that abut logically —
1591
+ * a sibling starting where the previous one ends, a child flush against
1592
+ * its parent's edge — land on the same physical pixel column with no
1593
+ * one-pixel gap or overlap at any scale. */
1594
+ static RECT nativeViewPhysicalFrame(Host *host, const NativeView &view, double scale) {
1595
+ double logical_x = 0;
1596
+ double logical_y = 0;
1597
+ nativeViewLogicalOrigin(host, view, &logical_x, &logical_y);
1598
+ RECT frame = {};
1599
+ frame.left = nativeViewCoord(logical_x * scale);
1600
+ frame.top = nativeViewCoord(logical_y * scale);
1601
+ frame.right = nativeViewCoord((logical_x + view.width) * scale);
1602
+ frame.bottom = nativeViewCoord((logical_y + view.height) * scale);
1603
+ return frame;
1521
1604
  }
1522
1605
 
1523
1606
  static void applyNativeViewText(NativeView &view, const std::string &text) {
@@ -1561,8 +1644,9 @@ static void applyNativeViewAccessibility(NativeView &view) {
1561
1644
 
1562
1645
  static void applyNativeViewFrame(Host *host, NativeView &view) {
1563
1646
  if (!view.hwnd) return;
1564
- POINT origin = nativeViewAbsoluteOrigin(host, view);
1565
- MoveWindow(view.hwnd, origin.x, origin.y, nativeViewExtent(view.width), nativeViewExtent(view.height), TRUE);
1647
+ const double scale = nativeViewFrameScale(host, view);
1648
+ RECT frame = nativeViewPhysicalFrame(host, view, scale);
1649
+ MoveWindow(view.hwnd, frame.left, frame.top, frame.right - frame.left, frame.bottom - frame.top, TRUE);
1566
1650
  }
1567
1651
 
1568
1652
  static void applyNativeViewState(NativeView &view, bool update_text, const std::string &text) {
@@ -1740,20 +1824,12 @@ static uint64_t gpuTimestampNs() {
1740
1824
  return seconds * 1000000000ull + remainder * 1000000000ull / (uint64_t)frequency.QuadPart;
1741
1825
  }
1742
1826
 
1743
- /* Device scale for a gpu_surface child. GetDpiForWindow is resolved
1744
- * dynamically so the host keeps working on Windows versions (and Wine
1745
- * prefixes) that predate per-monitor DPI. In a DPI-unaware process the
1746
- * call reports 96, so logical size == client pixels, matching how the
1747
- * rest of this host treats coordinates. */
1827
+ /* Device scale for a gpu_surface child: the shared per-window DPI
1828
+ * resolution (dpiForWindow) over the 96-dpi baseline. In a DPI-unaware
1829
+ * process the resolved DPI is 96, so logical size == client pixels,
1830
+ * matching how the rest of this host treats coordinates. */
1748
1831
  static double gpuSurfaceScale(HWND hwnd) {
1749
- using GetDpiForWindowFn = UINT(WINAPI *)(HWND);
1750
- static GetDpiForWindowFn get_dpi = reinterpret_cast<GetDpiForWindowFn>(
1751
- reinterpret_cast<void *>(GetProcAddress(GetModuleHandleW(L"user32.dll"), "GetDpiForWindow")));
1752
- if (get_dpi && hwnd) {
1753
- const UINT dpi = get_dpi(hwnd);
1754
- if (dpi > 0) return (double)dpi / 96.0;
1755
- }
1756
- return 1.0;
1832
+ return hwnd ? (double)dpiForWindow(hwnd) / 96.0 : 1.0;
1757
1833
  }
1758
1834
 
1759
1835
  static NativeView *gpuSurfaceViewForHwnd(Host *host, HWND hwnd) {
@@ -1846,8 +1922,17 @@ static Window *chromelessWindowForHwnd(Host *host, HWND hwnd) {
1846
1922
  return nullptr;
1847
1923
  }
1848
1924
 
1849
- /* Per-window dpi with the same dynamic resolution (and the same 96
1850
- * fallback) as gpuSurfaceScale. */
1925
+ static UINT systemDpi();
1926
+
1927
+ /* Per-window DPI, resolved dynamically to mirror the awareness chain
1928
+ * the embedded manifest declares. GetDpiForWindow (Windows 10 1607+,
1929
+ * per-monitor v2 — modern Wine prefixes export it too) is preferred;
1930
+ * where it is absent, shcore's GetDpiForMonitor reports the effective
1931
+ * DPI of the window's monitor (Windows 8.1+, matching per-monitor v1
1932
+ * awareness); where shcore is absent too, the system DPI (matching
1933
+ * system-DPI awareness; older Wine prefixes land here through
1934
+ * systemDpi's GetDeviceCaps branch). A DPI-unaware process reports 96
1935
+ * on every branch, so logical points == client pixels there. */
1851
1936
  static UINT dpiForWindow(HWND hwnd) {
1852
1937
  using GetDpiForWindowFn = UINT(WINAPI *)(HWND);
1853
1938
  static GetDpiForWindowFn get_dpi = reinterpret_cast<GetDpiForWindowFn>(
@@ -1856,7 +1941,22 @@ static UINT dpiForWindow(HWND hwnd) {
1856
1941
  const UINT dpi = get_dpi(hwnd);
1857
1942
  if (dpi > 0) return dpi;
1858
1943
  }
1859
- return 96;
1944
+ using GetDpiForMonitorFn = HRESULT(WINAPI *)(HMONITOR, int, UINT *, UINT *);
1945
+ static GetDpiForMonitorFn get_monitor_dpi = []() -> GetDpiForMonitorFn {
1946
+ HMODULE shcore = LoadLibraryW(L"shcore.dll");
1947
+ if (!shcore) return nullptr;
1948
+ return reinterpret_cast<GetDpiForMonitorFn>(
1949
+ reinterpret_cast<void *>(GetProcAddress(shcore, "GetDpiForMonitor")));
1950
+ }();
1951
+ if (get_monitor_dpi && hwnd) {
1952
+ HMONITOR monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
1953
+ UINT dpi_x = 0;
1954
+ UINT dpi_y = 0;
1955
+ /* 0 = MDT_EFFECTIVE_DPI, spelled numerically so headers that
1956
+ * predate shellscalingapi.h still compile. */
1957
+ if (monitor && get_monitor_dpi(monitor, 0, &dpi_x, &dpi_y) == S_OK && dpi_y > 0) return dpi_y;
1958
+ }
1959
+ return systemDpi();
1860
1960
  }
1861
1961
 
1862
1962
  /* Caption metrics MUST scale with the monitor the window sits on, or a
@@ -1871,6 +1971,43 @@ static int systemMetricForDpi(int index, UINT dpi) {
1871
1971
  return GetSystemMetrics(index);
1872
1972
  }
1873
1973
 
1974
+ /* System DPI for sizing a window that does not exist yet (creation
1975
+ * scales the requested logical content size to physical pixels before
1976
+ * the first monitor is known; WM_DPICHANGED re-derives the frame when
1977
+ * the window lands elsewhere), and the tail of dpiForWindow's chain
1978
+ * where no per-monitor API is available. GetDpiForSystem is resolved
1979
+ * dynamically (Windows 10 1607+) with the desktop DC's LOGPIXELSY,
1980
+ * then 96, as fallbacks. A DPI-unaware process reports 96 on every
1981
+ * branch, keeping points == pixels exactly as before. */
1982
+ static UINT systemDpi() {
1983
+ using GetDpiForSystemFn = UINT(WINAPI *)();
1984
+ static GetDpiForSystemFn get_dpi = reinterpret_cast<GetDpiForSystemFn>(
1985
+ reinterpret_cast<void *>(GetProcAddress(GetModuleHandleW(L"user32.dll"), "GetDpiForSystem")));
1986
+ if (get_dpi) {
1987
+ const UINT dpi = get_dpi();
1988
+ if (dpi > 0) return dpi;
1989
+ }
1990
+ HDC dc = GetDC(nullptr);
1991
+ if (dc) {
1992
+ const int dpi = GetDeviceCaps(dc, LOGPIXELSY);
1993
+ ReleaseDC(nullptr, dc);
1994
+ if (dpi > 0) return (UINT)dpi;
1995
+ }
1996
+ return 96;
1997
+ }
1998
+
1999
+ /* AdjustWindowRectEx pinned to an explicit DPI so the frame borders
2000
+ * match the monitor the window is being sized against; resolved
2001
+ * dynamically (Windows 10 1607+) with the classic system-metric call
2002
+ * as the fallback. */
2003
+ static BOOL adjustWindowRectForDpi(RECT *rect, DWORD style, BOOL menu, DWORD ex_style, UINT dpi) {
2004
+ using AdjustWindowRectExForDpiFn = BOOL(WINAPI *)(LPRECT, DWORD, BOOL, DWORD, UINT);
2005
+ static AdjustWindowRectExForDpiFn adjust = reinterpret_cast<AdjustWindowRectExForDpiFn>(
2006
+ reinterpret_cast<void *>(GetProcAddress(GetModuleHandleW(L"user32.dll"), "AdjustWindowRectExForDpi")));
2007
+ if (adjust) return adjust(rect, style, menu, ex_style, dpi);
2008
+ return AdjustWindowRectEx(rect, style, menu, ex_style);
2009
+ }
2010
+
1874
2011
  /* Thickness of the top resize frame (sizing border + padded border) at
1875
2012
  * the window's dpi: the WM_NCCALCSIZE maximize inset and the
1876
2013
  * WM_NCHITTEST top resize band are both exactly this tall. */
@@ -1943,12 +2080,12 @@ static void applyHiddenTitlebarFrame(Window &window) {
1943
2080
  * bottom borders, plus the menu bar when one is attached. Plain
1944
2081
  * AdjustWindowRectEx would count the caption band the custom calc gives
1945
2082
  * back, landing the client one band taller than requested. */
1946
- static SIZE hiddenOuterSizeForContent(DWORD style, DWORD ex_style, bool has_menu, double content_width, double content_height) {
2083
+ static SIZE hiddenOuterSizeForContent(DWORD style, DWORD ex_style, bool has_menu, double content_width, double content_height, UINT dpi) {
1947
2084
  RECT borders = { 0, 0, 0, 0 };
1948
- AdjustWindowRectEx(&borders, style & ~WS_CAPTION, FALSE, ex_style);
2085
+ adjustWindowRectForDpi(&borders, style & ~WS_CAPTION, FALSE, ex_style, dpi);
1949
2086
  SIZE outer = {};
1950
- outer.cx = (LONG)content_width + (borders.right - borders.left);
1951
- outer.cy = (LONG)content_height + borders.bottom + (has_menu ? GetSystemMetrics(SM_CYMENU) : 0);
2087
+ outer.cx = physicalContentExtent(content_width) + (borders.right - borders.left);
2088
+ outer.cy = physicalContentExtent(content_height) + borders.bottom + (has_menu ? systemMetricForDpi(SM_CYMENU, dpi) : 0);
1952
2089
  return outer;
1953
2090
  }
1954
2091
 
@@ -3821,6 +3958,92 @@ static void destroyAllWindows(Host *host) {
3821
3958
  #if NATIVE_SDK_HAS_WEBVIEW2
3822
3959
  using CreateEnvironmentFn = HRESULT (STDAPICALLTYPE *)(PCWSTR, PCWSTR, ICoreWebView2EnvironmentOptions *, ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler *);
3823
3960
 
3961
+ /* The event-handler factory. The full WRL provides this as
3962
+ * Microsoft::WRL::Callback, but the mingw WRL subset only carries ComPtr,
3963
+ * so the handful of WebView2 completion and event handlers are built on
3964
+ * this minimal equivalent: one refcounted COM object per handler that
3965
+ * forwards Invoke to the wrapped callable. QueryInterface needs each
3966
+ * handler's IID at runtime; the constants mirror the interface
3967
+ * declarations in WebView2.h (mingw's __uuidof only covers interfaces
3968
+ * its own headers declare, the same reason the WIC GUIDs further down
3969
+ * are defined locally). */
3970
+ static const GUID kNativeSdkIID_EnvironmentCompletedHandler = {0x4e8a3389, 0xc9d8, 0x4bd2, {0xb6, 0xb5, 0x12, 0x4f, 0xee, 0x6c, 0xc1, 0x4d}};
3971
+ static const GUID kNativeSdkIID_ControllerCompletedHandler = {0x6c4819f3, 0xc9b7, 0x4260, {0x81, 0x27, 0xc9, 0xf5, 0xbd, 0xe7, 0xf6, 0x8c}};
3972
+ static const GUID kNativeSdkIID_WebMessageReceivedHandler = {0x57213f19, 0x00e6, 0x49fa, {0x8e, 0x07, 0x89, 0x8e, 0xa0, 0x1e, 0xcb, 0xd2}};
3973
+ static const GUID kNativeSdkIID_AcceleratorKeyPressedHandler = {0xb29c7e28, 0xfa79, 0x41a8, {0x8e, 0x44, 0x65, 0x81, 0x1c, 0x76, 0xdc, 0xb2}};
3974
+ static const GUID kNativeSdkIID_WebResourceRequestedHandler = {0xab00b74c, 0x15f1, 0x4646, {0x80, 0xe8, 0xe7, 0x63, 0x41, 0xd2, 0x5d, 0x71}};
3975
+ static const GUID kNativeSdkIID_NavigationStartingHandler = {0x9adbe429, 0xf36d, 0x432b, {0x9d, 0xdc, 0xf8, 0x88, 0x1f, 0xbd, 0x76, 0xe3}};
3976
+
3977
+ template <typename Interface> struct WebView2HandlerIid;
3978
+ template <> struct WebView2HandlerIid<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler> {
3979
+ static const GUID &value() { return kNativeSdkIID_EnvironmentCompletedHandler; }
3980
+ };
3981
+ template <> struct WebView2HandlerIid<ICoreWebView2CreateCoreWebView2ControllerCompletedHandler> {
3982
+ static const GUID &value() { return kNativeSdkIID_ControllerCompletedHandler; }
3983
+ };
3984
+ template <> struct WebView2HandlerIid<ICoreWebView2WebMessageReceivedEventHandler> {
3985
+ static const GUID &value() { return kNativeSdkIID_WebMessageReceivedHandler; }
3986
+ };
3987
+ template <> struct WebView2HandlerIid<ICoreWebView2AcceleratorKeyPressedEventHandler> {
3988
+ static const GUID &value() { return kNativeSdkIID_AcceleratorKeyPressedHandler; }
3989
+ };
3990
+ template <> struct WebView2HandlerIid<ICoreWebView2WebResourceRequestedEventHandler> {
3991
+ static const GUID &value() { return kNativeSdkIID_WebResourceRequestedHandler; }
3992
+ };
3993
+ template <> struct WebView2HandlerIid<ICoreWebView2NavigationStartingEventHandler> {
3994
+ static const GUID &value() { return kNativeSdkIID_NavigationStartingHandler; }
3995
+ };
3996
+
3997
+ /* Every handler interface above declares a two-argument Invoke; this
3998
+ * trait reads the argument types off the interface so the override below
3999
+ * matches exactly. */
4000
+ template <typename Method> struct WebView2InvokeSignature;
4001
+ template <typename Interface, typename FirstArg, typename SecondArg>
4002
+ struct WebView2InvokeSignature<HRESULT (STDMETHODCALLTYPE Interface::*)(FirstArg, SecondArg)> {
4003
+ using First = FirstArg;
4004
+ using Second = SecondArg;
4005
+ };
4006
+
4007
+ template <typename Interface, typename Callable>
4008
+ class WebView2Handler final : public Interface {
4009
+ public:
4010
+ explicit WebView2Handler(Callable callable) : callable_(std::move(callable)) {}
4011
+ HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **object) override {
4012
+ if (!object) return E_POINTER;
4013
+ if (IsEqualIID(riid, WebView2HandlerIid<Interface>::value()) || IsEqualIID(riid, IID_IUnknown)) {
4014
+ *object = static_cast<Interface *>(this);
4015
+ AddRef();
4016
+ return S_OK;
4017
+ }
4018
+ *object = nullptr;
4019
+ return E_NOINTERFACE;
4020
+ }
4021
+ ULONG STDMETHODCALLTYPE AddRef() override {
4022
+ return refs_.fetch_add(1, std::memory_order_relaxed) + 1;
4023
+ }
4024
+ ULONG STDMETHODCALLTYPE Release() override {
4025
+ ULONG remaining = refs_.fetch_sub(1, std::memory_order_acq_rel) - 1;
4026
+ if (remaining == 0) delete this;
4027
+ return remaining;
4028
+ }
4029
+ HRESULT STDMETHODCALLTYPE Invoke(
4030
+ typename WebView2InvokeSignature<decltype(&Interface::Invoke)>::First first,
4031
+ typename WebView2InvokeSignature<decltype(&Interface::Invoke)>::Second second) override {
4032
+ return callable_(first, second);
4033
+ }
4034
+
4035
+ private:
4036
+ std::atomic<ULONG> refs_{1};
4037
+ Callable callable_;
4038
+ };
4039
+
4040
+ template <typename Interface, typename Callable>
4041
+ static ComPtr<Interface> Callback(Callable callable) {
4042
+ ComPtr<Interface> handler;
4043
+ handler.Attach(new WebView2Handler<Interface, Callable>(std::move(callable)));
4044
+ return handler;
4045
+ }
4046
+
3824
4047
  static const wchar_t *nativeSdkBridgeScript() {
3825
4048
  return LR"ZN((function(){
3826
4049
  if(window.zero&&window.zero.invoke&&window.zero.on&&window.zero._emit){return;}
@@ -3942,17 +4165,19 @@ static const wchar_t *nativeSdkBridgeScript() {
3942
4165
  }
3943
4166
 
3944
4167
  static RECT webViewRect(const ChildWebView &webview) {
4168
+ const double scale = webViewFrameScale(webview);
3945
4169
  RECT rect = {};
3946
4170
  rect.left = 0;
3947
4171
  rect.top = 0;
3948
- rect.right = webViewExtent(webview.width);
3949
- rect.bottom = webViewExtent(webview.height);
4172
+ rect.right = webViewExtent(webview.width * scale);
4173
+ rect.bottom = webViewExtent(webview.height * scale);
3950
4174
  return rect;
3951
4175
  }
3952
4176
 
3953
4177
  static void applyWebViewFrame(ChildWebView &webview) {
3954
4178
  if (!webview.hwnd) return;
3955
- MoveWindow(webview.hwnd, webViewCoord(webview.x), webViewCoord(webview.y), webViewExtent(webview.width), webViewExtent(webview.height), TRUE);
4179
+ const double scale = webViewFrameScale(webview);
4180
+ MoveWindow(webview.hwnd, webViewCoord(webview.x * scale), webViewCoord(webview.y * scale), webViewExtent(webview.width * scale), webViewExtent(webview.height * scale), TRUE);
3956
4181
  if (webview.controller) {
3957
4182
  RECT bounds = webViewRect(webview);
3958
4183
  webview.controller->put_Bounds(bounds);
@@ -4107,7 +4332,7 @@ static bool createChildWebView(Host *host, const std::string &key) {
4107
4332
  uint64_t bridge_window_id = found->second.window_id;
4108
4333
  std::string bridge_label = found->second.label;
4109
4334
  found->second.webview->add_WebMessageReceived(Callback<ICoreWebView2WebMessageReceivedEventHandler>(
4110
- [host, bridge_window_id, bridge_label, lifetime](ICoreWebView2 *, ICoreWebView2WebMessageReceivedEventArgs *args) -> HRESULT {
4335
+ [host, key, bridge_window_id, bridge_label, lifetime](ICoreWebView2 *, ICoreWebView2WebMessageReceivedEventArgs *args) -> HRESULT {
4111
4336
  auto token = lifetime.lock();
4112
4337
  if (!token) return S_OK;
4113
4338
  std::lock_guard<std::recursive_mutex> guard(token->mutex);
@@ -4545,6 +4770,56 @@ static LRESULT CALLBACK windowProc(HWND hwnd, UINT message, WPARAM wparam, LPARA
4545
4770
  }
4546
4771
  }
4547
4772
  return 0;
4773
+ case WM_DPICHANGED:
4774
+ /* The window moved to a monitor with a different DPI (or the
4775
+ * user changed display scaling). Adopt the system-suggested
4776
+ * frame — it keeps the window the same LOGICAL size on the
4777
+ * new scale — then re-derive everything DPI-dependent: the
4778
+ * hidden-titlebar band (its caption metrics scale with the
4779
+ * monitor), each native child's physical frame, every gpu
4780
+ * surface's logical-size/scale pairing so the runtime
4781
+ * re-rasterizes at the new density, and each explicit child
4782
+ * webview's physical frame. The SetWindowPos WM_SIZE
4783
+ * re-emits kResize, which now carries the new scale. Only
4784
+ * per-monitor-DPI-aware processes receive this message. */
4785
+ if (host) {
4786
+ const RECT *suggested = reinterpret_cast<const RECT *>(lparam);
4787
+ if (suggested) {
4788
+ SetWindowPos(hwnd, nullptr, suggested->left, suggested->top, suggested->right - suggested->left, suggested->bottom - suggested->top, SWP_NOZORDER | SWP_NOACTIVATE);
4789
+ }
4790
+ for (auto &entry : host->windows) {
4791
+ if (entry.second.hwnd == hwnd && windowUsesHiddenTitlebar(entry.second)) applyHiddenTitlebarFrame(entry.second);
4792
+ }
4793
+ for (auto &view_entry : host->native_views) {
4794
+ NativeView &view = view_entry.second;
4795
+ if (!view.hwnd || GetAncestor(view.hwnd, GA_ROOT) != hwnd) continue;
4796
+ applyNativeViewFrame(host, view);
4797
+ if (view.kind != kViewGpuSurface) continue;
4798
+ const double surface_scale = gpuSurfaceScale(view.hwnd);
4799
+ double width = 0;
4800
+ double height = 0;
4801
+ if (gpuSurfaceLogicalSize(view, view.hwnd, surface_scale, &width, &height)) {
4802
+ (void)syncGpuSurfaceGeometry(host, view, width, height, surface_scale);
4803
+ }
4804
+ }
4805
+ #if NATIVE_SDK_HAS_WEBVIEW2
4806
+ for (auto &webview_entry : host->webviews) {
4807
+ ChildWebView &webview = webview_entry.second;
4808
+ /* Explicit frames are LOGICAL points scaled to
4809
+ * physical pixels at apply time, so a monitor-scale
4810
+ * change strands them until re-applied here. The
4811
+ * auto-fill main webview stores PHYSICAL client-rect
4812
+ * pixels and already re-derived them in the WM_SIZE
4813
+ * that the SetWindowPos above dispatched, so it is
4814
+ * skipped. */
4815
+ if (!webview.frame_explicit) continue;
4816
+ if (!webview.hwnd || GetAncestor(webview.hwnd, GA_ROOT) != hwnd) continue;
4817
+ applyWebViewFrame(webview);
4818
+ }
4819
+ #endif
4820
+ return 0;
4821
+ }
4822
+ break;
4548
4823
  case WM_TIMER:
4549
4824
  if (host && handleAppTimerMessage(host, wparam)) return 0;
4550
4825
  if (host && handleAudioTimerMessage(host, wparam)) return 0;
@@ -4558,20 +4833,26 @@ static LRESULT CALLBACK windowProc(HWND hwnd, UINT message, WPARAM wparam, LPARA
4558
4833
  Window &window = entry.second;
4559
4834
  if (window.hwnd != hwnd) continue;
4560
4835
  if (window.min_width <= 0 && window.min_height <= 0) break;
4561
- /* The declared floor is a CONTENT size; convert to the
4562
- * outer track size for this window's current style.
4563
- * Hidden titlebar styles carry no top chrome (the
4564
- * custom WM_NCCALCSIZE hands the caption band to the
4565
- * client), so their conversion skips it too. */
4566
- RECT frame = { 0, 0, (LONG)(window.min_width > 0 ? window.min_width : 0), (LONG)(window.min_height > 0 ? window.min_height : 0) };
4836
+ /* The declared floor is a CONTENT size in LOGICAL
4837
+ * points; scale to physical pixels at this window's
4838
+ * DPI, then convert to the outer track size for its
4839
+ * current style. Hidden titlebar styles carry no top
4840
+ * chrome (the custom WM_NCCALCSIZE hands the caption
4841
+ * band to the client), so their conversion skips it
4842
+ * too. */
4843
+ const UINT dpi = dpiForWindow(hwnd);
4844
+ const double scale = (double)dpi / 96.0;
4845
+ const double min_content_width = window.min_width > 0 ? window.min_width * scale : 0;
4846
+ const double min_content_height = window.min_height > 0 ? window.min_height * scale : 0;
4847
+ RECT frame = { 0, 0, physicalContentExtent(min_content_width), physicalContentExtent(min_content_height) };
4567
4848
  const DWORD style = (DWORD)GetWindowLongPtrW(hwnd, GWL_STYLE);
4568
4849
  const DWORD ex_style = (DWORD)GetWindowLongPtrW(hwnd, GWL_EXSTYLE);
4569
4850
  const bool has_menu = GetMenu(hwnd) != nullptr;
4570
- AdjustWindowRectEx(&frame, style, has_menu, ex_style);
4851
+ adjustWindowRectForDpi(&frame, style, has_menu, ex_style, dpi);
4571
4852
  LONG outer_width = frame.right - frame.left;
4572
4853
  LONG outer_height = frame.bottom - frame.top;
4573
4854
  if (windowUsesHiddenTitlebar(window)) {
4574
- const SIZE outer = hiddenOuterSizeForContent(style, ex_style, has_menu, window.min_width > 0 ? window.min_width : 0, window.min_height > 0 ? window.min_height : 0);
4855
+ const SIZE outer = hiddenOuterSizeForContent(style, ex_style, has_menu, min_content_width, min_content_height, dpi);
4575
4856
  outer_width = outer.cx;
4576
4857
  outer_height = outer.cy;
4577
4858
  }
@@ -4640,19 +4921,26 @@ static bool createNativeWindow(Host *host, Window &window) {
4640
4921
  style = WS_POPUP | WS_SYSMENU | WS_MINIMIZEBOX;
4641
4922
  if (window.resizable) style |= WS_THICKFRAME | WS_MAXIMIZEBOX;
4642
4923
  }
4643
- /* The requested frame is a CONTENT size (the other hosts size the
4644
- * content area); grow it to the outer size for this style so the
4645
- * client rect lands at the request. The menu bar is attached after
4646
- * creation, so account for it here when menus are declared. Hidden
4647
- * styles use the custom-calc shape (no top chrome) — plain
4648
- * AdjustWindowRectEx would land their client one caption band tall. */
4924
+ /* The requested frame is a CONTENT size in LOGICAL points (the
4925
+ * other hosts size the content area); scale it to physical pixels
4926
+ * at the DPI the window opens at (the system DPI — WM_DPICHANGED
4927
+ * re-derives the frame if it lands on another monitor), then grow
4928
+ * it to the outer size for this style so the client rect lands at
4929
+ * the request. The menu bar is attached after creation, so account
4930
+ * for it here when menus are declared. Hidden styles use the
4931
+ * custom-calc shape (no top chrome) — plain adjustment would land
4932
+ * their client one caption band tall. */
4649
4933
  const bool has_menu = !host->menus.empty();
4650
- RECT frame = { 0, 0, (LONG)window.width, (LONG)window.height };
4651
- AdjustWindowRectEx(&frame, style, has_menu ? TRUE : FALSE, 0);
4934
+ const UINT dpi = systemDpi();
4935
+ const double scale = (double)dpi / 96.0;
4936
+ const double content_width = window.width * scale;
4937
+ const double content_height = window.height * scale;
4938
+ RECT frame = { 0, 0, physicalContentExtent(content_width), physicalContentExtent(content_height) };
4939
+ adjustWindowRectForDpi(&frame, style, has_menu ? TRUE : FALSE, 0, dpi);
4652
4940
  LONG outer_width = frame.right - frame.left;
4653
4941
  LONG outer_height = frame.bottom - frame.top;
4654
4942
  if (windowUsesHiddenTitlebar(window)) {
4655
- const SIZE outer = hiddenOuterSizeForContent(style, 0, has_menu, window.width, window.height);
4943
+ const SIZE outer = hiddenOuterSizeForContent(style, 0, has_menu, content_width, content_height, dpi);
4656
4944
  outer_width = outer.cx;
4657
4945
  outer_height = outer.cy;
4658
4946
  }
@@ -4706,6 +4994,15 @@ Host *native_sdk_windows_create(const char *app_name, size_t app_name_len, const
4706
4994
  InitCommonControlsEx(&controls);
4707
4995
 
4708
4996
  Host *host = new Host();
4997
+ /* The WebView2 environment factory requires a single-threaded
4998
+ * apartment on the calling thread; without one it fails with
4999
+ * CO_E_NOTINITIALIZED. Create, run, and destroy all execute on the
5000
+ * app's main thread, so one init here pairs with the CoUninitialize
5001
+ * at the end of native_sdk_windows_destroy — after the controllers
5002
+ * are closed. S_FALSE (already initialized) still pairs;
5003
+ * RPC_E_CHANGED_MODE (an MTA got there first) leaves nothing to
5004
+ * balance. */
5005
+ host->com_initialized = SUCCEEDED(CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE));
4709
5006
  host->app_name = slice(app_name, app_name_len);
4710
5007
  host->window_title = slice(window_title, window_title_len);
4711
5008
  host->bundle_id = slice(bundle_id, bundle_id_len);
@@ -4749,7 +5046,9 @@ void native_sdk_windows_destroy(Host *host) {
4749
5046
  audioReleaseSession(host, true);
4750
5047
  removeNotificationIcon(host);
4751
5048
  destroyAllWindows(host);
5049
+ const bool com_initialized = host->com_initialized;
4752
5050
  delete host;
5051
+ if (com_initialized) CoUninitialize();
4753
5052
  }
4754
5053
 
4755
5054
  void native_sdk_windows_run(Host *host, EventCallback callback, void *context) {
@@ -5367,16 +5666,17 @@ int native_sdk_windows_create_view(Host *host, uint64_t window_id, const char *l
5367
5666
  }
5368
5667
  if (view.visible) style |= WS_VISIBLE;
5369
5668
 
5370
- POINT origin = nativeViewAbsoluteOrigin(host, view);
5669
+ const double scale = nativeViewFrameScale(host, view);
5670
+ RECT frame = nativeViewPhysicalFrame(host, view, scale);
5371
5671
  HWND hwnd = CreateWindowExW(
5372
5672
  ex_style,
5373
5673
  class_name.c_str(),
5374
5674
  wide_text.c_str(),
5375
5675
  style,
5376
- origin.x,
5377
- origin.y,
5378
- nativeViewExtent(width),
5379
- nativeViewExtent(height),
5676
+ frame.left,
5677
+ frame.top,
5678
+ frame.right - frame.left,
5679
+ frame.bottom - frame.top,
5380
5680
  window->second.hwnd,
5381
5681
  nullptr,
5382
5682
  host->instance,
@@ -5923,15 +6223,19 @@ int native_sdk_windows_create_webview(Host *host, uint64_t window_id, const char
5923
6223
  if (host->webviews.find(key) != host->webviews.end()) return 0;
5924
6224
 
5925
6225
  std::string url_string = slice(url, url_len);
6226
+ /* The requested frame is in logical points (frame_explicit child
6227
+ * webviews scale like native view frames); physical placement at
6228
+ * the owning window's DPI. */
6229
+ const double frame_scale = (double)dpiForWindow(window->second.hwnd) / 96.0;
5926
6230
  HWND hwnd = CreateWindowExW(
5927
6231
  0,
5928
6232
  L"STATIC",
5929
6233
  L"",
5930
6234
  WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
5931
- webViewCoord(x),
5932
- webViewCoord(y),
5933
- webViewExtent(width),
5934
- webViewExtent(height),
6235
+ webViewCoord(x * frame_scale),
6236
+ webViewCoord(y * frame_scale),
6237
+ webViewExtent(width * frame_scale),
6238
+ webViewExtent(height * frame_scale),
5935
6239
  window->second.hwnd,
5936
6240
  nullptr,
5937
6241
  host->instance,
@@ -5973,7 +6277,8 @@ int native_sdk_windows_set_webview_frame(Host *host, uint64_t window_id, const c
5973
6277
  found->second.width = width;
5974
6278
  found->second.height = height;
5975
6279
  found->second.frame_explicit = true;
5976
- MoveWindow(found->second.hwnd, webViewCoord(x), webViewCoord(y), webViewExtent(width), webViewExtent(height), TRUE);
6280
+ const double frame_scale = webViewFrameScale(found->second);
6281
+ MoveWindow(found->second.hwnd, webViewCoord(x * frame_scale), webViewCoord(y * frame_scale), webViewExtent(width * frame_scale), webViewExtent(height * frame_scale), TRUE);
5977
6282
  #if NATIVE_SDK_HAS_WEBVIEW2
5978
6283
  if (found->second.controller) {
5979
6284
  RECT bounds = webViewRect(found->second);