@native-sdk/cli 0.8.3 → 0.9.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 (188) hide show
  1. package/build/app.zig +905 -61
  2. package/build.zig +674 -373
  3. package/build.zig.zon +1 -0
  4. package/native-sdk.d.ts +6 -0
  5. package/package.json +12 -11
  6. package/packages/core/compile-surface/core.ts +455 -3
  7. package/packages/core/package-lock.json +11 -11
  8. package/packages/core/package.json +2 -2
  9. package/packages/core/scripts/compiler_typecheck.mjs +116 -15
  10. package/packages/core/scripts/gen_service_surface.mjs +268 -0
  11. package/packages/core/scripts/npm_static_spike.mjs +64 -0
  12. package/packages/core/scripts/run_external_core_compiler.mjs +77 -6
  13. package/packages/core/scripts/run_external_service_compiler.mjs +240 -0
  14. package/packages/core/scripts/stage_external_core.mjs +9 -1
  15. package/packages/core/scripts/stage_external_services.mjs +172 -0
  16. package/packages/core/scripts/surface_manifest_diff.mjs +253 -0
  17. package/packages/core/scripts/vendor_service_packages.mjs +189 -0
  18. package/packages/core/sdk/core.d.ts +214 -2
  19. package/packages/core/sdk/core.ts +715 -42
  20. package/packages/core/sdk/events.d.ts +50 -0
  21. package/packages/core/sdk/events.ts +75 -0
  22. package/packages/core/src/checker.ts +528 -15
  23. package/packages/core/src/cli.ts +143 -3
  24. package/packages/core/src/contract.ts +26 -5
  25. package/packages/core/src/devhost.ts +1849 -18
  26. package/packages/core/src/devhost_journal.mjs +181 -0
  27. package/packages/core/src/devhost_resolver.mjs +17 -1
  28. package/packages/core/src/devhost_service_worker.mjs +90 -0
  29. package/packages/core/src/diagnostics.ts +84 -18
  30. package/packages/core/src/frontend.ts +204 -34
  31. package/packages/core/src/modules.ts +129 -80
  32. package/packages/core/src/service_contract.ts +597 -0
  33. package/packages/core/src/sqlite_cli.ts +93 -0
  34. package/packages/core/src/sqlite_codegen.ts +806 -0
  35. package/packages/core/src/sqlite_runtime_policy.ts +364 -0
  36. package/packages/core/src/typed_ast.ts +36 -8
  37. package/skill-data/core/SKILL.md +4 -2
  38. package/skill-data/core/references/project-anatomy.md +3 -2
  39. package/skill-data/core/references/web-engines-packaging-debugging.md +3 -1
  40. package/skill-data/native-ui/SKILL.md +55 -8
  41. package/skill-data/ts-core/SKILL.md +92 -40
  42. package/skill-data/ts-services/SKILL.md +126 -0
  43. package/skill-data/ts-services/references/service-surface.md +603 -0
  44. package/skill-data/zig/SKILL.md +1 -1
  45. package/skills/native-sdk/SKILL.md +1 -1
  46. package/src/app_runner/no_migrations.zig +3 -0
  47. package/src/app_runner/no_services.zig +20 -0
  48. package/src/app_runner/root.zig +104 -4
  49. package/src/app_runner/ts_core_main.zig +268 -4
  50. package/src/automation/snapshot.zig +23 -5
  51. package/src/embed/app_exports.zig +11 -1
  52. package/src/embed/c_api.zig +48 -2
  53. package/src/embed/conversions.zig +4 -5
  54. package/src/embed/host.zig +115 -1
  55. package/src/embed/root.zig +7 -0
  56. package/src/embed/tests.zig +213 -0
  57. package/src/embed/types.zig +51 -0
  58. package/src/embed/ui_host.zig +121 -5
  59. package/src/platform/android/NativeSdkActivity.java +131 -0
  60. package/src/platform/android/android_host.c +182 -1
  61. package/src/platform/android/native_sdk_app.h +17 -0
  62. package/src/platform/ios/native_sdk_app.h +17 -0
  63. package/src/platform/ios/uikit_host.m +115 -0
  64. package/src/platform/linux/cef_host.cpp +1 -1
  65. package/src/platform/linux/gtk_host.c +89 -17
  66. package/src/platform/linux/gtk_host.h +3 -0
  67. package/src/platform/linux/root.zig +41 -18
  68. package/src/platform/macos/appkit_host.h +26 -3
  69. package/src/platform/macos/appkit_host.m +1051 -129
  70. package/src/platform/macos/capture_info_plist.c +25 -0
  71. package/src/platform/macos/cef_host.mm +270 -36
  72. package/src/platform/macos/root.zig +312 -34
  73. package/src/platform/null_platform.zig +281 -19
  74. package/src/platform/null_platform_tests.zig +74 -0
  75. package/src/platform/root.zig +16 -0
  76. package/src/platform/types.zig +279 -15
  77. package/src/platform/windows/root.zig +243 -21
  78. package/src/platform/windows/webview2_host.cpp +464 -46
  79. package/src/primitives/app_manifest/comptime_scene.zig +2 -0
  80. package/src/primitives/app_manifest/root.zig +4 -0
  81. package/src/primitives/app_manifest/tests.zig +3 -0
  82. package/src/primitives/app_manifest/types.zig +34 -0
  83. package/src/primitives/app_manifest/validation.zig +19 -1
  84. package/src/primitives/canvas/code_tests.zig +9 -9
  85. package/src/primitives/canvas/events.zig +12 -11
  86. package/src/primitives/canvas/frame.zig +44 -9
  87. package/src/primitives/canvas/icons/mic.svg +1 -0
  88. package/src/primitives/canvas/icons.zig +2 -0
  89. package/src/primitives/canvas/root.zig +8 -0
  90. package/src/primitives/canvas/text_span_tests.zig +39 -0
  91. package/src/primitives/canvas/ui.zig +23 -4
  92. package/src/primitives/canvas/ui_markup.zig +15 -0
  93. package/src/primitives/canvas/ui_markup_compiled.zig +9 -0
  94. package/src/primitives/canvas/ui_markup_compiled_tests.zig +1 -1
  95. package/src/primitives/canvas/ui_markup_tests.zig +5 -0
  96. package/src/primitives/canvas/ui_markup_view.zig +9 -0
  97. package/src/primitives/canvas/ui_markup_view_tests.zig +9 -6
  98. package/src/primitives/canvas/ui_schema.zig +19 -10
  99. package/src/primitives/canvas/ui_schema_tests.zig +5 -3
  100. package/src/primitives/canvas/ui_tests.zig +18 -4
  101. package/src/primitives/canvas/widget_invalidation.zig +9 -2
  102. package/src/primitives/canvas/widget_render.zig +296 -114
  103. package/src/primitives/canvas/widget_runtime_tests.zig +133 -0
  104. package/src/primitives/canvas/widget_text_input.zig +10 -10
  105. package/src/primitives/canvas/widget_tree.zig +1 -1
  106. package/src/primitives/canvas/widgets.zig +29 -5
  107. package/src/root.zig +56 -0
  108. package/src/runtime/api.zig +11 -0
  109. package/src/runtime/automation_snapshot.zig +4 -0
  110. package/src/runtime/automation_widget_dispatch.zig +1 -0
  111. package/src/runtime/bridge_payload.zig +2 -0
  112. package/src/runtime/bridge_permission_tests.zig +23 -2
  113. package/src/runtime/bridge_responses.zig +3 -1
  114. package/src/runtime/canvas_frame.zig +31 -13
  115. package/src/runtime/canvas_frame_animation_tests.zig +4 -0
  116. package/src/runtime/canvas_frame_invalidation_tests.zig +35 -10
  117. package/src/runtime/canvas_widget_anchored_tests.zig +83 -0
  118. package/src/runtime/canvas_widget_events.zig +69 -24
  119. package/src/runtime/canvas_widget_runtime.zig +101 -6
  120. package/src/runtime/canvas_widget_scroll_driver_tests.zig +47 -4
  121. package/src/runtime/canvas_widget_scroll_drivers.zig +3 -3
  122. package/src/runtime/canvas_widget_semantics_tests.zig +2 -0
  123. package/src/runtime/canvas_widget_split_tree_tests.zig +228 -0
  124. package/src/runtime/canvas_widget_state.zig +6 -1
  125. package/src/runtime/canvas_widget_text_tests.zig +112 -3
  126. package/src/runtime/clock.zig +13 -1
  127. package/src/runtime/core.zig +133 -1
  128. package/src/runtime/credentials_store.zig +115 -0
  129. package/src/runtime/effects.zig +2568 -75
  130. package/src/runtime/effects_audio_capture_tests.zig +251 -0
  131. package/src/runtime/effects_credentials_tests.zig +332 -0
  132. package/src/runtime/effects_host_tests.zig +208 -1
  133. package/src/runtime/effects_relational_tests.zig +314 -0
  134. package/src/runtime/effects_store_tests.zig +211 -0
  135. package/src/runtime/flow.zig +14 -1
  136. package/src/runtime/gpu_surface_events.zig +6 -1
  137. package/src/runtime/native_command_event_tests.zig +42 -0
  138. package/src/runtime/persist_store.zig +666 -0
  139. package/src/runtime/record_store.zig +788 -0
  140. package/src/runtime/relational_store.zig +854 -0
  141. package/src/runtime/root.zig +52 -0
  142. package/src/runtime/runtime_event_tests.zig +70 -0
  143. package/src/runtime/service_host.zig +711 -0
  144. package/src/runtime/service_pool.zig +1314 -0
  145. package/src/runtime/session_blobs.zig +1 -1
  146. package/src/runtime/session_journal.zig +102 -0
  147. package/src/runtime/session_record.zig +177 -0
  148. package/src/runtime/session_replay.zig +109 -4
  149. package/src/runtime/shell_layout.zig +1 -0
  150. package/src/runtime/shell_layout_tests.zig +120 -0
  151. package/src/runtime/sqlite_engine.zig +474 -0
  152. package/src/runtime/state.zig +6 -0
  153. package/src/runtime/system_services.zig +49 -10
  154. package/src/runtime/tests.zig +5 -0
  155. package/src/runtime/ts_core_host.zig +1189 -118
  156. package/src/runtime/ts_core_host_tests.zig +638 -11
  157. package/src/runtime/ts_ui_app.zig +537 -1
  158. package/src/runtime/ui_app.zig +160 -19
  159. package/src/runtime/ui_app_tests.zig +203 -5
  160. package/src/runtime/validation.zig +22 -0
  161. package/src/runtime/view.zig +11 -0
  162. package/src/runtime/view_widget_scroll.zig +56 -5
  163. package/src/runtime/view_widget_text.zig +24 -5
  164. package/src/runtime/view_widget_tree.zig +1 -1
  165. package/src/runtime/window_storage.zig +1 -0
  166. package/src/runtime/window_view_runtime.zig +2 -3
  167. package/src/runtime/window_views.zig +19 -0
  168. package/src/tooling/android.zig +21 -16
  169. package/src/tooling/db.zig +160 -0
  170. package/src/tooling/ios.zig +7 -1
  171. package/src/tooling/manifest.zig +1248 -2
  172. package/src/tooling/package.zig +953 -6
  173. package/src/tooling/raw_manifest.zig +65 -0
  174. package/src/tooling/root.zig +1 -0
  175. package/src/tooling/templates.zig +216 -4
  176. package/src/tooling/ts_core.zig +283 -17
  177. package/src/tooling/verbs.zig +7 -0
  178. package/third_party/sqlite/README.md +13 -0
  179. package/third_party/sqlite/sqlite3.c +269649 -0
  180. package/third_party/sqlite/sqlite3.h +14349 -0
  181. package/tools/corewire/core_abi.zig +14 -2
  182. package/tools/corewire/emit.zig +98 -29
  183. package/tools/corewire/emit_facade.zig +414 -23
  184. package/tools/corewire/emit_profile.zig +6 -2
  185. package/tools/corewire/emit_service.zig +924 -0
  186. package/tools/corewire/main.zig +122 -0
  187. package/tools/corewire/service_contract.zig +250 -0
  188. package/tools/corewire/sidecar.zig +26 -15
