@windowkit/appkit 0.10.0 → 0.11.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
@@ -493,6 +493,37 @@ 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
+
496
527
  ## App lifecycle: open-URL, open-file, reopen, quit
497
528
 
498
529
  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.11.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/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();
@@ -4601,7 +4601,7 @@ static Napi::Value FontWithSize(const Napi::CallbackInfo& info) {
4601
4601
  });
4602
4602
  }
4603
4603
 
4604
- // fontShapeText(font, text)
4604
+ // fontShapeText(font, text, { letterSpacing }?)
4605
4605
  // -> { width, runs: [{ font: handle | null, glyphs: Uint16Array,
4606
4606
  // positions: Float64Array x0,y0,x1,y1,…,
4607
4607
  // advances: Float64Array }] }
@@ -4615,7 +4615,9 @@ static Napi::Value FontWithSize(const Napi::CallbackInfo& info) {
4615
4615
  // right. The typesetter's whole answer for a cluster — a base with its
4616
4616
  // marks positioned, an emoji sequence joined, a variation selector honoured
4617
4617
  // — as ids a caller can hand to ctxDrawGlyphs beside the ids it looked up
4618
- // itself; nothing here decides where a cluster goes.
4618
+ // itself; nothing here decides where a cluster goes. `letterSpacing` is
4619
+ // the points added after every character, as createLayout's span option
4620
+ // adds them, so a run shaped here and a paragraph laid out there agree.
4619
4621
  static Napi::Value FontShapeText(const Napi::CallbackInfo& info) {
4620
4622
  Napi::Env env = info.Env();
4621
4623
  if (!BCheckFontArg(info, "fontShapeText")) return env.Undefined();
@@ -4624,9 +4626,15 @@ static Napi::Value FontShapeText(const Napi::CallbackInfo& info) {
4624
4626
  Napi::Object out = Napi::Object::New(env);
4625
4627
  Napi::Array runsOut = Napi::Array::New(env);
4626
4628
  double width = 0;
4629
+ double spacing = info.Length() > 2 && info[2].IsObject()
4630
+ ? BNumOr(info[2].As<Napi::Object>(), "letterSpacing", 0)
4631
+ : 0;
4627
4632
  if (text.length > 0) {
4628
- NSDictionary* attrs =
4629
- @{(__bridge id)kCTFontAttributeName : (__bridge id)font};
4633
+ NSMutableDictionary* attrs = [NSMutableDictionary dictionary];
4634
+ attrs[(__bridge id)kCTFontAttributeName] = (__bridge id)font;
4635
+ if (spacing != 0 && std::isfinite(spacing)) {
4636
+ attrs[(__bridge id)kCTKernAttributeName] = @(spacing);
4637
+ }
4630
4638
  NSAttributedString* as =
4631
4639
  [[NSAttributedString alloc] initWithString:text attributes:attrs];
4632
4640
  CTLineRef line =
@@ -4803,6 +4811,57 @@ static Napi::Value FontApplyVariations(const Napi::CallbackInfo& info) {
4803
4811
  });
4804
4812
  }
4805
4813
 
4814
+ // fontApplyFeatures(font, ['tnum'] | { tnum: true, liga: false, salt: 2 })
4815
+ // -> CTFont
4816
+ // OpenType features by tag (kCTFontOpenTypeFeatureTag, macOS 10.13): an
4817
+ // array turns each tag on, an object sets each tag to its value — true or
4818
+ // false, or a number for a feature that selects among alternates. The
4819
+ // settings replace any the font already carries, the way a style names its
4820
+ // features whole. Answers the font it was given when there is nothing to
4821
+ // set, so a caller can apply it unconditionally.
4822
+ static Napi::Value FontApplyFeatures(const Napi::CallbackInfo& info) {
4823
+ Napi::Env env = info.Env();
4824
+ if (!BCheckFontArg(info, "fontApplyFeatures")) return env.Undefined();
4825
+ CTFontRef base = BFontFrom(info[0]);
4826
+ NSMutableArray* settings = [NSMutableArray array];
4827
+ auto add = [&](const std::string& tag, long value) {
4828
+ if (tag.size() != 4) return;
4829
+ [settings addObject:@{
4830
+ (__bridge id)kCTFontOpenTypeFeatureTag :
4831
+ [NSString stringWithUTF8String:tag.c_str()],
4832
+ (__bridge id)kCTFontOpenTypeFeatureValue : @(value),
4833
+ }];
4834
+ };
4835
+ if (info.Length() > 1 && info[1].IsArray()) {
4836
+ Napi::Array tags = info[1].As<Napi::Array>();
4837
+ for (uint32_t i = 0; i < tags.Length(); i++) {
4838
+ if (tags.Get(i).IsString()) {
4839
+ add(tags.Get(i).As<Napi::String>().Utf8Value(), 1);
4840
+ }
4841
+ }
4842
+ } else if (info.Length() > 1 && info[1].IsObject()) {
4843
+ Napi::Object o = info[1].As<Napi::Object>();
4844
+ Napi::Array names = o.GetPropertyNames();
4845
+ for (uint32_t i = 0; i < names.Length(); i++) {
4846
+ std::string tag = names.Get(i).As<Napi::String>().Utf8Value();
4847
+ Napi::Value v = o.Get(tag.c_str());
4848
+ if (v.IsBoolean()) add(tag, v.As<Napi::Boolean>().Value() ? 1 : 0);
4849
+ else if (v.IsNumber()) add(tag, (long)v.As<Napi::Number>().Int64Value());
4850
+ }
4851
+ }
4852
+ if (settings.count == 0) return info[0];
4853
+ CTFontDescriptorRef d = CTFontDescriptorCreateWithAttributes(
4854
+ (__bridge CFDictionaryRef)
4855
+ @{(__bridge id)kCTFontFeatureSettingsAttribute : settings});
4856
+ CTFontRef ct =
4857
+ CTFontCreateCopyWithAttributes(base, CTFontGetSize(base), NULL, d);
4858
+ CFRelease(d);
4859
+ if (!ct) return info[0];
4860
+ return Napi::External<void>::New(env, (void*)ct, [](Napi::Env, void* d2) {
4861
+ CFRelease(d2);
4862
+ });
4863
+ }
4864
+
4806
4865
  // listFonts({ family? , limit? }) -> [{ postScriptName, familyName,
4807
4866
  // styleName, path }]. With a family: that family's faces, in CoreText's
4808
4867
  // matching order. Without: every installed face (bounded by limit).
@@ -4951,6 +5010,12 @@ static Napi::Value CreateLayout(const Napi::CallbackInfo& info) {
4951
5010
  NSMutableDictionary* attrs = [NSMutableDictionary dictionary];
4952
5011
  attrs[(__bridge id)kCTFontAttributeName] = font;
4953
5012
  attrs[NSParagraphStyleAttributeName] = para;
5013
+ // CSS's letter-spacing, in points: added after every character, the
5014
+ // last on a line included — what kCTKernAttributeName does
5015
+ double spacing = BNumOr(span, "letterSpacing", 0);
5016
+ if (spacing != 0 && std::isfinite(spacing)) {
5017
+ attrs[(__bridge id)kCTKernAttributeName] = @(spacing);
5018
+ }
4954
5019
  if (span.Has("color") && span.Get("color").IsArray()) {
4955
5020
  CGColorRef color = BMakeColor(span.Get("color"));
4956
5021
  attrs[(__bridge id)kCTForegroundColorAttributeName] =
@@ -6445,6 +6510,7 @@ void InitBackend(Napi::Env env, Napi::Object exports) {
6445
6510
  BFN("cgFontWithSize", CgFontWithSize);
6446
6511
  BFN("fontByPostScriptName", FontByPostScriptName);
6447
6512
  BFN("fontApplyVariations", FontApplyVariations);
6513
+ BFN("fontApplyFeatures", FontApplyFeatures);
6448
6514
  BFN("drawLayoutGradient", DrawLayoutGradient);
6449
6515
  BFN("ctxSetShadow", CtxSetShadow);
6450
6516
  BFN("listFonts", ListFonts);
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);