@native-sdk/cli 0.5.4 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/build/app.zig +50 -1
  2. package/build.zig +534 -3
  3. package/build.zig.zon +7 -0
  4. package/native-sdk.d.ts +3 -1
  5. package/package.json +9 -9
  6. package/packages/core/package-lock.json +2 -2
  7. package/packages/core/package.json +1 -1
  8. package/packages/core/rt/rt.zig +280 -8
  9. package/packages/core/sdk/core.ts +481 -2
  10. package/packages/core/sdk/events.ts +17 -8
  11. package/packages/core/src/checker.ts +305 -2
  12. package/packages/core/src/diagnostics.ts +12 -0
  13. package/packages/core/src/emitter.ts +599 -3
  14. package/packages/core/src/typed_ast.ts +51 -4
  15. package/packages/core/src/types.ts +34 -1
  16. package/skill-data/native-ui/SKILL.md +39 -2
  17. package/skill-data/ts-core/SKILL.md +4 -2
  18. package/src/app_runner/root.zig +32 -10
  19. package/src/automation/layout_fingerprint.zig +160 -0
  20. package/src/automation/protocol.zig +82 -33
  21. package/src/automation/root.zig +1 -0
  22. package/src/automation/server.zig +1 -1
  23. package/src/automation/snapshot.zig +68 -9
  24. package/src/automation/watcher.zig +1 -1
  25. package/src/embed/host.zig +5 -0
  26. package/src/embed/ui_host.zig +13 -0
  27. package/src/platform/linux/gtk_host.c +527 -13
  28. package/src/platform/linux/gtk_host.h +25 -0
  29. package/src/platform/linux/root.zig +280 -7
  30. package/src/platform/macos/appkit_host.h +104 -6
  31. package/src/platform/macos/appkit_host.m +1283 -66
  32. package/src/platform/macos/cef_host.mm +110 -1
  33. package/src/platform/macos/root.zig +287 -7
  34. package/src/platform/null_platform.zig +398 -4
  35. package/src/platform/null_platform_tests.zig +35 -0
  36. package/src/platform/root.zig +9 -0
  37. package/src/platform/types.zig +386 -14
  38. package/src/platform/windows/root.zig +298 -9
  39. package/src/platform/windows/webview2_host.cpp +330 -5
  40. package/src/primitives/app_manifest/validation.zig +18 -0
  41. package/src/primitives/canvas/a11y_audit.zig +33 -11
  42. package/src/primitives/canvas/a11y_audit_tests.zig +20 -0
  43. package/src/primitives/canvas/drawing.zig +25 -0
  44. package/src/primitives/canvas/equality.zig +8 -0
  45. package/src/primitives/canvas/events.zig +103 -16
  46. package/src/primitives/canvas/frame.zig +125 -1
  47. package/src/primitives/canvas/layout_audit.zig +22 -5
  48. package/src/primitives/canvas/markdown_hostile_tests.zig +8 -4
  49. package/src/primitives/canvas/render_tests.zig +13 -10
  50. package/src/primitives/canvas/root.zig +48 -0
  51. package/src/primitives/canvas/terminal_box.zig +471 -0
  52. package/src/primitives/canvas/terminal_grid.zig +978 -0
  53. package/src/primitives/canvas/terminal_grid_tests.zig +1093 -0
  54. package/src/primitives/canvas/test_support.zig +1 -0
  55. package/src/primitives/canvas/tests.zig +1 -0
  56. package/src/primitives/canvas/text_tests.zig +39 -4
  57. package/src/primitives/canvas/tokens.zig +115 -12
  58. package/src/primitives/canvas/ui.zig +524 -5
  59. package/src/primitives/canvas/ui_markup.zig +195 -2
  60. package/src/primitives/canvas/ui_markup_compiled.zig +172 -1
  61. package/src/primitives/canvas/ui_markup_compiled_tests.zig +133 -8
  62. package/src/primitives/canvas/ui_markup_contract.zig +88 -5
  63. package/src/primitives/canvas/ui_markup_contract_tests.zig +39 -1
  64. package/src/primitives/canvas/ui_markup_huge_model_tests.zig +1 -0
  65. package/src/primitives/canvas/ui_markup_reflect.zig +75 -24
  66. package/src/primitives/canvas/ui_markup_tests.zig +149 -0
  67. package/src/primitives/canvas/ui_markup_view.zig +191 -0
  68. package/src/primitives/canvas/ui_markup_view_tests.zig +403 -19
  69. package/src/primitives/canvas/ui_schema.zig +97 -17
  70. package/src/primitives/canvas/ui_schema_tests.zig +18 -11
  71. package/src/primitives/canvas/ui_tests.zig +141 -9
  72. package/src/primitives/canvas/widget_access.zig +28 -2
  73. package/src/primitives/canvas/widget_anchored_tests.zig +48 -0
  74. package/src/primitives/canvas/widget_invalidation.zig +81 -1
  75. package/src/primitives/canvas/widget_layout.zig +59 -11
  76. package/src/primitives/canvas/widget_layout_tests.zig +125 -4
  77. package/src/primitives/canvas/widget_render.zig +272 -18
  78. package/src/primitives/canvas/widget_render_scroll.zig +108 -27
  79. package/src/primitives/canvas/widget_routing.zig +59 -7
  80. package/src/primitives/canvas/widget_runtime.zig +23 -0
  81. package/src/primitives/canvas/widget_runtime_tests.zig +149 -0
  82. package/src/primitives/canvas/widget_semantics.zig +119 -11
  83. package/src/primitives/canvas/widget_semantics_tests.zig +409 -0
  84. package/src/primitives/canvas/widget_tree.zig +17 -0
  85. package/src/primitives/canvas/widgets.zig +132 -0
  86. package/src/root.zig +16 -0
  87. package/src/runtime/api.zig +70 -1
  88. package/src/runtime/automation_commands.zig +20 -1
  89. package/src/runtime/automation_snapshot.zig +25 -1
  90. package/src/runtime/automation_widget_dispatch.zig +73 -8
  91. package/src/runtime/bridge_payload.zig +1 -0
  92. package/src/runtime/canvas_frame.zig +62 -7
  93. package/src/runtime/canvas_frame_animation_tests.zig +5 -4
  94. package/src/runtime/canvas_frame_helpers.zig +190 -1
  95. package/src/runtime/canvas_frame_invalidation_tests.zig +531 -0
  96. package/src/runtime/canvas_frame_patch_tests.zig +161 -10
  97. package/src/runtime/canvas_frame_retained_tests.zig +5 -2
  98. package/src/runtime/canvas_widget_accessibility_tests.zig +1 -1
  99. package/src/runtime/canvas_widget_clipboard_tests.zig +40 -0
  100. package/src/runtime/canvas_widget_context_menu.zig +269 -32
  101. package/src/runtime/canvas_widget_context_menu_tests.zig +640 -14
  102. package/src/runtime/canvas_widget_display.zig +1 -1
  103. package/src/runtime/canvas_widget_event_tests.zig +1823 -0
  104. package/src/runtime/canvas_widget_events.zig +240 -24
  105. package/src/runtime/canvas_widget_runtime.zig +213 -29
  106. package/src/runtime/canvas_widget_scroll_driver_tests.zig +170 -7
  107. package/src/runtime/canvas_widget_scroll_drivers.zig +151 -17
  108. package/src/runtime/canvas_widget_scroll_tests.zig +435 -23
  109. package/src/runtime/canvas_widget_state.zig +6 -0
  110. package/src/runtime/canvas_widget_text_tests.zig +1 -1
  111. package/src/runtime/core.zig +73 -2
  112. package/src/runtime/effects.zig +6389 -54
  113. package/src/runtime/effects_channel_tests.zig +3519 -0
  114. package/src/runtime/effects_pty_tests.zig +1362 -0
  115. package/src/runtime/effects_tests.zig +14 -9
  116. package/src/runtime/effects_video_tests.zig +3609 -0
  117. package/src/runtime/flow.zig +25 -4
  118. package/src/runtime/gpu_surface_events.zig +473 -13
  119. package/src/runtime/media_surface.zig +116 -11
  120. package/src/runtime/media_surface_tests.zig +61 -0
  121. package/src/runtime/pty.zig +1252 -0
  122. package/src/runtime/pty_windows.zig +1780 -0
  123. package/src/runtime/root.zig +25 -0
  124. package/src/runtime/runtime_event_tests.zig +20 -1
  125. package/src/runtime/session_journal.zig +367 -61
  126. package/src/runtime/session_record.zig +16 -0
  127. package/src/runtime/session_replay.zig +395 -11
  128. package/src/runtime/session_tests.zig +109 -15
  129. package/src/runtime/terminal_session.zig +1569 -0
  130. package/src/runtime/terminal_session_tests.zig +450 -0
  131. package/src/runtime/terminal_vt_ghostty.zig +15 -0
  132. package/src/runtime/terminal_vt_stub.zig +13 -0
  133. package/src/runtime/tests.zig +6 -0
  134. package/src/runtime/ts_core_host.zig +980 -140
  135. package/src/runtime/ts_core_host_tests.zig +1059 -1
  136. package/src/runtime/ts_ui_app.zig +16 -5
  137. package/src/runtime/ui_app.zig +2333 -63
  138. package/src/runtime/ui_app_tests.zig +3171 -744
  139. package/src/runtime/ui_app_virtual_variable_tests.zig +4 -2
  140. package/src/runtime/ui_app_window_tests.zig +268 -0
  141. package/src/runtime/view.zig +190 -2
  142. package/src/runtime/view_widget_scroll.zig +218 -68
  143. package/src/runtime/view_widget_text.zig +11 -2
  144. package/src/runtime/view_widget_tree.zig +111 -3
  145. package/src/runtime/window_storage.zig +45 -2
  146. package/src/runtime/window_view_runtime.zig +34 -2
  147. package/src/runtime/window_views.zig +1 -0
  148. package/src/terminal_session_tests_root.zig +15 -0
  149. package/src/tooling/templates.zig +25 -7
@@ -43,11 +43,14 @@ static void *NativeSdkAppKitAppearanceObservationContext = &NativeSdkAppKitAppea
43
43
  * is not paused, but no audio comes out until bytes arrive). */
44
44
  static void *NativeSdkAppKitAudioItemStatusContext = &NativeSdkAppKitAudioItemStatusContext;
45
45
  static void *NativeSdkAppKitAudioTimeControlContext = &NativeSdkAppKitAudioTimeControlContext;
46
+ static void *NativeSdkAppKitVideoItemStatusContext = &NativeSdkAppKitVideoItemStatusContext;
47
+ static void *NativeSdkAppKitVideoTimeControlContext = &NativeSdkAppKitVideoTimeControlContext;
46
48
  /* Render-thread ring state for the spectrum tap; defined with the rest
47
49
  * of the spectrum machinery in the audio section below. */
48
50
  typedef struct native_sdk_spectrum_tap_state native_sdk_spectrum_tap_state_t;
49
51
  static NSRect constrainFrame(NSRect frame);
50
52
  static NSString *NativeSdkAppKitBridgeScript(void);
53
+ static NSString *NativeSdkMenuKeyEquivalent(NSString *key);
51
54
  static NSString *NativeSdkMimeTypeForPath(NSString *path);
52
55
  static NSString *NativeSdkResolvedAssetRoot(NSString *rootPath);
53
56
  static void NativeSdkRegisterBundledFonts(void);
@@ -57,6 +60,7 @@ static NSArray<NSString *> *NativeSdkPolicyListFromBytes(const char *bytes, size
57
60
  static NSString *NativeSdkOriginForURL(NSURL *url);
58
61
  static BOOL NativeSdkPolicyListMatches(NSArray<NSString *> *values, NSURL *url);
59
62
  static NSString *NativeSdkShortcutKeyForEvent(NSEvent *event);
63
+ static BOOL NativeSdkTextNavigationNeedsRawKeyEvent(NSEvent *event);
60
64
  static BOOL NativeSdkShortcutUsesImplicitShift(NSString *key, NSEvent *event);
61
65
  static BOOL NativeSdkShortcutModifiersMatch(uint32_t shortcutModifiers, NSEventModifierFlags eventModifiers, BOOL allowImplicitShift);
62
66
  static NSEventModifierFlags NativeSdkMenuModifierFlags(uint32_t modifiers);
@@ -316,6 +320,7 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
316
320
  @property(nonatomic, strong) NSArray<NSValue *> *coveredMouseRects;
317
321
  @property(nonatomic, assign) NativeSdkAppKitHost *host;
318
322
  @property(nonatomic, assign) uint64_t windowId;
323
+ @property(nonatomic, strong) NSString *viewLabel;
319
324
  @end
320
325
 
321
326
  @interface NativeSdkBridgeScriptHandler : NSObject <WKScriptMessageHandler>
@@ -340,6 +345,16 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
340
345
  * overlay knob stays grabbable). */
341
346
  @interface NativeSdkScrollDriverView : NSScrollView
342
347
  @property(nonatomic, assign) uint64_t driverId;
348
+ @property(nonatomic, assign) uint64_t parentDriverId;
349
+ /* Bit i set = occluder i of the surface's occluder array hit-blocks
350
+ * this region at points it contains. */
351
+ @property(nonatomic, assign) uint32_t occluderMask;
352
+ /* The region's axis grants (the runtime's widgetScrollsAxis), pushed on
353
+ * every reconcile: the wheel winner-resolution's fallback rule needs
354
+ * grants, not range — a granted axis with short content still owns a
355
+ * bounce, an ungranted one owns nothing. */
356
+ @property(nonatomic, assign) BOOL grantsX;
357
+ @property(nonatomic, assign) BOOL grantsY;
343
358
  @end
344
359
 
345
360
  /* Captures the selected item id of a context-menu popUp; NSMenuItem
@@ -573,10 +588,28 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
573
588
  @property(nonatomic, assign) BOOL interpretedKeyEventEmittedInput;
574
589
  @property(nonatomic, strong) NSArray<NSAccessibilityElement *> *widgetAccessibilityElements;
575
590
  @property(nonatomic, strong) NSMutableArray<NativeSdkScrollDriverView *> *scrollDrivers;
576
- @property(nonatomic, weak) NativeSdkScrollDriverView *activeWheelDriver;
591
+ @property(nonatomic, assign) NSPoint wheelGesturePoint;
592
+ @property(nonatomic, assign) BOOL wheelGestureActive;
593
+ /* The last phase-less wheel's timestamp: discrete streams have no
594
+ * gesture phases, so a quiet gap IS the gesture boundary. */
595
+ @property(nonatomic, assign) uint64_t lastLegacyWheelTimestampNs;
596
+ /* The gesture's most recent native recipient: zero-delta phase events
597
+ * (begins, the terminal Ended/Cancelled) resolve no owner but still
598
+ * carry the bookkeeping the scroller's overscroll recovery keys off,
599
+ * so they forward here. */
600
+ @property(nonatomic, weak) NativeSdkScrollDriverView *lastNativeWheelDriver;
601
+ /* Driver ids the WIRE has scrolled during this gesture: once the engine
602
+ * applies relative deltas to a region, later ABSOLUTE native reports
603
+ * from the same region would erase them, so a wire-scrolled region
604
+ * never becomes the native recipient again until the gesture ends. */
605
+ @property(nonatomic, strong) NSMutableSet *wireBoundDriverIds;
606
+ /* Occluder rects (view space): floating surfaces and modal catchers
607
+ * that hit-block scroll regions beneath them. */
608
+ @property(nonatomic, strong) NSArray *scrollOccluderRects;
577
609
  @property(nonatomic, assign) BOOL applyingScrollDriverOffset;
