@native-sdk/cli 0.5.3 → 0.6.0

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 (172) hide show
  1. package/build/app.zig +91 -2
  2. package/build.zig +756 -5
  3. package/build.zig.zon +7 -0
  4. package/native-sdk.d.ts +19 -1
  5. package/package.json +9 -9
  6. package/packages/core/package-lock.json +2 -2
  7. package/packages/core/package.json +1 -1
  8. package/packages/core/rt/rt.zig +416 -9
  9. package/packages/core/sdk/core.ts +706 -5
  10. package/packages/core/sdk/events.ts +17 -8
  11. package/packages/core/src/checker.ts +305 -2
  12. package/packages/core/src/diagnostics.ts +12 -0
  13. package/packages/core/src/emitter.ts +3187 -264
  14. package/packages/core/src/typed_ast.ts +51 -4
  15. package/packages/core/src/types.ts +34 -1
  16. package/skill-data/native-ui/SKILL.md +42 -4
  17. package/skill-data/ts-core/SKILL.md +13 -3
  18. package/src/app_runner/root.zig +112 -10
  19. package/src/app_runner/ts_core_main.zig +4 -0
  20. package/src/automation/layout_fingerprint.zig +160 -0
  21. package/src/automation/protocol.zig +82 -33
  22. package/src/automation/root.zig +1 -0
  23. package/src/automation/server.zig +1 -1
  24. package/src/automation/snapshot.zig +68 -9
  25. package/src/automation/watcher.zig +1 -1
  26. package/src/embed/host.zig +5 -0
  27. package/src/embed/tests.zig +119 -1
  28. package/src/embed/ui_host.zig +13 -0
  29. package/src/platform/linux/gtk_host.c +639 -16
  30. package/src/platform/linux/gtk_host.h +25 -0
  31. package/src/platform/linux/root.zig +351 -7
  32. package/src/platform/macos/appkit_host.h +152 -8
  33. package/src/platform/macos/appkit_host.m +1816 -100
  34. package/src/platform/macos/cef_host.mm +372 -11
  35. package/src/platform/macos/root.zig +379 -11
  36. package/src/platform/null_platform.zig +696 -9
  37. package/src/platform/null_platform_tests.zig +35 -0
  38. package/src/platform/root.zig +42 -0
  39. package/src/platform/types.zig +524 -18
  40. package/src/platform/windows/root.zig +432 -9
  41. package/src/platform/windows/webview2_host.cpp +482 -45
  42. package/src/primitives/app_manifest/comptime_scene.zig +5 -0
  43. package/src/primitives/app_manifest/root.zig +1 -0
  44. package/src/primitives/app_manifest/types.zig +32 -0
  45. package/src/primitives/app_manifest/validation.zig +18 -0
  46. package/src/primitives/canvas/a11y_audit.zig +33 -11
  47. package/src/primitives/canvas/a11y_audit_tests.zig +20 -0
  48. package/src/primitives/canvas/drawing.zig +25 -0
  49. package/src/primitives/canvas/equality.zig +8 -0
  50. package/src/primitives/canvas/events.zig +103 -16
  51. package/src/primitives/canvas/frame.zig +125 -1
  52. package/src/primitives/canvas/layout_audit.zig +22 -5
  53. package/src/primitives/canvas/markdown_hostile_tests.zig +8 -4
  54. package/src/primitives/canvas/render_tests.zig +13 -10
  55. package/src/primitives/canvas/root.zig +48 -0
  56. package/src/primitives/canvas/terminal_box.zig +471 -0
  57. package/src/primitives/canvas/terminal_grid.zig +978 -0
  58. package/src/primitives/canvas/terminal_grid_tests.zig +1093 -0
  59. package/src/primitives/canvas/test_support.zig +1 -0
  60. package/src/primitives/canvas/tests.zig +2 -0
  61. package/src/primitives/canvas/text_tests.zig +39 -4
  62. package/src/primitives/canvas/tokens.zig +115 -12
  63. package/src/primitives/canvas/ui.zig +535 -12
  64. package/src/primitives/canvas/ui_markup.zig +253 -36
  65. package/src/primitives/canvas/ui_markup_binary.zig +4 -1
  66. package/src/primitives/canvas/ui_markup_compiled.zig +195 -9
  67. package/src/primitives/canvas/ui_markup_compiled_tests.zig +188 -8
  68. package/src/primitives/canvas/ui_markup_contract.zig +89 -6
  69. package/src/primitives/canvas/ui_markup_contract_tests.zig +65 -1
  70. package/src/primitives/canvas/ui_markup_huge_document_tests.zig +154 -0
  71. package/src/primitives/canvas/ui_markup_huge_model_tests.zig +1 -0
  72. package/src/primitives/canvas/ui_markup_reflect.zig +75 -24
  73. package/src/primitives/canvas/ui_markup_tests.zig +178 -9
  74. package/src/primitives/canvas/ui_markup_view.zig +220 -11
  75. package/src/primitives/canvas/ui_markup_view_tests.zig +553 -28
  76. package/src/primitives/canvas/ui_schema.zig +110 -17
  77. package/src/primitives/canvas/ui_schema_tests.zig +18 -10
  78. package/src/primitives/canvas/ui_tests.zig +141 -9
  79. package/src/primitives/canvas/widget_access.zig +28 -2
  80. package/src/primitives/canvas/widget_anchored_tests.zig +48 -0
  81. package/src/primitives/canvas/widget_invalidation.zig +81 -1
  82. package/src/primitives/canvas/widget_layout.zig +59 -11
  83. package/src/primitives/canvas/widget_layout_tests.zig +125 -4
  84. package/src/primitives/canvas/widget_render.zig +272 -18
  85. package/src/primitives/canvas/widget_render_scroll.zig +108 -27
  86. package/src/primitives/canvas/widget_routing.zig +59 -7
  87. package/src/primitives/canvas/widget_runtime.zig +23 -0
  88. package/src/primitives/canvas/widget_runtime_tests.zig +149 -0
  89. package/src/primitives/canvas/widget_semantics.zig +119 -11
  90. package/src/primitives/canvas/widget_semantics_tests.zig +409 -0
  91. package/src/primitives/canvas/widget_tree.zig +17 -0
  92. package/src/primitives/canvas/widgets.zig +132 -0
  93. package/src/root.zig +23 -0
  94. package/src/runtime/api.zig +76 -5
  95. package/src/runtime/automation_commands.zig +20 -1
  96. package/src/runtime/automation_snapshot.zig +25 -1
  97. package/src/runtime/automation_widget_dispatch.zig +73 -8
  98. package/src/runtime/bridge_payload.zig +8 -0
  99. package/src/runtime/bridge_responses.zig +5 -0
  100. package/src/runtime/builtin_bridge.zig +9 -4
  101. package/src/runtime/canvas_font_tests.zig +439 -2
  102. package/src/runtime/canvas_fonts.zig +61 -6
  103. package/src/runtime/canvas_frame.zig +62 -7
  104. package/src/runtime/canvas_frame_animation_tests.zig +5 -4
  105. package/src/runtime/canvas_frame_helpers.zig +190 -1
  106. package/src/runtime/canvas_frame_invalidation_tests.zig +531 -0
  107. package/src/runtime/canvas_frame_patch_tests.zig +161 -10
  108. package/src/runtime/canvas_frame_retained_tests.zig +5 -2
  109. package/src/runtime/canvas_image_tests.zig +195 -0
  110. package/src/runtime/canvas_images.zig +45 -12
  111. package/src/runtime/canvas_widget_accessibility_tests.zig +1 -1
  112. package/src/runtime/canvas_widget_clipboard_tests.zig +40 -0
  113. package/src/runtime/canvas_widget_context_menu.zig +269 -32
  114. package/src/runtime/canvas_widget_context_menu_tests.zig +640 -14
  115. package/src/runtime/canvas_widget_display.zig +1 -1
  116. package/src/runtime/canvas_widget_event_tests.zig +1823 -0
  117. package/src/runtime/canvas_widget_events.zig +240 -24
  118. package/src/runtime/canvas_widget_runtime.zig +213 -29
  119. package/src/runtime/canvas_widget_scroll_driver_tests.zig +170 -7
  120. package/src/runtime/canvas_widget_scroll_drivers.zig +151 -17
  121. package/src/runtime/canvas_widget_scroll_tests.zig +435 -23
  122. package/src/runtime/canvas_widget_state.zig +6 -0
  123. package/src/runtime/canvas_widget_text_tests.zig +1 -1
  124. package/src/runtime/core.zig +131 -13
  125. package/src/runtime/effects.zig +8136 -180
  126. package/src/runtime/effects_channel_tests.zig +3519 -0
  127. package/src/runtime/effects_fetch_tests.zig +89 -1
  128. package/src/runtime/effects_file_tests.zig +41 -1
  129. package/src/runtime/effects_image_tests.zig +1304 -0
  130. package/src/runtime/effects_pty_tests.zig +1362 -0
  131. package/src/runtime/effects_tests.zig +167 -9
  132. package/src/runtime/effects_video_tests.zig +3609 -0
  133. package/src/runtime/flow.zig +42 -4
  134. package/src/runtime/gpu_surface_events.zig +473 -13
  135. package/src/runtime/media_surface.zig +116 -11
  136. package/src/runtime/media_surface_tests.zig +61 -0
  137. package/src/runtime/pty.zig +1252 -0
  138. package/src/runtime/pty_windows.zig +1780 -0
  139. package/src/runtime/root.zig +36 -0
  140. package/src/runtime/runtime_event_tests.zig +20 -1
  141. package/src/runtime/session_blobs.zig +689 -0
  142. package/src/runtime/session_journal.zig +432 -62
  143. package/src/runtime/session_record.zig +43 -2
  144. package/src/runtime/session_replay.zig +556 -20
  145. package/src/runtime/session_tests.zig +2087 -1
  146. package/src/runtime/shell_layout.zig +7 -0
  147. package/src/runtime/terminal_session.zig +1569 -0
  148. package/src/runtime/terminal_session_tests.zig +450 -0
  149. package/src/runtime/terminal_vt_ghostty.zig +15 -0
  150. package/src/runtime/terminal_vt_stub.zig +13 -0
  151. package/src/runtime/testdata/fonts/NotoSansSC-Receipt.ttf +0 -0
  152. package/src/runtime/testdata/fonts/OFL.txt +93 -0
  153. package/src/runtime/tests.zig +8 -0
  154. package/src/runtime/ts_core_host.zig +1320 -45
  155. package/src/runtime/ts_core_host_tests.zig +1100 -1
  156. package/src/runtime/ts_ui_app.zig +23 -5
  157. package/src/runtime/ui_app.zig +2444 -69
  158. package/src/runtime/ui_app_tests.zig +3171 -744
  159. package/src/runtime/ui_app_virtual_variable_tests.zig +4 -2
  160. package/src/runtime/ui_app_window_tests.zig +736 -0
  161. package/src/runtime/view.zig +190 -2
  162. package/src/runtime/view_widget_scroll.zig +218 -68
  163. package/src/runtime/view_widget_text.zig +11 -2
  164. package/src/runtime/view_widget_tree.zig +111 -3
  165. package/src/runtime/window_command_bridge_tests.zig +117 -0
  166. package/src/runtime/window_storage.zig +77 -2
  167. package/src/runtime/window_view_runtime.zig +34 -2
  168. package/src/runtime/window_views.zig +62 -1
  169. package/src/terminal_session_tests_root.zig +15 -0
  170. package/src/tooling/manifest.zig +75 -0
  171. package/src/tooling/raw_manifest.zig +2 -0
  172. package/src/tooling/templates.zig +244 -8
