@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
@@ -2,6 +2,7 @@
2
2
 
3
3
  #import <AppKit/AppKit.h>
4
4
  #import <AVFoundation/AVFoundation.h>
5
+ #import <ScreenCaptureKit/ScreenCaptureKit.h>
5
6
  /* Spectrum analysis of the app's own playback: MediaToolbox provides
6
7
  * the MTAudioProcessingTap that hands the player's PCM to the host, and
7
8
  * Accelerate (vDSP) provides the FFT that turns it into band
@@ -23,8 +24,11 @@
23
24
  #include <stdint.h>
24
25
  #include <stdlib.h>
25
26
  #include <string.h>
27
+ #include <time.h>
26
28
 
27
29
  @class NativeSdkAppKitHost;
30
+ @class NativeSdkAudioCaptureTarget;
31
+ @class NativeSdkScreenAudioCapture;
28
32
 
29
33
  static const NSUInteger NativeSdkMaxChildWebViews = 16;
30
34
  static const NSUInteger NativeSdkMaxNativeViews = 32;
@@ -35,6 +39,53 @@ static const uint32_t NativeSdkShortcutModifierCommand = 1u << 1;
35
39
  static const uint32_t NativeSdkShortcutModifierControl = 1u << 2;
36
40
  static const uint32_t NativeSdkShortcutModifierOption = 1u << 3;
37
41
  static const uint32_t NativeSdkShortcutModifierShift = 1u << 4;
42
+
43
+ // SMAppService is resolved dynamically so the host keeps its existing
44
+ // deployment target. Class lookup alone does not load the framework, so
45
+ // load it explicitly on first use; older macOS releases simply leave the
46
+ // class unavailable and report unsupported.
47
+ static id NativeSdkMainAppService(void) {
48
+ static void *serviceManagementHandle = NULL;
49
+ static dispatch_once_t serviceManagementOnce;
50
+ dispatch_once(&serviceManagementOnce, ^{
51
+ serviceManagementHandle = dlopen(
52
+ "/System/Library/Frameworks/ServiceManagement.framework/ServiceManagement",
53
+ RTLD_LAZY | RTLD_LOCAL);
54
+ });
55
+ if (!serviceManagementHandle) return nil;
56
+ Class serviceClass = NSClassFromString(@"SMAppService");
57
+ SEL selector = NSSelectorFromString(@"mainApp");
58
+ if (!serviceClass || ![serviceClass respondsToSelector:selector]) return nil;
59
+ IMP implementation = [serviceClass methodForSelector:selector];
60
+ return ((id (*)(id, SEL))implementation)(serviceClass, selector);
61
+ }
62
+
63
+ static int NativeSdkLaunchAtLoginStatus(void) {
64
+ id service = NativeSdkMainAppService();
65
+ SEL selector = NSSelectorFromString(@"status");
66
+ if (!service || ![service respondsToSelector:selector]) return -1;
67
+ IMP implementation = [service methodForSelector:selector];
68
+ return (int)((NSInteger (*)(id, SEL))implementation)(service, selector);
69
+ }
70
+
71
+ static int NativeSdkSetLaunchAtLogin(BOOL enabled) {
72
+ id service = NativeSdkMainAppService();
73
+ if (!service) return -1;
74
+ int before = NativeSdkLaunchAtLoginStatus();
75
+ // Requires-approval is already registered in the requested enabled
76
+ // direction. Re-registering it returns kSMErrorAlreadyRegistered or
77
+ // kSMErrorLaunchDeniedByUser instead of advancing the user's consent.
78
+ if ((enabled && (before == 1 || before == 2)) || (!enabled && before == 0)) return before;
79
+ SEL selector = NSSelectorFromString(enabled ? @"registerAndReturnError:" : @"unregisterAndReturnError:");
80
+ if (![service respondsToSelector:selector]) return -1;
81
+ NSError *error = nil;
82
+ IMP implementation = [service methodForSelector:selector];
83
+ BOOL succeeded = ((BOOL (*)(id, SEL, NSError **))implementation)(service, selector, &error);
84
+ // -1 is reserved for an unavailable service/API. A supported service
85
+ // refusing the operation is a real failure so the TypeScript effect can
86
+ // distinguish "failed" from "unsupported".
87
+ return succeeded ? NativeSdkLaunchAtLoginStatus() : -2;
88
+ }
38
89
  static void *NativeSdkAppKitAppearanceObservationContext = &NativeSdkAppKitAppearanceObservationContext;
39
90
  /* KVO contexts for the app's single audio player: the AVPlayerItem's
40
91
  * load status (readyToPlay -> the LOADED acknowledgment; failed -> one
@@ -116,7 +167,10 @@ static BOOL NativeSdkAppKitHighContrastEnabled(void) {
116
167
  }
117
168
 
118
169
  static uint64_t NativeSdkTimestampNanoseconds(void) {
119
- return (uint64_t)([[NSDate date] timeIntervalSince1970] * 1000000000.0);
170
+ /* GPU input, frame pacing, and present-completion latency are duration
171
+ * math. CLOCK_MONOTONIC matches the runtime's monotonicNanoseconds seam
172
+ * and cannot jump when the wall clock is adjusted. */
173
+ return clock_gettime_nsec_np(CLOCK_MONOTONIC);
120
174
  }
121
175
 
122
176
  static uint64_t NativeSdkRetainedFrameIntervalNanoseconds(NSScreen *screen) {
@@ -280,6 +334,15 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
280
334
  } mutableCopy];
281
335
  }
282
336
 
337
+ // Preserve the closed core-effect failure classes across the C seam.
338
+ static int NativeSdkCredentialStatus(OSStatus status, int missingCode) {
339
+ if (status == errSecSuccess) return 1;
340
+ if (status == errSecItemNotFound) return missingCode;
341
+ if (status == errSecInteractionNotAllowed || status == errSecNotAvailable) return -2;
342
+ if (status == errSecAuthFailed || status == errSecUserCanceled || status == errSecMissingEntitlement) return -3;
343
+ return -1;
344
+ }
345
+
283
346
  /// The chromeless (titlebarStyle 3) window class: a borderless NSWindow
284
347
  /// refuses key/main status by default, which would leave a fully-skinned
285
348
  /// app deaf to the keyboard — this subclass restores both. Used only for
@@ -700,7 +763,7 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
700
763
  @property(nonatomic, assign) uint32_t modifiers;
701
764
  @end
702
765
 
703
- @interface NativeSdkAppKitHost : NSObject <WKNavigationDelegate>
766
+ @interface NativeSdkAppKitHost : NSObject <WKNavigationDelegate, NSMenuDelegate>
704
767
  @property(nonatomic, strong) NSWindow *window;
705
768
  @property(nonatomic, strong) WKWebView *webView;
706
769
  @property(nonatomic, strong) NativeSdkWindowDelegate *delegate;
@@ -811,6 +874,13 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
811
874
  * when a new load replaces the stream; orphaned (left to finish) when
812
875
  * the stream completes naturally. */
813
876
  @property(nonatomic, strong) NSURLSessionDownloadTask *audioCacheDownload;
