@windowkit/appkit 0.10.0 → 0.12.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.
package/README.md CHANGED
@@ -125,7 +125,7 @@ waits on the UI thread (`test/threaded-verbs.js` covers each row):
125
125
 
126
126
  | from a worker | verbs |
127
127
  | --- | --- |
128
- | unchanged, on the calling thread | surfaces, every `ctx*`, layouts and fonts, `pasteboardTypeForMIME`, `pasteboardTypeInfo`, `contentTypeFor`, `colorSpace` |
128
+ | unchanged, on the calling thread | surfaces, every `ctx*` (`ctxDrawSymbol` included), layouts and fonts, `symbolSize`, `pasteboardTypeForMIME`, `pasteboardTypeInfo`, `contentTypeFor`, `colorSpace` |
129
129
  | a command, answering nothing | `initApp`, `setActivationPolicy`, `setAppName`, `activateApp`, `showWindow`, `hideWindow`, `setWindowFrame`, `setWindowTitle`, `setWindowMinMax`, `setWindowIgnoresMouseEvents`, `invalidateWindowShadow`, `destroyWindow2`, `setCursor`, `setMainMenu`, `setDockMenu`, `setDockBadge`, `cancelUserAttention`, `setStatusItem`, `setStatusItemMenu`, `removeStatusItem`, `registerDropTypes`, `setDropResponse`, `pasteboardWriteText`, `pasteboardClear`, `cancelPanel`; the test posts `postMouseEvent`, `postKeyEvent`, `postAppleEvent`, `postAccessibilityDisplayChange` |
130
130
  | a handle at the call | `createWindow2`, followed by `window-created { handle, windowNumber }`; every event about the window, input included, carries `handle`, so `ev.handle === win` |
131
131
  | | `windowRootLayer`, allocated with the window |
@@ -493,6 +493,72 @@ native.ctxDrawSurface(win, grid, 0, 0, 2000, 1620, 40, 30, 2000, 1620);
493
493
  native.ctxSetBlendMode(win, 'source-over');