578
610
  @property(nonatomic, assign) BOOL scrollDriverEventPending;
579
611
  @property(nonatomic, assign) uint64_t pendingScrollDriverId;
612
+ @property(nonatomic, assign) double pendingScrollDriverOffsetX;
580
613
  @property(nonatomic, assign) double pendingScrollDriverOffsetY;
581
614
  @property(nonatomic, assign) uint64_t scrollDriverEventLastEmitNs;
582
615
  @property(nonatomic, assign) BOOL controlClickActive;
@@ -623,7 +656,7 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
623
656
  - (void)emitInputEventWithKind:(NSInteger)kind event:(NSEvent *)event button:(NSInteger)button deltaX:(double)deltaX deltaY:(double)deltaY;
624
657
  - (void)queuePointerMotionInputEvent:(NSEvent *)event kind:(NSInteger)kind button:(NSInteger)button;
625
658
  - (void)emitQueuedPointerMotionInputEvent;
626
- - (void)queueScrollInputEvent:(NSEvent *)event deltaX:(double)deltaX deltaY:(double)deltaY;
659
+ - (void)queueScrollInputEvent:(NSEvent *)event atPoint:(NSPoint)point deltaX:(double)deltaX deltaY:(double)deltaY;
627
660
  - (void)emitQueuedScrollInputEvent;
628
661
  - (void)emitPinchInputEventWithKind:(NSInteger)kind event:(NSEvent *)event magnification:(double)magnification;
629
662
  - (void)emitPinchChangeForEvent:(NSEvent *)event;
@@ -636,7 +669,7 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
636
669
  - (BOOL)emitWidgetAccessibilityActionWithId:(uint64_t)widgetId action:(NSInteger)action;
637
670
  - (BOOL)emitWidgetAccessibilityActionWithId:(uint64_t)widgetId action:(NSInteger)action text:(NSString *)text selectedRange:(NSRange)selectedRange hasSelectedRange:(BOOL)hasSelectedRange;
638
671
  - (void)setSurfaceCursor:(NSCursor *)cursor;
639
- - (void)setScrollDrivers:(const native_sdk_appkit_scroll_driver_t *)drivers count:(NSUInteger)count;
672
+ - (void)setScrollDrivers:(const native_sdk_appkit_scroll_driver_t *)drivers count:(NSUInteger)count occluders:(const native_sdk_appkit_scroll_occluder_t *)occluders occluderCount:(NSUInteger)occluderCount;
640
673
  @end
641
674
 
642
675
  @interface NativeSdkAssetSchemeHandler : NSObject <WKURLSchemeHandler>
@@ -760,6 +793,69 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
760
793
  * when a new load replaces the stream; orphaned (left to finish) when
761
794
  * the stream completes naturally. */
762
795
  @property(nonatomic, strong) NSURLSessionDownloadTask *audioCacheDownload;
796
+ /* The app's single video player and its two timers. One player is the
797
+ * whole surface, exactly like audio: a video app shows one stream at a
798
+ * time, and a second concurrent decode would be compositor design the
799
+ * platform seam has not earned. The position tick runs only while
800
+ * playing, at the audio tier's coarse honest cadence — position is a
801
+ * readout, not a frame clock; the FRAME timer (1/60 s, the
802
+ * scheduleFrame cadence) is the clock that actually paces decoded
803
+ * pixels into the sink, armed with the transport plus one-shot polls
804
+ * after seek/pause so a paused scrub still shows its frame. */
805
+ @property(nonatomic, strong) AVPlayer *videoPlayer;
806
+ @property(nonatomic, strong) AVPlayerItem *videoItem;
807
+ /* The frame tap: created at readyToPlay (the presentation size is only
808
+ * decoded then), sized to FIT the sink's per-frame pixel budget. */
809
+ @property(nonatomic, strong) AVPlayerItemVideoOutput *videoOutput;
810
+ @property(nonatomic, strong) NSTimer *videoPositionTimer;
811
+ @property(nonatomic, strong) NSTimer *videoFrameTimer;
812
+ /* Where decoded frames go: the C push trampoline and its context,
813
+ * installed by the load entries. Every timer callback runs on the main
814
+ * run loop, so no locking guards the pair. */
815
+ @property(nonatomic, assign) native_sdk_appkit_video_sink_push_t videoSinkPush;
816
+ @property(nonatomic, assign) void *videoSinkContext;
817
+ /* The reusable RGBA conversion target: malloc'd once per load to the
818
+ * output's max frame size, freed on stop/replace. Frames are converted
819
+ * BGRA -> tightly packed straight-alpha RGBA8 into it before the push. */
820
+ @property(nonatomic, assign) uint8_t *videoFrameBuffer;
821
+ @property(nonatomic, assign) size_t videoFrameBufferLen;
822
+ /* The STREAM's decoded pixel dimensions (presentationSize, falling back
823
+ * to the track's transformed naturalSize) — what LOADED reports, even
824
+ * when the output texture is fitted smaller. */
825
+ @property(nonatomic, assign) uint64_t videoStreamWidth;
826
+ @property(nonatomic, assign) uint64_t videoStreamHeight;
827
+ /* The poster-frame hunt: a load that acknowledges LOADED while paused
828
+ * (autoplay = false, "the poster-frame shape") still owes the surface
829
+ * its first decoded frame — the frame timer normally runs only while
830
+ * playing. Set on LOADED; the pump clears it at the first delivered
831
+ * frame (stopping the timer if still paused), and the tick counter
832
+ * bounds the hunt so an output that never yields a frame cannot poll
833
+ * at 60 Hz forever. */
834
+ @property(nonatomic, assign) BOOL videoPosterPending;
835
+ @property(nonatomic, assign) int videoPosterTicks;
836
+ /* The engine-minted token of the CURRENT load, echoed in every video
837
+ * event (see the header's video_token) so a replaced playback's queued
838
+ * straggler can never be attributed to the replacement. */
839
+ @property(nonatomic, assign) uint64_t videoToken;
840
+ /* Whether the loaded source is a local file: local sources never
841
+ * report buffering. */
842
+ @property(nonatomic, assign) BOOL videoSourceIsLocal;
843
+ /* NSNotificationCenter block-observer tokens for the item's natural
844
+ * end and mid-flight failure; removed on teardown. */
845
+ @property(nonatomic, strong) id videoEndObserver;
846
+ @property(nonatomic, strong) id videoFailObserver;
847
+ /* KVO registration flag so teardown removes observers exactly once. */
848
+ @property(nonatomic, assign) BOOL videoObservingStatus;
849
+ /* The LOADED acknowledgment fires once per load (item status can
850
+ * bounce through readyToPlay again after a stall). */
851
+ @property(nonatomic, assign) BOOL videoLoadedEmitted;
852
+ /* The honest buffering mirror emitted with every video event: YES from
853
+ * stream start (no bytes yet) until the player reports it is actually
854
+ * rolling, then follows timeControlStatus. Never set for local files. */
855
+ @property(nonatomic, assign) BOOL videoBuffering;
856
+ /* Loop intent: a looping player wraps from the natural end back to
857
+ * zero and keeps playing — no COMPLETED, because it never ends. */
858
+ @property(nonatomic, assign) BOOL videoLooping;
763
859
  @property(nonatomic, strong) NSString *appName;