@@ -73,6 +73,10 @@ using Microsoft::WRL::ComPtr;
73
73
  #include <mferror.h>
74
74
  #include <winhttp.h>
75
75
 
76
+ #ifndef CREATE_WAITABLE_TIMER_HIGH_RESOLUTION
77
+ #define CREATE_WAITABLE_TIMER_HIGH_RESOLUTION 0x00000002
78
+ #endif
79
+
76
80
  /* WASAPI process-scoped loopback (the spectrum analysis capture below).
77
81
  * The activation-parameter declarations arrived with the Windows 10 2004
78
82
  * SDK in audioclientactivationparams.h; the mingw-w64 headers zig ships
@@ -134,6 +138,7 @@ enum EventKind {
134
138
  kAudio = 18,
135
139
  kContextMenuAction = 19,
136
140
  kViewFocused = 20,
141
+ kTrayCommand = 21,
137
142
  };
138
143
 
139
144
  constexpr uint32_t kShortcutModifierPrimary = 1u << 0;
@@ -452,14 +457,17 @@ struct NativeView {
452
457
  * producer that wants a frame event — runtime frame requests, pixel
453
458
  * presents (the completion analog), the pre-first-present placeholder
454
459
  * pump — funnels through gpuSurfaceScheduleFrameEmission, which keeps
455
- * at most one emission in flight (a one-shot WM_TIMER) and fires it
456
- * on the frame-interval grid anchored at gpu_last_emit_ns. Producers
457
- * landing while one is queued fold into it: their facts (nonblank,
458
- * sample color, buffer contents) are already view state when the
459
- * emission fires. gpu_presented flips on the first present and
460
- * retires the placeholder pump — from then on frames are
461
- * demand-driven, so an idle surface emits ZERO frame events (the
462
- * idle law the macOS host enforces). */
460
+ * at most one emission in flight. A process-owned high-resolution
461
+ * waitable timer wakes an idle loop; a one-shot WM_TIMER is retained as
462
+ * the compatibility fallback, and the outer message loop also drains due
463
+ * emissions after every dispatched message so sustained input cannot
464
+ * starve the lowest-priority WM_TIMER channel. Every path fires on the
465
+ * frame-interval grid anchored at gpu_last_emit_ns. Producers landing while one is queued
466
+ * fold into it: their facts (nonblank, sample color, buffer contents)
467
+ * are already view state when the emission fires. gpu_presented flips
468
+ * on the first present and retires the placeholder pump — from then on
469
+ * frames are demand-driven, so an idle surface emits ZERO frame events
470
+ * (the idle law the macOS host enforces). */
463
471
  bool gpu_emission_scheduled = false;
464
472
  bool gpu_presented = false;
465
473
  /* One-shot: the next scheduled emission must fire at grid
@@ -543,7 +551,11 @@ struct Menu {
543
551
  struct TrayItem {
544
552
  uint32_t id = 0;
545
553
  std::string label;
554
+ std::string detail;
555
+ std::string key;
556
+ uint32_t modifiers = 0;
546
557
  uint32_t command_id = 0;
558
+ int role = 0;
547
559
  bool separator = false;
548
560
  bool enabled = true;
549
561
  };
@@ -605,6 +617,24 @@ struct AudioSpectrumState {
605
617
  uint64_t generation = 0;
606
618
  };
607
619
 
620
+ using AudioCapturePush = int (*)(void *context, int kind, int source,
621
+ uint32_t sample_rate, uint8_t channels, uint64_t timestamp_ns,
622
+ uint32_t frames, const uint8_t *pcm, size_t pcm_len);
623
+
624
+ struct AudioCaptureShared {
625
+ std::atomic<bool> stop{false};
626
+ int source = 0;
627
+ uint32_t sample_rate = 48000;
628
+ uint8_t channels = 1;
629
+ AudioCapturePush push = nullptr;
630
+ void *context = nullptr;
631
+ };
632
+
633
+ struct AudioCaptureState {
634
+ std::shared_ptr<AudioCaptureShared> shared;
635
+ std::thread worker;
636
+ };
637
+
608
638
  /* The app's single audio player (see the audio section further down for
609
639
  * the backend rationale). All fields are message-loop-thread state; the
610
640
  * lifetime mutex additionally guards `generation` and `source` because
@@ -682,6 +712,9 @@ struct Host {
682
712
  std::vector<Menu> menus;
683
713
  std::map<uint32_t, std::string> menu_commands;
684
714
  std::vector<TrayItem> tray_items;
715
+ std::string tray_activation_command;
716
+ std::string tray_alternate_activation_command;
717
+ std::string tray_open_command;
685
718
  int external_link_action = 0;
686
719
  bool app_active = false;
687
720
  bool notification_icon_added = false;
@@ -696,13 +729,20 @@ struct Host {
696
729
  /* Whether the CoInitializeEx in native_sdk_windows_create succeeded
697
730
  * and native_sdk_windows_destroy owes the balancing CoUninitialize. */
