@windowkit/appkit 0.18.0 → 0.20.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
@@ -126,14 +126,15 @@ waits on the UI thread (`test/threaded-verbs.js` covers each row):
126
126
  | from a worker | verbs |
127
127
  | --- | --- |
128
128
  | unchanged, on the calling thread | surfaces, every `ctx*` (`ctxDrawSymbol` included), layouts and fonts, `symbolSize`, `pasteboardTypeForMIME`, `pasteboardTypeInfo`, `contentTypeFor`, `colorSpace` |
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` |
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`, `cancelPopUpMenu`; 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 |
132
132
  | | `createStatusItem`: its clicks carry the handle, and it is held until `removeStatusItem` |
133
133
  | | `requestUserAttention`: a bridge id |
134
134
  | | `openPanel` / `savePanel`: the answer through the callback, as before |
135
+ | | `popUpMenu`: the menu opens from a callout of its own, and answers through the callback |
135
136
  | the published copy | `getWindowFrame`, `windowIsVisible`, `windowNumber` (all `null` until the window is made), `listScreens`, `accessibilityDisplayOptions`, `activationPolicy`, `appInfo`, `pasteboardChangeCount` |
136
- | a callback, the last argument | `pasteboardReadText`, `snapshotWindow`, `snapshotStatusItem`, `windowNumberAtPoint`, `mainMenuInfo`, `dockMenuInfo`, `statusItemInfo`, `activateMenuItem`, `activateDockMenuItem`, `activateStatusItemMenuItem`, `clickStatusItem`, `dragItems`, `dragItemData`, `dragItemString`, `postDragEvent`. On the main thread each still answers synchronously when no callback is given. |
137
+ | a callback, the last argument | `pasteboardReadText`, `snapshotWindow`, `snapshotStatusItem`, `windowNumberAtPoint`, `mainMenuInfo`, `dockMenuInfo`, `statusItemInfo`, `activateMenuItem`, `activateDockMenuItem`, `activateStatusItemMenuItem`, `popUpMenuInfo`, `activatePopUpMenuItem`, `clickStatusItem`, `dragItems`, `dragItemData`, `dragItemString`, `postDragEvent`. On the main thread each still answers synchronously when no callback is given. |
137
138
  | events | `beginDrag`: `drag-session-began`, or `drag-session-ended` with nothing dropped. Its `provide` is a TypeError; give every value up front. |
138
139
 
139
140
  A few verbs behave differently from a worker:
