@native-sdk/cli 0.5.3 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/build/app.zig +91 -2
  2. package/build.zig +756 -5
  3. package/build.zig.zon +7 -0
  4. package/native-sdk.d.ts +19 -1
  5. package/package.json +9 -9
  6. package/packages/core/package-lock.json +2 -2
  7. package/packages/core/package.json +1 -1
  8. package/packages/core/rt/rt.zig +416 -9
  9. package/packages/core/sdk/core.ts +706 -5
  10. package/packages/core/sdk/events.ts +17 -8
  11. package/packages/core/src/checker.ts +305 -2
  12. package/packages/core/src/diagnostics.ts +12 -0
  13. package/packages/core/src/emitter.ts +3187 -264
  14. package/packages/core/src/typed_ast.ts +51 -4
  15. package/packages/core/src/types.ts +34 -1
  16. package/skill-data/native-ui/SKILL.md +42 -4
  17. package/skill-data/ts-core/SKILL.md +13 -3
  18. package/src/app_runner/root.zig +112 -10
  19. package/src/app_runner/ts_core_main.zig +4 -0
  20. package/src/automation/layout_fingerprint.zig +160 -0
  21. package/src/automation/protocol.zig +82 -33
  22. package/src/automation/root.zig +1 -0
  23. package/src/automation/server.zig +1 -1
  24. package/src/automation/snapshot.zig +68 -9
  25. package/src/automation/watcher.zig +1 -1
  26. package/src/embed/host.zig +5 -0
  27. package/src/embed/tests.zig +119 -1
  28. package/src/embed/ui_host.zig +13 -0
  29. package/src/platform/linux/gtk_host.c +639 -16
  30. package/src/platform/linux/gtk_host.h +25 -0
  31. package/src/platform/linux/root.zig +351 -7
  32. package/src/platform/macos/appkit_host.h +152 -8
  33. package/src/platform/macos/appkit_host.m +1816 -100
  34. package/src/platform/macos/cef_host.mm +372 -11
  35. package/src/platform/macos/root.zig +379 -11
  36. package/src/platform/null_platform.zig +696 -9
  37. package/src/platform/null_platform_tests.zig +35 -0
  38. package/src/platform/root.zig +42 -0
  39. package/src/platform/types.zig +524 -18
  40. package/src/platform/windows/root.zig +432 -9
  41. package/src/platform/windows/webview2_host.cpp +482 -45
  42. package/src/primitives/app_manifest/comptime_scene.zig +5 -0
  43. package/src/primitives/app_manifest/root.zig +1 -0
  44. package/src/primitives/app_manifest/types.zig +32 -0
  45. package/src/primitives/app_manifest/validation.zig +18 -0
  46. package/src/primitives/canvas/a11y_audit.zig +33 -11
  47. package/src/primitives/canvas/a11y_audit_tests.zig +20 -0
  48. package/src/primitives/canvas/drawing.zig +25 -0
  49. package/src/primitives/canvas/equality.zig +8 -0
  50. package/src/primitives/canvas/events.zig +103 -16
  51. package/src/primitives/canvas/frame.zig +125 -1
  52. package/src/primitives/canvas/layout_audit.zig +22 -5
  53. package/src/primitives/canvas/markdown_hostile_tests.zig +8 -4
  54. package/src/primitives/canvas/render_tests.zig +13 -10
  55. package/src/primitives/canvas/root.zig +48 -0
  56. package/src/primitives/canvas/terminal_box.zig +471 -0
  57. package/src/primitives/canvas/terminal_grid.zig +978 -0
  58. package/src/primitives/canvas/terminal_grid_tests.zig +1093 -0
  59. package/src/primitives/canvas/test_support.zig +1 -0
  60. package/src/primitives/canvas/tests.zig +2 -0
  61. package/src/primitives/canvas/text_tests.zig +39 -4
  62. package/src/primitives/canvas/tokens.zig +115 -12
  63. package/src/primitives/canvas/ui.zig +535 -12
  64. package/src/primitives/canvas/ui_markup.zig +253 -36
  65. package/src/primitives/canvas/ui_markup_binary.zig +4 -1
  66. package/src/primitives/canvas/ui_markup_compiled.zig +195 -9
  67. package/src/primitives/canvas/ui_markup_compiled_tests.zig +188 -8
  68. package/src/primitives/canvas/ui_markup_contract.zig +89 -6
  69. package/src/primitives/canvas/ui_markup_contract_tests.zig +65 -1
  70. package/src/primitives/canvas/ui_markup_huge_document_tests.zig +154 -0
  71. package/src/primitives/canvas/ui_markup_huge_model_tests.zig +1 -0
  72. package/src/primitives/canvas/ui_markup_reflect.zig +75 -24
  73. package/src/primitives/canvas/ui_markup_tests.zig +178 -9
  74. package/src/primitives/canvas/ui_markup_view.zig +220 -11
  75. package/src/primitives/canvas/ui_markup_view_tests.zig +553 -28
  76. package/src/primitives/canvas/ui_schema.zig +110 -17
  77. package/src/primitives/canvas/ui_schema_tests.zig +18 -10
  78. package/src/primitives/canvas/ui_tests.zig +141 -9
  79. package/src/primitives/canvas/widget_access.zig +28 -2
  80. package/src/primitives/canvas/widget_anchored_tests.zig +48 -0
  81. package/src/primitives/canvas/widget_invalidation.zig +81 -1
  82. package/src/primitives/canvas/widget_layout.zig +59 -11
  83. package/src/primitives/canvas/widget_layout_tests.zig +125 -4
  84. package/src/primitives/canvas/widget_render.zig +272 -18
  85. package/src/primitives/canvas/widget_render_scroll.zig +108 -27
  86. package/src/primitives/canvas/widget_routing.zig +59 -7
  87. package/src/primitives/canvas/widget_runtime.zig +23 -0
  88. package/src/primitives/canvas/widget_runtime_tests.zig +149 -0
  89. package/src/primitives/canvas/widget_semantics.zig +119 -11
  90. package/src/primitives/canvas/widget_semantics_tests.zig +409 -0
  91. package/src/primitives/canvas/widget_tree.zig +17 -0
  92. package/src/primitives/canvas/widgets.zig +132 -0
  93. package/src/root.zig +23 -0
  94. package/src/runtime/api.zig +76 -5
  95. package/src/runtime/automation_commands.zig +20 -1
  96. package/src/runtime/automation_snapshot.zig +25 -1
  97. package/src/runtime/automation_widget_dispatch.zig +73 -8
  98. package/src/runtime/bridge_payload.zig +8 -0
  99. package/src/runtime/bridge_responses.zig +5 -0
  100. package/src/runtime/builtin_bridge.zig +9 -4
  101. package/src/runtime/canvas_font_tests.zig +439 -2
  102. package/src/runtime/canvas_fonts.zig +61 -6
  103. package/src/runtime/canvas_frame.zig +62 -7
  104. package/src/runtime/canvas_frame_animation_tests.zig +5 -4
  105. package/src/runtime/canvas_frame_helpers.zig +190 -1
  106. package/src/runtime/canvas_frame_invalidation_tests.zig +531 -0
  107. package/src/runtime/canvas_frame_patch_tests.zig +161 -10
  108. package/src/runtime/canvas_frame_retained_tests.zig +5 -2
  109. package/src/runtime/canvas_image_tests.zig +195 -0
  110. package/src/runtime/canvas_images.zig +45 -12
  111. package/src/runtime/canvas_widget_accessibility_tests.zig +1 -1
  112. package/src/runtime/canvas_widget_clipboard_tests.zig +40 -0
  113. package/src/runtime/canvas_widget_context_menu.zig +269 -32
  114. package/src/runtime/canvas_widget_context_menu_tests.zig +640 -14
  115. package/src/runtime/canvas_widget_display.zig +1 -1
  116. package/src/runtime/canvas_widget_event_tests.zig +1823 -0
  117. package/src/runtime/canvas_widget_events.zig +240 -24
  118. package/src/runtime/canvas_widget_runtime.zig +213 -29
  119. package/src/runtime/canvas_widget_scroll_driver_tests.zig +170 -7
  120. package/src/runtime/canvas_widget_scroll_drivers.zig +151 -17
  121. package/src/runtime/canvas_widget_scroll_tests.zig +435 -23
  122. package/src/runtime/canvas_widget_state.zig +6 -0
  123. package/src/runtime/canvas_widget_text_tests.zig +1 -1
  124. package/src/runtime/core.zig +131 -13
  125. package/src/runtime/effects.zig +8136 -180
  126. package/src/runtime/effects_channel_tests.zig +3519 -0
  127. package/src/runtime/effects_fetch_tests.zig +89 -1
  128. package/src/runtime/effects_file_tests.zig +41 -1
  129. package/src/runtime/effects_image_tests.zig +1304 -0
  130. package/src/runtime/effects_pty_tests.zig +1362 -0
  131. package/src/runtime/effects_tests.zig +167 -9
  132. package/src/runtime/effects_video_tests.zig +3609 -0
  133. package/src/runtime/flow.zig +42 -4
  134. package/src/runtime/gpu_surface_events.zig +473 -13
  135. package/src/runtime/media_surface.zig +116 -11
  136. package/src/runtime/media_surface_tests.zig +61 -0
  137. package/src/runtime/pty.zig +1252 -0
  138. package/src/runtime/pty_windows.zig +1780 -0
  139. package/src/runtime/root.zig +36 -0
  140. package/src/runtime/runtime_event_tests.zig +20 -1
  141. package/src/runtime/session_blobs.zig +689 -0
  142. package/src/runtime/session_journal.zig +432 -62
  143. package/src/runtime/session_record.zig +43 -2
  144. package/src/runtime/session_replay.zig +556 -20
  145. package/src/runtime/session_tests.zig +2087 -1
  146. package/src/runtime/shell_layout.zig +7 -0
  147. package/src/runtime/terminal_session.zig +1569 -0
  148. package/src/runtime/terminal_session_tests.zig +450 -0
  149. package/src/runtime/terminal_vt_ghostty.zig +15 -0
  150. package/src/runtime/terminal_vt_stub.zig +13 -0
  151. package/src/runtime/testdata/fonts/NotoSansSC-Receipt.ttf +0 -0
  152. package/src/runtime/testdata/fonts/OFL.txt +93 -0
  153. package/src/runtime/tests.zig +8 -0
  154. package/src/runtime/ts_core_host.zig +1320 -45
  155. package/src/runtime/ts_core_host_tests.zig +1100 -1
  156. package/src/runtime/ts_ui_app.zig +23 -5
  157. package/src/runtime/ui_app.zig +2444 -69
  158. package/src/runtime/ui_app_tests.zig +3171 -744
  159. package/src/runtime/ui_app_virtual_variable_tests.zig +4 -2
  160. package/src/runtime/ui_app_window_tests.zig +736 -0
  161. package/src/runtime/view.zig +190 -2
  162. package/src/runtime/view_widget_scroll.zig +218 -68
  163. package/src/runtime/view_widget_text.zig +11 -2
  164. package/src/runtime/view_widget_tree.zig +111 -3
  165. package/src/runtime/window_command_bridge_tests.zig +117 -0
  166. package/src/runtime/window_storage.zig +77 -2
  167. package/src/runtime/window_view_runtime.zig +34 -2
  168. package/src/runtime/window_views.zig +62 -1
  169. package/src/terminal_session_tests_root.zig +15 -0
  170. package/src/tooling/manifest.zig +75 -0
  171. package/src/tooling/raw_manifest.zig +2 -0
  172. package/src/tooling/templates.zig +244 -8