764
860
  /* The human-facing app name (app.zon display_name, falling back through
765
861
  * the window title to the binary name). Everything the OS labels the
@@ -798,6 +894,7 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
798
894
  @property(nonatomic, assign) BOOL observesAppearanceChanges;
799
895
  @property(nonatomic, assign) NSInteger bridgeFrameKeepalive;
800
896
  @property(nonatomic, strong) id shortcutEventMonitor;
897
+ @property(nonatomic, strong) id viewFocusEventMonitor;
801
898
  @property(nonatomic, strong) id willTerminateObserver;
802
899
  @property(nonatomic, strong) dispatch_source_t sigtermSource;
803
900
  @property(nonatomic, strong) NSArray<NativeSdkShortcut *> *shortcuts;
@@ -840,7 +937,7 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
840
937
  - (NSInteger)presentGpuSurfacePacketBinaryInWindow:(uint64_t)windowId label:(NSString *)label surfaceWidth:(CGFloat)surfaceWidth height:(CGFloat)surfaceHeight scale:(CGFloat)scale clearR:(uint8_t)clearR clearG:(uint8_t)clearG clearB:(uint8_t)clearB clearA:(uint8_t)clearA requiresRender:(BOOL)requiresRender commandCount:(NSUInteger)commandCount unsupportedCommandCount:(NSUInteger)unsupportedCommandCount representable:(BOOL)representable packet:(const uint8_t *)packet byteLength:(NSUInteger)byteLength;
841
938
  - (BOOL)requestGpuSurfaceFrameInWindow:(uint64_t)windowId label:(NSString *)label;
842
939
  - (BOOL)noteGpuSurfaceInputInWindow:(uint64_t)windowId label:(NSString *)label;
843
- - (BOOL)setGpuSurfaceScrollDriversInWindow:(uint64_t)windowId label:(NSString *)label drivers:(const native_sdk_appkit_scroll_driver_t *)drivers count:(NSUInteger)count;
940
+ - (BOOL)setGpuSurfaceScrollDriversInWindow:(uint64_t)windowId label:(NSString *)label drivers:(const native_sdk_appkit_scroll_driver_t *)drivers count:(NSUInteger)count occluders:(const native_sdk_appkit_scroll_occluder_t *)occluders occluderCount:(NSUInteger)occluderCount;
844
941
  - (BOOL)showContextMenuInWindow:(uint64_t)windowId label:(NSString *)label x:(double)x y:(double)y token:(uint64_t)token items:(const native_sdk_appkit_context_menu_item_t *)items count:(NSUInteger)count;
845
942
  - (BOOL)uploadGpuSurfaceImageWithId:(uint64_t)imageId width:(NSUInteger)width height:(NSUInteger)height rgba8:(const uint8_t *)rgba8 byteLength:(NSUInteger)byteLength;
846
943
  - (BOOL)removeGpuSurfaceImageWithId:(uint64_t)imageId;
@@ -918,6 +1015,29 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
918
1015
  - (void)stopAudioSpectrumTimer;
919
1016
  - (BOOL)anyHostWindowVisibleOnGlass;
920
1017
  - (void)audioSpectrumTimerFired:(NSTimer *)timer;
1018
+ - (int)videoLoadPath:(NSString *)path token:(uint64_t)token pushFn:(native_sdk_appkit_video_sink_push_t)pushFn pushContext:(void *)pushContext;
1019
+ - (int)videoLoadURL:(NSString *)urlString token:(uint64_t)token pushFn:(native_sdk_appkit_video_sink_push_t)pushFn pushContext:(void *)pushContext;
1020
+ - (void)videoInstallItem:(AVPlayerItem *)item localSource:(BOOL)localSource pushFn:(native_sdk_appkit_video_sink_push_t)pushFn pushContext:(void *)pushContext;
1021
+ - (BOOL)videoAttachOutputForItem:(AVPlayerItem *)item;
1022
+ - (void)videoTearDownPlayer;
1023
+ - (void)videoItemStatusChanged;
1024
+ - (void)videoTimeControlChanged;
1025
+ - (void)videoDidPlayToEnd;
1026
+ - (void)videoDidFail;
1027
+ - (int)videoPlay;
1028
+ - (int)videoPause;
1029
+ - (int)videoStop;
1030
+ - (int)videoSeekToMs:(uint64_t)positionMs;
1031
+ - (int)videoSetVolume:(double)volume;
1032
+ - (int)videoSetMuted:(BOOL)muted;
1033
+ - (int)videoSetLoop:(BOOL)loop;
1034
+ - (void)emitVideoEventOfKind:(int)kind;
1035
+ - (void)stopVideoPositionTimer;
1036
+ - (void)videoPositionTimerFired:(NSTimer *)timer;
1037
+ - (void)startVideoFrameTimer;
1038
+ - (void)stopVideoFrameTimer;
1039
+ - (void)videoFrameTimerFired:(NSTimer *)timer;
1040
+ - (void)videoPumpFrame;
921
1041
  - (void)wakeFromAnyThread;
922
1042
  - (void)scheduleBridgeFrames;
923
1043
  - (void)emitFrame;
@@ -3345,15 +3465,28 @@ static NSDictionary *NativeSdkPacketDictionaryFromBinary(const uint8_t *bytes, N
3345
3465
  @implementation NativeSdkScrollDriverView
3346
3466
 
3347
3467
  - (NSView *)hitTest:(NSPoint)point {
3348
- // Scroll-wheel events route to the driver through the ordinary hit
3349
- // test so AppKit's own (responsive) scrolling machinery handles them
3350
- // — a programmatically forwarded scrollWheel: is ignored by that
3351
- // path. Everything else passes through to the canvas beneath, except
3352
- // the overlay scrollers themselves (the knob stays grabbable).
3468
+ // Wheel events deliberately do NOT hit the driver: they fall
3469
+ // through to the surface, whose scrollWheel: resolves the gesture's
3470
+ // dominant axis against every driver under the pointer, locks the
3471
+ // gesture, forwards it to the winner, and splits any residual axis
3472
+ // to the engine wire — per-axis routing that direct NSScrollView
3473
+ // delivery cannot perform (NSScrollView consumes whole events, so a
3474
+ // diagonal gesture over a nested vertical list would swallow the
3475
+ // horizontal component its ancestor owns). The forwarded event
3476
+ // skips AppKit's concurrent responsive-scrolling fast path, but the
3477
+ // scroller still owns feel — momentum, rubber-band, and the overlay
3478
+ // scroller all run from forwarded events (the responder-chain
3479
+ // fallback always relied on exactly that). Everything else passes
3480
+ // through to the canvas beneath, except the overlay scrollers
3481
+ // themselves (the knob stays grabbable).
3353
3482
  NSView *hit = [super hitTest:point];
3354
3483
  if (!hit) return nil;
3484
+ // Wheel events never hit-test into the driver — not even over a
3485
+ // visible overlay scroller: a wheel over the knob still needs the
3486
+ // splitter, or its cross-axis component would be swallowed. Only
3487
+ // pointer interaction keeps the knob grabbable.
3355
3488
  NSEvent *current = NSApp.currentEvent;
3356
- if (current && current.type == NSEventTypeScrollWheel) return hit;
3489
+ if (current && current.type == NSEventTypeScrollWheel) return nil;
3357
3490
  NSView *candidate = hit;
3358
3491
  while (candidate && candidate != self) {
3359
3492
  if ([candidate isKindOfClass:[NSScroller class]]) return hit;
@@ -5851,15 +5984,96 @@ static BOOL NativeSdkCompositeBlurWriteRegion(NSDictionary *command, CGFloat sca
5851
5984
  }
5852
5985
 
5853
5986
  - (void)scrollWheel:(NSEvent *)event {
5854
- NativeSdkScrollDriverView *driver = [self scrollDriverForWheelEvent:event];
5855
- if (driver) {
5856
- // The OS scroller owns input + physics for this region (momentum,
5857
- // rubber-band, overlay scroller); the resulting contentOffset
5858
- // flows back through the clip-view bounds-change notification.
5859
- [driver scrollWheel:event];
5987
+ if (self.scrollDrivers.count == 0) {
5988
+ [self queueScrollInputEvent:event atPoint:[self convertPoint:event.locationInWindow fromView:nil] deltaX:-event.scrollingDeltaX deltaY:-event.scrollingDeltaY];
5989
+ return;
5990
+ }
5991
+ // Gesture anchoring: owners resolve at the point where the GESTURE
5992
+ // began (so momentum and wire hand-offs keep working the same
5993
+ // regions after the pointer wanders), re-evaluated EVERY event
5994
+ // against the drivers' live offsets — which is what hands an axis
5995
+ // to the ancestor the moment the inner region saturates, mirroring
5996
+ // the engine's per-event walk. Legacy wheels (no phases) resolve at
5997
+ // the live pointer; a quiet gap is their gesture boundary.
5998
+ const BOOL legacy = event.phase == NSEventPhaseNone && event.momentumPhase == NSEventPhaseNone;
5999
+ NSPoint point;
6000
+ if (legacy) {
6001
+ point = [self convertPoint:event.locationInWindow fromView:nil];
6002
+ const uint64_t now = NativeSdkTimestampNanoseconds();
6003
+ const BOOL freshBurst = self.lastLegacyWheelTimestampNs == 0 ||
6004
+ now - self.lastLegacyWheelTimestampNs > 250000000ull;
6005
+ self.lastLegacyWheelTimestampNs = now;
6006
+ if (freshBurst) {
6007
+ [self.wireBoundDriverIds removeAllObjects];
6008
+ self.lastNativeWheelDriver = nil;
6009
+ }
6010
+ } else {
6011
+ if (event.phase == NSEventPhaseBegan || event.phase == NSEventPhaseMayBegin) {
6012
+ self.wheelGesturePoint = [self convertPoint:event.locationInWindow fromView:nil];
6013
+ self.wheelGestureActive = YES;
6014
+ [self.wireBoundDriverIds removeAllObjects];
6015
+ self.lastLegacyWheelTimestampNs = 0;
6016
+ self.lastNativeWheelDriver = nil;
6017
+ }
6018
+ point = self.wheelGestureActive ? self.wheelGesturePoint : [self convertPoint:event.locationInWindow fromView:nil];
6019
+ if (event.momentumPhase == NSEventPhaseEnded || event.momentumPhase == NSEventPhaseCancelled) {
6020
+ self.wheelGestureActive = NO;
6021
+ }
6022
+ }
6023
+ if (!self.wireBoundDriverIds) self.wireBoundDriverIds = [[NSMutableSet alloc] init];
6024
+
6025
+ const double canvasDx = -event.scrollingDeltaX;
6026
+ const double canvasDy = -event.scrollingDeltaY;
6027
+
6028
+ // Zero-delta phase events (begins, the terminal Ended/Cancelled)
6029
+ // resolve no owner but still carry the bookkeeping the scroller's
6030
+ // overscroll recovery keys off — they forward to the gesture's last
6031
+ // native recipient and nowhere else.
6032
+ if (canvasDx == 0 && canvasDy == 0) {
6033
+ if (!legacy && self.lastNativeWheelDriver) {
6034
+ [self.lastNativeWheelDriver scrollWheel:event];
6035
+ }
5860
6036
  return;
5861
6037
  }
5862
- [self queueScrollInputEvent:event deltaX:-event.scrollingDeltaX deltaY:-event.scrollingDeltaY];
6038
+
6039
+ NSArray *chain = [self wheelCandidateChainAtPoint:point];
6040
+ NativeSdkScrollDriverView *ownerX = nil;
6041
+ NativeSdkScrollDriverView *ownerY = nil;
6042
+ [self resolveWheelOwnersInChain:chain canvasDx:canvasDx canvasDy:canvasDy ownerX:&ownerX ownerY:&ownerY];
6043
+
6044
+ // ONE owner takes the whole event natively; everything ambiguous
6045
+ // rides the wire, where the engine's real routing decides:
6046
+ // - no owner at all (dead axes, an overlay over the anchor);
6047
+ // - the two axes owned by DIFFERENT regions (one NSScrollView
6048
+ // cannot keep the axes apart — the engine applies each axis to
6049
+ // its own region and the set-offset flags sync the scrollers);
6050
+ // - an owner the wire already scrolled this gesture (the engine
6051
+ // applied relative deltas its next ABSOLUTE report would
6052
+ // erase).
6053
+ // A partially consumable delta stays NATIVE and clamps at the edge
6054
+ // — exactly the engine's rule (the region that can move consumes
6055
+ // the whole event; the remainder dies), so native and engine-only
6056
+ // execution agree.
6057
+ const BOOL dominantVertical = fabs(canvasDy) >= fabs(canvasDx);
6058
+ NativeSdkScrollDriverView *native = dominantVertical ? (ownerY ?: ownerX) : (ownerX ?: ownerY);
6059
+ const BOOL splitOwners = ownerX && ownerY && ownerX != ownerY;
6060
+ const BOOL nativeWireBound = native && [self.wireBoundDriverIds containsObject:@(native.driverId)];
6061
+ if (!native || splitOwners || nativeWireBound) {
6062
+ if (ownerX) [self.wireBoundDriverIds addObject:@(ownerX.driverId)];
6063
+ if (ownerY) [self.wireBoundDriverIds addObject:@(ownerY.driverId)];
6064
+ // Offsets first (one clock): the wire routing consults the
6065
+ // runtime's offsets, so any coalesced driver report must land
6066
+ // before the deltas that depend on it.
6067
+ [self emitQueuedScrollDriverEvent];
6068
+ [self queueScrollInputEvent:event atPoint:point deltaX:canvasDx deltaY:canvasDy];
6069
+ return;
6070
+ }
6071
+
6072
+ // The OS scroller owns input + physics for this event (momentum,
6073
+ // rubber-band, overlay scroller); the resulting contentOffset flows
6074
+ // back through the clip-view bounds-change notification.
6075
+ self.lastNativeWheelDriver = native;
6076
+ [native scrollWheel:event];
5863
6077
  }
5864
6078
 
5865
6079
  - (void)magnifyWithEvent:(NSEvent *)event {
@@ -5938,6 +6152,17 @@ static BOOL NativeSdkCompositeBlurWriteRegion(NSDictionary *command, CGFloat sca
5938
6152
 
5939
6153
  - (void)keyDown:(NSEvent *)event {
5940
6154
  if ([self focusedTextAccessibilityElement]) {
6155
+ // The shared canvas editor already maps Command/Option+Left/Right
6156
+ // (including Shift variants) onto line/word navigation. Preserve
6157
+ // those physical keys instead of letting interpretKeyEvents turn
6158
+ // Command+Left/Right into modifier-less Home/End selectors. A
6159
+ // focused terminal needs the modifiers even more: its emulator
6160
+ // translates the natural macOS gestures to shell bindings, and
6161
+ // negotiated key protocols must see every other combined chord.
6162
+ if (NativeSdkTextNavigationNeedsRawKeyEvent(event)) {
6163
+ [self emitInputEventWithKind:NATIVE_SDK_APPKIT_GPU_INPUT_KEY_DOWN event:event button:0 deltaX:0 deltaY:0];
6164
+ return;
6165
+ }
5941
6166
  self.interpretedKeyEventEmittedInput = NO;
5942
6167
  [self interpretKeyEvents:@[event]];
5943
6168
  if (!self.interpretedKeyEventEmittedInput) {
@@ -6066,10 +6291,13 @@ static BOOL NativeSdkCompositeBlurWriteRegion(NSDictionary *command, CGFloat sca
6066
6291
  deltaY:0];
6067
6292
  }
6068
6293
 
6069
- - (void)queueScrollInputEvent:(NSEvent *)event deltaX:(double)deltaX deltaY:(double)deltaY {
6294
+ // The POINT is caller-supplied: driver hand-offs pass the gesture's
6295
+ // anchor so residual and saturated-momentum deltas route to the same
6296
+ // regions the native side resolved, however far the pointer wandered.
6297
+ - (void)queueScrollInputEvent:(NSEvent *)event atPoint:(NSPoint)point deltaX:(double)deltaX deltaY:(double)deltaY {
6070
6298
  if (!self.host || self.surfaceLabel.length == 0 || !event) return;
6071
6299
  if (deltaX == 0 && deltaY == 0) return;
6072
- self.pendingScrollPoint = [self convertPoint:event.locationInWindow fromView:nil];
6300
+ self.pendingScrollPoint = point;
6073
6301
  self.pendingScrollDeltaX += deltaX;
6074
6302
  self.pendingScrollDeltaY += deltaY;
6075
6303
  self.pendingScrollModifiers = NativeSdkModifierFlagsForEvent(event);
@@ -6178,8 +6406,18 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
6178
6406
  // IS the canvas scroll offset, reported back per frame interval through
6179
6407
  // GPU_SURFACE_SCROLL_DRIVER events.
6180
6408
 
6181
- - (void)setScrollDrivers:(const native_sdk_appkit_scroll_driver_t *)drivers count:(NSUInteger)count {
6409
+ - (void)setScrollDrivers:(const native_sdk_appkit_scroll_driver_t *)drivers count:(NSUInteger)count occluders:(const native_sdk_appkit_scroll_occluder_t *)occluders occluderCount:(NSUInteger)occluderCount {
6182
6410
  if (!self.scrollDrivers) self.scrollDrivers = [[NSMutableArray alloc] init];
6411
+ // Occluder rects arrive in canvas coordinates (top-left origin,
6412
+ // y-down); store them flipped into this view's space, like the
6413
+ // driver frames.
6414
+ NSMutableArray *occluderRects = [[NSMutableArray alloc] initWithCapacity:occluderCount];
6415
+ for (NSUInteger index = 0; index < occluderCount; index += 1) {
6416
+ const native_sdk_appkit_scroll_occluder_t occluder = occluders[index];
6417
+ const NSRect rect = NSMakeRect(occluder.x, self.bounds.size.height - occluder.y - occluder.height, occluder.width, occluder.height);
6418
+ [occluderRects addObject:[NSValue valueWithRect:rect]];
6419
+ }
6420
+ self.scrollOccluderRects = occluderRects;
6183
6421
  for (NSInteger index = (NSInteger)self.scrollDrivers.count - 1; index >= 0; index -= 1) {
6184
6422
  NativeSdkScrollDriverView *driver = self.scrollDrivers[(NSUInteger)index];
6185
6423
  BOOL present = NO;
@@ -6194,6 +6432,11 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
6194
6432
  [driver removeFromSuperview];
6195
6433
  [self.scrollDrivers removeObjectAtIndex:(NSUInteger)index];
6196
6434
  }
6435
+ // Rebuilt in SPEC order every push: the specs ride layout pre-order
6436
+ // (outermost first, deepest last), and the wheel selection walk
6437
+ // depends on that order — a keyed reorder that keeps ids must not
6438
+ // leave a stale creation order deciding which region is "deepest".
6439
+ NSMutableArray *ordered = [[NSMutableArray alloc] initWithCapacity:count];
6197
6440
  for (NSUInteger spec = 0; spec < count; spec += 1) {
6198
6441
  const native_sdk_appkit_scroll_driver_t desired = drivers[spec];
6199
6442
  NativeSdkScrollDriverView *driver = nil;
@@ -6210,10 +6453,14 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
6210
6453
  driver.driverId = desired.driver_id;
6211
6454
  driver.drawsBackground = NO;
6212
6455
  driver.hasVerticalScroller = YES;
6213
- driver.hasHorizontalScroller = NO;
6456
+ // The horizontal scroller engages only when the driver's
6457
+ // content is wider than its frame — the runtime pins
6458
+ // content_width to the frame width on regions without a
6459
+ // horizontal axis grant, so vertical-only regions never
6460
+ // grow one.
6461
+ driver.hasHorizontalScroller = YES;
6214
6462
  driver.scrollerStyle = NSScrollerStyleOverlay;
6215
6463
  driver.autohidesScrollers = YES;
6216
- driver.horizontalScrollElasticity = NSScrollElasticityNone;
6217
6464
  driver.automaticallyAdjustsContentInsets = NO;
6218
6465
  NativeSdkScrollDriverDocumentView *document = [[NativeSdkScrollDriverDocumentView alloc] initWithFrame:NSMakeRect(0, 0, MAX(desired.content_width, 1), MAX(desired.content_height, 1))];
6219
6466
  driver.documentView = document;
@@ -6226,52 +6473,159 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
6226
6473
  // against anything but the actual frame races with relayout.
6227
6474
  // Elasticity rides the same reconcile: a region's edge behavior
6228
6475
  // (pin at the edges vs bounce past them) is per-region state the
6229
- // runtime owns.
6230
- NSScrollElasticity elasticity = desired.rubber_band ? NSScrollElasticityAllowed : NSScrollElasticityNone;
6231
- if (driver.verticalScrollElasticity != elasticity) driver.verticalScrollElasticity = elasticity;
6476
+ // runtime owns, armed ONLY on axes the region grants — an
6477
+ // ungranted axis must never bounce or report a native offset the
6478
+ // runtime would ignore and fight back.
6479
+ NSScrollElasticity verticalElasticity = (desired.rubber_band && desired.scrolls_y) ? NSScrollElasticityAllowed : NSScrollElasticityNone;
6480
+ if (driver.verticalScrollElasticity != verticalElasticity) driver.verticalScrollElasticity = verticalElasticity;
6481
+ NSScrollElasticity horizontalElasticity = (desired.rubber_band && desired.scrolls_x) ? NSScrollElasticityAllowed : NSScrollElasticityNone;
6482
+ if (driver.horizontalScrollElasticity != horizontalElasticity) driver.horizontalScrollElasticity = horizontalElasticity;
6483
+ // Scroller chrome follows the grants the same way, and the
6484
+ // grants themselves ride the view for the wheel winner walk.
6485
+ if (driver.hasVerticalScroller != (desired.scrolls_y != 0)) driver.hasVerticalScroller = desired.scrolls_y != 0;
6486
+ if (driver.hasHorizontalScroller != (desired.scrolls_x != 0)) driver.hasHorizontalScroller = desired.scrolls_x != 0;
6487
+ driver.grantsX = desired.scrolls_x != 0;
6488
+ driver.grantsY = desired.scrolls_y != 0;
6489
+ driver.parentDriverId = desired.parent_driver_id;
6490
+ driver.occluderMask = desired.occluder_mask;
6232
6491
  NSRect target = NSMakeRect(desired.x, self.bounds.size.height - desired.y - desired.height, desired.width, desired.height);
6233
6492
  if (!NSEqualRects(driver.frame, target)) driver.frame = target;
6234
6493
  NSSize contentSize = NSMakeSize(MAX(desired.content_width, 1), MAX(desired.content_height, 1));
6235
6494
  if (driver.documentView && !NSEqualSizes(driver.documentView.frame.size, contentSize)) {
6236
6495
  [driver.documentView setFrameSize:contentSize];
6237
6496
  }
6238
- if (created || desired.set_offset) [self applyScrollDriverOffset:driver offsetY:desired.offset_y];
6497
+ if (created || desired.set_offset_x || desired.set_offset_y) {
6498
+ [self applyScrollDriverOffset:driver
6499
+ offsetX:desired.offset_x
6500
+ setX:(created || desired.set_offset_x)
6501
+ offsetY:desired.offset_y
6502
+ setY:(created || desired.set_offset_y)];
6503
+ }
6504
+ [ordered addObject:driver];
6239
6505
  }
6506
+ self.scrollDrivers = ordered;
6240
6507
  }
6241
6508
 
6242
- - (void)applyScrollDriverOffset:(NativeSdkScrollDriverView *)driver offsetY:(double)offsetY {
6509
+ // Per-axis programmatic offset write: an axis the runtime did not move
6510
+ // keeps the native scroller's CURRENT origin, so a vertical write can
6511
+ // never drag a stale horizontal offset over native motion whose
6512
+ // coalesced report is still in flight (and vice versa).
6513
+ - (void)applyScrollDriverOffset:(NativeSdkScrollDriverView *)driver offsetX:(double)offsetX setX:(BOOL)setX offsetY:(double)offsetY setY:(BOOL)setY {
6514
+ const NSPoint current = driver.contentView.bounds.origin;
6243
6515
  self.applyingScrollDriverOffset = YES;
6244
- [driver.contentView setBoundsOrigin:NSMakePoint(0, offsetY)];
6516
+ [driver.contentView setBoundsOrigin:NSMakePoint(setX ? offsetX : current.x, setY ? offsetY : current.y)];
6245
6517
  [driver reflectScrolledClipView:driver.contentView];
6246
6518
  self.applyingScrollDriverOffset = NO;
6247
- }
6248
-
6249
- - (NativeSdkScrollDriverView *)scrollDriverForPoint:(NSPoint)viewPoint {
6250
- // Driver specs arrive in layout pre-order, so the LAST hit is the
6251
- // deepest scroll region under the pointer.
6252
- NativeSdkScrollDriverView *result = nil;
6519
+ // A queued (frame-coalesced) report for THIS driver predates the
6520
+ // programmatic write: rewrite it to the offsets the clip view
6521
+ // actually settled on, so the stale pair can never re-land and
6522
+ // yank the region back after the runtime moved it.
6523
+ if (self.scrollDriverEventPending && self.pendingScrollDriverId == driver.driverId) {
6524
+ self.pendingScrollDriverOffsetX = driver.contentView.bounds.origin.x;
6525
+ self.pendingScrollDriverOffsetY = driver.contentView.bounds.origin.y;
6526
+ }
6527
+ }
6528
+
6529
+ // Direction-aware consumption, the engine's nested-handoff predicate
6530
+ // (`canvasWidgetScrollCanConsumeAxis`) restated against the native
6531
+ // scroller with the engine's EXACT bounds (no edge tolerance — the
6532
+ // engine compares exactly, and a half-point slack would hand an
6533
+ // almost-home inner region's delta to its ancestor where the engine
6534
+ // still moves the inner one): a driver consumes a delta on an axis
6535
+ // only while its offset can still move in that direction, so a
6536
+ // saturated inner region hands an outward swipe to its ancestor
6537
+ // exactly like the engine walk does.
6538
+ static BOOL NativeSdkScrollDriverCanConsumeVertically(NativeSdkScrollDriverView *driver, double canvasDelta) {
6539
+ if (canvasDelta == 0) return NO;
6540
+ const double offset = driver.contentView.bounds.origin.y;
6541
+ const double maxOffset = driver.documentView.frame.size.height - driver.contentView.bounds.size.height;
6542
+ return canvasDelta > 0 ? offset < maxOffset : offset > 0;
6543
+ }
6544
+
6545
+ static BOOL NativeSdkScrollDriverCanConsumeHorizontally(NativeSdkScrollDriverView *driver, double canvasDelta) {
6546
+ if (canvasDelta == 0) return NO;
6547
+ const double offset = driver.contentView.bounds.origin.x;
6548
+ const double maxOffset = driver.documentView.frame.size.width - driver.contentView.bounds.size.width;
6549
+ return canvasDelta > 0 ? offset < maxOffset : offset > 0;
6550
+ }
6551
+
6552
+ // The wheel CANDIDATE CHAIN at a point: the deepest driver under the
6553
+ // point (specs ride layout pre-order, so the last containing entry is
6554
+ // the hit region) plus its ancestors by parent id — the widget-tree
6555
+ // containment chain the engine's route walks. Restricting owner
6556
+ // resolution to this chain keeps a geometrically overlapping but
6557
+ // UNRELATED region (a background scroller behind a floating surface)
6558
+ // from stealing an axis the engine would never give it. Ordered
6559
+ // outermost first, like the spec array.
6560
+ - (NSArray *)wheelCandidateChainAtPoint:(NSPoint)viewPoint {
6561
+ // Occluders first: an overlay containing the point hit-blocks every
6562
+ // region beneath it (bit set in the region's mask), exactly where
6563
+ // the engine's hit test would give the point to the overlay's
6564
+ // branch. Blocked drivers decline outright — the wheel then rides
6565
+ // the wire, where real hit-testing decides.
6566
+ uint32_t blockedBits = 0;
6567
+ NSUInteger occluderIndex = 0;
6568
+ for (NSValue *value in self.scrollOccluderRects) {
6569
+ if (NSPointInRect(viewPoint, value.rectValue)) blockedBits |= (uint32_t)1 << occluderIndex;
6570
+ occluderIndex += 1;
6571
+ }
6572
+ NativeSdkScrollDriverView *hit = nil;
6253
6573
  for (NativeSdkScrollDriverView *driver in self.scrollDrivers) {
6254
- if (NSPointInRect(viewPoint, driver.frame)) result = driver;
6255
- }
6256
- return result;
6257
- }
6258
-
6259
- - (NativeSdkScrollDriverView *)scrollDriverForWheelEvent:(NSEvent *)event {
6260
- if (self.scrollDrivers.count == 0) return nil;
6261
- const BOOL legacy = event.phase == NSEventPhaseNone && event.momentumPhase == NSEventPhaseNone;
6262
- if (legacy) {
6263
- return [self scrollDriverForPoint:[self convertPoint:event.locationInWindow fromView:nil]];
6264
- }
6265
- if (event.phase == NSEventPhaseBegan || event.phase == NSEventPhaseMayBegin) {
6266
- // Lock the gesture to the region under the pointer so momentum
6267
- // keeps scrolling it after the pointer wanders.
6268
- self.activeWheelDriver = [self scrollDriverForPoint:[self convertPoint:event.locationInWindow fromView:nil]];
6269
- }
6270
- NativeSdkScrollDriverView *driver = self.activeWheelDriver;
6271
- if (event.momentumPhase == NSEventPhaseEnded || event.momentumPhase == NSEventPhaseCancelled) {
6272
- self.activeWheelDriver = nil;
6273
- }
6274
- return driver;
6574
+ if ((driver.occluderMask & blockedBits) != 0) continue;
6575
+ if (NSPointInRect(viewPoint, driver.frame)) hit = driver;
6576
+ }
6577
+ if (!hit) return @[];
6578
+ NSMutableArray *chain = [[NSMutableArray alloc] init];
6579
+ NativeSdkScrollDriverView *current = hit;
6580
+ while (current) {
6581
+ if ((current.occluderMask & blockedBits) == 0) [chain insertObject:current atIndex:0];
6582
+ uint64_t parentId = current.parentDriverId;
6583
+ NativeSdkScrollDriverView *parent = nil;
6584
+ if (parentId != 0) {
6585
+ for (NativeSdkScrollDriverView *candidate in self.scrollDrivers) {
6586
+ if (candidate.driverId == parentId) {
6587
+ parent = candidate;
6588
+ break;
6589
+ }
6590
+ }
6591
+ }
6592
+ current = parent;
6593
+ }
6594
+ return chain;
6595
+ }
6596
+
6597
+ // Resolve each axis's OWNER independently over the candidate chain —
6598
+ // the engine's per-axis walk restated over the native drivers: an axis
6599
+ // routes to the DEEPEST chain region that can consume its delta right
6600
+ // now (direction-aware, so a saturated inner region hands an outward
6601
+ // swipe to its ancestor), falling back to the OUTERMOST region granted
6602
+ // that axis — which bounces if elastic (rubber-band needs no range,
6603
+ // short content included) and clamps into a harmless no-op if not,
6604
+ // exactly the engine's outermost-applies rule. Nil means no native
6605
+ // region owns the axis. Elastic-take deliberately never outranks a
6606
+ // consumer: an elastic inner list that saturates while its parent still
6607
+ // has range hands the axis over instead of bouncing forever.
6608
+ - (void)resolveWheelOwnersInChain:(NSArray *)chain
6609
+ canvasDx:(double)canvasDx
6610
+ canvasDy:(double)canvasDy
6611
+ ownerX:(NativeSdkScrollDriverView **)ownerX
6612
+ ownerY:(NativeSdkScrollDriverView **)ownerY {
6613
+ NativeSdkScrollDriverView *consumerX = nil;
6614
+ NativeSdkScrollDriverView *fallbackX = nil;
6615
+ NativeSdkScrollDriverView *consumerY = nil;
6616
+ NativeSdkScrollDriverView *fallbackY = nil;
6617
+ for (NativeSdkScrollDriverView *driver in chain) {
6618
+ if (canvasDx != 0 && driver.grantsX) {
6619
+ if (NativeSdkScrollDriverCanConsumeHorizontally(driver, canvasDx)) consumerX = driver;
6620
+ if (!fallbackX) fallbackX = driver;
6621
+ }
6622
+ if (canvasDy != 0 && driver.grantsY) {
6623
+ if (NativeSdkScrollDriverCanConsumeVertically(driver, canvasDy)) consumerY = driver;
6624
+ if (!fallbackY) fallbackY = driver;
6625
+ }
6626
+ }
6627
+ *ownerX = consumerX ?: fallbackX;
6628
+ *ownerY = consumerY ?: fallbackY;
6275
6629
  }
6276
6630
 
6277
6631
  - (void)scrollDriverBoundsDidChange:(NSNotification *)note {
@@ -6279,17 +6633,18 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
6279
6633
  NSClipView *clipView = note.object;
6280
6634
  for (NativeSdkScrollDriverView *driver in self.scrollDrivers) {
6281
6635
  if (driver.contentView != clipView) continue;
6282
- [self queueScrollDriverEventWithId:driver.driverId offsetY:clipView.bounds.origin.y];
6636
+ [self queueScrollDriverEventWithId:driver.driverId offsetX:clipView.bounds.origin.x offsetY:clipView.bounds.origin.y];
6283
6637
  return;
6284
6638
  }
6285
6639
  }
6286
6640
 
6287
- - (void)queueScrollDriverEventWithId:(uint64_t)driverId offsetY:(double)offsetY {
6641
+ - (void)queueScrollDriverEventWithId:(uint64_t)driverId offsetX:(double)offsetX offsetY:(double)offsetY {
6288
6642
  if (!self.host || self.surfaceLabel.length == 0) return;
6289
6643
  if (self.scrollDriverEventPending && self.pendingScrollDriverId != driverId) {
6290
6644
  [self emitQueuedScrollDriverEvent];
6291
6645
  }
6292
6646
  self.pendingScrollDriverId = driverId;
6647
+ self.pendingScrollDriverOffsetX = offsetX;
6293
6648
  self.pendingScrollDriverOffsetY = offsetY;
6294
6649
  if (self.scrollDriverEventPending) return;
6295
6650
  self.scrollDriverEventPending = YES;
@@ -6311,6 +6666,7 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
6311
6666
  - (void)emitQueuedScrollDriverEvent {
6312
6667
  if (!self.scrollDriverEventPending) return;
6313
6668
  const uint64_t driverId = self.pendingScrollDriverId;
6669
+ const double offsetX = self.pendingScrollDriverOffsetX;
6314
6670
  const double offsetY = self.pendingScrollDriverOffsetY;
6315
6671
  self.scrollDriverEventPending = NO;
6316
6672
  if (!self.host || self.surfaceLabel.length == 0) return;
@@ -6323,6 +6679,7 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
6323
6679
  .view_label_len = [self.surfaceLabel lengthOfBytesUsingEncoding:NSUTF8StringEncoding],
6324
6680
  .timestamp_ns = NativeSdkTimestampNanoseconds(),
6325
6681
  .widget_id = driverId,
6682
+ .scroll_driver_offset_x = offsetX,
6326
6683
  .scroll_driver_offset_y = offsetY,
6327
6684
  }];
6328
6685
  }
@@ -6933,6 +7290,7 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
6933
7290
  - (void)dealloc {
6934
7291
  [self invalidateAppTimers];
6935
7292
  [self audioStop];
7293
+ [self videoStop];
6936
7294
  /* The vDSP plan outlives individual playbacks (created lazily
6937
7295
  * once); the host's end is where it retires. */