@@ -283,6 +284,10 @@ card.animate('transform.rotation.z',
283
284
  card.animate('transform.translation.y',
284
285
  { values: [0, -6, 6, -6, 0], duration: 0.3, timing: [0.33, 1, 0.68, 1], id: 'shake' });
285
286
 
287
+ // a transform as a whole matrix, CSS's matrix(a, b, c, d, e, f) or matrix3d(…) —
288
+ // y grows down, as in CSS; see "Transforms as matrices"
289
+ card.set({ transform: { matrix: [0.87, 0.5, -0.5, 0.87, 0, 0] } });
290
+
286
291
  // text, two ways
287
292
  const label = new TextLayer();
288
293
  label.set({ frame: [0, 14, 228, 22], contentsScale: win.scale })
@@ -342,8 +347,9 @@ Three kinds, told apart by which option is present:
342
347
  | `{ 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
348
  | `{ 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
349
 
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.
350
+ A value — `from`, `to`, an entry of `values` — is a number, a point `[x, y]`, a colour
351
+ `[r, g, b, a]` in sRGB like every colour in this API, or a transform `{ matrix }` /
352
+ `{ matrix3d }` (below).
347
353
 
348
354
  Options every kind takes:
349
355
 
@@ -354,7 +360,7 @@ Options every kind takes:
354
360
  | `autoreverse` | turn around at the end of each pass |
355
361
  | `additive` | the values are deltas over the model value, and several in flight on one key path sum |
356
362
  | `cumulative` | each repetition starts where the last ended |
357
- | `delay` | seconds before it starts; the layer shows `from` while it waits (`fillMode: backwards`) |
363
+ | `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
364
  | `speed`, `timeOffset` | `CAMediaTiming`'s; `speed: 0` with a `timeOffset` is an animation paused at that time |
359
365
  | `hold` | keep the final value on screen after the end (`removedOnCompletion: NO`, `fillMode: forwards`) — the model value stays what it was |
360
366
  | `id` | report the end as a backend event (below) |
@@ -383,13 +389,39 @@ space's midpoint.
383
389
  a layer's `backgroundColor`, `borderColor` and `shadowColor`, a shape's fill and stroke,
384
390
  a gradient's stops, an animation's `from`/`to`, a presentation value, a text span's ink
385
391
  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
392
+ same colour rastered into a surface composite to the same pixels. An IOSurface says it
393
+ itself: those `createSurfaceIOSurface` makes and `surfaceFromIOSurfaceID` draws into name
394
+ sRGB as their colour space, and `setLayerContentsIOSurface` names one that names none — a
395
+ GL target — so a surface presented on a layer is matched to the display as a layer colour
396
+ is. Core Animation shows an IOSurface that names no space as the display's own numbers:
397
+ until these named theirs, a window presented that way went out on a wide-gamut panel as
398
+ the panel's own red, (255, 0, 0) in its space, beside a layer's sRGB red, (234, 51, 35),
399
+ and on a monitor with a profile of its own even a grey differed. (Before 0.6 the layer
387
400
  half was Generic RGB, which the compositor converts on its way to the display: `#dbe7f4`
388
401
  on a layer showed as (228, 236, 245) beside a surface's (219, 231, 244), and a colour
389
402
  animation landed on a model value that did not match its own `to`. A caller that draws
390
403
  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
404
  waiting for it, which is how `test/animation.js` checks every curve above.
392
405
 
406
+ **Transforms as matrices.** `setLayerProps`' `transform` takes Core Animation's
407
+ components — `{ translateX, translateY, rotate, scale, scaleX, scaleY }` — or a whole
408
+ matrix, in CSS's two spellings: `{ matrix: [a, b, c, d, e, f] }` is `matrix()`, a point
409
+ `(x, y)` going to `(a·x + c·y + e, b·x + d·y + f)` with the translation in points, and
410
+ `{ matrix3d: [m11, m12, …, m44] }` is `matrix3d()`, whose sixteen numbers are
411
+ `CATransform3D`'s in the order `presentationValue` reads one back. The same objects are
412
+ animation values, so a key path of `transform` can run keyframes a caller computed — a
413
+ CSS transform list sampled where CSS interpolates it, which `CATransform3D`'s own
414
+ interpolation would not reproduce for a turn of a whole circle or a mixed list. The
415
+ window's root layer is geometry-flipped, so y grows down here as it does in CSS: a
416
+ positive angle turns clockwise and a positive translation moves down, with no sign to
417
+ change on the way in. A matrix of the wrong length or with a number that is not finite
418
+ is a `TypeError`, and nothing is applied.
419
+
420
+ **`native.transformForms()`** — `['translate', 'rotate', 'scale', 'matrix', 'matrix3d']`:
421
+ the forms a transform takes on its way in. A caller that hands over matrices
422
+ feature-detects `matrix` here; before 0.19 an object holding one was read as no transform
423
+ at all, and refused as an animation value.
424
+
393
425
  **The end of an animation.** With an `id`, the animation's delegate forwards
394
426
  `animationDidStop:finished:` through `setBackendEventCallback` as
395
427
 
@@ -1174,6 +1206,50 @@ the item's window (pump afterwards; declined for left/right while a menu is
1174
1206
  set, since that click would open it), and `snapshotStatusItem(item, file)`
1175
1207
  writes the composited item to a PNG.
1176
1208
 
1209
+ ## Pop-up menu (a control's menu)
1210
+
1211
+ The menu that drops from a control in a window — a `<select>`'s list, a
1212
+ pop-up button's — the way `NSPopUpButton`'s does: the current item placed
1213
+ over the control and checked, the menu at least the control's width, in the
1214
+ font asked for. It is run through an `NSPopUpButtonCell` that is never drawn,
1215
+ `performClickWithFrame:inView:`, which is what a browser does for a
1216
+ `<select>` on macOS, so the placement, the tracking (type-select, the scroll
1217
+ arrows of a long menu, VoiceOver) and the look are AppKit's own. The items
1218
+ are `setMainMenu`'s vocabulary.
1219
+
1220
+ ```js
1221
+ const menu = native.popUpMenu(win, {
1222
+ items: [ // setMainMenu's item vocabulary
1223
+ { id: 1, title: 'Default' },
1224
+ { id: 2, title: 'Retro' },
1225
+ { separator: true },
1226
+ { id: 3, title: 'Chaos', enabled: false },
1227
+ ],
1228
+ frame: [40, 60, 220, 24], // the control, in the window's content, top-left, points
1229
+ selected: 2, // placed over the control, checked; absent: none is
1230
+ fontSize: 13, // the menu's font; the menu font at its own size by default
1231
+ fontFamily: 'Avenir Next', // a family the system has, else the menu font at fontSize
1232
+ appearance: 'dark', // 'light' | 'dark'; absent: the window's
1233
+ rtl: false,
1234
+ }, (id) => {
1235
+ // the id chosen, or null for a menu dismissed (Escape, a click outside, cancelPopUpMenu)
1236
+ });
1237
+ native.cancelPopUpMenu(menu); // ends the tracking: the callback answers null
1238
+ ```
1239
+
1240
+ Tracking is a modal loop. In pump mode it runs inside the call, the thread
1241
+ being AppKit's for the length of the gesture, and the callback has run when
1242
+ the call returns. From a worker the handle is answered at the call, the menu
1243
+ opens from a callout of its own, the answer arrives through the callback, and
1244
+ `cancelPopUpMenu` can end it while it is open.
1245
+
1246
+ For tests: `popUpMenuInfo(menu)` returns an open pop-up as `mainMenuInfo`'s
1247
+ shape plus `fontFamily`, `fontSize`, `appearance` and `rtl`, and null once
1248
+ it has answered; `activatePopUpMenuItem(menu, index)` chooses an item the
1249
+ way tracking would and ends the tracking. In pump mode, keys posted with
1250
+ `postKeyEvent` before the call are read by the tracking as a person's would
1251
+ be (`test/popup-menu.js`).
1252
+
1177
1253
  ## Dock & app presence
1178
1254
 
1179
1255
  The handful of things an app shows outside its own windows — the Dock tile and the name
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@windowkit/appkit",
3
- "version": "0.18.0",
3
+ "version": "0.20.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/surface-faded.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"
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/popup-menu.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,
@@ -2222,6 +2259,278 @@ static Napi::Value ActivateMenuItemFn(const Napi::CallbackInfo& info) {
2222
2259
  });