@@ -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);
@@ -301,10 +305,22 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
301
305
  @property(nonatomic, assign) BOOL observesContentLayout;
302
306
  @end
303
307
 
308
+ /// NSApp's delegate, installed by runWithCallback: — this host
309
+ /// otherwise drives NSApplication entirely through notification
310
+ /// observers, and staying that way for activation keeps those events
311
+ /// single-sourced (a delegate implementing applicationDidBecomeActive:
312
+ /// would ALSO receive the notification, double-emitting). The one job
313
+ /// here is the Dock-icon reopen: with no window visible, re-show the
314
+ /// windows the .hide close policy hid.
315
+ @interface NativeSdkAppDelegate : NSObject <NSApplicationDelegate>
316
+ @property(nonatomic, assign) NativeSdkAppKitHost *host;
317
+ @end
318
+
304
319
  @interface NativeSdkWebView : WKWebView <NSDraggingDestination>
305
320
  @property(nonatomic, strong) NSArray<NSValue *> *coveredMouseRects;
306
321
  @property(nonatomic, assign) NativeSdkAppKitHost *host;
307
322
  @property(nonatomic, assign) uint64_t windowId;
323
+ @property(nonatomic, strong) NSString *viewLabel;
308
324
  @end
309
325
 
310
326
  @interface NativeSdkBridgeScriptHandler : NSObject <WKScriptMessageHandler>
@@ -329,6 +345,16 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
329
345
  * overlay knob stays grabbable). */
330
346
  @interface NativeSdkScrollDriverView : NSScrollView
331
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;
332
358
  @end
333
359
 
334
360
  /* Captures the selected item id of a context-menu popUp; NSMenuItem
@@ -562,10 +588,28 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
562
588
  @property(nonatomic, assign) BOOL interpretedKeyEventEmittedInput;
563
589
  @property(nonatomic, strong) NSArray<NSAccessibilityElement *> *widgetAccessibilityElements;
564
590
  @property(nonatomic, strong) NSMutableArray<NativeSdkScrollDriverView *> *scrollDrivers;
565
- @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;
566
609
  @property(nonatomic, assign) BOOL applyingScrollDriverOffset;
567
610
  @property(nonatomic, assign) BOOL scrollDriverEventPending;
568
611
  @property(nonatomic, assign) uint64_t pendingScrollDriverId;
612
+ @property(nonatomic, assign) double pendingScrollDriverOffsetX;
569
613
  @property(nonatomic, assign) double pendingScrollDriverOffsetY;
570
614
  @property(nonatomic, assign) uint64_t scrollDriverEventLastEmitNs;
571
615
  @property(nonatomic, assign) BOOL controlClickActive;
@@ -612,7 +656,7 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
612
656
  - (void)emitInputEventWithKind:(NSInteger)kind event:(NSEvent *)event button:(NSInteger)button deltaX:(double)deltaX deltaY:(double)deltaY;
613
657
  - (void)queuePointerMotionInputEvent:(NSEvent *)event kind:(NSInteger)kind button:(NSInteger)button;
614
658
  - (void)emitQueuedPointerMotionInputEvent;
615
- - (void)queueScrollInputEvent:(NSEvent *)event deltaX:(double)deltaX deltaY:(double)deltaY;
659
+ - (void)queueScrollInputEvent:(NSEvent *)event atPoint:(NSPoint)point deltaX:(double)deltaX deltaY:(double)deltaY;
616
660
  - (void)emitQueuedScrollInputEvent;
617
661
  - (void)emitPinchInputEventWithKind:(NSInteger)kind event:(NSEvent *)event magnification:(double)magnification;
618
662
  - (void)emitPinchChangeForEvent:(NSEvent *)event;
@@ -625,7 +669,7 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
625
669
  - (BOOL)emitWidgetAccessibilityActionWithId:(uint64_t)widgetId action:(NSInteger)action;
626
670
  - (BOOL)emitWidgetAccessibilityActionWithId:(uint64_t)widgetId action:(NSInteger)action text:(NSString *)text selectedRange:(NSRange)selectedRange hasSelectedRange:(BOOL)hasSelectedRange;
627
671
  - (void)setSurfaceCursor:(NSCursor *)cursor;
628
- - (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;
629
673
  @end
630
674
 
631
675
  @interface NativeSdkAssetSchemeHandler : NSObject <WKURLSchemeHandler>
@@ -662,6 +706,20 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
662
706
  /// color, packed RGBA8 per window — so residual gaps (resize slack,
663
707
  /// titlebar bands) show the app's background, never a blank default.
664
708
  @property(nonatomic, strong) NSMutableDictionary<NSNumber *, NSNumber *> *windowClearColors;
709
+ /// close_policy per window (0 = quit, the default; 1 = hide). Applied
710
+ /// by native_sdk_appkit_set_window_close_policy right after create —
711
+ /// the delegate's windowShouldClose: consults it, so the user's close
712
+ /// affordance hides a .hide window instead of closing it.
713
+ @property(nonatomic, strong) NSMutableDictionary<NSNumber *, NSNumber *> *windowClosePolicies;
714
+ /// Windows currently hidden BY their .hide close policy — the set the
715
+ /// Dock reopen re-shows, and the truth emitWindowFrameForWindowId's
716
+ /// hidden flag reports. Ordinary orderOut/minimize states never enter
717
+ /// it.
718
+ @property(nonatomic, strong) NSMutableSet<NSNumber *> *policyHiddenWindows;
719
+ /// Strong ref for NSApp.delegate (which is unretained): the tiny
720
+ /// delegate that turns a Dock-icon reopen into re-showing
721
+ /// policy-hidden windows.
722
+ @property(nonatomic, strong) id reopenDelegate;
665
723
  @property(nonatomic, strong) NSMutableDictionary<NSString *, WKWebView *> *childWebViews;
666
724
  @property(nonatomic, strong) NSMutableDictionary<NSString *, NSView *> *nativeViews;
667
725
  /// App-owned NSViews adopted into native view containers (native-surface
@@ -735,6 +793,69 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
735
793
  * when a new load replaces the stream; orphaned (left to finish) when
736
794
  * the stream completes naturally. */
737
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;
738
859
  @property(nonatomic, strong) NSString *appName;
739
860
  /* The human-facing app name (app.zon display_name, falling back through
740
861
  * the window title to the binary name). Everything the OS labels the
@@ -764,10 +885,16 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
764
885
  @property(nonatomic, assign) void *context;
765
886
  @property(nonatomic, assign) void *bridgeContext;
766
887
  @property(nonatomic, assign) BOOL didShutdown;
888
+ /* A quit verb that arrived before [NSApp run] (see
889
+ * native_sdk_appkit_request_stop): parked here, drained at top level
890
+ * by runWithCallback's drainPendingPreRunStop calls once the pre-run
891
+ * dispatch that carried it has returned. */
892
+ @property(nonatomic, assign) BOOL pendingPreRunStop;
767
893
  @property(nonatomic, assign) BOOL observesApplicationActivation;
768
894
  @property(nonatomic, assign) BOOL observesAppearanceChanges;
769
895
  @property(nonatomic, assign) NSInteger bridgeFrameKeepalive;
770
896
  @property(nonatomic, strong) id shortcutEventMonitor;
897
+ @property(nonatomic, strong) id viewFocusEventMonitor;
771
898
  @property(nonatomic, strong) id willTerminateObserver;
772
899
  @property(nonatomic, strong) dispatch_source_t sigtermSource;
773
900
  @property(nonatomic, strong) NSArray<NativeSdkShortcut *> *shortcuts;
@@ -783,6 +910,9 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
783
910
  - (void)applyWindowClearColor:(uint64_t)windowId red:(uint8_t)red green:(uint8_t)green blue:(uint8_t)blue alpha:(uint8_t)alpha;
784
911
  - (void)focusWindowWithId:(uint64_t)windowId;
785
912
  - (void)closeWindowWithId:(uint64_t)windowId;
913
+ - (void)hideWindowWithId:(uint64_t)windowId;
914
+ - (void)showWindowWithId:(uint64_t)windowId;
915
+ - (BOOL)reopenPolicyHiddenWindows;
786
916
  - (BOOL)startWindowDragWithId:(uint64_t)windowId;
787
917
  - (BOOL)chromeInsetsForWindowId:(uint64_t)windowId top:(double *)top left:(double *)left bottom:(double *)bottom right:(double *)right buttonsX:(double *)buttonsX buttonsY:(double *)buttonsY buttonsWidth:(double *)buttonsWidth buttonsHeight:(double *)buttonsHeight;
788
918
  - (WKWebView *)ensureMainWebViewForWindowId:(uint64_t)windowId;
@@ -807,7 +937,7 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
807
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;
808
938
  - (BOOL)requestGpuSurfaceFrameInWindow:(uint64_t)windowId label:(NSString *)label;
809
939
  - (BOOL)noteGpuSurfaceInputInWindow:(uint64_t)windowId label:(NSString *)label;