6938
7296
  if (self.audioSpectrumFft) {
@@ -6944,6 +7302,10 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
6944
7302
  [NSEvent removeMonitor:self.shortcutEventMonitor];
6945
7303
  self.shortcutEventMonitor = nil;
6946
7304
  }
7305
+ if (self.viewFocusEventMonitor) {
7306
+ [NSEvent removeMonitor:self.viewFocusEventMonitor];
7307
+ self.viewFocusEventMonitor = nil;
7308
+ }
6947
7309
  [self removeAllChildBridgeHandlers];
6948
7310
  for (WKWebView *webView in self.webViews.allValues) {
6949
7311
  [webView.configuration.userContentController removeScriptMessageHandlerForName:@"nativeSdkBridge"];
@@ -7162,6 +7524,7 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
7162
7524
  WKWebView *webView = [[NativeSdkWebView alloc] initWithFrame:container.bounds configuration:configuration];
7163
7525
  ((NativeSdkWebView *)webView).host = self;
7164
7526
  ((NativeSdkWebView *)webView).windowId = windowId;
7527
+ ((NativeSdkWebView *)webView).viewLabel = @"main";
7165
7528
  [webView registerForDraggedTypes:@[NSPasteboardTypeFileURL]];
7166
7529
  webView.wantsLayer = YES;
7167
7530
  webView.layer.zPosition = 0;
@@ -7594,11 +7957,11 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
7594
7957
  return YES;
7595
7958
  }
