@windowkit/appkit 0.2.0 → 0.4.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@windowkit/appkit",
3
- "version": "0.2.0",
3
+ "version": "0.4.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",
Binary file
package/src/backend.mm CHANGED
@@ -111,6 +111,10 @@ static void EmitToJS(Napi::Env env, Napi::Object ev) {
111
111
  }
112
112
  @end
113
113
 
114
+ static bool WindowOnGlass(NSWindow* win) {
115
+ return (win.occlusionState & NSWindowOcclusionStateVisible) != 0;
116
+ }
117
+
114
118
  static Napi::Object WindowEvent(Napi::Env env, NSWindow* win,
115
119
  const char* type) {
116
120
  Napi::Object ev = Napi::Object::New(env);
@@ -160,6 +164,18 @@ static void EmitWindowGeometry(Napi::Env env, NSWindow* win, const char* type,
160
164
  Napi::HandleScope scope(env);
161
165
  EmitToJS(env, WindowEvent(env, (NSWindow*)n.object, "window-blur"));
162
166
  }
167
+ // A window entirely behind another application's window is still visible
168
+ // by isVisible's measure and still costs every frame its tree produces.
169
+ // AppKit knows the difference; `visible: false` here means no pixel of the
170
+ // window is on glass, so a renderer can hold its frames until one is.
171
+ - (void)windowDidChangeOcclusionState:(NSNotification*)n {
172
+ NSWindow* win = n.object;
173
+ Napi::Env env(env_);
174
+ Napi::HandleScope scope(env);
175
+ Napi::Object ev = WindowEvent(env, win, "window-occlusion");
176
+ ev.Set("visible", WindowOnGlass(win));
177
+ EmitToJS(env, ev);
178
+ }
163
179
  - (void)windowDidChangeBackingProperties:(NSNotification*)n {
164
180
  NSWindow* win = n.object;
165
181
  Napi::Env env(env_);
@@ -363,7 +379,7 @@ static Napi::Value SetWindowFrame(const Napi::CallbackInfo& info) {
363
379
  return info.Env().Undefined();
364
380
  }
365
381
 
366
- // -> { x, y, width, height, scale, visible, key } — content rect, top-left
382
+ // -> { x, y, width, height, scale, visible, occluded, key } — content rect, top-left
367
383
  // global coordinates, points.
368
384
  static Napi::Value GetWindowFrame(const Napi::CallbackInfo& info) {
369
385
  Napi::Env env = info.Env();
@@ -376,6 +392,8 @@ static Napi::Value GetWindowFrame(const Napi::CallbackInfo& info) {
376
392
  r.Set("height", content.size.height);
377
393
  r.Set("scale", win.backingScaleFactor);
378
394
  r.Set("visible", (bool)win.isVisible);
395
+ // visible but with no pixel on glass: fully behind another app's window
396
+ r.Set("occluded", win.isVisible && !WindowOnGlass(win));
379
397
  r.Set("key", (bool)win.isKeyWindow);
380
398
  return r;
381
399
  }
@@ -536,16 +554,81 @@ static Napi::Value Pump2(const Napi::CallbackInfo& info) {
536
554
  // ---------------------------------------------------------------------------
537
555
 
538
556
  struct CALSurface {
539
- CGContextRef ctx = nullptr;
557
+ CGContextRef ctx = nullptr; // nullptr once released
540
558
  size_t width = 0, height = 0; // pixels
541
559
  double scale = 1;
542
560
  // when the bitmap lives in an IOSurface (zero-copy presentation), the
543
561
  // surface owns a reference and the layer scans out of the same memory
544
562
  IOSurfaceRef iosurface = nullptr;
563
+ // bytes of bitmap this handle keeps alive, reported to V8 as external
564
+ // memory: a handle is a few dozen bytes of heap to the collector, the
565
+ // 10MB behind it is invisible, and a live resize retiring two of them a
566
+ // tick piles up RSS until the heap happens to grow into a collection
567
+ int64_t bytes = 0;
545
568
  };
546
569
 
570
+ // Free the bitmap now and hand the bytes back to V8's account. The struct
571
+ // outlives its bitmap: the External's finalizer deletes it, and ctx == nullptr
572
+ // marks it released to every verb in between.
573
+ static void SurfaceFree(Napi::Env env, CALSurface* s) {
574
+ if (!s->ctx) return;
575
+ CGContextRelease(s->ctx);
576
+ s->ctx = nullptr;
577
+ if (s->iosurface) {
578
+ CFRelease(s->iosurface);
579
+ s->iosurface = nullptr;
580
+ }
581
+ if (s->bytes) {
582
+ Napi::MemoryManagement::AdjustExternalMemory(env, -s->bytes);
583
+ s->bytes = 0;
584
+ }
585
+ }
586
+
587
+ static void SurfaceFinalize(Napi::Env env, void* d) {
588
+ auto* s = (CALSurface*)d;
589
+ SurfaceFree(env, s);
590
+ delete s;
591
+ }
592
+
593
+ static Napi::Value WrapSurface(Napi::Env env, CALSurface* s, int64_t bytes) {
594
+ s->bytes = bytes;
595
+ if (bytes) Napi::MemoryManagement::AdjustExternalMemory(env, bytes);
596
+ return Napi::External<void>::New(env, s, SurfaceFinalize);
597
+ }
598
+
599
+ // The surface behind a handle, or nullptr with a JS error pending when the
600
+ // handle was released: a use after releaseSurface is an error, not a crash.
601
+ // Callers return on nullptr.
547
602
  static CALSurface* SurfaceFrom(Napi::Value v) {
548
- return (CALSurface*)v.As<Napi::External<void>>().Data();
603
+ if (!v.IsExternal()) {
604
+ Napi::TypeError::New(v.Env(), "expected a surface handle")
605
+ .ThrowAsJavaScriptException();
606
+ return nullptr;
607
+ }
608
+ auto* s = (CALSurface*)v.As<Napi::External<void>>().Data();
609
+ if (!s->ctx) {
610
+ Napi::Error::New(v.Env(), "surface was released")
611
+ .ThrowAsJavaScriptException();
612
+ return nullptr;
613
+ }
614
+ return s;
615
+ }
616
+
617
+ // For the fire-and-forget drawing verbs: the context to draw into, or a
618
+ // scratch bitmap when the surface is released (the error is already
619
+ // pending; the stroke lands nowhere anyone looks).
620
+ static CGContextRef CtxOf(Napi::Value v) {
621
+ CALSurface* s = SurfaceFrom(v);
622
+ if (s) return s->ctx;
623
+ static CGContextRef scratch = nullptr;
624
+ if (!scratch) {
625
+ CGColorSpaceRef cs = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
626
+ scratch = CGBitmapContextCreate(
627
+ NULL, 1, 1, 8, 0, cs,
628
+ kCGImageAlphaPremultipliedFirst | (CGBitmapInfo)kCGBitmapByteOrder32Host);
629
+ CGColorSpaceRelease(cs);
630
+ }
631
+ return scratch;
549
632
  }
550
633
 
551
634
  // createSurface(widthPx, heightPx, scale) — top-left origin, y down (the
@@ -571,11 +654,7 @@ static Napi::Value CreateSurface(const Napi::CallbackInfo& info) {
571
654
  CGContextScaleCTM(ctx, 1, -1);
572
655
  CGContextSetInterpolationQuality(ctx, kCGInterpolationMedium);
573
656
  auto* s = new CALSurface{ctx, w, h, scale};
574
- return Napi::External<void>::New(env, s, [](Napi::Env, void* d) {
575
- auto* s = (CALSurface*)d;
576
- CGContextRelease(s->ctx);
577
- delete s;
578
- });
657
+ return WrapSurface(env, s, (int64_t)(CGBitmapContextGetBytesPerRow(ctx) * h));
579
658
  }
580
659
 
581
660
  // createSurfaceIOSurface(widthPx, heightPx, scale)
@@ -633,12 +712,7 @@ static Napi::Value CreateSurfaceIOSurface(const Napi::CallbackInfo& info) {
633
712
  CGContextSetInterpolationQuality(ctx, kCGInterpolationMedium);
634
713
  auto* s = new CALSurface{ctx, w, h, scale, ios};
635
714
  Napi::Object out = Napi::Object::New(env);
636
- out.Set("handle", Napi::External<void>::New(env, s, [](Napi::Env, void* d) {
637
- auto* p = (CALSurface*)d;
638
- CGContextRelease(p->ctx);
639
- if (p->iosurface) CFRelease(p->iosurface);
640
- delete p;
641
- }));
715
+ out.Set("handle", WrapSurface(env, s, (int64_t)IOSurfaceGetAllocSize(ios)));
642
716
  out.Set("iosurfaceId", (double)IOSurfaceGetID(ios));
643
717
  return out;
644
718
  }
@@ -676,27 +750,40 @@ static Napi::Value SurfaceFromIOSurfaceID(const Napi::CallbackInfo& info) {
676
750
  CGContextSetInterpolationQuality(ctx, kCGInterpolationMedium);
677
751
  auto* s = new CALSurface{ctx, w, h, scale, ios};
678
752
  Napi::Object out = Napi::Object::New(env);
679
- out.Set("handle", Napi::External<void>::New(env, s, [](Napi::Env, void* d) {
680
- auto* p = (CALSurface*)d;
681
- CGContextRelease(p->ctx);
682
- if (p->iosurface) CFRelease(p->iosurface);
683
- delete p;
684
- }));
753
+ out.Set("handle", WrapSurface(env, s, (int64_t)IOSurfaceGetAllocSize(ios)));
685
754
  out.Set("width", (double)w);
686
755
  out.Set("height", (double)h);
687
756
  return out;
688
757
  }
689
758
 
759
+ // releaseSurface(handle) — free the bitmap now, not when V8 gets around to
760
+ // the handle. A swapchain retires a pair per resize tick, 20MB at
761
+ // 900x700@2x; released on the flip that retires them, they never pile up.
762
+ // The finalizer stays as the safety net. Idempotent; every other verb on a
763
+ // released handle throws.
764
+ static Napi::Value ReleaseSurface(const Napi::CallbackInfo& info) {
765
+ Napi::Env env = info.Env();
766
+ if (!info[0].IsExternal()) {
767
+ Napi::TypeError::New(env, "releaseSurface: expected a surface handle")
768
+ .ThrowAsJavaScriptException();
769
+ return env.Undefined();
770
+ }
771
+ SurfaceFree(env, (CALSurface*)info[0].As<Napi::External<void>>().Data());
772
+ return env.Undefined();
773
+ }
774
+
690
775
  // CPU access bracketing for an IOSurface-backed surface: lock before the
691
776
  // frame's first draw, unlock before handing the buffer to the layer. No-op
692
777
  // on a plain surface, so callers need not care which kind they hold.
693
778
  static Napi::Value SurfaceLock(const Napi::CallbackInfo& info) {
694
779
  CALSurface* s = SurfaceFrom(info[0]);
780
+ if (!s) return info.Env().Undefined();
695
781
  if (s->iosurface) IOSurfaceLock(s->iosurface, 0, NULL);
696
782
  return info.Env().Undefined();
697
783
  }
698
784
  static Napi::Value SurfaceUnlock(const Napi::CallbackInfo& info) {
699
785
  CALSurface* s = SurfaceFrom(info[0]);
786
+ if (!s) return info.Env().Undefined();
700
787
  if (s->iosurface) IOSurfaceUnlock(s->iosurface, 0, NULL);
701
788
  return info.Env().Undefined();
702
789
  }
@@ -707,7 +794,9 @@ static Napi::Value SurfaceUnlock(const Napi::CallbackInfo& info) {
707
794
  static Napi::Value CopySurfaceRegion(const Napi::CallbackInfo& info) {
708
795
  Napi::Env env = info.Env();
709
796
  CALSurface* src = SurfaceFrom(info[0]);
797
+ if (!src) return info.Env().Undefined();
710
798
  CALSurface* dst = SurfaceFrom(info[1]);
799
+ if (!dst) return info.Env().Undefined();
711
800
  if (src->width != dst->width || src->height != dst->height) {
712
801
  Napi::Error::New(env, "copySurfaceRegion: size mismatch")
713
802
  .ThrowAsJavaScriptException();
@@ -749,6 +838,7 @@ static Napi::Value CopySurfaceRegion(const Napi::CallbackInfo& info) {
749
838
 
750
839
  static Napi::Value SurfaceSize(const Napi::CallbackInfo& info) {
751
840
  CALSurface* s = SurfaceFrom(info[0]);
841
+ if (!s) return info.Env().Undefined();
752
842
  Napi::Object r = Napi::Object::New(info.Env());
753
843
  r.Set("width", (double)s->width);
754
844
  r.Set("height", (double)s->height);
@@ -1071,6 +1161,7 @@ static Napi::Value DrawControlIntoSurface(const Napi::CallbackInfo& info) {
1071
1161
  Napi::Env env = info.Env();
1072
1162
  BEnsureApp();
1073
1163
  CALSurface* s = SurfaceFrom(info[0]);
1164
+ if (!s) return info.Env().Undefined();
1074
1165
  Napi::Object o = info[1].As<Napi::Object>();
1075
1166
  BezelControl c = BuildBezel(env, o);
1076
1167
  if (env.IsExceptionPending()) return env.Undefined();
@@ -1110,27 +1201,27 @@ static Napi::Value DrawControlIntoSurface(const Napi::CallbackInfo& info) {
1110
1201
  // --- drawing verbs. All take the surface handle first. ---------------------
1111
1202
 
1112
1203
  static Napi::Value CtxSave(const Napi::CallbackInfo& info) {
1113
- CGContextSaveGState(SurfaceFrom(info[0])->ctx);
1204
+ CGContextSaveGState(CtxOf(info[0]));
1114
1205
  return info.Env().Undefined();
1115
1206
  }
1116
1207
  static Napi::Value CtxRestore(const Napi::CallbackInfo& info) {
1117
- CGContextRestoreGState(SurfaceFrom(info[0])->ctx);
1208
+ CGContextRestoreGState(CtxOf(info[0]));
1118
1209
  return info.Env().Undefined();
1119
1210
  }
1120
1211
  static Napi::Value CtxTranslate(const Napi::CallbackInfo& info) {
1121
- CGContextTranslateCTM(SurfaceFrom(info[0])->ctx,
1212
+ CGContextTranslateCTM(CtxOf(info[0]),
1122
1213
  info[1].As<Napi::Number>().DoubleValue(),
1123
1214
  info[2].As<Napi::Number>().DoubleValue());
1124
1215
  return info.Env().Undefined();
1125
1216
  }
1126
1217
  static Napi::Value CtxScale(const Napi::CallbackInfo& info) {
1127
- CGContextScaleCTM(SurfaceFrom(info[0])->ctx,
1218
+ CGContextScaleCTM(CtxOf(info[0]),
1128
1219
  info[1].As<Napi::Number>().DoubleValue(),
1129
1220
  info[2].As<Napi::Number>().DoubleValue());
1130
1221
  return info.Env().Undefined();
1131
1222
  }
1132
1223
  static Napi::Value CtxTransform(const Napi::CallbackInfo& info) {
1133
- CGContextConcatCTM(SurfaceFrom(info[0])->ctx,
1224
+ CGContextConcatCTM(CtxOf(info[0]),
1134
1225
  CGAffineTransformMake(
1135
1226
  info[1].As<Napi::Number>().DoubleValue(),
1136
1227
  info[2].As<Napi::Number>().DoubleValue(),
@@ -1142,22 +1233,23 @@ static Napi::Value CtxTransform(const Napi::CallbackInfo& info) {
1142
1233
  }
1143
1234
 
1144
1235
  static Napi::Value CtxRotate(const Napi::CallbackInfo& info) {
1145
- CGContextRotateCTM(SurfaceFrom(info[0])->ctx,
1236
+ CGContextRotateCTM(CtxOf(info[0]),
1146
1237
  info[1].As<Napi::Number>().DoubleValue());
1147
1238
  return info.Env().Undefined();
1148
1239
  }
1149
1240
  static Napi::Value CtxBeginPath(const Napi::CallbackInfo& info) {
1150
- CGContextBeginPath(SurfaceFrom(info[0])->ctx);
1241
+ CGContextBeginPath(CtxOf(info[0]));
1151
1242
  return info.Env().Undefined();
1152
1243
  }
1153
1244
  static Napi::Value CtxMoveTo(const Napi::CallbackInfo& info) {
1154
- CGContextMoveToPoint(SurfaceFrom(info[0])->ctx,
1245
+ CGContextMoveToPoint(CtxOf(info[0]),
1155
1246
  info[1].As<Napi::Number>().DoubleValue(),
1156
1247
  info[2].As<Napi::Number>().DoubleValue());
1157
1248
  return info.Env().Undefined();
1158
1249
  }
1159
1250
  static Napi::Value CtxLineTo(const Napi::CallbackInfo& info) {
1160
1251
  CALSurface* s = SurfaceFrom(info[0]);
1252
+ if (!s) return info.Env().Undefined();
1161
1253
  double x = info[1].As<Napi::Number>().DoubleValue();
1162
1254
  double y = info[2].As<Napi::Number>().DoubleValue();
1163
1255
  if (CGContextIsPathEmpty(s->ctx)) CGContextMoveToPoint(s->ctx, x, y);
@@ -1165,7 +1257,7 @@ static Napi::Value CtxLineTo(const Napi::CallbackInfo& info) {
1165
1257
  return info.Env().Undefined();
1166
1258
  }
1167
1259
  static Napi::Value CtxRect(const Napi::CallbackInfo& info) {
1168
- CGContextAddRect(SurfaceFrom(info[0])->ctx,
1260
+ CGContextAddRect(CtxOf(info[0]),
1169
1261
  CGRectMake(info[1].As<Napi::Number>().DoubleValue(),
1170
1262
  info[2].As<Napi::Number>().DoubleValue(),
1171
1263
  info[3].As<Napi::Number>().DoubleValue(),
@@ -1176,6 +1268,7 @@ static Napi::Value CtxRect(const Napi::CallbackInfo& info) {
1176
1268
  // top-left/top-right/bottom-right/bottom-left, already clamped by JS.
1177
1269
  static Napi::Value CtxRoundRect(const Napi::CallbackInfo& info) {
1178
1270
  CALSurface* s = SurfaceFrom(info[0]);
1271
+ if (!s) return info.Env().Undefined();
1179
1272
  double x = info[1].As<Napi::Number>().DoubleValue();
1180
1273
  double y = info[2].As<Napi::Number>().DoubleValue();
1181
1274
  double w = info[3].As<Napi::Number>().DoubleValue();
@@ -1206,7 +1299,7 @@ static Napi::Value CtxArc(const Napi::CallbackInfo& info) {
1206
1299
  // The flag therefore maps straight across, not inverted: getting this
1207
1300
  // backwards leaves full circles (donuts) looking right and every partial
1208
1301
  // arc sweeping the long way round — the raster-gate gauges caught it.
1209
- CGContextAddArc(SurfaceFrom(info[0])->ctx,
1302
+ CGContextAddArc(CtxOf(info[0]),
1210
1303
  info[1].As<Napi::Number>().DoubleValue(),
1211
1304
  info[2].As<Napi::Number>().DoubleValue(),
1212
1305
  info[3].As<Napi::Number>().DoubleValue(),
@@ -1217,7 +1310,7 @@ static Napi::Value CtxArc(const Napi::CallbackInfo& info) {
1217
1310
  }
1218
1311
  static Napi::Value CtxEllipse(const Napi::CallbackInfo& info) {
1219
1312
  CGContextAddEllipseInRect(
1220
- SurfaceFrom(info[0])->ctx,
1313
+ CtxOf(info[0]),
1221
1314
  CGRectMake(info[1].As<Napi::Number>().DoubleValue() -
1222
1315
  info[3].As<Napi::Number>().DoubleValue(),
1223
1316
  info[2].As<Napi::Number>().DoubleValue() -
@@ -1227,7 +1320,7 @@ static Napi::Value CtxEllipse(const Napi::CallbackInfo& info) {
1227
1320
  return info.Env().Undefined();
1228
1321
  }
1229
1322
  static Napi::Value CtxCurveTo(const Napi::CallbackInfo& info) {
1230
- CGContextAddCurveToPoint(SurfaceFrom(info[0])->ctx,
1323
+ CGContextAddCurveToPoint(CtxOf(info[0]),
1231
1324
  info[1].As<Napi::Number>().DoubleValue(),
1232
1325
  info[2].As<Napi::Number>().DoubleValue(),
1233
1326
  info[3].As<Napi::Number>().DoubleValue(),
@@ -1237,7 +1330,7 @@ static Napi::Value CtxCurveTo(const Napi::CallbackInfo& info) {
1237
1330
  return info.Env().Undefined();
1238
1331
  }
1239
1332
  static Napi::Value CtxQuadTo(const Napi::CallbackInfo& info) {
1240
- CGContextAddQuadCurveToPoint(SurfaceFrom(info[0])->ctx,
1333
+ CGContextAddQuadCurveToPoint(CtxOf(info[0]),
1241
1334
  info[1].As<Napi::Number>().DoubleValue(),
1242
1335
  info[2].As<Napi::Number>().DoubleValue(),
1243
1336
  info[3].As<Napi::Number>().DoubleValue(),
@@ -1245,12 +1338,12 @@ static Napi::Value CtxQuadTo(const Napi::CallbackInfo& info) {
1245
1338
  return info.Env().Undefined();
1246
1339
  }
1247
1340
  static Napi::Value CtxClosePath(const Napi::CallbackInfo& info) {
1248
- CGContextClosePath(SurfaceFrom(info[0])->ctx);
1341
+ CGContextClosePath(CtxOf(info[0]));
1249
1342
  return info.Env().Undefined();
1250
1343
  }
1251
1344
 
1252
1345
  static Napi::Value CtxSetFillColor(const Napi::CallbackInfo& info) {
1253
- CGContextSetRGBFillColor(SurfaceFrom(info[0])->ctx,
1346
+ CGContextSetRGBFillColor(CtxOf(info[0]),
1254
1347
  info[1].As<Napi::Number>().DoubleValue(),
1255
1348
  info[2].As<Napi::Number>().DoubleValue(),
1256
1349
  info[3].As<Napi::Number>().DoubleValue(),
@@ -1258,7 +1351,7 @@ static Napi::Value CtxSetFillColor(const Napi::CallbackInfo& info) {
1258
1351
  return info.Env().Undefined();
1259
1352
  }
1260
1353
  static Napi::Value CtxSetStrokeColor(const Napi::CallbackInfo& info) {
1261
- CGContextSetRGBStrokeColor(SurfaceFrom(info[0])->ctx,
1354
+ CGContextSetRGBStrokeColor(CtxOf(info[0]),
1262
1355
  info[1].As<Napi::Number>().DoubleValue(),
1263
1356
  info[2].As<Napi::Number>().DoubleValue(),
1264
1357
  info[3].As<Napi::Number>().DoubleValue(),
@@ -1266,18 +1359,18 @@ static Napi::Value CtxSetStrokeColor(const Napi::CallbackInfo& info) {
1266
1359
  return info.Env().Undefined();
1267
1360
  }
1268
1361
  static Napi::Value CtxSetLineWidth(const Napi::CallbackInfo& info) {
1269
- CGContextSetLineWidth(SurfaceFrom(info[0])->ctx,
1362
+ CGContextSetLineWidth(CtxOf(info[0]),
1270
1363
  info[1].As<Napi::Number>().DoubleValue());
1271
1364
  return info.Env().Undefined();
1272
1365
  }
1273
1366
  static Napi::Value CtxSetGlobalAlpha(const Napi::CallbackInfo& info) {
1274
- CGContextSetAlpha(SurfaceFrom(info[0])->ctx,
1367
+ CGContextSetAlpha(CtxOf(info[0]),
1275
1368
  info[1].As<Napi::Number>().DoubleValue());
1276
1369
  return info.Env().Undefined();
1277
1370
  }
1278
1371
  static Napi::Value CtxSetLineCap(const Napi::CallbackInfo& info) {
1279
1372
  std::string cap = info[1].As<Napi::String>().Utf8Value();
1280
- CGContextSetLineCap(SurfaceFrom(info[0])->ctx,
1373
+ CGContextSetLineCap(CtxOf(info[0]),
1281
1374
  cap == "round" ? kCGLineCapRound
1282
1375
  : cap == "square" ? kCGLineCapSquare
1283
1376
  : kCGLineCapButt);
@@ -1285,7 +1378,7 @@ static Napi::Value CtxSetLineCap(const Napi::CallbackInfo& info) {
1285
1378
  }
1286
1379
  static Napi::Value CtxSetLineJoin(const Napi::CallbackInfo& info) {
1287
1380
  std::string join = info[1].As<Napi::String>().Utf8Value();
1288
- CGContextSetLineJoin(SurfaceFrom(info[0])->ctx,
1381
+ CGContextSetLineJoin(CtxOf(info[0]),
1289
1382
  join == "round" ? kCGLineJoinRound
1290
1383
  : join == "bevel" ? kCGLineJoinBevel
1291
1384
  : kCGLineJoinMiter);
@@ -1293,6 +1386,7 @@ static Napi::Value CtxSetLineJoin(const Napi::CallbackInfo& info) {
1293
1386
  }
1294
1387
  static Napi::Value CtxSetLineDash(const Napi::CallbackInfo& info) {
1295
1388
  CALSurface* s = SurfaceFrom(info[0]);
1389
+ if (!s) return info.Env().Undefined();
1296
1390
  Napi::Array a = info[1].As<Napi::Array>();
1297
1391
  double offset =
1298
1392
  info.Length() > 2 ? info[2].As<Napi::Number>().DoubleValue() : 0;
@@ -1317,6 +1411,7 @@ static void KeepPathAround(CGContextRef ctx, void (^op)(void)) {
1317
1411
 
1318
1412
  static Napi::Value CtxFill(const Napi::CallbackInfo& info) {
1319
1413
  CALSurface* s = SurfaceFrom(info[0]);
1414
+ if (!s) return info.Env().Undefined();
1320
1415
  bool evenOdd = info.Length() > 1 && info[1].ToBoolean().Value();
1321
1416
  KeepPathAround(s->ctx, ^{
1322
1417
  if (evenOdd) CGContextEOFillPath(s->ctx);
@@ -1326,17 +1421,19 @@ static Napi::Value CtxFill(const Napi::CallbackInfo& info) {
1326
1421
  }
1327
1422
  static Napi::Value CtxStroke(const Napi::CallbackInfo& info) {
1328
1423
  CALSurface* s = SurfaceFrom(info[0]);
1424
+ if (!s) return info.Env().Undefined();
1329
1425
  KeepPathAround(s->ctx, ^{ CGContextStrokePath(s->ctx); });
1330
1426
  return info.Env().Undefined();
1331
1427
  }
1332
1428
  static Napi::Value CtxClip(const Napi::CallbackInfo& info) {
1333
1429
  CALSurface* s = SurfaceFrom(info[0]);
1430
+ if (!s) return info.Env().Undefined();
1334
1431
  KeepPathAround(s->ctx, ^{ CGContextClip(s->ctx); });
1335
1432
  return info.Env().Undefined();
1336
1433
  }
1337
1434
 
1338
1435
  static Napi::Value CtxFillRect(const Napi::CallbackInfo& info) {
1339
- CGContextFillRect(SurfaceFrom(info[0])->ctx,
1436
+ CGContextFillRect(CtxOf(info[0]),
1340
1437
  CGRectMake(info[1].As<Napi::Number>().DoubleValue(),
1341
1438
  info[2].As<Napi::Number>().DoubleValue(),
1342
1439
  info[3].As<Napi::Number>().DoubleValue(),
@@ -1344,7 +1441,7 @@ static Napi::Value CtxFillRect(const Napi::CallbackInfo& info) {
1344
1441
  return info.Env().Undefined();
1345
1442
  }
1346
1443
  static Napi::Value CtxStrokeRect(const Napi::CallbackInfo& info) {
1347
- CGContextStrokeRect(SurfaceFrom(info[0])->ctx,
1444
+ CGContextStrokeRect(CtxOf(info[0]),
1348
1445
  CGRectMake(info[1].As<Napi::Number>().DoubleValue(),
1349
1446
  info[2].As<Napi::Number>().DoubleValue(),
1350
1447
  info[3].As<Napi::Number>().DoubleValue(),
@@ -1352,7 +1449,7 @@ static Napi::Value CtxStrokeRect(const Napi::CallbackInfo& info) {
1352
1449
  return info.Env().Undefined();
1353
1450
  }
1354
1451
  static Napi::Value CtxClearRect(const Napi::CallbackInfo& info) {
1355
- CGContextClearRect(SurfaceFrom(info[0])->ctx,
1452
+ CGContextClearRect(CtxOf(info[0]),
1356
1453
  CGRectMake(info[1].As<Napi::Number>().DoubleValue(),
1357
1454
  info[2].As<Napi::Number>().DoubleValue(),
1358
1455
  info[3].As<Napi::Number>().DoubleValue(),
@@ -1362,6 +1459,7 @@ static Napi::Value CtxClearRect(const Napi::CallbackInfo& info) {
1362
1459
  // fillRects(surface, flat [x,y,w,h,...]) — one call for a batch of fills.
1363
1460
  static Napi::Value CtxFillRects(const Napi::CallbackInfo& info) {
1364
1461
  CALSurface* s = SurfaceFrom(info[0]);
1462
+ if (!s) return info.Env().Undefined();
1365
1463
  Napi::Array a = info[1].As<Napi::Array>();
1366
1464
  std::vector<CGRect> rects;
1367
1465
  for (uint32_t i = 0; i + 3 < a.Length(); i += 4) {
@@ -1378,6 +1476,7 @@ static Napi::Value CtxFillRects(const Napi::CallbackInfo& info) {
1378
1476
  // mode: 0 = fill current path, 1 = fill rect args follow)
1379
1477
  static Napi::Value CtxFillLinearGradient(const Napi::CallbackInfo& info) {
1380
1478
  CALSurface* s = SurfaceFrom(info[0]);
1479
+ if (!s) return info.Env().Undefined();
1381
1480
  double x0 = info[1].As<Napi::Number>().DoubleValue();
1382
1481
  double y0 = info[2].As<Napi::Number>().DoubleValue();
1383
1482
  double x1 = info[3].As<Napi::Number>().DoubleValue();
@@ -1418,7 +1517,9 @@ static Napi::Value CtxFillLinearGradient(const Napi::CallbackInfo& info) {
1418
1517
  // drawSurface(dst, src, sx, sy, sw, sh, dx, dy, dw, dh)
1419
1518
  static Napi::Value CtxDrawSurface(const Napi::CallbackInfo& info) {
1420
1519
  CALSurface* dst = SurfaceFrom(info[0]);
1520
+ if (!dst) return info.Env().Undefined();
1421
1521
  CALSurface* src = SurfaceFrom(info[1]);
1522
+ if (!src) return info.Env().Undefined();
1422
1523
  double sx = info[2].As<Napi::Number>().DoubleValue();
1423
1524
  double sy = info[3].As<Napi::Number>().DoubleValue();
1424
1525
  double sw = info[4].As<Napi::Number>().DoubleValue();
@@ -1454,6 +1555,7 @@ static Napi::Value CtxDrawSurface(const Napi::CallbackInfo& info) {
1454
1555
  // directly, transform- and clip-free, per the canvas contract.
1455
1556
  static Napi::Value CtxPutImageData(const Napi::CallbackInfo& info) {
1456
1557
  CALSurface* s = SurfaceFrom(info[0]);
1558
+ if (!s) return info.Env().Undefined();
1457
1559
  Napi::Buffer<uint8_t> buf = info[1].As<Napi::Buffer<uint8_t>>();
1458
1560
  long w = info[2].As<Napi::Number>().Int64Value();
1459
1561
  long h = info[3].As<Napi::Number>().Int64Value();
@@ -1486,6 +1588,7 @@ static Napi::Value CtxPutImageData(const Napi::CallbackInfo& info) {
1486
1588
  static Napi::Value CtxGetImageData(const Napi::CallbackInfo& info) {
1487
1589
  Napi::Env env = info.Env();
1488
1590
  CALSurface* s = SurfaceFrom(info[0]);
1591
+ if (!s) return info.Env().Undefined();
1489
1592
  long x = info[1].As<Napi::Number>().Int64Value();
1490
1593
  long y = info[2].As<Napi::Number>().Int64Value();
1491
1594
  long w = info[3].As<Napi::Number>().Int64Value();
@@ -1523,6 +1626,7 @@ static Napi::Value CtxGetImageData(const Napi::CallbackInfo& info) {
1523
1626
  // CGBitmapContextCreateImage is copy-on-write, so this is cheap per frame.
1524
1627
  static Napi::Value SurfaceToLayer(const Napi::CallbackInfo& info) {
1525
1628
  CALSurface* s = SurfaceFrom(info[0]);
1629
+ if (!s) return info.Env().Undefined();
1526
1630
  CALayer* L = BDeref<CALayer*>(info[1]);
1527
1631
  CGImageRef img = CGBitmapContextCreateImage(s->ctx);
1528
1632
  [CATransaction begin];
@@ -1541,6 +1645,7 @@ static Napi::Value SurfaceToLayer(const Napi::CallbackInfo& info) {
1541
1645
  // whatever sat above the viewport). Returns whether anything moved.
1542
1646
  static Napi::Value ScrollSurface(const Napi::CallbackInfo& info) {
1543
1647
  CALSurface* s = SurfaceFrom(info[0]);
1648
+ if (!s) return info.Env().Undefined();
1544
1649
  long x = info[1].As<Napi::Number>().Int64Value();
1545
1650
  long y = info[2].As<Napi::Number>().Int64Value();
1546
1651
  long w = info[3].As<Napi::Number>().Int64Value();
@@ -1966,6 +2071,106 @@ static Napi::Value FontFallbackFor(const Napi::CallbackInfo& info) {
1966
2071
  });
1967
2072
  }
1968
2073
 
2074
+ // fontWithSize(font, size) -> font handle | null
2075
+ // The same face at another size (CTFontCreateCopyWithAttributes). A matched
2076
+ // family re-resolves per size through matchFont; a face that arrived by
2077
+ // substitution — fontFallbackFor's answer, a fontShapeText run's font — has
2078
+ // no family to re-match by, and asking the cascade again at the new size is
2079
+ // a different question with a possibly different answer. This is how such a
2080
+ // face answers metrics and advances at every size, as itself.
2081
+ static Napi::Value FontWithSize(const Napi::CallbackInfo& info) {
2082
+ Napi::Env env = info.Env();
2083
+ if (!BCheckFontArg(info, "fontWithSize")) return env.Undefined();
2084
+ double size = info[1].IsNumber() ? info[1].As<Napi::Number>().DoubleValue() : 0;
2085
+ if (!(size > 0)) {
2086
+ Napi::TypeError::New(env, "fontWithSize: expected a size > 0")
2087
+ .ThrowAsJavaScriptException();
2088
+ return env.Undefined();
2089
+ }
2090
+ CTFontRef sized = CTFontCreateCopyWithAttributes(BFontFrom(info[0]),
2091
+ (CGFloat)size, NULL, NULL);
2092
+ if (!sized) return env.Null();
2093
+ return Napi::External<void>::New(env, (void*)sized, [](Napi::Env, void* d) {
2094
+ CFRelease(d);
2095
+ });
2096
+ }
2097
+
2098
+ // fontShapeText(font, text)
2099
+ // -> { width, runs: [{ font: handle | null, glyphs: Uint16Array,
2100
+ // positions: Float64Array x0,y0,x1,y1,…,
2101
+ // advances: Float64Array }] }
2102
+ // One CTLine over `text` in this font, read back run by run: glyph ids,
2103
+ // each glyph's origin relative to the line origin in CoreText's text space
2104
+ // (y up), and its advance. A run's `font` is null when it is the font asked
2105
+ // for, and a new handle when CoreText substituted a face for characters
2106
+ // this one lacks — the ids in that run are the substitute's, and drawing
2107
+ // them with the base font would draw its glyphs at those indices instead.
2108
+ // Runs come in visual order, so a right-to-left cluster reads back left to
2109
+ // right. The typesetter's whole answer for a cluster — a base with its
2110
+ // marks positioned, an emoji sequence joined, a variation selector honoured
2111
+ // — as ids a caller can hand to ctxDrawGlyphs beside the ids it looked up
2112
+ // itself; nothing here decides where a cluster goes.
2113
+ static Napi::Value FontShapeText(const Napi::CallbackInfo& info) {
2114
+ Napi::Env env = info.Env();
2115
+ if (!BCheckFontArg(info, "fontShapeText")) return env.Undefined();
2116
+ CTFontRef font = BFontFrom(info[0]);
2117
+ NSString* text = info[1].IsString() ? BToNSString(info[1]) : @"";
2118
+ Napi::Object out = Napi::Object::New(env);
2119
+ Napi::Array runsOut = Napi::Array::New(env);
2120
+ double width = 0;
2121
+ if (text.length > 0) {
2122
+ NSDictionary* attrs =
2123
+ @{(__bridge id)kCTFontAttributeName : (__bridge id)font};
2124
+ NSAttributedString* as =
2125
+ [[NSAttributedString alloc] initWithString:text attributes:attrs];
2126
+ CTLineRef line =
2127
+ CTLineCreateWithAttributedString((__bridge CFAttributedStringRef)as);
2128
+ width = CTLineGetTypographicBounds(line, NULL, NULL, NULL);
2129
+ CFArrayRef runs = CTLineGetGlyphRuns(line);
2130
+ uint32_t written = 0;
2131
+ for (CFIndex ri = 0; ri < CFArrayGetCount(runs); ri++) {
2132
+ CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(runs, ri);
2133
+ CFIndex count = CTRunGetGlyphCount(run);
2134
+ if (count <= 0) continue;
2135
+ std::vector<CGGlyph> glyphs((size_t)count);
2136
+ std::vector<CGPoint> positions((size_t)count);
2137
+ std::vector<CGSize> advances((size_t)count);
2138
+ CTRunGetGlyphs(run, CFRangeMake(0, 0), glyphs.data());
2139
+ CTRunGetPositions(run, CFRangeMake(0, 0), positions.data());
2140
+ CTRunGetAdvances(run, CFRangeMake(0, 0), advances.data());
2141
+ CFDictionaryRef rattrs = CTRunGetAttributes(run);
2142
+ CTFontRef rfont =
2143
+ (CTFontRef)CFDictionaryGetValue(rattrs, kCTFontAttributeName);
2144
+ Napi::Object ro = Napi::Object::New(env);
2145
+ if (rfont && !CFEqual(rfont, font)) {
2146
+ CFRetain(rfont);
2147
+ ro.Set("font", Napi::External<void>::New(
2148
+ env, (void*)rfont,
2149
+ [](Napi::Env, void* d) { CFRelease(d); }));
2150
+ } else {
2151
+ ro.Set("font", env.Null());
2152
+ }
2153
+ Napi::Uint16Array g = Napi::Uint16Array::New(env, (size_t)count);
2154
+ Napi::Float64Array p = Napi::Float64Array::New(env, (size_t)count * 2);
2155
+ Napi::Float64Array a = Napi::Float64Array::New(env, (size_t)count);
2156
+ for (size_t i = 0; i < (size_t)count; i++) {
2157
+ g[i] = glyphs[i];
2158
+ p[i * 2] = positions[i].x;
2159
+ p[i * 2 + 1] = positions[i].y;
2160
+ a[i] = advances[i].width;
2161
+ }
2162
+ ro.Set("glyphs", g);
2163
+ ro.Set("positions", p);
2164
+ ro.Set("advances", a);
2165
+ runsOut.Set(written++, ro);
2166
+ }
2167
+ CFRelease(line);
2168
+ }
2169
+ out.Set("width", width);
2170
+ out.Set("runs", runsOut);
2171
+ return out;
2172
+ }
2173
+
1969
2174
  // --- direct font handles (custom faces that bypass registry matching) -----
1970
2175
 
1971
2176
  static double CssWeightOfCTFont(CTFontRef ct) {
@@ -2394,6 +2599,7 @@ static Napi::Value CreateLayout(const Napi::CallbackInfo& info) {
2394
2599
  // drawLayout(surface, layoutHandle, x, y) — honours the surface CTM and clip.
2395
2600
  static Napi::Value DrawLayout(const Napi::CallbackInfo& info) {
2396
2601
  CALSurface* s = SurfaceFrom(info[0]);
2602
+ if (!s) return info.Env().Undefined();
2397
2603
  CALLayout* layout = LayoutFrom(info[1]);
2398
2604
  double x = info[2].As<Napi::Number>().DoubleValue();
2399
2605
  double y = info[3].As<Napi::Number>().DoubleValue();
@@ -2424,6 +2630,7 @@ static Napi::Value DrawLayout(const Napi::CallbackInfo& info) {
2424
2630
  // through that same matrix, hence the y negation in BGlyphOriginsArg.
2425
2631
  static Napi::Value CtxDrawGlyphs(const Napi::CallbackInfo& info) {
2426
2632
  CALSurface* s = SurfaceFrom(info[0]);
2633
+ if (!s) return info.Env().Undefined();
2427
2634
  if (!info[1].IsArray()) return info.Env().Undefined();
2428
2635
  Napi::Array runs = info[1].As<Napi::Array>();
2429
2636
  CGContextRef ctx = s->ctx;
@@ -2457,6 +2664,7 @@ static Napi::Value CtxDrawGlyphs(const Napi::CallbackInfo& info) {
2457
2664
  // them — gradient text ink, canvas-style.
2458
2665
  static Napi::Value DrawLayoutGradient(const Napi::CallbackInfo& info) {
2459
2666
  CALSurface* s = SurfaceFrom(info[0]);
2667
+ if (!s) return info.Env().Undefined();
2460
2668
  CALLayout* layout = LayoutFrom(info[1]);
2461
2669
  double x = info[2].As<Napi::Number>().DoubleValue();
2462
2670
  double y = info[3].As<Napi::Number>().DoubleValue();
@@ -2526,6 +2734,7 @@ static Napi::Value DrawLayoutGradient(const Napi::CallbackInfo& info) {
2526
2734
  // ctxSetShadow(surface, blur, dx, dy, r, g, b, a) — blur <= 0 clears.
2527
2735
  static Napi::Value CtxSetShadow(const Napi::CallbackInfo& info) {
2528
2736
  CALSurface* s = SurfaceFrom(info[0]);
2737
+ if (!s) return info.Env().Undefined();
2529
2738
  double blur = info[1].As<Napi::Number>().DoubleValue();
2530
2739
  if (blur <= 0) {
2531
2740
  CGContextSetShadowWithColor(s->ctx, CGSizeMake(0, 0), 0, NULL);
@@ -2657,6 +2866,12 @@ static Napi::Value ListScreens(const Napi::CallbackInfo& info) {
2657
2866
  work.Set("height", v.size.height);
2658
2867
  o.Set("visible", work);
2659
2868
  o.Set("scale", s.backingScaleFactor);
2869
+ // the panel's own refresh rate, so a renderer paces frames on the
2870
+ // display's period instead of assuming 60Hz on a 120Hz ProMotion
2871
+ // panel; 0 where the OS cannot say (before macOS 12)
2872
+ double fps = 0;
2873
+ if (@available(macOS 12.0, *)) fps = (double)s.maximumFramesPerSecond;
2874
+ o.Set("fps", fps);
2660
2875
  o.Set("primary", i == 0);
2661
2876
  out.Set((uint32_t)i, o);
2662
2877
  }
@@ -2744,6 +2959,7 @@ void InitBackend(Napi::Env env, Napi::Object exports) {
2744
2959
  BFN("createSurface", CreateSurface);
2745
2960
  BFN("createSurfaceIOSurface", CreateSurfaceIOSurface);
2746
2961
  BFN("surfaceFromIOSurfaceID", SurfaceFromIOSurfaceID);
2962
+ BFN("releaseSurface", ReleaseSurface);
2747
2963
  BFN("surfaceLock", SurfaceLock);
2748
2964
  BFN("surfaceUnlock", SurfaceUnlock);
2749
2965
  BFN("copySurfaceRegion", CopySurfaceRegion);
@@ -2790,6 +3006,8 @@ void InitBackend(Napi::Env env, Napi::Object exports) {
2790
3006
  BFN("fontGlyphForCodepoint", FontGlyphForCodepoint);
2791
3007
  BFN("fontGlyphAdvances", FontGlyphAdvances);
2792
3008
  BFN("fontFallbackFor", FontFallbackFor);
3009
+ BFN("fontWithSize", FontWithSize);
3010
+ BFN("fontShapeText", FontShapeText);
2793
3011
  BFN("fontFromData", FontFromData);
2794
3012
  BFN("cgFontWithSize", CgFontWithSize);
2795
3013
  BFN("fontByPostScriptName", FontByPostScriptName);