@@ -41,7 +41,16 @@
41
41
  * WebView loads report WebViewNotFound at runtime. */
42
42
  #if defined(NATIVE_SDK_ALLOW_WEBVIEW2_STUB)
43
43
  #define NATIVE_SDK_HAS_WEBVIEW2 0
44
- #pragma message("Embedded WebView layer excluded by the build configuration: building the Windows host without it (canvas apps unaffected; WebView loads will report WebViewNotFound)")
44
+ /* Deliberately NO compiler diagnostic in this branch — not even an
45
+ * informational #pragma message. The stub is the expected, configured
46
+ * state of every native-only Windows build, and zig renders every
47
+ * clang diagnostic of a failing translation unit as `error:` (its
48
+ * serialized clang diagnostics carry no severity into the error
49
+ * bundle), so an informational note here masquerades as the
50
+ * build-killing error the moment any unrelated real error appears
51
+ * anywhere in this file. The teaching lives where it is actionable
52
+ * instead: a stubbed host reports WebViewNotFound the moment an app
53
+ * actually uses a WebView. */
45
54
  #elif __has_include(<WebView2.h>) && __has_include(<wrl.h>)
46
55
  #include <WebView2.h>
47
56
  #include <wrl.h>
@@ -121,6 +130,8 @@ enum EventKind {
121
130
  kTimer = 16,
122
131
  kAppearance = 17,
123
132
  kAudio = 18,
133
+ kContextMenuAction = 19,
134
+ kViewFocused = 20,
124
135
  };
125
136
 
126
137
  constexpr uint32_t kShortcutModifierPrimary = 1u << 0;
@@ -152,6 +163,11 @@ constexpr UINT kAudioSessionMessage = WM_APP + 45;
152
163
  * loop starves it far below the contract cadence, while posted messages
153
164
  * keep their place in the queue. */
154
165
  constexpr UINT kAudioSpectrumMessage = WM_APP + 46;
166
+ /* Posted by native_sdk_windows_show_context_menu (loop thread, but mid
167
+ * event dispatch); the window procedure presents the pending app context
168
+ * menu on a fresh loop turn — the same deferral the macOS host's
169
+ * dispatch_async performs before popUpMenuPositioningItem. */
170
+ constexpr UINT kShowContextMenuMessage = WM_APP + 47;
155
171
  constexpr const char *kAssetVirtualOrigin = "https://native-sdk-app.localhost";
156
172
 
157
173
  constexpr int kViewWebView = 0;
@@ -184,6 +200,10 @@ struct WindowsEvent {
184
200
  double y;
185
201
  int open;
186
202
  int focused;
203
+ /* kWindowFrame: nonzero while the window is alive but hidden by its
204
+ * close_policy (.hide intercepted WM_CLOSE). open stays 1 for the
205
+ * window's whole hidden stretch. */
206
+ int hidden;
187
207
  const char *label;
188
208
  size_t label_len;
189
209
  const char *title;
@@ -233,6 +253,21 @@ struct WindowsEvent {
233
253
  * from -60 dBFS at 0 to full scale at 255). Zeros on every other
234
254
  * event kind — every emit site value-initializes the struct. */
235
255
  uint8_t audio_bands[32];
256
+ /* kContextMenuAction payload (the macOS host's field names):
257
+ * widget_id echoes the request's correlation token, menu_item_id is
258
+ * the selected item's id (0 = dismissed without a selection). */
259
+ uint64_t widget_id;
260
+ uint32_t menu_item_id;
261
+ };
262
+
263
+ /* One context-menu entry crossing the C ABI (the same shape the macOS
264
+ * host takes). */
265
+ struct WindowsContextMenuItem {
266
+ uint32_t item_id;
267
+ const char *label;
268
+ size_t label_len;
269
+ int enabled;
270
+ int separator;
236
271
  };
237
272
 
