@windowkit/appkit 0.4.0 → 0.5.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/index.js CHANGED
@@ -74,13 +74,21 @@ class Layer {
74
74
  }
75
75
  }
76
76
 
77
- // Explicit CABasicAnimation on any animatable keyPath, e.g.
78
- // 'transform.rotation.z', 'position', 'opacity', 'strokeEnd', 'backgroundColor'.
77
+ // Explicit animation on any animatable keyPath, e.g. 'transform.rotation.z',
78
+ // 'position', 'opacity', 'strokeEnd', 'backgroundColor': a CABasicAnimation
79
+ // ({ from, to }), a CAKeyframeAnimation ({ values }) or a CASpringAnimation
80
+ // ({ spring }) — README "Animations" lists the options. Returns the layer;
81
+ // native.addAnimation returns the duration the animation will take (a
82
+ // spring's settling time).
79
83
  animate(keyPath, opts = {}, key = keyPath) {
80
84
  native.addAnimation(this._h, keyPath, opts, key);
81
85
  return this;
82
86
  }
83
87
 
88
+ // The value the render server is showing for a key path right now,
89
+ // animations applied — null before the layer's first commit.
90
+ presentationValue(keyPath) { return native.presentationValue(this._h, keyPath); }
91
+
84
92
  removeAnimation(key) { native.removeAnimation(this._h, key); }
85
93
  removeAllAnimations() { native.removeAllAnimations(this._h); }
86
94
 
@@ -130,7 +138,8 @@ class Window {
130
138
  snapshot(file) { return native.snapshotWindow(this._h, file); } // renderInContext -> PNG
131
139
  }
132
140
 