877
+ /* Independent microphone and system-output PCM capture. The target owns
878
+ * callback quiescence; the concrete producers own AVAudioEngine and
879
+ * ScreenCaptureKit respectively. */
880
+ @property(nonatomic, strong) NativeSdkAudioCaptureTarget *microphoneCaptureTarget;
881
+ @property(nonatomic, strong) AVAudioEngine *microphoneCaptureEngine;
882
+ @property(nonatomic, strong) NativeSdkAudioCaptureTarget *systemCaptureTarget;
883
+ @property(nonatomic, strong) NativeSdkScreenAudioCapture *systemCapture;
814
884
  /* The app's single video player and its two timers. One player is the
815
885
  * whole surface, exactly like audio: a video app shows one stream at a
816
886
  * time, and a second concurrent decode would be compositor design the
@@ -917,6 +987,15 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
917
987
  @property(nonatomic, strong) dispatch_source_t sigtermSource;
918
988
  @property(nonatomic, strong) NSArray<NativeSdkShortcut *> *shortcuts;
919
989
  @property(nonatomic, strong) NSStatusItem *statusItem;
990
+ @property(nonatomic, strong) NSImage *statusItemBaseImage;
991
+ @property(nonatomic, strong) NSMenu *statusMenu;
992
+ @property(nonatomic, assign) double statusPresentationWidth;
993
+ @property(nonatomic, assign) int statusPresentationTone;
994
+ @property(nonatomic, assign) double statusPresentationIconOpacity;
995
+ @property(nonatomic, assign) BOOL statusPresentationMonospaced;
996
+ @property(nonatomic, strong) NSString *statusActivationCommand;
997
+ @property(nonatomic, strong) NSString *statusAlternateActivationCommand;
998
+ @property(nonatomic, strong) NSString *statusOpenCommand;
920
999
  @property(nonatomic, assign) native_sdk_appkit_tray_callback_t trayCallback;
921
1000
  @property(nonatomic, assign) void *trayContext;
922
1001
  @property(nonatomic, strong) NSArray<NSString *> *allowedNavigationOrigins;
@@ -988,6 +1067,9 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
988
1067
  - (NSMenuItem *)menuItem:(NSString *)title action:(SEL)action key:(NSString *)key modifiers:(NSEventModifierFlags)modifiers;
989
1068
  - (NSMenuItem *)commandMenuItem:(NSString *)title command:(NSString *)command key:(NSString *)key modifiers:(uint32_t)modifiers enabled:(BOOL)enabled checked:(BOOL)checked;
990
1069
  - (void)menuCommandItemClicked:(NSMenuItem *)menuItem;
1070
+ - (void)menuWillOpen:(NSMenu *)menu;
1071
+ - (void)emitStatusCommand:(NSString *)command;
1072
+ - (void)statusItemActivated:(id)sender;
991
1073
  - (uint64_t)activeCommandWindowId;
992
1074
  - (void)setMenusWithTitles:(const char *const *)menuTitles titleLengths:(const size_t *)menuTitleLengths count:(size_t)menuCount itemMenuIndices:(const uint32_t *)itemMenuIndices itemLabels:(const char *const *)itemLabels itemLabelLengths:(const size_t *)itemLabelLengths itemCommands:(const char *const *)itemCommands itemCommandLengths:(const size_t *)itemCommandLengths itemKeys:(const char *const *)itemKeys itemKeyLengths:(const size_t *)itemKeyLengths itemModifiers:(const uint32_t *)itemModifiers itemSeparators:(const int *)itemSeparators itemEnabled:(const int *)itemEnabled itemChecked:(const int *)itemChecked itemCount:(size_t)itemCount;
993
1075
  - (void)runWithCallback:(native_sdk_appkit_event_callback_t)callback context:(void *)context;
@@ -1027,6 +1109,9 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
1027
1109
  - (int)audioStop;
1028
1110
  - (int)audioSeekToMs:(uint64_t)positionMs;
1029
1111
  - (int)audioSetVolume:(double)volume;
1112
+ - (int)audioCaptureStartSource:(int)source sampleRate:(uint32_t)sampleRate channels:(uint8_t)channels pushFn:(native_sdk_appkit_audio_capture_push_t)pushFn pushContext:(void *)pushContext;
1113
+ - (int)audioCaptureStopSource:(int)source;
1114
+ - (void)startMicrophoneCaptureTarget:(NativeSdkAudioCaptureTarget *)target;
1030
1115
  - (void)emitAudioEventOfKind:(int)kind;
1031
1116
  - (void)stopAudioPositionTimer;
1032
1117
  - (void)audioInstallSpectrumTapForItem:(AVPlayerItem *)item asset:(AVURLAsset *)asset;
@@ -1749,6 +1834,29 @@ static CGFloat NativeSdkPacketTransformScale(id value) {
1749
1834
  return fmax(0.0001, fmax(xScale, yScale));
1750
1835
  }
1751
1836
 
1837
+ /* Three box filters approximate a Gaussian closely while retaining the
1838
+ * O(pixels) sliding-window implementation in vImage. `sigma` is the CSS-like
1839
+ * blur radius in device pixels; the widths below are the standard optimal
1840
+ * three-box approximation, split between the neighboring odd widths whose
1841
+ * combined variance is closest to sigma squared. */
1842
+ static void NativeSdkGaussianBoxRadii(NSUInteger sigma, NSUInteger radii[3]) {
1843
+ const double passCount = 3.0;
1844
+ const double idealWidth = sqrt((12.0 * (double)sigma * (double)sigma / passCount) + 1.0);
1845
+ NSUInteger lowerWidth = (NSUInteger)floor(idealWidth);
1846
+ if ((lowerWidth & 1u) == 0) lowerWidth -= 1;
1847
+ lowerWidth = MAX((NSUInteger)1, lowerWidth);
1848
+ const NSUInteger upperWidth = lowerWidth + 2;
1849
+ const double lowerCountValue =
1850
+ (12.0 * (double)sigma * (double)sigma - passCount * (double)lowerWidth * (double)lowerWidth -
1851
+ 4.0 * passCount * (double)lowerWidth - 3.0 * passCount) /
1852
+ (-4.0 * (double)lowerWidth - 4.0);
1853
+ const NSInteger lowerCount = MAX((NSInteger)0, MIN((NSInteger)3, (NSInteger)llround(lowerCountValue)));
1854
+ for (NSUInteger pass = 0; pass < 3; pass++) {
1855
+ const NSUInteger width = pass < (NSUInteger)lowerCount ? lowerWidth : upperWidth;
1856
+ radii[pass] = (width - 1) / 2;
1857
+ }
1858
+ }
1859
+
1752
1860
  static BOOL NativeSdkPacketApplyBlur(NSDictionary *effect, CGFloat opacity, CGContextRef context, CGFloat scale, id transformValue, BOOL hasClip, NSRect clipRect) {
1753
1861
  if (!effect || !context) return NO;
1754
1862
  void *contextData = CGBitmapContextGetData(context);
@@ -1780,16 +1888,19 @@ static BOOL NativeSdkPacketApplyBlur(NSDictionary *effect, CGFloat opacity, CGCo
1780
1888
  NSUInteger maxY = (NSUInteger)maxYFloat;
1781
1889
  if (maxX <= minX || maxY <= minY) return YES;
1782
1890
 
1783
- NSUInteger radius = (NSUInteger)llround(fmax(0.0, NativeSdkPacketNumber(effect[@"radius"], 0) * normalizedScale * NativeSdkPacketTransformScale(transformValue)));
1784
- radius = MIN(radius, (NSUInteger)64);
1785
- if (radius == 0) return YES;
1891
+ NSUInteger sigma = (NSUInteger)llround(fmax(0.0, NativeSdkPacketNumber(effect[@"radius"], 0) * normalizedScale * NativeSdkPacketTransformScale(transformValue)));
1892
+ sigma = MIN(sigma, (NSUInteger)64);
1893
+ if (sigma == 0) return YES;
1786
1894
  CGFloat mix = fmax(0.0, fmin(1.0, opacity));
1787
1895
  if (mix <= 0) return YES;
1788
1896
 
1789
- NSUInteger expandedMinX = minX > radius ? minX - radius : 0;
1790
- NSUInteger expandedMaxX = MIN((NSUInteger)width, maxX + radius);
1791
- NSUInteger expandedMinY = minY > radius ? minY - radius : 0;
1792
- NSUInteger expandedMaxY = MIN((NSUInteger)height, maxY + radius);
1897
+ NSUInteger boxRadii[3] = {0, 0, 0};
1898
+ NativeSdkGaussianBoxRadii(sigma, boxRadii);
1899
+ const NSUInteger sampleExtent = boxRadii[0] + boxRadii[1] + boxRadii[2];
1900
+ NSUInteger expandedMinX = minX > sampleExtent ? minX - sampleExtent : 0;
1901
+ NSUInteger expandedMaxX = MIN((NSUInteger)width, maxX + sampleExtent);
1902
+ NSUInteger expandedMinY = minY > sampleExtent ? minY - sampleExtent : 0;
1903
+ NSUInteger expandedMaxY = MIN((NSUInteger)height, maxY + sampleExtent);
1793
1904
  if (expandedMaxX <= expandedMinX || expandedMaxY <= expandedMinY) return YES;
1794
1905
 
1795
1906
  NSUInteger regionWidth = expandedMaxX - expandedMinX;
@@ -1797,11 +1908,13 @@ static BOOL NativeSdkPacketApplyBlur(NSDictionary *effect, CGFloat opacity, CGCo
1797
1908
  size_t regionBytesPerRow = regionWidth * 4;
1798
1909
  size_t regionByteLength = regionBytesPerRow * regionHeight;
1799
1910
  NSMutableData *sourceData = [NSMutableData dataWithLength:regionByteLength];
1800
- NSMutableData *horizontalData = [NSMutableData dataWithLength:regionByteLength];
1801
- if (!sourceData || !horizontalData) return NO;
1911
+ NSMutableData *firstPassData = [NSMutableData dataWithLength:regionByteLength];
1912
+ NSMutableData *secondPassData = [NSMutableData dataWithLength:regionByteLength];
1913
+ if (!sourceData || !firstPassData || !secondPassData) return NO;
1802
1914
  uint8_t *destination = (uint8_t *)contextData;
1803
1915
  uint8_t *source = (uint8_t *)sourceData.mutableBytes;
1804
- uint8_t *horizontal = (uint8_t *)horizontalData.mutableBytes;
1916
+ uint8_t *firstPass = (uint8_t *)firstPassData.mutableBytes;
1917
+ uint8_t *secondPass = (uint8_t *)secondPassData.mutableBytes;
1805
1918
  for (NSUInteger row = 0; row < regionHeight; row++) {
1806
1919
  memcpy(
1807
1920
  source + row * regionBytesPerRow,
@@ -1810,91 +1923,37 @@ static BOOL NativeSdkPacketApplyBlur(NSDictionary *effect, CGFloat opacity, CGCo
1810
1923
  );
1811
1924
  }
1812
1925
 
1813
- /* Both passes keep the ORIGINAL clamped-window box average — the
1814
- * window shrinks at the surface edges exactly as before — but slide
1815
- * the window incrementally (add the entering sample, subtract the
1816
- * leaving one), turning O(region x radius) into O(region). The sums
1817
- * are the same integers the per-pixel rescan produced, so the output
1818
- * is byte-identical; a full-window dirty pass that repaints a
1819
- * backdrop-blurred popover stops costing milliseconds of scalar
1820
- * resampling. */
1821
- for (NSUInteger y = expandedMinY; y < expandedMaxY; y++) {
1822
- const uint8_t *sourceRow = source + (y - expandedMinY) * regionBytesPerRow;
1823
- uint8_t *horizontalRow = horizontal + (y - expandedMinY) * regionBytesPerRow;
1824
- NSUInteger windowMinX = minX > radius ? minX - radius : 0;
1825
- NSUInteger windowMaxX = MIN((NSUInteger)width - 1, minX + radius);
1826
- uint64_t sums[4] = {0, 0, 0, 0};
1827
- for (NSUInteger sx = windowMinX; sx <= windowMaxX; sx++) {
1828
- const uint8_t *pixel = sourceRow + (sx - expandedMinX) * 4;
1829
- sums[0] += pixel[0];
1830
- sums[1] += pixel[1];
1831
- sums[2] += pixel[2];
1832
- sums[3] += pixel[3];
1926
+ vImage_Buffer buffers[3] = {
1927
+ { .data = source, .height = regionHeight, .width = regionWidth, .rowBytes = regionBytesPerRow },
1928
+ { .data = firstPass, .height = regionHeight, .width = regionWidth, .rowBytes = regionBytesPerRow },
1929
+ { .data = secondPass, .height = regionHeight, .width = regionWidth, .rowBytes = regionBytesPerRow },
1930
+ };
1931
+ const Pixel_8888 edgeColor = {0, 0, 0, 0};
1932
+ for (NSUInteger pass = 0; pass < 3; pass++) {
1933
+ const vImage_Buffer *input = pass == 0 ? &buffers[0] : (pass == 1 ? &buffers[1] : &buffers[2]);
1934
+ const vImage_Buffer *output = pass == 1 ? &buffers[2] : &buffers[1];
1935
+ const uint32_t kernelSize = (uint32_t)(boxRadii[pass] * 2 + 1);
1936
+ if (kernelSize == 1) {
1937
+ memcpy(output->data, input->data, regionByteLength);
1938
+ continue;
1833
1939
  }
1940
+ const vImage_Error error = vImageBoxConvolve_ARGB8888(
1941
+ input, output, NULL, 0, 0, kernelSize, kernelSize, edgeColor, kvImageEdgeExtend
1942
+ );
1943
+ if (error != kvImageNoError) return NO;
1944
+ }
1945
+
1946
+ /* The third pass lands in firstPass. Preserve command opacity by
1947
+ * mixing that Gaussian approximation with the untouched backdrop. */
1948
+ for (NSUInteger y = minY; y < maxY; y++) {
1949
+ const NSUInteger regionY = y - expandedMinY;
1834
1950
  for (NSUInteger x = minX; x < maxX; x++) {
1835
- NSUInteger sampleMinX = x > radius ? x - radius : 0;
1836
- NSUInteger sampleMaxX = MIN((NSUInteger)width - 1, x + radius);
1837
- while (windowMaxX < sampleMaxX) {
1838
- windowMaxX += 1;
1839
- const uint8_t *pixel = sourceRow + (windowMaxX - expandedMinX) * 4;
1840
- sums[0] += pixel[0];
1841
- sums[1] += pixel[1];
1842
- sums[2] += pixel[2];
1843
- sums[3] += pixel[3];
1844
- }
1845
- while (windowMinX < sampleMinX) {
1846
- const uint8_t *pixel = sourceRow + (windowMinX - expandedMinX) * 4;
1847
- sums[0] -= pixel[0];
1848
- sums[1] -= pixel[1];
1849
- sums[2] -= pixel[2];
1850
- sums[3] -= pixel[3];
1851
- windowMinX += 1;
1852
- }
1853
- NSUInteger count = sampleMaxX - sampleMinX + 1;
1854
- uint8_t *out = horizontalRow + (x - expandedMinX) * 4;
1855
- out[0] = (uint8_t)(sums[0] / count);
1856
- out[1] = (uint8_t)(sums[1] / count);
1857
- out[2] = (uint8_t)(sums[2] / count);
1858
- out[3] = (uint8_t)(sums[3] / count);
1859
- }
1860
- }
1861
-
1862
- for (NSUInteger x = minX; x < maxX; x++) {
1863
- const uint8_t *horizontalColumn = horizontal + (x - expandedMinX) * 4;
1864
- NSUInteger windowMinY = minY > radius ? minY - radius : 0;
1865
- NSUInteger windowMaxY = MIN((NSUInteger)height - 1, minY + radius);
1866
- uint64_t sums[4] = {0, 0, 0, 0};
1867
- for (NSUInteger sy = windowMinY; sy <= windowMaxY; sy++) {
1868
- const uint8_t *pixel = horizontalColumn + (sy - expandedMinY) * regionBytesPerRow;
1869
- sums[0] += pixel[0];
1870
- sums[1] += pixel[1];
1871
- sums[2] += pixel[2];
1872
- sums[3] += pixel[3];
1873
- }
1874
- for (NSUInteger y = minY; y < maxY; y++) {
1875
- NSUInteger sampleMinY = y > radius ? y - radius : 0;
1876
- NSUInteger sampleMaxY = MIN((NSUInteger)height - 1, y + radius);
1877
- while (windowMaxY < sampleMaxY) {
1878
- windowMaxY += 1;
1879
- const uint8_t *pixel = horizontalColumn + (windowMaxY - expandedMinY) * regionBytesPerRow;
1880
- sums[0] += pixel[0];
1881
- sums[1] += pixel[1];
1882
- sums[2] += pixel[2];
1883
- sums[3] += pixel[3];
1884
- }
1885
- while (windowMinY < sampleMinY) {
1886
- const uint8_t *pixel = horizontalColumn + (windowMinY - expandedMinY) * regionBytesPerRow;
1887
- sums[0] -= pixel[0];
1888
- sums[1] -= pixel[1];
1889
- sums[2] -= pixel[2];
1890
- sums[3] -= pixel[3];
1891
- windowMinY += 1;
1892
- }
1893
- NSUInteger count = sampleMaxY - sampleMinY + 1;
1951
+ const NSUInteger regionX = x - expandedMinX;
1952
+ const size_t regionIndex = regionY * regionBytesPerRow + regionX * 4;
1894
1953
  uint8_t *out = destination + y * bytesPerRow + x * 4;
1895
1954
  for (NSUInteger channel = 0; channel < 4; channel++) {
1896
- CGFloat blurred = (CGFloat)(sums[channel] / count);
1897
- CGFloat original = (CGFloat)source[(y - expandedMinY) * regionBytesPerRow + (x - expandedMinX) * 4 + channel];
1955
+ const CGFloat original = (CGFloat)source[regionIndex + channel];
1956
+ const CGFloat blurred = (CGFloat)firstPass[regionIndex + channel];
1898
1957
  out[channel] = (uint8_t)llround(original + (blurred - original) * mix);
1899
1958
  }
1900
1959
  }
@@ -4033,7 +4092,7 @@ static const char *NativeSdkGpuShotDir(void) {
4033
4092
  * through the same CG code, clipped to the repaint region, and draw
4034
4093
  * as transient textured quads;
4035
4094
  * - blur reads the backdrop, so the pass splits around it: commit +
4036
- * wait, read the target back, run the existing scalar box blur on
4095
+ * wait, read the target back, run the vImage Gaussian approximation on
4037
4096
  * the readback, upload the blurred rect, and continue — a hybrid
4038
4097
  * frame, CPU only where the effect is inherently a backdrop read.
4039
4098
  * Scissor/dirty-rect semantics mirror the CPU path: full passes clear
@@ -4520,7 +4579,7 @@ static BOOL NativeSdkCompositeBlurWriteRegion(NSDictionary *command, CGFloat sca
4520
4579
  if (op->type == 0) continue;
4521
4580
  if (op->type == 3) {
4522
4581
  /* Blur sandwich: flush the pass, read the target back, run
4523
- * the reference scalar blur on the readback, upload the
4582
+ * the vImage Gaussian approximation on the readback, upload the
4524
4583
  * blurred rect, and continue compositing above it. */
4525
4584
  [encoder endEncoding];
4526
4585
  encoder = nil;
@@ -7277,6 +7336,333 @@ static BOOL NativeSdkScrollDriverCanConsumeHorizontally(NativeSdkScrollDriverVie
7277
7336
  @implementation NativeSdkShortcut
7278
7337
  @end
7279
7338
 
7339
+ /* ------------------------------------------------------- audio capture
7340
+ * Both native sources feed this one converter/quiescence target. AVAudioEngine
7341
+ * and ScreenCaptureKit normally hand us planar float PCM; the converter also
7342
+ * accepts interleaved float and signed-16 input, remixes mono/stereo, performs
7343
+ * linear sample-rate conversion, and emits <=20 ms signed-16 LE chunks. */
7344
+ @interface NativeSdkAudioCaptureTarget : NSObject {
7345
+ double _resamplePosition;
7346
+ double _resampleInputRate;
7347
+ uint32_t _resampleInputChannels;
7348
+ BOOL _resampleHasPrevious;
7349
+ BOOL _started;
7350
+ float _resamplePrevious[2];
7351
+ }
7352
+ @property(nonatomic, assign) int source;
7353
+ @property(nonatomic, assign) uint32_t sampleRate;
7354
+ @property(nonatomic, assign) uint8_t channels;
7355
+ @property(nonatomic, assign) native_sdk_appkit_audio_capture_push_t pushFn;
7356
+ @property(nonatomic, assign) void *pushContext;
7357
+ @property(nonatomic, strong) NSCondition *condition;
7358
+ @property(nonatomic, assign) BOOL active;
7359
+ @property(nonatomic, assign) NSUInteger inFlight;
7360
+ - (instancetype)initWithSource:(int)source sampleRate:(uint32_t)sampleRate channels:(uint8_t)channels pushFn:(native_sdk_appkit_audio_capture_push_t)pushFn pushContext:(void *)pushContext;
7361
+ - (BOOL)isCaptureActive;
7362
+ - (void)markInactive;
7363
+ - (void)deactivateAndWait;
7364
+ - (void)emitStarted;
7365
+ - (void)emitKind:(int)kind;
7366
+ - (void)consumeBufferList:(const AudioBufferList *)buffers format:(const AudioStreamBasicDescription *)format frames:(uint32_t)frames timestampNs:(uint64_t)timestampNs;
7367
+ @end
7368
+
7369
+ static float NativeSdkCaptureReadSample(const AudioBufferList *buffers, const AudioStreamBasicDescription *format, uint32_t frame, uint32_t channel) {
7370
+ if (!buffers || buffers->mNumberBuffers == 0) return 0.0f;
7371
+ const uint32_t inputChannels = MAX(1u, format->mChannelsPerFrame);
7372
+ const BOOL nonInterleaved = (format->mFormatFlags & kAudioFormatFlagIsNonInterleaved) != 0;
7373
+ const uint32_t bufferIndex = nonInterleaved ? MIN(channel, buffers->mNumberBuffers - 1) : 0;
7374
+ const AudioBuffer *buffer = &buffers->mBuffers[bufferIndex];
7375
+ if (!buffer->mData) return 0.0f;
7376
+ const uint32_t sampleIndex = nonInterleaved ? frame : frame * inputChannels + MIN(channel, inputChannels - 1);
7377
+ if ((format->mFormatFlags & kAudioFormatFlagIsFloat) && format->mBitsPerChannel == 32) {
7378
+ return ((const float *)buffer->mData)[sampleIndex];
7379
+ }
7380
+ if ((format->mFormatFlags & kAudioFormatFlagIsFloat) && format->mBitsPerChannel == 64) {
7381
+ return (float)((const double *)buffer->mData)[sampleIndex];
7382
+ }
7383
+ if ((format->mFormatFlags & kAudioFormatFlagIsSignedInteger) && format->mBitsPerChannel == 16) {
7384
+ return (float)((const int16_t *)buffer->mData)[sampleIndex] / 32768.0f;
7385
+ }
7386
+ return 0.0f;
7387
+ }
7388
+
7389
+ static float NativeSdkCaptureReadRemixedSample(const AudioBufferList *buffers, const AudioStreamBasicDescription *format, uint32_t frame, uint8_t outputChannels, uint32_t outputChannel) {
7390
+ const uint32_t inputChannels = MAX(1u, format->mChannelsPerFrame);
7391
+ if (outputChannels == 1) {
7392
+ float sample = 0.0f;
7393
+ for (uint32_t inputChannel = 0; inputChannel < inputChannels; inputChannel += 1) {
7394
+ sample += NativeSdkCaptureReadSample(buffers, format, frame, inputChannel);
7395
+ }
7396
+ return sample / (float)inputChannels;
7397
+ }
7398
+ return NativeSdkCaptureReadSample(buffers, format, frame, MIN(outputChannel, inputChannels - 1));
7399
+ }
7400
+
7401
+ @implementation NativeSdkAudioCaptureTarget
7402
+ - (instancetype)initWithSource:(int)source sampleRate:(uint32_t)sampleRate channels:(uint8_t)channels pushFn:(native_sdk_appkit_audio_capture_push_t)pushFn pushContext:(void *)pushContext {
7403
+ self = [super init];
7404
+ if (!self) return nil;
7405
+ self.source = source;
7406
+ self.sampleRate = sampleRate;
7407
+ self.channels = channels;
7408
+ self.pushFn = pushFn;
7409
+ self.pushContext = pushContext;
7410
+ self.condition = [[NSCondition alloc] init];
7411
+ self.active = YES;
7412
+ return self;
7413
+ }
7414
+ - (BOOL)isCaptureActive {
7415
+ [self.condition lock];
7416
+ BOOL value = self.active;
7417
+ [self.condition unlock];
7418
+ return value;
7419
+ }
7420
+ - (void)markInactive {
7421
+ [self.condition lock];
7422
+ self.active = NO;
7423
+ [self.condition unlock];
7424
+ }
7425
+ - (BOOL)beginPush {
7426
+ [self.condition lock];
7427
+ if (!self.active) { [self.condition unlock]; return NO; }
7428
+ self.inFlight += 1;
7429
+ [self.condition unlock];
7430
+ return YES;
7431
+ }
7432
+ - (BOOL)beginDataPush {
7433
+ [self.condition lock];
7434
+ if (!self.active || !_started) { [self.condition unlock]; return NO; }
7435
+ self.inFlight += 1;
7436
+ [self.condition unlock];
7437
+ return YES;
7438
+ }
7439
+ - (void)endPush {
7440
+ [self.condition lock];
7441
+ self.inFlight -= 1;
7442
+ if (self.inFlight == 0) [self.condition broadcast];
7443
+ [self.condition unlock];
7444
+ }
7445
+ - (void)deactivateAndWait {
7446
+ [self.condition lock];
7447
+ self.active = NO;
7448
+ while (self.inFlight > 0) [self.condition wait];
7449
+ [self.condition unlock];
7450
+ }
7451
+ - (void)emitStarted {
7452
+ [self.condition lock];
7453
+ if (!self.active || _started) { [self.condition unlock]; return; }
7454
+ self.inFlight += 1;
7455
+ [self.condition unlock];
7456
+
7457
+ int result = self.pushFn ? self.pushFn(self.pushContext, 0, self.source,
7458
+ self.sampleRate, self.channels, 0, 0, NULL, 0) : 1;
7459
+
7460
+ [self.condition lock];
7461
+ if (result == 1) self.active = NO;
7462
+ else if (self.active) _started = YES;
7463
+ self.inFlight -= 1;
7464
+ if (self.inFlight == 0) [self.condition broadcast];
7465
+ [self.condition unlock];
7466
+ }
7467
+ - (void)emitKind:(int)kind {
7468
+ if (![self beginPush]) return;
7469
+ int result = self.pushFn ? self.pushFn(self.pushContext, kind, self.source,
7470
+ self.sampleRate, self.channels, 0, 0, NULL, 0) : 1;
7471
+ [self endPush];
7472
+ if (result == 1) [self deactivateAndWait];
7473
+ }
7474
+ - (void)consumeBufferList:(const AudioBufferList *)buffers format:(const AudioStreamBasicDescription *)format frames:(uint32_t)frames timestampNs:(uint64_t)timestampNs {
7475
+ if (!buffers || !format || frames == 0 || format->mSampleRate <= 0 || ![self beginDataPush]) return;
7476
+ const uint32_t inputChannels = MAX(1u, format->mChannelsPerFrame);
7477
+ if (_resampleInputRate != format->mSampleRate || _resampleInputChannels != inputChannels) {
7478
+ _resamplePosition = 0.0;
7479
+ _resampleInputRate = format->mSampleRate;
7480
+ _resampleInputChannels = inputChannels;
7481
+ _resampleHasPrevious = NO;
7482
+ }
7483
+ const double step = format->mSampleRate / (double)self.sampleRate;
7484
+ const uint32_t chunkLimit = MAX(1u, self.sampleRate / 50u);
7485
+ int16_t output[1920];
7486
+ uint32_t chunkFrames = 0;
7487
+ uint64_t emittedFrames = 0;
7488
+ BOOL closed = NO;
7489
+ while (_resamplePosition <= (double)frames - 1.0) {
7490
+ const double flooredPosition = floor(_resamplePosition);
7491
+ const int64_t inputFrame = (int64_t)flooredPosition;
7492
+ const float fraction = (float)(_resamplePosition - flooredPosition);
7493
+ if (inputFrame < 0 && !_resampleHasPrevious) {
7494
+ _resamplePosition = 0.0;
7495
+ continue;
7496
+ }
7497
+ // A fractional sample at the end needs the next callback's first
7498
+ // frame. Defer it instead of repeating the current buffer's tail.
7499
+ if (inputFrame >= 0 && inputFrame + 1 >= frames && fraction > 0.0000001f) break;
7500
+
7501
+ for (uint32_t outChannel = 0; outChannel < self.channels; outChannel += 1) {
7502
+ const float first = inputFrame < 0
7503
+ ? _resamplePrevious[outChannel]
7504
+ : NativeSdkCaptureReadRemixedSample(buffers, format, (uint32_t)inputFrame, self.channels, outChannel);
7505
+ const float second = inputFrame < 0
7506
+ ? NativeSdkCaptureReadRemixedSample(buffers, format, 0, self.channels, outChannel)
7507
+ : (inputFrame + 1 < frames
7508
+ ? NativeSdkCaptureReadRemixedSample(buffers, format, (uint32_t)(inputFrame + 1), self.channels, outChannel)
7509
+ : first);
7510
+ float sample = first + (second - first) * fraction;
7511
+ sample = fmaxf(-1.0f, fminf(1.0f, sample));
7512
+ output[chunkFrames * self.channels + outChannel] = (int16_t)lrintf(sample * 32767.0f);
7513
+ }
7514
+ chunkFrames += 1;
7515
+ _resamplePosition += step;
7516
+
7517
+ if (chunkFrames == chunkLimit) {
7518
+ const size_t byteLen = (size_t)chunkFrames * self.channels * sizeof(int16_t);
7519
+ const int result = self.pushFn ? self.pushFn(self.pushContext, 1, self.source,
7520
+ self.sampleRate, self.channels, timestampNs + emittedFrames * NSEC_PER_SEC / self.sampleRate, chunkFrames,
7521
+ (const uint8_t *)output, byteLen) : 1;
7522
+ emittedFrames += chunkFrames;
7523
+ chunkFrames = 0;
7524
+ if (result == 1) {
7525
+ [self markInactive];
7526
+ closed = YES;
7527
+ break;
7528
+ }
7529
+ }
7530
+ }
7531
+ if (!closed && chunkFrames > 0) {
7532
+ const size_t byteLen = (size_t)chunkFrames * self.channels * sizeof(int16_t);
7533
+ const int result = self.pushFn ? self.pushFn(self.pushContext, 1, self.source,
7534
+ self.sampleRate, self.channels, timestampNs + emittedFrames * NSEC_PER_SEC / self.sampleRate, chunkFrames,
7535
+ (const uint8_t *)output, byteLen) : 1;
7536
+ if (result == 1) [self markInactive];
7537
+ }
7538
+ _resamplePosition -= frames;
7539
+ for (uint32_t outChannel = 0; outChannel < self.channels; outChannel += 1) {
7540
+ _resamplePrevious[outChannel] = NativeSdkCaptureReadRemixedSample(buffers, format, frames - 1, self.channels, outChannel);
7541
+ }
7542
+ _resampleHasPrevious = YES;
7543
+ [self endPush];
7544
+ }
7545
+ @end
7546
+
7547
+ @interface NativeSdkScreenAudioCapture : NSObject <SCStreamOutput, SCStreamDelegate>
7548
+ @property(nonatomic, strong) NativeSdkAudioCaptureTarget *target;
7549
+ @property(nonatomic, strong) SCStream *stream;
7550
+ @property(nonatomic, strong) dispatch_queue_t queue;
7551
+ @property(nonatomic, strong) NSLock *lifecycleLock;
7552
+ - (instancetype)initWithTarget:(NativeSdkAudioCaptureTarget *)target;
7553
+ - (void)start;
7554
+ - (void)stopAndWait;
7555
+ @end
7556
+
7557
+ @implementation NativeSdkScreenAudioCapture
7558
+ - (instancetype)initWithTarget:(NativeSdkAudioCaptureTarget *)target {
7559
+ self = [super init];
7560
+ if (!self) return nil;
7561
+ self.target = target;
7562
+ self.queue = dispatch_queue_create("dev.native-sdk.system-audio", DISPATCH_QUEUE_SERIAL);
7563
+ self.lifecycleLock = [[NSLock alloc] init];
7564
+ return self;
7565
+ }
7566
+ - (void)start {
7567
+ if (@available(macOS 13.0, *)) {
7568
+ __weak NativeSdkScreenAudioCapture *weakSelf = self;
7569
+ [SCShareableContent getShareableContentExcludingDesktopWindows:YES onScreenWindowsOnly:YES completionHandler:^(SCShareableContent *content, NSError *error) {
7570
+ NativeSdkScreenAudioCapture *strongSelf = weakSelf;
7571
+ if (!strongSelf || ![strongSelf.target isCaptureActive]) return;
7572
+ SCDisplay *display = content.displays.firstObject;
7573
+ if (error || !display) { [strongSelf.target emitKind:2]; return; }
7574
+ SCContentFilter *filter = [[SCContentFilter alloc] initWithDisplay:display excludingApplications:@[] exceptingWindows:@[]];
7575
+ SCStreamConfiguration *configuration = [[SCStreamConfiguration alloc] init];
7576
+ configuration.width = 2;
7577
+ configuration.height = 2;
7578
+ configuration.showsCursor = NO;
7579
+ configuration.capturesAudio = YES;
7580
+ configuration.excludesCurrentProcessAudio = NO;
7581
+ configuration.sampleRate = strongSelf.target.sampleRate;
7582
+ /* ScreenCaptureKit on Sonoma can accept a mono request but then
7583
+ * produce no audio sample buffers for a display stream. Capture
7584
+ * the system mix in its native stereo shape and let the shared
7585
+ * target converter downmix when the app requested mono. */
7586
+ configuration.channelCount = 2;
7587
+ configuration.minimumFrameInterval = CMTimeMake(1, 1);
7588
+ configuration.queueDepth = 1;
7589
+ SCStream *stream = [[SCStream alloc] initWithFilter:filter configuration:configuration delegate:strongSelf];
7590
+ NSError *outputError = nil;
7591
+ /* ScreenCaptureKit still creates a remote video queue for an
7592
+ * audio-enabled display stream. Register a tiny ignored screen
7593
+ * output so that queue stays valid; without it Sonoma reports a
7594
+ * recurring "stream output NOT found" error for every frame. */
7595
+ if (![stream addStreamOutput:strongSelf type:SCStreamOutputTypeScreen sampleHandlerQueue:strongSelf.queue error:&outputError] ||
7596
+ ![stream addStreamOutput:strongSelf type:SCStreamOutputTypeAudio sampleHandlerQueue:strongSelf.queue error:&outputError]) {
7597
+ [strongSelf.target emitKind:2];
7598
+ return;
7599
+ }
7600
+ /* Publish and start under the same lock stop uses to detach the
7601
+ * current stream. The shareable-content lookup is asynchronous:
7602
+ * without this final activity check, stop can observe stream=nil,
7603
+ * return, and then have this completion start an orphan capture. */
7604
+ [strongSelf.lifecycleLock lock];
7605
+ if (![strongSelf.target isCaptureActive]) {
7606
+ [strongSelf.lifecycleLock unlock];
7607
+ return;
7608
+ }
7609
+ strongSelf.stream = stream;
7610
+ [stream startCaptureWithCompletionHandler:^(NSError *startError) {
7611
+ if (startError) [strongSelf.target emitKind:2];
7612
+ else [strongSelf.target emitStarted];
7613
+ }];
7614
+ [strongSelf.lifecycleLock unlock];
7615
+ }];
7616
+ } else {
7617
+ [self.target emitKind:2];
7618
+ }
7619
+ }
7620
+ - (void)stream:(SCStream *)stream didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer ofType:(SCStreamOutputType)type API_AVAILABLE(macos(13.0)) {
7621
+ (void)stream;
7622
+ if (type != SCStreamOutputTypeAudio || !CMSampleBufferDataIsReady(sampleBuffer)) return;
7623
+ /* Query the exact AudioBufferList size. ScreenCaptureKit's Sonoma
7624
+ * buffers can require more storage than their two-channel ASBD suggests,
7625
+ * so a fixed "enough channels" allocation loses every audio sample with
7626
+ * kCMSampleBufferError_ArrayTooSmall. */
7627
+ size_t capacity = 0;
7628
+ OSStatus status = CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(sampleBuffer, &capacity,
7629
+ NULL, 0, NULL, NULL, kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment, NULL);
7630
+ if (status != noErr || capacity < sizeof(AudioBufferList) || capacity > 64 * 1024) return;
7631
+ AudioBufferList *buffers = malloc(capacity);
7632
+ if (!buffers) return;
7633
+ CMBlockBufferRef block = NULL;
7634
+ status = CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(sampleBuffer, NULL,
7635
+ buffers, capacity, NULL, NULL, kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment, &block);
7636
+ const AudioStreamBasicDescription *format = CMAudioFormatDescriptionGetStreamBasicDescription((CMAudioFormatDescriptionRef)CMSampleBufferGetFormatDescription(sampleBuffer));
7637
+ if (status == noErr && format) {
7638
+ [self.target consumeBufferList:buffers format:format frames:(uint32_t)CMSampleBufferGetNumSamples(sampleBuffer) timestampNs:NativeSdkTimestampNanoseconds()];
7639
+ }
7640
+ if (block) CFRelease(block);
7641
+ free(buffers);
7642
+ }
7643
+ - (void)stream:(SCStream *)stream didStopWithError:(NSError *)error API_AVAILABLE(macos(12.3)) {
7644
+ (void)stream; (void)error;
7645
+ [self.target emitKind:2];
7646
+ }
7647
+ - (void)stopAndWait {
7648
+ [self.target deactivateAndWait];
7649
+ if (@available(macOS 13.0, *)) {
7650
+ /* Detach under the startup lock. Once this unlocks, an in-flight
7651
+ * shareable-content completion either published its stream here (and
7652
+ * we stop it below), or sees the inactive target and cannot start. */
7653
+ [self.lifecycleLock lock];
7654
+ SCStream *stream = self.stream;
7655
+ self.stream = nil;
7656
+ [self.lifecycleLock unlock];
7657
+ if (stream) {
7658
+ dispatch_semaphore_t done = dispatch_semaphore_create(0);
7659
+ [stream stopCaptureWithCompletionHandler:^(NSError *error) { (void)error; dispatch_semaphore_signal(done); }];
7660
+ dispatch_semaphore_wait(done, dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC));
7661
+ }
7662
+ }
7663
+ }
7664
+ @end
7665
+
7280
7666
  @implementation NativeSdkAppKitHost
7281
7667
 
7282
7668
  - (instancetype)initWithAppName:(NSString *)appName displayName:(NSString *)displayName version:(NSString *)version aboutDescription:(NSString *)aboutDescription hasWebContent:(BOOL)hasWebContent windowTitle:(NSString *)windowTitle bundleIdentifier:(NSString *)bundleIdentifier iconPath:(NSString *)iconPath windowLabel:(NSString *)windowLabel x:(double)x y:(double)y width:(double)width height:(double)height restoreFrame:(BOOL)restoreFrame resizable:(BOOL)resizable titlebarStyle:(int)titlebarStyle showPolicy:(int)showPolicy windowFlags:(uint32_t)windowFlags {
@@ -7399,6 +7785,12 @@ static BOOL NativeSdkScrollDriverCanConsumeHorizontally(NativeSdkScrollDriverVie
7399
7785
  if ((windowFlags & (1u << 1)) != 0) window.level = NSFloatingWindowLevel;
7400
7786
  if ((windowFlags & (1u << 2)) != 0) window.ignoresMouseEvents = YES;
7401
7787
  if ((windowFlags & (1u << 3)) != 0) [self.passiveShowWindows addObject:key];
7788
+ if ((windowFlags & (1u << 4)) != 0) {
7789
+ NSWindowCollectionBehavior behavior = window.collectionBehavior;
7790
+ behavior &= ~(NSWindowCollectionBehaviorFullScreenPrimary | NSWindowCollectionBehaviorFullScreenAuxiliary);
7791
+ window.collectionBehavior = behavior | NSWindowCollectionBehaviorFullScreenNone;
7792
+ [window standardWindowButton:NSWindowZoomButton].enabled = NO;
7793
+ }
7402
7794
  [window setTitle:(title.length > 0 ? title : self.appName)];
7403
7795
  if (titlebarStyle == 1 || titlebarStyle == 2) {
7404
7796
  window.titlebarAppearsTransparent = YES;
@@ -7488,12 +7880,14 @@ static BOOL NativeSdkScrollDriverCanConsumeHorizontally(NativeSdkScrollDriverVie
7488
7880
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)NSEC_PER_SEC), dispatch_get_main_queue(), ^{
7489
7881
  [weakSelf showDeferredWindowIfPending:windowId reason:"fallback-deadline"];
7490
7882
  });
7883
+ } else if (showPolicy == 2) {
7884
+ [self.policyHiddenWindows addObject:key];
7491
7885
  }
7492
7886
  if (makeMain) {
7493
7887
  self.window = window;
7494
7888
  self.delegate = delegate;
7495
7889
  self.windowLabel = label.length > 0 ? label : @"main";
7496
- } else if (showPolicy != 1) {
7890
+ } else if (showPolicy == 0) {
7497
7891
  [self orderWindowForImplicitShow:windowId];
7498
7892
  }
7499
7893
  return YES;
@@ -7510,7 +7904,7 @@ static BOOL NativeSdkScrollDriverCanConsumeHorizontally(NativeSdkScrollDriverVie
7510
7904
  if ([self.passiveShowWindows containsObject:@(windowId)]) {
7511
7905
  [window orderFront:nil];
7512
7906
  } else {
7513
- [NSApp activate];
7907
+ [NSApp activateIgnoringOtherApps:YES];
7514
7908
  [window makeKeyAndOrderFront:nil];
7515
7909
  }
7516
7910
  }
@@ -7551,6 +7945,8 @@ static BOOL NativeSdkScrollDriverCanConsumeHorizontally(NativeSdkScrollDriverVie
7551
7945
 
7552
7946
  - (void)dealloc {
7553
7947
  [self invalidateAppTimers];
7948
+ [self audioCaptureStopSource:0];
7949
+ [self audioCaptureStopSource:1];
7554
7950
  [self audioStop];
7555
7951
  [self videoStop];
7556
7952
  /* The vDSP plan outlives individual playbacks (created lazily
@@ -7580,7 +7976,8 @@ static BOOL NativeSdkScrollDriverCanConsumeHorizontally(NativeSdkScrollDriverVie
7580
7976
  // An explicit focus overrides a pending present-before-show defer:
7581
7977
  // the runtime asked for the window NOW.
7582
7978
  [self.deferredShowWindows removeObjectForKey:@(windowId)];
7583
- [NSApp activate];
7979
+ [self.policyHiddenWindows removeObject:@(windowId)];
7980
+ [NSApp activateIgnoringOtherApps:YES];
7584
7981
  [window makeKeyAndOrderFront:nil];
7585
7982
  [self emitWindowFrameForWindowId:windowId open:YES];
7586
7983
  [self scheduleFrame];
@@ -7618,6 +8015,9 @@ static BOOL NativeSdkScrollDriverCanConsumeHorizontally(NativeSdkScrollDriverVie
7618
8015
  - (void)hideWindowWithId:(uint64_t)windowId {
7619
8016
  NSWindow *window = self.windows[@(windowId)];
7620
8017
  if (!window) return;
8018
+ // Hiding is an explicit policy decision and therefore supersedes a
8019
+ // pending first-present reveal and its fallback deadline.
8020
+ [self.deferredShowWindows removeObjectForKey:@(windowId)];
7621
8021
  [self.policyHiddenWindows addObject:@(windowId)];
7622
8022
  [window orderOut:nil];
7623
8023
  [self emitWindowFrameForWindowId:windowId open:YES];
@@ -9207,6 +9607,11 @@ static void NativeSdkApplyProcessDisplayName(NSString *displayName) {
9207
9607
  }];
9208
9608
  }
9209
9609
 
9610
+ - (void)menuWillOpen:(NSMenu *)menu {
9611
+ if (!self.statusItem || menu != self.statusMenu) return;
9612
+ [self emitStatusCommand:self.statusOpenCommand];
9613
+ }
9614
+
9210
9615
  - (void)setMenusWithTitles:(const char *const *)menuTitles titleLengths:(const size_t *)menuTitleLengths count:(size_t)menuCount itemMenuIndices:(const uint32_t *)itemMenuIndices itemLabels:(const char *const *)itemLabels itemLabelLengths:(const size_t *)itemLabelLengths itemCommands:(const char *const *)itemCommands itemCommandLengths:(const size_t *)itemCommandLengths itemKeys:(const char *const *)itemKeys itemKeyLengths:(const size_t *)itemKeyLengths itemModifiers:(const uint32_t *)itemModifiers itemSeparators:(const int *)itemSeparators itemEnabled:(const int *)itemEnabled itemChecked:(const int *)itemChecked itemCount:(size_t)itemCount {
9211
9616
  if (menuCount == 0) {
9212
9617
  [self buildMenuBar];
@@ -9255,7 +9660,7 @@ static void NativeSdkApplyProcessDisplayName(NSString *displayName) {
9255
9660
  // Present-before-show: a deferred startup window stays ordered out
9256
9661
  // here and appears when its first canvas present lands (or the
9257
9662
  // create-time fallback deadline fires).
9258
- if (!self.deferredShowWindows[@1]) {
9663
+ if (!self.deferredShowWindows[@1] && ![self.policyHiddenWindows containsObject:@1]) {
9259
9664
  [self orderWindowForImplicitShow:1];
9260
9665
  }
9261
9666
  if (!self.shortcutEventMonitor) {
@@ -9381,6 +9786,8 @@ static void NativeSdkApplyProcessDisplayName(NSString *displayName) {
9381
9786
  [self.timer invalidate];
9382
9787
  self.timer = nil;
9383
9788
  [self invalidateAppTimers];
9789
+ [self audioCaptureStopSource:0];
9790
+ [self audioCaptureStopSource:1];
9384
9791
  [self audioStop];
9385
9792
  [self videoStop];
9386
9793
  if (self.shortcutEventMonitor) {
@@ -10420,6 +10827,90 @@ static int NativeSdkSpectrumComputeBands(native_sdk_spectrum_tap_state_t *state,
10420
10827
  return 1;
10421
10828
  }
10422
10829
 
10830
+ - (void)startMicrophoneCaptureTarget:(NativeSdkAudioCaptureTarget *)target {
10831
+ if (![target isCaptureActive] || self.microphoneCaptureTarget != target) return;
10832
+ AVAudioEngine *engine = [[AVAudioEngine alloc] init];
10833
+ AVAudioInputNode *input = engine.inputNode;
10834
+ AVAudioFormat *inputFormat = [input outputFormatForBus:0];
10835
+ if (!input || inputFormat.channelCount == 0 || inputFormat.sampleRate <= 0) {
10836
+ [target emitKind:2];
10837
+ return;
10838
+ }
10839
+ __weak NativeSdkAudioCaptureTarget *weakTarget = target;
10840
+ [input installTapOnBus:0 bufferSize:480 format:nil block:^(AVAudioPCMBuffer *buffer, AVAudioTime *when) {
10841
+ (void)when;
10842
+ NativeSdkAudioCaptureTarget *strongTarget = weakTarget;
10843
+ if (!strongTarget) return;
10844
+ [strongTarget consumeBufferList:buffer.audioBufferList format:buffer.format.streamDescription frames:(uint32_t)buffer.frameLength timestampNs:NativeSdkTimestampNanoseconds()];
10845
+ }];
10846
+ [engine prepare];
10847
+ NSError *error = nil;
10848
+ if (![engine startAndReturnError:&error]) {
10849
+ [input removeTapOnBus:0];
10850
+ [target emitKind:2];
10851
+ return;
10852
+ }
10853
+ self.microphoneCaptureEngine = engine;
10854
+ [target emitStarted];
10855
+ }
10856
+
10857
+ - (int)audioCaptureStartSource:(int)source sampleRate:(uint32_t)sampleRate channels:(uint8_t)channels pushFn:(native_sdk_appkit_audio_capture_push_t)pushFn pushContext:(void *)pushContext {
10858
+ if ((source != 0 && source != 1) || !pushFn ||
10859
+ (sampleRate != 16000 && sampleRate != 24000 && sampleRate != 48000) ||
10860
+ (channels != 1 && channels != 2)) return 0;
10861
+ [self audioCaptureStopSource:source];
10862
+ NativeSdkAudioCaptureTarget *target = [[NativeSdkAudioCaptureTarget alloc]
10863
+ initWithSource:source sampleRate:sampleRate channels:channels pushFn:pushFn pushContext:pushContext];
10864
+ if (!target) return 0;
10865
+ if (source == 0) {
10866
+ self.microphoneCaptureTarget = target;
10867
+ AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
10868
+ if (status == AVAuthorizationStatusAuthorized) {
10869
+ [self startMicrophoneCaptureTarget:target];
10870
+ } else if (status == AVAuthorizationStatusNotDetermined) {
10871
+ __weak NativeSdkAppKitHost *weakSelf = self;
10872
+ [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {
10873
+ dispatch_async(dispatch_get_main_queue(), ^{
10874
+ NativeSdkAppKitHost *strongSelf = weakSelf;
10875
+ if (!strongSelf || strongSelf.microphoneCaptureTarget != target || ![target isCaptureActive]) return;
10876
+ if (granted) [strongSelf startMicrophoneCaptureTarget:target];
10877
+ else [target emitKind:2];
10878
+ });
10879
+ }];
10880
+ } else {
10881
+ [target emitKind:2];
10882
+ }
10883
+ } else {
10884
+ self.systemCaptureTarget = target;
10885
+ NativeSdkScreenAudioCapture *capture = [[NativeSdkScreenAudioCapture alloc] initWithTarget:target];
10886
+ self.systemCapture = capture;
10887
+ [capture start];
10888
+ }
10889
+ return 1;
10890
+ }
10891
+
10892
+ - (int)audioCaptureStopSource:(int)source {
10893
+ if (source == 0) {
10894
+ NativeSdkAudioCaptureTarget *target = self.microphoneCaptureTarget;
10895
+ [target deactivateAndWait];
10896
+ AVAudioInputNode *input = self.microphoneCaptureEngine.inputNode;
10897
+ if (input) [input removeTapOnBus:0];
10898
+ [self.microphoneCaptureEngine stop];
10899
+ self.microphoneCaptureEngine = nil;
10900
+ self.microphoneCaptureTarget = nil;
10901
+ return target ? 1 : 0;
10902
+ }
10903
+ if (source == 1) {
10904
+ NativeSdkScreenAudioCapture *capture = self.systemCapture;
10905
+ [capture stopAndWait];
10906
+ [self.systemCaptureTarget deactivateAndWait];
10907
+ self.systemCapture = nil;
10908
+ self.systemCaptureTarget = nil;
10909
+ return capture ? 1 : 0;
10910
+ }
10911
+ return 0;
10912
+ }
10913
+
10423
10914
  /* ---------------------------------------------------- video player
10424
10915
  *
10425
10916
  * The app's single video player: one AVPlayer whose
@@ -11429,6 +11920,27 @@ static void NativeSdkVideoFittedSize(double naturalWidth, double naturalHeight,
11429
11920
  }
11430
11921
  }
11431
11922
 
11923
+ - (void)emitStatusCommand:(NSString *)command {
11924
+ if (command.length == 0) return;
11925
+ const char *bytes = command.UTF8String;
11926
+ [self emitEvent:(native_sdk_appkit_event_t){
11927
+ .kind = NATIVE_SDK_APPKIT_EVENT_TRAY_COMMAND,
11928
+ .window_id = [self activeCommandWindowId],
11929
+ .command_name = bytes,
11930
+ .command_name_len = [command lengthOfBytesUsingEncoding:NSUTF8StringEncoding],
11931
+ }];
11932
+ }
11933
+
11934
+ - (void)statusItemActivated:(id)sender {
11935
+ (void)sender;
11936
+ if ((NSEvent.modifierFlags & NSEventModifierFlagOption) != 0 && self.statusAlternateActivationCommand.length > 0) {
11937
+ [self emitStatusCommand:self.statusAlternateActivationCommand];
11938
+ return;
11939
+ }
11940
+ [self emitStatusCommand:self.statusActivationCommand];
11941
+ if (self.statusMenu) [self.statusItem popUpStatusItemMenu:self.statusMenu];
11942
+ }
11943
+
11432
11944
  @end
11433
11945
 
11434
11946
  static NSArray<NSString *> *NativeSdkPolicyListFromBytes(const char *bytes, size_t len, NSArray<NSString *> *fallback) {
@@ -11757,6 +12269,26 @@ int native_sdk_appkit_audio_set_volume(native_sdk_appkit_host_t *host, double vo
11757
12269
  return [object audioSetVolume:volume];
11758
12270
  }
11759
12271
 
12272
+ int native_sdk_appkit_audio_capture_start(native_sdk_appkit_host_t *host, int source, uint32_t sample_rate, uint8_t channels, native_sdk_appkit_audio_capture_push_t push_fn, void *push_context) {
12273
+ if (!host) return 0;
12274
+ NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
12275
+ return [object audioCaptureStartSource:source sampleRate:sample_rate channels:channels pushFn:push_fn pushContext:push_context];
12276
+ }
12277
+
12278
+ int native_sdk_appkit_audio_capture_stop(native_sdk_appkit_host_t *host, int source) {
12279
+ if (!host) return 0;
12280
+ NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
12281
+ return [object audioCaptureStopSource:source];
12282
+ }
12283
+
12284
+ int native_sdk_appkit_audio_capture_supported(native_sdk_appkit_host_t *host, int source) {
12285
+ (void)host;
12286
+ if (source == 0) return 1;
12287
+ if (source != 1) return 0;
12288
+ if (@available(macOS 13.0, *)) return NSClassFromString(@"SCStream") != nil;
12289
+ return 0;
12290
+ }
12291
+
11760
12292
  int native_sdk_appkit_video_load(native_sdk_appkit_host_t *host, const char *path, size_t path_len, uint64_t token, native_sdk_appkit_video_sink_push_t push_fn, void *push_context) {
11761
12293
  NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
11762
12294
  NSString *path_string = [[NSString alloc] initWithBytes:path length:path_len encoding:NSUTF8StringEncoding];
@@ -11974,6 +12506,13 @@ int native_sdk_appkit_minimize_window(native_sdk_appkit_host_t *host, uint64_t w
11974
12506
  return 1;
11975
12507
  }
11976
12508
 
12509
+ int native_sdk_appkit_hide_window(native_sdk_appkit_host_t *host, uint64_t window_id) {
12510
+ NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
12511
+ if (!object.windows[@(window_id)]) return 0;
12512
+ [object hideWindowWithId:window_id];
12513
+ return 1;
12514
+ }
12515
+
11977
12516
  int native_sdk_appkit_show_window(native_sdk_appkit_host_t *host, uint64_t window_id) {
11978
12517
  NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
11979
12518
  if (!object.windows[@(window_id)]) return 0;
@@ -11981,6 +12520,23 @@ int native_sdk_appkit_show_window(native_sdk_appkit_host_t *host, uint64_t windo
11981
12520
  return 1;
11982
12521
  }
11983
12522
 
12523
+ int native_sdk_appkit_set_dock_presence(native_sdk_appkit_host_t *host, int visible) {
12524
+ (void)host;
12525
+ NSApplicationActivationPolicy policy = visible ? NSApplicationActivationPolicyRegular : NSApplicationActivationPolicyAccessory;
12526
+ BOOL changed = [NSApp setActivationPolicy:policy];
12527
+ return changed || NSApp.activationPolicy == policy ? 1 : 0;
12528
+ }
12529
+
12530
+ int native_sdk_appkit_launch_at_login_status(native_sdk_appkit_host_t *host) {
12531
+ (void)host;
12532
+ return NativeSdkLaunchAtLoginStatus();
12533
+ }
12534
+
12535
+ int native_sdk_appkit_set_launch_at_login(native_sdk_appkit_host_t *host, int enabled) {
12536
+ (void)host;
12537
+ return NativeSdkSetLaunchAtLogin(enabled != 0);
12538
+ }
12539
+
11984
12540
  int native_sdk_appkit_set_window_close_policy(native_sdk_appkit_host_t *host, uint64_t window_id, int close_policy) {
11985
12541
  NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
11986
12542
  if (!object.windows[@(window_id)]) return 0;
@@ -12255,7 +12811,7 @@ int native_sdk_appkit_set_credential(native_sdk_appkit_host_t *host, const char
12255
12811
  @autoreleasepool {
12256
12812
  NSString *serviceString = NativeSdkStringFromBytes(service, service_len);
12257
12813
  NSString *accountString = NativeSdkStringFromBytes(account, account_len);
12258
- if (serviceString.length == 0 || accountString.length == 0 || !secret || secret_len == 0) return 0;
12814
+ if (serviceString.length == 0 || accountString.length == 0 || (!secret && secret_len > 0)) return 0;
12259
12815
  NSData *secretData = [NSData dataWithBytes:secret length:secret_len];
12260
12816
  NSMutableDictionary *query = NativeSdkCredentialQuery(serviceString, accountString);
12261
12817
  NSDictionary *update = @{ (__bridge id)kSecValueData: secretData };
@@ -12264,7 +12820,7 @@ int native_sdk_appkit_set_credential(native_sdk_appkit_host_t *host, const char
12264
12820
  query[(__bridge id)kSecValueData] = secretData;
12265
12821
  status = SecItemAdd((__bridge CFDictionaryRef)query, NULL);
12266
12822
  }
12267
- return status == errSecSuccess ? 1 : 0;
12823
+ return NativeSdkCredentialStatus(status, -1);
12268
12824
  }
12269
12825
  }
12270
12826
 
@@ -12273,13 +12829,16 @@ size_t native_sdk_appkit_get_credential(native_sdk_appkit_host_t *host, const ch
12273
12829
  @autoreleasepool {
12274
12830
  NSString *serviceString = NativeSdkStringFromBytes(service, service_len);
12275
12831
  NSString *accountString = NativeSdkStringFromBytes(account, account_len);
12276
- if (serviceString.length == 0 || accountString.length == 0 || !buffer) return 0;
12832
+ if (serviceString.length == 0 || accountString.length == 0 || (!buffer && buffer_len > 0)) return SIZE_MAX - 1;
12277
12833
  NSMutableDictionary *query = NativeSdkCredentialQuery(serviceString, accountString);
12278
12834
  query[(__bridge id)kSecReturnData] = @YES;
12279
12835
  query[(__bridge id)kSecMatchLimit] = (__bridge id)kSecMatchLimitOne;
12280
12836
  CFTypeRef result = NULL;
12281
12837
  OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &result);
12282
- if (status != errSecSuccess || !result) return 0;
12838
+ if (status == errSecItemNotFound) return SIZE_MAX;
12839
+ if (status == errSecInteractionNotAllowed || status == errSecNotAvailable) return SIZE_MAX - 2;
12840
+ if (status == errSecAuthFailed || status == errSecUserCanceled || status == errSecMissingEntitlement) return SIZE_MAX - 3;
12841
+ if (status != errSecSuccess || !result) return SIZE_MAX - 1;
12283
12842
  NSData *data = CFBridgingRelease(result);
12284
12843
  if (data.length > buffer_len) return data.length;
12285
12844
  memcpy(buffer, data.bytes, data.length);
@@ -12295,7 +12854,26 @@ int native_sdk_appkit_delete_credential(native_sdk_appkit_host_t *host, const ch
12295
12854
  if (serviceString.length == 0 || accountString.length == 0) return 0;
12296
12855
  NSMutableDictionary *query = NativeSdkCredentialQuery(serviceString, accountString);
12297
12856
  OSStatus status = SecItemDelete((__bridge CFDictionaryRef)query);
12298
- return status == errSecSuccess ? 1 : 0;
12857
+ return NativeSdkCredentialStatus(status, 0);
12858
+ }
12859
+ }
12860
+
12861
+ size_t native_sdk_appkit_format_local_time(native_sdk_appkit_host_t *host, int64_t timestamp_ms, int style, char *buffer, size_t buffer_len) {
12862
+ (void)host;
12863
+ if (!buffer || buffer_len == 0 || style < 0 || style > 2) return 0;
12864
+ @autoreleasepool {
12865
+ NSDate *date = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)timestamp_ms / 1000.0];
12866
+ if (!date) return 0;
12867
+ NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
12868
+ formatter.locale = [NSLocale autoupdatingCurrentLocale];
12869
+ formatter.timeZone = [NSTimeZone localTimeZone];
12870
+ formatter.dateStyle = (style == 0 || style == 2) ? NSDateFormatterShortStyle : NSDateFormatterNoStyle;
12871
+ formatter.timeStyle = (style == 1 || style == 2) ? NSDateFormatterMediumStyle : NSDateFormatterNoStyle;
12872
+ NSString *text = [formatter stringFromDate:date];
12873
+ NSData *utf8 = [text dataUsingEncoding:NSUTF8StringEncoding];
12874
+ if (!utf8 || utf8.length == 0 || utf8.length > buffer_len) return 0;
12875
+ memcpy(buffer, utf8.bytes, utf8.length);
12876
+ return utf8.length;
12299
12877
  }
12300
12878
  }
12301
12879
 
@@ -12433,43 +13011,315 @@ int native_sdk_appkit_show_message_dialog(native_sdk_appkit_host_t *host, const
12433
13011
  }
12434
13012
  }
12435
13013
 
12436
- void native_sdk_appkit_create_tray(native_sdk_appkit_host_t *host, const char *icon_path, size_t icon_path_len, const char *title, size_t title_len, const char *tooltip, size_t tooltip_len) {
13014
+ static NSImage *NativeSdkTrayImageWithOpacity(NSImage *source, double opacity) {
13015
+ if (!source) return nil;
13016
+ const CGFloat fraction = MAX(0.0, MIN(1.0, opacity));
13017
+ if (fraction >= 1.0) return source;
13018
+ NSImage *image = [[NSImage alloc] initWithSize:source.size];
13019
+ [image lockFocus];
13020
+ [source drawInRect:NSMakeRect(0, 0, source.size.width, source.size.height)
13021
+ fromRect:NSZeroRect
13022
+ operation:NSCompositingOperationSourceOver
13023
+ fraction:fraction
13024
+ respectFlipped:YES
13025
+ hints:nil];
13026
+ [image unlockFocus];
13027
+ image.template = YES;
13028
+ return image;
13029
+ }
13030
+
13031
+ static void NativeSdkApplyTrayPresentation(NativeSdkAppKitHost *object, NSString *requestedTitle, double width, int tone, double iconOpacity, BOOL monospaced) {
13032
+ if (!object.statusItem) return;
13033
+ object.statusPresentationWidth = width;
13034
+ object.statusPresentationTone = tone;
13035
+ object.statusPresentationIconOpacity = iconOpacity;
13036
+ object.statusPresentationMonospaced = monospaced;
13037
+ NSString *title = requestedTitle ?: @"";
13038
+ if (!object.statusItemBaseImage && title.length == 0) {
13039
+ title = object.appName.length > 0 ? [object.appName substringToIndex:MIN(1, object.appName.length)] : @"Z";
13040
+ }
13041
+ NSFont *font = monospaced
13042
+ ? ([NSFont fontWithName:@"Geist Mono" size:11] ?: [NSFont monospacedDigitSystemFontOfSize:11 weight:NSFontWeightRegular])
13043
+ : [NSFont systemFontOfSize:11];
13044
+ NSStatusBarButton *button = object.statusItem.button;
13045
+ if (tone == 0) {
13046
+ button.title = title;
13047
+ button.font = font;
13048
+ button.contentTintColor = nil;
13049
+ } else {
13050
+ NSColor *color = tone == 1 ? NSColor.systemOrangeColor : NSColor.systemRedColor;
13051
+ button.attributedTitle = [[NSAttributedString alloc] initWithString:title attributes:@{
13052
+ NSForegroundColorAttributeName: color,
13053
+ NSFontAttributeName: font,
13054
+ }];
13055
+ button.contentTintColor = color;
13056
+ }
13057
+ button.image = NativeSdkTrayImageWithOpacity(object.statusItemBaseImage, iconOpacity);
13058
+ object.statusItem.length = width > 0 ? width : (requestedTitle.length > 0 ? NSVariableStatusItemLength : NSSquareStatusItemLength);
13059
+ }
13060
+
13061
+ void native_sdk_appkit_create_tray(native_sdk_appkit_host_t *host, const char *icon_path, size_t icon_path_len, const char *title, size_t title_len, const char *tooltip, size_t tooltip_len, double width, int tone, double icon_opacity, int monospaced, 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) {
12437
13062
  NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
12438
13063
  @autoreleasepool {
12439
13064
  if (object.statusItem) {
12440
13065
  [[NSStatusBar systemStatusBar] removeStatusItem:object.statusItem];
12441
13066
  }
12442
- // A titled menu-bar extra needs variable width; icon-only status
12443
- // items keep the classic square well.
13067
+ object.statusMenu = nil;
12444
13068
  BOOL hasTitle = title != NULL && title_len > 0;
12445
13069
  object.statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:hasTitle ? NSVariableStatusItemLength : NSSquareStatusItemLength];
13070
+ object.statusItemBaseImage = nil;
12446
13071
 
12447
13072
  if (icon_path && icon_path_len > 0) {
12448
13073
  NSString *path = [[NSString alloc] initWithBytes:icon_path length:icon_path_len encoding:NSUTF8StringEncoding];
12449
- NSImage *image = [[NSImage alloc] initWithContentsOfFile:path];
13074
+ NSImage *image = [[NSImage alloc] initWithContentsOfFile:NativeSdkResolvedAssetFilePath(path)];
12450
13075
  if (image) {
12451
13076
  image.template = YES;
12452
13077
  image.size = NSMakeSize(18, 18);
12453
- object.statusItem.button.image = image;
13078
+ object.statusItemBaseImage = image;
12454
13079
  }
12455
13080
  }
12456
- if (hasTitle) {
12457
- object.statusItem.button.title = [[NSString alloc] initWithBytes:title length:title_len encoding:NSUTF8StringEncoding] ?: @"";
12458
- }
12459
- if (!object.statusItem.button.image && object.statusItem.button.title.length == 0) {
12460
- object.statusItem.button.title = object.appName.length > 0 ? [object.appName substringToIndex:MIN(1, object.appName.length)] : @"Z";
12461
- }
13081
+ NSString *titleString = hasTitle ? ([[NSString alloc] initWithBytes:title length:title_len encoding:NSUTF8StringEncoding] ?: @"") : @"";
12462
13082
  if (tooltip && tooltip_len > 0) {
12463
13083
  object.statusItem.button.toolTip = [[NSString alloc] initWithBytes:tooltip length:tooltip_len encoding:NSUTF8StringEncoding];
12464
13084
  }
13085
+ object.statusActivationCommand = activation_command ? ([[NSString alloc] initWithBytes:activation_command length:activation_command_len encoding:NSUTF8StringEncoding] ?: @"") : @"";
13086
+ object.statusAlternateActivationCommand = alternate_activation_command ? ([[NSString alloc] initWithBytes:alternate_activation_command length:alternate_activation_command_len encoding:NSUTF8StringEncoding] ?: @"") : @"";
13087
+ object.statusOpenCommand = open_command ? ([[NSString alloc] initWithBytes:open_command length:open_command_len encoding:NSUTF8StringEncoding] ?: @"") : @"";
13088
+ if (object.statusActivationCommand.length > 0 || object.statusAlternateActivationCommand.length > 0) {
13089
+ object.statusItem.button.target = object;
13090
+ object.statusItem.button.action = @selector(statusItemActivated:);
13091
+ [object.statusItem.button sendActionOn:NSEventMaskLeftMouseUp];
13092
+ }
13093
+ NativeSdkApplyTrayPresentation(object, titleString, width, tone, icon_opacity, monospaced != 0);
12465
13094
  }
12466
13095
  }
12467
13096
 
12468
- void native_sdk_appkit_update_tray_menu(native_sdk_appkit_host_t *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) {
13097
+ enum {
13098
+ NativeSdkTrayRoleCommand = 0,
13099
+ NativeSdkTrayRoleInfo = 1,
13100
+ NativeSdkTrayRoleHeader = 2,
13101
+ NativeSdkTrayRoleHero = 3,
13102
+ NativeSdkTrayRoleAgent = 4,
13103
+ NativeSdkTrayRoleContext = 5,
13104
+ };
13105
+
13106
+ static NSView *NativeSdkTrayHeroView(NSString *headline, NSString *quota) {
13107
+ NSArray<NSString *> *parts = [headline componentsSeparatedByString:@"\n"];
13108
+ NSString *value = parts.count > 0 ? parts[0] : @"";
13109
+ NSString *account = parts.count > 1 ? parts[1] : @"";
13110
+ NSString *stale = parts.count > 2 ? parts[2] : @"";
13111
+ NSString *reset = parts.count > 3 ? parts[3] : @"";
13112
+ CGFloat height = quota.length > 0 ? 56 : 32;
13113
+ if (stale.length > 0) height += 14;
13114
+ NSView *view = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 320, height)];
13115
+ NSTextField *amount = [NSTextField labelWithString:value ?: @""];
13116
+ amount.font = [NSFont fontWithName:@"Geist Mono" size:20] ?: [NSFont monospacedDigitSystemFontOfSize:20 weight:NSFontWeightMedium];
13117
+ amount.translatesAutoresizingMaskIntoConstraints = NO;
13118
+ NSTextField *caption = [NSTextField labelWithString:(reset.length > 0 ? [NSString stringWithFormat:@"today · %@", reset] : @"today")];
13119
+ caption.font = [NSFont systemFontOfSize:11];
13120
+ caption.textColor = NSColor.secondaryLabelColor;
13121
+ caption.translatesAutoresizingMaskIntoConstraints = NO;
13122
+ [view addSubview:amount];
13123
+ [view addSubview:caption];
13124
+ [NSLayoutConstraint activateConstraints:@[
13125
+ [amount.leadingAnchor constraintEqualToAnchor:view.leadingAnchor constant:14],
13126
+ [amount.topAnchor constraintEqualToAnchor:view.topAnchor constant:3],
13127
+ [caption.leadingAnchor constraintEqualToAnchor:amount.trailingAnchor constant:6],
13128
+ [caption.firstBaselineAnchor constraintEqualToAnchor:amount.firstBaselineAnchor],
13129
+ ]];
13130
+ if (account.length > 0) {
13131
+ NSTextField *accountLabel = [NSTextField labelWithString:account];
13132
+ accountLabel.font = [NSFont systemFontOfSize:10];
13133
+ accountLabel.textColor = NSColor.secondaryLabelColor;
13134
+ accountLabel.lineBreakMode = NSLineBreakByTruncatingTail;
13135
+ accountLabel.translatesAutoresizingMaskIntoConstraints = NO;
13136
+ [view addSubview:accountLabel];
13137
+ [NSLayoutConstraint activateConstraints:@[
13138
+ [accountLabel.trailingAnchor constraintEqualToAnchor:view.trailingAnchor constant:-14],
13139
+ [accountLabel.firstBaselineAnchor constraintEqualToAnchor:caption.firstBaselineAnchor],
13140
+ [accountLabel.leadingAnchor constraintGreaterThanOrEqualToAnchor:caption.trailingAnchor constant:12],
13141
+ ]];
13142
+ }
13143
+ if (quota.length > 0) {
13144
+ NSProgressIndicator *progress = [[NSProgressIndicator alloc] initWithFrame:NSZeroRect];
13145
+ progress.style = NSProgressIndicatorStyleBar;
13146
+ progress.controlSize = NSControlSizeMini;
13147
+ progress.indeterminate = NO;
13148
+ progress.minValue = 0;
13149
+ progress.maxValue = 100;
13150
+ NSScanner *scanner = [NSScanner scannerWithString:quota];
13151
+ double percent = 0;
13152
+ [scanner scanDouble:&percent];
13153
+ progress.doubleValue = MIN(MAX(percent, 0), 100);
13154
+ progress.translatesAutoresizingMaskIntoConstraints = NO;
13155
+ NSTextField *quotaLabel = [NSTextField labelWithString:quota];
13156
+ quotaLabel.font = [NSFont systemFontOfSize:11];
13157
+ quotaLabel.textColor = NSColor.secondaryLabelColor;
13158
+ quotaLabel.translatesAutoresizingMaskIntoConstraints = NO;
13159
+ [view addSubview:progress];
13160
+ [view addSubview:quotaLabel];
13161
+ [NSLayoutConstraint activateConstraints:@[
13162
+ [progress.leadingAnchor constraintEqualToAnchor:view.leadingAnchor constant:14],
13163
+ [progress.trailingAnchor constraintEqualToAnchor:view.trailingAnchor constant:-14],
13164
+ [progress.topAnchor constraintEqualToAnchor:amount.bottomAnchor constant:4],
13165
+ [progress.heightAnchor constraintEqualToConstant:5],
13166
+ [quotaLabel.leadingAnchor constraintEqualToAnchor:view.leadingAnchor constant:14],
13167
+ [quotaLabel.topAnchor constraintEqualToAnchor:progress.bottomAnchor constant:2],
13168
+ ]];
13169
+ }
13170
+ if (stale.length > 0) {
13171
+ NSTextField *staleLabel = [NSTextField labelWithString:stale];
13172
+ staleLabel.font = [NSFont systemFontOfSize:10];
13173
+ staleLabel.textColor = NSColor.tertiaryLabelColor;
13174
+ staleLabel.translatesAutoresizingMaskIntoConstraints = NO;
13175
+ [view addSubview:staleLabel];
13176
+ [NSLayoutConstraint activateConstraints:@[
13177
+ [staleLabel.leadingAnchor constraintEqualToAnchor:view.leadingAnchor constant:14],
13178
+ [staleLabel.bottomAnchor constraintEqualToAnchor:view.bottomAnchor constant:-6],
13179
+ ]];
13180
+ }
13181
+ view.accessibilityLabel = quota.length > 0 ? [NSString stringWithFormat:@"%@ today, %@", value ?: @"", quota] : [NSString stringWithFormat:@"%@ today", value ?: @""];
13182
+ view.accessibilityRole = NSAccessibilityGroupRole;
13183
+ return view;
13184
+ }
13185
+
13186
+ static NSView *NativeSdkTrayAgentsView(NativeSdkAppKitHost *object, const uint32_t *itemIds, NSArray<NSString *> *labels, NSArray<NSString *> *states, NSArray<NSNumber *> *enabled, NSArray<NSString *> *keys, NSArray<NSNumber *> *modifiers) {
13187
+ NSStackView *row = [[NSStackView alloc] initWithFrame:NSMakeRect(0, 0, 320, 32)];
13188
+ row.orientation = NSUserInterfaceLayoutOrientationHorizontal;
13189
+ row.alignment = NSLayoutAttributeCenterY;
13190
+ row.spacing = 8;
13191
+ row.edgeInsets = NSEdgeInsetsMake(5, 14, 5, 14);
13192
+ NSString *appearance = [NSApp.effectiveAppearance bestMatchFromAppearancesWithNames:@[NSAppearanceNameAqua, NSAppearanceNameDarkAqua]];
13193
+ BOOL dark = [appearance isEqualToString:NSAppearanceNameDarkAqua];
13194
+ NSColor *warningColor = dark ? NSColor.systemOrangeColor : [NSColor colorWithSRGBRed:0.54 green:0.23 blue:0.00 alpha:1.0];
13195
+ NSColor *successColor = dark ? NSColor.systemGreenColor : [NSColor colorWithSRGBRed:0.06 green:0.42 blue:0.20 alpha:1.0];
13196
+ for (NSUInteger index = 0; index < labels.count; index++) {
13197
+ NSString *state = states[index];
13198
+ // `detail` is presentation text as well as the semantic state. The
13199
+ // documented examples append a glyph ("configured ✓", "warning ⚠"),
13200
+ // so classify the leading token instead of requiring the whole label
13201
+ // to be the bare state name.
13202
+ BOOL configured = [state isEqualToString:@"configured"] || [state hasPrefix:@"configured "];
13203
+ BOOL warning = [state isEqualToString:@"warning"] || [state hasPrefix:@"warning "];
13204
+ NSString *title = [NSString stringWithFormat:@"%@ %@", configured ? @"✓" : warning ? @"⚠" : @"○", labels[index]];
13205
+ NSView *control = [[NSView alloc] initWithFrame:NSZeroRect];
13206
+ NSTextField *label = [NSTextField labelWithString:title];
13207
+ label.font = [NSFont systemFontOfSize:11];
13208
+ label.textColor = configured ? successColor : warning ? warningColor : NSColor.secondaryLabelColor;
13209
+ label.translatesAutoresizingMaskIntoConstraints = NO;
13210
+ label.accessibilityElement = NO;
13211
+ NSButton *button = [NSButton buttonWithTitle:@"" target:object action:@selector(trayMenuItemClicked:)];
13212
+ button.tag = itemIds[index];
13213
+ button.bordered = NO;
13214
+ button.transparent = YES;
13215
+ button.enabled = enabled[index].boolValue;
13216
+ NSString *key = keys[index];
13217
+ if (key.length > 0) {
13218
+ button.keyEquivalent = NativeSdkMenuKeyEquivalent(key);
13219
+ button.keyEquivalentModifierMask = NativeSdkMenuModifierFlags(modifiers[index].unsignedIntValue);
13220
+ }
13221
+ button.translatesAutoresizingMaskIntoConstraints = NO;
13222
+ button.accessibilityLabel = title;
13223
+ [control addSubview:label];
13224
+ [control addSubview:button];
13225
+ [NSLayoutConstraint activateConstraints:@[
13226
+ [label.leadingAnchor constraintEqualToAnchor:control.leadingAnchor],
13227
+ [label.trailingAnchor constraintEqualToAnchor:control.trailingAnchor],
13228
+ [label.centerYAnchor constraintEqualToAnchor:control.centerYAnchor],
13229
+ [button.leadingAnchor constraintEqualToAnchor:control.leadingAnchor],
13230
+ [button.trailingAnchor constraintEqualToAnchor:control.trailingAnchor],
13231
+ [button.topAnchor constraintEqualToAnchor:control.topAnchor],
13232
+ [button.bottomAnchor constraintEqualToAnchor:control.bottomAnchor],
13233
+ ]];
13234
+ [row addArrangedSubview:control];
13235
+ }
13236
+ [row.heightAnchor constraintEqualToConstant:32].active = YES;
13237
+ [row.widthAnchor constraintEqualToConstant:320].active = YES;
13238
+ return row;
13239
+ }
13240
+
13241
+ static NSView *NativeSdkTrayContextView(NSString *primary, NSString *secondary) {
13242
+ NSArray<NSString *> *parts = [secondary componentsSeparatedByString:@"\n"];
13243
+ NSString *quota = parts.count > 0 ? parts[0] : @"";
13244
+ NSString *windows = parts.count > 1 ? parts[1] : @"";
13245
+ NSView *view = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 320, 58)];
13246
+ NSTextField *primaryLabel = [NSTextField labelWithString:primary ?: @""];
13247
+ primaryLabel.font = [NSFont systemFontOfSize:11 weight:NSFontWeightMedium];
13248
+ primaryLabel.lineBreakMode = NSLineBreakByTruncatingTail;
13249
+ primaryLabel.translatesAutoresizingMaskIntoConstraints = NO;
13250
+ NSTextField *secondaryLabel = [NSTextField labelWithString:quota ?: @""];
13251
+ secondaryLabel.font = [NSFont systemFontOfSize:10];
13252
+ secondaryLabel.textColor = NSColor.secondaryLabelColor;
13253
+ secondaryLabel.translatesAutoresizingMaskIntoConstraints = NO;
13254
+ NSTextField *windowsLabel = [NSTextField labelWithString:windows ?: @""];
13255
+ windowsLabel.font = [NSFont systemFontOfSize:10];
13256
+ windowsLabel.textColor = NSColor.secondaryLabelColor;
13257
+ windowsLabel.translatesAutoresizingMaskIntoConstraints = NO;
13258
+ [view addSubview:primaryLabel];
13259
+ [view addSubview:secondaryLabel];
13260
+ [view addSubview:windowsLabel];
13261
+ [NSLayoutConstraint activateConstraints:@[
13262
+ [primaryLabel.leadingAnchor constraintEqualToAnchor:view.leadingAnchor constant:14],
13263
+ [primaryLabel.trailingAnchor constraintLessThanOrEqualToAnchor:view.trailingAnchor constant:-14],
13264
+ [primaryLabel.topAnchor constraintEqualToAnchor:view.topAnchor constant:6],
13265
+ [secondaryLabel.leadingAnchor constraintEqualToAnchor:view.leadingAnchor constant:14],
13266
+ [secondaryLabel.topAnchor constraintEqualToAnchor:primaryLabel.bottomAnchor constant:2],
13267
+ [windowsLabel.leadingAnchor constraintEqualToAnchor:view.leadingAnchor constant:14],
13268
+ [windowsLabel.topAnchor constraintEqualToAnchor:secondaryLabel.bottomAnchor constant:2],
13269
+ ]];
13270
+ view.accessibilityLabel = secondary.length > 0 ? [NSString stringWithFormat:@"%@, %@", primary ?: @"", [secondary stringByReplacingOccurrencesOfString:@"\n" withString:@", "]] : primary ?: @"";
13271
+ view.accessibilityRole = NSAccessibilityGroupRole;
13272
+ return view;
13273
+ }
13274
+
13275
+ static NSView *NativeSdkTrayReadoutView(NSString *label, NSString *value, BOOL isHeader) {
13276
+ NSFont *bodyFont = [NSFont menuFontOfSize:0];
13277
+ NSTextField *labelField = [NSTextField labelWithString:label ?: @""];
13278
+ labelField.font = isHeader ? [NSFont systemFontOfSize:bodyFont.pointSize - 2 weight:NSFontWeightSemibold] : bodyFont;
13279
+ labelField.textColor = isHeader ? NSColor.secondaryLabelColor : NSColor.labelColor;
13280
+ labelField.translatesAutoresizingMaskIntoConstraints = NO;
13281
+ NSView *row = [[NSView alloc] initWithFrame:NSZeroRect];
13282
+ row.translatesAutoresizingMaskIntoConstraints = NO;
13283
+ [row addSubview:labelField];
13284
+ NSMutableArray<NSLayoutConstraint *> *constraints = [NSMutableArray arrayWithArray:@[
13285
+ [labelField.leadingAnchor constraintEqualToAnchor:row.leadingAnchor constant:14],
13286
+ [labelField.topAnchor constraintEqualToAnchor:row.topAnchor constant:3],
13287
+ [labelField.bottomAnchor constraintEqualToAnchor:row.bottomAnchor constant:-3],
13288
+ ]];
13289
+ if (value.length > 0) {
13290
+ NSTextField *valueField = [NSTextField labelWithString:value];
13291
+ valueField.font = [NSFont monospacedDigitSystemFontOfSize:bodyFont.pointSize weight:NSFontWeightRegular];
13292
+ valueField.textColor = NSColor.secondaryLabelColor;
13293
+ valueField.translatesAutoresizingMaskIntoConstraints = NO;
13294
+ [row addSubview:valueField];
13295
+ [constraints addObjectsFromArray:@[
13296
+ [valueField.trailingAnchor constraintEqualToAnchor:row.trailingAnchor constant:-14],
13297
+ [valueField.firstBaselineAnchor constraintEqualToAnchor:labelField.firstBaselineAnchor],
13298
+ [valueField.leadingAnchor constraintGreaterThanOrEqualToAnchor:labelField.trailingAnchor constant:28],
13299
+ ]];
13300
+ row.accessibilityLabel = [NSString stringWithFormat:@"%@, %@", label ?: @"", value];
13301
+ } else {
13302
+ [constraints addObject:[labelField.trailingAnchor constraintLessThanOrEqualToAnchor:row.trailingAnchor constant:-14]];
13303
+ row.accessibilityLabel = label ?: @"";
13304
+ }
13305
+ [NSLayoutConstraint activateConstraints:constraints];
13306
+ row.accessibilityRole = NSAccessibilityStaticTextRole;
13307
+ return row;
13308
+ }
13309
+
13310
+ void native_sdk_appkit_update_tray_menu(native_sdk_appkit_host_t *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) {
12469
13311
  NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
12470
13312
  @autoreleasepool {
12471
13313
  if (!object.statusItem) return;
12472
- NSMenu *menu = [[NSMenu alloc] initWithTitle:@""];
13314
+ NSMenu *menu = object.statusMenu;
13315
+ if (menu == nil) {
13316
+ menu = [[NSMenu alloc] initWithTitle:@""];
13317
+ object.statusMenu = menu;
13318
+ } else {
13319
+ [menu removeAllItems];
13320
+ }
13321
+ menu.autoenablesItems = NO;
13322
+ NSMutableArray<NSView *> *readoutRows = [NSMutableArray array];
12473
13323
  for (size_t i = 0; i < count; i++) {
12474
13324
  if (separators[i]) {
12475
13325
  [menu addItem:[NSMenuItem separatorItem]];
@@ -12482,9 +13332,73 @@ void native_sdk_appkit_update_tray_menu(native_sdk_appkit_host_t *host, const ui
12482
13332
  item.tag = (NSInteger)item_ids[i];
12483
13333
  item.target = object;
12484
13334
  item.enabled = enabled_flags[i] != 0;
13335
+ if (keys[i] && key_lens[i] > 0) {
13336
+ NSString *key = [[NSString alloc] initWithBytes:keys[i] length:key_lens[i] encoding:NSUTF8StringEncoding] ?: @"";
13337
+ item.keyEquivalent = NativeSdkMenuKeyEquivalent(key);
13338
+ item.keyEquivalentModifierMask = NativeSdkMenuModifierFlags(modifiers[i]);
13339
+ }
13340
+ NSString *detail = details[i] && detail_lens[i] > 0 ? [[NSString alloc] initWithBytes:details[i] length:detail_lens[i] encoding:NSUTF8StringEncoding] : @"";
13341
+ if (roles[i] == NativeSdkTrayRoleHero) {
13342
+ item.action = NULL;
13343
+ item.target = nil;
13344
+ item.view = NativeSdkTrayHeroView(label, detail);
13345
+ [menu addItem:item];
13346
+ continue;
13347
+ }
13348
+ if (roles[i] == NativeSdkTrayRoleAgent) {
13349
+ NSMutableArray<NSString *> *agentLabels = [NSMutableArray array];
13350
+ NSMutableArray<NSString *> *agentStates = [NSMutableArray array];
13351
+ NSMutableArray<NSNumber *> *agentEnabled = [NSMutableArray array];
13352
+ NSMutableArray<NSString *> *agentKeys = [NSMutableArray array];
13353
+ NSMutableArray<NSNumber *> *agentModifiers = [NSMutableArray array];
13354
+ uint32_t agentIds[32] = {0};
13355
+ size_t agentCount = 0;
13356
+ while (i < count && roles[i] == NativeSdkTrayRoleAgent && agentCount < 32) {
13357
+ [agentLabels addObject:(labels[i] ? [[NSString alloc] initWithBytes:labels[i] length:label_lens[i] encoding:NSUTF8StringEncoding] : @"")];
13358
+ [agentStates addObject:(details[i] ? [[NSString alloc] initWithBytes:details[i] length:detail_lens[i] encoding:NSUTF8StringEncoding] : @"")];
13359
+ [agentEnabled addObject:@(enabled_flags[i] != 0)];
13360
+ [agentKeys addObject:(keys[i] ? ([[NSString alloc] initWithBytes:keys[i] length:key_lens[i] encoding:NSUTF8StringEncoding] ?: @"") : @"")];
13361
+ [agentModifiers addObject:@(modifiers[i])];
13362
+ agentIds[agentCount++] = item_ids[i];
13363
+ i++;
13364
+ }
13365
+ i--;
13366
+ item.action = NULL;
13367
+ item.target = nil;
13368
+ // The custom buttons own every agent equivalent. Leaving the
13369
+ // first row's equivalent on this actionless wrapper would let
13370
+ // NSMenu consume it before the button can dispatch its id.
13371
+ item.keyEquivalent = @"";
13372
+ item.keyEquivalentModifierMask = 0;
13373
+ item.view = NativeSdkTrayAgentsView(object, agentIds, agentLabels, agentStates, agentEnabled, agentKeys, agentModifiers);
13374
+ [menu addItem:item];
13375
+ continue;
13376
+ }
13377
+ if (roles[i] == NativeSdkTrayRoleContext) {
13378
+ item.action = NULL;
13379
+ item.target = nil;
13380
+ item.view = NativeSdkTrayContextView(label, detail);
13381
+ [menu addItem:item];
13382
+ continue;
13383
+ }
13384
+ if (roles[i] == NativeSdkTrayRoleHeader || roles[i] == NativeSdkTrayRoleInfo) {
13385
+ item.action = NULL;
13386
+ item.target = nil;
13387
+ NSView *view = NativeSdkTrayReadoutView(label, roles[i] == NativeSdkTrayRoleInfo ? detail : @"", roles[i] == NativeSdkTrayRoleHeader);
13388
+ item.view = view;
13389
+ [readoutRows addObject:view];
13390
+ }
12485
13391
  [menu addItem:item];
12486
13392
  }
12487
- object.statusItem.menu = menu;
13393
+ if (readoutRows.count > 0) {
13394
+ CGFloat widest = 0;
13395
+ for (NSView *row in readoutRows) widest = MAX(widest, row.fittingSize.width);
13396
+ for (NSView *row in readoutRows) [row.widthAnchor constraintEqualToConstant:widest].active = YES;
13397
+ }
13398
+ menu.delegate = object;
13399
+ if (object.statusActivationCommand.length == 0 && object.statusAlternateActivationCommand.length == 0) {
13400
+ object.statusItem.menu = menu;
13401
+ }
12488
13402
  }
12489
13403
  }
12490
13404
 
@@ -12492,17 +13406,23 @@ void native_sdk_appkit_update_tray_title(native_sdk_appkit_host_t *host, const c
12492
13406
  NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
12493
13407
  @autoreleasepool {
12494
13408
  if (!object.statusItem) return;
12495
- BOOL hasTitle = title != NULL && title_len > 0;
12496
- NSString *value = hasTitle ? ([[NSString alloc] initWithBytes:title length:title_len encoding:NSUTF8StringEncoding] ?: @"") : @"";
12497
- object.statusItem.button.title = value;
12498
- if (!object.statusItem.button.image && value.length == 0) {
12499
- // Same fallback as create: a bare status item must still show
12500
- // SOMETHING to stay clickable.
12501
- object.statusItem.button.title = object.appName.length > 0 ? [object.appName substringToIndex:MIN(1, object.appName.length)] : @"Z";
12502
- }
12503
- // Titled extras need variable width; icon-only ones keep the
12504
- // classic square well (mirrors create's length choice).
12505
- object.statusItem.length = object.statusItem.button.title.length > 0 ? NSVariableStatusItemLength : NSSquareStatusItemLength;
13409
+ NSString *value = title && title_len > 0 ? ([[NSString alloc] initWithBytes:title length:title_len encoding:NSUTF8StringEncoding] ?: @"") : @"";
13410
+ NativeSdkApplyTrayPresentation(
13411
+ object,
13412
+ value,
13413
+ object.statusPresentationWidth,
13414
+ object.statusPresentationTone,
13415
+ object.statusPresentationIconOpacity,
13416
+ object.statusPresentationMonospaced
13417
+ );
13418
+ }
13419
+ }
13420
+
13421
+ void native_sdk_appkit_update_tray_presentation(native_sdk_appkit_host_t *host, const char *title, size_t title_len, double width, int tone, double icon_opacity, int monospaced) {
13422
+ NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
13423
+ @autoreleasepool {
13424
+ NSString *value = title ? ([[NSString alloc] initWithBytes:title length:title_len encoding:NSUTF8StringEncoding] ?: @"") : @"";
13425
+ NativeSdkApplyTrayPresentation(object, value, width, tone, icon_opacity, monospaced != 0);
12506
13426
  }
12507
13427
  }
12508
13428
 
@@ -12511,6 +13431,8 @@ void native_sdk_appkit_remove_tray(native_sdk_appkit_host_t *host) {
12511
13431
  if (object.statusItem) {
12512
13432
  [[NSStatusBar systemStatusBar] removeStatusItem:object.statusItem];
12513
13433
  object.statusItem = nil;
13434
+ object.statusItemBaseImage = nil;
13435
+ object.statusMenu = nil;
12514
13436
  }
12515
13437
  }
12516
13438