698
731
  bool com_initialized = false;
732
+ /* Earliest retained-canvas frame deadline. The handle is lazy and only
733
+ * armed while a surface has one emission in flight; MsgWait... folds it
734
+ * into the UI-thread message pump without a helper thread or callback. */
735
+ HANDLE gpu_frame_wake_timer = nullptr;
699
736
  AudioState audio;
700
737
  AudioSpectrumState spectrum;
738
+ AudioCaptureState captures[2];
701
739
  PendingContextMenu context_menu;
702
740
  std::shared_ptr<HostLifetime> lifetime = std::make_shared<HostLifetime>();
703
741
  };
704
742
 
705
743
  static std::string webViewKey(uint64_t window_id, const std::string &label);
744
+ static void gpuSurfaceRefreshFrameWakeTimer(Host *host);
745
+ static void gpuSurfaceDestroyFrameWakeTimer(Host *host);
706
746
 
707
747
  static std::string slice(const char *bytes, size_t len) {
708
748
  return bytes && len > 0 ? std::string(bytes, len) : std::string();
@@ -1452,8 +1492,8 @@ static std::string shortcutKeyLabel(const std::string &key) {
1452
1492
  return key;
1453
1493
  }
1454
1494
 
1455
- static std::string menuShortcutSuffix(const MenuItem &item) {
1456
- if (item.key.empty()) return std::string();
1495
+ static std::string shortcutSuffix(const std::string &key, uint32_t modifiers) {
1496
+ if (key.empty()) return std::string();
1457
1497
  std::string suffix = "\t";
1458
1498
  bool has_prefix = false;
1459
1499
  auto append = [&](const char *value) {
@@ -1461,15 +1501,19 @@ static std::string menuShortcutSuffix(const MenuItem &item) {
1461
1501
  suffix += value;
1462
1502
  has_prefix = true;
1463
1503
  };
1464
- if ((item.modifiers & kShortcutModifierPrimary) != 0 || (item.modifiers & kShortcutModifierControl) != 0) append("Ctrl");
1465
- if ((item.modifiers & kShortcutModifierCommand) != 0) append("Win");
1466
- if ((item.modifiers & kShortcutModifierOption) != 0) append("Alt");
1467
- if ((item.modifiers & kShortcutModifierShift) != 0) append("Shift");
1504
+ if ((modifiers & kShortcutModifierPrimary) != 0 || (modifiers & kShortcutModifierControl) != 0) append("Ctrl");
1505
+ if ((modifiers & kShortcutModifierCommand) != 0) append("Win");
1506
+ if ((modifiers & kShortcutModifierOption) != 0) append("Alt");
1507
+ if ((modifiers & kShortcutModifierShift) != 0) append("Shift");
1468
1508
  if (has_prefix) suffix += "+";
1469
- suffix += shortcutKeyLabel(item.key);
1509
+ suffix += shortcutKeyLabel(key);
1470
1510
  return suffix;
1471
1511
  }
1472
1512
 
1513
+ static std::string menuShortcutSuffix(const MenuItem &item) {
1514
+ return shortcutSuffix(item.key, item.modifiers);
1515
+ }
1516
+
1473
1517
  static HMENU buildMenuBar(Host *host) {
1474
1518
  if (!host || host->menus.empty()) return nullptr;
1475
1519
  HMENU menu_bar = CreateMenu();
@@ -1523,9 +1567,9 @@ static bool emitMenuCommandForId(Host *host, HWND hwnd, uint32_t command_id) {
1523
1567
  return true;
1524
1568
  }
1525
1569
 
1526
- static bool emitTrayActionForCommandId(Host *host, uint32_t command_id) {
1570
+ static bool emitTrayActionForCommandId(Host *host, const std::vector<TrayItem> &items, uint32_t command_id) {
1527
1571
  if (!host || !host->callback) return false;
1528
- for (const TrayItem &item : host->tray_items) {
1572
+ for (const TrayItem &item : items) {
1529
1573
  if (item.separator || item.command_id != command_id) continue;
1530
1574
  WindowsEvent event = {};
1531
1575
  event.kind = kTrayAction;
@@ -1536,18 +1580,41 @@ static bool emitTrayActionForCommandId(Host *host, uint32_t command_id) {
1536
1580
  return false;
1537
1581
  }
1538
1582
 
1583
+ static bool emitStatusCommand(Host *host, HWND hwnd, const std::string &command) {
1584
+ if (!host || !host->callback || command.empty()) return false;
1585
+ const Window *window = windowForHwnd(host, hwnd);
1586
+ if (!window) return false;
1587
+ WindowsEvent event = {};
1588
+ event.kind = kTrayCommand;
1589
+ event.window_id = window->id;
1590
+ event.command_name = command.c_str();
1591
+ event.command_name_len = command.size();
1592
+ host->callback(host->callback_context, &event);
1593
+ return true;
1594
+ }
1595
+
1539
1596
  static void showTrayMenu(Host *host, HWND hwnd) {
1540
- if (!host || !host->tray_active || host->tray_items.empty() || !hwnd) return;
1597
+ if (!host || !host->tray_active || !hwnd) return;
1598
+ emitStatusCommand(host, hwnd, host->tray_open_command);
1599
+ // The open hook may synchronously rebuild or remove the tray.
1600
+ if (!host->tray_active || host->tray_items.empty()) return;
1601
+ // TrackPopupMenu owns a nested message loop. Timers and posted wakes can
1602
+ // rebuild host->tray_items while this menu is open, so retain the exact
1603
+ // command-id -> stable item-id mapping represented by the visible rows.
1604
+ const std::vector<TrayItem> displayed_items = host->tray_items;
1541
1605
  HMENU menu = CreatePopupMenu();
1542
1606
  if (!menu) return;
1543
- for (const TrayItem &item : host->tray_items) {
1607
+ for (const TrayItem &item : displayed_items) {
1544
1608
  if (item.separator) {
1545
1609
  AppendMenuW(menu, MF_SEPARATOR, 0, nullptr);
1546
1610
  continue;
1547
1611
  }
1548
1612
  UINT flags = MF_STRING;
1549
1613
  if (!item.enabled) flags |= MF_GRAYED;
1550
- std::wstring label = widen(item.label);
1614
+ std::string display_label = item.label;
1615
+ if (!item.detail.empty()) display_label += " — " + item.detail;
1616
+ display_label += shortcutSuffix(item.key, item.modifiers);
1617
+ std::wstring label = widen(display_label);
1551
1618
  AppendMenuW(menu, flags, item.command_id, label.c_str());
1552
1619
  }
1553
1620
  POINT cursor = {};
@@ -1555,12 +1622,12 @@ static void showTrayMenu(Host *host, HWND hwnd) {
1555
1622
  SetForegroundWindow(hwnd);
1556
1623
  UINT command_id = TrackPopupMenu(menu, TPM_RETURNCMD | TPM_NONOTIFY | TPM_RIGHTBUTTON, cursor.x, cursor.y, 0, hwnd, nullptr);
1557
1624
  DestroyMenu(menu);
1558
- if (command_id != 0) emitTrayActionForCommandId(host, command_id);
1625
+ if (command_id != 0) emitTrayActionForCommandId(host, displayed_items, command_id);
1559
1626
  PostMessageW(hwnd, WM_NULL, 0, 0);
1560
1627
  }
1561
1628
 
1562
1629
  static bool emitShortcutForWindow(Host *host, const Window *window, WPARAM wparam) {
1563
- if (!host || (host->shortcuts.empty() && host->menus.empty())) return false;
1630
+ if (!host || (host->shortcuts.empty() && host->menus.empty() && host->tray_items.empty())) return false;
1564
1631
  if (!window) return false;
1565
1632
  std::string key = shortcutKeyFromWParam(wparam);
1566
1633
  if (key.empty()) return false;
@@ -1603,6 +1670,15 @@ static bool emitShortcutForWindow(Host *host, const Window *window, WPARAM wpara
1603
1670
  return true;
1604
1671
  }
1605
1672
  }
1673
+ // Status-menu key equivalents share the focused-window key path on
1674
+ // Windows. AppKit gets this behavior from NSMenu; Win32 popup menus
1675
+ // need the binding dispatched explicitly.
1676
+ for (const TrayItem &item : host->tray_items) {
1677
+ if (item.separator || !item.enabled || item.key.empty()) continue;
1678
+ if (item.key != key) continue;
1679
+ if (!shortcutModifiersMatch(item.modifiers, allow_implicit_shift)) continue;
1680
+ return emitTrayActionForCommandId(host, host->tray_items, item.command_id);
1681
+ }
1606
1682
  }
1607
1683
  return false;
1608
1684
  }
@@ -1928,6 +2004,7 @@ static void destroyNativeViewAndChildren(Host *host, const std::string &key) {
1928
2004
  for (const std::string &child : children) destroyNativeViewAndChildren(host, child);
1929
2005
  if (found->second.hwnd) DestroyWindow(found->second.hwnd);
1930
2006
  host->native_views.erase(found);
2007
+ gpuSurfaceRefreshFrameWakeTimer(host);
1931
2008
  }
1932
2009
 
1933
2010
  static void destroyNativeViewsForWindow(Host *host, uint64_t window_id) {
@@ -1951,13 +2028,13 @@ static void destroyNativeViewsForWindow(Host *host, uint64_t window_id) {
1951
2028
  * buffer is still valid. Frame events are DEMAND-DRIVEN through one
1952
2029
  * scheduler per surface (the macOS host's design): runtime frame
1953
2030
  * requests and pixel presents each arm a single grid-anchored one-shot
1954
- * WM_TIMER emission, so an armed animation loop sees one
2031
+ * emission, so an armed animation loop sees one
1955
2032
  * gpu_surface_frame per frame interval and an idle surface sees none.
1956
2033
  * Until the first present lands, a placeholder 16 ms WM_TIMER pump arms
1957
2034
  * the same scheduler (the runtime's install choreography rides the
1958
- * first frame events), then removes itself. WM_TIMER granularity
1959
- * (~10-16 ms, coalesced under load) quantizes individual periods; the
1960
- * grid-anchored clock turns that into jitter, never drift.
2035
+ * first frame events), then removes itself. The scheduler's high-resolution
2036
+ * waitable deadline avoids WM_TIMER's ~10-16 ms quantization while the
2037
+ * grid-anchored clock still prevents drift.
1961
2038
  * gpu_surface_resize rides WM_SIZE/DPI changes plus each emission's
1962
2039
  * geometry sync. Mouse, wheel, and
1963
2040
  * key input map onto the same gpu_surface_input kinds the other hosts
@@ -2715,6 +2792,60 @@ static bool gpuSurfaceOccludedPacingActive(Host *host, const NativeView &view) {
2715
2792
  return root != nullptr && IsIconic(root);
2716
2793
  }
2717
2794
 
2795
+ /* SetTimer can round a nominal 16.67 ms frame delay onto the legacy system
2796
+ * timer grid. A high-resolution waitable timer expresses the EARLIEST pending
2797
+ * surface deadline directly and participates
2798
+ * in the UI thread's MsgWaitForMultipleObjectsEx loop. The per-HWND WM_TIMER
2799
+ * remains armed as a fallback for older Windows/builds that reject the high-
2800
+ * resolution flag; it is not the normal cadence source.
2801
+ *
2802
+ * This is one process-owned handle, not one timer per surface. Refreshing
2803
+ * scans the small native-view table and re-arms to the earliest single-flight
2804
+ * deadline. Callback-driven view destruction is safe because no NativeView
2805
+ * pointer crosses the wait. */
2806
+ static void gpuSurfaceRefreshFrameWakeTimer(Host *host) {
2807
+ if (!host) return;
2808
+ const uint64_t now = gpuTimestampNs();
2809
+ uint64_t earliest_ns = UINT64_MAX;
2810
+ for (const auto &entry : host->native_views) {
2811
+ const NativeView &view = entry.second;
2812
+ if (view.kind != kViewGpuSurface || !view.hwnd || !view.gpu_emission_scheduled) continue;
2813
+ const uint64_t pace_ns = (!view.gpu_prompt_frame_pending && gpuSurfaceOccludedPacingActive(host, view)) ? kGpuOccludedHeartbeatNs : kGpuFrameIntervalNs;
2814
+ const uint64_t due_ns = view.gpu_last_emit_ns == 0 ? now : view.gpu_last_emit_ns + pace_ns;
2815
+ earliest_ns = std::min(earliest_ns, due_ns);
2816
+ }
2817
+
2818
+ if (earliest_ns == UINT64_MAX) {
2819
+ if (host->gpu_frame_wake_timer) CancelWaitableTimer(host->gpu_frame_wake_timer);
2820
+ return;
2821
+ }
2822
+ if (!host->gpu_frame_wake_timer) {
2823
+ host->gpu_frame_wake_timer = CreateWaitableTimerExW(
2824
+ nullptr, nullptr, CREATE_WAITABLE_TIMER_HIGH_RESOLUTION,
2825
+ TIMER_MODIFY_STATE | SYNCHRONIZE);
2826
+ if (!host->gpu_frame_wake_timer) {
2827
+ host->gpu_frame_wake_timer = CreateWaitableTimerW(nullptr, FALSE, nullptr);
2828
+ }
2829
+ if (!host->gpu_frame_wake_timer) return;
2830
+ }
2831
+
2832
+ const uint64_t wait_ns = earliest_ns > now ? earliest_ns - now : 1;
2833
+ const uint64_t due_100ns = std::max<uint64_t>(1, (wait_ns + 99) / 100);
2834
+ LARGE_INTEGER due = {};
2835
+ due.QuadPart = -static_cast<LONGLONG>(std::min<uint64_t>(due_100ns, LLONG_MAX));
2836
+ if (!SetWaitableTimer(host->gpu_frame_wake_timer, &due, 0, nullptr, nullptr, FALSE)) {
2837
+ CloseHandle(host->gpu_frame_wake_timer);
2838
+ host->gpu_frame_wake_timer = nullptr;
2839
+ }
2840
+ }
2841
+
2842
+ static void gpuSurfaceDestroyFrameWakeTimer(Host *host) {
2843
+ if (!host || !host->gpu_frame_wake_timer) return;
2844
+ CancelWaitableTimer(host->gpu_frame_wake_timer);
2845
+ CloseHandle(host->gpu_frame_wake_timer);
2846
+ host->gpu_frame_wake_timer = nullptr;
2847
+ }
2848
+
2718
2849
  /* The single frame-event emission: view state (nonblank verdict, sample
2719
2850
  * color, buffer geometry) is the payload, so one event serves frame
2720
2851
  * requests and present completions alike. */
@@ -2769,8 +2900,8 @@ static void gpuSurfaceEmitFrame(Host *host, NativeView &view, HWND hwnd) {
2769
2900
  * is queued fold into it. Always fires through the message loop — a
2770
2901
  * request lands mid engine dispatch and a synchronous emission would
2771
2902
  * re-enter the engine — and the pacing clock's grid stamping keeps the
2772
- * message hop out of the period. SetTimer clamps short delays up to its
2773
- * ~10 ms floor; the clock absorbs that as jitter, not drift. */
2903
+ * message hop out of the period. The waitable timer supplies the precise
2904
+ * wake; SetTimer is only the compatibility fallback. */
2774
2905
  static void gpuSurfaceScheduleFrameEmission(Host *host, NativeView &view) {
2775
2906
  if (!view.hwnd || view.gpu_emission_scheduled) return;
2776
2907
  const uint64_t now = gpuTimestampNs();
@@ -2787,9 +2918,55 @@ static void gpuSurfaceScheduleFrameEmission(Host *host, NativeView &view) {
2787
2918
  delay_ns = view.gpu_last_emit_ns + pace_ns - now;
2788
2919
  }
2789
2920
  const UINT delay_ms = (UINT)((delay_ns + 500000ull) / 1000000ull);
2790
- if (SetTimer(view.hwnd, kGpuEmitTimerId, delay_ms, nullptr)) {
2791
- view.gpu_emission_scheduled = true;
2921
+ view.gpu_emission_scheduled = true;
2922
+ (void)SetTimer(view.hwnd, kGpuEmitTimerId, delay_ms, nullptr);
2923
+ gpuSurfaceRefreshFrameWakeTimer(host);
2924
+ }
2925
+
2926
+ /* WM_TIMER is generated only after higher-priority input/posted messages
2927
+ * have drained. A trackpad or high-rate wheel can therefore keep the
2928
+ * one-shot emit timer pending for hundreds of milliseconds even though the
2929
+ * frame deadline passed. The outer GetMessage loop calls this after EVERY
2930
+ * dispatched message: while the queue is busy, that dispatch becomes the
2931
+ * wake source; while it is idle, the existing timer wakes it. Emission stays
2932
+ * outside the platform callback that requested the frame, so the runtime is
2933
+ * never re-entered, and the existing single-flight/grid clock still owns
2934
+ * coalescing and pacing.
2935
+ *
2936
+ * Capture stable map keys before emitting. A frame callback may close its
2937
+ * own view (or another due view), so each key is re-resolved immediately
2938
+ * before use and no iterator/reference survives an engine callback. */
2939
+ static void gpuSurfaceDrainDueFrameEmissions(Host *host) {
2940
+ if (!host || !host->running) return;
2941
+ const uint64_t now = gpuTimestampNs();
2942
+ std::vector<std::string> due_keys;
2943
+ for (const auto &entry : host->native_views) {
2944
+ const NativeView &view = entry.second;
2945
+ if (view.kind != kViewGpuSurface || !view.hwnd || !view.gpu_emission_scheduled) continue;
2946
+ const uint64_t pace_ns = (!view.gpu_prompt_frame_pending && gpuSurfaceOccludedPacingActive(host, view)) ? kGpuOccludedHeartbeatNs : kGpuFrameIntervalNs;
2947
+ if (view.gpu_last_emit_ns == 0 || now >= view.gpu_last_emit_ns + pace_ns) {
2948
+ due_keys.push_back(entry.first);
2949
+ }
2950
+ }
2951
+ for (const std::string &key : due_keys) {
2952
+ /* Emission enters application code synchronously. A preceding due
2953
+ * surface may have stopped the host, so never begin another callback
2954
+ * after shutdown/failure. */
2955
+ if (!host->running) return;
2956
+ auto found = host->native_views.find(key);
2957
+ if (found == host->native_views.end()) continue;
2958
+ NativeView &view = found->second;
2959
+ if (view.kind != kViewGpuSurface || !view.hwnd || !view.gpu_emission_scheduled) continue;
2960
+ const uint64_t current_ns = gpuTimestampNs();
2961
+ const uint64_t pace_ns = (!view.gpu_prompt_frame_pending && gpuSurfaceOccludedPacingActive(host, view)) ? kGpuOccludedHeartbeatNs : kGpuFrameIntervalNs;
2962
+ if (view.gpu_last_emit_ns > 0 && current_ns < view.gpu_last_emit_ns + pace_ns) continue;
2963
+ const HWND hwnd = view.hwnd;
2964
+ KillTimer(hwnd, kGpuEmitTimerId);
2965
+ view.gpu_emission_scheduled = false;
2966
+ gpuSurfaceEmitFrame(host, view, hwnd);
2967
+ if (!host->running) return;
2792
2968
  }
2969
+ gpuSurfaceRefreshFrameWakeTimer(host);
2793
2970
  }
2794
2971
 
2795
2972
  static void paintGpuSurface(NativeView &view, HWND hwnd, HDC dc) {
@@ -3037,7 +3214,7 @@ static bool presentTransparentWindow(Host *host, Window &window) {
3037
3214
  }
3038
3215
 
3039
3216
  static void showWindowImplicit(Window &window) {
3040
- if (!window.hwnd || window.shown) return;
3217
+ if (!window.hwnd || window.shown || window.policy_hidden) return;
3041
3218
  ShowWindow(window.hwnd, window.activate_on_show ? SW_SHOW : SW_SHOWNOACTIVATE);
3042
3219
  window.shown = true;
3043
3220
  window.deferred_show_started_ms = 0;
@@ -3130,6 +3307,7 @@ static LRESULT CALLBACK gpuSurfaceProc(HWND hwnd, UINT message, WPARAM wparam, L
3130
3307
  KillTimer(hwnd, kGpuEmitTimerId);
3131
3308
  view->gpu_emission_scheduled = false;
3132
3309
  gpuSurfaceEmitFrame(host, *view, hwnd);
3310
+ if (host->running) gpuSurfaceRefreshFrameWakeTimer(host);
3133
3311
  return 0;
3134
3312
  }
3135
3313
  break;
@@ -4258,6 +4436,129 @@ static void audioHandleSpectrumMessage(Host *host, WPARAM generation) {
4258
4436
  audioEmitSpectrum(host, bands);
4259
4437
  }
4260
4438
 
4439
+ /* ------------------------------------------------------- audio capture
4440
+ * Default microphone capture uses the default eCapture endpoint; system
4441
+ * capture uses the default eRender endpoint with WASAPI's loopback flag.
4442
+ * Shared-mode conversion asks the in-box audio engine for the SDK's exact
4443
+ * signed-16 format, so device-native rates/layouts never leak across the
4444
+ * platform seam. Each source owns a joinable worker: stop is the required
4445
+ * quiescence fence before the Zig sink storage can be cleared. */
4446
+ static void audioCaptureThread(std::shared_ptr<AudioCaptureShared> shared) {
4447
+ HRESULT com_hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE);
4448
+ IMMDeviceEnumerator *enumerator = nullptr;
4449
+ IMMDevice *device = nullptr;
4450
+ IAudioClient *client = nullptr;
4451
+ IAudioCaptureClient *capture = nullptr;
4452
+ HANDLE ready = nullptr;
4453
+ bool running = false;
4454
+ do {
4455
+ if (FAILED(CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_ALL,
4456
+ IID_IMMDeviceEnumerator, reinterpret_cast<void **>(&enumerator))) || !enumerator) break;
4457
+ const EDataFlow flow = shared->source == 1 ? eRender : eCapture;
4458
+ if (FAILED(enumerator->GetDefaultAudioEndpoint(flow, eConsole, &device)) || !device) break;
4459
+ if (FAILED(device->Activate(IID_IAudioClient, CLSCTX_ALL, nullptr,
4460
+ reinterpret_cast<void **>(&client))) || !client) break;
4461
+ WAVEFORMATEX format = {};
4462
+ format.wFormatTag = WAVE_FORMAT_PCM;
4463
+ format.nChannels = shared->channels;
4464
+ format.nSamplesPerSec = shared->sample_rate;
4465
+ format.wBitsPerSample = 16;
4466
+ format.nBlockAlign = (WORD)(format.nChannels * 2);
4467
+ format.nAvgBytesPerSec = format.nSamplesPerSec * format.nBlockAlign;
4468
+ DWORD flags = AUDCLNT_STREAMFLAGS_EVENTCALLBACK |
4469
+ AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM |
4470
+ AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY;
4471
+ if (shared->source == 1) flags |= AUDCLNT_STREAMFLAGS_LOOPBACK;
4472
+ if (FAILED(client->Initialize(AUDCLNT_SHAREMODE_SHARED, flags, 1000000, 0, &format, nullptr))) break;
4473
+ ready = CreateEventW(nullptr, FALSE, FALSE, nullptr);
4474
+ if (!ready || FAILED(client->SetEventHandle(ready))) break;
4475
+ if (FAILED(client->GetService(IID_IAudioCaptureClient, reinterpret_cast<void **>(&capture))) || !capture) break;
4476
+ if (FAILED(client->Start())) break;
4477
+ running = true;
4478
+ } while (false);
4479
+
4480
+ if (!running) {
4481
+ if (!shared->stop.load(std::memory_order_relaxed) && shared->push) {
4482
+ shared->push(shared->context, 2, shared->source, shared->sample_rate,
4483
+ shared->channels, 0, 0, nullptr, 0);
4484
+ }
4485
+ } else {
4486
+ if (shared->push && shared->push(shared->context, 0, shared->source,
4487
+ shared->sample_rate, shared->channels, 0, 0, nullptr, 0) == 1) {
4488
+ shared->stop.store(true, std::memory_order_relaxed);
4489
+ }
4490
+ const UINT32 max_frames = 3840u / ((UINT32)shared->channels * 2u);
4491
+ int16_t silence[1920] = {};
4492
+ bool terminal_error = false;
4493
+ while (!shared->stop.load(std::memory_order_relaxed)) {
4494
+ const DWORD wait_result = WaitForSingleObject(ready, 50);
4495
+ /* A timeout is also a polling fallback for loopback endpoints
4496
+ * whose event notification is late or absent. */
4497
+ if (wait_result != WAIT_OBJECT_0 && wait_result != WAIT_TIMEOUT) {
4498
+ terminal_error = true;
4499
+ break;
4500
+ }
4501
+ while (!shared->stop.load(std::memory_order_relaxed)) {
4502
+ UINT32 pending = 0;
4503
+ if (FAILED(capture->GetNextPacketSize(&pending))) {
4504
+ terminal_error = true;
4505
+ break;
4506
+ }
4507
+ if (pending == 0) break;
4508
+ BYTE *data = nullptr;
4509
+ UINT32 frames = 0;
4510
+ DWORD packet_flags = 0;
4511
+ if (FAILED(capture->GetBuffer(&data, &frames, &packet_flags, nullptr, nullptr))) {
4512
+ terminal_error = true;
4513
+ break;
4514
+ }
4515
+ UINT32 offset = 0;
4516
+ while (offset < frames && !shared->stop.load(std::memory_order_relaxed)) {
4517
+ const UINT32 chunk = std::min(max_frames, frames - offset);
4518
+ const size_t byte_len = (size_t)chunk * shared->channels * 2;
4519
+ const uint8_t *pcm = ((packet_flags & AUDCLNT_BUFFERFLAGS_SILENT) || !data)
4520
+ ? reinterpret_cast<const uint8_t *>(silence)
4521
+ : data + (size_t)offset * shared->channels * 2;
4522
+ const int result = shared->push ? shared->push(shared->context, 1,
4523
+ shared->source, shared->sample_rate, shared->channels,
4524
+ gpuTimestampNs(), chunk, pcm, byte_len) : 1;
4525
+ if (result == 1) shared->stop.store(true, std::memory_order_relaxed);
4526
+ offset += chunk;
4527
+ }
4528
+ if (FAILED(capture->ReleaseBuffer(frames))) {
4529
+ terminal_error = true;
4530
+ break;
4531
+ }
4532
+ }
4533
+ if (terminal_error) break;
4534
+ }
4535
+ if (terminal_error && !shared->stop.load(std::memory_order_relaxed) && shared->push) {
4536
+ shared->push(shared->context, 2, shared->source, shared->sample_rate,
4537
+ shared->channels, 0, 0, nullptr, 0);
4538
+ }
4539
+ client->Stop();
4540
+ }
4541
+ if (capture) capture->Release();
4542
+ if (client) client->Release();
4543
+ if (device) device->Release();
4544
+ if (enumerator) enumerator->Release();
4545
+ if (ready) CloseHandle(ready);
4546
+ if (SUCCEEDED(com_hr)) CoUninitialize();
4547
+ }
4548
+
4549
+ static void audioCaptureStop(Host *host, int source) {
4550
+ if (!host || source < 0 || source > 1) return;
4551
+ AudioCaptureState &state = host->captures[source];
4552
+ if (state.shared) state.shared->stop.store(true, std::memory_order_relaxed);
4553
+ if (state.worker.joinable()) state.worker.join();
4554
+ state.shared.reset();
4555
+ }
4556
+
4557
+ static void audioCaptureStopAll(Host *host) {
4558
+ audioCaptureStop(host, 0);
4559
+ audioCaptureStop(host, 1);
4560
+ }
4561
+
4261
4562
  /* Release the whole pipeline. The session retires through Close(): the
4262
4563
  * event pump answers the MESessionClosed handshake by shutting source
4263
4564
  * and session down on the worker thread, so the loop never blocks. The
@@ -5389,7 +5690,16 @@ static LRESULT CALLBACK windowProc(HWND hwnd, UINT message, WPARAM wparam, LPARA
5389
5690
  case kNotificationCallbackMessage:
5390
5691
  if (host && host->tray_active) {
5391
5692
  UINT tray_event = LOWORD(lparam);
5392
- if (tray_event == WM_CONTEXTMENU || tray_event == WM_RBUTTONUP || tray_event == WM_LBUTTONUP) {
5693
+ if (tray_event == NIN_SELECT || tray_event == NIN_KEYSELECT || tray_event == WM_LBUTTONUP) {
5694
+ if (keyDown(VK_MENU) && !host->tray_alternate_activation_command.empty()) {
5695
+ emitStatusCommand(host, hwnd, host->tray_alternate_activation_command);
5696
+ return 0;
5697
+ }
5698
+ emitStatusCommand(host, hwnd, host->tray_activation_command);
5699
+ showTrayMenu(host, hwnd);
5700
+ return 0;
5701
+ }
5702
+ if (tray_event == WM_CONTEXTMENU || tray_event == WM_RBUTTONUP) {
5393
5703
  showTrayMenu(host, hwnd);
5394
5704
  return 0;
5395
5705
  }
@@ -5773,7 +6083,7 @@ static bool createNativeWindow(Host *host, Window &window) {
5773
6083
  window.hwnd = nullptr;
5774
6084
  return false;
5775
6085
  }
5776
- if (!window.show_on_first_present) {
6086
+ if (!window.show_on_first_present && !window.policy_hidden) {
5777
6087
  showWindowImplicit(window);
5778
6088
  }
5779
6089
  SetTimer(hwnd, kFrameTimerId, 16, nullptr);
@@ -5834,12 +6144,14 @@ Host *native_sdk_windows_create(const char *app_name, size_t app_name_len, const
5834
6144
  window.click_through = (window_flags & (1u << 2)) != 0;
5835
6145
  window.activate_on_show = (window_flags & (1u << 3)) == 0;
5836
6146
  window.show_on_first_present = show_policy == 1;
6147
+ window.policy_hidden = show_policy == 2;
5837
6148
  host->windows[window.id] = window;
5838
6149
  return host;
5839
6150
  }
5840
6151
 
5841
6152
  void native_sdk_windows_destroy(Host *host) {
5842
6153
  if (!host) return;
6154
+ audioCaptureStopAll(host);
5843
6155
  std::shared_ptr<HostLifetime> lifetime = host->lifetime;
5844
6156
  std::lock_guard<std::recursive_mutex> guard(lifetime->mutex);
5845
6157
  lifetime->alive = false;
@@ -5861,6 +6173,7 @@ void native_sdk_windows_destroy(Host *host) {
5861
6173
  audioReleaseSession(host, true);
5862
6174
  removeNotificationIcon(host);
5863
6175
  destroyAllWindows(host);
6176
+ gpuSurfaceDestroyFrameWakeTimer(host);
5864
6177
  const bool com_initialized = host->com_initialized;
5865
6178
  delete host;
5866
6179
  if (com_initialized) CoUninitialize();
@@ -5882,9 +6195,23 @@ void native_sdk_windows_run(Host *host, EventCallback callback, void *context) {
5882
6195
  emit(host, entry.second, kWindowFrame);
5883
6196
  }
5884
6197
  MSG message = {};
5885
- while (host->running && GetMessageW(&message, nullptr, 0, 0) > 0) {
6198
+ while (host->running) {
6199
+ HANDLE handles[1] = {};
6200
+ const DWORD handle_count = host->gpu_frame_wake_timer ? 1 : 0;
6201
+ if (handle_count != 0) handles[0] = host->gpu_frame_wake_timer;
6202
+ const DWORD wait_result = MsgWaitForMultipleObjectsEx(
6203
+ handle_count, handles, INFINITE, QS_ALLINPUT, MWMO_INPUTAVAILABLE);
6204
+ if (wait_result == WAIT_FAILED) break;
6205
+ if (handle_count != 0 && wait_result == WAIT_OBJECT_0) {
6206
+ gpuSurfaceDrainDueFrameEmissions(host);
6207
+ continue;
6208
+ }
6209
+ if (wait_result != WAIT_OBJECT_0 + handle_count) continue;
6210
+ const BOOL received = GetMessageW(&message, nullptr, 0, 0);
6211
+ if (received <= 0) break;
5886
6212
  TranslateMessage(&message);
5887
6213
  DispatchMessageW(&message);
6214
+ if (host->running) gpuSurfaceDrainDueFrameEmissions(host);
5888
6215
  }
5889
6216
  WindowsEvent shutdown = {};
5890
6217
  shutdown.kind = kShutdown;
@@ -6224,6 +6551,7 @@ int native_sdk_windows_create_window(Host *host, uint64_t window_id, const char
6224
6551
  window.click_through = (window_flags & (1u << 2)) != 0;
6225
6552
  window.activate_on_show = (window_flags & (1u << 3)) == 0;
6226
6553
  window.show_on_first_present = show_policy == 1;
6554
+ window.policy_hidden = show_policy == 2;
6227
6555
  /* Register BEFORE creating: createNativeWindow's post-create frame
6228
6556
  * pass (hidden titlebar styles) resolves the window through the map
6229
6557
  * by HWND, so the stored entry must be the one it mutates. */
@@ -6371,6 +6699,7 @@ int native_sdk_windows_focus_window(Host *host, uint64_t window_id) {
6371
6699
  if (!host) return 0;
6372
6700
  auto found = host->windows.find(window_id);
6373
6701
  if (found == host->windows.end() || !found->second.hwnd) return 0;
6702
+ found->second.policy_hidden = false;
6374
6703
  if (!found->second.shown) {
6375
6704
  ShowWindow(found->second.hwnd, SW_SHOW);
6376
6705
  found->second.shown = true;
@@ -6402,6 +6731,17 @@ int native_sdk_windows_minimize_window(Host *host, uint64_t window_id) {
6402
6731
  return 1;
6403
6732
  }
6404
6733
 
6734
+ int native_sdk_windows_hide_window(Host *host, uint64_t window_id) {
6735
+ if (!host) return 0;
6736
+ auto found = host->windows.find(window_id);
6737
+ if (found == host->windows.end() || !found->second.hwnd) return 0;
6738
+ found->second.policy_hidden = true;
6739
+ found->second.shown = false;
6740
+ ShowWindow(found->second.hwnd, SW_HIDE);
6741
+ emit(host, found->second, kWindowFrame);
6742
+ return 1;
6743
+ }
6744
+
6405
6745
  /* The show verb: bring the window back to the glass and foreground it —
6406
6746
  * the counterpart to a close_policy hide (and the tray-menu "Open"
6407
6747
  * consequence). Restores a minimized window on the way. */
@@ -7132,24 +7472,33 @@ int native_sdk_windows_show_notification(Host *host, const char *title, size_t t
7132
7472
  return Shell_NotifyIconW(NIM_MODIFY, &data) ? 1 : 0;
7133
7473
  }
7134
7474
 
7135
- int native_sdk_windows_create_tray(Host *host, const char *icon_path, size_t icon_path_len, const char *tooltip, size_t tooltip_len) {
7475
+ int native_sdk_windows_create_tray(Host *host, const char *icon_path, size_t icon_path_len, const char *tooltip, size_t tooltip_len, const char *activation_command, size_t activation_command_len, const char *alternate_activation_command, size_t alternate_activation_command_len, const char *open_command, size_t open_command_len) {
7136
7476
  if (!host) return 0;
7137
7477
  std::string icon = slice(icon_path, icon_path_len);
7138
7478
  std::string tip = slice(tooltip, tooltip_len);
7139
7479
  if (!setNotificationIcon(host, icon, tip, true)) return 0;
7480
+ host->tray_activation_command = slice(activation_command, activation_command_len);
7481
+ host->tray_alternate_activation_command = slice(alternate_activation_command, alternate_activation_command_len);
7482
+ host->tray_open_command = slice(open_command, open_command_len);
7140
7483
  host->tray_active = true;
7141
7484
  return 1;
7142
7485
  }
7143
7486
 
7144
- int native_sdk_windows_update_tray_menu(Host *host, const uint32_t *item_ids, const char *const *labels, const size_t *label_lens, const int *separators, const int *enabled_flags, size_t count) {
7487
+ int native_sdk_windows_update_tray_menu(Host *host, const uint32_t *item_ids, const char *const *labels, const size_t *label_lens, const int *separators, const int *enabled_flags, const char *const *details, const size_t *detail_lens, const int *roles, const char *const *keys, const size_t *key_lens, const uint32_t *modifiers, size_t count) {
7145
7488
  if (!host || !host->tray_active) return 0;
7146
7489
  host->tray_items.clear();
7147
- if (count > 0 && (!item_ids || !labels || !label_lens || !separators || !enabled_flags)) return 0;
7490
+ if (count > 0 && (!item_ids || !labels || !label_lens || !separators || !enabled_flags || !details || !detail_lens || !roles || !keys || !key_lens || !modifiers)) return 0;
7148
7491
  host->tray_items.reserve(count);
7149
7492
  for (size_t index = 0; index < count; ++index) {
7150
7493
  TrayItem item;
7151
7494
  item.id = item_ids[index];
7152
7495
  item.label = slice(labels[index], label_lens[index]);
7496
+ item.detail = slice(details[index], detail_lens[index]);
7497
+ item.role = roles[index];
7498
+ // Shortcut validation accepts ASCII uppercase keys, while Windows key
7499
+ // events are normalized to lowercase before matching.
7500
+ item.key = lowerAscii(slice(keys[index], key_lens[index]));
7501
+ item.modifiers = modifiers[index];
7153
7502
  item.separator = separators[index] != 0;
7154
7503
  item.enabled = enabled_flags[index] != 0;
7155
7504
  if (!item.separator) item.command_id = kTrayCommandBase + static_cast<uint32_t>(index);
@@ -7162,6 +7511,9 @@ void native_sdk_windows_remove_tray(Host *host) {
7162
7511
  if (!host) return;
7163
7512
  host->tray_active = false;
7164
7513
  host->tray_items.clear();
7514
+ host->tray_activation_command.clear();
7515
+ host->tray_alternate_activation_command.clear();
7516
+ host->tray_open_command.clear();
7165
7517
  removeNotificationIcon(host);
7166
7518
  }
7167
7519
 
@@ -7198,7 +7550,8 @@ int native_sdk_windows_clear_recent_documents(Host *host) {
7198
7550
 
7199
7551
  int native_sdk_windows_set_credential(Host *host, const char *service, size_t service_len, const char *account, size_t account_len, const char *secret, size_t secret_len) {
7200
7552
  (void)host;
7201
- if (!service || service_len == 0 || !account || account_len == 0 || !secret || secret_len == 0 || secret_len > UINT32_MAX) return 0;
7553
+ if (!service || service_len == 0 || !account || account_len == 0 || (!secret && secret_len > 0) || secret_len > UINT32_MAX) return 0;
7554
+ if (secret_len > CRED_MAX_CREDENTIAL_BLOB_SIZE) return -4;
7202
7555
  HMODULE advapi = LoadLibraryW(L"advapi32.dll");
7203
7556
  if (!advapi) return 0;
7204
7557
  auto cred_write = reinterpret_cast<BOOL (WINAPI *)(PCREDENTIALW, DWORD)>(GetProcAddress(advapi, "CredWriteW"));
@@ -7220,28 +7573,32 @@ int native_sdk_windows_set_credential(Host *host, const char *service, size_t se
7220
7573
  credential.UserName = const_cast<LPWSTR>(user_name.c_str());
7221
7574
 
7222
7575
  BOOL ok = cred_write(&credential, 0);
7576
+ DWORD error = ok ? ERROR_SUCCESS : GetLastError();
7223
7577
  FreeLibrary(advapi);
7224
- return ok ? 1 : 0;
7578
+ if (ok) return 1;
7579
+ return error == ERROR_ACCESS_DENIED ? -3 : -1;
7225
7580
  }
7226
7581
 
7227
7582
  size_t native_sdk_windows_get_credential(Host *host, const char *service, size_t service_len, const char *account, size_t account_len, char *buffer, size_t buffer_len) {
7228
7583
  (void)host;
7229
- if (!service || service_len == 0 || !account || account_len == 0 || !buffer) return 0;
7584
+ if (!service || service_len == 0 || !account || account_len == 0 || (!buffer && buffer_len > 0)) return SIZE_MAX - 1;
7230
7585
  HMODULE advapi = LoadLibraryW(L"advapi32.dll");
7231
- if (!advapi) return 0;
7586
+ if (!advapi) return SIZE_MAX - 1;
7232
7587
  auto cred_read = reinterpret_cast<BOOL (WINAPI *)(LPCWSTR, DWORD, DWORD, PCREDENTIALW *)>(GetProcAddress(advapi, "CredReadW"));
7233
7588
  auto cred_free = reinterpret_cast<void (WINAPI *)(PVOID)>(GetProcAddress(advapi, "CredFree"));
7234
7589
  if (!cred_read || !cred_free) {
7235
7590
  FreeLibrary(advapi);
7236
- return 0;
7591
+ return SIZE_MAX - 1;
7237
7592
  }
7238
7593
 
7239
7594
  std::wstring target = credentialTarget(slice(service, service_len), slice(account, account_len));
7240
7595
  PCREDENTIALW credential = nullptr;
7241
7596
  BOOL ok = cred_read(target.c_str(), CRED_TYPE_GENERIC, 0, &credential);
7242
7597
  if (!ok || !credential) {
7598
+ DWORD error = GetLastError();
7243
7599
  FreeLibrary(advapi);
7244
- return 0;
7600
+ if (error == ERROR_NOT_FOUND) return SIZE_MAX;
7601
+ return error == ERROR_ACCESS_DENIED ? SIZE_MAX - 3 : SIZE_MAX - 1;
7245
7602
  }
7246
7603
 
7247
7604
  size_t secret_len = credential->CredentialBlobSize;
@@ -7260,17 +7617,50 @@ int native_sdk_windows_delete_credential(Host *host, const char *service, size_t
7260
7617
  (void)host;
7261
7618
  if (!service || service_len == 0 || !account || account_len == 0) return 0;
7262
7619
  HMODULE advapi = LoadLibraryW(L"advapi32.dll");
7263
- if (!advapi) return 0;
7620
+ if (!advapi) return -1;
7264
7621
  auto cred_delete = reinterpret_cast<BOOL (WINAPI *)(LPCWSTR, DWORD, DWORD)>(GetProcAddress(advapi, "CredDeleteW"));
7265
7622
  if (!cred_delete) {
7266
7623
  FreeLibrary(advapi);
7267
- return 0;
7624
+ return -1;
7268
7625
  }
7269
7626
 
7270
7627
  std::wstring target = credentialTarget(slice(service, service_len), slice(account, account_len));
7271
7628
  BOOL ok = cred_delete(target.c_str(), CRED_TYPE_GENERIC, 0);
7629
+ DWORD error = ok ? ERROR_SUCCESS : GetLastError();
7272
7630
  FreeLibrary(advapi);
7273
- return ok ? 1 : 0;
7631
+ if (ok) return 1;
7632
+ if (error == ERROR_NOT_FOUND) return 0;
7633
+ return error == ERROR_ACCESS_DENIED ? -3 : -1;
7634
+ }
7635
+
7636
+ size_t native_sdk_windows_format_local_time(Host *host, int64_t timestamp_ms, int style, char *buffer, size_t buffer_len) {
7637
+ (void)host;
7638
+ if (!buffer || buffer_len == 0 || style < 0 || style > 2) return 0;
7639
+
7640
+ const long double ticks_value = static_cast<long double>(timestamp_ms) * 10000.0L + 116444736000000000.0L;
7641
+ if (ticks_value < 0.0L || ticks_value > static_cast<long double>(UINT64_MAX)) return 0;
7642
+ ULARGE_INTEGER ticks = {};
7643
+ ticks.QuadPart = static_cast<uint64_t>(ticks_value);
7644
+ FILETIME utc = { ticks.LowPart, ticks.HighPart };
7645
+ SYSTEMTIME utc_system_time = {};
7646
+ SYSTEMTIME system_time = {};
7647
+ if (!FileTimeToSystemTime(&utc, &utc_system_time) ||
7648
+ !SystemTimeToTzSpecificLocalTimeEx(nullptr, &utc_system_time, &system_time)) return 0;
7649
+
7650
+ wchar_t date_text[128] = {};
7651
+ wchar_t time_text[128] = {};
7652
+ if ((style == 0 || style == 2) && GetDateFormatEx(LOCALE_NAME_USER_DEFAULT, DATE_SHORTDATE, &system_time, nullptr, date_text, ARRAYSIZE(date_text), nullptr) == 0) return 0;
7653
+ if ((style == 1 || style == 2) && GetTimeFormatEx(LOCALE_NAME_USER_DEFAULT, 0, &system_time, nullptr, time_text, ARRAYSIZE(time_text)) == 0) return 0;
7654
+
7655
+ std::wstring text;
7656
+ if (style == 0) text = date_text;
7657
+ else if (style == 1) text = time_text;
7658
+ else text = std::wstring(date_text) + L" " + time_text;
7659
+ if (text.empty()) return 0;
7660
+ const int needed = WideCharToMultiByte(CP_UTF8, 0, text.data(), static_cast<int>(text.size()), nullptr, 0, nullptr, nullptr);
7661
+ if (needed <= 0 || static_cast<size_t>(needed) > buffer_len) return 0;
7662
+ if (WideCharToMultiByte(CP_UTF8, 0, text.data(), static_cast<int>(text.size()), buffer, needed, nullptr, nullptr) != needed) return 0;
7663
+ return static_cast<size_t>(needed);
7274
7664
  }
7275
7665
 
7276
7666
  int native_sdk_windows_create_webview(Host *host, uint64_t window_id, const char *label, size_t label_len, const char *url, size_t url_len, double x, double y, double width, double height, int layer, int transparent, int bridge_enabled) {
@@ -7608,4 +7998,32 @@ int native_sdk_windows_audio_spectrum_supported(Host *host) {
7608
7998
  return audioSpectrumSupported() ? 1 : 0;
7609
7999
  }
7610
8000
 
8001
+ int native_sdk_windows_audio_capture_start(Host *host, int source, uint32_t sample_rate,
8002
+ uint8_t channels, AudioCapturePush push_fn, void *push_context) {
8003
+ if (!host || source < 0 || source > 1 || !push_fn ||
8004
+ (sample_rate != 16000 && sample_rate != 24000 && sample_rate != 48000) ||
8005
+ (channels != 1 && channels != 2)) return 0;
8006
+ audioCaptureStop(host, source);
8007
+ AudioCaptureState &state = host->captures[source];
8008
+ state.shared = std::make_shared<AudioCaptureShared>();
8009
+ state.shared->source = source;
8010
+ state.shared->sample_rate = sample_rate;
8011
+ state.shared->channels = channels;
8012
+ state.shared->push = push_fn;
8013
+ state.shared->context = push_context;
8014
+ try {
8015
+ state.worker = std::thread(audioCaptureThread, state.shared);
8016
+ } catch (...) {
8017
+ state.shared.reset();
8018
+ return 0;
8019
+ }
8020
+ return 1;
8021
+ }
8022
+
8023
+ int native_sdk_windows_audio_capture_stop(Host *host, int source) {
8024
+ if (!host || source < 0 || source > 1) return 0;
8025
+ audioCaptureStop(host, source);
8026
+ return 1;
8027
+ }
8028
+
7611
8029
  }