238
273
  struct WindowsOpenDialogOpts {
@@ -306,6 +341,14 @@ struct Window {
306
341
  * behind the button cluster matches the app's header). */
307
342
  COLORREF hidden_caption_color = 0;
308
343
  bool hidden_caption_color_set = false;
344
+ /* close_policy: 0 = quit (WM_CLOSE destroys; the default), 1 = hide
345
+ * (WM_CLOSE hides — SW_HIDE — and the app keeps running behind its
346
+ * tray icon, the Win32 tray-player shape). Applied right after
347
+ * create via native_sdk_windows_set_window_close_policy. */
348
+ int close_policy = 0;
349
+ /* True while the .hide policy has this window off the glass; the
350
+ * hwnd stays live and the map entry stays owned. */
351
+ bool policy_hidden = false;
309
352
  };
310
353
 
311
354
  /* One rectangle of a canvas view's window-drag mirror (runtime push,
@@ -401,9 +444,21 @@ struct NativeView {
401
444
  int gpu_nonblank = 0;
402
445
  uint32_t gpu_sample_color = 0;
403
446
  int gpu_pointer_down = 0;
447
+ /* TrackMouseEvent(TME_LEAVE) armed for the current hover session:
448
+ * set on the first WM_MOUSEMOVE, cleared by the WM_MOUSELEAVE it
449
+ * buys, re-armed by the next move. */
450
+ int gpu_mouse_tracking = 0;
404
451
  double gpu_pointer_x = 0;
405
452
  double gpu_pointer_y = 0;
406
453
  WCHAR gpu_pending_high_surrogate = 0;
454
+ /* The WM_KEYDOWN just dispatched a registered shortcut, so every
455
+ * already-translated WM_CHAR trailing it belongs to the SAME
456
+ * keystroke and must not also type (AltGr raises Ctrl+Alt, so an
457
+ * AltGr chord that matches a ctrl+alt accelerator would otherwise
458
+ * both fire the accelerator and insert its composed text). Holds
459
+ * across the whole translated burst; the next WM_KEYDOWN or
460
+ * WM_KEYUP disarms it. */
461
+ bool gpu_shortcut_ate_char = false;
407
462
  /* UTF-8 preedit last sent as ime_set_composition; empty = no active
408
463
  * composition. Mirrors gpu_preedit_text in the GTK host and markedText
409
464
  * in the AppKit host. */
@@ -534,6 +589,27 @@ struct AudioState {
534
589
  std::shared_ptr<AudioDownloadCancel> download_cancel;
535
590
  };
536
591
 
592
+ /* The one pending app context menu (menus are modal, so one at a time):
593
+ * copied out of the service call's borrowed request memory, presented on
594
+ * the next loop turn by the window procedure. */
595
+ struct PendingContextMenu {
596
+ bool active = false;
597
+ uint64_t window_id = 0;
598
+ std::string view_label;
599
+ /* Pointer location in LOGICAL points, view-local (the same space the
600
+ * gpu-surface input path reports in). */
601
+ double x = 0;
602
+ double y = 0;
603
+ uint64_t token = 0;
604
+ struct Item {
605
+ uint32_t id = 0;
606
+ std::string label;
607
+ bool enabled = true;
608
+ bool separator = false;
609
+ };
610
+ std::vector<Item> items;
611
+ };
612
+
537
613
  struct Host {
538
614
  HINSTANCE instance = GetModuleHandleW(nullptr);
539
615
  std::string app_name;
@@ -571,6 +647,7 @@ struct Host {
571
647
  bool com_initialized = false;
572
648
  AudioState audio;
573
649
  AudioSpectrumState spectrum;
650
+ PendingContextMenu context_menu;
574
651
  std::shared_ptr<HostLifetime> lifetime = std::make_shared<HostLifetime>();
575
652
  };
576
653
 
@@ -1138,6 +1215,18 @@ static std::string extractHtmlClipboardFragment(const std::string &payload) {
1138
1215
 
1139
1216
  static UINT dpiForWindow(HWND hwnd);
1140
1217
 
1218
+ /* A Win32 top-level window keeps keyboard ownership while focus lives
1219
+ * in any of its native child views. GetFocus() returns the CHILD HWND in
1220
+ * that case (GPU surfaces and hosted controls alike), so direct equality
1221
+ * with window.hwnd falsely reports the owning window blurred exactly
1222
+ * while its child is receiving keyboard input. Walking to GA_ROOT makes
1223
+ * the window-level flag match Win32's active focus tree. */
1224
+ static bool windowOwnsKeyboardFocus(const Window &window) {
1225
+ if (!window.hwnd) return false;
1226
+ HWND focused = GetFocus();
1227
+ return focused && GetAncestor(focused, GA_ROOT) == window.hwnd;
1228
+ }
1229
+
1141
1230
  static void emit(Host *host, const Window &window, EventKind kind) {
1142
1231
  if (!host || !host->callback) return;
1143
1232
  RECT rect = {};
@@ -1156,7 +1245,8 @@ static void emit(Host *host, const Window &window, EventKind kind) {
1156
1245
  event.x = window.x;
1157
1246
  event.y = window.y;
1158
1247
  event.open = window.hwnd != nullptr;
1159
- event.focused = window.hwnd && GetFocus() == window.hwnd;
1248
+ event.focused = windowOwnsKeyboardFocus(window);
1249
+ event.hidden = window.policy_hidden ? 1 : 0;
1160
1250
  event.label = window.label.c_str();
1161
1251
  event.label_len = window.label.size();
1162
1252
  event.title = window.title.c_str();
@@ -1204,6 +1294,24 @@ static std::string shortcutKeyFromWParam(WPARAM wparam) {
1204
1294
  case VK_RIGHT: return "arrowright";
1205
1295
  case VK_UP: return "arrowup";
1206
1296
  case VK_DOWN: return "arrowdown";
1297
+ case VK_DELETE: return "delete";
1298
+ case VK_HOME: return "home";
1299
+ case VK_END: return "end";
1300
+ case VK_PRIOR: return "pageup";
1301
+ case VK_NEXT: return "pagedown";
1302
+ case VK_INSERT: return "insert";
1303
+ case VK_F1: return "f1";
1304
+ case VK_F2: return "f2";
1305
+ case VK_F3: return "f3";
1306
+ case VK_F4: return "f4";
1307
+ case VK_F5: return "f5";
1308
+ case VK_F6: return "f6";
1309
+ case VK_F7: return "f7";
1310
+ case VK_F8: return "f8";
1311
+ case VK_F9: return "f9";
1312
+ case VK_F10: return "f10";
1313
+ case VK_F11: return "f11";
1314
+ case VK_F12: return "f12";
1207
1315
  case VK_OEM_PLUS: return "=";
1208
1316
  case VK_OEM_MINUS: return "-";
1209
1317
  case VK_OEM_COMMA: return ",";
@@ -1278,6 +1386,18 @@ static std::string shortcutKeyLabel(const std::string &key) {
1278
1386
  if (key == "arrowright") return "Right";
1279
1387
  if (key == "arrowup") return "Up";
1280
1388
  if (key == "arrowdown") return "Down";
1389
+ if (key == "delete") return "Del";
1390
+ if (key == "home") return "Home";
1391
+ if (key == "end") return "End";
1392
+ if (key == "pageup") return "PgUp";
1393
+ if (key == "pagedown") return "PgDn";
1394
+ if (key == "insert") return "Ins";
1395
+ if (key.size() >= 2 && key.size() <= 3 && key[0] == 'f' &&
1396
+ std::isdigit(static_cast<unsigned char>(key[1]))) {
1397
+ std::string label = key;
1398
+ label[0] = 'F';
1399
+ return label;
1400
+ }
1281
1401
  return key;
1282
1402
  }
1283
1403
 
@@ -1389,7 +1509,7 @@ static void showTrayMenu(Host *host, HWND hwnd) {
1389
1509
  }
1390
1510
 
1391
1511
  static bool emitShortcutForWindow(Host *host, const Window *window, WPARAM wparam) {
1392
- if (!host || host->shortcuts.empty()) return false;
1512
+ if (!host || (host->shortcuts.empty() && host->menus.empty())) return false;
1393
1513
  if (!window) return false;
1394
1514
  std::string key = shortcutKeyFromWParam(wparam);
1395
1515
  if (key.empty()) return false;
@@ -1412,6 +1532,26 @@ static bool emitShortcutForWindow(Host *host, const Window *window, WPARAM wpara
1412
1532
  host->callback(host->callback_context, &event);
1413
1533
  return true;
1414
1534
  }
1535
+ /* Menu accelerators dispatch from the same keydown path: a menu
1536
+ * item's key+modifiers is a keyboard binding whose event is the
1537
+ * item's menu command, exactly as if the item were clicked. The
1538
+ * other platforms get this from their menu systems (AppKit key
1539
+ * equivalents, GTK accels); here the message loop is that system. */
1540
+ for (const Menu &menu : host->menus) {
1541
+ for (const MenuItem &item : menu.items) {
1542
+ if (item.separator || !item.enabled || item.key.empty()) continue;
1543
+ if (item.key != key) continue;
1544
+ if (!shortcutModifiersMatch(item.modifiers, allow_implicit_shift)) continue;
1545
+ if (!host->callback) return true;
1546
+ WindowsEvent event = {};
1547
+ event.kind = kMenuCommand;
1548
+ event.window_id = window->id;
1549
+ event.command_name = item.command.c_str();
1550
+ event.command_name_len = item.command.size();
1551
+ host->callback(host->callback_context, &event);
1552
+ return true;
1553
+ }
1554
+ }
1415
1555
  }
1416
1556
  return false;
1417
1557
  }
@@ -1808,11 +1948,15 @@ constexpr uint64_t kGpuFrameIntervalNs = 16666667ull;
1808
1948
  * riding the frame channel (on_frame interpolation, armed tweens) and
1809
1949
  * snap it on restore; the heartbeat keeps those models gently current
1810
1950
  * while event-driven truth (audio position, input) flows at its own
1811
- * cadence. Minimize (IsIconic on the root window) is the one occlusion
1812
- * signal Win32 reports reliably for this GDI-presenting host; a window
1813
- * fully covered by other windows has no dependable signal without a
1814
- * DXGI presentation path, so covered-but-not-minimized windows keep
1815
- * full cadence deliberately rather than guess. */
1951
+ * cadence. Two occlusion facts key the throttle: minimize (IsIconic on
1952
+ * the root window — the one signal Win32 reports reliably for this
1953
+ * GDI-presenting host) and the close_policy .hide hide (host-owned
1954
+ * bookkeeping: a policy-hidden window is SW_HIDE'd off the glass, and
1955
+ * the menu-bar app shape keeps it that way for days — full-rate frame
1956
+ * completions there are pure background CPU burn). A window fully
1957
+ * covered by OTHER windows has no dependable signal without a DXGI
1958
+ * presentation path, so covered-but-not-minimized windows keep full
1959
+ * cadence deliberately rather than guess. */
1816
1960
  constexpr uint64_t kGpuOccludedHeartbeatNs = 1000000000ull;
1817
1961
  /* Placeholder pump timer (repeating, retired by the first present). */
1818
1962
  constexpr UINT_PTR kGpuFrameTimerId = 1;
@@ -1846,6 +1990,63 @@ static NativeView *gpuSurfaceViewForHwnd(Host *host, HWND hwnd) {
1846
1990
  return nullptr;
1847
1991
  }
1848
1992
 
1993
+ /* Present the pending app context menu — the tray menu's popup
1994
+ * discipline (SetForegroundWindow, TPM_RETURNCMD | TPM_NONOTIFY, the
1995
+ * WM_NULL post) applied to the runtime's declared items. Runs from the
1996
+ * kShowContextMenuMessage case in the window procedure, so it is on the
1997
+ * message-loop thread but on a FRESH loop turn, never nested inside the
1998
+ * input dispatch that requested it. TrackPopupMenu blocks in its own
1999
+ * modal message loop until the user picks or dismisses (the same shape
2000
+ * as the macOS host's popUpMenuPositioningItem nested tracking loop),
2001
+ * and TPM_RETURNCMD hands the selection back inline — the
2002
+ * kContextMenuAction event is emitted right after it returns, selection
2003
+ * or dismissal (menu_item_id 0) alike, exactly the payload the macOS
2004
+ * host emits so replay is shape-identical across platforms. */
2005
+ static void showAppContextMenu(Host *host, HWND hwnd) {
2006
+ if (!host || !host->context_menu.active) return;
2007
+ PendingContextMenu request = std::move(host->context_menu);
2008
+ host->context_menu = PendingContextMenu{};
2009
+ HMENU menu = CreatePopupMenu();
2010
+ if (!menu) return;
2011
+ for (const PendingContextMenu::Item &item : request.items) {
2012
+ if (item.separator) {
2013
+ AppendMenuW(menu, MF_SEPARATOR, 0, nullptr);
2014
+ continue;
2015
+ }
2016
+ UINT flags = MF_STRING;
2017
+ if (!item.enabled) flags |= MF_GRAYED;
2018
+ std::wstring label = widen(item.label);
2019
+ AppendMenuW(menu, flags, item.id, label.c_str());
2020
+ }
2021
+ /* The request's point is LOGICAL view-local (the exact coordinates
2022
+ * the gpu-surface input path reported the click in, which divides
2023
+ * physical client pixels by gpuSurfaceScale on the way out): invert
2024
+ * that scale against the presenting view's HWND — the gpu-surface
2025
+ * child when the label resolves, the top-level client area otherwise
2026
+ * — then map to screen for TrackPopupMenu. */
2027
+ HWND target = hwnd;
2028
+ if (!request.view_label.empty()) {
2029
+ auto view = host->native_views.find(nativeViewKey(request.window_id, request.view_label));
2030
+ if (view != host->native_views.end() && view->second.hwnd) target = view->second.hwnd;
2031
+ }
2032
+ const double scale = gpuSurfaceScale(target);
2033
+ POINT point = { (LONG)lround(request.x * scale), (LONG)lround(request.y * scale) };
2034
+ ClientToScreen(target, &point);
2035
+ SetForegroundWindow(hwnd);
2036
+ UINT command_id = TrackPopupMenu(menu, TPM_RETURNCMD | TPM_NONOTIFY | TPM_RIGHTBUTTON, point.x, point.y, 0, hwnd, nullptr);
2037
+ DestroyMenu(menu);
2038
+ WindowsEvent event = {};
2039
+ event.kind = kContextMenuAction;
2040
+ event.window_id = request.window_id;
2041
+ event.view_label = request.view_label.c_str();
2042
+ event.view_label_len = request.view_label.size();
2043
+ event.timestamp_ns = gpuTimestampNs();
2044
+ event.widget_id = request.token;
2045
+ event.menu_item_id = command_id;
2046
+ if (host->callback) host->callback(host->callback_context, &event);
2047
+ PostMessageW(hwnd, WM_NULL, 0, 0);
2048
+ }
2049
+
1849
2050
  /* ------------------------------------------------------------------------
1850
2051
  * Hidden-titlebar window chrome (the Win32 custom-frame pattern).
1851
2052
  *
@@ -2389,13 +2590,19 @@ static void gpuSurfaceAdvancePacingClock(NativeView &view) {
2389
2590
  }
2390
2591
  }
2391
2592
 
2392
- /* Frame completions run on the minimized heartbeat when the surface has
2393
- * presented at least once and its top-level window is iconic — the same
2394
- * first-present exemption the macOS occluded pacing keeps, so surface
2395
- * establishment (and the nonblank verdict automation reads) is never
2396
- * throttled. */
2397
- static bool gpuSurfaceOccludedPacingActive(const NativeView &view) {
2593
+ /* Frame completions run on the occluded heartbeat when the surface has
2594
+ * presented at least once and its window is off the glass — iconic, or
2595
+ * alive-but-hidden under close_policy .hide (see kGpuOccludedHeartbeatNs:
2596
+ * both facts are reliable, and a policy-hidden menu-bar app would
2597
+ * otherwise spin its frame loop full-rate for days). First-present
2598
+ * exemption as on macOS, so surface establishment (and the nonblank
2599
+ * verdict automation reads) is never throttled. */
2600
+ static bool gpuSurfaceOccludedPacingActive(Host *host, const NativeView &view) {
2398
2601
  if (!view.gpu_presented || !view.hwnd) return false;
2602
+ if (host) {
2603
+ auto owner = host->windows.find(view.window_id);
2604
+ if (owner != host->windows.end() && owner->second.policy_hidden) return true;
2605
+ }
2399
2606
  HWND root = GetAncestor(view.hwnd, GA_ROOT);
2400
2607
  return root != nullptr && IsIconic(root);
2401
2608
  }
@@ -2429,7 +2636,7 @@ static void gpuSurfaceEmitFrame(Host *host, NativeView &view, HWND hwnd) {
2429
2636
  /* Heartbeat-paced completions are not latency endpoints: their
2430
2637
  * timestamp measures the deliberate minimized cadence, not a paint
2431
2638
  * — the runtime skips input-latency stamping for them. */
2432
- event.occluded = gpuSurfaceOccludedPacingActive(view) ? 1 : 0;
2639
+ event.occluded = gpuSurfaceOccludedPacingActive(host, view) ? 1 : 0;
2433
2640
  emitGpuSurfaceEvent(host, view, event);
2434
2641
  }
2435
2642
 
@@ -2440,16 +2647,17 @@ static void gpuSurfaceEmitFrame(Host *host, NativeView &view, HWND hwnd) {
2440
2647
  * re-enter the engine — and the pacing clock's grid stamping keeps the
2441
2648
  * message hop out of the period. SetTimer clamps short delays up to its
2442
2649
  * ~10 ms floor; the clock absorbs that as jitter, not drift. */
2443
- static void gpuSurfaceScheduleFrameEmission(NativeView &view) {
2650
+ static void gpuSurfaceScheduleFrameEmission(Host *host, NativeView &view) {
2444
2651
  if (!view.hwnd || view.gpu_emission_scheduled) return;
2445
2652
  const uint64_t now = gpuTimestampNs();
2446
- /* Minimized surfaces pace on the heartbeat, not the frame grid —
2447
- * see kGpuOccludedHeartbeatNs. Exempt: an input's responding frame
2448
- * (external truth on its own cadence; it cannot sustain a spin).
2449
- * Restore re-arms the pending timer at the grid delay (the
2450
- * top-level WM_SIZE handler), so the long delay never gates the
2451
- * return to full cadence. */
2452
- const uint64_t pace_ns = (!view.gpu_prompt_frame_pending && gpuSurfaceOccludedPacingActive(view)) ? kGpuOccludedHeartbeatNs : kGpuFrameIntervalNs;
2653
+ /* Occluded surfaces (minimized or policy-hidden) pace on the
2654
+ * heartbeat, not the frame grid — see kGpuOccludedHeartbeatNs.
2655
+ * Exempt: an input's responding frame (external truth on its own
2656
+ * cadence; it cannot sustain a spin). Reveal re-arms the pending
2657
+ * timer at the grid delay (restore through the top-level WM_SIZE
2658
+ * handler, re-show through the show verb), so the long delay never
2659
+ * gates the return to full cadence. */
2660
+ const uint64_t pace_ns = (!view.gpu_prompt_frame_pending && gpuSurfaceOccludedPacingActive(host, view)) ? kGpuOccludedHeartbeatNs : kGpuFrameIntervalNs;
2453
2661
  uint64_t delay_ns = 0;
2454
2662
  if (view.gpu_last_emit_ns > 0 && now < view.gpu_last_emit_ns + pace_ns) {
2455
2663
  delay_ns = view.gpu_last_emit_ns + pace_ns - now;
@@ -2506,6 +2714,13 @@ static std::string gpuSurfaceKeyName(WPARAM wparam) {
2506
2714
  }
2507
2715
 
2508
2716
  static void gpuSurfaceCharInput(Host *host, NativeView &view, WPARAM wparam) {
2717
+ /* A keystroke a registered shortcut consumed never ALSO types: the
2718
+ * message loop translated its WM_CHAR(s) before the accelerator
2719
+ * could refuse them. The latch holds for the WHOLE translated burst
2720
+ * — one keystroke can post several UTF-16 units (ligature layouts,
2721
+ * surrogate pairs) — and is bounded by the message sequence, not a
2722
+ * count: the next WM_KEYDOWN or WM_KEYUP disarms it. */
2723
+ if (view.gpu_shortcut_ate_char) return;
2509
2724
  const WCHAR unit = (WCHAR)wparam;
2510
2725
  std::wstring wide;
2511
2726
  if (unit >= 0xD800 && unit <= 0xDBFF) {
@@ -2523,8 +2738,15 @@ static void gpuSurfaceCharInput(Host *host, NativeView &view, WPARAM wparam) {
2523
2738
  wide.push_back(unit);
2524
2739
  }
2525
2740
  /* Control/alt chords produce control characters or menu accelerators,
2526
- * not text; mirror the GTK path, which skips text for modified keys. */
2527
- if (keyDown(VK_CONTROL) || keyDown(VK_MENU) || keyDown(VK_LWIN) || keyDown(VK_RWIN)) return;
2741
+ * not text; mirror the GTK path, which skips text for modified keys.
2742
+ * EXCEPT AltGr: Windows raises Ctrl+Alt together for it, and an
2743
+ * AltGr-composed printable (AltGr+Q -> "@" on German layouts) IS
2744
+ * committed text — the one chord whose WM_CHAR must flow, or those
2745
+ * layouts lose the character entirely (an AltGr chord a shortcut
2746
+ * consumed was already discarded above). Win alone still gates. */
2747
+ const bool altgr = keyDown(VK_CONTROL) && keyDown(VK_MENU);
2748
+ if (!altgr && (keyDown(VK_CONTROL) || keyDown(VK_MENU))) return;
2749
+ if (keyDown(VK_LWIN) || keyDown(VK_RWIN)) return;
2528
2750
  const std::string text = narrow(wide);
2529
2751
  if (text.empty()) return;
2530
2752
  emitGpuSurfaceInput(host, view, kGpuInputTextInput, view.gpu_pointer_x, view.gpu_pointer_y, 0, 0, 0, "", text.c_str(), gpuModifierFlags());
@@ -2545,7 +2767,7 @@ static LRESULT CALLBACK gpuSurfaceProc(HWND hwnd, UINT message, WPARAM wparam, L
2545
2767
  KillTimer(hwnd, kGpuFrameTimerId);
2546
2768
  return 0;
2547
2769
  }
2548
- gpuSurfaceScheduleFrameEmission(*view);
2770
+ gpuSurfaceScheduleFrameEmission(host, *view);
2549
2771
  return 0;
2550
2772
  }
2551
2773
  if (wparam == kGpuEmitTimerId) {
@@ -2634,6 +2856,18 @@ static LRESULT CALLBACK gpuSurfaceProc(HWND hwnd, UINT message, WPARAM wparam, L
2634
2856
  return 0;
2635
2857
  }
2636
2858
  case WM_MOUSEMOVE: {
2859
+ /* Win32 only reports the pointer LEAVING the client area on
2860
+ * request: arm TME_LEAVE once per hover session so the
2861
+ * WM_MOUSELEAVE below can retire hover state (washes, hover
2862
+ * Msgs, tooltip intent) the way the AppKit host's
2863
+ * mouseExited does. */
2864
+ if (!view->gpu_mouse_tracking) {
2865
+ TRACKMOUSEEVENT track = {};
2866
+ track.cbSize = sizeof(track);
2867
+ track.dwFlags = TME_LEAVE;
2868
+ track.hwndTrack = hwnd;
2869
+ if (TrackMouseEvent(&track)) view->gpu_mouse_tracking = 1;
2870
+ }
2637
2871
  const double x = (double)(short)LOWORD(lparam) / scale;
2638
2872
  const double y = (double)(short)HIWORD(lparam) / scale;
2639
2873
  view->gpu_pointer_x = x;
@@ -2642,6 +2876,46 @@ static LRESULT CALLBACK gpuSurfaceProc(HWND hwnd, UINT message, WPARAM wparam, L
2642
2876
  emitGpuSurfaceInput(host, *view, kind, x, y, 0, 0, 0, "", "", gpuModifierFlags());
2643
2877
  return 0;
2644
2878
  }
2879
+ case WM_MOUSELEAVE: {
2880
+ view->gpu_mouse_tracking = 0;
2881
+ /* The pointer left the client area without a press in
2882
+ * flight: the window-leave edge, reported as the same
2883
+ * pointer cancel a capture loss emits. A captured drag
2884
+ * keeps receiving moves outside the window and settles
2885
+ * through its own up/capture-change instead. One
2886
+ * exception: in-canvas window-drag regions answer
2887
+ * WM_NCHITTEST with HTTRANSPARENT (the parent drags), so
2888
+ * the OS reports a "leave" the moment the cursor enters
2889
+ * one while it still sits over this canvas. That hand-off
2890
+ * is recognized by BOTH tests below - the cursor is still
2891
+ * geometrically inside our rectangle AND the window now
2892
+ * owning the point is one of our own ancestors (hit-test
2893
+ * transparency forwards to the parent chain). A cursor
2894
+ * inside our rectangle but owned by a SIBLING child (an
2895
+ * overlapping WebView pane) is a genuine departure and
2896
+ * must cancel, or hover strands until a later move. */
2897
+ if (!view->gpu_pointer_down) {
2898
+ POINT screen = {};
2899
+ bool suppressed = false;
2900
+ if (GetCursorPos(&screen)) {
2901
+ POINT client = screen;
2902
+ RECT rect = {};
2903
+ if (ScreenToClient(hwnd, &client) && GetClientRect(hwnd, &rect) && PtInRect(&rect, client)) {
2904
+ const HWND owner = WindowFromPoint(screen);
2905
+ for (HWND walk = GetParent(hwnd); walk; walk = GetParent(walk)) {
2906
+ if (walk == owner) {
2907
+ suppressed = true;
2908
+ break;
2909
+ }
2910
+ }
2911
+ }
2912
+ }
2913
+ if (!suppressed) {
2914
+ emitGpuSurfaceInput(host, *view, kGpuInputPointerCancel, view->gpu_pointer_x, view->gpu_pointer_y, 0, 0, 0, "", "", gpuModifierFlags());
2915
+ }
2916
+ }
2917
+ return 0;
2918
+ }
2645
2919
  case WM_CAPTURECHANGED:
2646
2920
  if (view->gpu_pointer_down) {
2647
2921
  view->gpu_pointer_down = 0;
@@ -2668,7 +2942,18 @@ static LRESULT CALLBACK gpuSurfaceProc(HWND hwnd, UINT message, WPARAM wparam, L
2668
2942
  }
2669
2943
  case WM_KEYDOWN:
2670
2944
  case WM_SYSKEYDOWN: {
2671
- if (emitShortcutForHwnd(host, GetAncestor(hwnd, GA_ROOT), wparam)) return 0;
2945
+ /* A fresh keystroke re-disarms the one-shot: a shortcut that
2946
+ * translated to no WM_CHAR (F-keys) must not leave it armed
2947
+ * to eat a later ordinary character. */
2948
+ view->gpu_shortcut_ate_char = false;
2949
+ if (emitShortcutForHwnd(host, GetAncestor(hwnd, GA_ROOT), wparam)) {
2950
+ /* The keystroke was consumed as a shortcut; its
2951
+ * already-translated WM_CHAR (posted by the message
2952
+ * loop's TranslateMessage before this dispatch) must
2953
+ * not ALSO type — one keystroke, one action. */
2954
+ view->gpu_shortcut_ate_char = true;
2955
+ return 0;
2956
+ }
2672
2957
  const std::string key = gpuSurfaceKeyName(wparam);
2673
2958
  if (!key.empty()) {
2674
2959
  emitGpuSurfaceInput(host, *view, kGpuInputKeyDown, view->gpu_pointer_x, view->gpu_pointer_y, 0, 0, 0, key.c_str(), "", gpuModifierFlags());
@@ -2677,6 +2962,9 @@ static LRESULT CALLBACK gpuSurfaceProc(HWND hwnd, UINT message, WPARAM wparam, L
2677
2962
  }
2678
2963
  case WM_KEYUP:
2679
2964
  case WM_SYSKEYUP: {
2965
+ /* The shortcut keystroke's translated burst ended with its
2966
+ * release: disarm the char latch (see gpuSurfaceCharInput). */
2967
+ view->gpu_shortcut_ate_char = false;
2680
2968
  const std::string key = gpuSurfaceKeyName(wparam);
2681
2969
  if (!key.empty()) {
2682
2970
  emitGpuSurfaceInput(host, *view, kGpuInputKeyUp, view->gpu_pointer_x, view->gpu_pointer_y, 0, 0, 0, key.c_str(), "", gpuModifierFlags());
@@ -3555,16 +3843,19 @@ static void audioSpectrumStartCapture(Host *host) {
3555
3843
  }
3556
3844
 
3557
3845
  /* Whether any of the host's top-level windows still reaches the glass.
3558
- * Minimize-keyed on purpose: IsIconic is the one occlusion fact this
3559
- * host trusts (the same decision the minimized frame heartbeat makes —
3560
- * the covered-but-not-minimized case has no reliable cheap signal on
3561
- * the DXGI presentation path), so covered windows keep full spectrum
3562
- * cadence and only an all-minimized app goes quiet. Checked across the
3563
- * whole window table because a spectrum consumer may draw its bands in
3564
- * any of the app's windows. */
3846
+ * Keyed on the two occlusion facts this host trusts (the same decision
3847
+ * the occluded frame heartbeat makes): minimize (IsIconic) and the
3848
+ * close_policy .hide hide (policy_hidden — a menu-bar app's window off
3849
+ * the glass behind its tray icon must not keep 25 Hz spectrum
3850
+ * emissions flowing for a display nobody can see). The
3851
+ * covered-but-not-minimized case has no reliable cheap signal without
3852
+ * a DXGI presentation path, so covered windows keep full spectrum
3853
+ * cadence and only an app with every window minimized or policy-hidden
3854
+ * goes quiet. Checked across the whole window table because a spectrum
3855
+ * consumer may draw its bands in any of the app's windows. */
3565
3856
  static bool audioAnyWindowReachesGlass(Host *host) {
3566
3857
  for (auto &entry : host->windows) {
3567
- if (entry.second.hwnd && !IsIconic(entry.second.hwnd)) return true;
3858
+ if (entry.second.hwnd && !IsIconic(entry.second.hwnd) && !entry.second.policy_hidden) return true;
3568
3859
  }
3569
3860
  return false;
3570
3861
  }
@@ -3575,12 +3866,13 @@ static bool audioAnyWindowReachesGlass(Host *host) {
3575
3866
  * transports emit nothing — the bars freeze honestly — while silence on
3576
3867
  * a rolling transport still emits its row of zeros. The occluded-
3577
3868
  * emission rule gates delivery too: SPECTRUM bands describe a display,
3578
- * so while every window is minimized no report is emitted — no event
3579
- * wakes the runtime's update loop for glass nobody can see, and the
3580
- * journal records the stretch as honest silence. The capture thread
3581
- * keeps its ring fresh (it must drain the loopback client regardless,
3582
- * and its FFT runs off the loop thread), so the first beat after a
3583
- * restore delivers current bands — honest within one report. */
3869
+ * so while every window is minimized or policy-hidden no report is
3870
+ * emitted — no event wakes the runtime's update loop for glass nobody
3871
+ * can see, and the journal records the stretch as honest silence. The
3872
+ * capture thread keeps its ring fresh (it must drain the loopback
3873
+ * client regardless, and its FFT runs off the loop thread), so the
3874
+ * first beat after a restore or re-show delivers current bands —
3875
+ * honest within one report. */
3584
3876
  static void audioHandleSpectrumMessage(Host *host, WPARAM generation) {
3585
3877
  AudioState &audio = host->audio;
3586
3878
  AudioSpectrumState &spectrum = host->spectrum;
@@ -3977,6 +4269,7 @@ static const GUID kNativeSdkIID_EnvironmentCompletedHandler = {0x4e8a3389, 0xc9d
3977
4269
  static const GUID kNativeSdkIID_ControllerCompletedHandler = {0x6c4819f3, 0xc9b7, 0x4260, {0x81, 0x27, 0xc9, 0xf5, 0xbd, 0xe7, 0xf6, 0x8c}};
3978
4270
  static const GUID kNativeSdkIID_WebMessageReceivedHandler = {0x57213f19, 0x00e6, 0x49fa, {0x8e, 0x07, 0x89, 0x8e, 0xa0, 0x1e, 0xcb, 0xd2}};
3979
4271
  static const GUID kNativeSdkIID_AcceleratorKeyPressedHandler = {0xb29c7e28, 0xfa79, 0x41a8, {0x8e, 0x44, 0x65, 0x81, 0x1c, 0x76, 0xdc, 0xb2}};
4272
+ static const GUID kNativeSdkIID_FocusChangedHandler = {0x05ea24bd, 0x6452, 0x4926, {0x90, 0x14, 0x4b, 0x82, 0xb4, 0x98, 0x13, 0x5d}};
3980
4273
  static const GUID kNativeSdkIID_WebResourceRequestedHandler = {0xab00b74c, 0x15f1, 0x4646, {0x80, 0xe8, 0xe7, 0x63, 0x41, 0xd2, 0x5d, 0x71}};
3981
4274
  static const GUID kNativeSdkIID_NavigationStartingHandler = {0x9adbe429, 0xf36d, 0x432b, {0x9d, 0xdc, 0xf8, 0x88, 0x1f, 0xbd, 0x76, 0xe3}};
3982
4275
 
@@ -3993,6 +4286,9 @@ template <> struct WebView2HandlerIid<ICoreWebView2WebMessageReceivedEventHandle
3993
4286
  template <> struct WebView2HandlerIid<ICoreWebView2AcceleratorKeyPressedEventHandler> {
3994
4287
  static const GUID &value() { return kNativeSdkIID_AcceleratorKeyPressedHandler; }
3995
4288
  };
4289
+ template <> struct WebView2HandlerIid<ICoreWebView2FocusChangedEventHandler> {
4290
+ static const GUID &value() { return kNativeSdkIID_FocusChangedHandler; }
4291
+ };
3996
4292
  template <> struct WebView2HandlerIid<ICoreWebView2WebResourceRequestedEventHandler> {
3997
4293
  static const GUID &value() { return kNativeSdkIID_WebResourceRequestedHandler; }
3998
4294
  };
@@ -4331,6 +4627,23 @@ static bool createChildWebView(Host *host, const std::string &key) {
4331
4627
  controller->put_Bounds(bounds);
4332
4628
  controller->put_ZoomFactor(found->second.zoom);
4333
4629
  controller->put_IsVisible(TRUE);
4630
+ EventRegistrationToken focus_token = {};
4631
+ controller->add_GotFocus(Callback<ICoreWebView2FocusChangedEventHandler>(
4632
+ [host, key, lifetime](ICoreWebView2Controller *, IUnknown *) -> HRESULT {
4633
+ auto token = lifetime.lock();
4634
+ if (!token) return S_OK;
4635
+ std::lock_guard<std::recursive_mutex> guard(token->mutex);
4636
+ if (!token->alive || !host->callback) return S_OK;
4637
+ auto focused = host->webviews.find(key);
4638
+ if (focused == host->webviews.end()) return S_OK;
4639
+ WindowsEvent event = {};
4640
+ event.kind = kViewFocused;
4641
+ event.window_id = focused->second.window_id;
4642
+ event.view_label = focused->second.label.c_str();
4643
+ event.view_label_len = focused->second.label.size();
4644
+ host->callback(host->callback_context, &event);
4645
+ return S_OK;
4646
+ }).Get(), &focus_token);
4334
4647
  if (found->second.webview) {
4335
4648
  if (found->second.bridge_enabled) {
4336
4649
  found->second.webview->AddScriptToExecuteOnDocumentCreated(nativeSdkBridgeScript(), nullptr);
@@ -4697,6 +5010,9 @@ static LRESULT CALLBACK windowProc(HWND hwnd, UINT message, WPARAM wparam, LPARA
4697
5010
  case kAudioSpectrumMessage:
4698
5011
  if (host) audioHandleSpectrumMessage(host, wparam);
4699
5012
  return 0;
5013
+ case kShowContextMenuMessage:
5014
+ if (host) showAppContextMenu(host, hwnd);
5015
+ return 0;
4700
5016
  case kNotificationCallbackMessage:
4701
5017
  if (host && host->tray_active) {
4702
5018
  UINT tray_event = LOWORD(lparam);
@@ -4783,13 +5099,25 @@ static LRESULT CALLBACK windowProc(HWND hwnd, UINT message, WPARAM wparam, LPARA
4783
5099
  if (surface.kind != kViewGpuSurface || !surface.hwnd || !surface.gpu_emission_scheduled) continue;
4784
5100
  if (GetAncestor(surface.hwnd, GA_ROOT) != hwnd) continue;
4785
5101
  surface.gpu_emission_scheduled = false;
4786
- gpuSurfaceScheduleFrameEmission(surface);
5102
+ gpuSurfaceScheduleFrameEmission(host, surface);
4787
5103
  }
4788
5104
  }
4789
5105
  }
4790
5106
  return 0;
4791
5107
  case WM_SETFOCUS:
4792
5108
  case WM_KILLFOCUS:
5109
+ if (host) {
5110
+ /* Native child views own Win32 focus directly. Project
5111
+ * their focus edges onto the owning top-level window so
5112
+ * runtime key-window state follows child-to-child and
5113
+ * cross-window focus moves, not only the rare edges
5114
+ * delivered to the top-level HWND itself. */
5115
+ HWND root = GetAncestor(hwnd, GA_ROOT);
5116
+ for (auto &entry : host->windows) {
5117
+ if (entry.second.hwnd == root) emit(host, entry.second, kWindowFrame);
5118
+ }
5119
+ }
5120
+ return 0;
4793
5121
  case WM_MOVE:
4794
5122
  if (host) {
4795
5123
  for (auto &entry : host->windows) {
@@ -4896,6 +5224,38 @@ static LRESULT CALLBACK windowProc(HWND hwnd, UINT message, WPARAM wparam, LPARA
4896
5224
  if (host) emitAppearanceIfChanged(host, false);
4897
5225
  break;
4898
5226
  case WM_CLOSE:
5227
+ /* close_policy .hide: the user's close (caption X, Alt+F4)
5228
+ * hides the window instead of destroying it — the hwnd and
5229
+ * every view stay live, the app keeps running behind its
5230
+ * tray icon, and the frame event reports the hidden state.
5231
+ * Runtime-initiated closes call DestroyWindow directly
5232
+ * (native_sdk_windows_close_window) and bypass this hook. */
5233
+ if (host) {
5234
+ for (auto &entry : host->windows) {
5235
+ if (entry.second.hwnd == hwnd && entry.second.close_policy == 1) {
5236
+ /* The hide is honest only while a tray icon is
5237
+ * live: SW_HIDE removes the taskbar entry and
5238
+ * Windows has no dock-reopen path, so without a
5239
+ * tray the hidden window is a running, invisible,
5240
+ * unreachable app. tray_active is set only when
5241
+ * Shell_NotifyIcon actually added the icon, so a
5242
+ * declared tray whose creation FAILED at runtime
5243
+ * lands here too. The trade: consulting the live
5244
+ * state at close time means a close that arrives
5245
+ * before the app installs its tray (or after it
5246
+ * removes it) really closes — a loud, visible
5247
+ * close beats a silently stranded process. */
5248
+ if (!host->tray_active) {
5249
+ fprintf(stderr, "native-sdk: close_policy \"hide\" downgraded to a real close: no live tray icon exists (tray creation failed or no status item was installed), so a hidden window would have no re-show affordance\n");
5250
+ break;
5251
+ }
5252
+ entry.second.policy_hidden = true;
5253
+ ShowWindow(hwnd, SW_HIDE);
5254
+ emit(host, entry.second, kWindowFrame);
5255
+ return 0;
5256
+ }
5257
+ }
5258
+ }
4899
5259
  DestroyWindow(hwnd);
4900
5260
  return 0;
4901
5261
  case WM_DESTROY:
@@ -4905,6 +5265,8 @@ static LRESULT CALLBACK windowProc(HWND hwnd, UINT message, WPARAM wparam, LPARA
4905
5265
  destroyNativeViewsForWindow(host, entry.first);
4906
5266
  destroyChildWebViewsForWindow(host, entry.first);
4907
5267
  entry.second.hwnd = nullptr;
5268
+ /* Destroyed means closed, never hidden. */
5269
+ entry.second.policy_hidden = false;
4908
5270
  emit(host, entry.second, kWindowFrame);
4909
5271
  }
4910
5272
  }
@@ -5594,6 +5956,47 @@ int native_sdk_windows_minimize_window(Host *host, uint64_t window_id) {
5594
5956
  return 1;
5595
5957
  }
5596
5958
 
5959
+ /* The show verb: bring the window back to the glass and foreground it —
5960
+ * the counterpart to a close_policy hide (and the tray-menu "Open"
5961
+ * consequence). Restores a minimized window on the way. */
5962
+ int native_sdk_windows_show_window(Host *host, uint64_t window_id) {
5963
+ if (!host) return 0;
5964
+ auto found = host->windows.find(window_id);
5965
+ if (found == host->windows.end() || !found->second.hwnd) return 0;
5966
+ found->second.policy_hidden = false;
5967
+ ShowWindow(found->second.hwnd, IsIconic(found->second.hwnd) ? SW_RESTORE : SW_SHOW);
5968
+ /* Re-show returns full frame cadence without dropping a beat, the
5969
+ * same supersede the top-level WM_SIZE handler runs on restore:
5970
+ * SW_SHOW on a same-size window dispatches no WM_SIZE, so a
5971
+ * heartbeat-paced emission parked up to a second out on a child
5972
+ * surface's one-shot timer is re-armed here at the frame-grid
5973
+ * delay (policy_hidden just cleared, so the scheduler paces on the
5974
+ * grid again; SetTimer with the same id replaces the pending
5975
+ * timer). */
5976
+ for (auto &view_entry : host->native_views) {
5977
+ NativeView &surface = view_entry.second;
5978
+ if (surface.kind != kViewGpuSurface || !surface.hwnd || !surface.gpu_emission_scheduled) continue;
5979
+ if (surface.window_id != window_id) continue;
5980
+ surface.gpu_emission_scheduled = false;
5981
+ gpuSurfaceScheduleFrameEmission(host, surface);
5982
+ }
5983
+ SetForegroundWindow(found->second.hwnd);
5984
+ SetFocus(found->second.hwnd);
5985
+ emit(host, found->second, kWindowFrame);
5986
+ return 1;
5987
+ }
5988
+
5989
+ /* What the user's close affordance does: 0 = quit (destroy; the
5990
+ * default), 1 = hide (SW_HIDE and keep running). Applied right after
5991
+ * create — close handling is host window state for the window's life. */
5992
+ int native_sdk_windows_set_window_close_policy(Host *host, uint64_t window_id, int close_policy) {
5993
+ if (!host) return 0;
5994
+ auto found = host->windows.find(window_id);
5995
+ if (found == host->windows.end()) return 0;
5996
+ found->second.close_policy = close_policy;
5997
+ return 1;
5998
+ }
5999
+
5597
6000
  int native_sdk_windows_create_view(Host *host, uint64_t window_id, const char *label, size_t label_len, int kind, const char *parent, size_t parent_len, double x, double y, double width, double height, int layer, int visible, int enabled, const char *role, size_t role_len, const char *accessibility_label, size_t accessibility_label_len, const char *text, size_t text_len, const char *command, size_t command_len) {
5598
6001
  if (!host || label_len == 0 || !isSupportedNativeViewKind(kind) || !validNativeViewFrame(x, y, width, height)) return 0;
5599
6002
  auto window = host->windows.find(window_id);
@@ -5740,7 +6143,7 @@ int native_sdk_windows_request_gpu_surface_frame(Host *host, uint64_t window_id,
5740
6143
  * frame-event scheduler: repaint retained content and arm the next
5741
6144
  * grid-paced emission (folding into one already in flight). */
5742
6145
  InvalidateRect(found->second.hwnd, nullptr, FALSE);
5743
- gpuSurfaceScheduleFrameEmission(found->second);
6146
+ gpuSurfaceScheduleFrameEmission(host, found->second);
5744
6147
  return 1;
5745
6148
  }
5746
6149
 
@@ -5758,11 +6161,45 @@ int native_sdk_windows_note_gpu_surface_input(Host *host, uint64_t window_id, co
5758
6161
  view.gpu_prompt_frame_pending = true;
5759
6162
  if (view.gpu_emission_scheduled) {
5760
6163
  view.gpu_emission_scheduled = false;
5761
- gpuSurfaceScheduleFrameEmission(view);
6164
+ gpuSurfaceScheduleFrameEmission(host, view);
5762
6165
  }
5763
6166
  return 1;
5764
6167
  }
5765
6168
 
6169
+ /* Queue the app context menu for presentation. Called on the loop
6170
+ * thread mid event dispatch (the runtime asks from inside its input
6171
+ * handling), so the request is copied out of the caller's borrowed
6172
+ * memory and presentation defers to a fresh loop turn via PostMessageW —
6173
+ * the same two-step the macOS host performs (its dispatch_async before
6174
+ * popUpMenuPositioningItem). The window procedure's
6175
+ * kShowContextMenuMessage case runs showAppContextMenu, whose
6176
+ * TrackPopupMenu blocks in its own modal loop and whose selection (or
6177
+ * dismissal) emits the kContextMenuAction event carrying `token`. */
6178
+ int native_sdk_windows_show_context_menu(Host *host, uint64_t window_id, const char *label, size_t label_len, double x, double y, uint64_t token, const WindowsContextMenuItem *items, size_t count) {
6179
+ if (!host || !items || count == 0) return 0;
6180
+ auto found = host->windows.find(window_id);
6181
+ if (found == host->windows.end() || !found->second.hwnd) return 0;
6182
+ PendingContextMenu pending;
6183
+ pending.active = true;
6184
+ pending.window_id = window_id;
6185
+ pending.view_label = slice(label, label_len);
6186
+ pending.x = x;
6187
+ pending.y = y;
6188
+ pending.token = token;
6189
+ pending.items.reserve(count);
6190
+ for (size_t index = 0; index < count; index++) {
6191
+ PendingContextMenu::Item item;
6192
+ item.id = items[index].item_id;
6193
+ item.label = slice(items[index].label, items[index].label_len);
6194
+ item.enabled = items[index].enabled != 0;
6195
+ item.separator = items[index].separator != 0;
6196
+ pending.items.push_back(std::move(item));
6197
+ }
6198
+ host->context_menu = std::move(pending);
6199
+ PostMessageW(found->second.hwnd, kShowContextMenuMessage, 0, 0);
6200
+ return 1;
6201
+ }
6202
+
5766
6203
  int native_sdk_windows_present_gpu_surface_pixels(Host *host, uint64_t window_id, const char *label, size_t label_len, size_t width, size_t height, double scale, int has_dirty_rect, double dirty_x, double dirty_y, double dirty_width, double dirty_height, const uint8_t *rgba8, size_t rgba8_len) {
5767
6204
  (void)scale;
5768
6205
  (void)has_dirty_rect;
@@ -5826,7 +6263,7 @@ int native_sdk_windows_present_gpu_surface_pixels(Host *host, uint64_t window_id
5826
6263
  const bool first_present = !view.gpu_presented;
5827
6264
  view.gpu_presented = true;
5828
6265
  if (first_present) view.gpu_prompt_frame_pending = true;
5829
- gpuSurfaceScheduleFrameEmission(view);
6266
+ gpuSurfaceScheduleFrameEmission(host, view);
5830
6267
  return 1;
5831
6268
  }
5832
6269