@native-sdk/cli 0.5.2 → 0.5.4

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 (123) hide show
  1. package/build/app.zig +41 -1
  2. package/build.zig +264 -3
  3. package/native-sdk.d.ts +17 -1
  4. package/package.json +9 -9
  5. package/packages/core/package-lock.json +2 -2
  6. package/packages/core/package.json +1 -1
  7. package/packages/core/rt/rt.zig +138 -3
  8. package/packages/core/sdk/core.ts +225 -3
  9. package/packages/core/sdk/events.ts +39 -2
  10. package/packages/core/src/checker.ts +1 -1
  11. package/packages/core/src/emitter.ts +2625 -262
  12. package/packages/core/src/infer.ts +53 -7
  13. package/skill-data/automation/SKILL.md +7 -4
  14. package/skill-data/core/references/app-model-runtime.md +3 -0
  15. package/skill-data/native-ui/SKILL.md +4 -2
  16. package/skill-data/ts-core/SKILL.md +9 -1
  17. package/src/app_runner/root.zig +106 -1
  18. package/src/app_runner/ts_core_main.zig +4 -0
  19. package/src/automation/protocol.zig +20 -1
  20. package/src/embed/host.zig +27 -0
  21. package/src/embed/tests.zig +187 -0
  22. package/src/embed/ui_host.zig +4 -0
  23. package/src/platform/linux/gtk_host.c +112 -3
  24. package/src/platform/linux/root.zig +71 -0
  25. package/src/platform/macos/appkit_host.h +59 -2
  26. package/src/platform/macos/appkit_host.m +663 -34
  27. package/src/platform/macos/cef_host.mm +262 -10
  28. package/src/platform/macos/root.zig +126 -4
  29. package/src/platform/null_platform.zig +298 -5
  30. package/src/platform/null_platform_tests.zig +39 -0
  31. package/src/platform/root.zig +36 -0
  32. package/src/platform/types.zig +247 -8
  33. package/src/platform/windows/root.zig +134 -0
  34. package/src/platform/windows/webview2_host.cpp +152 -40
  35. package/src/primitives/app_manifest/comptime_scene.zig +5 -0
  36. package/src/primitives/app_manifest/root.zig +1 -0
  37. package/src/primitives/app_manifest/types.zig +32 -0
  38. package/src/primitives/canvas/chart.zig +7 -7
  39. package/src/primitives/canvas/chart_tests.zig +66 -0
  40. package/src/primitives/canvas/commands.zig +48 -0
  41. package/src/primitives/canvas/events.zig +161 -0
  42. package/src/primitives/canvas/font_ttf.zig +155 -8
  43. package/src/primitives/canvas/font_ttf_tests.zig +686 -0
  44. package/src/primitives/canvas/reference.zig +67 -8
  45. package/src/primitives/canvas/render_fingerprints.zig +8 -0
  46. package/src/primitives/canvas/root.zig +25 -0
  47. package/src/primitives/canvas/tests.zig +1 -0
  48. package/src/primitives/canvas/ui.zig +46 -9
  49. package/src/primitives/canvas/ui_markup.zig +82 -34
  50. package/src/primitives/canvas/ui_markup_binary.zig +4 -1
  51. package/src/primitives/canvas/ui_markup_binary_tests.zig +25 -0
  52. package/src/primitives/canvas/ui_markup_compiled.zig +63 -11
  53. package/src/primitives/canvas/ui_markup_compiled_tests.zig +88 -0
  54. package/src/primitives/canvas/ui_markup_contract.zig +10 -1
  55. package/src/primitives/canvas/ui_markup_contract_tests.zig +50 -0
  56. package/src/primitives/canvas/ui_markup_huge_document_tests.zig +154 -0
  57. package/src/primitives/canvas/ui_markup_tests.zig +55 -9
  58. package/src/primitives/canvas/ui_markup_view.zig +81 -14
  59. package/src/primitives/canvas/ui_markup_view_tests.zig +219 -7
  60. package/src/primitives/canvas/ui_schema.zig +29 -0
  61. package/src/primitives/canvas/ui_schema_tests.zig +11 -11
  62. package/src/primitives/canvas/ui_tests.zig +31 -0
  63. package/src/primitives/canvas/vector.zig +258 -141
  64. package/src/primitives/canvas/widget_access.zig +1 -1
  65. package/src/primitives/canvas/widget_builtin_tests.zig +129 -0
  66. package/src/primitives/canvas/widget_layout.zig +9 -4
  67. package/src/primitives/canvas/widget_render.zig +78 -40
  68. package/src/primitives/canvas/widget_render_controls.zig +15 -4
  69. package/src/primitives/canvas/widget_semantics.zig +6 -1
  70. package/src/primitives/canvas/widget_semantics_tests.zig +168 -0
  71. package/src/primitives/canvas/widget_text_input.zig +118 -10
  72. package/src/primitives/canvas/widgets.zig +16 -0
  73. package/src/root.zig +12 -0
  74. package/src/runtime/api.zig +15 -0
  75. package/src/runtime/automation_commands.zig +33 -0
  76. package/src/runtime/automation_widget_dispatch.zig +64 -0
  77. package/src/runtime/bridge_payload.zig +7 -0
  78. package/src/runtime/bridge_responses.zig +5 -0
  79. package/src/runtime/builtin_bridge.zig +9 -4
  80. package/src/runtime/canvas_font_tests.zig +711 -5
  81. package/src/runtime/canvas_fonts.zig +120 -25
  82. package/src/runtime/canvas_frame_helpers.zig +15 -0
  83. package/src/runtime/canvas_image_tests.zig +221 -0
  84. package/src/runtime/canvas_images.zig +78 -19
  85. package/src/runtime/canvas_limits.zig +44 -8
  86. package/src/runtime/canvas_widget_clipboard_tests.zig +123 -0
  87. package/src/runtime/canvas_widget_context_menu_tests.zig +55 -0
  88. package/src/runtime/canvas_widget_events.zig +24 -4
  89. package/src/runtime/canvas_widget_runtime.zig +24 -7
  90. package/src/runtime/canvas_widget_state.zig +6 -1
  91. package/src/runtime/canvas_widget_text_tests.zig +277 -0
  92. package/src/runtime/core.zig +148 -9
  93. package/src/runtime/effects.zig +1664 -43
  94. package/src/runtime/effects_fetch_tests.zig +89 -1
  95. package/src/runtime/effects_file_tests.zig +41 -1
  96. package/src/runtime/effects_image_tests.zig +1304 -0
  97. package/src/runtime/effects_tests.zig +153 -0
  98. package/src/runtime/flow.zig +44 -0
  99. package/src/runtime/gpu_surface_events.zig +7 -0
  100. package/src/runtime/media_surface.zig +726 -0
  101. package/src/runtime/media_surface_tests.zig +1476 -0
  102. package/src/runtime/root.zig +20 -0
  103. package/src/runtime/session_blobs.zig +689 -0
  104. package/src/runtime/session_journal.zig +111 -20
  105. package/src/runtime/session_record.zig +27 -2
  106. package/src/runtime/session_replay.zig +168 -16
  107. package/src/runtime/session_tests.zig +2118 -4
  108. package/src/runtime/shell_layout.zig +7 -0
  109. package/src/runtime/testdata/fonts/NotoSansSC-Receipt.ttf +0 -0
  110. package/src/runtime/testdata/fonts/OFL.txt +93 -0
  111. package/src/runtime/tests.zig +3 -0
  112. package/src/runtime/ts_core_host.zig +439 -4
  113. package/src/runtime/ts_core_host_tests.zig +41 -0
  114. package/src/runtime/ts_ui_app.zig +63 -0
  115. package/src/runtime/ui_app.zig +169 -6
  116. package/src/runtime/ui_app_tests.zig +334 -0
  117. package/src/runtime/ui_app_window_tests.zig +468 -0
  118. package/src/runtime/window_command_bridge_tests.zig +117 -0
  119. package/src/runtime/window_storage.zig +32 -0
  120. package/src/runtime/window_views.zig +61 -1
  121. package/src/tooling/manifest.zig +75 -0
  122. package/src/tooling/raw_manifest.zig +2 -0
  123. package/src/tooling/templates.zig +219 -1
@@ -301,6 +301,17 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
301
301
  @property(nonatomic, assign) BOOL observesContentLayout;
302
302
  @end
303
303
 