7596
7959
 
7597
- - (BOOL)setGpuSurfaceScrollDriversInWindow:(uint64_t)windowId label:(NSString *)label drivers:(const native_sdk_appkit_scroll_driver_t *)drivers count:(NSUInteger)count {
7960
+ - (BOOL)setGpuSurfaceScrollDriversInWindow:(uint64_t)windowId label:(NSString *)label drivers:(const native_sdk_appkit_scroll_driver_t *)drivers count:(NSUInteger)count occluders:(const native_sdk_appkit_scroll_occluder_t *)occluders occluderCount:(NSUInteger)occluderCount {
7598
7961
  NSString *key = [self nativeViewKeyForWindow:windowId label:label];
7599
7962
  NSView *view = self.nativeViews[key];
7600
7963
  if (![view isKindOfClass:[NativeSdkMetalSurfaceView class]]) return NO;
7601
- [(NativeSdkMetalSurfaceView *)view setScrollDrivers:drivers count:count];
7964
+ [(NativeSdkMetalSurfaceView *)view setScrollDrivers:drivers count:count occluders:occluders occluderCount:occluderCount];
7602
7965
  return YES;
7603
7966
  }
7604
7967
 
@@ -7844,6 +8207,7 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
7844
8207
  WKWebView *webview = [[NativeSdkWebView alloc] initWithFrame:[self webViewFrameForWindow:window x:x y:y width:width height:height] configuration:configuration];
7845
8208
  ((NativeSdkWebView *)webview).host = self;
7846
8209
  ((NativeSdkWebView *)webview).windowId = windowId;
8210
+ ((NativeSdkWebView *)webview).viewLabel = label;
7847
8211
  [webview registerForDraggedTypes:@[NSPasteboardTypeFileURL]];
7848
8212
  webview.wantsLayer = YES;
7849
8213
  webview.layer.zPosition = layer;
@@ -8545,7 +8909,7 @@ static void NativeSdkApplyProcessDisplayName(NSString *displayName) {
8545
8909
  }
8546
8910
 
8547
8911
  - (NSMenuItem *)commandMenuItem:(NSString *)title command:(NSString *)command key:(NSString *)key modifiers:(uint32_t)modifiers enabled:(BOOL)enabled checked:(BOOL)checked {
8548
- NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:title ?: @"" action:@selector(menuCommandItemClicked:) keyEquivalent:key ?: @""];
8912
+ NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:title ?: @"" action:@selector(menuCommandItemClicked:) keyEquivalent:NativeSdkMenuKeyEquivalent(key ?: @"")];
8549
8913
  item.target = self;
8550
8914
  item.enabled = enabled;
8551
8915
  item.representedObject = command ?: @"";
@@ -8639,6 +9003,31 @@ static void NativeSdkApplyProcessDisplayName(NSString *displayName) {
8639
9003
  return event;
8640
9004
  }];
8641
9005
  }
9006
+ if (!self.viewFocusEventMonitor) {
9007
+ __weak NativeSdkAppKitHost *weakSelf = self;
9008
+ self.viewFocusEventMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:
9009
+ (NSEventMaskLeftMouseDown | NSEventMaskRightMouseDown | NSEventMaskOtherMouseDown)
9010
+ handler:^NSEvent *(NSEvent *event) {
9011
+ NativeSdkAppKitHost *strongSelf = weakSelf;
9012
+ NSView *content = event.window.contentView;
9013
+ if (!strongSelf || !content) return event;
9014
+ NSPoint point = [content convertPoint:event.locationInWindow fromView:nil];
9015
+ NSView *hit = [content hitTest:point];
9016
+ while (hit && ![hit isKindOfClass:[NativeSdkWebView class]]) {
9017
+ hit = hit.superview;
9018
+ }
9019
+ if (![hit isKindOfClass:[NativeSdkWebView class]]) return event;
9020
+ NativeSdkWebView *webView = (NativeSdkWebView *)hit;
9021
+ const char *label = webView.viewLabel.UTF8String ?: "";
9022
+ [strongSelf emitEvent:(native_sdk_appkit_event_t){
9023
+ .kind = NATIVE_SDK_APPKIT_EVENT_VIEW_FOCUSED,
9024
+ .window_id = webView.windowId,
9025
+ .view_label = label,
9026
+ .view_label_len = strlen(label),
9027
+ }];
9028
+ return event;
9029
+ }];
9030
+ }
8642
9031
 
8643
9032
  [self startApplicationActivationObservers];
8644
9033
  [self startAppearanceObservers];
@@ -8725,10 +9114,15 @@ static void NativeSdkApplyProcessDisplayName(NSString *displayName) {
8725
9114
  self.timer = nil;
8726
9115
  [self invalidateAppTimers];
8727
9116
  [self audioStop];
9117
+ [self videoStop];
8728
9118
  if (self.shortcutEventMonitor) {
8729
9119
  [NSEvent removeMonitor:self.shortcutEventMonitor];
8730
9120
  self.shortcutEventMonitor = nil;
8731
9121
  }
9122
+ if (self.viewFocusEventMonitor) {
9123
+ [NSEvent removeMonitor:self.viewFocusEventMonitor];
9124
+ self.viewFocusEventMonitor = nil;
9125
+ }
8732
9126
  [self stopAppearanceObservers];
8733
9127
  [self stopApplicationActivationObservers];
8734
9128
  [NSApp stop:nil];
@@ -8849,6 +9243,22 @@ static void NativeSdkApplyProcessDisplayName(NSString *displayName) {
8849
9243
  });
8850
9244
  return;
8851
9245
  }
9246
+ /* Same hop for the video player's observers: every video entry
9247
+ * point is loop-thread only too. */
9248
+ if (context == NativeSdkAppKitVideoItemStatusContext) {
9249
+ __weak NativeSdkAppKitHost *weakSelf = self;
9250
+ dispatch_async(dispatch_get_main_queue(), ^{
9251
+ [weakSelf videoItemStatusChanged];
9252
+ });
9253
+ return;
9254
+ }
9255
+ if (context == NativeSdkAppKitVideoTimeControlContext) {
9256
+ __weak NativeSdkAppKitHost *weakSelf = self;
9257
+ dispatch_async(dispatch_get_main_queue(), ^{
9258
+ [weakSelf videoTimeControlChanged];
9259
+ });
9260
+ return;
9261
+ }
8852
9262
  [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
8853
9263
  }
8854
9264
 
