@windowkit/appkit 0.17.0 → 0.19.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
@@ -283,6 +283,10 @@ card.animate('transform.rotation.z',
283
283
  card.animate('transform.translation.y',
284
284
  { values: [0, -6, 6, -6, 0], duration: 0.3, timing: [0.33, 1, 0.68, 1], id: 'shake' });
285
285
 
286
+ // a transform as a whole matrix, CSS's matrix(a, b, c, d, e, f) or matrix3d(…) —
287
+ // y grows down, as in CSS; see "Transforms as matrices"
288
+ card.set({ transform: { matrix: [0.87, 0.5, -0.5, 0.87, 0, 0] } });
289
+
286
290
  // text, two ways
287
291
  const label = new TextLayer();
288
292
  label.set({ frame: [0, 14, 228, 22], contentsScale: win.scale })
@@ -342,8 +346,9 @@ Three kinds, told apart by which option is present:
342
346
  | `{ values, keyTimes?, timings?, calculationMode? }` | `CAKeyframeAnimation` | `keyTimes` one per value in 0..1, never decreasing (evenly spaced when omitted); `timings` one curve per segment; `calculationMode` `linear` (default), `discrete`, `paced`, `cubic`, `cubicPaced` |
343
347
  | `{ spring: { mass, stiffness, damping, initialVelocity } \| true, from, to }` | `CASpringAnimation` | CA's defaults for what is omitted (`true` is all of them); the duration is the settling time unless a `duration` cuts it short |
344
348
 
345
- A value — `from`, `to`, an entry of `values` — is a number, a point `[x, y]`, or a colour
346
- `[r, g, b, a]` in generic RGB like every colour in this API.
349
+ A value — `from`, `to`, an entry of `values` — is a number, a point `[x, y]`, a colour
350
+ `[r, g, b, a]` in sRGB like every colour in this API, or a transform `{ matrix }` /
351
+ `{ matrix3d }` (below).
347
352
 
348
353
  Options every kind takes:
349
354
 
@@ -354,7 +359,7 @@ Options every kind takes:
354
359
  | `autoreverse` | turn around at the end of each pass |
355
360
  | `additive` | the values are deltas over the model value, and several in flight on one key path sum |
356
361
  | `cumulative` | each repetition starts where the last ended |
357
- | `delay` | seconds before it starts; the layer shows `from` while it waits (`fillMode: backwards`) |
362
+ | `delay` | seconds before it starts; the layer shows `from` while it waits (`fillMode: backwards`). A negative delay is CSS's: the animation starts that far in and ends that much sooner, a begin time in the past rather than a `timeOffset`, which would wrap a one-shot animation round to its start |
358
363
  | `speed`, `timeOffset` | `CAMediaTiming`'s; `speed: 0` with a `timeOffset` is an animation paused at that time |
359
364
  | `hold` | keep the final value on screen after the end (`removedOnCompletion: NO`, `fillMode: forwards`) — the model value stays what it was |
360
365
  | `id` | report the end as a backend event (below) |
@@ -383,13 +388,39 @@ space's midpoint.
383
388
  a layer's `backgroundColor`, `borderColor` and `shadowColor`, a shape's fill and stroke,
384
389
  a gradient's stops, an animation's `from`/`to`, a presentation value, a text span's ink
385
390
  and the surfaces `createSurface` makes. One space, so a colour set on a layer and the
386
- same colour rastered into a surface composite to the same pixels. (Before 0.6 the layer
391
+ same colour rastered into a surface composite to the same pixels. An IOSurface says it
392
+ itself: those `createSurfaceIOSurface` makes and `surfaceFromIOSurfaceID` draws into name
393
+ sRGB as their colour space, and `setLayerContentsIOSurface` names one that names none — a
394
+ GL target — so a surface presented on a layer is matched to the display as a layer colour
395
+ is. Core Animation shows an IOSurface that names no space as the display's own numbers:
396
+ until these named theirs, a window presented that way went out on a wide-gamut panel as
397
+ the panel's own red, (255, 0, 0) in its space, beside a layer's sRGB red, (234, 51, 35),
398
+ and on a monitor with a profile of its own even a grey differed. (Before 0.6 the layer
387
399
  half was Generic RGB, which the compositor converts on its way to the display: `#dbe7f4`
388
400
  on a layer showed as (228, 236, 245) beside a surface's (219, 231, 244), and a colour
389
401
  animation landed on a model value that did not match its own `to`. A caller that draws
390
402
  both ways — react-x11's layer promotion — feature-detects the verb.) `speed: 0, timeOffset: t` plus a read is how a curve is sampled without
391
403
  waiting for it, which is how `test/animation.js` checks every curve above.
392
404
 
405
+ **Transforms as matrices.** `setLayerProps`' `transform` takes Core Animation's
406
+ components — `{ translateX, translateY, rotate, scale, scaleX, scaleY }` — or a whole
407
+ matrix, in CSS's two spellings: `{ matrix: [a, b, c, d, e, f] }` is `matrix()`, a point
408
+ `(x, y)` going to `(a·x + c·y + e, b·x + d·y + f)` with the translation in points, and
409
+ `{ matrix3d: [m11, m12, …, m44] }` is `matrix3d()`, whose sixteen numbers are
410
+ `CATransform3D`'s in the order `presentationValue` reads one back. The same objects are
411
+ animation values, so a key path of `transform` can run keyframes a caller computed — a
412
+ CSS transform list sampled where CSS interpolates it, which `CATransform3D`'s own
413
+ interpolation would not reproduce for a turn of a whole circle or a mixed list. The
414
+ window's root layer is geometry-flipped, so y grows down here as it does in CSS: a
415
+ positive angle turns clockwise and a positive translation moves down, with no sign to
416
+ change on the way in. A matrix of the wrong length or with a number that is not finite
417
+ is a `TypeError`, and nothing is applied.
418
+
419
+ **`native.transformForms()`** — `['translate', 'rotate', 'scale', 'matrix', 'matrix3d']`:
420
+ the forms a transform takes on its way in. A caller that hands over matrices
421
+ feature-detects `matrix` here; before 0.19 an object holding one was read as no transform
422
+ at all, and refused as an animation value.
423
+
393
424
  **The end of an animation.** With an `id`, the animation's delegate forwards
394
425
  `animationDidStop:finished:` through `setBackendEventCallback` as
395
426
 
@@ -506,6 +537,26 @@ native.ctxDrawSurface(win, grid, 0, 0, 2000, 1620, 40, 30, 2000, 1620);
506
537
  native.ctxSetBlendMode(win, 'source-over');
507
538
  ```
508
539
 
540
+ - **`native.ctxDrawSurfaceFaded(dst, src, sx, sy, sw, sh, dx, dy, dw, dh, alpha)`** —
541
+ `ctxDrawSurface` under an alpha below 1, which the caller passes again because it is
542
+ the alpha it set with `ctxSetGlobalAlpha` and CoreGraphics keeps no getter for it.
543
+ CoreGraphics draws an image under an alpha below 1 at some fifteen times what the same
544
+ draw costs at 1, and composites a transparency layer the same way, so a group faded on
545
+ a surface of its own — CSS `opacity`, a fade — cost more than drawing again what was
546
+ on it. This scales the source rect's premultiplied pixels by the alpha into a bitmap
547
+ of their own and draws that at 1: the same colours within a unit a channel, and a
548
+ 556x300 surface in 0.25ms where the alpha path takes 1.24ms on an M1 Pro. The
549
+ destination keeps the alpha it was set to. A source rect off the pixel grid or past
550
+ the source, an IOSurface-backed source, a surface drawn onto itself and an alpha of 1
551
+ or 0 are drawn as `ctxDrawSurface` draws them, under the alpha already set — so a
552
+ caller can call it for every draw under an alpha, and feature-detect the verb to know
553
+ whether a faded surface is cheap here.
554
+
555
+ ```js
556
+ native.ctxSetGlobalAlpha(win, 0.6);
557
+ native.ctxDrawSurfaceFaded(win, card, 0, 0, 556, 300, 100, 100, 556, 300, 0.6);
558
+ ```
559
+
509
560
  ## Text: letter spacing and OpenType features
510
561
 
511
562
  The text verbs a renderer lays paragraphs out and shapes glyph runs with —
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@windowkit/appkit",
3
- "version": "0.17.0",
3
+ "version": "0.19.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/round-rect-xy.js && node test/control-bezels.js && node test/text-features.js && node test/text-coverage.js && node test/text-typesetter.js && node test/text-line-height.js && node test/text-line-width.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"
46
+ "test": "node test/app-lifecycle.js && node test/animation.js && node test/layer-transform.js && node test/accessibility-display.js && node test/ignores-mouse-events.js && node test/surface-blit.js && node test/surface-faded.js && node test/surface-colorspace.js && node test/round-rect-xy.js && node test/control-bezels.js && node test/text-features.js && node test/font-from-data.js && node test/text-coverage.js && node test/text-typesetter.js && node test/text-line-height.js && node test/text-line-width.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/notifications.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/addon.mm CHANGED
@@ -71,6 +71,21 @@ static Napi::Value ColorSpace(const Napi::CallbackInfo& info) {
71
71
  return Napi::String::New(info.Env(), "sRGB");
72
72
  }
73
73
 
74
+ // The forms a layer transform takes on its way in, as setLayerProps'
75
+ // `transform` and as an animation's values: Core Animation's translate,
76
+ // rotate and scale components, and a whole matrix in either of CSS's
77
+ // spellings (`MatrixFrom`). A caller that hands over a matrix it computed —
78
+ // a CSS transform, sampled — feature-detects `matrix` here: before 0.19 a
79
+ // bridge read an object holding one as no transform at all, and refused it
80
+ // as an animation value.
81
+ static Napi::Value TransformForms(const Napi::CallbackInfo& info) {
82
+ Napi::Env env = info.Env();
83
+ static const char* forms[] = {"translate", "rotate", "scale", "matrix", "matrix3d"};
84
+ Napi::Array a = Napi::Array::New(env, 5);
85
+ for (uint32_t i = 0; i < 5; i++) a.Set(i, Napi::String::New(env, forms[i]));
86
+ return a;
87
+ }
88
+
74
89
  static CGPoint PointFrom(Napi::Value v) {
75
90
  Napi::Array a = v.As<Napi::Array>();
76
91
  return CGPointMake(a.Get(0u).As<Napi::Number>().DoubleValue(),
@@ -478,10 +493,49 @@ static Napi::Value RemoveFromSuperlayer(const Napi::CallbackInfo& info) {
478
493
  return info.Env().Undefined();
479
494
  }
480
495
 
496
+ // A transform given as a matrix, in CSS's two spellings: `matrix` is
497
+ // `matrix(a, b, c, d, e, f)`, a point (x, y) going to (a·x + c·y + e,
498
+ // b·x + d·y + f), and `matrix3d` is `matrix3d()`'s sixteen numbers, which
499
+ // are CATransform3D's m11…m44 in that order (a transform read back through
500
+ // presentationValue comes out in it). The root layer is geometry-flipped, so
501
+ // y grows down here as it does in CSS: no sign changes on the way in.
502
+ // Returns 0 when `t` holds neither, 1 when it held one and `out` is set, and
503
+ // -1 for a matrix of the wrong shape.
504
+ static int MatrixFrom(Napi::Object t, CATransform3D* out) {
505
+ bool two = t.Has("matrix");
506
+ if (!two && !t.Has("matrix3d")) return 0;
507
+ Napi::Value mv = t.Get(two ? "matrix" : "matrix3d");
508
+ uint32_t n = two ? 6 : 16;
509
+ if (!mv.IsArray() || mv.As<Napi::Array>().Length() != n) return -1;
510
+ Napi::Array a = mv.As<Napi::Array>();
511
+ double c[16];
512
+ for (uint32_t i = 0; i < n; i++) {
513
+ Napi::Value e = a.Get(i);
514
+ if (!e.IsNumber()) return -1;
515
+ c[i] = e.As<Napi::Number>().DoubleValue();
516
+ if (!std::isfinite(c[i])) return -1;
517
+ }
518
+ CATransform3D m = CATransform3DIdentity;
519
+ if (two) {
520
+ m.m11 = c[0];
521
+ m.m12 = c[1];
522
+ m.m21 = c[2];
523
+ m.m22 = c[3];
524
+ m.m41 = c[4];
525
+ m.m42 = c[5];
526
+ } else {
527
+ CGFloat* f = &m.m11;
528
+ for (uint32_t i = 0; i < 16; i++) f[i] = c[i];
529
+ }
530
+ *out = m;
531
+ return 1;
532
+ }
533
+
481
534
  static CATransform3D TransformFrom(Napi::Value v) {
482
535
  if (v.IsNull() || v.IsUndefined()) return CATransform3DIdentity;
483
536
  Napi::Object t = v.As<Napi::Object>();
484
537
  CATransform3D m = CATransform3DIdentity;
538
+ if (MatrixFrom(t, &m) == 1) return m;
485
539
  m = CATransform3DTranslate(m, NumOr(t, "translateX", 0), NumOr(t, "translateY", 0), 0);
486
540
  double rot = NumOr(t, "rotate", 0); // radians
487
541
  if (rot != 0) m = CATransform3DRotate(m, rot, 0, 0, 1);
@@ -521,6 +575,7 @@ struct LayerPropsSpec {
521
575
  bool hasMasks = false, hasShadowOpacity = false, hasShadowRadius = false;
522
576
  bool hasShadowOffset = false, hasContentsScale = false, hasName = false;
523
577
  bool hasMask = false, hasTransform = false, clearContents = false;
578
+ bool badTransform = false; // a matrix of the wrong shape: a TypeError, nothing applied
524
579
  double corner = 0, borderWidth = 0, shadowRadius = 3, contentsScale = 1;
525
580
  float opacity = 1, shadowOpacity = 0;
526
581
  bool hidden = false, masks = false;
@@ -586,7 +641,12 @@ static LayerPropsSpec ParseLayerProps(Napi::Object o) {
586
641
  Napi::Value v = o.Get("mask");
587
642
  s.mask = (v.IsNull() || v.IsUndefined()) ? nil : CALHandleTarget(v);
588
643
  }
589
- if ((s.hasTransform = o.Has("transform"))) s.transform = TransformFrom(o.Get("transform"));
644
+ if ((s.hasTransform = o.Has("transform"))) {
645
+ Napi::Value tv = o.Get("transform");
646
+ CATransform3D m;
647
+ if (tv.IsObject() && MatrixFrom(tv.As<Napi::Object>(), &m) == -1) s.badTransform = true;
648
+ else s.transform = TransformFrom(tv);
649
+ }
590
650
  if (o.Has("contents")) s.clearContents = o.Get("contents").IsNull();
591
651
  return s;
592
652
  }
@@ -622,6 +682,11 @@ static void ApplyLayerProps(CALayer* L, const LayerPropsSpec& s) {
622
682
  static Napi::Value SetLayerProps(const Napi::CallbackInfo& info) {
623
683
  id target = CALHandleTarget(info[0]);
624
684
  LayerPropsSpec s = ParseLayerProps(info[1].As<Napi::Object>());
685
+ if (s.badTransform) {
686
+ Napi::TypeError::New(info.Env(), "transform: matrix is six finite numbers, matrix3d sixteen")
687
+ .ThrowAsJavaScriptException();
688
+ return info.Env().Undefined();
689
+ }
625
690
  CALOnLayers(^{
626
691
  CALayer* L = CALResolve(target);
627
692
  if (L) ApplyLayerProps(L, s);
@@ -806,10 +871,16 @@ static bool ThrowType(Napi::Env env, const char* msg) {
806
871
  return false;
807
872
  }
808
873
 
809
- // A number, a point [x, y] or a colour [r, g, b(, a)] — the value types a key
810
- // path takes here. nil for anything else, which the caller reports.
874
+ // A number, a point [x, y], a colour [r, g, b(, a)] or a transform
875
+ // { matrix } / { matrix3d } — the value types a key path takes here. nil for
876
+ // anything else, which the caller reports.
811
877
  static id AnimValue(Napi::Value v) {
812
878
  if (v.IsNumber()) return @(v.As<Napi::Number>().DoubleValue());
879
+ if (v.IsObject() && !v.IsArray()) {
880
+ CATransform3D m;
881
+ if (MatrixFrom(v.As<Napi::Object>(), &m) != 1) return nil;
882
+ return [NSValue valueWithCATransform3D:m];
883
+ }
813
884
  if (v.IsArray()) {
814
885
  Napi::Array a = v.As<Napi::Array>();
815
886
  if (a.Length() == 2) {
@@ -944,12 +1015,12 @@ static bool ApplyTiming(Napi::Env env, CAPropertyAnimation* a, Napi::Object o,
944
1015
  static bool ReadFromTo(Napi::Env env, CABasicAnimation* a, Napi::Object o) {
945
1016
  if (o.Has("from")) {
946
1017
  id v = AnimValue(o.Get("from"));
947
- if (!v) return ThrowType(env, "from: expected a number, [x, y] or [r, g, b, a]");
1018
+ if (!v) return ThrowType(env, "from: expected a number, [x, y], [r, g, b, a] or { matrix }");
948
1019
  a.fromValue = v;
949
1020
  }
950
1021
  if (o.Has("to")) {
951
1022
  id v = AnimValue(o.Get("to"));
952
- if (!v) return ThrowType(env, "to: expected a number, [x, y] or [r, g, b, a]");
1023
+ if (!v) return ThrowType(env, "to: expected a number, [x, y], [r, g, b, a] or { matrix }");
953
1024
  a.toValue = v;
954
1025
  }
955
1026
  return true;
@@ -998,7 +1069,7 @@ static Napi::Value AddAnimation(const Napi::CallbackInfo& info) {
998
1069
  for (uint32_t i = 0; i < varr.Length(); i++) {
999
1070
  id v = AnimValue(varr.Get(i));
1000
1071
  if (!v) {
1001
- ThrowType(env, "values: each entry is a number, [x, y] or [r, g, b, a]");
1072
+ ThrowType(env, "values: each entry is a number, [x, y], [r, g, b, a] or { matrix }");
1002
1073
  return env.Undefined();
1003
1074
  }
1004
1075
  [values addObject:v];
@@ -1091,8 +1162,12 @@ static Napi::Value AddAnimation(const Napi::CallbackInfo& info) {
1091
1162
  CALayer* L = CALResolve(target);
1092
1163
  if (!L) return;
1093
1164
  // in the layer's own time — the media time unless the layer itself has
1094
- // been slowed or offset
1095
- if (delay > 0) a.beginTime = [L convertTime:CACurrentMediaTime() fromLayer:nil] + delay;
1165
+ // been slowed or offset. A negative delay is a begin time in the past,
1166
+ // CSS's negative animation-delay: the animation joined that far in, and
1167
+ // over that much sooner. Not a timeOffset, which moves where in its
1168
+ // cycle an animation is and not when it ends, so a one-shot animation
1169
+ // joined half way would run to its end and wrap round to its start.
1170
+ if (delay != 0) a.beginTime = [L convertTime:CACurrentMediaTime() fromLayer:nil] + delay;
1096
1171
  [L addAnimation:a forKey:key];
1097
1172
  });
1098
1173
  return Napi::Number::New(env, duration);
@@ -1529,13 +1604,19 @@ static Napi::Value DrawControl(const Napi::CallbackInfo& info) {
1529
1604
  return r;
1530
1605
  }
1531
1606
 
1607
+ // An IOSurface's colour space named sRGB, or kept as its producer named it
1608
+ // (backend.mm).
1609
+ void CALNameSurfaceSRGB(IOSurfaceRef ios, bool keep);
1610
+
1532
1611
  // setLayerContentsIOSurface(layer, iosurfaceId) — the receiving end of an
1533
1612
  // IOSurface render target (x11-dri's appleCreateTarget): the id is process-
1534
1613
  // global, so the GPU addon and this one never share a pointer. The layer
1535
1614
  // retains the surface; our lookup reference goes with the change. From a
1536
1615
  // worker the flip happens when the frame applies, so the renderer may not
1537
1616
  // draw into the buffer it replaced until `surface-released` names it (or
1538
- // surfaceIsInUse says it is off glass).
1617
+ // surfaceIsInUse says it is off glass). A surface that names no colour
1618
+ // space is named sRGB here: shown as it was, its numbers would be the
1619
+ // display's own and not the space the rest of the window is in.
1539
1620
  static Napi::Value SetLayerContentsIOSurface(const Napi::CallbackInfo& info) {
1540
1621
  Napi::Env env = info.Env();
1541
1622
  id target = CALHandleTarget(info[0]);
@@ -1546,6 +1627,7 @@ static Napi::Value SetLayerContentsIOSurface(const Napi::CallbackInfo& info) {
1546
1627
  .ThrowAsJavaScriptException();
1547
1628
  return env.Undefined();
1548
1629
  }
1630
+ CALNameSurfaceSRGB(surface, true);
1549
1631
  id s = CFBridgingRelease(surface); // held until the change has been made
1550
1632
  CALOnLayers(^{
1551
1633
  CALayer* L = CALResolve(target);
@@ -1667,6 +1749,7 @@ static Napi::Object Init(Napi::Env env, Napi::Object exports) {
1667
1749
  FN("txCommit", TxCommit);
1668
1750
  FN("presentationValue", PresentationValue);
1669
1751
  FN("colorSpace", ColorSpace);
1752
+ FN("transformForms", TransformForms);
1670
1753
  FN("hitTest", HitTest);
1671
1754
  FN("measureText", MeasureText);
1672
1755
  FN("createTextImage", CreateTextImage);
package/src/backend.mm CHANGED
@@ -1647,6 +1647,41 @@ static Napi::Value CreateSurface(const Napi::CallbackInfo& info) {
1647
1647
  return WrapSurface(env, s, (int64_t)(CGBitmapContextGetBytesPerRow(ctx) * h));
1648
1648
  }
1649
1649
 
1650
+ // Name an IOSurface's colour space: sRGB, the space of the bitmap context
1651
+ // laid over it and of every colour this bridge makes. Core Animation
1652
+ // matches content that names its space to the display — a CGImage carries
1653
+ // its CGColorSpace, a layer colour is a CGColor — and shows an IOSurface
1654
+ // that names none as the display's own numbers. So on a display whose
1655
+ // profile is not sRGB the window's bitmap and a layer beside it disagreed:
1656
+ // on a MacBook's wide-gamut panel #ff0000 in the bitmap was the panel's own
1657
+ // red, (255, 0, 0) in its space, where the same red on a layer showed as
1658
+ // sRGB red, (234, 51, 35); on a monitor whose profile is its own, even
1659
+ // #808080 differed, (128, 128, 128) against (117, 117, 117).
1660
+ //
1661
+ // A surface this bridge draws into is named sRGB whatever it said before
1662
+ // (`keep` false): what is in it is what an sRGB context wrote. One it is
1663
+ // only handed to show (setLayerContentsIOSurface — a GL target, another
1664
+ // process's buffer) keeps a space its producer named, and is taken to be
1665
+ // sRGB, like everything else here, when it names none.
1666
+ void CALNameSurfaceSRGB(IOSurfaceRef ios, bool keep) {
1667
+ static const CFPropertyListRef srgb = [] {
1668
+ CGColorSpaceRef cs = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
1669
+ CFPropertyListRef p = CGColorSpaceCopyPropertyList(cs);
1670
+ CGColorSpaceRelease(cs);
1671
+ return p;
1672
+ }();
1673
+ if (!ios || !srgb) return;
1674
+ if (keep) {
1675
+ for (CFStringRef key : {kIOSurfaceColorSpace, kIOSurfaceICCProfile}) {
1676
+ CFTypeRef named = IOSurfaceCopyValue(ios, key);
1677
+ if (!named) continue;
1678
+ CFRelease(named);
1679
+ return;
1680
+ }
1681
+ }
1682
+ IOSurfaceSetValue(ios, kIOSurfaceColorSpace, srgb);
1683
+ }
1684
+
1650
1685
  // createSurfaceIOSurface(widthPx, heightPx, scale)
1651
1686
  // -> { handle, iosurfaceId }
1652
1687
  // The zero-copy presentation surface: the CG bitmap is laid directly over
@@ -1685,6 +1720,7 @@ static Napi::Value CreateSurfaceIOSurface(const Napi::CallbackInfo& info) {
1685
1720
  Napi::Error::New(env, "IOSurfaceCreate failed").ThrowAsJavaScriptException();
1686
1721
  return env.Undefined();
1687
1722
  }
1723
+ CALNameSurfaceSRGB(ios, false);
1688
1724
  CGColorSpaceRef cs = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
1689
1725
  CGContextRef ctx = CGBitmapContextCreateWithData(
1690
1726
  IOSurfaceGetBaseAddress(ios), w, h, 8, IOSurfaceGetBytesPerRow(ios), cs,
@@ -1723,6 +1759,7 @@ static Napi::Value SurfaceFromIOSurfaceID(const Napi::CallbackInfo& info) {
1723
1759
  }
1724
1760
  size_t w = IOSurfaceGetWidth(ios);
1725
1761
  size_t h = IOSurfaceGetHeight(ios);
1762
+ CALNameSurfaceSRGB(ios, false);
1726
1763
  CGColorSpaceRef cs = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
1727
1764
  CGContextRef ctx = CGBitmapContextCreateWithData(
1728
1765
  IOSurfaceGetBaseAddress(ios), w, h, 8, IOSurfaceGetBytesPerRow(ios), cs,
@@ -4094,6 +4131,80 @@ static Napi::Value CtxDrawSurface(const Napi::CallbackInfo& info) {
4094
4131
  return info.Env().Undefined();
4095
4132
  }
4096
4133
 
4134
+ // drawSurfaceFaded(dst, src, sx, sy, sw, sh, dx, dy, dw, dh, alpha)
4135
+ //
4136
+ // drawSurface at `alpha` — the alpha the caller set with ctxSetGlobalAlpha,
4137
+ // passed again because CoreGraphics keeps no getter for it. CoreGraphics
4138
+ // draws an image under an alpha below 1 at some fifteen times what the same
4139
+ // draw costs at 1 — a 556x300 surface, 1.3ms against 0.09 on an M1 Pro — and
4140
+ // composites a transparency layer the same way, so a group faded on a
4141
+ // surface (CSS opacity, a fade) cost more than drawing what was on it again.
4142
+ // The source rect's premultiplied pixels scaled by the alpha into a bitmap
4143
+ // of their own, and that drawn at 1, come to the same colours within a unit
4144
+ // for 0.25ms. A rect off the pixel grid or past the source, an IOSurface the
4145
+ // CPU would have to lock, a surface onto itself and an alpha of 1 or 0 are
4146
+ // drawn as drawSurface draws them, under the alpha already set.
4147
+ static Napi::Value CtxDrawSurfaceFaded(const Napi::CallbackInfo& info) {
4148
+ CALSurface* dst = SurfaceFrom(info[0]);
4149
+ if (!dst) return info.Env().Undefined();
4150
+ CALSurface* src = SurfaceFrom(info[1]);
4151
+ if (!src) return info.Env().Undefined();
4152
+ double sx = info[2].As<Napi::Number>().DoubleValue();
4153
+ double sy = info[3].As<Napi::Number>().DoubleValue();
4154
+ double sw = info[4].As<Napi::Number>().DoubleValue();
4155
+ double sh = info[5].As<Napi::Number>().DoubleValue();
4156
+ double dx = info[6].As<Napi::Number>().DoubleValue();
4157
+ double dy = info[7].As<Napi::Number>().DoubleValue();
4158
+ double dw = info[8].As<Napi::Number>().DoubleValue();
4159
+ double dh = info[9].As<Napi::Number>().DoubleValue();
4160
+ double alpha = info[10].As<Napi::Number>().DoubleValue();
4161
+ bool rows = sx == floor(sx) && sy == floor(sy) && sw == floor(sw) &&
4162
+ sh == floor(sh) && sx >= 0 && sy >= 0 && sw >= 1 && sh >= 1 &&
4163
+ sx + sw <= (double)src->width && sy + sh <= (double)src->height;
4164
+ if (!(alpha > 0 && alpha < 1) || !rows || src->iosurface || src == dst) {
4165
+ return CtxDrawSurface(info);
4166
+ }
4167
+ size_t w = (size_t)sw;
4168
+ size_t h = (size_t)sh;
4169
+ CGColorSpaceRef cs = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
4170
+ CGContextRef faded = CGBitmapContextCreate(
4171
+ NULL, w, h, 8, 0, cs,
4172
+ kCGImageAlphaPremultipliedFirst | (CGBitmapInfo)kCGBitmapByteOrder32Host);
4173
+ CGColorSpaceRelease(cs);
4174
+ const uint8_t* from = (const uint8_t*)CGBitmapContextGetData(src->ctx);
4175
+ uint8_t* to = faded ? (uint8_t*)CGBitmapContextGetData(faded) : nullptr;
4176
+ if (!from || !to) {
4177
+ if (faded) CGContextRelease(faded);
4178
+ return CtxDrawSurface(info);
4179
+ }
4180
+ size_t fromStride = CGBitmapContextGetBytesPerRow(src->ctx);
4181
+ size_t toStride = CGBitmapContextGetBytesPerRow(faded);
4182
+ // premultiplied, so every channel scales with the alpha, whatever order
4183
+ // the host keeps them in: c * a / 255, rounded, in shifts
4184
+ const unsigned a = (unsigned)(alpha * 255 + 0.5);
4185
+ for (size_t y = 0; y < h; y++) {
4186
+ const uint8_t* row = from + ((size_t)sy + y) * fromStride + (size_t)sx * 4;
4187
+ uint8_t* out = to + y * toStride;
4188
+ for (size_t k = 0; k < w * 4; k++) {
4189
+ unsigned t = row[k] * a + 128;
4190
+ out[k] = (uint8_t)((t + (t >> 8)) >> 8);
4191
+ }
4192
+ }
4193
+ CGImageRef image = CGBitmapContextCreateImage(faded);
4194
+ CGContextRelease(faded);
4195
+ if (!image) return CtxDrawSurface(info);
4196
+ CGContextSaveGState(dst->ctx);
4197
+ CGContextSetAlpha(dst->ctx, 1);
4198
+ // the base CTM is flipped; flip back around the destination rect so the
4199
+ // image lands upright
4200
+ CGContextTranslateCTM(dst->ctx, dx, dy + dh);
4201
+ CGContextScaleCTM(dst->ctx, 1, -1);
4202
+ CGContextDrawImage(dst->ctx, CGRectMake(0, 0, dw, dh), image);
4203
+ CGContextRestoreGState(dst->ctx);
4204
+ CGImageRelease(image);
4205
+ return info.Env().Undefined();
4206
+ }
4207
+
4097
4208
  // putImageData(surface, buffer RGBA straight, w, h, dx, dy) — writes pixels
4098
4209
  // directly, transform- and clip-free, per the canvas contract.
4099
4210
  static Napi::Value CtxPutImageData(const Napi::CallbackInfo& info) {
@@ -4774,9 +4885,10 @@ static double CssWeightOfCTFont(CTFontRef ct) {
4774
4885
 
4775
4886
  // fontFromData(buffer) -> { cg: External<CGFont>, familyName,
4776
4887
  // postScriptName, weight, italic }. The CGFont is the process's own handle
4777
- // to the face — no registry round trip, so a face CoreText refuses to
4778
- // register (in-memory data) still renders. Registration is attempted as a
4779
- // best effort so descriptor matching elsewhere can also find it.
4888
+ // to the face — no registry round trip. It reads the face and installs
4889
+ // nothing: the face is never registered with CoreText, so matchFont,
4890
+ // fontByPostScriptName and listFonts go on answering exactly what they did
4891
+ // before the bytes were read (windowkit/appkit#92).
4780
4892
  static Napi::Value FontFromData(const Napi::CallbackInfo& info) {
4781
4893
  Napi::Env env = info.Env();
4782
4894
  Napi::Buffer<uint8_t> buf = info[0].As<Napi::Buffer<uint8_t>>();
@@ -4786,7 +4898,6 @@ static Napi::Value FontFromData(const Napi::CallbackInfo& info) {
4786
4898
  CGFontRef cg = provider ? CGFontCreateWithDataProvider(provider) : NULL;
4787
4899
  if (provider) CGDataProviderRelease(provider);
4788
4900
  if (!cg) return env.Null();
4789
- CTFontManagerRegisterGraphicsFont(cg, NULL); // best effort
4790
4901
  CTFontRef ct = CTFontCreateWithGraphicsFont(cg, 12, NULL, NULL);
4791
4902
  Napi::Object r = Napi::Object::New(env);
4792
4903
  r.Set("cg", Napi::External<void>::New(env, (void*)cg, [](Napi::Env, void* d) {
@@ -7203,6 +7314,7 @@ void InitBackend(Napi::Env env, Napi::Object exports) {
7203
7314
  BFN("ctxFillRects", CtxFillRects);
7204
7315
  BFN("ctxFillLinearGradient", CtxFillLinearGradient);
7205
7316
  BFN("ctxDrawSurface", CtxDrawSurface);
7317
+ BFN("ctxDrawSurfaceFaded", CtxDrawSurfaceFaded);
7206
7318
  BFN("ctxPutImageData", CtxPutImageData);
7207
7319
  BFN("ctxGetImageData", CtxGetImageData);
7208
7320
  BFN("surfaceToLayer", SurfaceToLayer);
@@ -31,10 +31,12 @@
31
31
  // which is what the framework requires for a response that launched the
32
32
  // app (a click on a banner while the app was not running) to be delivered
33
33
  // at all. Its methods carry no thread guarantee, so a response crosses to
34
- // node's loop through a thread-safe function and is then emitted through
35
- // the same backend callback every other event takes; whatever arrives
36
- // before setBackendEventCallback() is held and replayed, in order, at the
37
- // start of the first pump2() with a listener.
34
+ // node's loop through a thread-safe function — the main thread's
35
+ // environment's, made the once, since pump mode delivers on the main thread
36
+ // and nowhere else — and is then emitted through the same backend callback
37
+ // every other event takes; whatever arrives before setBackendEventCallback()
38
+ // is held and replayed, in order, at the start of the first pump2() with a
39
+ // listener.
38
40
  //
39
41
  // Categories are handed to the system as a whole set, and the system keeps
40
42
  // none for an app it has not yet authorized — notificationCategories reads
@@ -57,6 +59,10 @@
57
59
  #import <Cocoa/Cocoa.h>
58
60
  #import <UserNotifications/UserNotifications.h>
59
61
 
62
+ #include <pthread.h>
63
+
64
+ #include <atomic>
65
+ #include <mutex>
60
66
  #include <string>
61
67
  #include <vector>
62
68
 
@@ -132,7 +138,14 @@ static Napi::Value StringOrNull(Napi::Env env, NSString* s) {
132
138
 
133
139
  @class CALNotificationDelegate;
134
140
 
135
- static bool gProbed = false;
141
+ // The centre, the delegate and the bundle check are the process's, not an
142
+ // environment's, so they go up the once — in whichever environment loads the
143
+ // module first, since the delegate has to be in place before
144
+ // finishLaunching whoever got here first. call_once rather than a bare bool:
145
+ // it publishes the outcome below to every later loader's thread, and a verb
146
+ // only ever runs in an environment that has loaded the module, so its read
147
+ // of gCenter is behind this.
148
+ static std::once_flag gProbeOnce;
136
149
  static UNUserNotificationCenter* gCenter = nil;
137
150
  static NSString* gUnavailable = nil; // why, when gCenter is nil
138
151
  static CALNotificationDelegate* gDelegate = nil; // the centre's delegate is weak
@@ -157,10 +170,13 @@ struct NotifEvent {
157
170
 
158
171
  static void CallJsEvent(Napi::Env env, Napi::Function, void*, NotifEvent* ev);
159
172
  using EventTsfn = Napi::TypedThreadSafeFunction<void, NotifEvent, CallJsEvent>;
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;
173
+ // The main thread's environment's (InitNotifications), called from the
174
+ // centre's own thread, so through CALTsfn: once that environment has begun
175
+ // to end, an event is dropped rather than sent into it. Null until made;
176
+ // leaked with the process.
177
+ static std::atomic<CALTsfn*> gEvents{nullptr};
178
+ // What arrived before a listener, in arrival order. The main thread's: both
179
+ // the function's callback and pump2's replay run there.
164
180
  static std::vector<NotifEvent*> gHeld;
165
181
 
166
182
  static CALEvent EventRecord(const NotifEvent& ev) {
@@ -209,16 +225,19 @@ static void CallJsEvent(Napi::Env env, Napi::Function, void*, NotifEvent* ev) {
209
225
  CALRaiseUncaughtIfPending(env);
210
226
  }
211
227
 
212
- // From any thread: onto node's loop, then to the listener or the held list
213
- // — in pump mode. With threaded mode's channel open the record goes straight
214
- // into it from the centre's own thread.
228
+ // From any thread: onto the main thread's loop, then to the listener or the
229
+ // held list — in pump mode. With threaded mode's channel open the record
230
+ // goes straight into it from the centre's own thread. There is no function
231
+ // to cross on until the main thread has loaded the module, and until then
232
+ // nothing on the main thread could be listening either: dropped.
215
233
  static void QueueEvent(NotifEvent* ev) {
216
234
  if (CALChannelOpen()) {
217
235
  CALEmit(EventRecord(*ev));
218
236
  delete ev;
219
237
  return;
220
238
  }
221
- bool queued = gEvents.Use(false, [ev](napi_threadsafe_function f) {
239
+ CALTsfn* events = gEvents.load();
240
+ bool queued = events && events->Use(false, [ev](napi_threadsafe_function f) {
222
241
  return EventTsfn(f).NonBlockingCall(ev);
223
242
  });
224
243
  if (!queued) delete ev;
@@ -290,12 +309,7 @@ static UNNotificationCategory* DefaultCategory() {
290
309
  options:UNNotificationCategoryOptionCustomDismissAction];
291
310
  }
292
311
 
293
- static void ProbeCenter(Napi::Env env) {
294
- if (gProbed) return;
295
- gProbed = true;
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);
312
+ static void Probe() {
299
313
  @autoreleasepool {
300
314
  NSBundle* main = NSBundle.mainBundle;
301
315
  if (!main.bundleIdentifier) {
@@ -328,6 +342,8 @@ static void ProbeCenter(Napi::Env env) {
328
342
  }
329
343
  }
330
344
 
345
+ static void ProbeCenter() { std::call_once(gProbeOnce, Probe); }
346
+
331
347
  // The centre, or a thrown Error naming why there is none.
332
348
  static UNUserNotificationCenter* CenterOrThrow(Napi::Env env, const char* fn) {
333
349
  if (gCenter) return gCenter;
@@ -957,7 +973,19 @@ static Napi::Value PostNotificationResponse(const Napi::CallbackInfo& info) {
957
973
  // ---------------------------------------------------------------------------
958
974
 
959
975
  void InitNotifications(Napi::Env env, Napi::Object exports) {
960
- ProbeCenter(env);
976
+ ProbeCenter();
977
+ // The event function is the main thread's, made the once: pump mode calls
978
+ // the listener inline and only the main thread may (CALEmit), and the held
979
+ // list is the main thread's too. It used to be made in whichever
980
+ // environment loaded the module first — a worker's, if a worker got there
981
+ // first, and then every pump-mode response crossed to the worker's thread
982
+ // and was dropped there, for good once that worker ended, while the main
983
+ // thread sat with a listener installed.
984
+ if (pthread_main_np() && !gEvents.load()) {
985
+ EventTsfn events = EventTsfn::New(env, "appkit:notifications", 0, 1);
986
+ events.Unref(env); // events never hold the loop open by themselves
987
+ gEvents.store(new CALTsfn(CALTsfn::Watch(env, events)));
988
+ }
961
989
  exports.Set("notificationSettings",
962
990
  Napi::Function::New(env, NotificationSettings));
963
991
  exports.Set("requestNotificationAuthorization",