304
+ /// NSApp's delegate, installed by runWithCallback: — this host
305
+ /// otherwise drives NSApplication entirely through notification
306
+ /// observers, and staying that way for activation keeps those events
307
+ /// single-sourced (a delegate implementing applicationDidBecomeActive:
308
+ /// would ALSO receive the notification, double-emitting). The one job
309
+ /// here is the Dock-icon reopen: with no window visible, re-show the
310
+ /// windows the .hide close policy hid.
311
+ @interface NativeSdkAppDelegate : NSObject <NSApplicationDelegate>
312
+ @property(nonatomic, assign) NativeSdkAppKitHost *host;
313
+ @end
314
+
304
315
  @interface NativeSdkWebView : WKWebView <NSDraggingDestination>
305
316
  @property(nonatomic, strong) NSArray<NSValue *> *coveredMouseRects;
306
317
  @property(nonatomic, assign) NativeSdkAppKitHost *host;
@@ -569,6 +580,7 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
569
580
  @property(nonatomic, assign) double pendingScrollDriverOffsetY;
570
581
  @property(nonatomic, assign) uint64_t scrollDriverEventLastEmitNs;
571
582
  @property(nonatomic, assign) BOOL controlClickActive;
583
+ @property(nonatomic, assign) BOOL pinchGestureActive;
572
584
  - (void)configureWithHost:(NativeSdkAppKitHost *)host windowId:(uint64_t)windowId label:(NSString *)label;
573
585
  - (BOOL)isAvailable;
574
586
  - (void)updateDrawableSize;
@@ -613,6 +625,8 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
613
625
  - (void)emitQueuedPointerMotionInputEvent;
614
626
  - (void)queueScrollInputEvent:(NSEvent *)event deltaX:(double)deltaX deltaY:(double)deltaY;
615
627
  - (void)emitQueuedScrollInputEvent;
628
+ - (void)emitPinchInputEventWithKind:(NSInteger)kind event:(NSEvent *)event magnification:(double)magnification;
629
+ - (void)emitPinchChangeForEvent:(NSEvent *)event;
616
630
  - (void)emitInputEventWithKind:(NSInteger)kind point:(NSPoint)point timestampNs:(uint64_t)timestampNs modifiers:(uint32_t)modifiers keyText:(NSString *)keyText inputText:(NSString *)inputText button:(NSInteger)button deltaX:(double)deltaX deltaY:(double)deltaY;
617
631
  - (void)emitSyntheticKeyDownWithKey:(NSString *)key modifiers:(uint32_t)modifiers;
618
632
  - (void)updateSurfaceTrackingArea;
@@ -659,6 +673,20 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
659
673
  /// color, packed RGBA8 per window — so residual gaps (resize slack,
660
674
  /// titlebar bands) show the app's background, never a blank default.
661
675
  @property(nonatomic, strong) NSMutableDictionary<NSNumber *, NSNumber *> *windowClearColors;
676
+ /// close_policy per window (0 = quit, the default; 1 = hide). Applied
677
+ /// by native_sdk_appkit_set_window_close_policy right after create —
678
+ /// the delegate's windowShouldClose: consults it, so the user's close
679
+ /// affordance hides a .hide window instead of closing it.
680
+ @property(nonatomic, strong) NSMutableDictionary<NSNumber *, NSNumber *> *windowClosePolicies;
681
+ /// Windows currently hidden BY their .hide close policy — the set the
682
+ /// Dock reopen re-shows, and the truth emitWindowFrameForWindowId's
683
+ /// hidden flag reports. Ordinary orderOut/minimize states never enter
684
+ /// it.
685
+ @property(nonatomic, strong) NSMutableSet<NSNumber *> *policyHiddenWindows;
686
+ /// Strong ref for NSApp.delegate (which is unretained): the tiny
687
+ /// delegate that turns a Dock-icon reopen into re-showing
688
+ /// policy-hidden windows.
689
+ @property(nonatomic, strong) id reopenDelegate;
662
690
  @property(nonatomic, strong) NSMutableDictionary<NSString *, WKWebView *> *childWebViews;
663
691
  @property(nonatomic, strong) NSMutableDictionary<NSString *, NSView *> *nativeViews;
664
692
  /// App-owned NSViews adopted into native view containers (native-surface
@@ -761,6 +789,11 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
761
789
  @property(nonatomic, assign) void *context;
762
790
  @property(nonatomic, assign) void *bridgeContext;
763
791
  @property(nonatomic, assign) BOOL didShutdown;
792
+ /* A quit verb that arrived before [NSApp run] (see
793
+ * native_sdk_appkit_request_stop): parked here, drained at top level
794
+ * by runWithCallback's drainPendingPreRunStop calls once the pre-run
795
+ * dispatch that carried it has returned. */
796
+ @property(nonatomic, assign) BOOL pendingPreRunStop;
764
797
  @property(nonatomic, assign) BOOL observesApplicationActivation;
765
798
  @property(nonatomic, assign) BOOL observesAppearanceChanges;
766
799
  @property(nonatomic, assign) NSInteger bridgeFrameKeepalive;
@@ -780,6 +813,9 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
780
813
  - (void)applyWindowClearColor:(uint64_t)windowId red:(uint8_t)red green:(uint8_t)green blue:(uint8_t)blue alpha:(uint8_t)alpha;
781
814
  - (void)focusWindowWithId:(uint64_t)windowId;
782
815
  - (void)closeWindowWithId:(uint64_t)windowId;
816
+ - (void)hideWindowWithId:(uint64_t)windowId;
817
+ - (void)showWindowWithId:(uint64_t)windowId;
818
+ - (BOOL)reopenPolicyHiddenWindows;
783
819
  - (BOOL)startWindowDragWithId:(uint64_t)windowId;