2223
2260
  }
2224
2261
 
2262
+ // ---------------------------------------------------------------------------
2263
+ // pop-up menus — a menu that drops from a control in a window, the way an
2264
+ // NSPopUpButton's does: the chosen item placed over the control, the menu
2265
+ // at least the control's width, the current item checked. What a <select>
2266
+ // and a context menu want, and what a drawn menu can only imitate: its
2267
+ // vibrancy needs private API to reproduce, and its tracking (type-select,
2268
+ // the scroll arrows of a long menu, VoiceOver) is AppKit's.
2269
+ //
2270
+ // Run through an NSPopUpButtonCell that is never drawn, which is what a
2271
+ // browser does for a <select>: performClickWithFrame:inView: places and
2272
+ // tracks the menu exactly as the control would, over the frame given, in
2273
+ // the cell's font. Tracking is a modal loop, so the answer is a callback:
2274
+ // in pump mode it runs before the call returns, the thread having been
2275
+ // AppKit's for the length of the gesture; from a worker the menu is opened
2276
+ // from a callout of its own (CALOnUIModal) and answers through a
2277
+ // threadsafe function, and cancelPopUpMenu can end it.
2278
+ // ---------------------------------------------------------------------------
2279
+
2280
+ static Napi::Value BCommandAnswer(Napi::Env env, bool ok);
2281
+
2282
+ // An item's action records the choice rather than emitting `menu-activate`:
2283
+ // a pop-up answers its caller, once, and a dismissal is an answer too.
2284
+ @interface CALPopUpTarget : CALMenuTarget {
2285
+ @public
2286
+ bool picked_;
2287
+ NSInteger chosen_;
2288
+ }
2289
+ @end
2290
+ @implementation CALPopUpTarget
2291
+ - (void)activate:(NSMenuItem*)sender {
2292
+ picked_ = true;
2293
+ chosen_ = sender.tag;
2294
+ }
2295
+ @end
2296
+
2297
+ struct PopUpSpec {
2298
+ std::vector<MenuItemSpec> items;
2299
+ double frame[4] = {0, 0, 0, 0}; // the control: x, y, width, height
2300
+ bool hasSelected = false;
2301
+ NSInteger selected = 0;
2302
+ double fontSize = 0; // 0: the menu font's own size
2303
+ NSString* fontFamily = @""; // a family the system knows, or the menu font
2304
+ NSString* appearance = @""; // "light" | "dark" | "": the window's
2305
+ bool rtl = false;
2306
+ };
2307
+
2308
+ static PopUpSpec ParsePopUpSpec(Napi::Object o) {
2309
+ PopUpSpec s;
2310
+ Napi::Value items = o.Get("items");
2311
+ if (items.IsArray()) s.items = ParseMenuItems(items.As<Napi::Array>());
2312
+ Napi::Value frame = o.Get("frame");
2313
+ if (frame.IsArray()) {
2314
+ Napi::Array a = frame.As<Napi::Array>();
2315
+ for (uint32_t i = 0; i < 4 && i < a.Length(); i++) {
2316
+ Napi::Value v = a.Get(i);
2317
+ if (v.IsNumber()) s.frame[i] = v.As<Napi::Number>().DoubleValue();
2318
+ }
2319
+ }
2320
+ Napi::Value sel = o.Get("selected");
2321
+ if (sel.IsNumber()) {
2322
+ s.hasSelected = true;
2323
+ s.selected = (NSInteger)sel.As<Napi::Number>().Int64Value();
2324
+ }
2325
+ s.fontSize = BNumOr(o, "fontSize", 0);
2326
+ s.fontFamily = BStrOr(o, "fontFamily", @"");
2327
+ s.appearance = BStrOr(o, "appearance", @"");
2328
+ s.rtl = BBoolOr(o, "rtl", false);
2329
+ return s;
2330
+ }
2331
+
2332
+ // The family asked for when the system has it — a face it matched under
2333
+ // another name is not it — and the menu font at that size otherwise.
2334
+ static NSFont* PopUpFont(NSString* family, double size) {
2335
+ CGFloat sz = size > 0 ? size : [NSFont systemFontSize];
2336
+ if (family.length) {
2337
+ NSFontDescriptor* d = [NSFontDescriptor
2338
+ fontDescriptorWithFontAttributes:@{NSFontFamilyAttribute : family}];
2339
+ NSFont* f = [NSFont fontWithDescriptor:d size:sz];
2340
+ if (f && [f.familyName caseInsensitiveCompare:family] == NSOrderedSame) return f;
2341
+ }
2342
+ return [NSFont menuFontOfSize:size > 0 ? size : 0];
2343
+ }
2344
+
2345
+ // What a pop-up owes JS, hung on its menu: pump mode's callback, or a
2346
+ // worker's threadsafe function.
2347
+ @interface CALPopUpPending : NSObject {
2348
+ @public
2349
+ napi_env env_;
2350
+ Napi::FunctionReference cb_;
2351
+ bool threaded_;
2352
+ CALTsfn tsfn_;
2353
+ }
2354
+ @end
2355
+ @implementation CALPopUpPending
2356
+ @end
2357
+
2358
+ static char kPopUpPendingKey;
2359
+
2360
+ // The menu as the spec describes it, and the cell that will run it.
2361
+ static NSPopUpButtonCell* MakePopUp(const PopUpSpec& spec, CALPopUpTarget* target) {
2362
+ NSMenu* menu = BuildMenu(spec.items, target);
2363
+ NSFont* font = PopUpFont(spec.fontFamily, spec.fontSize);
2364
+ menu.font = font;
2365
+ if ([spec.appearance isEqualToString:@"dark"]) {
2366
+ menu.appearance = [NSAppearance appearanceNamed:NSAppearanceNameDarkAqua];
2367
+ } else if ([spec.appearance isEqualToString:@"light"]) {
2368
+ menu.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua];
2369
+ }
2370
+ if (spec.rtl) {
2371
+ menu.userInterfaceLayoutDirection = NSUserInterfaceLayoutDirectionRightToLeft;
2372
+ }
2373
+ NSPopUpButtonCell* cell = [[NSPopUpButtonCell alloc] initTextCell:@"" pullsDown:NO];
2374
+ cell.autoenablesItems = NO;
2375
+ cell.font = font;
2376
+ cell.menu = menu;
2377
+ NSInteger at = spec.hasSelected ? [menu indexOfItemWithTag:spec.selected] : -1;
2378
+ if (at >= 0) [cell selectItemAtIndex:at];
2379
+ else [cell selectItem:nil];
2380
+ return cell;
2381
+ }
2382
+
2383
+ // Track it over the control, on the UI thread, and say what was chosen.
2384
+ static CALValueBlock TrackPopUp(NSPopUpButtonCell* cell, CALPopUpTarget* target,
2385
+ NSWindow* win, const PopUpSpec& spec) {
2386
+ if (win && win.contentView) {
2387
+ NSView* view = win.contentView;
2388
+ double x = spec.frame[0], y = spec.frame[1];
2389
+ double w = spec.frame[2], h = spec.frame[3];
2390
+ // the frame is top-left, as every rect here is
2391
+ NSRect r = NSMakeRect(x, view.isFlipped ? y : view.bounds.size.height - y - h, w, h);
2392
+ [cell attachPopUpWithFrame:r inView:view];
2393
+ [cell performClickWithFrame:r inView:view];
2394
+ [cell dismissPopUp];
2395
+ }
2396
+ bool picked = target->picked_;
2397
+ double chosen = (double)target->chosen_;
2398
+ return ^Napi::Value(Napi::Env e) {
2399
+ return picked ? Napi::Value(Napi::Number::New(e, chosen)) : Napi::Value(e.Null());
2400
+ };
2401
+ }
2402
+
2403
+ // The one place a pop-up answers; the pending record comes off first.
2404
+ static void FinishPopUp(NSMenu* menu, CALValueBlock answer) {
2405
+ CALPopUpPending* p = objc_getAssociatedObject(menu, &kPopUpPendingKey);
2406
+ if (!p) return;
2407
+ objc_setAssociatedObject(menu, &kPopUpPendingKey, nil,
2408
+ OBJC_ASSOCIATION_RETAIN_NONATOMIC);
2409
+ if (p->threaded_) {
2410
+ CALReply(p->tsfn_, answer);
2411
+ return;
2412
+ }
2413
+ Napi::Env env(p->env_);
2414
+ Napi::HandleScope scope(env);
2415
+ Napi::Value result = answer(env);
2416
+ Napi::FunctionReference cb = std::move(p->cb_);
2417
+ cb.Call({result});
2418
+ }
2419
+
2420
+ // popUpMenu(win, spec, cb) -> menu handle
2421
+ // spec: { items, // setMainMenu's item vocabulary
2422
+ // frame: [x, y, w, h], // the control, in the window's content,
2423
+ // // top-left, points
2424
+ // selected?, // the id placed over the control, checked
2425
+ // fontSize?, fontFamily?,// the menu's font; the menu font otherwise
2426
+ // appearance?: 'light' | 'dark', rtl? }
2427
+ // cb(id | null) — the item chosen, or null for a menu dismissed
2428
+ static Napi::Value PopUpMenuFn(const Napi::CallbackInfo& info) {
2429
+ Napi::Env env = info.Env();
2430
+ if (!info[0].IsExternal() || !info[1].IsObject() || !info[2].IsFunction()) {
2431
+ Napi::TypeError::New(env, "popUpMenu(win, spec, cb): window handle, spec object and callback required")
2432
+ .ThrowAsJavaScriptException();
2433
+ return env.Undefined();
2434
+ }
2435
+ id owner = CALHandleTarget(info[0]);
2436
+ PopUpSpec spec = ParsePopUpSpec(info[1].As<Napi::Object>());
2437
+
2438
+ if (pthread_main_np()) {
2439
+ BEnsureApp();
2440
+ CALPopUpTarget* target = [CALPopUpTarget new];
2441
+ target->source_ = "popup";
2442
+ NSPopUpButtonCell* cell = MakePopUp(spec, target);
2443
+ CALPopUpPending* p = [CALPopUpPending new];
2444
+ p->env_ = (napi_env)env;
2445
+ p->cb_ = Napi::Persistent(info[2].As<Napi::Function>());
2446
+ p->threaded_ = false;
2447
+ objc_setAssociatedObject(cell.menu, &kPopUpPendingKey, p,
2448
+ OBJC_ASSOCIATION_RETAIN_NONATOMIC);
2449
+ Napi::Value handle = BWrapRetained(env, cell.menu);
2450
+ FinishPopUp(cell.menu, TrackPopUp(cell, target, owner ? CALResolve(owner) : nil, spec));
2451
+ return handle;
2452
+ }
2453
+
2454
+ CALHandle* h = CALNewHandle();
2455
+ Napi::Value handle = CALWrapHandle(env, h, false);
2456
+ CALTsfn tsfn = CALReplyTo(env, info[2].As<Napi::Function>(), "appkit:popUpMenu");
2457
+ CALOnUIModal(^{
2458
+ BEnsureApp();
2459
+ CALPopUpTarget* target = [CALPopUpTarget new];
2460
+ target->source_ = "popup";
2461
+ NSPopUpButtonCell* cell = MakePopUp(spec, target);
2462
+ CALPopUpPending* p = [CALPopUpPending new];
2463
+ p->threaded_ = true;
2464
+ p->tsfn_ = tsfn;
2465
+ objc_setAssociatedObject(cell.menu, &kPopUpPendingKey, p,
2466
+ OBJC_ASSOCIATION_RETAIN_NONATOMIC);
2467
+ h->object_ = cell.menu;
2468
+ FinishPopUp(cell.menu, TrackPopUp(cell, target, owner ? CALResolve(owner) : nil, spec));
2469
+ });
2470
+ return handle;
2471
+ }
2472
+
2473
+ // cancelPopUpMenu(menu) -> bool — end the tracking: the pop-up answers null.
2474
+ // A pop-up that has answered already is left alone.
2475
+ static Napi::Value CancelPopUpMenuFn(const Napi::CallbackInfo& info) {
2476
+ Napi::Env env = info.Env();
2477
+ if (!info[0].IsExternal()) {
2478
+ Napi::TypeError::New(env, "cancelPopUpMenu: menu handle required")
2479
+ .ThrowAsJavaScriptException();
2480
+ return env.Undefined();
2481
+ }
2482
+ id target = CALHandleTarget(info[0]);
2483
+ __block bool ok = false;
2484
+ CALOnUI(^{
2485
+ NSMenu* menu = CALResolve(target);
2486
+ if (!menu || !objc_getAssociatedObject(menu, &kPopUpPendingKey)) return;
2487
+ [menu cancelTrackingWithoutAnimation];
2488
+ ok = true;
2489
+ });
2490
+ return BCommandAnswer(env, ok);
2491
+ }
2492
+
2493
+ // popUpMenuInfo(menu, cb?) — an open pop-up as data, for tests: the tree in
2494
+ // mainMenuInfo's shape, its font and its appearance; null once it answered.
2495
+ static Napi::Value PopUpMenuInfoFn(const Napi::CallbackInfo& info) {
2496
+ id target = CALHandleTarget(info[0]);
2497
+ return CALAnswer(info, "popUpMenuInfo", ^CALValueBlock {
2498
+ NSMenu* menu = CALResolve(target);
2499
+ if (!menu || !objc_getAssociatedObject(menu, &kPopUpPendingKey)) {
2500
+ return ^Napi::Value(Napi::Env e) { return e.Null(); };
2501
+ }
2502
+ std::shared_ptr<MenuInfoData> data = MenuInfoOf(menu);
2503
+ std::string family = menu.font.familyName.UTF8String ?: "";
2504
+ double size = menu.font.pointSize;
2505
+ std::string appearance = menu.appearance.name.UTF8String ?: "";
2506
+ bool rtl = menu.userInterfaceLayoutDirection == NSUserInterfaceLayoutDirectionRightToLeft;
2507
+ return ^Napi::Value(Napi::Env e) {
2508
+ Napi::Object o = MenuInfoValue(e, *data);
2509
+ o.Set("fontFamily", family);
2510
+ o.Set("fontSize", size);
2511
+ o.Set("appearance", appearance);
2512
+ o.Set("rtl", rtl);
2513
+ return o;
2514
+ };
2515
+ });
2516
+ }
2517
+
2518
+ // activatePopUpMenuItem(menu, index, cb?) -> bool — choose an open pop-up's
2519
+ // item by index, the way tracking would, and end the tracking. For tests.
2520
+ static Napi::Value ActivatePopUpMenuItemFn(const Napi::CallbackInfo& info) {
2521
+ id target = CALHandleTarget(info[0]);
2522
+ NSInteger index = info.Length() > 1 && info[1].IsNumber()
2523
+ ? (NSInteger)info[1].As<Napi::Number>().Int64Value()
2524
+ : -1;
2525
+ return CALAnswer(info, "activatePopUpMenuItem", ^CALValueBlock {
2526
+ NSMenu* menu = CALResolve(target);
2527
+ bool ok = menu && objc_getAssociatedObject(menu, &kPopUpPendingKey) &&
2528
+ ActivateInMenu(menu, {index});
2529
+ if (ok) [menu cancelTrackingWithoutAnimation];
2530
+ return BoolAnswer(ok);
2531
+ });
2532
+ }
2533
+
2225
2534
  // ---------------------------------------------------------------------------
2226
2535
  // status items — NSStatusItem, the menu-bar extra (the "tray"). The cocoa
2227
2536
  // counterpart of the freedesktop StatusNotifierItem: an icon or a title in
@@ -7330,6 +7639,10 @@ void InitBackend(Napi::Env env, Napi::Object exports) {
7330
7639
  BFN("setDockMenu", SetDockMenuFn);
7331
7640
  BFN("dockMenuInfo", DockMenuInfoFn);
7332
7641
  BFN("activateDockMenuItem", ActivateDockMenuItemFn);
7642
+ BFN("popUpMenu", PopUpMenuFn);
7643
+ BFN("cancelPopUpMenu", CancelPopUpMenuFn);
7644
+ BFN("popUpMenuInfo", PopUpMenuInfoFn);
7645
+ BFN("activatePopUpMenuItem", ActivatePopUpMenuItemFn);
7333
7646
  BFN("initApp", InitAppFn);
7334
7647
  BFN("setActivationPolicy", SetActivationPolicyFn);
7335
7648
  BFN("setDockBadge", SetDockBadgeFn);