@@ -9023,7 +9433,12 @@ static double NativeSdkSecondsFromCMTime(CMTime time) {
9023
9433
 
9024
9434
  static CMTime NativeSdkCMTimeFromMs(uint64_t ms) {
9025
9435
  CMTime time;
9026
- time.value = (CMTimeValue)ms;
9436
+ /* The millisecond position arrives as u64; CMTimeValue is signed
9437
+ * 64-bit, so an absurd request past INT64_MAX must clamp rather
9438
+ * than wrap negative. AVPlayer then clamps the (still enormous)
9439
+ * positive time to the item's duration — seek-past-end lands at
9440
+ * the end, per the transport contract. */
9441
+ time.value = (ms > (uint64_t)INT64_MAX) ? INT64_MAX : (CMTimeValue)ms;
9027
9442
  time.timescale = 1000;
9028
9443
  time.flags = kCMTimeFlags_Valid;
9029
9444
  time.epoch = 0;
@@ -9196,9 +9611,14 @@ static int NativeSdkSpectrumComputeBands(native_sdk_spectrum_tap_state_t *state,
9196
9611
  double duration = self.audioItem ? NativeSdkSecondsFromCMTime(self.audioItem.duration) : 0.0;
9197
9612
  if (position > 0) position_ms = (uint64_t)llround(position * 1000.0);
9198
9613
  if (duration > 0) duration_ms = (uint64_t)llround(duration * 1000.0);
9199
- /* rate > 0 is the transport intent (un-paused); the buffering
9200
- * flag beside it says whether audio is actually coming out.
9201
- * Local files never buffer — the flag is stream-only. */
9614
+ /* rate > 0 is the transport intent (un-paused), NOT the
9615
+ * effective rate: a stream stalled in AVPlayer's waiting state
9616
+ * keeps rate at the requested value (see the video twin in
9617
+ * emitVideoEventOfKind for the AVPlayer.h contract), so a
9618
+ * stalled-but-unpaused stream reports playing=1 with the
9619
+ * buffering flag beside it saying whether audio is actually
9620
+ * coming out. Local files never buffer — the flag is
9621
+ * stream-only. */
9202
9622
  playing = player.rate > 0 ? 1 : 0;
9203
9623
  buffering = (!self.audioSourceIsLocal && self.audioBuffering) ? 1 : 0;
9204
9624
  }
@@ -9732,6 +10152,679 @@ static int NativeSdkSpectrumComputeBands(native_sdk_spectrum_tap_state_t *state,
9732
10152
  return 1;
9733
10153
  }
9734
10154
 
10155
+ /* ---------------------------------------------------- video player
10156
+ *
10157
+ * The app's single video player: one AVPlayer whose
10158
+ * AVPlayerItemVideoOutput frames feed the sink push handed to the load
10159
+ * entries. The transport, events, and buffering vocabulary mirror the
10160
+ * audio player above; the one addition is the frame pump — a 1/60 s
10161
+ * timer (the scheduleFrame cadence) that polls the output, converts
10162
+ * each new BGRA pixel buffer into the reusable tightly packed RGBA8
10163
+ * buffer, and pushes it through the sink. Pixels never ride events. */
10164
+
10165
+ /* The sink's per-frame ceiling, mirrored from the Zig side
10166
+ * (max_media_surface_pixel_bytes): the output is sized to FIT it. */
10167
+ #define NATIVE_SDK_VIDEO_MAX_FRAME_BYTES (8 * 1024 * 1024)
10168
+
10169
+ /* Fit the stream's natural size to the frame budget: scale DOWN
10170
+ * preserving aspect when width * height * 4 exceeds it (4K fits to
10171
+ * roughly 1867x1050), never up — a small video decodes at its own
10172
+ * size. */
10173
+ static void NativeSdkVideoFittedSize(double naturalWidth, double naturalHeight, size_t *outWidth, size_t *outHeight) {
10174
+ double width = naturalWidth >= 1.0 ? naturalWidth : 1.0;
10175
+ double height = naturalHeight >= 1.0 ? naturalHeight : 1.0;
10176
+ const double budget_pixels = (double)(NATIVE_SDK_VIDEO_MAX_FRAME_BYTES / 4);
10177
+ const double pixels = width * height;
10178
+ if (pixels > budget_pixels) {
10179
+ const double scale = sqrt(budget_pixels / pixels);
10180
+ width = floor(width * scale);
10181
+ height = floor(height * scale);
10182
+ if (width < 1.0) width = 1.0;
10183
+ if (height < 1.0) height = 1.0;
10184
+ }
10185
+ *outWidth = (size_t)width;
10186
+ *outHeight = (size_t)height;
10187
+ }
10188
+
10189
+ /* Emit one video report carrying the live position/duration readout of
10190
+ * the app's single AVPlayer. Runs on the loop thread — every video
10191
+ * entry point is loop-thread only; the player's KVO and notification
10192
+ * handlers hop to the main queue before landing here. */
10193
+ - (void)emitVideoEventOfKind:(int)kind {
10194
+ AVPlayer *player = self.videoPlayer;
10195
+ uint64_t position_ms = 0;
10196
+ uint64_t duration_ms = 0;
10197
+ int playing = 0;
10198
+ int buffering = 0;
10199
+ if (player) {
10200
+ double position = NativeSdkSecondsFromCMTime(player.currentTime);
10201
+ double duration = self.videoItem ? NativeSdkSecondsFromCMTime(self.videoItem.duration) : 0.0;
10202
+ if (position > 0) position_ms = (uint64_t)llround(position * 1000.0);
10203
+ if (duration > 0) duration_ms = (uint64_t)llround(duration * 1000.0);
10204
+ /* rate > 0 is the transport intent (un-paused), NOT the
10205
+ * effective rate: while a stream stalls into
10206
+ * AVPlayerTimeControlStatusWaitingToPlayAtSpecifiedRate, the
10207
+ * AVPlayer.h contract keeps rate at the requested value ("the
10208
+ * value of the rate property is not currently effective but
10209
+ * instead indicates the rate at which playback will start or
10210
+ * resume"), so a stalled-but-unpaused playback reports
10211
+ * playing=1 with the buffering flag beside it saying whether
10212
+ * frames are actually coming out — the transport control keeps
10213
+ * offering Pause. AVPlayer resets rate to 0.0 on its own only
10214
+ * with waits-to-minimize-stalling disabled (our LOCAL-file
10215
+ * configuration, where a mid-file stall has no bytes to wait
10216
+ * for and playback would not self-resume — reporting paused,
10217
+ * and offering Play, is then the honest affordance). Local
10218
+ * files never buffer — the flag is stream-only. */
10219
+ playing = player.rate > 0 ? 1 : 0;
10220
+ buffering = (!self.videoSourceIsLocal && self.videoBuffering) ? 1 : 0;
10221
+ }
10222
+ native_sdk_appkit_event_t event = {
10223
+ .kind = NATIVE_SDK_APPKIT_EVENT_VIDEO,
10224
+ .video_kind = kind,
10225
+ .video_token = self.videoToken,
10226
+ .video_position_ms = position_ms,
10227
+ .video_duration_ms = duration_ms,
10228
+ .video_playing = playing,
10229
+ .video_buffering = buffering,
10230
+ .timestamp_ns = NativeSdkTimestampNanoseconds(),
10231
+ };
10232
+ if (kind == NATIVE_SDK_APPKIT_VIDEO_EVENT_LOADED) {
10233
+ /* The acknowledgment carries the STREAM's true dimensions —
10234
+ * the honest source geometry, even when the output texture is
10235
+ * fitted smaller to the frame budget. */
10236
+ event.video_width = self.videoStreamWidth;
10237
+ event.video_height = self.videoStreamHeight;
10238
+ }
10239
+ [self emitEvent:event];
10240
+ }
10241
+
10242
+ - (void)stopVideoPositionTimer {
10243
+ [self.videoPositionTimer invalidate];
10244
+ self.videoPositionTimer = nil;
10245
+ }
10246
+
10247
+ - (void)videoPositionTimerFired:(NSTimer *)timer {
10248
+ (void)timer;
10249
+ if (!self.videoPlayer) {
10250
+ [self stopVideoPositionTimer];
10251
+ return;
10252
+ }
10253
+ [self emitVideoEventOfKind:NATIVE_SDK_APPKIT_VIDEO_EVENT_POSITION];
10254
+ }
10255
+
10256
+ - (void)startVideoFrameTimer {
10257
+ if (self.videoFrameTimer) return;
10258
+ /* The pixel clock (1/60 s, the scheduleFrame cadence). Common
10259
+ * modes so frames keep flowing during live resize and menu
10260
+ * tracking (default-mode timers do not fire in tracking
10261
+ * runloops). Block-based with a WEAK host: a target-selector
10262
+ * repeating timer retains its target through the run loop, so a
10263
+ * host destroyed mid-playback could never dealloc — the timer
10264
+ * self-invalidates when the host is gone instead. */
10265
+ __weak NativeSdkAppKitHost *weakSelf = self;
10266
+ NSTimer *tick = [NSTimer timerWithTimeInterval:(1.0 / 60.0)
10267
+ repeats:YES
10268
+ block:^(NSTimer *timer) {
10269
+ NativeSdkAppKitHost *strongSelf = weakSelf;
10270
+ if (!strongSelf) {
10271
+ [timer invalidate];
10272
+ return;
10273
+ }
10274
+ [strongSelf videoFrameTimerFired:timer];
10275
+ }];
10276
+ [[NSRunLoop mainRunLoop] addTimer:tick forMode:NSRunLoopCommonModes];
10277
+ self.videoFrameTimer = tick;
10278
+ }
10279
+
10280
+ - (void)stopVideoFrameTimer {
10281
+ [self.videoFrameTimer invalidate];
10282
+ self.videoFrameTimer = nil;
10283
+ }
10284
+
10285
+ - (void)videoFrameTimerFired:(NSTimer *)timer {
10286
+ (void)timer;
10287
+ if (!self.videoPlayer) {
10288
+ [self stopVideoFrameTimer];
10289
+ return;
10290
+ }
10291
+ [self videoPumpFrame];
10292
+ /* The poster hunt's bound: a paused hunt that has not yielded a
10293
+ * frame within ~3s (180 ticks) stops polling — honest surrender,
10294
+ * the placeholder stays. A PLAYING stream never surrenders here;
10295
+ * its timer belongs to playback. */
10296
+ if (self.videoPosterPending &&
10297
+ self.videoPlayer.timeControlStatus != AVPlayerTimeControlStatusPlaying) {
10298
+ self.videoPosterTicks += 1;
10299
+ if (self.videoPosterTicks > 180) {
10300
+ self.videoPosterPending = NO;
10301
+ [self stopVideoFrameTimer];
10302
+ }
10303
+ }
10304
+ }
10305
+
10306
+ /* One poll of the video output: if a new frame is due at the current
10307
+ * host time, convert it and push it through the sink. Also called
10308
+ * one-shot after pause and seek, so a paused scrub still paints the
10309
+ * frame it landed on. Main-thread only, like every video entry. */
10310
+ - (void)videoPumpFrame {
10311
+ AVPlayerItemVideoOutput *output = self.videoOutput;
10312
+ native_sdk_appkit_video_sink_push_t push = self.videoSinkPush;
10313
+ if (!output || !push || !self.videoFrameBuffer) return;
10314
+ CMTime itemTime = [output itemTimeForHostTime:CACurrentMediaTime()];
10315
+ if (![output hasNewPixelBufferForItemTime:itemTime]) return;
10316
+ CVPixelBufferRef pixels = [output copyPixelBufferForItemTime:itemTime itemTimeForDisplay:NULL];
10317
+ if (!pixels) return;
10318
+ const size_t width = CVPixelBufferGetWidth(pixels);
10319
+ const size_t height = CVPixelBufferGetHeight(pixels);
10320
+ const size_t frame_len = width * height * 4;
10321
+ if (frame_len == 0 || frame_len > self.videoFrameBufferLen) {
10322
+ CFRelease(pixels);
10323
+ return;
10324
+ }
10325
+ /* A failed lock never mapped the buffer: the base address would be
10326
+ * garbage and the matching unlock would unbalance the buffer's lock
10327
+ * count. Drop this frame and keep hunting — the poster latch stays
10328
+ * set for the same reason a converted-but-unpushed tick keeps it
10329
+ * (below): only an actual push verdict may end the hunt. */
10330
+ if (CVPixelBufferLockBaseAddress(pixels, kCVPixelBufferLock_ReadOnly) != kCVReturnSuccess) {
10331
+ CFRelease(pixels);
10332
+ return;
10333
+ }
10334
+ void *base = CVPixelBufferGetBaseAddress(pixels);
10335
+ /* -1 = no push happened (NULL base address or a failed channel
10336
+ * permutation). Only an actual push verdict may end the poster
10337
+ * hunt or release the claim below; a converted-but-unpushed tick
10338
+ * must keep hunting, or a paused load's surface stays blank. */
10339
+ int result = -1;
10340
+ if (base) {
10341
+ /* BGRA -> RGBA is one channel permutation; vImage reads the
10342
+ * buffer's bytesPerRow stride and writes the tightly packed
10343
+ * rows the sink contract requires. */
10344
+ vImage_Buffer source = {
10345
+ .data = base,
10346
+ .height = height,
10347
+ .width = width,
10348
+ .rowBytes = CVPixelBufferGetBytesPerRow(pixels),
10349
+ };
10350
+ vImage_Buffer destination = {
10351
+ .data = self.videoFrameBuffer,
10352
+ .height = height,
10353
+ .width = width,
10354
+ .rowBytes = width * 4,
10355
+ };
10356
+ const uint8_t permute[4] = { 2, 1, 0, 3 };
10357
+ if (vImagePermuteChannels_ARGB8888(&source, &destination, permute, kvImageNoFlags) == kvImageNoError) {
10358
+ result = push(self.videoSinkContext, width, height, self.videoFrameBuffer, frame_len);
10359
+ }
10360
+ }
10361
+ CVPixelBufferUnlockBaseAddress(pixels, kCVPixelBufferLock_ReadOnly);
10362
+ CFRelease(pixels);
10363
+ /* The first delivered frame ends the poster hunt: a paused load
10364
+ * has painted its poster, so the timer stops until play; a playing
10365
+ * load keeps its timer, the latch just clears. */
10366
+ if (result == 0 && self.videoPosterPending) {
10367
+ self.videoPosterPending = NO;
10368
+ AVPlayer *player = self.videoPlayer;
10369
+ if (player && player.timeControlStatus != AVPlayerTimeControlStatusPlaying) {
10370
+ [self stopVideoFrameTimer];
10371
+ }
10372
+ }
10373
+ /* 1 says the receiving claim was released (the sink is
10374
+ * latest-wins; a released claim just means stop pushing) — the
10375
+ * frame timer has nothing left to feed. Any other nonzero result
10376
+ * is one dropped frame; the decode keeps rolling. */
10377
+ if (result == 1) {
10378
+ self.videoPosterPending = NO;
10379
+ [self stopVideoFrameTimer];
10380
+ }
10381
+ }
10382
+
10383
+ /* Local files on the app's single video player. Unlike audio there is
10384
+ * no synchronous decode verdict to probe for (AVAudioPlayer's header
10385
+ * decode has no video twin), so the existence check is the only
10386
+ * synchronous refusal — an undecodable file reports asynchronously as
10387
+ * one FAILED event. */
10388
+ - (int)videoLoadPath:(NSString *)path token:(uint64_t)token pushFn:(native_sdk_appkit_video_sink_push_t)pushFn pushContext:(void *)pushContext {
10389
+ [self videoStop];
10390
+ self.videoToken = token;
10391
+ /* Relative paths resolve against the bundle's Resources inside a
10392
+ * packaged .app (where the process cwd is meaningless — `open`
10393
+ * launches at /), and keep their cwd meaning everywhere else. */
10394
+ NSString *resolved = NativeSdkResolvedAssetFilePath(path);
10395
+ if (![[NSFileManager defaultManager] fileExistsAtPath:resolved]) return 1;
10396
+ AVURLAsset *asset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:resolved] options:nil];
10397
+ AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset];
10398
+ [self videoInstallItem:item localSource:YES pushFn:pushFn pushContext:pushContext];
10399
+ return 0;
10400
+ }
10401
+
10402
+ /* URL sources: a progressive AVPlayer stream — playable as soon as
10403
+ * enough bytes arrive, never download-then-play. No cache layer here
10404
+ * (unlike audio's verified-entry two-step): video bytes are large and
10405
+ * the streaming path alone is the honest slice. Returns 0 for a
10406
+ * started stream, 2 when the URL cannot be parsed; everything
10407
+ * asynchronous — readiness, stalls, natural end, network death —
10408
+ * arrives as EVENT_VIDEO reports. */
10409
+ - (int)videoLoadURL:(NSString *)urlString token:(uint64_t)token pushFn:(native_sdk_appkit_video_sink_push_t)pushFn pushContext:(void *)pushContext {
10410
+ [self videoStop];
10411
+ self.videoToken = token;
10412
+ NSURL *url = [NSURL URLWithString:urlString];
10413
+ if (!url || !url.scheme) return 2;
10414
+ AVURLAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];
10415
+ AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset];
10416
+ [self videoInstallItem:item localSource:NO pushFn:pushFn pushContext:pushContext];
10417
+ return 0;
10418
+ }
10419
+
10420
+ /* Shared install for both sources: the single AVPlayer, its status and
10421
+ * time-control observers, the end/failure notifications, and the sink
10422
+ * destination. The LOADED acknowledgment stays asynchronous by
10423
+ * contract (readyToPlay KVO -> videoItemStatusChanged, which also
10424
+ * attaches the video output — the presentation size is only decoded
10425
+ * then): emitting inside the service call would re-enter the runtime
10426
+ * while it is still dispatching the command that asked for the load. */
10427
+ - (void)videoInstallItem:(AVPlayerItem *)item localSource:(BOOL)localSource pushFn:(native_sdk_appkit_video_sink_push_t)pushFn pushContext:(void *)pushContext {
10428
+ AVPlayer *player = [AVPlayer playerWithPlayerItem:item];
10429
+ /* Stall policy by source: a local file has all its bytes, so
10430
+ * playback starts immediately; a stream keeps the default — start
10431
+ * as soon as sustained playback is likely, roll through short gaps.
10432
+ * Stated explicitly because immediate progressive start is the
10433
+ * contract for streams. */
10434
+ player.automaticallyWaitsToMinimizeStalling = localSource ? NO : YES;
10435
+ self.videoItem = item;
10436
+ self.videoPlayer = player;
10437
+ self.videoSinkPush = pushFn;
10438
+ self.videoSinkContext = pushContext;
10439
+ self.videoSourceIsLocal = localSource;
10440
+ /* Buffering follows timeControlStatus (videoTimeControlChanged):
10441
+ * the moment an un-paused stream needs bytes, the player enters
10442
+ * the waiting state and the observer flips this flag. Presetting
10443
+ * it would make a PAUSED fresh stream read as buffering — a
10444
+ * paused player is paused, not waiting. */
10445
+ self.videoBuffering = NO;
10446
+ self.videoLoadedEmitted = NO;
10447
+ [item addObserver:self
10448
+ forKeyPath:@"status"
10449
+ options:NSKeyValueObservingOptionNew
10450
+ context:NativeSdkAppKitVideoItemStatusContext];
10451
+ [player addObserver:self
10452
+ forKeyPath:@"timeControlStatus"
10453
+ options:NSKeyValueObservingOptionNew
10454
+ context:NativeSdkAppKitVideoTimeControlContext];
10455
+ self.videoObservingStatus = YES;
10456
+ __weak NativeSdkAppKitHost *weakSelf = self;
10457
+ /* Both blocks re-check the notification's item against the CURRENT
10458
+ * one: removeObserver (the teardown a replacing load runs) stops
10459
+ * future deliveries, but a notification already enqueued on the
10460
+ * main queue still executes its block — ungated, a replaced item's
10461
+ * terminal would tear down the replacement's player and emit a
10462
+ * false terminal event for the playback that replaced it. */
10463
+ self.videoEndObserver = [[NSNotificationCenter defaultCenter]
10464
+ addObserverForName:AVPlayerItemDidPlayToEndTimeNotification
10465
+ object:item
10466
+ queue:[NSOperationQueue mainQueue]
10467
+ usingBlock:^(NSNotification *note) {
10468
+ NativeSdkAppKitHost *host = weakSelf;
10469
+ if (!host || note.object != host.videoItem) return;
10470
+ [host videoDidPlayToEnd];
10471
+ }];
10472
+ self.videoFailObserver = [[NSNotificationCenter defaultCenter]
10473
+ addObserverForName:AVPlayerItemFailedToPlayToEndTimeNotification
10474
+ object:item
10475
+ queue:[NSOperationQueue mainQueue]
10476
+ usingBlock:^(NSNotification *note) {
10477
+ NativeSdkAppKitHost *host = weakSelf;
10478
+ if (!host || note.object != host.videoItem) return;
10479
+ [host videoDidFail];
10480
+ }];
10481
+ }
10482
+
10483
+ /* Attach the frame tap once the item is ready — presentationSize is
10484
+ * only decoded then. The output's pixel buffers are BGRA fitted to the
10485
+ * frame budget; the STREAM dimensions recorded here are what LOADED
10486
+ * reports. Returns NO when this playback could never paint a frame:
10487
+ * an item with no video geometry at all (an audio-only file loaded as
10488
+ * video — sound over a permanently blank surface is a broken video
10489
+ * playback, and audio-only sources belong to the audio channel), or a
10490
+ * conversion buffer that cannot be allocated after geometry promised
10491
+ * frames. Either way the caller reports the load FAILED instead of
10492
+ * acknowledging a playback that can never paint. */
10493
+ - (BOOL)videoAttachOutputForItem:(AVPlayerItem *)item {
10494
+ /* Rotated media (iPhone portrait: encoded landscape, presented
10495
+ * through a 90-degree track preferredTransform) needs the
10496
+ * transform BAKED into the vended frames: a raw output tap gets
10497
+ * the encoded orientation — sideways and stretched into the
10498
+ * requested attributes — while AVPlayerLayer would have applied
10499
+ * the transform for presentation. A properties-of-asset video
10500
+ * composition renders it in (verified against a portrait-flagged
10501
+ * H.264 asset: the tap vends encoded orientation without it and
10502
+ * display orientation with it). Identity-transform assets skip
10503
+ * the composition's render pass, and track-less items (streams)
10504
+ * have no transform to bake. */
10505
+ NSArray<AVAssetTrack *> *videoTracks = [item.asset tracksWithMediaType:AVMediaTypeVideo];
10506
+ if (videoTracks.count > 0 && !CGAffineTransformIsIdentity(videoTracks.firstObject.preferredTransform)) {
10507
+ #pragma clang diagnostic push
10508
+ #pragma clang diagnostic ignored "-Wdeprecated-declarations"
10509
+ /* The synchronous variant: this runs at readyToPlay, where the
10510
+ * asset's properties are already loaded, and the completion-
10511
+ * handler replacement is not available on every supported
10512
+ * macOS. */
10513
+ item.videoComposition = [AVMutableVideoComposition videoCompositionWithPropertiesOfAsset:item.asset];
10514
+ #pragma clang diagnostic pop
10515
+ }
10516
+ CGSize natural = item.presentationSize;
10517
+ if (natural.width < 1.0 || natural.height < 1.0) {
10518
+ /* Fallback: the first video track's naturalSize with its
10519
+ * preferredTransform applied (rotated media reports a
10520
+ * transposed natural size). */
10521
+ if (videoTracks.count > 0) {
10522
+ AVAssetTrack *track = videoTracks.firstObject;
10523
+ CGSize transformed = CGSizeApplyAffineTransform(track.naturalSize, track.preferredTransform);
10524
+ natural = CGSizeMake(fabs(transformed.width), fabs(transformed.height));
10525
+ }
10526
+ }
10527
+ if (natural.width < 1.0 || natural.height < 1.0) return NO;
10528
+ self.videoStreamWidth = (uint64_t)llround(natural.width);
10529
+ self.videoStreamHeight = (uint64_t)llround(natural.height);
10530
+ size_t fitted_width = 0;
10531
+ size_t fitted_height = 0;
10532
+ NativeSdkVideoFittedSize(natural.width, natural.height, &fitted_width, &fitted_height);
10533
+ /* The width/height attributes are client REQUIREMENTS on the
10534
+ * vended buffers (AVPlayerItemVideoOutput's pixelBufferAttributes
10535
+ * contract), not hints: the output converts AND scales every frame
10536
+ * to satisfy them, so a 3840x2160 source tapped with fitted
10537
+ * attributes vends fitted-size buffers (verified against a UHD
10538
+ * H.264 asset: requested 1866x1050, vended 1866x1050). The
10539
+ * oversized-frame drop in videoPumpFrame is defense in depth
10540
+ * against a hypothetical host ignoring the attributes, never an
10541
+ * expected path. */
10542
+ AVPlayerItemVideoOutput *output = [[AVPlayerItemVideoOutput alloc] initWithPixelBufferAttributes:@{
10543
+ (id)kCVPixelBufferPixelFormatTypeKey: @(kCVPixelFormatType_32BGRA),
10544
+ (id)kCVPixelBufferWidthKey: @(fitted_width),
10545
+ (id)kCVPixelBufferHeightKey: @(fitted_height),
10546
+ }];
10547
+ [item addOutput:output];
10548
+ self.videoOutput = output;
10549
+ /* The reusable conversion target: one allocation per load at the
10550
+ * output's max frame size, freed on stop/replace. Allocation
10551
+ * failure is a FAILED load, never a silent zero-frame playback. */
10552
+ if (self.videoFrameBuffer) free(self.videoFrameBuffer);
10553
+ self.videoFrameBufferLen = fitted_width * fitted_height * 4;
10554
+ self.videoFrameBuffer = malloc(self.videoFrameBufferLen);
10555
+ if (!self.videoFrameBuffer) {
10556
+ self.videoFrameBufferLen = 0;
10557
+ return NO;
10558
+ }
10559
+ return YES;
10560
+ }
10561
+
10562
+ /* Release the player, its observers, the frame tap, and the conversion
10563
+ * buffer. The sink destination is cleared with them — a retired
10564
+ * playback must never push another frame. */
10565
+ - (void)videoTearDownPlayer {
10566
+ AVPlayerItem *item = self.videoItem;
10567
+ AVPlayer *player = self.videoPlayer;
10568
+ if (self.videoObservingStatus) {
10569
+ [item removeObserver:self forKeyPath:@"status" context:NativeSdkAppKitVideoItemStatusContext];
10570
+ [player removeObserver:self forKeyPath:@"timeControlStatus" context:NativeSdkAppKitVideoTimeControlContext];
10571
+ self.videoObservingStatus = NO;
10572
+ }
10573
+ if (self.videoEndObserver) {
10574
+ [[NSNotificationCenter defaultCenter] removeObserver:self.videoEndObserver];
10575
+ self.videoEndObserver = nil;
10576
+ }
10577
+ if (self.videoFailObserver) {
10578
+ [[NSNotificationCenter defaultCenter] removeObserver:self.videoFailObserver];
10579
+ self.videoFailObserver = nil;
10580
+ }
10581
+ [player pause];
10582
+ if (self.videoOutput && item) [item removeOutput:self.videoOutput];
10583
+ self.videoOutput = nil;
10584
+ self.videoItem = nil;
10585
+ self.videoPlayer = nil;
10586
+ self.videoSinkPush = NULL;
10587
+ self.videoSinkContext = NULL;
10588
+ self.videoSourceIsLocal = NO;
10589
+ self.videoBuffering = NO;
10590
+ self.videoLoadedEmitted = NO;
10591
+ self.videoLooping = NO;
10592
+ self.videoStreamWidth = 0;
10593
+ self.videoStreamHeight = 0;
10594
+ self.videoPosterPending = NO;
10595
+ self.videoPosterTicks = 0;
10596
+ self.videoToken = 0;
10597
+ if (self.videoFrameBuffer) {
10598
+ free(self.videoFrameBuffer);
10599
+ self.videoFrameBuffer = NULL;
10600
+ self.videoFrameBufferLen = 0;
10601
+ }
10602
+ }
10603
+
10604
+ /* Item status flipped (main queue, hopped from KVO): readyToPlay is
10605
+ * the load's LOADED acknowledgment — the geometry is decoded, the
10606
+ * frame tap attaches, and playback is rolling or about to; failed is
10607
+ * the honest terminal report for an unreachable host or an
10608
+ * undecodable payload. */
10609
+ - (void)videoItemStatusChanged {
10610
+ AVPlayerItem *item = self.videoItem;
10611
+ if (!item) return;
10612
+ if (item.status == AVPlayerItemStatusReadyToPlay) {
10613
+ if (self.videoLoadedEmitted) return;
10614
+ self.videoLoadedEmitted = YES;
10615
+ if (![self videoAttachOutputForItem:item]) {
10616
+ /* No video geometry (an audio-only asset) or no conversion
10617
+ * buffer: acknowledging LOADED would promise frames that
10618
+ * can never arrive, so the load fails honestly. */
10619
+ [self videoDidFail];
10620
+ return;
10621
+ }
10622
+ [self emitVideoEventOfKind:NATIVE_SDK_APPKIT_VIDEO_EVENT_LOADED];
10623
+ /* The poster frame: a paused load (autoplay = false) runs no
10624
+ * frame timer, so start a bounded first-frame hunt — the
10625
+ * output needs a beat past readyToPlay to yield the frame at
10626
+ * position zero. A playing load clears the latch at its first
10627
+ * pumped frame and the timer just keeps rolling. */
10628
+ self.videoPosterPending = YES;
10629
+ self.videoPosterTicks = 0;
10630
+ [self startVideoFrameTimer];
10631
+ return;
10632
+ }
10633
+ if (item.status == AVPlayerItemStatusFailed) {
10634
+ [self videoDidFail];
10635
+ }
10636
+ }
10637
+
10638
+ /* timeControlStatus flipped (main queue, hopped from KVO): waiting to
10639
+ * play at the requested rate IS buffering — for streams. A local file
10640
+ * has all its bytes, so the flag never surfaces for local sources
10641
+ * (waits-to-minimize-stalling is off for them anyway). Emit the
10642
+ * transition immediately as a position report so the UI flips its
10643
+ * buffering state now, not at the next 500ms tick. */
10644
+ - (void)videoTimeControlChanged {
10645
+ AVPlayer *player = self.videoPlayer;
10646
+ if (!player) return;
10647
+ /* Playback actually rolling: make sure the pixel clock runs. The
10648
+ * poster hunt may have stopped the frame timer while the stream
10649
+ * buffered (or surrendered past its bound), and nothing else
10650
+ * restarts it when AVPlayer's waiting phase finally ends —
10651
+ * startVideoFrameTimer is idempotent, so a timer videoPlay already
10652
+ * armed is untouched. */
10653
+ if (player.timeControlStatus == AVPlayerTimeControlStatusPlaying) {
10654
+ [self startVideoFrameTimer];
10655
+ }
10656
+ if (self.videoSourceIsLocal) return;
10657
+ BOOL buffering = player.timeControlStatus == AVPlayerTimeControlStatusWaitingToPlayAtSpecifiedRate;
10658
+ if (buffering == self.videoBuffering) return;
10659
+ self.videoBuffering = buffering;
10660
+ /* A transition INTO paused is the caller's own pause landing (rate
10661
+ * hit zero): pause emits no acknowledgment by contract — the
10662
+ * engine's command mirror already cleared its buffering flag — and
10663
+ * position reports are for playback in motion, so the flag update
10664
+ * above stays silent. Waiting and playing transitions still emit:
10665
+ * they are the stream's own news. */
10666
+ if (player.timeControlStatus == AVPlayerTimeControlStatusPaused) return;
10667
+ [self emitVideoEventOfKind:NATIVE_SDK_APPKIT_VIDEO_EVENT_POSITION];
10668
+ }
10669
+
10670
+ /* Natural end of the video, both sources. A looping playback wraps to
10671
+ * zero and keeps rolling, emitting NOTHING — a playback that never
10672
+ * ends never completes (the documented contract); position ticks keep
10673
+ * telling the truth on their own cadence. A non-looping end is
10674
+ * retire-before-emit, the audio pattern: the completion Msg routinely
10675
+ * starts the NEXT video from inside its own dispatch, and tearing down
10676
+ * afterwards would destroy the player that load just installed. The
10677
+ * duration is captured first so the event still carries the honest
10678
+ * terminal position. */
10679
+ - (void)videoDidPlayToEnd {
10680
+ if (!self.videoPlayer) return;
10681
+ if (self.videoLooping) {
10682
+ CMTime zero = NativeSdkCMTimeFromMs(0);
10683
+ [self.videoPlayer seekToTime:zero toleranceBefore:zero toleranceAfter:zero];
10684
+ [self.videoPlayer play];
10685
+ return;
10686
+ }
10687
+ [self stopVideoPositionTimer];
10688
+ [self stopVideoFrameTimer];
10689
+ uint64_t duration_ms = 0;
10690
+ if (self.videoItem) {
10691
+ double duration = NativeSdkSecondsFromCMTime(self.videoItem.duration);
10692
+ if (duration > 0) duration_ms = (uint64_t)llround(duration * 1000.0);
10693
+ }
10694
+ const uint64_t token = self.videoToken;
10695
+ [self videoTearDownPlayer];
10696
+ [self emitEvent:(native_sdk_appkit_event_t){
10697
+ .kind = NATIVE_SDK_APPKIT_EVENT_VIDEO,
10698
+ .video_kind = NATIVE_SDK_APPKIT_VIDEO_EVENT_COMPLETED,
10699
+ .video_token = token,
10700
+ .video_position_ms = duration_ms,
10701
+ .video_duration_ms = duration_ms,
10702
+ .video_playing = 0,
10703
+ .video_buffering = 0,
10704
+ .timestamp_ns = NativeSdkTimestampNanoseconds(),
10705
+ }];
10706
+ }
10707
+
10708
+ /* Playback died — a stream lost its network, a local file hit a decode
10709
+ * error mid-file, or an item never became playable (an undecodable
10710
+ * payload, an unreachable host): one FAILED event, player retired
10711
+ * first. */
10712
+ - (void)videoDidFail {
10713
+ if (!self.videoPlayer) return;
10714
+ [self stopVideoPositionTimer];
10715
+ [self stopVideoFrameTimer];
10716
+ const uint64_t token = self.videoToken;
10717
+ [self videoTearDownPlayer];
10718
+ [self emitEvent:(native_sdk_appkit_event_t){
10719
+ .kind = NATIVE_SDK_APPKIT_EVENT_VIDEO,
10720
+ .video_kind = NATIVE_SDK_APPKIT_VIDEO_EVENT_FAILED,
10721
+ .video_token = token,
10722
+ .video_position_ms = 0,
10723
+ .video_duration_ms = 0,
10724
+ .video_playing = 0,
10725
+ .video_buffering = 0,
10726
+ .timestamp_ns = NativeSdkTimestampNanoseconds(),
10727
+ }];
10728
+ }
10729
+
10730
+ - (int)videoPlay {
10731
+ AVPlayer *player = self.videoPlayer;
10732
+ if (!player) return 0;
10733
+ /* AVPlayer's play is asynchronous by nature (it starts when
10734
+ * buffered bytes allow), so play always "applies" — readiness and
10735
+ * stalls report through the event stream. */
10736
+ [player play];
10737
+ if (!self.videoPositionTimer) {
10738
+ /* Common modes for the same reason app timers use them: the
10739
+ * readout must keep ticking while a menu is open or the window
10740
+ * is live-resizing. Weak-host block timer, the pixel clock's
10741
+ * rule: no retain cycle through the run loop. */
10742
+ __weak NativeSdkAppKitHost *weakSelf = self;
10743
+ NSTimer *tick = [NSTimer timerWithTimeInterval:0.5
10744
+ repeats:YES
10745
+ block:^(NSTimer *timer) {
10746
+ NativeSdkAppKitHost *strongSelf = weakSelf;
10747
+ if (!strongSelf) {
10748
+ [timer invalidate];
10749
+ return;
10750
+ }
10751
+ [strongSelf videoPositionTimerFired:timer];
10752
+ }];
10753
+ [[NSRunLoop mainRunLoop] addTimer:tick forMode:NSRunLoopCommonModes];
10754
+ self.videoPositionTimer = tick;
10755
+ }
10756
+ [self startVideoFrameTimer];
10757
+ return 1;
10758
+ }
10759
+
10760
+ - (int)videoPause {
10761
+ AVPlayer *player = self.videoPlayer;
10762
+ if (!player) return 0;
10763
+ [player pause];
10764
+ [self stopVideoPositionTimer];
10765
+ [self stopVideoFrameTimer];
10766
+ /* One final poll: the frame the pause landed on may not have been
10767
+ * pumped yet, and a paused surface should hold it. */
10768
+ [self videoPumpFrame];
10769
+ return 1;
10770
+ }
10771
+
10772
+ - (int)videoStop {
10773
+ [self stopVideoPositionTimer];
10774
+ [self stopVideoFrameTimer];
10775
+ if (!self.videoPlayer) return 0;
10776
+ [self videoTearDownPlayer];
10777
+ return 1;
10778
+ }
10779
+
10780
+ - (int)videoSeekToMs:(uint64_t)positionMs {
10781
+ AVPlayer *player = self.videoPlayer;
10782
+ if (!player) return 0;
10783
+ /* AVPlayer clamps to the seekable ranges it has (or fetches the
10784
+ * range it needs); exact tolerance keeps the readout honest
10785
+ * against the requested position. */
10786
+ CMTime zero = NativeSdkCMTimeFromMs(0);
10787
+ __weak NativeSdkAppKitHost *weakSelf = self;
10788
+ [player seekToTime:NativeSdkCMTimeFromMs(positionMs)
10789
+ toleranceBefore:zero
10790
+ toleranceAfter:zero
10791
+ completionHandler:^(BOOL finished) {
10792
+ if (!finished) return;
10793
+ /* One-shot poll on the loop thread so a PAUSED scrub still
10794
+ * paints the sought frame — the frame timer only runs while
10795
+ * playing. */
10796
+ dispatch_async(dispatch_get_main_queue(), ^{
10797
+ [weakSelf videoPumpFrame];
10798
+ });
10799
+ }];
10800
+ return 1;
10801
+ }
10802
+
10803
+ - (int)videoSetVolume:(double)volume {
10804
+ AVPlayer *player = self.videoPlayer;
10805
+ if (!player) return 0;
10806
+ player.volume = (float)volume;
10807
+ return 1;
10808
+ }
10809
+
10810
+ - (int)videoSetMuted:(BOOL)muted {
10811
+ AVPlayer *player = self.videoPlayer;
10812
+ if (!player) return 0;
10813
+ player.muted = muted;
10814
+ return 1;
10815
+ }
10816
+
10817
+ - (int)videoSetLoop:(BOOL)loop {
10818
+ AVPlayer *player = self.videoPlayer;
10819
+ if (!player) return 0;
10820
+ self.videoLooping = loop;
10821
+ /* A looping player must not pause itself at the end notification's
10822
+ * moment — the wrap seek in videoDidPlayToEnd restarts it
10823
+ * seamlessly. */
10824
+ player.actionAtItemEnd = loop ? AVPlayerActionAtItemEndNone : AVPlayerActionAtItemEndPause;
10825
+ return 1;
10826
+ }
10827
+
9735
10828
  - (void)scheduleBridgeFrames {
9736
10829
  self.bridgeFrameKeepalive = NativeSdkBridgeFrameKeepaliveFrames;
9737
10830
  [self scheduleFrame];
@@ -10094,6 +11187,58 @@ static NSString *NativeSdkOriginForURL(NSURL *url) {
10094
11187
  return [NSString stringWithFormat:@"%@://%@", scheme, host];
10095
11188
  }
10096
11189
 
11190
+ /* The canonical key name -> NSMenuItem key equivalent. Single characters
11191
+ * pass through; named keys become the character AppKit expects (function
11192
+ * keys and navigation keys are private-use unichars, editing keys their
11193
+ * control characters). An unknown name degrades to no key equivalent
11194
+ * rather than a multi-character string AppKit would misread. */
11195
+ static NSString *NativeSdkMenuKeyEquivalent(NSString *key) {
11196
+ if (key.length == 0) return @"";
11197
+ // Lowercase single characters too (key names validate
11198
+ // case-insensitively): an uppercase key equivalent implies Shift to
11199
+ // AppKit, which the explicit modifier mask already expresses.
11200
+ if (key.length == 1) return key.lowercaseString;
11201
+ static NSDictionary<NSString *, NSString *> *named = nil;
11202
+ static dispatch_once_t once;
11203
+ dispatch_once(&once, ^{
11204
+ named = @{
11205
+ @"escape": [NSString stringWithFormat:@"%C", (unichar)0x1b],
11206
+ @"enter": @"\r",
11207
+ @"tab": @"\t",
11208
+ @"space": @" ",
11209
+ /* The physical Mac Delete/backspace key emits 0x7f (what the
11210
+ * key-event normalizer maps to "backspace"), not the nominal
11211
+ * BS control 0x08 — key equivalents must match what the key
11212
+ * actually produces or the accelerator never fires. */
11213
+ @"backspace": [NSString stringWithFormat:@"%C", (unichar)0x7f],
11214
+ @"arrowup": [NSString stringWithFormat:@"%C", (unichar)NSUpArrowFunctionKey],
11215
+ @"arrowdown": [NSString stringWithFormat:@"%C", (unichar)NSDownArrowFunctionKey],
11216
+ @"arrowleft": [NSString stringWithFormat:@"%C", (unichar)NSLeftArrowFunctionKey],
11217
+ @"arrowright": [NSString stringWithFormat:@"%C", (unichar)NSRightArrowFunctionKey],
11218
+ @"delete": [NSString stringWithFormat:@"%C", (unichar)NSDeleteFunctionKey],
11219
+ @"home": [NSString stringWithFormat:@"%C", (unichar)NSHomeFunctionKey],
11220
+ @"end": [NSString stringWithFormat:@"%C", (unichar)NSEndFunctionKey],
11221
+ @"pageup": [NSString stringWithFormat:@"%C", (unichar)NSPageUpFunctionKey],
11222
+ @"pagedown": [NSString stringWithFormat:@"%C", (unichar)NSPageDownFunctionKey],
11223
+ @"insert": [NSString stringWithFormat:@"%C", (unichar)NSInsertFunctionKey],
11224
+ @"f1": [NSString stringWithFormat:@"%C", (unichar)NSF1FunctionKey],
11225
+ @"f2": [NSString stringWithFormat:@"%C", (unichar)NSF2FunctionKey],
11226
+ @"f3": [NSString stringWithFormat:@"%C", (unichar)NSF3FunctionKey],
11227
+ @"f4": [NSString stringWithFormat:@"%C", (unichar)NSF4FunctionKey],
11228
+ @"f5": [NSString stringWithFormat:@"%C", (unichar)NSF5FunctionKey],
11229
+ @"f6": [NSString stringWithFormat:@"%C", (unichar)NSF6FunctionKey],
11230
+ @"f7": [NSString stringWithFormat:@"%C", (unichar)NSF7FunctionKey],
11231
+ @"f8": [NSString stringWithFormat:@"%C", (unichar)NSF8FunctionKey],
11232
+ @"f9": [NSString stringWithFormat:@"%C", (unichar)NSF9FunctionKey],
11233
+ @"f10": [NSString stringWithFormat:@"%C", (unichar)NSF10FunctionKey],
11234
+ @"f11": [NSString stringWithFormat:@"%C", (unichar)NSF11FunctionKey],
11235
+ @"f12": [NSString stringWithFormat:@"%C", (unichar)NSF12FunctionKey],
11236
+ };
11237
+ });
11238
+ NSString *equivalent = named[key.lowercaseString];
11239
+ return equivalent ?: @"";
11240
+ }
11241
+
10097
11242
  static NSString *NativeSdkShortcutKeyForEvent(NSEvent *event) {
10098
11243
  NSString *characters = event.charactersIgnoringModifiers ?: @"";
10099
11244
  if (characters.length == 0) return @"";
@@ -10106,6 +11251,21 @@ static NSString *NativeSdkShortcutKeyForEvent(NSEvent *event) {
10106
11251
  case NSDeleteFunctionKey: return @"delete";
10107
11252
  case NSHomeFunctionKey: return @"home";
10108
11253
  case NSEndFunctionKey: return @"end";
11254
+ case NSPageUpFunctionKey: return @"pageup";
11255
+ case NSPageDownFunctionKey: return @"pagedown";
11256
+ case NSInsertFunctionKey: return @"insert";
11257
+ case NSF1FunctionKey: return @"f1";
11258
+ case NSF2FunctionKey: return @"f2";
11259
+ case NSF3FunctionKey: return @"f3";
11260
+ case NSF4FunctionKey: return @"f4";
11261
+ case NSF5FunctionKey: return @"f5";
11262
+ case NSF6FunctionKey: return @"f6";
11263
+ case NSF7FunctionKey: return @"f7";
11264
+ case NSF8FunctionKey: return @"f8";
11265
+ case NSF9FunctionKey: return @"f9";
11266
+ case NSF10FunctionKey: return @"f10";
11267
+ case NSF11FunctionKey: return @"f11";
11268
+ case NSF12FunctionKey: return @"f12";
10109
11269
  case 0x1b: return @"escape";
10110
11270
  case '\r': return @"enter";
10111
11271
  case '\t': return @"tab";
@@ -10137,6 +11297,14 @@ static NSString *NativeSdkShortcutKeyForEvent(NSEvent *event) {
10137
11297
  }
10138
11298
  }
10139
11299
 
11300
+ static BOOL NativeSdkTextNavigationNeedsRawKeyEvent(NSEvent *event) {
11301
+ if (!event) return NO;
11302
+ NSEventModifierFlags flags = event.modifierFlags & NSEventModifierFlagDeviceIndependentFlagsMask;
11303
+ if ((flags & (NSEventModifierFlagCommand | NSEventModifierFlagOption)) == 0) return NO;
11304
+ NSString *key = NativeSdkShortcutKeyForEvent(event);
11305
+ return [key isEqualToString:@"arrowleft"] || [key isEqualToString:@"arrowright"];
11306
+ }
11307
+
10140
11308
  static BOOL NativeSdkShortcutUsesImplicitShift(NSString *key, NSEvent *event) {
10141
11309
  if ((event.modifierFlags & NSEventModifierFlagShift) == 0) return NO;
10142
11310
  if (key.length != 1) return NO;
@@ -10321,6 +11489,55 @@ int native_sdk_appkit_audio_set_volume(native_sdk_appkit_host_t *host, double vo
10321
11489
  return [object audioSetVolume:volume];
10322
11490
  }
10323
11491
 
11492
+ 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) {
11493
+ NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
11494
+ NSString *path_string = [[NSString alloc] initWithBytes:path length:path_len encoding:NSUTF8StringEncoding];
11495
+ if (!path_string) return 1;
11496
+ return [object videoLoadPath:path_string token:token pushFn:push_fn pushContext:push_context];
11497
+ }
11498
+
11499
+ int native_sdk_appkit_video_load_url(native_sdk_appkit_host_t *host, const char *url, size_t url_len, uint64_t token, native_sdk_appkit_video_sink_push_t push_fn, void *push_context) {
11500
+ NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
11501
+ NSString *url_string = [[NSString alloc] initWithBytes:url length:url_len encoding:NSUTF8StringEncoding];
11502
+ if (!url_string) return 2;
11503
+ return [object videoLoadURL:url_string token:token pushFn:push_fn pushContext:push_context];
11504
+ }
11505
+
11506
+ int native_sdk_appkit_video_play(native_sdk_appkit_host_t *host) {
11507
+ NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
11508
+ return [object videoPlay];
11509
+ }
11510
+
11511
+ int native_sdk_appkit_video_pause(native_sdk_appkit_host_t *host) {
11512
+ NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
11513
+ return [object videoPause];
11514
+ }
11515
+
11516
+ int native_sdk_appkit_video_stop(native_sdk_appkit_host_t *host) {
11517
+ NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
11518
+ return [object videoStop];
11519
+ }
11520
+
11521
+ int native_sdk_appkit_video_seek(native_sdk_appkit_host_t *host, uint64_t position_ms) {
11522
+ NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
11523
+ return [object videoSeekToMs:position_ms];
11524
+ }
11525
+
11526
+ int native_sdk_appkit_video_set_volume(native_sdk_appkit_host_t *host, double volume) {
11527
+ NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
11528
+ return [object videoSetVolume:volume];
11529
+ }
11530
+
11531
+ int native_sdk_appkit_video_set_muted(native_sdk_appkit_host_t *host, int muted) {
11532
+ NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
11533
+ return [object videoSetMuted:(muted != 0)];
11534
+ }
11535
+
11536
+ int native_sdk_appkit_video_set_loop(native_sdk_appkit_host_t *host, int loop) {
11537
+ NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
11538
+ return [object videoSetLoop:(loop != 0)];
11539
+ }
11540
+
10324
11541
  void native_sdk_appkit_wake(native_sdk_appkit_host_t *host) {
10325
11542
  NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
10326
11543
  [object wakeFromAnyThread];
@@ -10610,10 +11827,10 @@ int native_sdk_appkit_note_gpu_surface_input(native_sdk_appkit_host_t *host, uin
10610
11827
  return [object noteGpuSurfaceInputInWindow:window_id label:labelString ?: @""] ? 1 : 0;
10611
11828
  }
10612
11829
 
10613
- int native_sdk_appkit_set_gpu_surface_scroll_drivers(native_sdk_appkit_host_t *host, uint64_t window_id, const char *label, size_t label_len, const native_sdk_appkit_scroll_driver_t *drivers, size_t count) {
11830
+ int native_sdk_appkit_set_gpu_surface_scroll_drivers(native_sdk_appkit_host_t *host, uint64_t window_id, const char *label, size_t label_len, const native_sdk_appkit_scroll_driver_t *drivers, size_t count, const native_sdk_appkit_scroll_occluder_t *occluders, size_t occluder_count) {
10614
11831
  NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
10615
11832
  NSString *labelString = label ? [[NSString alloc] initWithBytes:label length:label_len encoding:NSUTF8StringEncoding] : @"";
10616
- return [object setGpuSurfaceScrollDriversInWindow:window_id label:labelString ?: @"" drivers:drivers count:count] ? 1 : 0;
11833
+ return [object setGpuSurfaceScrollDriversInWindow:window_id label:labelString ?: @"" drivers:drivers count:count occluders:occluders occluderCount:occluder_count] ? 1 : 0;
10617
11834
  }
10618
11835
 
10619
11836
  int native_sdk_appkit_show_context_menu(native_sdk_appkit_host_t *host, uint64_t window_id, const char *label, size_t label_len, double x, double y, uint64_t token, const native_sdk_appkit_context_menu_item_t *items, size_t count) {