133
- // Group property changes into one CATransaction (shared animation duration/timing).
141
+ // Group property changes into one CATransaction (shared animation duration and
142
+ // timing — a curve name or cubic-bezier control points [x1, y1, x2, y2]).
134
143
  function transaction(fn, opts = {}) {
135
144
  native.txBegin(opts);
136
145
  try { fn(); } finally { native.txCommit(); }
@@ -178,7 +187,73 @@ const controls = {
178
187
  isDark: () => native.appearanceIsDark(),
179
188
  };
180
189
 
190
+ // Privacy (TCC) authorizations. kind: 'camera' | 'microphone' |
191
+ // 'screen-recording' | 'accessibility' | 'input-monitoring' | 'location' |
192
+ // 'automation' (with { target: bundleId }). Status and request never touch
193
+ // policy: the renderer decides when to ask and what to do with a refusal.
194
+ const permissions = {
195
+ // -> 'authorized' | 'denied' | 'restricted' | 'notDetermined'; never prompts
196
+ status: (kind, opts) => native.authorizationStatus(kind, opts),
197
+ // Raises the system prompt where macOS has one; resolves to granted. Screen
198
+ // recording and accessibility can only be granted in Settings, so their
199
+ // prompt is the system's go-to-Settings dialog and this resolves at once.
200
+ request: (kind, opts) =>
201
+ new Promise((resolve) => native.requestAuthorization(kind, opts, resolve)),
202
+ // Best-effort deep link to the Privacy pane (or its top level with no kind);
203
+ // also takes 'files-and-folders' and 'full-disk-access'.
204
+ openSettings: (kind) => native.openPrivacySettings(kind),
205
+ };
206
+
207
+ // Desktop notifications through UNUserNotificationCenter — the macOS
208
+ // counterpart of org.freedesktop.Notifications. Mechanism only: what to say,
209
+ // when to ask and what to do with a refusal stay in the renderer. Banners
210
+ // are attributed to an app bundle, so a bare `node` process can post none:
211
+ // read settings().available first (it carries the reason when false) and
212
+ // fall to another rung; every other call throws in that state rather than
213
+ // dropping silently. Responses arrive as backend events, through
214
+ // native.setBackendEventCallback: 'notification-action' { identifier,
215
+ // actionId ('default' for a click on the banner itself), categoryId,
216
+ // userInfo } and 'notification-dismissed' { identifier, reason, ... }.
217
+ const notifications = {
218
+ // -> { available: false, bundleIdentifier, reason } | { available: true,
219
+ // bundleIdentifier, authorizationStatus: 'notDetermined' | 'denied' |
220
+ // 'authorized' | 'provisional', alert, sound, badge, ... }
221
+ settings: () => new Promise((resolve) => native.notificationSettings(resolve)),
222
+ // The system prompt, once per app; resolves to granted (boolean).
223
+ requestAuthorization: (options = ['alert', 'sound', 'badge']) =>
224
+ new Promise((resolve, reject) =>
225
+ native.requestNotificationAuthorization(options, (granted, err) =>
226
+ err ? reject(err) : resolve(granted))),
227
+ // [{ id, actions: [{ id, title, destructive?, foreground? }] }] — the action
228
+ // sets a notification's categoryId can name; replaces the whole set.
229
+ setCategories: (categories) => native.setNotificationCategories(categories),
230
+ // { identifier?, title, subtitle?, body?, sound?: 'default' | null,
231
+ // categoryId?, userInfo?, threadId?, badge? } -> identifier, once the
232
+ // system has accepted it (rejects while the app is not authorized).
233
+ post: (props) =>
234
+ new Promise((resolve, reject) => {
235
+ const id = native.postNotification(props, (err) => (err ? reject(err) : resolve(id)));
236
+ }),
237
+ // The same identifier again replaces the banner in place.
238
+ update: (identifier, props) =>
239
+ new Promise((resolve, reject) => {
240
+ native.updateNotification(identifier, props, (err) => (err ? reject(err) : resolve(identifier)));
241
+ }),
242
+ remove: (identifiers) => native.removeNotification(identifiers),
243
+ // readback: what is in Notification Center for this app, and the categories
244
+ delivered: () => new Promise((resolve) => native.deliveredNotifications(resolve)),
245
+ categories: () => new Promise((resolve) => native.notificationCategories(resolve)),
246
+ };
247
+
248
+ const accessibility = {
249
+ // System Settings › Accessibility › Display, as NSWorkspace reports it:
250
+ // { reduceMotion, reduceTransparency, increaseContrast, differentiateWithoutColor, invertColors }.
251
+ // A change arrives as an 'accessibility-display-changed' backend event with the same fields;
252
+ // install the callback first, then read this (README "Accessibility display options").
253
+ displayOptions: () => native.accessibilityDisplayOptions(),
254
+ };
255
+
181
256
  module.exports = {
182
257
  app, Window, Layer, TextLayer, GradientLayer, ShapeLayer,
183
- transaction, withoutAnimations, text, controls, native,
258
+ transaction, withoutAnimations, text, controls, permissions, notifications, accessibility, native,
184
259
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@windowkit/appkit",
3
- "version": "0.4.0",
3
+ "version": "0.5.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",
@@ -42,7 +42,8 @@
42
42
  "scripts": {
43
43
  "install": "node scripts/install.js",
44
44
  "build": "node-gyp rebuild",
45
- "demo": "node demo/demo.js"
45
+ "demo": "node demo/demo.js",
46
+ "test": "node test/app-lifecycle.js && node test/animation.js && node test/accessibility-display.js"
46
47
  },
47
48
  "dependencies": {
48
49
  "node-addon-api": "^8.3.0"
Binary file
package/src/addon.mm CHANGED
@@ -93,22 +93,11 @@ static Napi::Value WrapRetained(Napi::Env env, id obj) {
93
93
  - (void)keyDown:(NSEvent*)event { (void)event; }
94
94
  @end
95
95
 
96
- static bool gAppInited = false;
97
-
98
- static void EnsureApp() {
99
- if (gAppInited) return;
100
- @autoreleasepool {
101
- [NSApplication sharedApplication];
102
- [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
103
- [NSApp finishLaunching];
104
- }
105
- gAppInited = true;
106
- }
107
-
108
- static Napi::Value InitApp(const Napi::CallbackInfo& info) {
109
- EnsureApp();
110
- return info.Env().Undefined();
111
- }
96
+ // src/backend.mm owns the NSApplication setup (activation policy, no window
97
+ // tabbing, the app delegate that must precede finishLaunching); both faces
98
+ // of the addon share the one call so finishLaunching runs once.
99
+ void BEnsureApp();
100
+ static void EnsureApp() { BEnsureApp(); }
112
101
 
113
102
  static Napi::Value CreateWindowFn(const Napi::CallbackInfo& info) {
114
103
  Napi::Env env = info.Env();
@@ -127,6 +116,7 @@ static Napi::Value CreateWindowFn(const Napi::CallbackInfo& info) {
127
116
  backing:NSBackingStoreBuffered
128
117
  defer:NO];
129
118
  win.releasedWhenClosed = NO;
119
+ win.tabbingMode = NSWindowTabbingModeDisallowed;
130
120
  win.title = title;
131
121
  win.acceptsMouseMovedEvents = YES;
132
122
 
@@ -257,6 +247,7 @@ static Napi::Value PostMouseEvent(const Napi::CallbackInfo& info) {
257
247
  static Napi::Value SetEventCallback(const Napi::CallbackInfo& info) {
258
248
  if (info[0].IsFunction()) {
259
249
  gEventCb = Napi::Persistent(info[0].As<Napi::Function>());
250
+ gEventCb.SuppressDestruct(); // static: outlives the env, see backend.mm
260
251
  } else {
261
252
  gEventCb.Reset();
262
253
  }
@@ -524,7 +515,31 @@ static Napi::Value SetShapeProps(const Napi::CallbackInfo& info) {
524
515
  // ---------------------------------------------------------------------------
525
516
  // animations & transactions
526
517
  // ---------------------------------------------------------------------------
518
+ //
519
+ // Mechanism for a renderer that keeps its own model of what is animating
520
+ // (react-x11's transitions and loops, windowkit/appkit#29): the layer's
521
+ // model value is set under disableActions and an explicit animation carries
522
+ // the pixels from `from` to `to` — or through `values` — while the render
523
+ // server interpolates. Beyond CA's own vocabulary, four things let a
524
+ // renderer's timing model stay the truth about an animation it no longer
525
+ // ticks: a curve given as control points, which the renderer can evaluate
526
+ // identically on its side (a name means whatever each side thinks it
527
+ // means); an additive animation, so a retarget carries on from wherever the
528
+ // last one got to with nothing read back; a delay that shows `from` while it
529
+ // waits; and the presentation value plus the completion event, which say
530
+ // where an animation is and when it stopped.
531
+
532
+ // backend.mm's event callback, for the completion event.
533
+ bool CALHasBackendCb();
534
+ void CALEmitBackendEvent(Napi::Env env, Napi::Object ev);
535
+
536
+ static bool ThrowType(Napi::Env env, const char* msg) {
537
+ Napi::TypeError::New(env, msg).ThrowAsJavaScriptException();
538
+ return false;
539
+ }
527
540
 
541
+ // A number, a point [x, y] or a colour [r, g, b(, a)] — the value types a key
542
+ // path takes here. nil for anything else, which the caller reports.
528
543
  static id AnimValue(Napi::Value v) {
529
544
  if (v.IsNumber()) return @(v.As<Napi::Number>().DoubleValue());
530
545
  if (v.IsArray()) {
@@ -538,35 +553,271 @@ static id AnimValue(Napi::Value v) {
538
553
  return nil;
539
554
  }
540
555
 
541
- static CAMediaTimingFunction* TimingFn(NSString* name) {
542
- if ([name isEqualToString:@"linear"]) return [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
543
- if ([name isEqualToString:@"easeIn"]) return [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
544
- if ([name isEqualToString:@"easeOut"]) return [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
545
- if ([name isEqualToString:@"easeInEaseOut"]) return [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
546
- return [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault];
556
+ // A timing function: one of CA's names (their CSS spellings are accepted
557
+ // too — they are the same four curves), or the control points of a cubic
558
+ // bezier. nil with a TypeError pending for anything else: an animation on
559
+ // the wrong curve is the kind of bug nobody files, they just think the app
560
+ // feels off.
561
+ static CAMediaTimingFunction* TimingFrom(Napi::Env env, Napi::Value v) {
562
+ if (v.IsString()) {
563
+ NSString* name = ToNSString(v);
564
+ if ([name isEqualToString:@"linear"])
565
+ return [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
566
+ if ([name isEqualToString:@"easeIn"] || [name isEqualToString:@"ease-in"])
567
+ return [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
568
+ if ([name isEqualToString:@"easeOut"] || [name isEqualToString:@"ease-out"])
569
+ return [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
570
+ if ([name isEqualToString:@"easeInEaseOut"] || [name isEqualToString:@"ease-in-out"])
571
+ return [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
572
+ if ([name isEqualToString:@"default"] || [name isEqualToString:@"ease"])
573
+ return [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault];
574
+ ThrowType(env, "timing: expected linear, easeIn, easeOut, easeInEaseOut, default "
575
+ "(or the CSS spellings) or control points [x1, y1, x2, y2]");
576
+ return nil;
577
+ }
578
+ if (v.IsArray()) {
579
+ Napi::Array a = v.As<Napi::Array>();
580
+ float p[4] = {0, 0, 0, 0};
581
+ bool ok = a.Length() == 4;
582
+ for (uint32_t i = 0; ok && i < 4; i++) {
583
+ Napi::Value e = a.Get(i);
584
+ ok = e.IsNumber() && std::isfinite(e.As<Napi::Number>().DoubleValue());
585
+ if (ok) p[i] = (float)e.As<Napi::Number>().DoubleValue();
586
+ }
587
+ // x is time: it has to stay inside the unit interval for the curve to be
588
+ // a function of it. y may overshoot — that is what a back-out curve is.
589
+ if (ok) ok = p[0] >= 0 && p[0] <= 1 && p[2] >= 0 && p[2] <= 1;
590
+ if (!ok) {
591
+ ThrowType(env, "timing: control points are [x1, y1, x2, y2], finite, with x1 and x2 in 0..1");
592
+ return nil;
593
+ }
594
+ return [CAMediaTimingFunction functionWithControlPoints:p[0]:p[1]:p[2]:p[3]];
595
+ }
596
+ ThrowType(env, "timing: expected a curve name or control points [x1, y1, x2, y2]");
597
+ return nil;
547
598
  }
548
599
 
549
- // addAnimation(layer, keyPath, opts, key)
600
+ // The completion event. A delegate is set only when the caller passes an
601
+ // `id`, so an animation nobody wants to hear about costs nothing; CAAnimation
602
+ // holds its delegate strongly, so this lives exactly as long as the animation.
603
+ // animationDidStop: arrives on the main thread from the run loop the pump
604
+ // drives — inside pump2(), like a window delegate's methods — so it calls
605
+ // into JS directly. `finished` is NO for an animation that was removed, or
606
+ // whose layer left the tree, before it ran out.
607
+ @interface CALAnimationDelegate : NSObject <CAAnimationDelegate>
608
+ @property(nonatomic, assign) napi_env env;
609
+ @property(nonatomic, copy) NSString* animId;
610
+ @property(nonatomic, copy) NSString* key;
611
+ @property(nonatomic, copy) NSString* keyPath;
612
+ @end
613
+
614
+ @implementation CALAnimationDelegate
615
+ - (void)animationDidStop:(CAAnimation*)anim finished:(BOOL)flag {
616
+ if (!CALHasBackendCb()) return;
617
+ Napi::Env env(self.env);
618
+ Napi::HandleScope scope(env);
619
+ Napi::Object ev = Napi::Object::New(env);
620
+ ev.Set("type", "animation-end");
621
+ ev.Set("id", self.animId.UTF8String);
622
+ ev.Set("key", self.key.UTF8String);
623
+ ev.Set("keyPath", self.keyPath.UTF8String);
624
+ ev.Set("finished", Napi::Boolean::New(env, flag));
625
+ CALEmitBackendEvent(env, ev);
626
+ }
627
+ @end
628
+
629
+ // What every animation kind shares: repetition, the curve, additive, a
630
+ // delay, speed/timeOffset, hold, and the completion delegate. false with a
631
+ // TypeError pending.
632
+ static bool ApplyTiming(Napi::Env env, CAPropertyAnimation* a, CALayer* L, Napi::Object o,
633
+ NSString* key) {
634
+ double rep = NumOr(o, "repeat", 0);
635
+ if (rep > 0) a.repeatCount = std::isinf(rep) ? HUGE_VALF : (float)rep;
636
+ a.autoreverses = BoolOr(o, "autoreverse", false);
637
+ if (o.Has("timing")) {
638
+ CAMediaTimingFunction* fn = TimingFrom(env, o.Get("timing"));
639
+ if (!fn) return false;
640
+ a.timingFunction = fn;
641
+ }
642
+ // Additive: the animation's values are deltas over the model value, and
643
+ // several in flight on one key path sum. That is how a retarget stays
644
+ // continuous — the model goes straight to the new target, the animation
645
+ // runs (old − new) → 0 — and why nothing has to be read back for it.
646
+ a.additive = BoolOr(o, "additive", false);
647
+ a.cumulative = BoolOr(o, "cumulative", false);
648
+ // speed 0 with a timeOffset is an animation paused at that time: how a
649
+ // caller pauses one, and how a test samples a curve without waiting for it
650
+ if (o.Has("speed")) a.speed = (float)NumOr(o, "speed", 1);
651
+ if (o.Has("timeOffset")) a.timeOffset = NumOr(o, "timeOffset", 0);
652
+ bool hold = BoolOr(o, "hold", false);
653
+ double delay = NumOr(o, "delay", 0);
654
+ if (delay > 0) {
655
+ // in the layer's own time — the media time unless the layer itself has
656
+ // been slowed or offset
657
+ a.beginTime = [L convertTime:CACurrentMediaTime() fromLayer:nil] + delay;
658
+ // and the layer shows `from` while it waits, rather than the model value
659
+ // it is about to leave and then snap back from
660
+ a.fillMode = hold ? kCAFillModeBoth : kCAFillModeBackwards;
661
+ }
662
+ if (hold) {
663
+ a.removedOnCompletion = NO;
664
+ if (delay <= 0) a.fillMode = kCAFillModeForwards;
665
+ }
666
+ if (o.Has("id")) {
667
+ Napi::Value idv = o.Get("id");
668
+ if (!idv.IsString()) return ThrowType(env, "id: expected a string");
669
+ CALAnimationDelegate* d = [CALAnimationDelegate new];
670
+ d.env = env;
671
+ d.animId = ToNSString(idv);
672
+ d.key = key;
673
+ d.keyPath = a.keyPath;
674
+ a.delegate = d;
675
+ }
676
+ return true;
677
+ }
678
+
679
+ static bool ReadFromTo(Napi::Env env, CABasicAnimation* a, Napi::Object o) {
680
+ if (o.Has("from")) {
681
+ id v = AnimValue(o.Get("from"));
682
+ if (!v) return ThrowType(env, "from: expected a number, [x, y] or [r, g, b, a]");
683
+ a.fromValue = v;
684
+ }
685
+ if (o.Has("to")) {
686
+ id v = AnimValue(o.Get("to"));
687
+ if (!v) return ThrowType(env, "to: expected a number, [x, y] or [r, g, b, a]");
688
+ a.toValue = v;
689
+ }
690
+ return true;
691
+ }
692
+
693
+ // addAnimation(layer, keyPath, opts, key) -> the animation's duration in
694
+ // seconds, which for a spring is its settling time — the number a caller
695
+ // needs to know when the animation is over.
696
+ //
697
+ // { from, to, duration } CABasicAnimation
698
+ // { values, keyTimes?, timings?, calculationMode? } CAKeyframeAnimation
699
+ // { spring: { mass, stiffness, damping, initialVelocity } | true, from, to }
700
+ // CASpringAnimation
701
+ // plus, for any of them: repeat, autoreverse, timing (a name or control
702
+ // points), additive, cumulative, delay, speed, timeOffset, hold, and id —
703
+ // with an id the animation reports its end as an `animation-end` backend
704
+ // event { id, key, keyPath, finished }.
550
705
  static Napi::Value AddAnimation(const Napi::CallbackInfo& info) {
706
+ Napi::Env env = info.Env();
551
707
  CALayer* L = Deref<CALayer*>(info[0]);
552
708
  NSString* keyPath = ToNSString(info[1]);
553
709
  Napi::Object o = info[2].As<Napi::Object>();
554
710
  NSString* key = info.Length() > 3 && info[3].IsString() ? ToNSString(info[3]) : keyPath;
555
711
 
556
- CABasicAnimation* a = [CABasicAnimation animationWithKeyPath:keyPath];
557
- if (o.Has("from")) a.fromValue = AnimValue(o.Get("from"));
558
- if (o.Has("to")) a.toValue = AnimValue(o.Get("to"));
559
- a.duration = NumOr(o, "duration", 0.25);
560
- double rep = NumOr(o, "repeat", 0);
561
- if (rep > 0) a.repeatCount = std::isinf(rep) ? HUGE_VALF : (float)rep;
562
- a.autoreverses = BoolOr(o, "autoreverse", false);
563
- if (o.Has("timing")) a.timingFunction = TimingFn(ToNSString(o.Get("timing")));
564
- if (BoolOr(o, "hold", false)) {
565
- a.removedOnCompletion = NO;
566
- a.fillMode = kCAFillModeForwards;
712
+ bool keyframe = o.Has("values");
713
+ bool spring = o.Has("spring");
714
+ if (keyframe && spring) {
715
+ ThrowType(env, "values and spring are two different animations; pass one of them");
716
+ return env.Undefined();
567
717
  }
718
+
719
+ CAPropertyAnimation* a = nil;
720
+ if (keyframe) {
721
+ CAKeyframeAnimation* k = [CAKeyframeAnimation animationWithKeyPath:keyPath];
722
+ Napi::Value vv = o.Get("values");
723
+ if (!vv.IsArray() || vv.As<Napi::Array>().Length() < 2) {
724
+ ThrowType(env, "values: expected an array of at least two values");
725
+ return env.Undefined();
726
+ }
727
+ Napi::Array varr = vv.As<Napi::Array>();
728
+ NSMutableArray* values = [NSMutableArray arrayWithCapacity:varr.Length()];
729
+ for (uint32_t i = 0; i < varr.Length(); i++) {
730
+ id v = AnimValue(varr.Get(i));
731
+ if (!v) {
732
+ ThrowType(env, "values: each entry is a number, [x, y] or [r, g, b, a]");
733
+ return env.Undefined();
734
+ }
735
+ [values addObject:v];
736
+ }
737
+ k.values = values;
738
+ if (o.Has("keyTimes")) {
739
+ Napi::Value kv = o.Get("keyTimes");
740
+ bool ok = kv.IsArray() && kv.As<Napi::Array>().Length() == varr.Length();
741
+ NSMutableArray* times = [NSMutableArray arrayWithCapacity:varr.Length()];
742
+ double last = 0;
743
+ for (uint32_t i = 0; ok && i < varr.Length(); i++) {
744
+ Napi::Value t = kv.As<Napi::Array>().Get(i);
745
+ double d = t.IsNumber() ? t.As<Napi::Number>().DoubleValue() : -1;
746
+ ok = d >= last && d <= 1 && (i > 0 || d == 0);
747
+ last = d;
748
+ [times addObject:@(d)];
749
+ }
750
+ if (!ok) {
751
+ ThrowType(env, "keyTimes: one per value, from 0 to at most 1, never decreasing");
752
+ return env.Undefined();
753
+ }
754
+ k.keyTimes = times;
755
+ }
756
+ if (o.Has("timings")) {
757
+ Napi::Value tv = o.Get("timings");
758
+ if (!tv.IsArray() || tv.As<Napi::Array>().Length() != varr.Length() - 1) {
759
+ ThrowType(env, "timings: one curve per segment, so one fewer than values");
760
+ return env.Undefined();
761
+ }
762
+ NSMutableArray* fns = [NSMutableArray arrayWithCapacity:varr.Length() - 1];
763
+ for (uint32_t i = 0; i + 1 < varr.Length(); i++) {
764
+ CAMediaTimingFunction* fn = TimingFrom(env, tv.As<Napi::Array>().Get(i));
765
+ if (!fn) return env.Undefined();
766
+ [fns addObject:fn];
767
+ }
768
+ k.timingFunctions = fns;
769
+ }
770
+ if (o.Has("calculationMode")) {
771
+ NSString* mode = StrOr(o, "calculationMode", @"linear");
772
+ if ([mode isEqualToString:@"linear"]) k.calculationMode = kCAAnimationLinear;
773
+ else if ([mode isEqualToString:@"discrete"]) k.calculationMode = kCAAnimationDiscrete;
774
+ else if ([mode isEqualToString:@"paced"]) k.calculationMode = kCAAnimationPaced;
775
+ else if ([mode isEqualToString:@"cubic"]) k.calculationMode = kCAAnimationCubic;
776
+ else if ([mode isEqualToString:@"cubicPaced"]) k.calculationMode = kCAAnimationCubicPaced;
777
+ else {
778
+ ThrowType(env, "calculationMode: expected linear, discrete, paced, cubic or cubicPaced");
779
+ return env.Undefined();
780
+ }
781
+ }
782
+ k.duration = NumOr(o, "duration", 0.25);
783
+ a = k;
784
+ } else if (spring) {
785
+ CASpringAnimation* s = [CASpringAnimation animationWithKeyPath:keyPath];
786
+ Napi::Value sv = o.Get("spring");
787
+ if (sv.IsObject()) {
788
+ Napi::Object so = sv.As<Napi::Object>();
789
+ // checked before they are set: CA refuses a bad value with a log line
790
+ // and keeps its default, which would make the check below pass
791
+ double mass = NumOr(so, "mass", s.mass);
792
+ double stiffness = NumOr(so, "stiffness", s.stiffness);
793
+ double damping = NumOr(so, "damping", s.damping);
794
+ double velocity = NumOr(so, "initialVelocity", s.initialVelocity);
795
+ if (!(mass > 0 && stiffness > 0 && damping >= 0 && std::isfinite(velocity))) {
796
+ ThrowType(env, "spring: mass and stiffness are positive, damping is not negative");
797
+ return env.Undefined();
798
+ }
799
+ s.mass = mass;
800
+ s.stiffness = stiffness;
801
+ s.damping = damping;
802
+ s.initialVelocity = velocity;
803
+ } else if (!(sv.IsBoolean() && sv.As<Napi::Boolean>().Value())) {
804
+ ThrowType(env, "spring: expected { mass, stiffness, damping, initialVelocity } or true for CA's defaults");
805
+ return env.Undefined();
806
+ }
807
+ if (!ReadFromTo(env, s, o)) return env.Undefined();
808
+ // CA's default duration is 0.25s and would cut the spring off mid-swing;
809
+ // it settles when the physics says, unless the caller cuts it themselves
810
+ s.duration = o.Has("duration") ? NumOr(o, "duration", 0.25) : s.settlingDuration;
811
+ a = s;
812
+ } else {
813
+ CABasicAnimation* b = [CABasicAnimation animationWithKeyPath:keyPath];
814
+ if (!ReadFromTo(env, b, o)) return env.Undefined();
815
+ b.duration = NumOr(o, "duration", 0.25);
816
+ a = b;
817
+ }
818
+ if (!ApplyTiming(env, a, L, o, key)) return env.Undefined();
568
819
  [L addAnimation:a forKey:key];
569
- return info.Env().Undefined();
820
+ return Napi::Number::New(env, a.duration);
570
821
  }
571
822
 
572
823
  static Napi::Value RemoveAnimation(const Napi::CallbackInfo& info) {
@@ -581,15 +832,101 @@ static Napi::Value RemoveAllAnimations(const Napi::CallbackInfo& info) {
581
832
  return info.Env().Undefined();
582
833
  }
583
834
 
835
+ // A CA value back to JS: a number; a point or size as [x, y]; a rect as
836
+ // [x, y, w, h]; a colour as [r, g, b, a] in generic RGB; a transform as its
837
+ // sixteen components, row by row. null for anything else.
838
+ static Napi::Value JSFromCAValue(Napi::Env env, id v) {
839
+ if (!v) return env.Null();
840
+ if ([v isKindOfClass:[NSNumber class]]) return Napi::Number::New(env, [(NSNumber*)v doubleValue]);
841
+ if ([v isKindOfClass:[NSValue class]]) {
842
+ NSValue* nv = (NSValue*)v;
843
+ const char* t = nv.objCType;
844
+ Napi::Array arr = Napi::Array::New(env);
845
+ if (strcmp(t, @encode(CGPoint)) == 0) {
846
+ CGPoint p = nv.pointValue;
847
+ arr.Set(0u, p.x); arr.Set(1u, p.y);
848
+ } else if (strcmp(t, @encode(CGSize)) == 0) {
849
+ CGSize s = nv.sizeValue;
850
+ arr.Set(0u, s.width); arr.Set(1u, s.height);
851
+ } else if (strcmp(t, @encode(CGRect)) == 0) {
852
+ CGRect r = nv.rectValue;
853
+ arr.Set(0u, r.origin.x); arr.Set(1u, r.origin.y);
854
+ arr.Set(2u, r.size.width); arr.Set(3u, r.size.height);
855
+ } else if (strcmp(t, @encode(CATransform3D)) == 0) {
856
+ CATransform3D m = nv.CATransform3DValue;
857
+ const CGFloat* c = &m.m11;
858
+ for (uint32_t i = 0; i < 16; i++) arr.Set(i, (double)c[i]);
859
+ } else {
860
+ return env.Null();
861
+ }
862
+ return arr;
863
+ }
864
+ if (CFGetTypeID((__bridge CFTypeRef)v) == CGColorGetTypeID()) {
865
+ CGColorRef c = (__bridge CGColorRef)v;
866
+ CGColorSpaceRef rgb = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
867
+ CGColorRef conv = CGColorCreateCopyByMatchingToColorSpace(rgb, kCGRenderingIntentDefault, c, NULL);
868
+ CGColorSpaceRelease(rgb);
869
+ CGColorRef src = conv ? conv : c;
870
+ const CGFloat* comps = CGColorGetComponents(src);
871
+ size_t n = CGColorGetNumberOfComponents(src);
872
+ Napi::Array arr = Napi::Array::New(env, 4);
873
+ if (n == 4) {
874
+ for (uint32_t i = 0; i < 4; i++) arr.Set(i, (double)comps[i]);
875
+ } else if (n == 2) {
876
+ arr.Set(0u, (double)comps[0]); arr.Set(1u, (double)comps[0]);
877
+ arr.Set(2u, (double)comps[0]); arr.Set(3u, (double)comps[1]);
878
+ } else {
879
+ if (conv) CGColorRelease(conv);
880
+ return env.Null();
881
+ }
882
+ if (conv) CGColorRelease(conv);
883
+ return arr;
884
+ }
885
+ return env.Null();
886
+ }
887
+
888
+ // presentationValue(layer, keyPath) -> the value the render server is
889
+ // showing for that key path right now, animations applied — or null before
890
+ // the layer's first commit. The model value is what the caller set; this is
891
+ // where the pixels are, which is the `from` an interrupted colour animation
892
+ // needs and the number a test reads a curve back through.
893
+ static Napi::Value PresentationValue(const Napi::CallbackInfo& info) {
894
+ Napi::Env env = info.Env();
895
+ CALayer* L = Deref<CALayer*>(info[0]);
896
+ NSString* keyPath = ToNSString(info[1]);
897
+ CALayer* p = L.presentationLayer;
898
+ if (!p) return env.Null();
899
+ id v = nil;
900
+ @try {
901
+ v = [p valueForKeyPath:keyPath];
902
+ } @catch (NSException* e) {
903
+ return env.Null();
904
+ }
905
+ return JSFromCAValue(env, v);
906
+ }
907
+
584
908
  static Napi::Value TxBegin(const Napi::CallbackInfo& info) {
909
+ Napi::Env env = info.Env();
910
+ CAMediaTimingFunction* timing = nil;
911
+ bool hasTiming = false;
912
+ if (info.Length() > 0 && info[0].IsObject()) {
913
+ Napi::Object o = info[0].As<Napi::Object>();
914
+ if (o.Has("timing")) {
915
+ hasTiming = true;
916
+ timing = TimingFrom(env, o.Get("timing"));
917
+ // a bad curve is reported before anything is begun, so a throw here
918
+ // leaves no transaction open
919
+ if (!timing) return env.Undefined();
920
+ }
921
+ }
585
922
  [CATransaction begin];
586
923
  if (info.Length() > 0 && info[0].IsObject()) {
587
924
  Napi::Object o = info[0].As<Napi::Object>();
588
925
  if (o.Has("duration")) [CATransaction setAnimationDuration:NumOr(o, "duration", 0.25)];
589
926
  if (BoolOr(o, "disableActions", false)) [CATransaction setDisableActions:YES];
590
- if (o.Has("timing")) [CATransaction setAnimationTimingFunction:TimingFn(ToNSString(o.Get("timing")))];
927
+ if (hasTiming) [CATransaction setAnimationTimingFunction:timing];
591
928
  }
592
- return info.Env().Undefined();
929
+ return env.Undefined();
593
930
  }
594
931
 
595
932
  static Napi::Value TxCommit(const Napi::CallbackInfo& info) {
@@ -918,13 +1255,19 @@ static Napi::Value SnapshotWindow(const Napi::CallbackInfo& info) {
918
1255
  // module init
919
1256
  // ---------------------------------------------------------------------------
920
1257
 
921
- // src/backend.mm — the react-x11 backend surface (windows with delegates,
922
- // enriched events, CG surfaces, CoreText layouts, pasteboard, screens).
1258
+ // src/backend.mm — the react-x11 backend surface (initApp and the app
1259
+ // delegate, windows with delegates, enriched events, CG surfaces, CoreText
1260
+ // layouts, pasteboard, screens).
923
1261
  void InitBackend(Napi::Env env, Napi::Object exports);
1262
+ // src/permissions.mm — privacy (TCC) authorizations: status, the system
1263
+ // prompt where a framework offers one, the Settings pane otherwise.
1264
+ void InitPermissions(Napi::Env env, Napi::Object exports);
1265
+ // src/notifications.mm — user notifications through UNUserNotificationCenter:
1266
+ // settings, authorization, categories, post/update/remove, action events.
1267
+ void InitNotifications(Napi::Env env, Napi::Object exports);
924
1268
 
925
1269
  static Napi::Object Init(Napi::Env env, Napi::Object exports) {
926
1270
  #define FN(js, fn) exports.Set(js, Napi::Function::New(env, fn))
927
- FN("initApp", InitApp);
928
1271
  FN("pump", Pump);
929
1272
  FN("setEventCallback", SetEventCallback);
930
1273
  FN("postMouseEvent", PostMouseEvent);
@@ -951,6 +1294,7 @@ static Napi::Object Init(Napi::Env env, Napi::Object exports) {
951
1294
  FN("removeAllAnimations", RemoveAllAnimations);
952
1295
  FN("txBegin", TxBegin);
953
1296
  FN("txCommit", TxCommit);
1297
+ FN("presentationValue", PresentationValue);
954
1298
  FN("hitTest", HitTest);
955
1299
  FN("measureText", MeasureText);
956
1300
  FN("createTextImage", CreateTextImage);
@@ -960,6 +1304,8 @@ static Napi::Object Init(Napi::Env env, Napi::Object exports) {
960
1304
  FN("appearanceIsDark", AppearanceIsDark);
961
1305
  #undef FN
962
1306
  InitBackend(env, exports);
1307
+ InitPermissions(env, exports);
1308
+ InitNotifications(env, exports);
963
1309
  return exports;
964
1310
  }
965
1311