784
820
  - (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;
785
821
  - (WKWebView *)ensureMainWebViewForWindowId:(uint64_t)windowId;
@@ -840,6 +876,7 @@ static NSMutableDictionary *NativeSdkCredentialQuery(NSString *service, NSString
840
876
  - (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;
841
877
  - (void)runWithCallback:(native_sdk_appkit_event_callback_t)callback context:(void *)context;
842
878
  - (void)stop;
879
+ - (BOOL)drainPendingPreRunStop;
843
880
  - (void)emitEvent:(native_sdk_appkit_event_t)event;
844
881
  - (BOOL)emitDroppedFileURLs:(NSArray<NSURL *> *)urls windowId:(uint64_t)windowId;
845
882
  - (void)startApplicationActivationObservers;
@@ -1019,6 +1056,22 @@ static void NativeSdkEmitGpuSurfaceResizes(NSView *view) {
1019
1056
  return [self.host emitDroppedFileURLs:urls windowId:self.windowId];
1020
1057
  }
1021
1058
 
1059
+ // close_policy .hide: the USER's close affordance (the red button,
1060
+ // cmd+W — anything routed through performClose:) hides the window
1061
+ // instead of closing it, and the app keeps running behind its status
1062
+ // item. Runtime-initiated closes bypass this hook deliberately
1063
+ // (closeWindowWithId: calls -close directly for .hide windows), so an
1064
+ // app that decides to really close its window still can. A future
1065
+ // .event tier would land here too — the delegate forwarding the close
1066
+ // request to the model instead of deciding — the enum keeps that room.
1067
+ - (BOOL)windowShouldClose:(NSWindow *)sender {
1068
+ (void)sender;
1069
+ NSNumber *policy = self.host.windowClosePolicies[@(self.windowId)];
1070
+ if (policy.intValue != 1) return YES;
1071
+ [self.host hideWindowWithId:self.windowId];
1072
+ return NO;
1073
+ }
1074
+
1022
1075
  - (void)windowWillClose:(NSNotification *)notification {
1023
1076
  (void)notification;
1024
1077
  if (self.observesContentLayout) {
@@ -1026,6 +1079,10 @@ static void NativeSdkEmitGpuSurfaceResizes(NSView *view) {
1026
1079
  [window removeObserver:self forKeyPath:@"contentLayoutRect"];
1027
1080
  self.observesContentLayout = NO;
1028
1081
  }
1082
+ // A really-closing window is closed, not hidden: leave the
1083
+ // policy-hidden set before the frame emit so open=false never
1084
+ // carries a stale hidden=true.
1085
+ [self.host.policyHiddenWindows removeObject:@(self.windowId)];
1029
1086
  [self.host emitWindowFrameForWindowId:self.windowId open:NO];
1030
1087
  [self.host closeWebViewsInWindow:self.windowId];
1031
1088
  [self.host closeNativeViewsInWindow:self.windowId];
@@ -1038,6 +1095,7 @@ static void NativeSdkEmitGpuSurfaceResizes(NSView *view) {
1038
1095
  [self.host.windowLabels removeObjectForKey:key];
1039
1096
  [self.host.deferredShowWindows removeObjectForKey:key];
1040
1097
  [self.host.windowClearColors removeObjectForKey:key];
1098
+ [self.host.windowClosePolicies removeObjectForKey:key];
1041
1099
  if (self.host.windows.count == 0) {
1042
1100
  [self.host emitShutdown];
1043
1101
  [self.host stop];
@@ -1046,6 +1104,20 @@ static void NativeSdkEmitGpuSurfaceResizes(NSView *view) {
1046
1104
 
1047
1105
  @end
1048
1106
 
1107
+ @implementation NativeSdkAppDelegate
1108
+
1109
+ // Clicking the Dock icon with every window gone from the glass: when
1110
+ // policy-hidden windows exist, re-show them and answer NO (the reopen
1111
+ // is handled); otherwise answer YES so AppKit keeps its default
1112
+ // behavior (deminiaturizing, ordering in) untouched.
1113
+ - (BOOL)applicationShouldHandleReopen:(NSApplication *)sender hasVisibleWindows:(BOOL)flag {
1114
+ (void)sender;
1115
+ if (flag) return YES;
1116
+ return ![self.host reopenPolicyHiddenWindows];
1117
+ }
1118
+
1119
+ @end
1120
+
1049
1121
  @implementation NativeSdkWebView
1050
1122
 
1051
1123
  - (BOOL)pointIsCovered:(NSPoint)point {
@@ -1760,19 +1832,122 @@ static NSMutableDictionary<NSNumber *, id> *NativeSdkRegisteredFontDescriptors(v
1760
1832
  return table;
1761
1833
  }
1762
1834
 
1763
- // The registered face for a canvas font id at `size`, or nil when the id
1764
- // has no registered face. Checked BEFORE the built-in candidates and
1765
- // their cache so a registered id can never be masked by a font resolved
1766
- // for that id earlier (ids are engine-validated and permanent, so cached
1767
- // NSFonts here never go stale).
1768
- static NSFont *NativeSdkRegisteredFontForId(unsigned long long value, CGFloat size) {
1769
- NSMutableDictionary<NSNumber *, id> *table = NativeSdkRegisteredFontDescriptors();
1770
- static NSMutableDictionary<NSString *, NSFont *> *sizeCache = nil;
1835
+ // The per-(id, size) NSFont cache for registered faces, keyed "id/size".
1836
+ // Ids are permanent within ONE runtime (`error.FontIdInUse` guards
1837
+ // re-use for a runtime's lifetime), but this cache is per-PROCESS and
1838
+ // runtimes are not: an embedder that destroys its runtime
1839
+ // (`Runtime.deinit`) and registers a DIFFERENT face under the same
1840
+ // valid id in a new runtime is inside the documented lifecycle. Entries
1841
+ // therefore go stale exactly when an id's descriptor is (re)installed,
1842
+ // so `native_sdk_appkit_register_font` evicts the id's cached sizes
1843
+ // before installing the new descriptor. The measured-width NSCache
1844
+ // (`NativeSdkMeasuredWidthCache`) goes stale at the same moment but
1845
+ // cannot be prefix-evicted (NSCache does not enumerate keys), so it is
1846
+ // invalidated by registration token instead — see
1847
+ // NativeSdkRegisteredFontTokens below. Accessed only under the
1848
+ // descriptor table's @synchronized guard, like the descriptors.
1849
+ static NSMutableDictionary<NSString *, NSFont *> *NativeSdkRegisteredFontSizeCache(void) {
1850
+ static NSMutableDictionary<NSString *, NSFont *> *cache = nil;
1851
+ static dispatch_once_t onceToken;
1852
+ dispatch_once(&onceToken, ^{
1853
+ cache = [[NSMutableDictionary alloc] init];
1854
+ });
1855
+ return cache;
1856
+ }
1857
+
1858
+ // Per-id registration tokens, the invalidation handle for the
1859
+ // measured-width NSCache (`NativeSdkMeasuredWidthCache`). That
1860
+ // cache has the same lifetime hazard as the size cache above (per-
1861
+ // process cache, per-runtime id permanence) but no way to evict an
1862
+ // id's entries — NSCache cannot enumerate keys — so every registration
1863
+ // stamps its id with the next value of ONE process-global monotonic
1864
+ // counter and the width-cache key includes the stamp. Tokens never
1865
+ // repeat, so no registration can ever reach widths a previous life of
1866
+ // its id cached (re-registration leaves those unreachable entries to
1867
+ // age out under the cache's count limit; unregistration clears the
1868
+ // cache outright — see `native_sdk_appkit_unregister_font`) — which is
1869
+ // exactly what makes an id's record REMOVABLE at unregister, retaining
1870
+ // zero state per retired id.
1871
+ // A per-id bump counter could not offer that: deleting a per-id count
1872
+ // would let a future registration of the id restart at 1 and collide
1873
+ // with the retired life's still-cached widths, so retired ids would
1874
+ // each pin a record for the process lifetime. Ids never registered
1875
+ // (the built-in faces) have no record and measure under token 0 — the
1876
+ // same value an unregistered id returns to, honest because both states
1877
+ // resolve through the same built-in candidates. Accessed only under
1878
+ // the descriptor table's @synchronized guard, like the descriptors.
1879
+ static NSMutableDictionary<NSNumber *, NSNumber *> *NativeSdkRegisteredFontTokens(void) {
1880
+ static NSMutableDictionary<NSNumber *, NSNumber *> *table = nil;
1771
1881
  static dispatch_once_t onceToken;
1772
1882
  dispatch_once(&onceToken, ^{
1773
- sizeCache = [[NSMutableDictionary alloc] init];
1883
+ table = [[NSMutableDictionary alloc] init];
1774
1884
  });
1885
+ return table;
1886
+ }
1887
+
1888
+ // The process-global registration token counter: pre-incremented at
1889
+ // every registration, so 0 is never a live token and stays the honest
1890
+ // "no registered face" value. Mutated only under the descriptor
1891
+ // table's @synchronized guard, like every table here.
1892
+ static unsigned long long NativeSdkRegisteredFontTokenCounter = 0;
1893
+
1894
+ // The measured-width NSCache `native_sdk_appkit_measure_text` memoizes
1895
+ // shaped widths in, hoisted out of that function (exactly the shared-
1896
+ // accessor shape the NSFont size cache above took) so
1897
+ // `native_sdk_appkit_unregister_font` can reach it at teardown: a
1898
+ // retiring token's entries can never be SERVED again (tokens never
1899
+ // repeat) but a function-local static left them RESIDENT — up to the
1900
+ // full count limit of keys, each carrying the measured text itself —
1901
+ // until memory pressure. NSCache is thread-safe, so unlike the
1902
+ // dictionaries above this cache is deliberately NOT confined to the
1903
+ // descriptor table's @synchronized guard: measure_text shapes outside
1904
+ // the critical section on purpose (see the snapshot comment) and
1905
+ // re-enters the guard only to recheck the token before a
1906
+ // registered-token write (see the recheck comment in measure_text).
1907
+ static NSCache<NSString *, NSNumber *> *NativeSdkMeasuredWidthCache(void) {
1908
+ static NSCache<NSString *, NSNumber *> *cache = nil;
1909
+ static dispatch_once_t onceToken;
1910
+ dispatch_once(&onceToken, ^{
1911
+ cache = [[NSCache alloc] init];
1912
+ cache.countLimit = 16384;
1913
+ });
1914
+ return cache;
1915
+ }
1916
+
1917
+ // The id's current registration token AND the registered face that
1918
+ // token resolves to, snapshotted under ONE acquisition of the
1919
+ // descriptor table's @synchronized guard. The pair must be atomic
1920
+ // because measure_text keys its width memoization by (id, token): with
1921
+ // the token read and the face resolved under SEPARATE acquisitions, a
1922
+ // registration landing between them pairs token 0 with the NEW
1923
+ // registered face and caches a registered-face width under the
1924
+ // reusable token-0 key — served again after the registration is torn
1925
+ // down, when token 0 honestly means built-in resolution. One critical
1926
+ // section makes a torn pair unrepresentable; the width computation
1927
+ // itself stays outside the lock (see measure_text), because a
1928
+ // stale-but-consistent pair is harmless: measure_text rechecks the
1929
+ // token under the guard before caching, so a pair retired mid-shape
1930
+ // is never even written. Returns nil with
1931
+ // *out_token = 0 when the id holds no registration, so token 0 only
1932
+ // ever pairs with built-in resolution. (A registered descriptor whose
1933
+ // CTFont creation fails also answers nil, under its live token: the
1934
+ // built-in fallback then caches under that token — still one
1935
+ // consistent resolution per registration life, since the failure is a
1936
+ // property of the installed descriptor.)
1937
+ //
1938
+ // The registered-face NSFonts cached here stay honest because
1939
+ // registration evicts an id's entries when its descriptor changes (see
1940
+ // NativeSdkRegisteredFontSizeCache) — an id is only permanent within
1941
+ // one runtime, and this cache outlives runtimes. Registered faces are
1942
+ // checked BEFORE the built-in candidates and their cache so a
1943
+ // registered id can never be masked by a font resolved for that id
1944
+ // earlier.
1945
+ static NSFont *NativeSdkRegisteredFontSnapshot(unsigned long long value, CGFloat size, unsigned long long *out_token) {
1946
+ NSMutableDictionary<NSNumber *, id> *table = NativeSdkRegisteredFontDescriptors();
1947
+ NSMutableDictionary<NSString *, NSFont *> *sizeCache = NativeSdkRegisteredFontSizeCache();
1775
1948
  @synchronized (table) {
1949
+ NSNumber *tokenNumber = NativeSdkRegisteredFontTokens()[@(value)];
1950
+ *out_token = tokenNumber ? tokenNumber.unsignedLongLongValue : 0;
1776
1951
  id descriptorObject = table[@(value)];
1777
1952
  if (!descriptorObject) return nil;
1778
1953
  NSString *key = [NSString stringWithFormat:@"%llu/%.3f", value, (double)size];
@@ -1786,36 +1961,133 @@ static NSFont *NativeSdkRegisteredFontForId(unsigned long long value, CGFloat si
1786
1961
  }
1787
1962
  }
1788
1963
 
1964
+ // The registered face for a canvas font id at `size`, or nil when the id
1965
+ // has no registered face — the snapshot above for callers that resolve
1966
+ // but do not memoize by token (packet drawing, the advances batch).
1967
+ static NSFont *NativeSdkRegisteredFontForId(unsigned long long value, CGFloat size) {
1968
+ unsigned long long token = 0;
1969
+ return NativeSdkRegisteredFontSnapshot(value, size, &token);
1970
+ }
1971
+
1789
1972
  // Engine-validated TrueType bytes for a registered canvas font id: parse
1790
1973
  // them into a font descriptor once and key it by id, so measurement and
1791
1974
  // packet text drawing resolve the id to this exact face. Returns 1 on
1792
1975
  // success, 0 when CoreText rejects the data — the engine already parsed
1793
1976
  // the face, so a rejection here is surfaced as a loud registration
1794
- // error engine-side, never a silent fallback at draw time.
1795
- int native_sdk_appkit_register_font(uint64_t font_id, const uint8_t *bytes, size_t bytes_len) {
1796
- if (font_id == 0 || !bytes || bytes_len == 0) return 0;
1977
+ // error engine-side, never a silent fallback at draw time. On success
1978
+ // `*out_token` reports the registration token minted below — the
1979
+ // ownership handle unregister_font matches against, so a teardown can
1980
+ // only remove the registration it owns.
1981
+ int native_sdk_appkit_register_font(uint64_t font_id, const uint8_t *bytes, size_t bytes_len, uint64_t *out_token) {
1982
+ if (out_token) *out_token = 0;
1983
+ if (font_id == 0 || !bytes || bytes_len == 0 || !out_token) return 0;
1797
1984
  @autoreleasepool {
1798
1985
  NSData *data = [NSData dataWithBytes:bytes length:bytes_len];
1799
1986
  CTFontDescriptorRef descriptor = CTFontManagerCreateFontDescriptorFromData((__bridge CFDataRef)data);
1800
1987
  if (!descriptor) return 0;
1801
1988
  NSMutableDictionary<NSNumber *, id> *table = NativeSdkRegisteredFontDescriptors();
1802
1989
  @synchronized (table) {
1990
+ // Evict the id's cached NSFonts BEFORE installing the new
1991
+ // descriptor: the process may still hold fonts a PREVIOUS
1992
+ // runtime resolved for this id (ids are per-runtime
1993
+ // permanent, the cache is per-process), and serving them
1994
+ // would measure and draw the old face under the new id.
1995
+ NSMutableDictionary<NSString *, NSFont *> *sizeCache = NativeSdkRegisteredFontSizeCache();
1996
+ NSString *stalePrefix = [NSString stringWithFormat:@"%llu/", (unsigned long long)font_id];
1997
+ NSArray<NSString *> *cachedKeys = sizeCache.allKeys;
1998
+ for (NSString *cachedKey in cachedKeys) {
1999
+ if ([cachedKey hasPrefix:stalePrefix]) [sizeCache removeObjectForKey:cachedKey];
2000
+ }
2001
+ // The measured-width cache holds the same stale state but
2002
+ // cannot be enumerated for eviction, so stamp the id with a
2003
+ // fresh process-global token instead: width-cache keys
2004
+ // include the token, tokens never repeat, and everything
2005
+ // cached under any previous stamp becomes unreachable. The
2006
+ // stamp doubles as the registration's ownership token,
2007
+ // reported to the caller so its teardown can name exactly
2008
+ // this registration.
2009
+ unsigned long long token = ++NativeSdkRegisteredFontTokenCounter;
2010
+ NativeSdkRegisteredFontTokens()[@(font_id)] = @(token);
1803
2011
  table[@(font_id)] = (__bridge_transfer id)descriptor;
2012
+ *out_token = token;
1804
2013
  }
1805
2014
  return 1;
1806
2015
  }
1807
2016
  }
1808
2017
 
1809
- // Resolves a canvas font id to the NSFont presentation draws with. Both
1810
- // packet text drawing and native_sdk_appkit_measure_text go through this
1811
- // single function so measured layout and drawn glyphs share font
1812
- // resolution. Ids 3-6 are the reserved sans span variants (medium, bold,
1813
- // italic, bold italic); everything else keeps the regular sans/mono
1814
- // candidates. Registered faces win first (see above). Resolved
1815
- // built-in fonts are cached per (font id, size).
1816
- static NSFont *NativeSdkFontForFontId(unsigned long long value, CGFloat size) {
1817
- NSFont *registered = NativeSdkRegisteredFontForId(value, size);
1818
- if (registered) return registered;
2018
+ // Teardown twin of the registration above, called by Runtime.deinit for
2019
+ // each id the dying runtime registered: font ids are per-runtime but
2020
+ // every table here is per-process, so without this removal an embedder
2021
+ // cycling runtimes with fresh ids grows the descriptor table (and its
2022
+ // caches) for the process lifetime. Removal drops EVERYTHING the
2023
+ // registration installed: the id's cached NSFonts (the same prefix
2024
+ // eviction re-registration runs), the id's registration token record,
2025
+ // the descriptor itself, and — by clearing the measured-width NSCache
2026
+ // wholesale, the only eviction NSCache permits — the widths measured
2027
+ // under the retiring token. Zero retained state per retired id, so
2028
+ // runtime cycles truly do not accumulate host entries. Deleting the
2029
+ // token record (rather than bumping it) is safe precisely because
2030
+ // tokens come from one process-global monotonic counter: a future
2031
+ // registration of this id takes a fresh, never-repeated token, so no
2032
+ // per-id record has to survive to keep this life's width-cache keys
2033
+ // unreachable. An id
2034
+ // with no installed descriptor (never registered host-side, or already
2035
+ // returned) is a no-op accept.
2036
+ //
2037
+ // Removal is token-guarded: `token` is the ownership handle the id's
2038
+ // register call reported, and state comes out ONLY while the id's
2039
+ // current registration still carries it. Font ids are per-runtime while
2040
+ // this state is per-process, so a later runtime may have re-registered
2041
+ // the id (last wins — its face is the live one measurement and drawing
2042
+ // resolve); an id-keyed removal here would let the OLDER runtime's
2043
+ // deinit delete the newer runtime's descriptor and caches, dropping its
2044
+ // host text to the default family while its engine still holds the
2045
+ // face. A stale token is a no-op accept, not an error: the registration
2046
+ // it owned is already gone, which is exactly the state its owner asked
2047
+ // this call to establish.
2048
+ int native_sdk_appkit_unregister_font(uint64_t font_id, uint64_t token) {
2049
+ if (font_id == 0) return 0;
2050
+ @autoreleasepool {
2051
+ NSMutableDictionary<NSNumber *, id> *table = NativeSdkRegisteredFontDescriptors();
2052
+ @synchronized (table) {
2053
+ NSNumber *current = NativeSdkRegisteredFontTokens()[@(font_id)];
2054
+ if (!current || current.unsignedLongLongValue != token) return 1;
2055
+ NSMutableDictionary<NSString *, NSFont *> *sizeCache = NativeSdkRegisteredFontSizeCache();
2056
+ NSString *stalePrefix = [NSString stringWithFormat:@"%llu/", (unsigned long long)font_id];
2057
+ NSArray<NSString *> *cachedKeys = sizeCache.allKeys;
2058
+ for (NSString *cachedKey in cachedKeys) {
2059
+ if ([cachedKey hasPrefix:stalePrefix]) [sizeCache removeObjectForKey:cachedKey];
2060
+ }
2061
+ [NativeSdkRegisteredFontTokens() removeObjectForKey:@(font_id)];
2062
+ [table removeObjectForKey:@(font_id)];
2063
+ // The retiring token's measured widths can never be served
2064
+ // again (tokens never repeat) but would otherwise stay
2065
+ // resident until memory pressure. NSCache cannot enumerate
2066
+ // keys, so a per-id eviction is impossible and clearing the
2067
+ // WHOLE cache is the only honest release. The collateral is
2068
+ // cheap where it lands: unregistration is a teardown-
2069
+ // frequency event, and every other live id re-warms each
2070
+ // width it still needs in one measure call. The clear runs
2071
+ // only on this token-matched path — a stale-token no-op
2072
+ // above must not cost live registrations their warm cache.
2073
+ // A measurement in flight during this teardown cannot
2074
+ // repopulate the cleared cache: measure_text rechecks the
2075
+ // id's token under this same guard before caching, and this
2076
+ // removal already retired the token it snapshotted.
2077
+ [NativeSdkMeasuredWidthCache() removeAllObjects];
2078
+ }
2079
+ return 1;
2080
+ }
2081
+ }
2082
+
2083
+ // The built-in-candidates half of font resolution: never consults the
2084
+ // registered tables, so callers that already hold a registered-face
2085
+ // snapshot (measure_text) fall back here without re-reading state the
2086
+ // snapshot fixed. Ids 3-6 are the reserved sans span variants (medium,
2087
+ // bold, italic, bold italic); everything else keeps the regular
2088
+ // sans/mono candidates. Resolved built-in fonts are cached per
2089
+ // (font id, size).
2090
+ static NSFont *NativeSdkBuiltInFontForFontId(unsigned long long value, CGFloat size) {
1819
2091
  static NSCache<NSString *, NSFont *> *cache = nil;
1820
2092
  static dispatch_once_t onceToken;
1821
2093
  dispatch_once(&onceToken, ^{
@@ -1863,6 +2135,19 @@ static NSFont *NativeSdkFontForFontId(unsigned long long value, CGFloat size) {
1863
2135
  return font;
1864
2136
  }
1865
2137
 
2138
+ // Resolves a canvas font id to the NSFont presentation draws with. Both
2139
+ // packet text drawing and native_sdk_appkit_measure_text go through this
2140
+ // resolution order (registered faces win, then the built-in candidates)
2141
+ // so measured layout and drawn glyphs share font resolution —
2142
+ // measure_text inlines the two halves around its width cache because it
2143
+ // must key that cache by the registration-token snapshot the first half
2144
+ // fixes.
2145
+ static NSFont *NativeSdkFontForFontId(unsigned long long value, CGFloat size) {
2146
+ NSFont *registered = NativeSdkRegisteredFontForId(value, size);
2147
+ if (registered) return registered;
2148
+ return NativeSdkBuiltInFontForFontId(value, size);
2149
+ }
2150
+
1866
2151
  static NSFont *NativeSdkPacketPreferredFont(NSDictionary *text, CGFloat size) {
1867
2152
  NSNumber *fontId = [text[@"font"] isKindOfClass:[NSNumber class]] ? text[@"font"] : nil;
1868
2153
  unsigned long long value = fontId ? fontId.unsignedLongLongValue : 1;
@@ -1880,19 +2165,58 @@ double native_sdk_appkit_measure_text(uint64_t font_id, double size, const char
1880
2165
  @autoreleasepool {
1881
2166
  NSString *value = [[NSString alloc] initWithBytes:text length:text_len encoding:NSUTF8StringEncoding];
1882
2167
  if (!value) return -1;
1883
- static NSCache<NSString *, NSNumber *> *widthCache = nil;
1884
- static dispatch_once_t onceToken;
1885
- dispatch_once(&onceToken, ^{
1886
- widthCache = [[NSCache alloc] init];
1887
- widthCache.countLimit = 16384;
1888
- });
1889
- NSString *key = [NSString stringWithFormat:@"%llu/%.3f/%@", (unsigned long long)font_id, (double)clamped, value];
2168
+ NSCache<NSString *, NSNumber *> *widthCache = NativeSdkMeasuredWidthCache();
2169
+ // The key carries the id's registration token so a face
2170
+ // re-registered under the same id (a new runtime in this
2171
+ // process) never serves a previous face's widths — see
2172
+ // NativeSdkRegisteredFontTokens for why token, not eviction,
2173
+ // invalidates this cache. Token and registered face come from
2174
+ // ONE snapshot (one critical section — see
2175
+ // NativeSdkRegisteredFontSnapshot): reading them under separate
2176
+ // acquisitions let a registration land between the reads and
2177
+ // cache the new face's width under the reusable token-0 key,
2178
+ // serving stale registered widths in the unregistered state
2179
+ // after teardown.
2180
+ unsigned long long token = 0;
2181
+ NSFont *registered = NativeSdkRegisteredFontSnapshot((unsigned long long)font_id, clamped, &token);
2182
+ NSString *key = [NSString stringWithFormat:@"%llu/%llu/%.3f/%@", (unsigned long long)font_id, token, (double)clamped, value];
1890
2183
  NSNumber *cached = [widthCache objectForKey:key];
1891
2184
  if (cached) return cached.doubleValue;
1892
- NSFont *font = NativeSdkFontForFontId(font_id, clamped);
2185
+ // A nil snapshot means built-in resolution — with token 0 by the
2186
+ // snapshot's contract unless a live descriptor's CTFont creation
2187
+ // failed, so token 0 only ever keys built-in widths. Shaping
2188
+ // stays OUTSIDE the critical section: a registration or
2189
+ // unregistration landing after the snapshot leaves this width
2190
+ // stale but consistent, and the token recheck below drops the
2191
+ // write instead of caching it.
2192
+ NSFont *font = registered ?: NativeSdkBuiltInFontForFontId(font_id, clamped);
1893
2193
  if (!font) return -1;
1894
2194
  double width = [value sizeWithAttributes:@{ NSFontAttributeName : font }].width;
1895
- [widthCache setObject:@(width) forKey:key];
2195
+ if (token == 0) {
2196
+ // Token 0 is built-in resolution: built-in faces are never
2197
+ // registered, so no unregister can ever clear widths keyed
2198
+ // under it — this write needs no recheck.
2199
+ [widthCache setObject:@(width) forKey:key];
2200
+ return width;
2201
+ }
2202
+ // A registered-token width is cached only after RECHECKING the
2203
+ // token under the guard. Unregister's only possible eviction is
2204
+ // clearing the whole width cache, and shaping ran outside the
2205
+ // critical section: an unconditional write here would land AFTER
2206
+ // that clear whenever the teardown ran inside the shaping window,
2207
+ // repopulating the cleared cache with a retired-token entry — one
2208
+ // no lookup can ever serve (tokens never repeat) but that stays
2209
+ // resident until memory pressure. A mismatch means the
2210
+ // registration was torn down (or replaced) mid-shape — dropping
2211
+ // the write costs one re-measure of a face that is already gone,
2212
+ // and keeps teardown's cleared cache actually clear.
2213
+ NSMutableDictionary<NSNumber *, id> *table = NativeSdkRegisteredFontDescriptors();
2214
+ @synchronized (table) {
2215
+ NSNumber *currentToken = NativeSdkRegisteredFontTokens()[@(font_id)];
2216
+ if (currentToken && currentToken.unsignedLongLongValue == token) {
2217
+ [widthCache setObject:@(width) forKey:key];
2218
+ }
2219
+ }
1896
2220
  return width;
1897
2221
  }
1898
2222
  }
@@ -1907,6 +2231,14 @@ double native_sdk_appkit_measure_text(uint64_t font_id, double size, const char
1907
2231
  // call per text run replaces one measure_text round-trip per cluster of
1908
2232
  // every growing line prefix — the engine caches the batch, so a run is
1909
2233
  // typically shaped here once per content change, not once per frame.
2234
+ //
2235
+ // Unlike measure_text this needs no registration-token snapshot: it
2236
+ // memoizes nothing host-side (the engine caches the batch and
2237
+ // invalidates it by its own measure generation, bumped at every
2238
+ // registration), so each call resolves the font once and uses it
2239
+ // immediately — there is no (token, face) pairing that could tear
2240
+ // across lock acquisitions or outlive the registration it was read
2241
+ // from.
1910
2242
  int native_sdk_appkit_measure_text_advances(uint64_t font_id, double size, const char *text, size_t text_len, float *advances) {
1911
2243
  if (!text || text_len == 0 || !advances) return 0;
1912
2244
  CGFloat clamped = MAX(1, size);
@@ -5530,6 +5862,80 @@ static BOOL NativeSdkCompositeBlurWriteRegion(NSDictionary *command, CGFloat sca
5530
5862
  [self queueScrollInputEvent:event deltaX:-event.scrollingDeltaX deltaY:-event.scrollingDeltaY];
5531
5863
  }
5532
5864
 
5865
+ - (void)magnifyWithEvent:(NSEvent *)event {
5866
+ // Trackpad pinch, phase-explicit. A cancelled gesture folds into
5867
+ // PINCH_END: pinch delivers incremental deltas the app applies as
5868
+ // they arrive, so there is no un-committed transient to roll back
5869
+ // the way pointer_cancel rolls back an in-flight press —
5870
+ // cancellation just means "the delta stream stops here".
5871
+ //
5872
+ // Change deltas emit uncoalesced (no per-frame queue like scroll):
5873
+ // the cumulative gesture scale is the PRODUCT of (1 + delta), and
5874
+ // summing coalesced deltas would drift from what the fingers did.
5875
+ //
5876
+ // HOW TO READ NSEvent.magnification — settled; do not "fix" again.
5877
+ // Apple's documentation contradicts itself: the NSEvent API
5878
+ // reference's prose says to ADD each event's magnification to your
5879
+ // scale factor, while Apple's own Event Handling Guide example
5880
+ // MULTIPLIES (currentSize *= 1 + event.magnification). The de facto
5881
+ // platform behavior is what the browser engines ship, and every
5882
+ // engine reads raw magnification as the MULTIPLICATIVE per-event
5883
+ // delta:
5884
+ // - WebKit, ViewGestureControllerMac.mm:
5885
+ // m_magnification += m_magnification * scaleWithResistance;
5886
+ // i.e. zoom *= 1 + event.magnification, per event.
5887
+ // - Chromium's mac gesture-event builder emits
5888
+ // pinch_update.scale = event.magnification + 1.0;
5889
+ // compounded multiplicatively downstream.
5890
+ // Ruling: raw event.magnification IS the multiplicative per-event
5891
+ // delta. This handler forwards it untransformed (per-event floor
5892
+ // aside — see emitPinchChangeForEvent:), and the app-side product
5893
+ // of (1 + scale) is the zoom users already experience for the same
5894
+ // gesture in Safari and Chrome. Do NOT reintroduce a running-sum
5895
+ // "additive normalization" here: it matches neither Apple's example
5896
+ // nor any engine — a raw +0.25, +0.20 stream must land on
5897
+ // 1.25 * 1.20 = 1.5, where a sum-normalized stream lands on 1.45.
5898
+ //
5899
+ // EVERY magnifyWithEvent: carries the magnification since the
5900
+ // previous event — the terminal (Ended/Cancelled) one included —
5901
+ // so each branch below must forward a nonzero magnification as a
5902
+ // PINCH_CHANGE or the cumulative product diverges from what the
5903
+ // OS delivered.
5904
+ const NSEventPhase phase = event.phase;
5905
+ if (phase & NSEventPhaseBegan) {
5906
+ [self emitQueuedPointerMotionInputEvent];
5907
+ self.pinchGestureActive = YES;
5908
+ [self emitPinchInputEventWithKind:NATIVE_SDK_APPKIT_GPU_INPUT_PINCH_BEGIN event:event magnification:0];
5909
+ [self emitPinchChangeForEvent:event];
5910
+ return;
5911
+ }
5912
+ if (phase & NSEventPhaseChanged) {
5913
+ if (!self.pinchGestureActive) {
5914
+ // A gesture already in flight when this view became the
5915
+ // hit target skips Began; open the stream cleanly anyway.
5916
+ self.pinchGestureActive = YES;
5917
+ [self emitPinchInputEventWithKind:NATIVE_SDK_APPKIT_GPU_INPUT_PINCH_BEGIN event:event magnification:0];
5918
+ }
5919
+ [self emitPinchChangeForEvent:event];
5920
+ return;
5921
+ }
5922
+ if (phase & (NSEventPhaseEnded | NSEventPhaseCancelled)) {
5923
+ if (!self.pinchGestureActive) return;
5924
+ self.pinchGestureActive = NO;
5925
+ // The terminal event's nonzero magnification emits as a final
5926
+ // PINCH_CHANGE before the end marker (a zero-magnification
5927
+ // terminal event emits only PINCH_END). Cancelled takes the
5928
+ // same path deliberately: our model applies deltas
5929
+ // incrementally with no rollback (see above), so the honest
5930
+ // stream reports every delta the OS measured, then says the
5931
+ // gesture is over.
5932
+ [self emitPinchChangeForEvent:event];
5933
+ [self emitPinchInputEventWithKind:NATIVE_SDK_APPKIT_GPU_INPUT_PINCH_END event:event magnification:0];
5934
+ return;
5935
+ }
5936
+ // NSEventPhaseMayBegin / stationary phases carry no gesture fact.
5937
+ }
5938
+
5533
5939
  - (void)keyDown:(NSEvent *)event {
5534
5940
  if ([self focusedTextAccessibilityElement]) {
5535
5941
  self.interpretedKeyEventEmittedInput = NO;
@@ -5710,6 +6116,59 @@ static BOOL NativeSdkCompositeBlurWriteRegion(NSDictionary *command, CGFloat sca
5710
6116
  deltaY:deltaY];
5711
6117
  }
5712
6118
 
6119
+ // --- Pinch change forwarding ---------------------------------------------
6120
+ // Raw event.magnification IS the wire's multiplicative per-event delta
6121
+ // (see the doctrine note at magnifyWithEvent:); it forwards untransformed.
6122
+ // One guard stands between the OS and the wire: a single event whose
6123
+ // magnification is at or below -1 would put a factor (1 + delta) <= 0 on
6124
+ // the wire — a zoom inverting through zero scale, which no physical pinch
6125
+ // can perform (only a driver/toolkit glitch could report it), and which
6126
+ // downstream products cannot recover from. Clamp PER EVENT to a floor
6127
+ // just above -1; the epsilon is 2^-10 (~0.001, exactly representable in
6128
+ // f32 and f64), so a glitched event's factor bottoms out at 2^-10 and
6129
+ // every emitted factor stays > 0.
6130
+ static const double NativeSdkPinchMagnificationFloor = -1.0 + 0x1p-10;
6131
+
6132
+ static double NativeSdkClampedPinchMagnification(double magnification) {
6133
+ return magnification < NativeSdkPinchMagnificationFloor ? NativeSdkPinchMagnificationFloor : magnification;
6134
+ }
6135
+
6136
+ // Forward one magnify event's raw magnification as a PINCH_CHANGE
6137
+ // (nothing to emit when the event measured no magnification).
6138
+ - (void)emitPinchChangeForEvent:(NSEvent *)event {
6139
+ const double magnification = NativeSdkClampedPinchMagnification(event.magnification);
6140
+ if (magnification == 0) return;
6141
+ [self emitPinchInputEventWithKind:NATIVE_SDK_APPKIT_GPU_INPUT_PINCH_CHANGE event:event magnification:magnification];
6142
+ }
6143
+
6144
+ // Pinch input: the shared input-emit shape (converted point, top-left
6145
+ // origin flip, host timestamp, modifier flags) with the magnification
6146
+ // delta riding the event's `scale` field — unused (zero) on every other
6147
+ // input kind, so the runtime reads it unconditionally. The x/y point is
6148
+ // the POINTER anchor: AppKit reports gesture events at locationInWindow
6149
+ // (the pointer location), never a midpoint between the fingers — NSTouch
6150
+ // positions are trackpad-normalized and have no view-space meaning, and
6151
+ // zoom-at-cursor is the anchoring apps want.
6152
+ - (void)emitPinchInputEventWithKind:(NSInteger)kind event:(NSEvent *)event magnification:(double)magnification {
6153
+ if (!self.host || self.surfaceLabel.length == 0 || !event) return;
6154
+ NSPoint point = [self convertPoint:event.locationInWindow fromView:nil];
6155
+ CGFloat y = self.bounds.size.height - point.y;
6156
+ const char *labelBytes = self.surfaceLabel.UTF8String ?: "";
6157
+ [self.host emitEvent:(native_sdk_appkit_event_t){
6158
+ .kind = NATIVE_SDK_APPKIT_EVENT_GPU_SURFACE_INPUT,
6159
+ .window_id = self.windowId,
6160
+ .timestamp_ns = NativeSdkTimestampNanoseconds(),
6161
+ .x = point.x,
6162
+ .y = y,
6163
+ .scale = magnification,
6164
+ .view_label = labelBytes,
6165
+ .view_label_len = [self.surfaceLabel lengthOfBytesUsingEncoding:NSUTF8StringEncoding],
6166
+ .shortcut_modifiers = NativeSdkModifierFlagsForEvent(event),
6167
+ .input_kind = (int)kind,
6168
+ }];
6169
+ [self requestRetainedCanvasFrame];
6170
+ }
6171
+
5713
6172
  // --- Native scroll drivers ---------------------------------------------
5714
6173
  // Each scrollable canvas region gets an invisible NSScrollView subview
5715
6174
  // sized to the region and backed by a flipped document view sized to the
@@ -6277,6 +6736,8 @@ static BOOL NativeSdkCompositeBlurWriteRegion(NSDictionary *command, CGFloat sca
6277
6736
  self.windowLabels = [[NSMutableDictionary alloc] init];
6278
6737
  self.deferredShowWindows = [[NSMutableDictionary alloc] init];
6279
6738
  self.windowClearColors = [[NSMutableDictionary alloc] init];
6739
+ self.windowClosePolicies = [[NSMutableDictionary alloc] init];
6740
+ self.policyHiddenWindows = [[NSMutableSet alloc] init];
6280
6741
  self.childWebViews = [[NSMutableDictionary alloc] init];
6281
6742
  self.nativeViews = [[NSMutableDictionary alloc] init];
6282
6743
  self.adoptedViewSurfaces = [[NSMutableDictionary alloc] init];
@@ -6294,6 +6755,7 @@ static BOOL NativeSdkCompositeBlurWriteRegion(NSDictionary *command, CGFloat sca
6294
6755
 
6295
6756
  [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];
6296
6757
  self.didShutdown = NO;
6758
+ self.pendingPreRunStop = NO;
6297
6759
  self.observesApplicationActivation = NO;
6298
6760
 
6299
6761
  return self;
@@ -6503,6 +6965,14 @@ static BOOL NativeSdkCompositeBlurWriteRegion(NSDictionary *command, CGFloat sca
6503
6965
  - (void)closeWindowWithId:(uint64_t)windowId {
6504
6966
  NSWindow *window = self.windows[@(windowId)];
6505
6967
  if (!window) return;
6968
+ // A runtime-initiated close is the app DECIDING to close: it must
6969
+ // not bounce off the window's own .hide close policy, so it skips
6970
+ // performClose: (which runs windowShouldClose:) and closes
6971
+ // directly — the full windowWillClose teardown still runs.
6972
+ if ([self.windowClosePolicies[@(windowId)] intValue] == 1) {
6973
+ [window close];
6974
+ return;
6975
+ }
6506
6976
  // performClose: simulates the titlebar close button, which a
6507
6977
  // chromeless (borderless) window does not have — AppKit just beeps.
6508
6978
  // Closing directly runs the same delegate teardown
@@ -6514,6 +6984,50 @@ static BOOL NativeSdkCompositeBlurWriteRegion(NSDictionary *command, CGFloat sca
6514
6984
  [window performClose:nil];
6515
6985
  }
6516
6986
 
6987
+ // close_policy .hide, the hiding half: order the window out (it keeps
6988
+ // its views, its webviews, and its host records — nothing tears down),
6989
+ // remember it as policy-hidden, and report the state on the frame
6990
+ // channel so the runtime's window table and the session journal both
6991
+ // carry the truth. orderOut composes with the host's bookkeeping where
6992
+ // close would not: the windows dictionary still owns the window, so
6993
+ // the count never reaches zero and no shutdown emits.
6994
+ - (void)hideWindowWithId:(uint64_t)windowId {
6995
+ NSWindow *window = self.windows[@(windowId)];
6996
+ if (!window) return;
6997
+ [self.policyHiddenWindows addObject:@(windowId)];
6998
+ [window orderOut:nil];
6999
+ [self emitWindowFrameForWindowId:windowId open:YES];
7000
+ }
7001
+
7002
+ // The counterpart show verb: bring a hidden (or merely unfocused)
7003
+ // window back to the glass and activate the app — the tray-menu
7004
+ // "Open" consequence and the Dock reopen both land here. Also clears a
7005
+ // pending present-before-show defer and a minimize, for the same
7006
+ // reason focusWindowWithId: does: the runtime asked for the window NOW.
7007
+ - (void)showWindowWithId:(uint64_t)windowId {
7008
+ NSWindow *window = self.windows[@(windowId)];
7009
+ if (!window) return;
7010
+ [self.policyHiddenWindows removeObject:@(windowId)];
7011
+ [self.deferredShowWindows removeObjectForKey:@(windowId)];
7012
+ if (window.miniaturized) [window deminiaturize:nil];
7013
+ [window makeKeyAndOrderFront:nil];
7014
+ [NSApp activate];
7015
+ [self emitWindowFrameForWindowId:windowId open:YES];
7016
+ [self scheduleFrame];
7017
+ }
7018
+
7019
+ // The Dock-icon reopen consequence: with no window visible, re-show
7020
+ // every window the .hide close policy hid. Returns whether any window
7021
+ // was re-shown (the app delegate then suppresses AppKit's default
7022
+ // reopen handling for exactly that case).
7023
+ - (BOOL)reopenPolicyHiddenWindows {
7024
+ if (self.policyHiddenWindows.count == 0) return NO;
7025
+ for (NSNumber *key in [self.policyHiddenWindows copy]) {
7026
+ [self showWindowWithId:key.unsignedLongLongValue];
7027
+ }
7028
+ return YES;
7029
+ }
7030
+
6517
7031
  // The real OS minimize verb, for app-drawn window controls (chromeless
6518
7032
  // windows have no traffic lights to click): the window genies into the
6519
7033
  // Dock exactly like the yellow button. miniaturize: is used over
@@ -8095,6 +8609,16 @@ static void NativeSdkApplyProcessDisplayName(NSString *displayName) {
8095
8609
  self.callback = callback;
8096
8610
  self.context = context;
8097
8611
 
8612
+ // The Dock-reopen delegate (close_policy .hide's re-show path).
8613
+ // NSApp.delegate is free in this host — everything else rides
8614
+ // notification observers — and NSApp does not retain it.
8615
+ if (!NSApp.delegate) {
8616
+ NativeSdkAppDelegate *reopenDelegate = [[NativeSdkAppDelegate alloc] init];
8617
+ reopenDelegate.host = self;
8618
+ self.reopenDelegate = reopenDelegate;
8619
+ NSApp.delegate = reopenDelegate;
8620
+ }
8621
+
8098
8622
  // Present-before-show: a deferred startup window stays ordered out
8099
8623
  // here and appears when its first canvas present lands (or the
8100
8624
  // create-time fallback deadline fires).
@@ -8120,9 +8644,20 @@ static void NativeSdkApplyProcessDisplayName(NSString *displayName) {
8120
8644
  [self startAppearanceObservers];
8121
8645
 
8122
8646
  [self emitEvent:(native_sdk_appkit_event_t){ .kind = NATIVE_SDK_APPKIT_EVENT_START }];
8647
+ // A VALID quit can arrive during the START dispatch (an update that
8648
+ // returns fx.quitApp() at boot). Pre-run there is no queue turn to
8649
+ // defer it to, so native_sdk_appkit_request_stop parked it — and
8650
+ // THIS is its drain point: emitShutdown + stop run at top level,
8651
+ // after the START dispatch has committed to the session recorder,
8652
+ // never nested inside it (a nested emit seals the journal before
8653
+ // the start record commits and replay refuses the recording).
8654
+ [self drainPendingPreRunStop];
8123
8655
  // A failed START handler requests shutdown synchronously, before the
8124
8656
  // run loop exists — [NSApp stop:] is a no-op there. Honor the request
8125
- // here instead of stranding a live app behind a blank window.
8657
+ // here instead of stranding a live app behind a blank window. (That
8658
+ // request is the HOST side's native_sdk_appkit_stop, which keeps its
8659
+ // inline pre-run emit — distinct from the quit verb's pending flag
8660
+ // drained above.)
8126
8661
  if (self.didShutdown) return;
8127
8662
  [self emitAppearanceChanged];
8128
8663
  [self emitResize];
@@ -8139,6 +8674,14 @@ static void NativeSdkApplyProcessDisplayName(NSString *displayName) {
8139
8674
  }
8140
8675
  }
8141
8676
 
8677
+ // The appearance/resize/window-frame emits and the synchronous
8678
+ // first canvas frame above are pre-run dispatches too — a boot
8679
+ // command's update (a TS core's first-frame command included) can
8680
+ // return the quit verb during any of them. Drain the parked quit
8681
+ // here at top level before the run-loop machinery arms; when it
8682
+ // drains, the app never enters [NSApp run].
8683
+ if ([self drainPendingPreRunStop]) return;
8684
+
8142
8685
  // Terminations that bypass the host's own stop path — cmd+Q's
8143
8686
  // default NSApp terminate, an AppleScript quit — must still deliver
8144
8687
  // the shutdown event synchronously before the process exits: the
@@ -8201,6 +8744,22 @@ static void NativeSdkApplyProcessDisplayName(NSString *displayName) {
8201
8744
  [NSApp postEvent:event atStart:NO];
8202
8745
  }
8203
8746
 
8747
+ /* Drain the quit verb a pre-run dispatch parked (see
8748
+ * native_sdk_appkit_request_stop): emitShutdown + stop at TOP LEVEL,
8749
+ * strictly after the requesting dispatch returned, so the session
8750
+ * recorder commits the requesting event before the shutdown record
8751
+ * seals the journal. Answers YES only when it drained; a request that
8752
+ * raced an already-emitted shutdown (a failed emit's inline stop) is
8753
+ * consumed without a second emit. */
8754
+ - (BOOL)drainPendingPreRunStop {
8755
+ if (!self.pendingPreRunStop) return NO;
8756
+ self.pendingPreRunStop = NO;
8757
+ if (self.didShutdown) return NO;
8758
+ [self emitShutdown];
8759
+ [self stop];
8760
+ return YES;
8761
+ }
8762
+
8204
8763
  - (void)emitEvent:(native_sdk_appkit_event_t)event {
8205
8764
  if (self.callback) {
8206
8765
  self.callback(self.context, &event);
@@ -8347,6 +8906,10 @@ static void NativeSdkApplyProcessDisplayName(NSString *displayName) {
8347
8906
  .scale = window.backingScaleFactor,
8348
8907
  .open = open ? 1 : 0,
8349
8908
  .focused = window.isKeyWindow ? 1 : 0,
8909
+ // The hidden flag reports host truth, not a parameter: every
8910
+ // frame emit while a window sits in the policy-hidden set
8911
+ // carries it, and hide/show flip the set before they emit.
8912
+ .hidden = [self.policyHiddenWindows containsObject:@(windowId)] ? 1 : 0,
8350
8913
  .label = label.UTF8String,
8351
8914
  .label_len = [label lengthOfBytesUsingEncoding:NSUTF8StringEncoding],
8352
8915
  }];
@@ -9765,8 +10328,58 @@ void native_sdk_appkit_wake(native_sdk_appkit_host_t *host) {
9765
10328
 
9766
10329
  void native_sdk_appkit_stop(native_sdk_appkit_host_t *host) {
9767
10330
  NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
9768
- [object emitShutdown];
9769
- [object stop];
10331
+ /* The HOST side's shutdown request — a failed event emit asks for
10332
+ * the teardown (see RunState.emit's catch in macos/root.zig). Not
10333
+ * the quit verb's landing point: that is
10334
+ * native_sdk_appkit_request_stop below. Queued while the run loop
10335
+ * is live, so the emit lands on the next turn at top level; [NSApp
10336
+ * run] drains the main queue and stop's posted wake event unwinds
10337
+ * it, so a stop that is the last thing an app ever does still
10338
+ * exits promptly. */
10339
+ if (!NSApp.running) {
10340
+ /* Before [NSApp run] there is no loop to drain the queue — a
10341
+ * failed START handler requests shutdown synchronously (see
10342
+ * runWithCallback's didShutdown check) and must keep getting
10343
+ * the inline emit, or the request would strand until a run
10344
+ * loop that may never start. */
10345
+ [object emitShutdown];
10346
+ [object stop];
10347
+ return;
10348
+ }
10349
+ dispatch_async(dispatch_get_main_queue(), ^{
10350
+ [object emitShutdown];
10351
+ [object stop];
10352
+ });
10353
+ }
10354
+
10355
+ void native_sdk_appkit_request_stop(native_sdk_appkit_host_t *host) {
10356
+ NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
10357
+ /* The quit VERB's landing point (fx.quitApp). The verb arrives MID
10358
+ * DISPATCH — some update returned it, so the runtime is still
10359
+ * inside that event's dispatch. Emitting SHUTDOWN here would nest
10360
+ * the shutdown dispatch inside the requester's: the session
10361
+ * recorder commits nested events innermost-first and seals the
10362
+ * journal on shutdown, so the nested seal makes the OUTER commit a
10363
+ * no-op and the journal loses the very event (and model mutation)
10364
+ * that quit the app — replay diverges. While the run loop is live,
10365
+ * one main-queue hop delivers the identical emitShutdown + stop on
10366
+ * the next loop turn, after the requesting dispatch has committed.
10367
+ * Before [NSApp run] there is no queue turn that would drain in
10368
+ * time — a quit from App.start's update, or from a boot command
10369
+ * during the synchronous first canvas frame, must NOT fall back to
10370
+ * an inline emit (the same nesting bug, just pre-run) — so the
10371
+ * request parks in pendingPreRunStop and runWithCallback drains it
10372
+ * at top level once the pre-run dispatch that carried it returns.
10373
+ * (The inline pre-run emit lives only in native_sdk_appkit_stop
10374
+ * above, for the host-side failed-START request.) */
10375
+ if (!NSApp.running) {
10376
+ object.pendingPreRunStop = YES;
10377
+ return;
10378
+ }
10379
+ dispatch_async(dispatch_get_main_queue(), ^{
10380
+ [object emitShutdown];
10381
+ [object stop];
10382
+ });
9770
10383
  }
9771
10384
 
9772
10385
  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) {
@@ -9876,6 +10489,22 @@ int native_sdk_appkit_minimize_window(native_sdk_appkit_host_t *host, uint64_t w
9876
10489
  return 1;
9877
10490
  }
9878
10491
 
10492
+ int native_sdk_appkit_show_window(native_sdk_appkit_host_t *host, uint64_t window_id) {
10493
+ NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
10494
+ if (!object.windows[@(window_id)]) return 0;
10495
+ [object showWindowWithId:window_id];
10496
+ return 1;
10497
+ }
10498
+
10499
+ int native_sdk_appkit_set_window_close_policy(native_sdk_appkit_host_t *host, uint64_t window_id, int close_policy) {
10500
+ NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
10501
+ if (!object.windows[@(window_id)]) return 0;
10502
+ // Applied right after create, like the content min-size floor —
10503
+ // close handling is host window state fixed for the window's life.
10504
+ object.windowClosePolicies[@(window_id)] = @(close_policy);
10505
+ return 1;
10506
+ }
10507
+
9879
10508
  int native_sdk_appkit_start_window_drag(native_sdk_appkit_host_t *host, uint64_t window_id) {
9880
10509
  NativeSdkAppKitHost *object = (__bridge NativeSdkAppKitHost *)host;
9881
10510
  return [object startWindowDragWithId:window_id] ? 1 : 0;