494
494
  ```
495
495
 
496
+ ## Text: letter spacing and OpenType features
497
+
498
+ The text verbs a renderer lays paragraphs out and shapes glyph runs with —
499
+ `matchFont`, `createLayout`, `fontShapeText` — take the two adjustments a designed
500
+ interface reaches for past the face and the size:
501
+
502
+ - **`native.fontApplyFeatures(font, features)`** — the font with OpenType features set by
503
+ tag, the sibling of `fontApplyVariations`. An array turns each tag on (`['tnum']`); an
504
+ object sets each tag to its value, `true`/`false` or a number for a feature that selects
505
+ among alternates (`{ tnum: true, liga: false, salt: 2 }`). The settings replace any the
506
+ font carries, and with nothing to set the font itself comes back, so it can be applied
507
+ unconditionally. `tnum` is the one a live readout wants: the system face's digits are
508
+ proportional, and a number that changes while a slider moves reflows with every value.
509
+ - **`letterSpacing`**, in points: a `createLayout` span option, and a third-argument option
510
+ to `fontShapeText` — `{ letterSpacing }` — so a paragraph and a run shaped alone agree.
511
+ It is added after every character, the last on a line included, which is what
512
+ `kCTKernAttributeName` does and what CSS's `letter-spacing` long did; negative values
513
+ tighten. It says nothing about ligatures: a caller that wants CSS's rule turns the
514
+ optional ones off through `fontApplyFeatures` on a spaced span.
515
+
516
+ ```js
517
+ const face = native.matchFont({ families: ['system-ui'], size: 30 });
518
+ const small = native.matchFont({ families: ['system-ui'], size: 11, weight: 600 });
519
+ const readout = native.createLayout({
520
+ spans: [{ text: '487 Hz', font: native.fontApplyFeatures(face, ['tnum']) }],
521
+ });
522
+ const label = native.createLayout({
523
+ spans: [{ text: 'NOISE TYPE', font: small, letterSpacing: 1.26 }],
524
+ });
525
+ ```
526
+
527
+ ## SF Symbols in a surface
528
+
529
+ The system's icons by name — what `createStatusItem`'s `image` and a menu item's `iconName`
530
+ already take — drawn into a surface, for a renderer's own content:
531
+
532
+ - **`native.ctxDrawSymbol(surface, name, x, y, width, height, options?)`** — the symbol fitted
533
+ into the rect, centred and keeping its proportions, in the **current fill colour**. A symbol
534
+ is a template, its shape in whatever colour it is drawn with, so it is drawn the way
535
+ `ctxDrawGlyphs` draws a run: through the surface's CTM and clip, at its global alpha and
536
+ blend mode, over what is already there. Answers `false`, drawing nothing, for a name the
537
+ catalogue does not know — a name from another platform's icon theme simply misses.
538
+ - **`native.symbolSize(name, options?)`** — `{ width, height }` in points, the padding the
539
+ symbol is designed with included, or `null` for an unknown name: the box a symbol sits in
540
+ beside text of the same point size.
541
+
542
+ | option | |
543
+ | --------------- | ----------------------------------------------------------------------------- |
544
+ | `pointSize` | the size it is designed for, default 13 — the size of the text beside it |
545
+ | `weight` | 100-900, default 400: the nearest of AppKit's weights, as `matchFont` maps it |
546
+ | `scale` | `'small'`, `'medium'` (default) or `'large'`, relative to the point size |
547
+ | `variableValue` | 0-1, how much of a variable symbol shows — macOS 13 and later, ignored before |
548
+
549
+ Both run on the calling thread in threaded mode too, and draw the same pixels there.
550
+
551
+ ```js
552
+ const s = native.createSurface(96, 96, 2);
553
+ native.ctxSetFillColor(s, 0.2, 0.4, 0.8, 1);
554
+ const { width, height } = native.symbolSize('speaker.wave.3.fill', { pointSize: 20 });
555
+ native.ctxDrawSymbol(s, 'speaker.wave.3.fill', 8, 8, width * 2, height * 2, {
556
+ pointSize: 20,
557
+ weight: 600,
558
+ variableValue: 0.66,
559
+ });
560
+ ```
561
+
496
562
  ## App lifecycle: open-URL, open-file, reopen, quit
497
563
 
498
564
  The OS talks to the application as a whole through Apple Events: a URL for a scheme
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@windowkit/appkit",
3
- "version": "0.10.0",
3
+ "version": "0.12.0",
4
4
  "description": "Retained-mode AppKit backend for Node.js: Core Animation (CALayer) layer trees, CoreText layout and drawing, IOSurface presentation, NSMenu, and native control bezels — the macOS half of react-x11.",
5
5
  "author": "Andrey Sidorov <andrey.sidorov@gmail.com>",
6
6
  "license": "MIT",
@@ -43,7 +43,7 @@
43
43
  "install": "node scripts/install.js",
44
44
  "build": "node-gyp rebuild",
45
45
  "demo": "node demo/demo.js",
46
- "test": "node test/app-lifecycle.js && node test/animation.js && node test/accessibility-display.js && node test/ignores-mouse-events.js && node test/surface-blit.js && node test/eventkit-permissions.js && node test/calendars.js && node test/calendar-writes.js && node test/screencolor.js && node test/threaded.js && node test/threaded-verbs.js && node test/threaded-frames.js && node test/threaded-resize.js && node test/ending-worker.js && node test/live-resize.js && node test/activation-policy.js"
46
+ "test": "node test/app-lifecycle.js && node test/animation.js && node test/accessibility-display.js && node test/ignores-mouse-events.js && node test/surface-blit.js && node test/text-features.js && node test/symbols.js && node test/eventkit-permissions.js && node test/calendars.js && node test/calendar-writes.js && node test/screencolor.js && node test/threaded.js && node test/threaded-verbs.js && node test/threaded-frames.js && node test/threaded-resize.js && node test/ending-worker.js && node test/live-resize.js && node test/activation-policy.js"
47
47
  },
48
48
  "dependencies": {
49
49
  "node-addon-api": "^8.3.0"
Binary file
package/src/backend.mm CHANGED
@@ -3120,7 +3120,7 @@ static Napi::Value AppInfoFn(const Napi::CallbackInfo& info) {
3120
3120
  napi_env env_;
3121
3121
  Napi::FunctionReference cb_;
3122
3122
  bool threaded_;
3123
- Napi::ThreadSafeFunction tsfn_;
3123
+ CALTsfn tsfn_;
3124
3124
  bool open_; // NSOpenPanel answers paths[], NSSavePanel answers a path
3125
3125
  bool modal_; // app-modal (runModal) rather than a sheet
3126
3126
  }
@@ -3310,7 +3310,7 @@ static Napi::Value PresentPanel(const Napi::CallbackInfo& info, bool open) {
3310
3310
  // answer through a threadsafe function in this environment.
3311
3311
  CALHandle* h = CALNewHandle();
3312
3312
  Napi::Value handle = CALWrapHandle(env, h, false);
3313
- Napi::ThreadSafeFunction tsfn = CALReplyTo(
3313
+ CALTsfn tsfn = CALReplyTo(
3314
3314
  env, info[1].As<Napi::Function>(), open ? "appkit:openPanel" : "appkit:savePanel");
3315
3315
  dispatch_block_t present = ^{
3316
3316
  BEnsureApp();
@@ -4196,19 +4196,24 @@ static Napi::Value ScrollSurface(const Napi::CallbackInfo& info) {
4196
4196
  // fonts + text layout (CoreText)
4197
4197
  // ---------------------------------------------------------------------------
4198
4198
 
4199
+ // A CSS weight, 100-900, as the nearest of AppKit's named weights — what a
4200
+ // face and an SF Symbol are both configured with.
4201
+ static NSFontWeight FontWeightFromCss(double weight) {
4202
+ if (weight <= 150) return NSFontWeightUltraLight;
4203
+ if (weight <= 250) return NSFontWeightThin;
4204
+ if (weight <= 350) return NSFontWeightLight;
4205
+ if (weight <= 450) return NSFontWeightRegular;
4206
+ if (weight <= 550) return NSFontWeightMedium;
4207
+ if (weight <= 650) return NSFontWeightSemibold;
4208
+ if (weight <= 750) return NSFontWeightBold;
4209
+ if (weight <= 850) return NSFontWeightHeavy;
4210
+ return NSFontWeightBlack;
4211
+ }
4212
+
4199
4213
  // matchFont({ families: [..], size, weight (100-900), italic }) -> font handle
4200
4214
  static NSFont* ResolveFamily(NSString* family, double size, double weight,
4201
4215
  bool italic) {
4202
- NSFontWeight w = NSFontWeightRegular;
4203
- if (weight <= 150) w = NSFontWeightUltraLight;
4204
- else if (weight <= 250) w = NSFontWeightThin;
4205
- else if (weight <= 350) w = NSFontWeightLight;
4206
- else if (weight <= 450) w = NSFontWeightRegular;
4207
- else if (weight <= 550) w = NSFontWeightMedium;
4208
- else if (weight <= 650) w = NSFontWeightSemibold;
4209
- else if (weight <= 750) w = NSFontWeightBold;
4210
- else if (weight <= 850) w = NSFontWeightHeavy;
4211
- else w = NSFontWeightBlack;
4216
+ NSFontWeight w = FontWeightFromCss(weight);
4212
4217
 
4213
4218
  NSFont* font = nil;
4214
4219
  NSString* lower = family.lowercaseString;
@@ -4601,7 +4606,7 @@ static Napi::Value FontWithSize(const Napi::CallbackInfo& info) {
4601
4606
  });
4602
4607
  }
4603
4608
 
4604
- // fontShapeText(font, text)
4609
+ // fontShapeText(font, text, { letterSpacing }?)
4605
4610
  // -> { width, runs: [{ font: handle | null, glyphs: Uint16Array,
4606
4611
  // positions: Float64Array x0,y0,x1,y1,…,
4607
4612
  // advances: Float64Array }] }
@@ -4615,7 +4620,9 @@ static Napi::Value FontWithSize(const Napi::CallbackInfo& info) {
4615
4620
  // right. The typesetter's whole answer for a cluster — a base with its
4616
4621
  // marks positioned, an emoji sequence joined, a variation selector honoured
4617
4622
  // — as ids a caller can hand to ctxDrawGlyphs beside the ids it looked up
4618
- // itself; nothing here decides where a cluster goes.
4623
+ // itself; nothing here decides where a cluster goes. `letterSpacing` is
4624
+ // the points added after every character, as createLayout's span option
4625
+ // adds them, so a run shaped here and a paragraph laid out there agree.
4619
4626
  static Napi::Value FontShapeText(const Napi::CallbackInfo& info) {
4620
4627
  Napi::Env env = info.Env();
4621
4628
  if (!BCheckFontArg(info, "fontShapeText")) return env.Undefined();
@@ -4624,9 +4631,15 @@ static Napi::Value FontShapeText(const Napi::CallbackInfo& info) {
4624
4631
  Napi::Object out = Napi::Object::New(env);
4625
4632
  Napi::Array runsOut = Napi::Array::New(env);
4626
4633
  double width = 0;
4634
+ double spacing = info.Length() > 2 && info[2].IsObject()
4635
+ ? BNumOr(info[2].As<Napi::Object>(), "letterSpacing", 0)
4636
+ : 0;
4627
4637
  if (text.length > 0) {
4628
- NSDictionary* attrs =
4629
- @{(__bridge id)kCTFontAttributeName : (__bridge id)font};
4638
+ NSMutableDictionary* attrs = [NSMutableDictionary dictionary];
4639
+ attrs[(__bridge id)kCTFontAttributeName] = (__bridge id)font;
4640
+ if (spacing != 0 && std::isfinite(spacing)) {
4641
+ attrs[(__bridge id)kCTKernAttributeName] = @(spacing);
4642
+ }
4630
4643
  NSAttributedString* as =
4631
4644
  [[NSAttributedString alloc] initWithString:text attributes:attrs];
4632
4645
  CTLineRef line =
@@ -4803,6 +4816,57 @@ static Napi::Value FontApplyVariations(const Napi::CallbackInfo& info) {
4803
4816
  });
4804
4817
  }
4805
4818
 
4819
+ // fontApplyFeatures(font, ['tnum'] | { tnum: true, liga: false, salt: 2 })
4820
+ // -> CTFont
4821
+ // OpenType features by tag (kCTFontOpenTypeFeatureTag, macOS 10.13): an
4822
+ // array turns each tag on, an object sets each tag to its value — true or
4823
+ // false, or a number for a feature that selects among alternates. The
4824
+ // settings replace any the font already carries, the way a style names its
4825
+ // features whole. Answers the font it was given when there is nothing to
4826
+ // set, so a caller can apply it unconditionally.
4827
+ static Napi::Value FontApplyFeatures(const Napi::CallbackInfo& info) {
4828
+ Napi::Env env = info.Env();
4829
+ if (!BCheckFontArg(info, "fontApplyFeatures")) return env.Undefined();
4830
+ CTFontRef base = BFontFrom(info[0]);
4831
+ NSMutableArray* settings = [NSMutableArray array];
4832
+ auto add = [&](const std::string& tag, long value) {
4833
+ if (tag.size() != 4) return;
4834
+ [settings addObject:@{
4835
+ (__bridge id)kCTFontOpenTypeFeatureTag :
4836
+ [NSString stringWithUTF8String:tag.c_str()],
4837
+ (__bridge id)kCTFontOpenTypeFeatureValue : @(value),
4838
+ }];
4839
+ };
4840
+ if (info.Length() > 1 && info[1].IsArray()) {
4841
+ Napi::Array tags = info[1].As<Napi::Array>();
4842
+ for (uint32_t i = 0; i < tags.Length(); i++) {
4843
+ if (tags.Get(i).IsString()) {
4844
+ add(tags.Get(i).As<Napi::String>().Utf8Value(), 1);
4845
+ }
4846
+ }
4847
+ } else if (info.Length() > 1 && info[1].IsObject()) {
4848
+ Napi::Object o = info[1].As<Napi::Object>();
4849
+ Napi::Array names = o.GetPropertyNames();
4850
+ for (uint32_t i = 0; i < names.Length(); i++) {
4851
+ std::string tag = names.Get(i).As<Napi::String>().Utf8Value();
4852
+ Napi::Value v = o.Get(tag.c_str());
4853
+ if (v.IsBoolean()) add(tag, v.As<Napi::Boolean>().Value() ? 1 : 0);
4854
+ else if (v.IsNumber()) add(tag, (long)v.As<Napi::Number>().Int64Value());
4855
+ }
4856
+ }
4857
+ if (settings.count == 0) return info[0];
4858
+ CTFontDescriptorRef d = CTFontDescriptorCreateWithAttributes(
4859
+ (__bridge CFDictionaryRef)
4860
+ @{(__bridge id)kCTFontFeatureSettingsAttribute : settings});
4861
+ CTFontRef ct =
4862
+ CTFontCreateCopyWithAttributes(base, CTFontGetSize(base), NULL, d);
4863
+ CFRelease(d);
4864
+ if (!ct) return info[0];
4865
+ return Napi::External<void>::New(env, (void*)ct, [](Napi::Env, void* d2) {
4866
+ CFRelease(d2);
4867
+ });
4868
+ }
4869
+
4806
4870
  // listFonts({ family? , limit? }) -> [{ postScriptName, familyName,
4807
4871
  // styleName, path }]. With a family: that family's faces, in CoreText's
4808
4872
  // matching order. Without: every installed face (bounded by limit).
@@ -4951,6 +5015,12 @@ static Napi::Value CreateLayout(const Napi::CallbackInfo& info) {
4951
5015
  NSMutableDictionary* attrs = [NSMutableDictionary dictionary];
4952
5016
  attrs[(__bridge id)kCTFontAttributeName] = font;
4953
5017
  attrs[NSParagraphStyleAttributeName] = para;
5018
+ // CSS's letter-spacing, in points: added after every character, the
5019
+ // last on a line included — what kCTKernAttributeName does
5020
+ double spacing = BNumOr(span, "letterSpacing", 0);
5021
+ if (spacing != 0 && std::isfinite(spacing)) {
5022
+ attrs[(__bridge id)kCTKernAttributeName] = @(spacing);
5023
+ }
4954
5024
  if (span.Has("color") && span.Get("color").IsArray()) {
4955
5025
  CGColorRef color = BMakeColor(span.Get("color"));
4956
5026
  attrs[(__bridge id)kCTForegroundColorAttributeName] =
@@ -5164,6 +5234,121 @@ static Napi::Value CtxDrawGlyphs(const Napi::CallbackInfo& info) {
5164
5234
  return info.Env().Undefined();
5165
5235
  }
5166
5236
 
5237
+ // ---------------------------------------------------------------------------
5238
+ // SF Symbols, drawn in a surface (sidorares/react-x11#591)
5239
+ // ---------------------------------------------------------------------------
5240
+ //
5241
+ // The system's icons by name — what a status item and a menu item already
5242
+ // take — for a renderer drawing its own content. A symbol is a template: its
5243
+ // shape, in whatever colour it is drawn with, so it is drawn here the way a
5244
+ // glyph run is, in the current fill colour, and tints the way text does.
5245
+
5246
+ // The symbol's image for (name, options), or nil for a name the catalogue
5247
+ // does not know. Options: pointSize (default 13), weight (100-900, default
5248
+ // 400), scale ('small' | 'medium' | 'large', default 'medium'),
5249
+ // variableValue (0-1, macOS 13 and later; ignored before).
5250
+ static NSImage* SymbolImage(Napi::Value nameValue, Napi::Value optionsValue) {
5251
+ if (!nameValue.IsString()) {
5252
+ Napi::TypeError::New(nameValue.Env(), "expected a symbol name")
5253
+ .ThrowAsJavaScriptException();
5254
+ return nil;
5255
+ }
5256
+ NSString* name = BToNSString(nameValue);
5257
+ double pointSize = 13, weight = 400, variable = NAN;
5258
+ NSImageSymbolScale scale = NSImageSymbolScaleMedium;
5259
+ if (optionsValue.IsObject()) {
5260
+ Napi::Object o = optionsValue.As<Napi::Object>();
5261
+ pointSize = BNumOr(o, "pointSize", 13);
5262
+ weight = BNumOr(o, "weight", 400);
5263
+ NSString* s = BStrOr(o, "scale", @"medium");
5264
+ if ([s isEqualToString:@"small"]) scale = NSImageSymbolScaleSmall;
5265
+ else if ([s isEqualToString:@"large"]) scale = NSImageSymbolScaleLarge;
5266
+ if (o.Has("variableValue") && o.Get("variableValue").IsNumber())
5267
+ variable = o.Get("variableValue").As<Napi::Number>().DoubleValue();
5268
+ }
5269
+ NSImage* img = nil;
5270
+ if (!std::isnan(variable)) {
5271
+ if (@available(macOS 13.0, *)) {
5272
+ img = [NSImage imageWithSystemSymbolName:name
5273
+ variableValue:variable
5274
+ accessibilityDescription:nil];
5275
+ }
5276
+ }
5277
+ if (!img) {
5278
+ img = [NSImage imageWithSystemSymbolName:name accessibilityDescription:nil];
5279
+ }
5280
+ if (!img) return nil;
5281
+ NSImageSymbolConfiguration* cfg = [NSImageSymbolConfiguration
5282
+ configurationWithPointSize:pointSize
5283
+ weight:FontWeightFromCss(weight)
5284
+ scale:scale];
5285
+ return [img imageWithSymbolConfiguration:cfg];
5286
+ }
5287
+
5288
+ // symbolSize(name, options?) -> { width, height } in points, or null for a
5289
+ // name the catalogue does not know. The image's size, the padding the symbol
5290
+ // is designed with included: the box a symbol sits in beside text.
5291
+ static Napi::Value SymbolSize(const Napi::CallbackInfo& info) {
5292
+ Napi::Env env = info.Env();
5293
+ @autoreleasepool {
5294
+ NSImage* img = SymbolImage(info[0], info.Length() > 1 ? info[1] : env.Undefined());
5295
+ if (env.IsExceptionPending()) return env.Undefined();
5296
+ if (!img) return env.Null();
5297
+ Napi::Object out = Napi::Object::New(env);
5298
+ out.Set("width", img.size.width);
5299
+ out.Set("height", img.size.height);
5300
+ return out;
5301
+ }
5302
+ }
5303
+
5304
+ // ctxDrawSymbol(surface, name, x, y, width, height, options?) -> boolean
5305
+ // The symbol fitted into the rect, centred, keeping its proportions, in the
5306
+ // current fill colour — so it follows the surface CTM, clip, global alpha and
5307
+ // blend mode like every other ctx verb. Answers false, drawing nothing, for a
5308
+ // name the catalogue does not know. Options as symbolSize's.
5309
+ static Napi::Value CtxDrawSymbol(const Napi::CallbackInfo& info) {
5310
+ Napi::Env env = info.Env();
5311
+ CALSurface* s = SurfaceFrom(info[0]);
5312
+ if (!s) return env.Undefined();
5313
+ @autoreleasepool {
5314
+ NSImage* img = SymbolImage(info[1], info.Length() > 6 ? info[6] : env.Undefined());
5315
+ if (env.IsExceptionPending()) return env.Undefined();
5316
+ if (!img) return Napi::Boolean::New(env, false);
5317
+ double x = info[2].As<Napi::Number>().DoubleValue();
5318
+ double y = info[3].As<Napi::Number>().DoubleValue();
5319
+ double w = info[4].As<Napi::Number>().DoubleValue();
5320
+ double h = info[5].As<Napi::Number>().DoubleValue();
5321
+ NSSize size = img.size;
5322
+ if (!(w > 0 && h > 0 && size.width > 0 && size.height > 0))
5323
+ return Napi::Boolean::New(env, true);
5324
+ double k = std::min(w / size.width, h / size.height);
5325
+ CGRect rect = CGRectMake(x + (w - size.width * k) / 2, y + (h - size.height * k) / 2,
5326
+ size.width * k, size.height * k);
5327
+ CGContextRef ctx = s->ctx;
5328
+ CGContextSaveGState(ctx);
5329
+ // The template's shape into a layer of its own, then the fill colour
5330
+ // through it: the layer composites once with the context's alpha, blend
5331
+ // mode and clip, as a glyph run's ink does.
5332
+ CGContextBeginTransparencyLayerWithRect(ctx, rect, NULL);
5333
+ // the surface's base CTM is y-down, so the context is a flipped one
5334
+ NSGraphicsContext* g = [NSGraphicsContext graphicsContextWithCGContext:ctx flipped:YES];
5335
+ [NSGraphicsContext saveGraphicsState];
5336
+ [NSGraphicsContext setCurrentContext:g];
5337
+ [img drawInRect:NSRectFromCGRect(rect)
5338
+ fromRect:NSZeroRect
5339
+ operation:NSCompositingOperationSourceOver
5340
+ fraction:1.0
5341
+ respectFlipped:YES
5342
+ hints:nil];
5343
+ [NSGraphicsContext restoreGraphicsState];
5344
+ CGContextSetBlendMode(ctx, kCGBlendModeSourceIn);
5345
+ CGContextFillRect(ctx, rect);
5346
+ CGContextEndTransparencyLayer(ctx);
5347
+ CGContextRestoreGState(ctx);
5348
+ return Napi::Boolean::New(env, true);
5349
+ }
5350
+ }
5351
+
5167
5352
  // drawLayoutGradient(surface, layoutHandle, x, y, x0, y0, x1, y1,
5168
5353
  // stops [offset,r,g,b,a,...])
5169
5354
  // The glyph outlines become the clip and a linear gradient fills through
@@ -6445,6 +6630,7 @@ void InitBackend(Napi::Env env, Napi::Object exports) {
6445
6630
  BFN("cgFontWithSize", CgFontWithSize);
6446
6631
  BFN("fontByPostScriptName", FontByPostScriptName);
6447
6632
  BFN("fontApplyVariations", FontApplyVariations);
6633
+ BFN("fontApplyFeatures", FontApplyFeatures);
6448
6634
  BFN("drawLayoutGradient", DrawLayoutGradient);
6449
6635
  BFN("ctxSetShadow", CtxSetShadow);
6450
6636
  BFN("listFonts", ListFonts);
@@ -6452,6 +6638,8 @@ void InitBackend(Napi::Env env, Napi::Object exports) {
6452
6638
  BFN("createLayout", CreateLayout);
6453
6639
  BFN("drawLayout", DrawLayout);
6454
6640
  BFN("ctxDrawGlyphs", CtxDrawGlyphs);
6641
+ BFN("ctxDrawSymbol", CtxDrawSymbol);
6642
+ BFN("symbolSize", SymbolSize);
6455
6643
  BFN("layoutIndexAt", LayoutIndexAt);
6456
6644
  BFN("layoutCaret", LayoutCaret);
6457
6645
  BFN("pasteboardWriteText", PbWriteTextFn);
package/src/calendars.mm CHANGED
@@ -740,8 +740,8 @@ static Napi::Value ErrorJs(Napi::Env env, const CalAnswer& a) {
740
740
  // cb(err) or cb(null, ...) on the JS thread, from a background queue, then
741
741
  // the thread-safe function goes — which is what was holding the loop open
742
742
  // for the length of the fetch or the write.
743
- static void Deliver(Napi::ThreadSafeFunction tsfn, CalAnswer* a) {
744
- napi_status st = tsfn.BlockingCall(
743
+ static void Deliver(const CALTsfn& tsfn, CalAnswer* a) {
744
+ bool queued = tsfn.Answer(
745
745
  a, [](Napi::Env env, Napi::Function cb, CalAnswer* a) {
746
746
  // an environment on its way out gets no answer (channel.h)
747
747
  if (!CALCanCallIntoJS(env)) {
@@ -773,15 +773,16 @@ static void Deliver(Napi::ThreadSafeFunction tsfn, CalAnswer* a) {
773
773
  }
774
774
  delete a;
775
775
  });
776
- if (st != napi_ok) delete a;
777
- tsfn.Release();
776
+ if (!queued) delete a;
778
777
  }
779
778
 
780
779
  // --- the store's change notification ----------------------------------------
781
780
 
782
781
  static void CallJsChanged(Napi::Env env, Napi::Function, void*, void*);
783
782
  using ChangedTsfn = Napi::TypedThreadSafeFunction<void, void, CallJsChanged>;
784
- static ChangedTsfn gChanged;
783
+ // The main thread's environment's (InitCalendars), called from whichever
784
+ // thread EventKit posts on; null until made. Leaked with the process.
785
+ static std::atomic<CALTsfn*> gChanged{nullptr};
785
786
  // One change waiting for a listener. The event carries nothing and the
786
787
  // framework coalesces, so what is held is that a change happened at all.
787
788
  static bool gHeldChange = false;
@@ -826,10 +827,13 @@ void CALCalendarsObserveStore(EKEventStore* store) {
826
827
  object:store
827
828
  queue:nil
828
829
  usingBlock:^(NSNotification*) {
829
- if (CALChannelOpen())
830
+ if (CALChannelOpen()) {
830
831
  CALEmit(CALEvent("calendar-store-changed"));
831
- else
832
- gChanged.NonBlockingCall();
832
+ } else if (CALTsfn* changed = gChanged.load()) {
833
+ changed->Use(false, [](napi_threadsafe_function f) {
834
+ return ChangedTsfn(f).NonBlockingCall();
835
+ });
836
+ }
833
837
  }];
834
838
  }
835
839
 
@@ -905,8 +909,8 @@ static Napi::Value Calendars(const Napi::CallbackInfo& info) {
905
909
  }
906
910
  @autoreleasepool {
907
911
  EKEventStore* store = CALEventStore(); // JS thread: it is a singleton
908
- Napi::ThreadSafeFunction tsfn = Napi::ThreadSafeFunction::New(
909
- env, info[0].As<Napi::Function>(), "appkit:calendars", 0, 1);
912
+ CALTsfn tsfn = CALTsfn::New(env, info[0].As<Napi::Function>(),
913
+ "appkit:calendars");
910
914
  dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
911
915
  @autoreleasepool {
912
916
  CalAnswer* a = new CalAnswer;
@@ -931,8 +935,8 @@ static Napi::Value EventsBetween(const Napi::CallbackInfo& info) {
931
935
  }
932
936
  @autoreleasepool {
933
937
  EKEventStore* store = CALEventStore();
934
- Napi::ThreadSafeFunction tsfn = Napi::ThreadSafeFunction::New(
935
- env, info[1].As<Napi::Function>(), "appkit:eventsBetween", 0, 1);
938
+ CALTsfn tsfn = CALTsfn::New(env, info[1].As<Napi::Function>(),
939
+ "appkit:eventsBetween");
936
940
  dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
937
941
  @autoreleasepool {
938
942
  CalAnswer* a = new CalAnswer;
@@ -1548,8 +1552,8 @@ static Napi::Value DefaultCalendar(const Napi::CallbackInfo& info) {
1548
1552
  }
1549
1553
  @autoreleasepool {
1550
1554
  EKEventStore* store = CALEventStore();
1551
- Napi::ThreadSafeFunction tsfn = Napi::ThreadSafeFunction::New(
1552
- env, info[0].As<Napi::Function>(), "appkit:defaultCalendar", 0, 1);
1555
+ CALTsfn tsfn = CALTsfn::New(env, info[0].As<Napi::Function>(),
1556
+ "appkit:defaultCalendar");
1553
1557
  dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
1554
1558
  @autoreleasepool {
1555
1559
  CalAnswer* a = new CalAnswer;
@@ -1583,8 +1587,8 @@ static Napi::Value SaveEvent(const Napi::CallbackInfo& info) {
1583
1587
  }
1584
1588
  @autoreleasepool {
1585
1589
  EKEventStore* store = CALEventStore();
1586
- Napi::ThreadSafeFunction tsfn = Napi::ThreadSafeFunction::New(
1587
- env, info[cbAt].As<Napi::Function>(), "appkit:saveEvent", 0, 1);
1590
+ CALTsfn tsfn = CALTsfn::New(env, info[cbAt].As<Napi::Function>(),
1591
+ "appkit:saveEvent");
1588
1592
  dispatch_async(WriteQueue(), ^{
1589
1593
  @autoreleasepool {
1590
1594
  CalAnswer* a = new CalAnswer;
@@ -1619,8 +1623,8 @@ static Napi::Value RemoveEvent(const Napi::CallbackInfo& info) {
1619
1623
  }
1620
1624
  @autoreleasepool {
1621
1625
  EKEventStore* store = CALEventStore();
1622
- Napi::ThreadSafeFunction tsfn = Napi::ThreadSafeFunction::New(
1623
- env, info[cbAt].As<Napi::Function>(), "appkit:removeEvent", 0, 1);
1626
+ CALTsfn tsfn = CALTsfn::New(env, info[cbAt].As<Napi::Function>(),
1627
+ "appkit:removeEvent");
1624
1628
  dispatch_async(WriteQueue(), ^{
1625
1629
  @autoreleasepool {
1626
1630
  CalAnswer* a = new CalAnswer;
@@ -1643,8 +1647,8 @@ static Napi::Value CommitCalendarStore(const Napi::CallbackInfo& info) {
1643
1647
  }
1644
1648
  @autoreleasepool {
1645
1649
  EKEventStore* store = CALEventStore();
1646
- Napi::ThreadSafeFunction tsfn = Napi::ThreadSafeFunction::New(
1647
- env, info[0].As<Napi::Function>(), "appkit:commitCalendarStore", 0, 1);
1650
+ CALTsfn tsfn = CALTsfn::New(env, info[0].As<Napi::Function>(),
1651
+ "appkit:commitCalendarStore");
1648
1652
  dispatch_async(WriteQueue(), ^{
1649
1653
  @autoreleasepool {
1650
1654
  CalAnswer* a = new CalAnswer;
@@ -1667,8 +1671,8 @@ static Napi::Value ResetCalendarStore(const Napi::CallbackInfo& info) {
1667
1671
  }
1668
1672
  @autoreleasepool {
1669
1673
  EKEventStore* store = CALEventStore();
1670
- Napi::ThreadSafeFunction tsfn = Napi::ThreadSafeFunction::New(
1671
- env, info[0].As<Napi::Function>(), "appkit:resetCalendarStore", 0, 1);
1674
+ CALTsfn tsfn = CALTsfn::New(env, info[0].As<Napi::Function>(),
1675
+ "appkit:resetCalendarStore");
1672
1676
  dispatch_async(WriteQueue(), ^{
1673
1677
  @autoreleasepool {
1674
1678
  CalAnswer* a = new CalAnswer;
@@ -1702,8 +1706,15 @@ static Napi::Value PostCalendarStoreChanged(const Napi::CallbackInfo& info) {
1702
1706
  // ---------------------------------------------------------------------------
1703
1707
 
1704
1708
  void InitCalendars(Napi::Env env, Napi::Object exports) {
1705
- gChanged = ChangedTsfn::New(env, "appkit:calendars-changed", 0, 1);
1706
- gChanged.Unref(env); // a change never holds the loop open by itself
1709
+ // Pump mode delivers on the main thread only (CALEmit), so a change
1710
+ // crosses to the main thread's environment: made there, the once. Each
1711
+ // environment used to make its own and replace the last, so a worker's —
1712
+ // gone with the worker — could be the one EventKit's thread then called.
1713
+ if (pthread_main_np() && !gChanged.load()) {
1714
+ ChangedTsfn changed = ChangedTsfn::New(env, "appkit:calendars-changed", 0, 1);
1715
+ changed.Unref(env); // a change never holds the loop open by itself
1716
+ gChanged.store(new CALTsfn(CALTsfn::Watch(env, changed)));
1717
+ }
1707
1718
  exports.Set("calendars", Napi::Function::New(env, Calendars));
1708
1719
  exports.Set("eventsBetween", Napi::Function::New(env, EventsBetween));
1709
1720
  exports.Set("defaultCalendar", Napi::Function::New(env, DefaultCalendar));
package/src/channel.h CHANGED
@@ -17,7 +17,9 @@
17
17
 
18
18
  #include <atomic>
19
19
  #include <cstdint>
20
+ #include <functional>
20
21
  #include <initializer_list>
22
+ #include <memory>
21
23
  #include <string>
22
24
  #include <vector>
23
25
 
@@ -190,12 +192,70 @@ void CALOnLayers(void (^op)(void));
190
192
  // `surface-released { id }`.
191
193
  void CALNoteContentsReplaced(id layer, id next);
192
194
 
195
+ // A threadsafe function called from a thread other than its environment's —
196
+ // a dispatch queue, a framework's completion handler, the UI thread — which
197
+ // must not be touched once that environment has begun to end. Node without
198
+ // nodejs/node#55877 (every 18, 20 and 22; 24 before 24.14; 25 before 25.4)
199
+ // frees a threadsafe function in its environment's teardown whether or not a
200
+ // thread still holds it: a call that lands afterwards locks a freed mutex
201
+ // inside napi_call_threadsafe_function and aborts the process, before any
202
+ // callback runs, where CALCanCallIntoJS cannot help. Node with it keeps the
203
+ // function for the thread, but a call answered napi_closing has let the
204
+ // thread's reference go and may have freed it: a release after that is the
205
+ // same abort.
206
+ //
207
+ // So the function is used through a record of whether it still may be,
208
+ // under the record's lock. An environment cleanup hook, registered after the
209
+ // function is made and so run before the function's own teardown (hooks run
210
+ // in reverse order), lets the reference go on the holder's behalf and marks
211
+ // the record; a call after that finds it marked and does nothing. Copies
212
+ // share the record.
213
+ class CALTsfn {
214
+ public:
215
+ CALTsfn() = default;
216
+
217
+ // One answer's function for cb, made in env: holds env's loop open until
218
+ // it answers or is released.
219
+ static CALTsfn New(Napi::Env env, Napi::Function cb, const char* name);
220
+
221
+ // A long-lived function made elsewhere, whose one reference is never let
222
+ // go — an event source's — watched from here on: on env's thread, right
223
+ // after the function is made.
224
+ static CALTsfn Watch(napi_env env, napi_threadsafe_function f);
225
+
226
+ // From any thread: callback(env, cb, data) queued for env's thread, then
227
+ // the reference let go. False when nothing was queued — env is ending, or
228
+ // the function was answered or released already — and data is still the
229
+ // caller's to free.
230
+ template <typename DataType, typename Callback>
231
+ bool Answer(DataType* data, Callback callback) const {
232
+ return Use(true, [&](napi_threadsafe_function f) {
233
+ return Napi::ThreadSafeFunction(f).BlockingCall(data, callback);
234
+ });
235
+ }
236
+
237
+ // From any thread: the reference let go without an answer.
238
+ void Release() const { Use(true, nullptr); }
239
+
240
+ // The general form, from any thread: `call` gets the function, under the
241
+ // record's lock, while its environment has not begun to end and the
242
+ // reference is held; with `release` the reference goes after it. True when
243
+ // call answered napi_ok.
244
+ bool Use(bool release,
245
+ const std::function<napi_status(napi_threadsafe_function)>& call) const;
246
+
247
+ private:
248
+ struct Life;
249
+ static void EnvEnding(void* box);
250
+ static void Finalized(napi_env env, void* box);
251
+ std::shared_ptr<Life> life_;
252
+ };
253
+
193
254
  // A one-shot callback in the calling environment, answered from any thread:
194
255
  // `make` runs there and builds the one argument cb gets. A pending reply
195
256
  // holds that environment's loop open, like I/O in flight.
196
- Napi::ThreadSafeFunction CALReplyTo(Napi::Env env, Napi::Function cb,
197
- const char* name);
198
- void CALReply(Napi::ThreadSafeFunction tsfn, CALValueBlock make);
257
+ CALTsfn CALReplyTo(Napi::Env env, Napi::Function cb, const char* name);
258
+ void CALReply(const CALTsfn& tsfn, CALValueBlock make);
199
259
 
200
260
  // Whether JS can still be called in `env`. A worker that is ending (an
201
261
  // uncaught error, its own process.exit) can still run a threadsafe
@@ -157,7 +157,10 @@ struct NotifEvent {
157
157
 
158
158
  static void CallJsEvent(Napi::Env env, Napi::Function, void*, NotifEvent* ev);
159
159
  using EventTsfn = Napi::TypedThreadSafeFunction<void, NotifEvent, CallJsEvent>;
160
- static EventTsfn gEvents;
160
+ // Made in the first environment to reach the centre (ProbeCenter) and called
161
+ // from the centre's own thread, so through CALTsfn: once that environment
162
+ // has begun to end, an event is dropped rather than sent into it.
163
+ static CALTsfn gEvents;
161
164
  static std::vector<NotifEvent*> gHeld;
162
165
 
163
166
  static CALEvent EventRecord(const NotifEvent& ev) {
@@ -215,7 +218,10 @@ static void QueueEvent(NotifEvent* ev) {
215
218
  delete ev;
216
219
  return;
217
220
  }
218
- if (gEvents.NonBlockingCall(ev) != napi_ok) delete ev;
221
+ bool queued = gEvents.Use(false, [ev](napi_threadsafe_function f) {
222
+ return EventTsfn(f).NonBlockingCall(ev);
223
+ });
224
+ if (!queued) delete ev;
219
225
  }
220
226
 
221
227
  static void QueueResponse(UNNotificationResponse* r) {
@@ -287,8 +293,9 @@ static UNNotificationCategory* DefaultCategory() {
287
293
  static void ProbeCenter(Napi::Env env) {
288
294
  if (gProbed) return;
289
295
  gProbed = true;
290
- gEvents = EventTsfn::New(env, "appkit:notifications", 0, 1);
291
- gEvents.Unref(env); // events never hold the loop open by themselves
296
+ EventTsfn events = EventTsfn::New(env, "appkit:notifications", 0, 1);
297
+ events.Unref(env); // events never hold the loop open by themselves
298
+ gEvents = CALTsfn::Watch(env, events);
292
299
  @autoreleasepool {
293
300
  NSBundle* main = NSBundle.mainBundle;
294
301
  if (!main.bundleIdentifier) {
@@ -413,29 +420,26 @@ static Napi::Value NotificationSettings(const Napi::CallbackInfo& info) {
413
420
  Napi::Env env = info.Env();
414
421
  if (!CallbackArg(info, 0, "notificationSettings", "(cb)"))
415
422
  return env.Undefined();
416
- Napi::ThreadSafeFunction tsfn = Napi::ThreadSafeFunction::New(
417
- env, info[0].As<Napi::Function>(), "appkit:notificationSettings", 0, 1);
423
+ CALTsfn tsfn = CALTsfn::New(env, info[0].As<Napi::Function>(),
424
+ "appkit:notificationSettings");
418
425
  if (!gCenter) {
419
- tsfn.BlockingCall((void*)nullptr,
420
- [](Napi::Env env, Napi::Function cb, void*) {
421
- // an environment on its way out gets no answer
422
- // (channel.h)
423
- if (!CALCanCallIntoJS(env)) return;
424
- CALCallJS(env, cb, {UnavailableObject(env)});
425
- });
426
- tsfn.Release();
426
+ tsfn.Answer((void*)nullptr, [](Napi::Env env, Napi::Function cb, void*) {
427
+ // an environment on its way out gets no answer (channel.h)
428
+ if (!CALCanCallIntoJS(env)) return;
429
+ CALCallJS(env, cb, {UnavailableObject(env)});
430
+ });
427
431
  return env.Undefined();
428
432
  }
429
433
  [gCenter getNotificationSettingsWithCompletionHandler:^(
430
434
  UNNotificationSettings* s) {
431
435
  void* p = (void*)CFBridgingRetain(s);
432
- tsfn.BlockingCall(p, [](Napi::Env env, Napi::Function cb, void* p) {
436
+ bool queued = tsfn.Answer(p, [](Napi::Env env, Napi::Function cb, void* p) {
433
437
  UNNotificationSettings* s = CFBridgingRelease(p);
434
438
  // an environment on its way out gets no answer (channel.h)
435
439
  if (!CALCanCallIntoJS(env)) return;
436
440
  CALCallJS(env, cb, {SettingsObject(env, s)});
437
441
  });
438
- tsfn.Release();
442
+ if (!queued) CFRelease(p);
439
443
  }];
440
444
  return env.Undefined();
441
445
  }
@@ -500,13 +504,12 @@ static Napi::Value RequestNotificationAuthorization(
500
504
  if (!CallbackArg(info, 1, fn, "(options, cb)")) return env.Undefined();
501
505
  UNUserNotificationCenter* center = CenterOrThrow(env, fn);
502
506
  if (!center) return env.Undefined();
503
- Napi::ThreadSafeFunction tsfn = Napi::ThreadSafeFunction::New(
504
- env, info[1].As<Napi::Function>(), "appkit:requestNotificationAuthorization",
505
- 0, 1);
507
+ CALTsfn tsfn = CALTsfn::New(env, info[1].As<Napi::Function>(),
508
+ "appkit:requestNotificationAuthorization");
506
509
  [center requestAuthorizationWithOptions:opts
507
510
  completionHandler:^(BOOL granted, NSError* error) {
508
511
  Outcome* out = new Outcome{(bool)granted, error};
509
- tsfn.BlockingCall(
512
+ bool queued = tsfn.Answer(
510
513
  out, [](Napi::Env env, Napi::Function cb,
511
514
  Outcome* out) {
512
515
  if (out->ok && gCenter && gCategories) {
@@ -524,7 +527,7 @@ static Napi::Value RequestNotificationAuthorization(
524
527
  ErrorValue(env, out->error)});
525
528
  delete out;
526
529
  });
527
- tsfn.Release();
530
+ if (!queued) delete out;
528
531
  }];
529
532
  return env.Undefined();
530
533
  }
@@ -654,12 +657,12 @@ static Napi::Value NotificationCategories(const Napi::CallbackInfo& info) {
654
657
  if (!CallbackArg(info, 0, fn, "(cb)")) return env.Undefined();
655
658
  UNUserNotificationCenter* center = CenterOrThrow(env, fn);
656
659
  if (!center) return env.Undefined();
657
- Napi::ThreadSafeFunction tsfn = Napi::ThreadSafeFunction::New(
658
- env, info[0].As<Napi::Function>(), "appkit:notificationCategories", 0, 1);
660
+ CALTsfn tsfn = CALTsfn::New(env, info[0].As<Napi::Function>(),
661
+ "appkit:notificationCategories");
659
662
  [center getNotificationCategoriesWithCompletionHandler:^(
660
663
  NSSet<UNNotificationCategory*>* cats) {
661
664
  void* p = (void*)CFBridgingRetain(cats);
662
- tsfn.BlockingCall(p, [](Napi::Env env, Napi::Function cb, void* p) {
665
+ bool queued = tsfn.Answer(p, [](Napi::Env env, Napi::Function cb, void* p) {
663
666
  NSSet<UNNotificationCategory*>* cats = CFBridgingRelease(p);
664
667
  // an environment on its way out gets no answer (channel.h)
665
668
  if (!CALCanCallIntoJS(env)) return;
@@ -668,7 +671,7 @@ static Napi::Value NotificationCategories(const Napi::CallbackInfo& info) {
668
671
  for (UNNotificationCategory* c in cats) out.Set(n++, CategoryObject(env, c));
669
672
  CALCallJS(env, cb, {out});
670
673
  });
671
- tsfn.Release();
674
+ if (!queued) CFRelease(p);
672
675
  }];
673
676
  return env.Undefined();
674
677
  }
@@ -761,13 +764,12 @@ static Napi::Value Post(const Napi::CallbackInfo& info, size_t propsAt,
761
764
  if (!hasCb) {
762
765
  [center addNotificationRequest:req withCompletionHandler:nil];
763
766
  } else {
764
- Napi::ThreadSafeFunction tsfn = Napi::ThreadSafeFunction::New(
765
- env, info[cbAt].As<Napi::Function>(), "appkit:postNotification", 0,
766
- 1);
767
+ CALTsfn tsfn = CALTsfn::New(env, info[cbAt].As<Napi::Function>(),
768
+ "appkit:postNotification");
767
769
  [center addNotificationRequest:req
768
770
  withCompletionHandler:^(NSError* error) {
769
771
  Outcome* out = new Outcome{error == nil, error};
770
- tsfn.BlockingCall(
772
+ bool queued = tsfn.Answer(
771
773
  out, [](Napi::Env env, Napi::Function cb, Outcome* out) {
772
774
  // an environment on its way out gets no answer
773
775
  // (channel.h)
@@ -778,7 +780,7 @@ static Napi::Value Post(const Napi::CallbackInfo& info, size_t propsAt,
778
780
  CALCallJS(env, cb, {ErrorValue(env, out->error)});
779
781
  delete out;
780
782
  });
781
- tsfn.Release();
783
+ if (!queued) delete out;
782
784
  }];
783
785
  }
784
786
  return Napi::String::New(env, req.identifier.UTF8String);
@@ -842,12 +844,12 @@ static Napi::Value DeliveredNotifications(const Napi::CallbackInfo& info) {
842
844
  if (!CallbackArg(info, 0, fn, "(cb)")) return env.Undefined();
843
845
  UNUserNotificationCenter* center = CenterOrThrow(env, fn);
844
846
  if (!center) return env.Undefined();
845
- Napi::ThreadSafeFunction tsfn = Napi::ThreadSafeFunction::New(
846
- env, info[0].As<Napi::Function>(), "appkit:deliveredNotifications", 0, 1);
847
+ CALTsfn tsfn = CALTsfn::New(env, info[0].As<Napi::Function>(),
848
+ "appkit:deliveredNotifications");
847
849
  [center getDeliveredNotificationsWithCompletionHandler:^(
848
850
  NSArray<UNNotification*>* list) {
849
851
  void* p = (void*)CFBridgingRetain(list);
850
- tsfn.BlockingCall(p, [](Napi::Env env, Napi::Function cb, void* p) {
852
+ bool queued = tsfn.Answer(p, [](Napi::Env env, Napi::Function cb, void* p) {
851
853
  NSArray<UNNotification*>* list = CFBridgingRelease(p);
852
854
  // an environment on its way out gets no answer (channel.h)
853
855
  if (!CALCanCallIntoJS(env)) return;
@@ -881,7 +883,7 @@ static Napi::Value DeliveredNotifications(const Napi::CallbackInfo& info) {
881
883
  }
882
884
  CALCallJS(env, cb, {out});
883
885
  });
884
- tsfn.Release();
886
+ if (!queued) CFRelease(p);
885
887
  }];
886
888
  return env.Undefined();
887
889
  }
@@ -296,10 +296,9 @@ struct Reply {
296
296
  bool granted;
297
297
  };
298
298
 
299
- static void Answer(Napi::ThreadSafeFunction tsfn, const char* status,
300
- bool granted) {
299
+ static void Answer(const CALTsfn& tsfn, const char* status, bool granted) {
301
300
  Reply* r = new Reply{status, granted};
302
- napi_status st = tsfn.BlockingCall(
301
+ bool queued = tsfn.Answer(
303
302
  r, [](Napi::Env env, Napi::Function cb, Reply* r) {
304
303
  // an environment on its way out gets no answer (channel.h)
305
304
  if (!CALCanCallIntoJS(env)) {
@@ -310,12 +309,11 @@ static void Answer(Napi::ThreadSafeFunction tsfn, const char* status,
310
309
  Napi::String::New(env, r->status)});
311
310
  delete r;
312
311
  });
313
- if (st != napi_ok) delete r;
314
- tsfn.Release();
312
+ if (!queued) delete r;
315
313
  }
316
314
 
317
315
  // For every kind but the EventKit pair, granted is the one full grant.
318
- static void Answer(Napi::ThreadSafeFunction tsfn, const char* status) {
316
+ static void Answer(const CALTsfn& tsfn, const char* status) {
319
317
  Answer(tsfn, status, strcmp(status, kAuthorized) == 0);
320
318
  }
321
319
 
@@ -326,7 +324,7 @@ static void Answer(Napi::ThreadSafeFunction tsfn, const char* status) {
326
324
  @interface CALLocationRequest : NSObject <CLLocationManagerDelegate> {
327
325
  @public
328
326
  CLLocationManager* mgr_;
329
- Napi::ThreadSafeFunction tsfn_;
327
+ CALTsfn tsfn_;
330
328
  bool done_;
331
329
  }
332
330
  @end
@@ -348,7 +346,7 @@ static NSMutableArray<CALLocationRequest*>* gLocationRequests = nil;
348
346
  // The manager reports on the run loop of the thread that made it, and a
349
347
  // worker has none: it is made on the UI thread (inline in pump mode, a
350
348
  // command in threaded mode), where the delegate call then arrives.
351
- static void StartLocationRequest(Napi::ThreadSafeFunction tsfn) {
349
+ static void StartLocationRequest(CALTsfn tsfn) { // by value: the block copies it
352
350
  CALOnUI(^{
353
351
  CALLocationRequest* r = [CALLocationRequest new];
354
352
  r->tsfn_ = tsfn;
@@ -420,9 +418,8 @@ static Napi::Value RequestAuthorization(const Napi::CallbackInfo& info) {
420
418
  return env.Undefined();
421
419
  }
422
420
  @autoreleasepool {
423
- Napi::ThreadSafeFunction tsfn = Napi::ThreadSafeFunction::New(
424
- env, info[cbAt].As<Napi::Function>(), "appkit:requestAuthorization",
425
- 0, 1);
421
+ CALTsfn tsfn = CALTsfn::New(env, info[cbAt].As<Napi::Function>(),
422
+ "appkit:requestAuthorization");
426
423
  switch (kind) {
427
424
  case Kind::Camera:
428
425
  case Kind::Microphone: {
@@ -57,13 +57,13 @@ struct ColorAnswer {
57
57
  // none is. Touched on the UI thread only: the verb's own part runs there
58
58
  // (inline in pump mode, a command from a worker), and so does AppKit's
59
59
  // handler, inside the pump or the run.
60
- static std::vector<Napi::ThreadSafeFunction> gWaiting;
60
+ static std::vector<CALTsfn> gWaiting;
61
61
 
62
62
  // cb(err) | cb(null, null) | cb(null, { r, g, b }) on the JS thread, then the
63
63
  // thread-safe function goes — which is what held the loop open meanwhile.
64
- static void Deliver(Napi::ThreadSafeFunction tsfn, const ColorAnswer& answer) {
64
+ static void Deliver(const CALTsfn& tsfn, const ColorAnswer& answer) {
65
65
  ColorAnswer* a = new ColorAnswer(answer);
66
- napi_status st = tsfn.BlockingCall(
66
+ bool queued = tsfn.Answer(
67
67
  a, [](Napi::Env env, Napi::Function cb, ColorAnswer* a) {
68
68
  // an environment on its way out gets no answer (channel.h)
69
69
  if (!CALCanCallIntoJS(env)) {
@@ -83,8 +83,7 @@ static void Deliver(Napi::ThreadSafeFunction tsfn, const ColorAnswer& answer) {
83
83
  }
84
84
  delete a;
85
85
  });
86
- if (st != napi_ok) delete a;
87
- tsfn.Release();
86
+ if (!queued) delete a;
88
87
  }
89
88
 
90
89
  // The one place a session answers. The waiting list comes off first, so a
@@ -112,9 +111,9 @@ static void FinishSession(NSColor* picked) {
112
111
  "sampleScreenColor: the sampler answered a colour with no sRGB form";
113
112
  }
114
113
  }
115
- std::vector<Napi::ThreadSafeFunction> waiting;
114
+ std::vector<CALTsfn> waiting;
116
115
  waiting.swap(gWaiting);
117
- for (Napi::ThreadSafeFunction& tsfn : waiting) Deliver(tsfn, a);
116
+ for (const CALTsfn& tsfn : waiting) Deliver(tsfn, a);
118
117
  }
119
118
 
120
119
  // sampleScreenColor(cb) — show the system sampler and answer once,
@@ -129,8 +128,8 @@ static Napi::Value SampleScreenColor(const Napi::CallbackInfo& info) {
129
128
  return env.Undefined();
130
129
  }
131
130
  // made in the caller's environment, which is the one answered
132
- Napi::ThreadSafeFunction tsfn = Napi::ThreadSafeFunction::New(
133
- env, info[0].As<Napi::Function>(), "appkit:sampleScreenColor", 0, 1);
131
+ CALTsfn tsfn = CALTsfn::New(env, info[0].As<Napi::Function>(),
132
+ "appkit:sampleScreenColor");
134
133
  CALOnUI(^{
135
134
  @autoreleasepool {
136
135
  BEnsureApp();
package/src/threaded.mm CHANGED
@@ -577,20 +577,109 @@ id CALResolve(id target) {
577
577
  return target;
578
578
  }
579
579
 
580
+ // --- threadsafe functions used from other threads (channel.h) -----------------
581
+
582
+ struct CALTsfn::Life {
583
+ std::mutex mu;
584
+ // null once the reference is let go: answered, released, or the
585
+ // environment ending
586
+ napi_threadsafe_function f = nullptr;
587
+ // the function's finalizer frees the hook's box (a one-shot's); without
588
+ // one the hook does (a long-lived function's, finalized only after it)
589
+ bool finalizes = false;
590
+ };
591
+
592
+ // The environment's cleanup hook, run before the function's own: the
593
+ // reference its holder would have let go goes now, from the environment's
594
+ // thread — so Node that keeps a held function past teardown (#55877) frees
595
+ // it with the rest — and the holder finds the record marked.
596
+ void CALTsfn::EnvEnding(void* arg) {
597
+ auto* box = static_cast<std::shared_ptr<Life>*>(arg);
598
+ Life& life = **box;
599
+ bool finalizes;
600
+ {
601
+ std::lock_guard<std::mutex> l(life.mu);
602
+ if (life.f) napi_release_threadsafe_function(life.f, napi_tsfn_release);
603
+ life.f = nullptr;
604
+ finalizes = life.finalizes;
605
+ }
606
+ if (!finalizes) delete box;
607
+ }
608
+
609
+ // The function's finalizer, on its environment's thread: the hook is not
610
+ // needed any more (at teardown it has run already, and removing it is a
611
+ // no-op).
612
+ void CALTsfn::Finalized(napi_env env, void* arg) {
613
+ auto* box = static_cast<std::shared_ptr<Life>*>(arg);
614
+ napi_remove_env_cleanup_hook(env, EnvEnding, box);
615
+ {
616
+ std::lock_guard<std::mutex> l((*box)->mu);
617
+ (*box)->f = nullptr;
618
+ }
619
+ delete box;
620
+ }
621
+
622
+ CALTsfn CALTsfn::New(Napi::Env env, Napi::Function cb, const char* name) {
623
+ auto life = std::make_shared<Life>();
624
+ life->finalizes = true;
625
+ auto* box = new std::shared_ptr<Life>(life);
626
+ Napi::ThreadSafeFunction f = Napi::ThreadSafeFunction::New(
627
+ env, cb, name, 0, 1, [box](Napi::Env env) { Finalized(env, box); });
628
+ CALTsfn t;
629
+ if (!(napi_threadsafe_function)f) { // not made; the error is pending in env
630
+ delete box;
631
+ return t;
632
+ }
633
+ life->f = f;
634
+ // after the function's own hook, so it runs before it
635
+ napi_add_env_cleanup_hook(env, EnvEnding, box);
636
+ t.life_ = life;
637
+ return t;
638
+ }
639
+
640
+ CALTsfn CALTsfn::Watch(napi_env env, napi_threadsafe_function f) {
641
+ CALTsfn t;
642
+ if (!f) return t;
643
+ auto life = std::make_shared<Life>();
644
+ life->f = f;
645
+ napi_add_env_cleanup_hook(env, EnvEnding, new std::shared_ptr<Life>(life));
646
+ t.life_ = life;
647
+ return t;
648
+ }
649
+
650
+ bool CALTsfn::Use(
651
+ bool release,
652
+ const std::function<napi_status(napi_threadsafe_function)>& call) const {
653
+ if (!life_) return false;
654
+ std::lock_guard<std::mutex> l(life_->mu);
655
+ napi_threadsafe_function f = life_->f;
656
+ if (!f) return false;
657
+ napi_status st = call ? call(f) : napi_ok;
658
+ if (st == napi_closing) {
659
+ // the call let the reference go itself, and may have freed the function
660
+ life_->f = nullptr;
661
+ return false;
662
+ }
663
+ if (release) {
664
+ napi_release_threadsafe_function(f, napi_tsfn_release);
665
+ life_->f = nullptr;
666
+ }
667
+ return call && st == napi_ok;
668
+ }
669
+
580
670
  // --- one-shot replies ---------------------------------------------------------
581
671
 
582
672
  struct Reply {
583
673
  CALValueBlock make;
584
674
  };
585
675
 
586
- Napi::ThreadSafeFunction CALReplyTo(Napi::Env env, Napi::Function cb,
587
- const char* name) {
588
- return Napi::ThreadSafeFunction::New(env, cb, name, 0, 1);
676
+ CALTsfn CALReplyTo(Napi::Env env, Napi::Function cb, const char* name) {
677
+ return CALTsfn::New(env, cb, name);
589
678
  }
590
679
 
591
- void CALReply(Napi::ThreadSafeFunction tsfn, CALValueBlock make) {
680
+ void CALReply(const CALTsfn& tsfn, CALValueBlock make) {
592
681
  Reply* r = new Reply{make};
593
- napi_status st = tsfn.BlockingCall(r, [](Napi::Env env, Napi::Function cb, Reply* r) {
682
+ bool queued = tsfn.Answer(r, [](Napi::Env env, Napi::Function cb, Reply* r) {
594
683
  // an environment on its way out gets no answer (channel.h)
595
684
  if (!CALCanCallIntoJS(env)) {
596
685
  delete r;
@@ -600,8 +689,7 @@ void CALReply(Napi::ThreadSafeFunction tsfn, CALValueBlock make) {
600
689
  delete r;
601
690
  CALCallJS(env, cb, {v});
602
691
  });
603
- if (st != napi_ok) delete r;
604
- tsfn.Release();
692
+ if (!queued) delete r;
605
693
  }
606
694
 
607
695
  Napi::Value CALAnswer(const Napi::CallbackInfo& info, const char* name,
@@ -618,7 +706,7 @@ Napi::Value CALAnswer(const Napi::CallbackInfo& info, const char* name,
618
706
  }
619
707
  return compute()(env);
620
708
  }
621
- Napi::ThreadSafeFunction tsfn = CALReplyTo(env, last.As<Napi::Function>(), name);
709
+ CALTsfn tsfn = CALReplyTo(env, last.As<Napi::Function>(), name);
622
710
  dispatch_block_t work = ^{ CALReply(tsfn, compute()); };
623
711
  if (nested) CALOnUIModal(work);
624
712
  else CALOnUI(work);