810
- - (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;
811
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;
812
942
  - (BOOL)uploadGpuSurfaceImageWithId:(uint64_t)imageId width:(NSUInteger)width height:(NSUInteger)height rgba8:(const uint8_t *)rgba8 byteLength:(NSUInteger)byteLength;
813
943
  - (BOOL)removeGpuSurfaceImageWithId:(uint64_t)imageId;
@@ -843,6 +973,7 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
843
973
  - (void)setMenusWithTitles:(const char *const *)menuTitles titleLengths:(const size_t *)menuTitleLengths count:(size_t)menuCount itemMenuIndices:(const uint32_t *)itemMenuIndices itemLabels:(const char *const *)itemLabels itemLabelLengths:(const size_t *)itemLabelLengths itemCommands:(const char *const *)itemCommands itemCommandLengths:(const size_t *)itemCommandLengths itemKeys:(const char *const *)itemKeys itemKeyLengths:(const size_t *)itemKeyLengths itemModifiers:(const uint32_t *)itemModifiers itemSeparators:(const int *)itemSeparators itemEnabled:(const int *)itemEnabled itemChecked:(const int *)itemChecked itemCount:(size_t)itemCount;
844
974
  - (void)runWithCallback:(native_sdk_appkit_event_callback_t)callback context:(void *)context;
845
975
  - (void)stop;
976
+ - (BOOL)drainPendingPreRunStop;
846
977
  - (void)emitEvent:(native_sdk_appkit_event_t)event;
847
978
  - (BOOL)emitDroppedFileURLs:(NSArray<NSURL *> *)urls windowId:(uint64_t)windowId;
848
979
  - (void)startApplicationActivationObservers;
@@ -884,6 +1015,29 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
884
1015
  - (void)stopAudioSpectrumTimer;
885
1016
  - (BOOL)anyHostWindowVisibleOnGlass;
886
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;
887
1041
  - (void)wakeFromAnyThread;
888
1042
  - (void)scheduleBridgeFrames;
889
1043
  - (void)emitFrame;
@@ -1022,6 +1176,22 @@ static void NativeSdkEmitGpuSurfaceResizes(NSView *view) {
1022
1176
  return [self.host emitDroppedFileURLs:urls windowId:self.windowId];
1023
1177
  }
1024
1178
 
1179
+ // close_policy .hide: the USER's close affordance (the red button,
1180
+ // cmd+W — anything routed through performClose:) hides the window
1181
+ // instead of closing it, and the app keeps running behind its status
1182
+ // item. Runtime-initiated closes bypass this hook deliberately
1183
+ // (closeWindowWithId: calls -close directly for .hide windows), so an
1184
+ // app that decides to really close its window still can. A future
1185
+ // .event tier would land here too — the delegate forwarding the close
1186
+ // request to the model instead of deciding — the enum keeps that room.
1187
+ - (BOOL)windowShouldClose:(NSWindow *)sender {
1188
+ (void)sender;
1189
+ NSNumber *policy = self.host.windowClosePolicies[@(self.windowId)];
1190
+ if (policy.intValue != 1) return YES;
1191
+ [self.host hideWindowWithId:self.windowId];
1192
+ return NO;
1193
+ }
1194
+
1025
1195
  - (void)windowWillClose:(NSNotification *)notification {
1026
1196
  (void)notification;
1027
1197
  if (self.observesContentLayout) {
@@ -1029,6 +1199,10 @@ static void NativeSdkEmitGpuSurfaceResizes(NSView *view) {
1029
1199
  [window removeObserver:self forKeyPath:@"contentLayoutRect"];
1030
1200
  self.observesContentLayout = NO;
1031
1201
  }
1202
+ // A really-closing window is closed, not hidden: leave the
1203
+ // policy-hidden set before the frame emit so open=false never
1204
+ // carries a stale hidden=true.
1205
+ [self.host.policyHiddenWindows removeObject:@(self.windowId)];
1032
1206
  [self.host emitWindowFrameForWindowId:self.windowId open:NO];
1033
1207
  [self.host closeWebViewsInWindow:self.windowId];
1034
1208
  [self.host closeNativeViewsInWindow:self.windowId];
@@ -1041,6 +1215,7 @@ static void NativeSdkEmitGpuSurfaceResizes(NSView *view) {
1041
1215
  [self.host.windowLabels removeObjectForKey:key];
1042
1216
  [self.host.deferredShowWindows removeObjectForKey:key];
1043
1217
  [self.host.windowClearColors removeObjectForKey:key];
1218
+ [self.host.windowClosePolicies removeObjectForKey:key];
1044
1219
  if (self.host.windows.count == 0) {
1045
1220
  [self.host emitShutdown];
1046
1221
  [self.host stop];
@@ -1049,6 +1224,20 @@ static void NativeSdkEmitGpuSurfaceResizes(NSView *view) {
1049
1224
 
1050
1225
  @end
1051
1226
 
1227
+ @implementation NativeSdkAppDelegate
1228
+
1229
+ // Clicking the Dock icon with every window gone from the glass: when
1230
+ // policy-hidden windows exist, re-show them and answer NO (the reopen
1231
+ // is handled); otherwise answer YES so AppKit keeps its default
1232
+ // behavior (deminiaturizing, ordering in) untouched.
1233
+ - (BOOL)applicationShouldHandleReopen:(NSApplication *)sender hasVisibleWindows:(BOOL)flag {
1234
+ (void)sender;
1235
+ if (flag) return YES;
1236
+ return ![self.host reopenPolicyHiddenWindows];
1237
+ }
1238
+
1239
+ @end
1240
+
1052
1241
  @implementation NativeSdkWebView
1053
1242
 
1054
1243
  - (BOOL)pointIsCovered:(NSPoint)point {
@@ -1763,19 +1952,122 @@ static NSMutableDictionary<NSNumber *, id> *NativeSdkRegisteredFontDescriptors(v
1763
1952
  return table;
1764
1953
  }
1765
1954
 
1766
- // The registered face for a canvas font id at `size`, or nil when the id
1767
- // has no registered face. Checked BEFORE the built-in candidates and
1768
- // their cache so a registered id can never be masked by a font resolved
1769
- // for that id earlier (ids are engine-validated and permanent, so cached
1770
- // NSFonts here never go stale).
1771
- static NSFont *NativeSdkRegisteredFontForId(unsigned long long value, CGFloat size) {
1772
- NSMutableDictionary<NSNumber *, id> *table = NativeSdkRegisteredFontDescriptors();
1773
- static NSMutableDictionary<NSString *, NSFont *> *sizeCache = nil;
1955
+ // The per-(id, size) NSFont cache for registered faces, keyed "id/size".
1956
+ // Ids are permanent within ONE runtime (`error.FontIdInUse` guards
1957
+ // re-use for a runtime's lifetime), but this cache is per-PROCESS and
1958
+ // runtimes are not: an embedder that destroys its runtime
1959
+ // (`Runtime.deinit`) and registers a DIFFERENT face under the same
1960
+ // valid id in a new runtime is inside the documented lifecycle. Entries
1961
+ // therefore go stale exactly when an id's descriptor is (re)installed,
1962
+ // so `native_sdk_appkit_register_font` evicts the id's cached sizes
1963
+ // before installing the new descriptor. The measured-width NSCache
1964
+ // (`NativeSdkMeasuredWidthCache`) goes stale at the same moment but
1965
+ // cannot be prefix-evicted (NSCache does not enumerate keys), so it is
1966
+ // invalidated by registration token instead — see
1967
+ // NativeSdkRegisteredFontTokens below. Accessed only under the
1968
+ // descriptor table's @synchronized guard, like the descriptors.
1969
+ static NSMutableDictionary<NSString *, NSFont *> *NativeSdkRegisteredFontSizeCache(void) {
1970
+ static NSMutableDictionary<NSString *, NSFont *> *cache = nil;
1971
+ static dispatch_once_t onceToken;
1972
+ dispatch_once(&onceToken, ^{
1973
+ cache = [[NSMutableDictionary alloc] init];
1974
+ });
1975
+ return cache;
1976
+ }
1977
+
1978
+ // Per-id registration tokens, the invalidation handle for the
1979
+ // measured-width NSCache (`NativeSdkMeasuredWidthCache`). That
1980
+ // cache has the same lifetime hazard as the size cache above (per-
1981
+ // process cache, per-runtime id permanence) but no way to evict an
1982
+ // id's entries — NSCache cannot enumerate keys — so every registration
1983
+ // stamps its id with the next value of ONE process-global monotonic
1984
+ // counter and the width-cache key includes the stamp. Tokens never
1985
+ // repeat, so no registration can ever reach widths a previous life of
1986
+ // its id cached (re-registration leaves those unreachable entries to
1987
+ // age out under the cache's count limit; unregistration clears the
1988
+ // cache outright — see `native_sdk_appkit_unregister_font`) — which is
1989
+ // exactly what makes an id's record REMOVABLE at unregister, retaining
1990
+ // zero state per retired id.
1991
+ // A per-id bump counter could not offer that: deleting a per-id count
1992
+ // would let a future registration of the id restart at 1 and collide
1993
+ // with the retired life's still-cached widths, so retired ids would
1994
+ // each pin a record for the process lifetime. Ids never registered
1995
+ // (the built-in faces) have no record and measure under token 0 — the
1996
+ // same value an unregistered id returns to, honest because both states
1997
+ // resolve through the same built-in candidates. Accessed only under
1998
+ // the descriptor table's @synchronized guard, like the descriptors.
1999
+ static NSMutableDictionary<NSNumber *, NSNumber *> *NativeSdkRegisteredFontTokens(void) {
2000
+ static NSMutableDictionary<NSNumber *, NSNumber *> *table = nil;
1774
2001
  static dispatch_once_t onceToken;
1775
2002
  dispatch_once(&onceToken, ^{
1776
- sizeCache = [[NSMutableDictionary alloc] init];
2003
+ table = [[NSMutableDictionary alloc] init];
1777
2004
  });
2005
+ return table;
2006
+ }
2007
+
2008
+ // The process-global registration token counter: pre-incremented at
2009
+ // every registration, so 0 is never a live token and stays the honest
2010
+ // "no registered face" value. Mutated only under the descriptor
2011
+ // table's @synchronized guard, like every table here.
2012
+ static unsigned long long NativeSdkRegisteredFontTokenCounter = 0;
2013
+
2014
+ // The measured-width NSCache `native_sdk_appkit_measure_text` memoizes
2015
+ // shaped widths in, hoisted out of that function (exactly the shared-
2016
+ // accessor shape the NSFont size cache above took) so
2017
+ // `native_sdk_appkit_unregister_font` can reach it at teardown: a
2018
+ // retiring token's entries can never be SERVED again (tokens never
2019
+ // repeat) but a function-local static left them RESIDENT — up to the
2020
+ // full count limit of keys, each carrying the measured text itself —
2021
+ // until memory pressure. NSCache is thread-safe, so unlike the
2022
+ // dictionaries above this cache is deliberately NOT confined to the
2023
+ // descriptor table's @synchronized guard: measure_text shapes outside
2024
+ // the critical section on purpose (see the snapshot comment) and
2025
+ // re-enters the guard only to recheck the token before a
2026
+ // registered-token write (see the recheck comment in measure_text).
2027
+ static NSCache<NSString *, NSNumber *> *NativeSdkMeasuredWidthCache(void) {
2028
+ static NSCache<NSString *, NSNumber *> *cache = nil;
2029
+ static dispatch_once_t onceToken;
2030
+ dispatch_once(&onceToken, ^{
2031
+ cache = [[NSCache alloc] init];
2032
+ cache.countLimit = 16384;
2033
+ });
2034
+ return cache;
2035
+ }
2036
+
2037
+ // The id's current registration token AND the registered face that
2038
+ // token resolves to, snapshotted under ONE acquisition of the
2039
+ // descriptor table's @synchronized guard. The pair must be atomic
2040
+ // because measure_text keys its width memoization by (id, token): with
2041
+ // the token read and the face resolved under SEPARATE acquisitions, a
2042
+ // registration landing between them pairs token 0 with the NEW
2043
+ // registered face and caches a registered-face width under the
2044
+ // reusable token-0 key — served again after the registration is torn
2045
+ // down, when token 0 honestly means built-in resolution. One critical
2046
+ // section makes a torn pair unrepresentable; the width computation
2047
+ // itself stays outside the lock (see measure_text), because a
2048
+ // stale-but-consistent pair is harmless: measure_text rechecks the
2049
+ // token under the guard before caching, so a pair retired mid-shape
2050
+ // is never even written. Returns nil with
2051
+ // *out_token = 0 when the id holds no registration, so token 0 only
2052
+ // ever pairs with built-in resolution. (A registered descriptor whose
2053
+ // CTFont creation fails also answers nil, under its live token: the
2054
+ // built-in fallback then caches under that token — still one
2055
+ // consistent resolution per registration life, since the failure is a
2056
+ // property of the installed descriptor.)
2057
+ //
2058
+ // The registered-face NSFonts cached here stay honest because
2059
+ // registration evicts an id's entries when its descriptor changes (see
2060
+ // NativeSdkRegisteredFontSizeCache) — an id is only permanent within
2061
+ // one runtime, and this cache outlives runtimes. Registered faces are
2062
+ // checked BEFORE the built-in candidates and their cache so a
2063
+ // registered id can never be masked by a font resolved for that id
2064
+ // earlier.
2065
+ static NSFont *NativeSdkRegisteredFontSnapshot(unsigned long long value, CGFloat size, unsigned long long *out_token) {
2066
+ NSMutableDictionary<NSNumber *, id> *table = NativeSdkRegisteredFontDescriptors();
2067
+ NSMutableDictionary<NSString *, NSFont *> *sizeCache = NativeSdkRegisteredFontSizeCache();
1778
2068
  @synchronized (table) {
2069
+ NSNumber *tokenNumber = NativeSdkRegisteredFontTokens()[@(value)];
2070
+ *out_token = tokenNumber ? tokenNumber.unsignedLongLongValue : 0;
1779
2071
  id descriptorObject = table[@(value)];
1780
2072
  if (!descriptorObject) return nil;
1781
2073
  NSString *key = [NSString stringWithFormat:@"%llu/%.3f", value, (double)size];
@@ -1789,36 +2081,133 @@ static NSFont *NativeSdkRegisteredFontForId(unsigned long long value, CGFloat si
1789
2081
  }
1790
2082
  }
1791
2083
 
2084
+ // The registered face for a canvas font id at `size`, or nil when the id
2085
+ // has no registered face — the snapshot above for callers that resolve
2086
+ // but do not memoize by token (packet drawing, the advances batch).
2087
+ static NSFont *NativeSdkRegisteredFontForId(unsigned long long value, CGFloat size) {
2088
+ unsigned long long token = 0;
2089
+ return NativeSdkRegisteredFontSnapshot(value, size, &token);
2090
+ }
2091
+
1792
2092
  // Engine-validated TrueType bytes for a registered canvas font id: parse
1793
2093
  // them into a font descriptor once and key it by id, so measurement and
1794
2094
  // packet text drawing resolve the id to this exact face. Returns 1 on
1795
2095
  // success, 0 when CoreText rejects the data — the engine already parsed
1796
2096
  // the face, so a rejection here is surfaced as a loud registration
1797
- // error engine-side, never a silent fallback at draw time.
1798
- int native_sdk_appkit_register_font(uint64_t font_id, const uint8_t *bytes, size_t bytes_len) {
1799
- if (font_id == 0 || !bytes || bytes_len == 0) return 0;
2097
+ // error engine-side, never a silent fallback at draw time. On success
2098
+ // `*out_token` reports the registration token minted below — the
2099
+ // ownership handle unregister_font matches against, so a teardown can
2100
+ // only remove the registration it owns.
2101
+ int native_sdk_appkit_register_font(uint64_t font_id, const uint8_t *bytes, size_t bytes_len, uint64_t *out_token) {
2102
+ if (out_token) *out_token = 0;
2103
+ if (font_id == 0 || !bytes || bytes_len == 0 || !out_token) return 0;
1800
2104
  @autoreleasepool {
1801
2105
  NSData *data = [NSData dataWithBytes:bytes length:bytes_len];
1802
2106
  CTFontDescriptorRef descriptor = CTFontManagerCreateFontDescriptorFromData((__bridge CFDataRef)data);
1803
2107
  if (!descriptor) return 0;
1804
2108
  NSMutableDictionary<NSNumber *, id> *table = NativeSdkRegisteredFontDescriptors();
1805
2109
  @synchronized (table) {
2110
+ // Evict the id's cached NSFonts BEFORE installing the new
2111
+ // descriptor: the process may still hold fonts a PREVIOUS
2112
+ // runtime resolved for this id (ids are per-runtime
2113
+ // permanent, the cache is per-process), and serving them
2114
+ // would measure and draw the old face under the new id.
2115
+ NSMutableDictionary<NSString *, NSFont *> *sizeCache = NativeSdkRegisteredFontSizeCache();
2116
+ NSString *stalePrefix = [NSString stringWithFormat:@"%llu/", (unsigned long long)font_id];
2117
+ NSArray<NSString *> *cachedKeys = sizeCache.allKeys;
2118
+ for (NSString *cachedKey in cachedKeys) {
2119
+ if ([cachedKey hasPrefix:stalePrefix]) [sizeCache removeObjectForKey:cachedKey];
2120
+ }
2121
+ // The measured-width cache holds the same stale state but
2122
+ // cannot be enumerated for eviction, so stamp the id with a
2123
+ // fresh process-global token instead: width-cache keys
2124
+ // include the token, tokens never repeat, and everything
2125
+ // cached under any previous stamp becomes unreachable. The
2126
+ // stamp doubles as the registration's ownership token,
2127
+ // reported to the caller so its teardown can name exactly
2128
+ // this registration.
2129
+ unsigned long long token = ++NativeSdkRegisteredFontTokenCounter;
2130
+ NativeSdkRegisteredFontTokens()[@(font_id)] = @(token);
1806
2131
  table[@(font_id)] = (__bridge_transfer id)descriptor;
2132
+ *out_token = token;
1807
2133
  }
1808
2134
  return 1;
1809
2135
  }
1810
2136
  }
1811
2137
 
1812
- // Resolves a canvas font id to the NSFont presentation draws with. Both
1813
- // packet text drawing and native_sdk_appkit_measure_text go through this
1814
- // single function so measured layout and drawn glyphs share font
1815
- // resolution. Ids 3-6 are the reserved sans span variants (medium, bold,
1816
- // italic, bold italic); everything else keeps the regular sans/mono
1817
- // candidates. Registered faces win first (see above). Resolved
1818
- // built-in fonts are cached per (font id, size).
1819
- static NSFont *NativeSdkFontForFontId(unsigned long long value, CGFloat size) {
1820
- NSFont *registered = NativeSdkRegisteredFontForId(value, size);
1821
- if (registered) return registered;
2138
+ // Teardown twin of the registration above, called by Runtime.deinit for
2139
+ // each id the dying runtime registered: font ids are per-runtime but
2140
+ // every table here is per-process, so without this removal an embedder
2141
+ // cycling runtimes with fresh ids grows the descriptor table (and its
2142
+ // caches) for the process lifetime. Removal drops EVERYTHING the
2143
+ // registration installed: the id's cached NSFonts (the same prefix
2144
+ // eviction re-registration runs), the id's registration token record,
2145
+ // the descriptor itself, and — by clearing the measured-width NSCache
2146
+ // wholesale, the only eviction NSCache permits — the widths measured
2147
+ // under the retiring token. Zero retained state per retired id, so
2148
+ // runtime cycles truly do not accumulate host entries. Deleting the
2149
+ // token record (rather than bumping it) is safe precisely because
2150
+ // tokens come from one process-global monotonic counter: a future
2151
+ // registration of this id takes a fresh, never-repeated token, so no
2152
+ // per-id record has to survive to keep this life's width-cache keys
2153
+ // unreachable. An id
2154
+ // with no installed descriptor (never registered host-side, or already
2155
+ // returned) is a no-op accept.
2156
+ //
2157
+ // Removal is token-guarded: `token` is the ownership handle the id's
2158
+ // register call reported, and state comes out ONLY while the id's
2159
+ // current registration still carries it. Font ids are per-runtime while
2160
+ // this state is per-process, so a later runtime may have re-registered
2161
+ // the id (last wins — its face is the live one measurement and drawing
2162
+ // resolve); an id-keyed removal here would let the OLDER runtime's
2163
+ // deinit delete the newer runtime's descriptor and caches, dropping its
2164
+ // host text to the default family while its engine still holds the
2165
+ // face. A stale token is a no-op accept, not an error: the registration
2166
+ // it owned is already gone, which is exactly the state its owner asked
2167
+ // this call to establish.
2168
+ int native_sdk_appkit_unregister_font(uint64_t font_id, uint64_t token) {
2169
+ if (font_id == 0) return 0;
2170
+ @autoreleasepool {
2171
+ NSMutableDictionary<NSNumber *, id> *table = NativeSdkRegisteredFontDescriptors();
2172
+ @synchronized (table) {
2173
+ NSNumber *current = NativeSdkRegisteredFontTokens()[@(font_id)];
2174
+ if (!current || current.unsignedLongLongValue != token) return 1;
2175
+ NSMutableDictionary<NSString *, NSFont *> *sizeCache = NativeSdkRegisteredFontSizeCache();
2176
+ NSString *stalePrefix = [NSString stringWithFormat:@"%llu/", (unsigned long long)font_id];
2177
+ NSArray<NSString *> *cachedKeys = sizeCache.allKeys;
2178
+ for (NSString *cachedKey in cachedKeys) {
2179
+ if ([cachedKey hasPrefix:stalePrefix]) [sizeCache removeObjectForKey:cachedKey];
2180
+ }
2181
+ [NativeSdkRegisteredFontTokens() removeObjectForKey:@(font_id)];
2182
+ [table removeObjectForKey:@(font_id)];
2183
+ // The retiring token's measured widths can never be served
2184
+ // again (tokens never repeat) but would otherwise stay
2185
+ // resident until memory pressure. NSCache cannot enumerate
2186
+ // keys, so a per-id eviction is impossible and clearing the
2187
+ // WHOLE cache is the only honest release. The collateral is
2188
+ // cheap where it lands: unregistration is a teardown-
2189
+ // frequency event, and every other live id re-warms each
2190
+ // width it still needs in one measure call. The clear runs
2191
+ // only on this token-matched path — a stale-token no-op
2192
+ // above must not cost live registrations their warm cache.
2193
+ // A measurement in flight during this teardown cannot
2194
+ // repopulate the cleared cache: measure_text rechecks the
2195
+ // id's token under this same guard before caching, and this
2196
+ // removal already retired the token it snapshotted.
2197
+ [NativeSdkMeasuredWidthCache() removeAllObjects];
2198
+ }
2199
+ return 1;
2200
+ }
2201
+ }
2202
+
2203
+ // The built-in-candidates half of font resolution: never consults the
2204
+ // registered tables, so callers that already hold a registered-face
2205
+ // snapshot (measure_text) fall back here without re-reading state the
2206
+ // snapshot fixed. Ids 3-6 are the reserved sans span variants (medium,
2207
+ // bold, italic, bold italic); everything else keeps the regular
2208
+ // sans/mono candidates. Resolved built-in fonts are cached per
2209
+ // (font id, size).
2210
+ static NSFont *NativeSdkBuiltInFontForFontId(unsigned long long value, CGFloat size) {
1822
2211
  static NSCache<NSString *, NSFont *> *cache = nil;
1823
2212
  static dispatch_once_t onceToken;
1824
2213
  dispatch_once(&onceToken, ^{
@@ -1866,6 +2255,19 @@ static NSFont *NativeSdkFontForFontId(unsigned long long value, CGFloat size) {
1866
2255
  return font;
1867
2256
  }
1868
2257
 
2258
+ // Resolves a canvas font id to the NSFont presentation draws with. Both
2259
+ // packet text drawing and native_sdk_appkit_measure_text go through this
2260
+ // resolution order (registered faces win, then the built-in candidates)
2261
+ // so measured layout and drawn glyphs share font resolution —
2262
+ // measure_text inlines the two halves around its width cache because it
2263
+ // must key that cache by the registration-token snapshot the first half
2264
+ // fixes.
2265
+ static NSFont *NativeSdkFontForFontId(unsigned long long value, CGFloat size) {
2266
+ NSFont *registered = NativeSdkRegisteredFontForId(value, size);
2267
+ if (registered) return registered;
2268
+ return NativeSdkBuiltInFontForFontId(value, size);
2269
+ }
2270
+
1869
2271
  static NSFont *NativeSdkPacketPreferredFont(NSDictionary *text, CGFloat size) {
1870
2272
  NSNumber *fontId = [text[@"font"] isKindOfClass:[NSNumber class]] ? text[@"font"] : nil;
1871
2273
  unsigned long long value = fontId ? fontId.unsignedLongLongValue : 1;
@@ -1883,19 +2285,58 @@ double native_sdk_appkit_measure_text(uint64_t font_id, double size, const char
1883
2285
  @autoreleasepool {
1884
2286
  NSString *value = [[NSString alloc] initWithBytes:text length:text_len encoding:NSUTF8StringEncoding];
1885
2287
  if (!value) return -1;
1886
- static NSCache<NSString *, NSNumber *> *widthCache = nil;
1887
- static dispatch_once_t onceToken;
1888
- dispatch_once(&onceToken, ^{
1889
- widthCache = [[NSCache alloc] init];
1890
- widthCache.countLimit = 16384;
1891
- });
1892
- NSString *key = [NSString stringWithFormat:@"%llu/%.3f/%@", (unsigned long long)font_id, (double)clamped, value];
2288
+ NSCache<NSString *, NSNumber *> *widthCache = NativeSdkMeasuredWidthCache();
2289
+ // The key carries the id's registration token so a face
2290
+ // re-registered under the same id (a new runtime in this
2291
+ // process) never serves a previous face's widths — see
2292
+ // NativeSdkRegisteredFontTokens for why token, not eviction,
2293
+ // invalidates this cache. Token and registered face come from
2294
+ // ONE snapshot (one critical section — see
2295
+ // NativeSdkRegisteredFontSnapshot): reading them under separate
2296
+ // acquisitions let a registration land between the reads and
2297
+ // cache the new face's width under the reusable token-0 key,
2298
+ // serving stale registered widths in the unregistered state
2299
+ // after teardown.
2300
+ unsigned long long token = 0;
2301
+ NSFont *registered = NativeSdkRegisteredFontSnapshot((unsigned long long)font_id, clamped, &token);
2302
+ NSString *key = [NSString stringWithFormat:@"%llu/%llu/%.3f/%@", (unsigned long long)font_id, token, (double)clamped, value];
1893
2303
  NSNumber *cached = [widthCache objectForKey:key];
1894
2304
  if (cached) return cached.doubleValue;
1895
- NSFont *font = NativeSdkFontForFontId(font_id, clamped);
2305
+ // A nil snapshot means built-in resolution — with token 0 by the
2306
+ // snapshot's contract unless a live descriptor's CTFont creation
2307
+ // failed, so token 0 only ever keys built-in widths. Shaping
2308
+ // stays OUTSIDE the critical section: a registration or
2309
+ // unregistration landing after the snapshot leaves this width
2310
+ // stale but consistent, and the token recheck below drops the
2311
+ // write instead of caching it.
2312
+ NSFont *font = registered ?: NativeSdkBuiltInFontForFontId(font_id, clamped);
1896
2313
  if (!font) return -1;
1897
2314
  double width = [value sizeWithAttributes:@{ NSFontAttributeName : font }].width;
1898
- [widthCache setObject:@(width) forKey:key];
2315
+ if (token == 0) {
2316
+ // Token 0 is built-in resolution: built-in faces are never
2317
+ // registered, so no unregister can ever clear widths keyed
2318
+ // under it — this write needs no recheck.
2319
+ [widthCache setObject:@(width) forKey:key];
2320
+ return width;
2321
+ }
2322
+ // A registered-token width is cached only after RECHECKING the
2323
+ // token under the guard. Unregister's only possible eviction is
2324
+ // clearing the whole width cache, and shaping ran outside the
2325
+ // critical section: an unconditional write here would land AFTER
2326
+ // that clear whenever the teardown ran inside the shaping window,
2327
+ // repopulating the cleared cache with a retired-token entry — one
2328
+ // no lookup can ever serve (tokens never repeat) but that stays
2329
+ // resident until memory pressure. A mismatch means the
2330
+ // registration was torn down (or replaced) mid-shape — dropping
2331
+ // the write costs one re-measure of a face that is already gone,
2332
+ // and keeps teardown's cleared cache actually clear.
2333
+ NSMutableDictionary<NSNumber *, id> *table = NativeSdkRegisteredFontDescriptors();
2334
+ @synchronized (table) {
2335
+ NSNumber *currentToken = NativeSdkRegisteredFontTokens()[@(font_id)];
2336
+ if (currentToken && currentToken.unsignedLongLongValue == token) {
2337
+ [widthCache setObject:@(width) forKey:key];
2338
+ }
2339
+ }
1899
2340
  return width;
1900
2341
  }
1901
2342
  }
@@ -1910,6 +2351,14 @@ double native_sdk_appkit_measure_text(uint64_t font_id, double size, const char
1910
2351
  // call per text run replaces one measure_text round-trip per cluster of
1911
2352
  // every growing line prefix — the engine caches the batch, so a run is
1912
2353
  // typically shaped here once per content change, not once per frame.
2354
+ //
2355
+ // Unlike measure_text this needs no registration-token snapshot: it
2356
+ // memoizes nothing host-side (the engine caches the batch and
2357
+ // invalidates it by its own measure generation, bumped at every
2358
+ // registration), so each call resolves the font once and uses it
2359
+ // immediately — there is no (token, face) pairing that could tear
2360
+ // across lock acquisitions or outlive the registration it was read
2361
+ // from.
1913
2362
  int native_sdk_appkit_measure_text_advances(uint64_t font_id, double size, const char *text, size_t text_len, float *advances) {
1914
2363
  if (!text || text_len == 0 || !advances) return 0;
1915
2364
  CGFloat clamped = MAX(1, size);
@@ -3016,15 +3465,28 @@ static NSDictionary *NativeSdkPacketDictionaryFromBinary(const uint8_t *bytes, N
3016
3465
  @implementation NativeSdkScrollDriverView
3017
3466
 
3018
3467
  - (NSView *)hitTest:(NSPoint)point {
3019
- // Scroll-wheel events route to the driver through the ordinary hit
3020
- // test so AppKit's own (responsive) scrolling machinery handles them
3021
- // — a programmatically forwarded scrollWheel: is ignored by that
3022
- // path. Everything else passes through to the canvas beneath, except
3023
- // 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).
3024
3482
  NSView *hit = [super hitTest:point];
3025
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.
3026
3488
  NSEvent *current = NSApp.currentEvent;
3027
- if (current && current.type == NSEventTypeScrollWheel) return hit;
3489
+ if (current && current.type == NSEventTypeScrollWheel) return nil;
3028
3490
  NSView *candidate = hit;
3029
3491
  while (candidate && candidate != self) {
3030
3492
  if ([candidate isKindOfClass:[NSScroller class]]) return hit;
@@ -5522,15 +5984,96 @@ static BOOL NativeSdkCompositeBlurWriteRegion(NSDictionary *command, CGFloat sca
5522
5984
  }
5523
5985
 
5524
5986
  - (void)scrollWheel:(NSEvent *)event {
5525
- NativeSdkScrollDriverView *driver = [self scrollDriverForWheelEvent:event];
5526
- if (driver) {
5527
- // The OS scroller owns input + physics for this region (momentum,
5528
- // rubber-band, overlay scroller); the resulting contentOffset
5529
- // flows back through the clip-view bounds-change notification.
5530
- [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
+ }
5531
6036
  return;
5532
6037
  }
5533
- [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];
5534
6077
  }
5535
6078
 
5536
6079
  - (void)magnifyWithEvent:(NSEvent *)event {
@@ -5609,6 +6152,17 @@ static BOOL NativeSdkCompositeBlurWriteRegion(NSDictionary *command, CGFloat sca
5609
6152
 
5610
6153
  - (void)keyDown:(NSEvent *)event {
5611
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
+ }
5612
6166
  self.interpretedKeyEventEmittedInput = NO;
5613
6167
  [self interpretKeyEvents:@[event]];
5614
6168
  if (!self.interpretedKeyEventEmittedInput) {
@@ -5737,10 +6291,13 @@ static BOOL NativeSdkCompositeBlurWriteRegion(NSDictionary *command, CGFloat sca
5737
6291
  deltaY:0];
5738
6292
  }
5739
6293
 
5740
- - (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 {
5741
6298
  if (!self.host || self.surfaceLabel.length == 0 || !event) return;
5742
6299
  if (deltaX == 0 && deltaY == 0) return;
5743
- self.pendingScrollPoint = [self convertPoint:event.locationInWindow fromView:nil];
6300
+ self.pendingScrollPoint = point;
5744
6301
  self.pendingScrollDeltaX += deltaX;
5745
6302
  self.pendingScrollDeltaY += deltaY;
5746
6303
  self.pendingScrollModifiers = NativeSdkModifierFlagsForEvent(event);
@@ -5849,8 +6406,18 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
5849
6406
  // IS the canvas scroll offset, reported back per frame interval through
5850
6407
  // GPU_SURFACE_SCROLL_DRIVER events.
5851
6408
 
5852
- - (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 {
5853
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;
5854
6421
  for (NSInteger index = (NSInteger)self.scrollDrivers.count - 1; index >= 0; index -= 1) {
5855
6422
  NativeSdkScrollDriverView *driver = self.scrollDrivers[(NSUInteger)index];
5856
6423
  BOOL present = NO;
@@ -5865,6 +6432,11 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
5865
6432
  [driver removeFromSuperview];
5866
6433
  [self.scrollDrivers removeObjectAtIndex:(NSUInteger)index];
5867
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];
5868
6440
  for (NSUInteger spec = 0; spec < count; spec += 1) {
5869
6441
  const native_sdk_appkit_scroll_driver_t desired = drivers[spec];
5870
6442
  NativeSdkScrollDriverView *driver = nil;
@@ -5881,10 +6453,14 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
5881
6453
  driver.driverId = desired.driver_id;
5882
6454
  driver.drawsBackground = NO;
5883
6455
  driver.hasVerticalScroller = YES;
5884
- 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;
5885
6462
  driver.scrollerStyle = NSScrollerStyleOverlay;
5886
6463
  driver.autohidesScrollers = YES;
5887
- driver.horizontalScrollElasticity = NSScrollElasticityNone;
5888
6464
  driver.automaticallyAdjustsContentInsets = NO;
5889
6465
  NativeSdkScrollDriverDocumentView *document = [[NativeSdkScrollDriverDocumentView alloc] initWithFrame:NSMakeRect(0, 0, MAX(desired.content_width, 1), MAX(desired.content_height, 1))];
5890
6466
  driver.documentView = document;
@@ -5897,52 +6473,159 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
5897
6473
  // against anything but the actual frame races with relayout.
5898
6474
  // Elasticity rides the same reconcile: a region's edge behavior
5899
6475
  // (pin at the edges vs bounce past them) is per-region state the
5900
- // runtime owns.
5901
- NSScrollElasticity elasticity = desired.rubber_band ? NSScrollElasticityAllowed : NSScrollElasticityNone;
5902
- 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;
5903
6491
  NSRect target = NSMakeRect(desired.x, self.bounds.size.height - desired.y - desired.height, desired.width, desired.height);
5904
6492
  if (!NSEqualRects(driver.frame, target)) driver.frame = target;
5905
6493
  NSSize contentSize = NSMakeSize(MAX(desired.content_width, 1), MAX(desired.content_height, 1));
5906
6494
  if (driver.documentView && !NSEqualSizes(driver.documentView.frame.size, contentSize)) {
5907
6495
  [driver.documentView setFrameSize:contentSize];
5908
6496
  }
5909
- 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];
5910
6505
  }
6506
+ self.scrollDrivers = ordered;
5911
6507
  }
5912
6508
 
5913
- - (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;
5914
6515
  self.applyingScrollDriverOffset = YES;
5915
- [driver.contentView setBoundsOrigin:NSMakePoint(0, offsetY)];
6516
+ [driver.contentView setBoundsOrigin:NSMakePoint(setX ? offsetX : current.x, setY ? offsetY : current.y)];
5916
6517
  [driver reflectScrolledClipView:driver.contentView];
5917
6518
  self.applyingScrollDriverOffset = NO;
5918
- }
5919
-
5920
- - (NativeSdkScrollDriverView *)scrollDriverForPoint:(NSPoint)viewPoint {
5921
- // Driver specs arrive in layout pre-order, so the LAST hit is the
5922
- // deepest scroll region under the pointer.
5923
- 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;
5924
6573
  for (NativeSdkScrollDriverView *driver in self.scrollDrivers) {
5925
- if (NSPointInRect(viewPoint, driver.frame)) result = driver;
5926
- }
5927
- return result;
5928
- }
5929
-
5930
- - (NativeSdkScrollDriverView *)scrollDriverForWheelEvent:(NSEvent *)event {
5931
- if (self.scrollDrivers.count == 0) return nil;
5932
- const BOOL legacy = event.phase == NSEventPhaseNone && event.momentumPhase == NSEventPhaseNone;
5933
- if (legacy) {
5934
- return [self scrollDriverForPoint:[self convertPoint:event.locationInWindow fromView:nil]];
5935
- }
5936
- if (event.phase == NSEventPhaseBegan || event.phase == NSEventPhaseMayBegin) {
5937
- // Lock the gesture to the region under the pointer so momentum
5938
- // keeps scrolling it after the pointer wanders.
5939
- self.activeWheelDriver = [self scrollDriverForPoint:[self convertPoint:event.locationInWindow fromView:nil]];
5940
- }
5941
- NativeSdkScrollDriverView *driver = self.activeWheelDriver;
5942
- if (event.momentumPhase == NSEventPhaseEnded || event.momentumPhase == NSEventPhaseCancelled) {
5943
- self.activeWheelDriver = nil;
5944
- }
5945
- 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;
5946
6629
  }
5947
6630
 
5948
6631
  - (void)scrollDriverBoundsDidChange:(NSNotification *)note {
@@ -5950,17 +6633,18 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
5950
6633
  NSClipView *clipView = note.object;
5951
6634
  for (NativeSdkScrollDriverView *driver in self.scrollDrivers) {
5952
6635
  if (driver.contentView != clipView) continue;
5953
- [self queueScrollDriverEventWithId:driver.driverId offsetY:clipView.bounds.origin.y];
6636
+ [self queueScrollDriverEventWithId:driver.driverId offsetX:clipView.bounds.origin.x offsetY:clipView.bounds.origin.y];
5954
6637
  return;
5955
6638
  }
5956
6639
  }
5957
6640
 
5958
- - (void)queueScrollDriverEventWithId:(uint64_t)driverId offsetY:(double)offsetY {
6641
+ - (void)queueScrollDriverEventWithId:(uint64_t)driverId offsetX:(double)offsetX offsetY:(double)offsetY {
5959
6642
  if (!self.host || self.surfaceLabel.length == 0) return;
5960
6643
  if (self.scrollDriverEventPending && self.pendingScrollDriverId != driverId) {
5961
6644
  [self emitQueuedScrollDriverEvent];
5962
6645
  }
5963
6646
  self.pendingScrollDriverId = driverId;
6647
+ self.pendingScrollDriverOffsetX = offsetX;
5964
6648
  self.pendingScrollDriverOffsetY = offsetY;
5965
6649
  if (self.scrollDriverEventPending) return;
5966
6650
  self.scrollDriverEventPending = YES;
@@ -5982,6 +6666,7 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
5982
6666
  - (void)emitQueuedScrollDriverEvent {
5983
6667
  if (!self.scrollDriverEventPending) return;
5984
6668
  const uint64_t driverId = self.pendingScrollDriverId;
6669
+ const double offsetX = self.pendingScrollDriverOffsetX;
5985
6670
  const double offsetY = self.pendingScrollDriverOffsetY;
5986
6671
  self.scrollDriverEventPending = NO;
5987
6672
  if (!self.host || self.surfaceLabel.length == 0) return;
@@ -5994,6 +6679,7 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
5994
6679
  .view_label_len = [self.surfaceLabel lengthOfBytesUsingEncoding:NSUTF8StringEncoding],
5995
6680
  .timestamp_ns = NativeSdkTimestampNanoseconds(),
5996
6681
  .widget_id = driverId,
6682
+ .scroll_driver_offset_x = offsetX,
5997
6683
  .scroll_driver_offset_y = offsetY,
5998
6684
  }];
5999
6685
  }
@@ -6407,6 +7093,8 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
6407
7093
  self.windowLabels = [[NSMutableDictionary alloc] init];
6408
7094
  self.deferredShowWindows = [[NSMutableDictionary alloc] init];
6409
7095
  self.windowClearColors = [[NSMutableDictionary alloc] init];
7096
+ self.windowClosePolicies = [[NSMutableDictionary alloc] init];
7097
+ self.policyHiddenWindows = [[NSMutableSet alloc] init];
6410
7098
  self.childWebViews = [[NSMutableDictionary alloc] init];
6411
7099
  self.nativeViews = [[NSMutableDictionary alloc] init];
6412
7100
  self.adoptedViewSurfaces = [[NSMutableDictionary alloc] init];
@@ -6424,6 +7112,7 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
6424
7112
 
6425
7113
  [self createWindowWithId:1 title:(windowTitle.length > 0 ? windowTitle : self.appName) label:self.windowLabel x:x y:y width:width height:height restoreFrame:restoreFrame resizable:resizable titlebarStyle:titlebarStyle showPolicy:showPolicy makeMain:YES];
6426
7114
  self.didShutdown = NO;
7115
+ self.pendingPreRunStop = NO;
6427
7116
  self.observesApplicationActivation = NO;
6428
7117
 
6429
7118
  return self;
@@ -6601,6 +7290,7 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
6601
7290
  - (void)dealloc {
6602
7291
  [self invalidateAppTimers];
6603
7292
  [self audioStop];
7293
+ [self videoStop];
6604
7294
  /* The vDSP plan outlives individual playbacks (created lazily
6605
7295
  * once); the host's end is where it retires. */
6606
7296
  if (self.audioSpectrumFft) {
@@ -6612,6 +7302,10 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
6612
7302
  [NSEvent removeMonitor:self.shortcutEventMonitor];
6613
7303
  self.shortcutEventMonitor = nil;
6614
7304
  }
7305
+ if (self.viewFocusEventMonitor) {
7306
+ [NSEvent removeMonitor:self.viewFocusEventMonitor];
7307
+ self.viewFocusEventMonitor = nil;
7308
+ }
6615
7309
  [self removeAllChildBridgeHandlers];
6616
7310
  for (WKWebView *webView in self.webViews.allValues) {
6617
7311
  [webView.configuration.userContentController removeScriptMessageHandlerForName:@"nativeSdkBridge"];
@@ -6633,6 +7327,14 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
6633
7327
  - (void)closeWindowWithId:(uint64_t)windowId {
6634
7328
  NSWindow *window = self.windows[@(windowId)];
6635
7329
  if (!window) return;
7330
+ // A runtime-initiated close is the app DECIDING to close: it must
7331
+ // not bounce off the window's own .hide close policy, so it skips
7332
+ // performClose: (which runs windowShouldClose:) and closes
7333
+ // directly — the full windowWillClose teardown still runs.
7334
+ if ([self.windowClosePolicies[@(windowId)] intValue] == 1) {
7335
+ [window close];
7336
+ return;
7337
+ }
6636
7338
  // performClose: simulates the titlebar close button, which a
6637
7339
  // chromeless (borderless) window does not have — AppKit just beeps.
6638
7340
  // Closing directly runs the same delegate teardown
@@ -6644,6 +7346,50 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
6644
7346
  [window performClose:nil];
6645
7347
  }
6646
7348
 
7349
+ // close_policy .hide, the hiding half: order the window out (it keeps
7350
+ // its views, its webviews, and its host records — nothing tears down),
7351
+ // remember it as policy-hidden, and report the state on the frame
7352
+ // channel so the runtime's window table and the session journal both
7353
+ // carry the truth. orderOut composes with the host's bookkeeping where
7354
+ // close would not: the windows dictionary still owns the window, so
7355
+ // the count never reaches zero and no shutdown emits.
7356
+ - (void)hideWindowWithId:(uint64_t)windowId {
7357
+ NSWindow *window = self.windows[@(windowId)];
7358
+ if (!window) return;
7359
+ [self.policyHiddenWindows addObject:@(windowId)];
7360
+ [window orderOut:nil];
7361
+ [self emitWindowFrameForWindowId:windowId open:YES];
7362
+ }
7363
+
7364
+ // The counterpart show verb: bring a hidden (or merely unfocused)
7365
+ // window back to the glass and activate the app — the tray-menu
7366
+ // "Open" consequence and the Dock reopen both land here. Also clears a
7367
+ // pending present-before-show defer and a minimize, for the same
7368
+ // reason focusWindowWithId: does: the runtime asked for the window NOW.
7369
+ - (void)showWindowWithId:(uint64_t)windowId {
7370
+ NSWindow *window = self.windows[@(windowId)];
7371
+ if (!window) return;
7372
+ [self.policyHiddenWindows removeObject:@(windowId)];
7373
+ [self.deferredShowWindows removeObjectForKey:@(windowId)];
7374
+ if (window.miniaturized) [window deminiaturize:nil];
7375
+ [window makeKeyAndOrderFront:nil];
7376
+ [NSApp activate];
7377
+ [self emitWindowFrameForWindowId:windowId open:YES];
7378
+ [self scheduleFrame];
7379
+ }
7380
+
7381
+ // The Dock-icon reopen consequence: with no window visible, re-show
7382
+ // every window the .hide close policy hid. Returns whether any window
7383
+ // was re-shown (the app delegate then suppresses AppKit's default
7384
+ // reopen handling for exactly that case).
7385
+ - (BOOL)reopenPolicyHiddenWindows {
7386
+ if (self.policyHiddenWindows.count == 0) return NO;
7387
+ for (NSNumber *key in [self.policyHiddenWindows copy]) {
7388
+ [self showWindowWithId:key.unsignedLongLongValue];
7389
+ }
7390
+ return YES;
7391
+ }
7392
+
6647
7393
  // The real OS minimize verb, for app-drawn window controls (chromeless
6648
7394
  // windows have no traffic lights to click): the window genies into the
6649
7395
  // Dock exactly like the yellow button. miniaturize: is used over
@@ -6778,6 +7524,7 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
6778
7524
  WKWebView *webView = [[NativeSdkWebView alloc] initWithFrame:container.bounds configuration:configuration];
6779
7525
  ((NativeSdkWebView *)webView).host = self;
6780
7526
  ((NativeSdkWebView *)webView).windowId = windowId;
7527
+ ((NativeSdkWebView *)webView).viewLabel = @"main";
6781
7528
  [webView registerForDraggedTypes:@[NSPasteboardTypeFileURL]];
6782
7529
  webView.wantsLayer = YES;
6783
7530
  webView.layer.zPosition = 0;
@@ -7210,11 +7957,11 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
7210
7957
  return YES;
7211
7958
  }
7212
7959
 
7213
- - (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 {
7214
7961
  NSString *key = [self nativeViewKeyForWindow:windowId label:label];
7215
7962
  NSView *view = self.nativeViews[key];
7216
7963
  if (![view isKindOfClass:[NativeSdkMetalSurfaceView class]]) return NO;
7217
- [(NativeSdkMetalSurfaceView *)view setScrollDrivers:drivers count:count];
7964
+ [(NativeSdkMetalSurfaceView *)view setScrollDrivers:drivers count:count occluders:occluders occluderCount:occluderCount];
7218
7965
  return YES;
7219
7966
  }
7220
7967
 
@@ -7460,6 +8207,7 @@ static double NativeSdkClampedPinchMagnification(double magnification) {
7460
8207
  WKWebView *webview = [[NativeSdkWebView alloc] initWithFrame:[self webViewFrameForWindow:window x:x y:y width:width height:height] configuration:configuration];
7461
8208
  ((NativeSdkWebView *)webview).host = self;
7462
8209
  ((NativeSdkWebView *)webview).windowId = windowId;
8210
+ ((NativeSdkWebView *)webview).viewLabel = label;
7463
8211
  [webview registerForDraggedTypes:@[NSPasteboardTypeFileURL]];
7464
8212
  webview.wantsLayer = YES;
7465
8213
  webview.layer.zPosition = layer;
@@ -8161,7 +8909,7 @@ static void NativeSdkApplyProcessDisplayName(NSString *displayName) {
8161
8909
  }
8162
8910
 
8163
8911
  - (NSMenuItem *)commandMenuItem:(NSString *)title command:(NSString *)command key:(NSString *)key modifiers:(uint32_t)modifiers enabled:(BOOL)enabled checked:(BOOL)checked {
8164
- NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:title ?: @"" action:@selector(menuCommandItemClicked:) keyEquivalent:key ?: @""];
8912
+ NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:title ?: @"" action:@selector(menuCommandItemClicked:) keyEquivalent:NativeSdkMenuKeyEquivalent(key ?: @"")];
8165
8913
  item.target = self;
8166
8914
  item.enabled = enabled;
8167
8915
  item.representedObject = command ?: @"";
@@ -8225,6 +8973,16 @@ static void NativeSdkApplyProcessDisplayName(NSString *displayName) {
8225
8973
  self.callback = callback;
8226
8974
  self.context = context;
8227
8975
 
8976
+ // The Dock-reopen delegate (close_policy .hide's re-show path).
8977
+ // NSApp.delegate is free in this host — everything else rides
8978
+ // notification observers — and NSApp does not retain it.
8979
+ if (!NSApp.delegate) {
8980
+ NativeSdkAppDelegate *reopenDelegate = [[NativeSdkAppDelegate alloc] init];
8981
+ reopenDelegate.host = self;
8982
+ self.reopenDelegate = reopenDelegate;
8983
+ NSApp.delegate = reopenDelegate;
8984
+ }
8985
+
8228
8986
  // Present-before-show: a deferred startup window stays ordered out
8229
8987
  // here and appears when its first canvas present lands (or the
8230
8988
  // create-time fallback deadline fires).
@@ -8245,14 +9003,50 @@ static void NativeSdkApplyProcessDisplayName(NSString *displayName) {
8245
9003
  return event;
8246
9004
  }];
8247
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
+ }
8248
9031
 
8249
9032
  [self startApplicationActivationObservers];
8250
9033
  [self startAppearanceObservers];
8251
9034
 
8252
9035
  [self emitEvent:(native_sdk_appkit_event_t){ .kind = NATIVE_SDK_APPKIT_EVENT_START }];
9036
+ // A VALID quit can arrive during the START dispatch (an update that
9037
+ // returns fx.quitApp() at boot). Pre-run there is no queue turn to
9038
+ // defer it to, so native_sdk_appkit_request_stop parked it — and
9039
+ // THIS is its drain point: emitShutdown + stop run at top level,
9040
+ // after the START dispatch has committed to the session recorder,
9041
+ // never nested inside it (a nested emit seals the journal before
9042
+ // the start record commits and replay refuses the recording).
9043
+ [self drainPendingPreRunStop];
8253
9044
  // A failed START handler requests shutdown synchronously, before the
8254
9045
  // run loop exists — [NSApp stop:] is a no-op there. Honor the request
8255
- // here instead of stranding a live app behind a blank window.
9046
+ // here instead of stranding a live app behind a blank window. (That
9047
+ // request is the HOST side's native_sdk_appkit_stop, which keeps its
9048
+ // inline pre-run emit — distinct from the quit verb's pending flag
9049
+ // drained above.)
8256
9050
  if (self.didShutdown) return;
8257
9051
  [self emitAppearanceChanged];
8258
9052
  [self emitResize];
@@ -8269,6 +9063,14 @@ static void NativeSdkApplyProcessDisplayName(NSString *displayName) {
8269
9063
  }
8270
9064
  }
8271
9065
 
9066
+ // The appearance/resize/window-frame emits and the synchronous
9067
+ // first canvas frame above are pre-run dispatches too — a boot
9068
+ // command's update (a TS core's first-frame command included) can
9069
+ // return the quit verb during any of them. Drain the parked quit
9070
+ // here at top level before the run-loop machinery arms; when it
9071
+ // drains, the app never enters [NSApp run].
9072
+ if ([self drainPendingPreRunStop]) return;
9073
+
8272
9074
  // Terminations that bypass the host's own stop path — cmd+Q's
8273
9075
  // default NSApp terminate, an AppleScript quit — must still deliver
8274
9076
  // the shutdown event synchronously before the process exits: the
@@ -8312,10 +9114,15 @@ static void NativeSdkApplyProcessDisplayName(NSString *displayName) {
8312
9114
  self.timer = nil;
8313
9115
  [self invalidateAppTimers];
8314
9116
  [self audioStop];
9117
+ [self videoStop];
8315
9118
  if (self.shortcutEventMonitor) {
8316
9119
  [NSEvent removeMonitor:self.shortcutEventMonitor];
8317
9120
  self.shortcutEventMonitor = nil;
8318
9121
  }
9122
+ if (self.viewFocusEventMonitor) {
9123
+ [NSEvent removeMonitor:self.viewFocusEventMonitor];
9124
+ self.viewFocusEventMonitor = nil;
9125
+ }
8319
9126
  [self stopAppearanceObservers];
8320
9127
  [self stopApplicationActivationObservers];
8321
9128
  [NSApp stop:nil];
@@ -8331,6 +9138,22 @@ static void NativeSdkApplyProcessDisplayName(NSString *displayName) {
8331
9138
  [NSApp postEvent:event atStart:NO];
8332
9139
  }
8333
9140
 
9141
+ /* Drain the quit verb a pre-run dispatch parked (see
9142
+ * native_sdk_appkit_request_stop): emitShutdown + stop at TOP LEVEL,
9143
+ * strictly after the requesting dispatch returned, so the session
9144
+ * recorder commits the requesting event before the shutdown record
9145
+ * seals the journal. Answers YES only when it drained; a request that
9146
+ * raced an already-emitted shutdown (a failed emit's inline stop) is
9147
+ * consumed without a second emit. */
9148
+ - (BOOL)drainPendingPreRunStop {
9149
+ if (!self.pendingPreRunStop) return NO;
9150
+ self.pendingPreRunStop = NO;
9151
+ if (self.didShutdown) return NO;
9152
+ [self emitShutdown];
9153
+ [self stop];
9154
+ return YES;
9155
+ }
9156
+
8334
9157
  - (void)emitEvent:(native_sdk_appkit_event_t)event {
8335
9158
  if (self.callback) {
8336
9159
  self.callback(self.context, &event);
@@ -8420,6 +9243,22 @@ static void NativeSdkApplyProcessDisplayName(NSString *displayName) {
8420
9243
  });
8421
9244
  return;
8422
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
+ }
8423
9262
  [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
8424
9263
  }
8425
9264
 
@@ -8477,6 +9316,10 @@ static void NativeSdkApplyProcessDisplayName(NSString *displayName) {
8477
9316
  .scale = window.backingScaleFactor,
8478
9317
  .open = open ? 1 : 0,
8479
9318
  .focused = window.isKeyWindow ? 1 : 0,
9319
+ // The hidden flag reports host truth, not a parameter: every
9320
+ // frame emit while a window sits in the policy-hidden set
9321
+ // carries it, and hide/show flip the set before they emit.
9322
+ .hidden = [self.policyHiddenWindows containsObject:@(windowId)] ? 1 : 0,
8480
9323
  .label = label.UTF8String,
8481
9324
  .label_len = [label lengthOfBytesUsingEncoding:NSUTF8StringEncoding],
8482
9325
  }];
@@ -8590,7 +9433,12 @@ static double NativeSdkSecondsFromCMTime(CMTime time) {
8590
9433
 
8591
9434
  static CMTime NativeSdkCMTimeFromMs(uint64_t ms) {
8592
9435
  CMTime time;
8593
- 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;
8594
9442
  time.timescale = 1000;
8595
9443
  time.flags = kCMTimeFlags_Valid;
8596
9444
  time.epoch = 0;
@@ -8763,9 +9611,14 @@ static int NativeSdkSpectrumComputeBands(native_sdk_spectrum_tap_state_t *state,
8763
9611
  double duration = self.audioItem ? NativeSdkSecondsFromCMTime(self.audioItem.duration) : 0.0;
8764
9612
  if (position > 0) position_ms = (uint64_t)llround(position * 1000.0);
8765
9613
  if (duration > 0) duration_ms = (uint64_t)llround(duration * 1000.0);
8766
- /* rate > 0 is the transport intent (un-paused); the buffering
8767
- * flag beside it says whether audio is actually coming out.
8768
- * 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. */
8769
9622
  playing = player.rate > 0 ? 1 : 0;
8770
9623
  buffering = (!self.audioSourceIsLocal && self.audioBuffering) ? 1 : 0;
8771
9624
  }
@@ -9299,6 +10152,679 @@ static int NativeSdkSpectrumComputeBands(native_sdk_spectrum_tap_state_t *state,
9299
10152
  return 1;
9300
10153
  }
9301
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
+
9302
10828
  - (void)scheduleBridgeFrames {
9303
10829
  self.bridgeFrameKeepalive = NativeSdkBridgeFrameKeepaliveFrames;
9304
10830
  [self scheduleFrame];
@@ -9661,6 +11187,58 @@ static NSString *NativeSdkOriginForURL(NSURL *url) {
9661
11187
  return [NSString stringWithFormat:@"%@://%@", scheme, host];
9662
11188
  }
9663
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
+
9664
11242
  static NSString *NativeSdkShortcutKeyForEvent(NSEvent *event) {
9665
11243
  NSString *characters = event.charactersIgnoringModifiers ?: @"";
9666
11244
  if (characters.length == 0) return @"";
@@ -9673,6 +11251,21 @@ static NSString *NativeSdkShortcutKeyForEvent(NSEvent *event) {
9673
11251
  case NSDeleteFunctionKey: return @"delete";
9674
11252
  case NSHomeFunctionKey: return @"home";
9675
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";
9676
11269
  case 0x1b: return @"escape";
9677
11270
  case '\r': return @"enter";
9678
11271
  case '\t': return @"tab";
@@ -9704,6 +11297,14 @@ static NSString *NativeSdkShortcutKeyForEvent(NSEvent *event) {
9704
11297
  }
9705
11298
  }
9706
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
+
9707
11308
  static BOOL NativeSdkShortcutUsesImplicitShift(NSString *key, NSEvent *event) {
9708
11309
  if ((event.modifierFlags & NSEventModifierFlagShift) == 0) return NO;
9709
11310
  if (key.length != 1) return NO;
@@ -9888,6 +11489,55 @@ int native_sdk_appkit_audio_set_volume(native_sdk_appkit_host_t *host, double vo
9888
11489
  return [object audioSetVolume:volume];
9889
11490
  }
9890
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
+
9891
11541
  void native_sdk_appkit_wake(native_sdk_appkit_host_t *host) {
9892
11542
  NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
9893
11543
  [object wakeFromAnyThread];
@@ -9895,8 +11545,58 @@ void native_sdk_appkit_wake(native_sdk_appkit_host_t *host) {
9895
11545
 
9896
11546
  void native_sdk_appkit_stop(native_sdk_appkit_host_t *host) {
9897
11547
  NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
9898
- [object emitShutdown];
9899
- [object stop];
11548
+ /* The HOST side's shutdown request — a failed event emit asks for
11549
+ * the teardown (see RunState.emit's catch in macos/root.zig). Not
11550
+ * the quit verb's landing point: that is
11551
+ * native_sdk_appkit_request_stop below. Queued while the run loop
11552
+ * is live, so the emit lands on the next turn at top level; [NSApp
11553
+ * run] drains the main queue and stop's posted wake event unwinds
11554
+ * it, so a stop that is the last thing an app ever does still
11555
+ * exits promptly. */
11556
+ if (!NSApp.running) {
11557
+ /* Before [NSApp run] there is no loop to drain the queue — a
11558
+ * failed START handler requests shutdown synchronously (see
11559
+ * runWithCallback's didShutdown check) and must keep getting
11560
+ * the inline emit, or the request would strand until a run
11561
+ * loop that may never start. */
11562
+ [object emitShutdown];
11563
+ [object stop];
11564
+ return;
11565
+ }
11566
+ dispatch_async(dispatch_get_main_queue(), ^{
11567
+ [object emitShutdown];
11568
+ [object stop];
11569
+ });
11570
+ }
11571
+
11572
+ void native_sdk_appkit_request_stop(native_sdk_appkit_host_t *host) {
11573
+ NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
11574
+ /* The quit VERB's landing point (fx.quitApp). The verb arrives MID
11575
+ * DISPATCH — some update returned it, so the runtime is still
11576
+ * inside that event's dispatch. Emitting SHUTDOWN here would nest
11577
+ * the shutdown dispatch inside the requester's: the session
11578
+ * recorder commits nested events innermost-first and seals the
11579
+ * journal on shutdown, so the nested seal makes the OUTER commit a
11580
+ * no-op and the journal loses the very event (and model mutation)
11581
+ * that quit the app — replay diverges. While the run loop is live,
11582
+ * one main-queue hop delivers the identical emitShutdown + stop on
11583
+ * the next loop turn, after the requesting dispatch has committed.
11584
+ * Before [NSApp run] there is no queue turn that would drain in
11585
+ * time — a quit from App.start's update, or from a boot command
11586
+ * during the synchronous first canvas frame, must NOT fall back to
11587
+ * an inline emit (the same nesting bug, just pre-run) — so the
11588
+ * request parks in pendingPreRunStop and runWithCallback drains it
11589
+ * at top level once the pre-run dispatch that carried it returns.
11590
+ * (The inline pre-run emit lives only in native_sdk_appkit_stop
11591
+ * above, for the host-side failed-START request.) */
11592
+ if (!NSApp.running) {
11593
+ object.pendingPreRunStop = YES;
11594
+ return;
11595
+ }
11596
+ dispatch_async(dispatch_get_main_queue(), ^{
11597
+ [object emitShutdown];
11598
+ [object stop];
11599
+ });
9900
11600
  }
9901
11601
 
9902
11602
  void native_sdk_appkit_load_webview(native_sdk_appkit_host_t *host, const char *source, size_t source_len, int source_kind, const char *asset_root, size_t asset_root_len, const char *asset_entry, size_t asset_entry_len, const char *asset_origin, size_t asset_origin_len, int spa_fallback) {
@@ -10006,6 +11706,22 @@ int native_sdk_appkit_minimize_window(native_sdk_appkit_host_t *host, uint64_t w
10006
11706
  return 1;
10007
11707
  }
10008
11708
 
11709
+ int native_sdk_appkit_show_window(native_sdk_appkit_host_t *host, uint64_t window_id) {
11710
+ NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
11711
+ if (!object.windows[@(window_id)]) return 0;
11712
+ [object showWindowWithId:window_id];
11713
+ return 1;
11714
+ }
11715
+
11716
+ int native_sdk_appkit_set_window_close_policy(native_sdk_appkit_host_t *host, uint64_t window_id, int close_policy) {
11717
+ NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
11718
+ if (!object.windows[@(window_id)]) return 0;
11719
+ // Applied right after create, like the content min-size floor —
11720
+ // close handling is host window state fixed for the window's life.
11721
+ object.windowClosePolicies[@(window_id)] = @(close_policy);
11722
+ return 1;
11723
+ }
11724
+
10009
11725
  int native_sdk_appkit_start_window_drag(native_sdk_appkit_host_t *host, uint64_t window_id) {
10010
11726
  NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
10011
11727
  return [object startWindowDragWithId:window_id] ? 1 : 0;
@@ -10111,10 +11827,10 @@ int native_sdk_appkit_note_gpu_surface_input(native_sdk_appkit_host_t *host, uin
10111
11827
  return [object noteGpuSurfaceInputInWindow:window_id label:labelString ?: @""] ? 1 : 0;
10112
11828
  }
10113
11829
 
10114
- 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) {
10115
11831
  NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
10116
11832
  NSString *labelString = label ? [[NSString alloc] initWithBytes:label length:label_len encoding:NSUTF8StringEncoding] : @"";
10117
- 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;
10118
11834
  }
10119
11835
 
10120
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) {