@windowkit/appkit 0.20.0 → 0.22.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
@@ -125,7 +125,7 @@ waits on the UI thread (`test/threaded-verbs.js` covers each row):
125
125
 
126
126
  | from a worker | verbs |
127
127
  | --- | --- |
128
- | unchanged, on the calling thread | surfaces, every `ctx*` (`ctxDrawSymbol` included), layouts and fonts, `symbolSize`, `pasteboardTypeForMIME`, `pasteboardTypeInfo`, `contentTypeFor`, `colorSpace` |
128
+ | unchanged, on the calling thread | surfaces and video surfaces, every `ctx*` (`ctxDrawSymbol` included), layouts and fonts, `symbolSize`, `pasteboardTypeForMIME`, `pasteboardTypeInfo`, `contentTypeFor`, `colorSpace` |
129
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 |
@@ -558,6 +558,120 @@ native.ctxSetGlobalAlpha(win, 0.6);
558
558
  native.ctxDrawSurfaceFaded(win, card, 0, 0, 556, 300, 100, 100, 556, 300, 0.6);
559
559
  ```
560
560
 
561
+ ## Video surfaces
562
+
563
+ A frame a decoder hands over as bytes — ffmpeg over a pipe, a WASM decoder, an addon —
564
+ goes on the screen the way VideoToolbox's own output does: as a YCbCr IOSurface a plain
565
+ layer shows, converted and scaled by the render server. The CPU's share is the copy in.
566
+
567
+ - **`native.createVideoSurface(widthPx, heightPx, options?)`** → `{ handle, iosurfaceId }`.
568
+ `format` is `'NV12'` (the default: two planes, `420v`, or `420f` with `range: 'full'`)
569
+ or `'BGRA'`. `colorSpace` — `'bt709'` (the default), `'bt601'` or `'bt2020'` (SDR) — and
570
+ `range` — `'video'` (the default) or `'full'` — say what an NV12 surface's numbers mean,
571
+ and go on it as the attachments CoreVideo gives a decoded frame: the YCbCr matrix, the
572
+ primaries and the transfer function, which Core Animation reads. Shown through
573
+ `setLayerContentsIOSurface(layer, iosurfaceId)`, which keeps a colour a surface names
574
+ (or derives from CoreVideo's tags: see below). A new surface is black.
575
+ - **`native.writeVideoSurface(target, format, planes, options?)`** — one frame, `planes`
576
+ an array of Buffers or typed arrays: `'NV12'` (Y, then CbCr pairs), `'I420'` (Y, Cb, Cr)
577
+ or `'BGRA'`, each plane `options.strides[i]` bytes a row (packed by default) and checked
578
+ to hold every row; a 4:2:0 chroma plane is `ceil(width / 2)` by `ceil(height / 2)`. An
579
+ NV12 surface takes NV12, and I420 with its chroma interleaved on the way in; a BGRA
580
+ surface takes BGRA, and YCbCr converted. `target` may also be a **2D surface**
581
+ (`createSurface`, `createSurfaceIOSurface`), for a renderer that draws the frame in its
582
+ own paint order — something is drawn over the video — rather than lifting it onto a
583
+ layer: the frame lands at the surface's top-left, `options.width`/`height` of it (the
584
+ surface's size by default), converted with `options.colorSpace` and `range`. A frame's
585
+ fourth byte is ignored: a frame is opaque.
586
+ - **`native.videoSurfaceIsInUse(handle)`** — whether anything still reads the surface; a
587
+ renderer keeping a ring writes only into one this answers `false` for, and in threaded
588
+ mode `surface-released { id }` names the surface a frame took off a layer.
589
+ - **`native.releaseVideoSurface(handle)`** — free it now; idempotent; a layer showing it
590
+ keeps it until it lets go. Every other verb on a released handle throws.
591
+ - **`native.videoFormats()`** → `{ surfaces: ['NV12', 'BGRA'], frames: ['NV12', 'I420',
592
+ 'BGRA'] }`, for a renderer to ask rather than assume.
593
+
594
+ Two things the verbs exist to get right, both measured on screen (`test/video-surface.js`):
595
+
596
+ - **Three planes draw nothing.** A layer shows `420v`, `420f` and `2vuy` surfaces and shows
597
+ `y420`/`f420` as transparent, so an I420 frame is interleaved into NV12, in the copy
598
+ the write makes anyway — 0.27ms at 1080p on an M1 Pro, against 0.07ms for NV12 as it is.
599
+ - **The same colours on a layer, in a bitmap and under `AVPlayerLayer`.** An NV12 surface
600
+ is named the colour space CoreVideo makes of its tags, and `setLayerContentsIOSurface`
601
+ names one the same way for a tagged surface it is handed by id. Shown with the tags
602
+ alone, Core Animation linearises a frame tagged BT.709 throughout with the exact 709
603
+ curve, where `AVPlayerLayer` — the platform's player — VideoToolbox's pixel transfer
604
+ and Core Image all use Apple's 1.961 gamma: a video-range grey of Y′=50 was sRGB 55 on
605
+ such a layer and 44 everywhere else. Named, a frame on a layer, the same frame
606
+ converted into a bitmap by VideoToolbox (about 1ms at 1080p) and the player showing it
607
+ agree to within a level or two. What cannot match is gamut: a layer keeps a 2020
608
+ colour outside sRGB on a wide-gamut panel, and an sRGB bitmap clips it.
609
+
610
+ ## Playing a file
611
+
612
+ A file or URL played by AVFoundation — the platform's decoder, audio, seeking and HLS —
613
+ for a renderer's `<video src>`, with the picture on a layer the renderer places among its
614
+ own, and the frame showing drawable into a surface when something is drawn over it.
615
+
616
+ - **`native.createPlayer(url, { autoPlay, loop, muted, volume, rate })`** →
617
+ `{ id, layer }`. `url` is a path, a `file://` URL or an `http(s)` one. `layer` is the
618
+ `AVPlayerLayer` that shows it, a handle every layer verb takes (`addSublayer`,
619
+ `setLayerProps`, `removeFromSuperlayer`); its `videoGravity` fills the layer, so the
620
+ renderer fits the picture itself. Nothing plays until `autoPlay` or `paused: false`.
621
+ - **`native.playerSet(id, { paused, rate, volume, muted, loop })`** — what it names
622
+ changes, the rest stays; **`native.playerSeek(id, seconds)`** — exact, not to the
623
+ nearest keyframe.
624
+ - **`native.playerCopyFrame(id, surface)`** → `{ width, height, time, written }`, or
625
+ `null` when no frame is newer than the last one copied: the frame showing now,
626
+ converted into a 2D surface of the frame's size in the colours the layer shows it in
627
+ (the same conversion as `writeVideoSurface`). A surface of another size is told the
628
+ size and left alone (`written: false`). It reads `AVPlayerItemVideoOutput` on the
629
+ calling thread, as a display link would, so a worker's renderer copies without a hop.
630
+ - **`native.releasePlayer(id)`** — stopped, and everything it holds let go; its events
631
+ stop.
632
+
633
+ Its events go through `setBackendEventCallback`, by `id`: `player-metadata { width,
634
+ height, duration }` once the item is ready, and again if either moves (`duration` is
635
+ `Infinity` for a live stream); `player-state { playing, rate }` when it starts or stops;
636
+ `player-time { currentTime }` four times a second while it plays and once after a seek;
637
+ `player-ended` at the end of an item that does not loop; `player-error { message }`.
638
+
639
+ `test/player.js` plays `test/fixtures/clip.mp4` — 1.5s of one colour, 160x90 H.264
640
+ tagged BT.709 — on a layer and copied into a surface beside it, and holds the two to
641
+ the same colour on screen: 211, 127, 67 and 211, 127, 68 on an M1 Pro.
642
+
643
+ ## Text: at a display's scale
644
+
645
+ A text verb's size is the caller's pixels, and a renderer that draws in device pixels hands
646
+ over device pixels: a 13px label on a 2x display is 26. CoreText reads some of a face's data
647
+ by point size, though — the optical size and tracking San Francisco is set at, the tracking
648
+ Apple Color Emoji's `trak` table adds below 29pt — so a font made at 26 is San Francisco as
649
+ it is set at 26pt, 8% narrower than AppKit sets the 13pt label, and a 19px emoji is 1em wide
650
+ where it is 23pt at 19pt. Faces with no such data (Helvetica, Menlo) measure the same either
651
+ way.
652
+
653
+ - **`scale`** — the display's backing scale, as a `matchFont` option and a third argument
654
+ to `cgFontWithSize(cg, size, scale)` and `fontByPostScriptName(name, size, scale)`. The
655
+ font is made at `size / scale` points under a matrix that scales it by `scale`, so CoreText
656
+ reads the face at its point size, and every verb answers in the caller's pixels as before:
657
+ metrics, advances, `fontShapeText`'s runs, a layout's lines, runs, carets and hit testing,
658
+ and `drawLayout`, `ctxDrawGlyphs`, `drawLayoutGradient` and `layoutCoverage` draw it there.
659
+ `fontMetrics(font).size` is the size asked for. A copy — `fontWithSize`, variations,
660
+ features, a `fontFallbackFor` face, a face a layout substitutes — keeps the scale. Absent
661
+ or 1, nothing changes.
662
+
663
+ Two answers are the scaled face's own rather than the point-size face's times the scale. An
664
+ emoji's advance: CoreText rounds a bitmap glyph's to a whole pixel of the font it is set in,
665
+ a whole point at 1x and half of one at 2x, so a 19px emoji is 45 pixels at 2x where the
666
+ point-size face's 23 points are 46. And the system face's `postScriptName` is
667
+ `.SFNS-Regular`, CoreText's name for it, where NSFont calls the unscaled one by its alias,
668
+ `.AppleSystemUIFont`.
669
+
670
+ ```js
671
+ // 13px at 2x: San Francisco as AppKit sets 13pt, measured in device pixels
672
+ const label = native.matchFont({ families: ['system-ui'], size: 26, scale: 2 });
673
+ ```
674
+
561
675
  ## Text: letter spacing and OpenType features
562
676
 
563
677
  The text verbs a renderer lays paragraphs out and shapes glyph runs with —
package/binding.gyp CHANGED
@@ -9,7 +9,9 @@
9
9
  "src/notifications.mm",
10
10
  "src/calendars.mm",
11
11
  "src/screencolor.mm",
12
- "src/threaded.mm"
12
+ "src/threaded.mm",
13
+ "src/video.mm",
14
+ "src/player.mm"
13
15
  ],
14
16
  "include_dirs": [
15
17
  "<!@(node -p \"require('node-addon-api').include\")"
@@ -28,6 +30,9 @@
28
30
  "-framework CoreGraphics",
29
31
  "-framework ImageIO",
30
32
  "-framework IOSurface",
33
+ "-framework CoreVideo",
34
+ "-framework VideoToolbox",
35
+ "-framework CoreMedia",
31
36
  "-framework UniformTypeIdentifiers",
32
37
  "-framework AVFoundation",
33
38
  "-framework CoreLocation",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@windowkit/appkit",
3
- "version": "0.20.0",
3
+ "version": "0.22.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/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"
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/video-surface.js && node test/player.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/text-scale.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
@@ -1718,6 +1718,12 @@ void InitScreenColor(Napi::Env env, Napi::Object exports);
1718
1718
  // src/threaded.mm — threaded mode: runMain parks the main thread in
1719
1719
  // [NSApp run], commands in through the main run loop, events out in batches.
1720
1720
  void InitThreaded(Napi::Env env, Napi::Object exports);
1721
+ // src/video.mm — video surfaces: a YCbCr or BGRA IOSurface a layer shows
1722
+ // as it is, frames written into it, and frames converted into a surface.
1723
+ void InitVideo(Napi::Env env, Napi::Object exports);
1724
+ // src/player.mm — a file or URL played by AVFoundation: an AVPlayer, its
1725
+ // AVPlayerLayer as a layer handle, and the frame showing copied into a surface.
1726
+ void InitPlayer(Napi::Env env, Napi::Object exports);
1721
1727
 
1722
1728
  static Napi::Object Init(Napi::Env env, Napi::Object exports) {
1723
1729
  #define FN(js, fn) exports.Set(js, Napi::Function::New(env, fn))
@@ -1764,6 +1770,8 @@ static Napi::Object Init(Napi::Env env, Napi::Object exports) {
1764
1770
  InitCalendars(env, exports);
1765
1771
  InitScreenColor(env, exports);
1766
1772
  InitThreaded(env, exports);
1773
+ InitVideo(env, exports);
1774
+ InitPlayer(env, exports);
1767
1775
  return exports;
1768
1776
  }
1769
1777
 
package/src/backend.mm CHANGED
@@ -1604,6 +1604,22 @@ static CALSurface* SurfaceFrom(Napi::Value v) {
1604
1604
  return s;
1605
1605
  }
1606
1606
 
1607
+ // A 2D surface's bitmap, for video.mm's writeVideoSurface: false, with a
1608
+ // JS error pending, when `v` is not a live surface handle.
1609
+ struct CALSurfaceBits {
1610
+ uint8_t* data;
1611
+ size_t width, height, bytesPerRow;
1612
+ };
1613
+ bool CALSurfaceBitmap(Napi::Value v, CALSurfaceBits* out) {
1614
+ CALSurface* s = SurfaceFrom(v);
1615
+ if (!s) return false;
1616
+ out->data = (uint8_t*)CGBitmapContextGetData(s->ctx);
1617
+ out->width = s->width;
1618
+ out->height = s->height;
1619
+ out->bytesPerRow = CGBitmapContextGetBytesPerRow(s->ctx);
1620
+ return true;
1621
+ }
1622
+
1607
1623
  // For the fire-and-forget drawing verbs: the context to draw into, or a
1608
1624
  // scratch bitmap when the surface is released (the error is already
1609
1625
  // pending; the stroke lands nowhere anyone looks).
@@ -1661,8 +1677,12 @@ static Napi::Value CreateSurface(const Napi::CallbackInfo& info) {
1661
1677
  // A surface this bridge draws into is named sRGB whatever it said before
1662
1678
  // (`keep` false): what is in it is what an sRGB context wrote. One it is
1663
1679
  // 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.
1680
+ // process's buffer, a video frame) keeps a space its producer named, and is
1681
+ // taken to be sRGB, like everything else here, when it names none. A video
1682
+ // frame says what it is the way CoreVideo writes a decoded buffer's
1683
+ // attachments onto its IOSurface — matrix, primaries, transfer function —
1684
+ // and is named the colour space those make (video.mm says why).
1685
+ bool CALNameVideoColorSpace(IOSurfaceRef ios);
1666
1686
  void CALNameSurfaceSRGB(IOSurfaceRef ios, bool keep) {
1667
1687
  static const CFPropertyListRef srgb = [] {
1668
1688
  CGColorSpaceRef cs = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
@@ -1678,6 +1698,8 @@ void CALNameSurfaceSRGB(IOSurfaceRef ios, bool keep) {
1678
1698
  CFRelease(named);
1679
1699
  return;
1680
1700
  }
1701
+ // a video frame's tags, named as the colour space they make (video.mm)
1702
+ if (CALNameVideoColorSpace(ios)) return;
1681
1703
  }
1682
1704
  IOSurfaceSetValue(ios, kIOSurfaceColorSpace, srgb);
1683
1705
  }
@@ -4649,7 +4671,60 @@ static NSFontWeight FontWeightFromCss(double weight) {
4649
4671
  return NSFontWeightBlack;
4650
4672
  }
4651
4673
 
4652
- // matchFont({ families: [..], size, weight (100-900), italic }) -> font handle
4674
+ // --- a font at a display's scale ---------------------------------------------
4675
+ //
4676
+ // A size here is in the caller's pixels, and on a Retina display those are
4677
+ // device pixels: a 13px label is 26. A font made at 26 is a 26pt font to
4678
+ // CoreText, which reads some of a face's data by point size — the optical
4679
+ // size and tracking San Francisco is set at, the tracking Apple Color Emoji's
4680
+ // trak table adds below 29pt — so the label was set as SF is at 26pt, 8%
4681
+ // narrower than AppKit sets it at 13, and a 19px emoji was 1em wide where it
4682
+ // is 23pt at 19pt. Faces with no such data measure the same either way.
4683
+ //
4684
+ // So a font may be made at a `scale`: at size / scale points, under a matrix
4685
+ // that scales it by `scale`. CoreText reads the face at its point size and
4686
+ // answers in the caller's pixels — metrics, advances, bounds, a line's width,
4687
+ // a caret's offset — through the matrix. Two things it does not take through
4688
+ // it, and every reader of them here goes through the helpers below: a run's
4689
+ // glyph origins, which are in text space, before the font matrix
4690
+ // (BRunPositions); and a bitmap glyph, which CoreText draws at the font's
4691
+ // point size whatever its matrix (BDrawGlyphsAtScale). A copy of a scaled
4692
+ // font — another size, variations, features, a fallback face — keeps the
4693
+ // scale. A font made without one has the identity matrix, and nothing here
4694
+ // changes for it.
4695
+
4696
+ /** The scale a font was made at: its matrix's, or 1. */
4697
+ static double BFontScale(CTFontRef font) {
4698
+ if (!font) return 1;
4699
+ const CGAffineTransform m = CTFontGetMatrix(font);
4700
+ return m.a > 0 && m.a == m.d && m.b == 0 && m.c == 0 && m.tx == 0 &&
4701
+ m.ty == 0
4702
+ ? m.a
4703
+ : 1;
4704
+ }
4705
+
4706
+ /** A scale argument: a finite number above 0, else 1. */
4707
+ static double BScaleOf(Napi::Value v) {
4708
+ if (!v.IsNumber()) return 1;
4709
+ const double scale = v.As<Napi::Number>().DoubleValue();
4710
+ return scale > 0 && std::isfinite(scale) ? scale : 1;
4711
+ }
4712
+
4713
+ /** `font` (owned, released) as the same face under the matrix of `scale`,
4714
+ * at the point size it already has. */
4715
+ static CTFontRef BAtScale(CTFontRef font, double scale) {
4716
+ if (!font || scale == 1) return font;
4717
+ const CGAffineTransform m = CGAffineTransformMakeScale(scale, scale);
4718
+ CTFontRef scaled = CTFontCreateCopyWithAttributes(font, 0, &m, NULL);
4719
+ if (!scaled) return font;
4720
+ CFRelease(font);
4721
+ return scaled;
4722
+ }
4723
+
4724
+ // matchFont({ families: [..], size, weight (100-900), italic, scale? })
4725
+ // -> font handle
4726
+ // `size` is in the caller's pixels; `scale`, the display's, makes the font
4727
+ // at size / scale points under a matrix of `scale` (see above).
4653
4728
  static NSFont* ResolveFamily(NSString* family, double size, double weight,
4654
4729
  bool italic) {
4655
4730
  NSFontWeight w = FontWeightFromCss(weight);
@@ -4711,7 +4786,8 @@ static NSFont* ResolveFamily(NSString* family, double size, double weight,
4711
4786
  static Napi::Value MatchFont(const Napi::CallbackInfo& info) {
4712
4787
  Napi::Env env = info.Env();
4713
4788
  Napi::Object o = info[0].As<Napi::Object>();
4714
- double size = BNumOr(o, "size", 14);
4789
+ const double scale = BScaleOf(o.Get("scale"));
4790
+ double size = BNumOr(o, "size", 14) / scale;
4715
4791
  double weight = BNumOr(o, "weight", 400);
4716
4792
  bool italic = BBoolOr(o, "italic", false);
4717
4793
  NSFont* font = nil;
@@ -4726,9 +4802,18 @@ static Napi::Value MatchFont(const Napi::CallbackInfo& info) {
4726
4802
  NSFontWeight w = weight >= 550 ? NSFontWeightSemibold : NSFontWeightRegular;
4727
4803
  font = [NSFont systemFontOfSize:size weight:w];
4728
4804
  }
4805
+ if (scale != 1 && font) {
4806
+ CTFontRef scaled =
4807
+ BAtScale((CTFontRef)CFBridgingRetain(font), scale);
4808
+ font = (__bridge_transfer NSFont*)scaled;
4809
+ }
4729
4810
  return BWrapRetained(env, font);
4730
4811
  }
4731
4812
 
4813
+ // fontMetrics(font) -> { ascent, descent, leading, capHeight, xHeight, size,
4814
+ // familyName, postScriptName }
4815
+ // In the caller's pixels, a scaled font's included: `size` is the one the
4816
+ // font was asked for.
4732
4817
  static Napi::Value FontMetrics(const Napi::CallbackInfo& info) {
4733
4818
  Napi::Env env = info.Env();
4734
4819
  NSFont* font = BDeref<NSFont*>(info[0]);
@@ -4739,7 +4824,7 @@ static Napi::Value FontMetrics(const Napi::CallbackInfo& info) {
4739
4824
  r.Set("leading", CTFontGetLeading(ct));
4740
4825
  r.Set("capHeight", CTFontGetCapHeight(ct));
4741
4826
  r.Set("xHeight", CTFontGetXHeight(ct));
4742
- r.Set("size", CTFontGetSize(ct));
4827
+ r.Set("size", CTFontGetSize(ct) * BFontScale(ct));
4743
4828
  r.Set("familyName", font.familyName ? font.familyName.UTF8String : "");
4744
4829
  r.Set("postScriptName", font.fontName.UTF8String);
4745
4830
  return r;
@@ -4783,6 +4868,71 @@ static bool BCheckFontArg(const Napi::CallbackInfo& info, const char* fn) {
4783
4868
  return false;
4784
4869
  }
4785
4870
 
4871
+ static CTFontRef BRunFont(CTRunRef run) {
4872
+ return (CTFontRef)CFDictionaryGetValue(CTRunGetAttributes(run),
4873
+ kCTFontAttributeName);
4874
+ }
4875
+
4876
+ // A run's glyph origins from its line's origin, y up, in the caller's pixels.
4877
+ // CTRunGetPositions answers in text space, before the font matrix, where
4878
+ // everything else CoreText measures of a scaled font has the matrix applied;
4879
+ // so a scaled run's origins are multiplied by its scale here. A line set in
4880
+ // faces of one scale, which is every line a caller makes, is in one space.
4881
+ static void BRunPositions(CTRunRef run, std::vector<CGPoint>* out) {
4882
+ const CFIndex count = CTRunGetGlyphCount(run);
4883
+ out->resize(count > 0 ? (size_t)count : 0);
4884
+ if (count <= 0) return;
4885
+ CTRunGetPositions(run, CFRangeMake(0, 0), out->data());
4886
+ const double scale = BFontScale(BRunFont(run));
4887
+ if (scale == 1) return;
4888
+ for (CGPoint& p : *out) {
4889
+ p.x *= scale;
4890
+ p.y *= scale;
4891
+ }
4892
+ }
4893
+
4894
+ // A scaled font as its point-size face: the same font with the identity
4895
+ // matrix. Kept, because a terminal draws its runs every frame. +1.
4896
+ static CTFontRef BAtPointSize(CTFontRef font) {
4897
+ static NSCache* kept = [[NSCache alloc] init];
4898
+ id key = (__bridge id)font;
4899
+ id hit = [kept objectForKey:key];
4900
+ if (!hit) {
4901
+ const CGAffineTransform identity = CGAffineTransformIdentity;
4902
+ CTFontRef plain = CTFontCreateCopyWithAttributes(font, 0, &identity, NULL);
4903
+ if (!plain) return (CTFontRef)CFRetain(font);
4904
+ hit = (__bridge_transfer id)plain;
4905
+ [kept setObject:hit forKey:key];
4906
+ }
4907
+ return (CTFontRef)CFBridgingRetain(hit);
4908
+ }
4909
+
4910
+ // A scaled font's glyphs drawn the way AppKit draws text to a Retina backing
4911
+ // store: the face at its point size, under a CTM scaled by the scale. Drawn
4912
+ // through the font's matrix instead, an outline came out right and a bitmap
4913
+ // glyph — Apple Color Emoji's — at the font's point size, so an emoji was
4914
+ // half its size at 2x. `origins` are from `at`, in the caller's pixels, y up,
4915
+ // as BRunPositions answers them; `at` is in the context's user space, and the
4916
+ // text matrix is the y-flip every draw here sets.
4917
+ static void BDrawGlyphsAtScale(CGContextRef ctx, CTFontRef font,
4918
+ const CGGlyph* glyphs, const CGPoint* origins,
4919
+ size_t count, CGPoint at) {
4920
+ if (count == 0) return;
4921
+ const double scale = BFontScale(font);
4922
+ std::vector<CGPoint> points(count);
4923
+ for (size_t i = 0; i < count; i++) {
4924
+ points[i] = CGPointMake(origins[i].x / scale, origins[i].y / scale);
4925
+ }
4926
+ CTFontRef plain = BAtPointSize(font);
4927
+ CGContextSaveGState(ctx);
4928
+ CGContextTranslateCTM(ctx, at.x, at.y);
4929
+ CGContextScaleCTM(ctx, scale, scale);
4930
+ CGContextSetTextMatrix(ctx, CGAffineTransformMakeScale(1, -1));
4931
+ CTFontDrawGlyphs(plain, glyphs, points.data(), (CFIndex)count, ctx);
4932
+ CGContextRestoreGState(ctx);
4933
+ CFRelease(plain);
4934
+ }
4935
+
4786
4936
  // One code point -> its UTF-16 form. False for a surrogate or an
4787
4937
  // out-of-range value.
4788
4938
  static bool BUtf16ForCodepoint(uint32_t cp, unichar out[2], CFIndex* len) {
@@ -5027,7 +5177,8 @@ static Napi::Value FontFallbackFor(const Napi::CallbackInfo& info) {
5027
5177
  // substitution — fontFallbackFor's answer, a fontShapeText run's font — has
5028
5178
  // no family to re-match by, and asking the cascade again at the new size is
5029
5179
  // a different question with a possibly different answer. This is how such a
5030
- // face answers metrics and advances at every size, as itself.
5180
+ // face answers metrics and advances at every size, as itself. `size` is in
5181
+ // the caller's pixels, and a scaled font's copy keeps its scale.
5031
5182
  static Napi::Value FontWithSize(const Napi::CallbackInfo& info) {
5032
5183
  Napi::Env env = info.Env();
5033
5184
  if (!BCheckFontArg(info, "fontWithSize")) return env.Undefined();
@@ -5037,8 +5188,11 @@ static Napi::Value FontWithSize(const Napi::CallbackInfo& info) {
5037
5188
  .ThrowAsJavaScriptException();
5038
5189
  return env.Undefined();
5039
5190
  }
5040
- CTFontRef sized = CTFontCreateCopyWithAttributes(BFontFrom(info[0]),
5041
- (CGFloat)size, NULL, NULL);
5191
+ CTFontRef font = BFontFrom(info[0]);
5192
+ const double scale = BFontScale(font);
5193
+ const CGAffineTransform m = CGAffineTransformMakeScale(scale, scale);
5194
+ CTFontRef sized =
5195
+ CTFontCreateCopyWithAttributes(font, (CGFloat)(size / scale), &m, NULL);
5042
5196
  if (!sized) return env.Null();
5043
5197
  return Napi::External<void>::New(env, (void*)sized, [](Napi::Env, void* d) {
5044
5198
  CFRelease(d);
@@ -5094,7 +5248,7 @@ static Napi::Value FontShapeText(const Napi::CallbackInfo& info) {
5094
5248
  std::vector<CGPoint> positions((size_t)count);
5095
5249
  std::vector<CGSize> advances((size_t)count);
5096
5250
  CTRunGetGlyphs(run, CFRangeMake(0, 0), glyphs.data());
5097
- CTRunGetPositions(run, CFRangeMake(0, 0), positions.data());
5251
+ BRunPositions(run, &positions);
5098
5252
  CTRunGetAdvances(run, CFRangeMake(0, 0), advances.data());
5099
5253
  CFDictionaryRef rattrs = CTRunGetAttributes(run);
5100
5254
  CTFontRef rfont =
@@ -5192,27 +5346,33 @@ static Napi::Value FontFromData(const Napi::CallbackInfo& info) {
5192
5346
  return r;
5193
5347
  }
5194
5348
 
5195
- // cgFontWithSize(cgExternal, size) -> CTFont handle (what layouts take)
5349
+ // cgFontWithSize(cgExternal, size, scale?) -> CTFont handle (what layouts
5350
+ // take), at a scale as matchFont makes one
5196
5351
  static Napi::Value CgFontWithSize(const Napi::CallbackInfo& info) {
5197
5352
  Napi::Env env = info.Env();
5198
5353
  CGFontRef cg = (CGFontRef)info[0].As<Napi::External<void>>().Data();
5199
5354
  double size = info[1].As<Napi::Number>().DoubleValue();
5200
- CTFontRef ct = CTFontCreateWithGraphicsFont(cg, size, NULL, NULL);
5355
+ const double scale = BScaleOf(info[2]);
5356
+ const CGAffineTransform m = CGAffineTransformMakeScale(scale, scale);
5357
+ CTFontRef ct = CTFontCreateWithGraphicsFont(cg, size / scale,
5358
+ scale == 1 ? NULL : &m, NULL);
5201
5359
  if (!ct) return env.Null();
5202
5360
  return Napi::External<void>::New(env, (void*)ct, [](Napi::Env, void* d) {
5203
5361
  CFRelease(d);
5204
5362
  });
5205
5363
  }
5206
5364
 
5207
- // fontByPostScriptName(name, size) -> CTFont handle or null. Exact: a
5208
- // fallback answer (a substituted face) reads as null so the caller can try
5209
- // the next route.
5365
+ // fontByPostScriptName(name, size, scale?) -> CTFont handle or null, at a
5366
+ // scale as matchFont makes one. Exact: a fallback answer (a substituted
5367
+ // face) reads as null so the caller can try the next route.
5210
5368
  static Napi::Value FontByPostScriptName(const Napi::CallbackInfo& info) {
5211
5369
  Napi::Env env = info.Env();
5212
5370
  NSString* name = BToNSString(info[0]);
5213
5371
  double size = info[1].As<Napi::Number>().DoubleValue();
5214
- CTFontRef ct =
5215
- CTFontCreateWithName((__bridge CFStringRef)name, size, NULL);
5372
+ const double scale = BScaleOf(info[2]);
5373
+ const CGAffineTransform m = CGAffineTransformMakeScale(scale, scale);
5374
+ CTFontRef ct = CTFontCreateWithName((__bridge CFStringRef)name,
5375
+ size / scale, scale == 1 ? NULL : &m);
5216
5376
  if (!ct) return env.Null();
5217
5377
  CFStringRef got = CTFontCopyPostScriptName(ct);
5218
5378
  bool exact = got && [(__bridge NSString*)got isEqualToString:name];
@@ -5404,6 +5564,9 @@ struct CALLine {
5404
5564
  descent = 0;
5405
5565
  long start = 0, end = 0; // UTF-16 units
5406
5566
  bool hardBreak = false; // the line ends with a newline it owns
5567
+ // a run of bitmap glyphs in a scaled face, which drawLayout draws apart
5568
+ // (BDrawGlyphsAtScale)
5569
+ bool bitmapsAtScale = false;
5407
5570
  std::vector<CALRun> runs;
5408
5571
  };
5409
5572
 
@@ -5745,6 +5908,14 @@ static Napi::Value CreateLayout(const Napi::CallbackInfo& info) {
5745
5908
  CTRunGetPositions(run, CFRangeMake(0, 1), &first);
5746
5909
  rx = first.x;
5747
5910
  }
5911
+ // in text space, before a scaled face's matrix (BRunPositions)
5912
+ CTFontRef rfont = BRunFont(run);
5913
+ const double rscale = BFontScale(rfont);
5914
+ rx *= rscale;
5915
+ if (rscale != 1 &&
5916
+ (CTFontGetSymbolicTraits(rfont) & kCTFontTraitColorGlyphs)) {
5917
+ L.bitmapsAtScale = true;
5918
+ }
5748
5919
  }
5749
5920
  CALRun R;
5750
5921
  R.x = rx;
@@ -5855,9 +6026,40 @@ static Napi::Value DrawLayout(const Napi::CallbackInfo& info) {
5855
6026
  // per glyph run. Standard recipe: flip the text matrix, position each
5856
6027
  // line at its baseline in the flipped space.
5857
6028
  CGContextSetTextMatrix(ctx, CGAffineTransformMakeScale(1, -1));
6029
+ std::vector<CGPoint> positions;
5858
6030
  for (const CALLine& L : layout->lines) {
5859
- CGContextSetTextPosition(ctx, x + L.x, y + L.baseline);
5860
- CTLineDraw(L.line, ctx);
6031
+ if (!L.bitmapsAtScale) {
6032
+ CGContextSetTextPosition(ctx, x + L.x, y + L.baseline);
6033
+ CTLineDraw(L.line, ctx);
6034
+ continue;
6035
+ }
6036
+ // a line with a scaled face's bitmap glyphs in it is drawn a run at a
6037
+ // time, and a scaled run at its face's point size under a scaled CTM:
6038
+ // CTRunDraw, unlike CTLineDraw, does not draw through the font matrix
6039
+ // either, outlines included
6040
+ CFArrayRef runs = CTLineGetGlyphRuns(L.line);
6041
+ for (CFIndex ri = 0; ri < CFArrayGetCount(runs); ri++) {
6042
+ CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(runs, ri);
6043
+ CTFontRef font = BRunFont(run);
6044
+ if (!font || BFontScale(font) == 1) {
6045
+ CGContextSetTextPosition(ctx, x + L.x, y + L.baseline);
6046
+ CTRunDraw(run, ctx, CFRangeMake(0, 0));
6047
+ continue;
6048
+ }
6049
+ const CFIndex count = CTRunGetGlyphCount(run);
6050
+ if (count <= 0) continue;
6051
+ std::vector<CGGlyph> glyphs((size_t)count);
6052
+ CTRunGetGlyphs(run, CFRangeMake(0, 0), glyphs.data());
6053
+ BRunPositions(run, &positions);
6054
+ CGContextSaveGState(ctx);
6055
+ CGColorRef ink = (CGColorRef)CFDictionaryGetValue(
6056
+ CTRunGetAttributes(run), kCTForegroundColorAttributeName);
6057
+ if (ink) CGContextSetFillColorWithColor(ctx, ink);
6058
+ BDrawGlyphsAtScale(ctx, font, glyphs.data(), positions.data(),
6059
+ (size_t)count,
6060
+ CGPointMake(x + L.x, y + L.baseline));
6061
+ CGContextRestoreGState(ctx);
6062
+ }
5861
6063
  }
5862
6064
  CGContextRestoreGState(ctx);
5863
6065
  return info.Env().Undefined();
@@ -5897,8 +6099,14 @@ static Napi::Value CtxDrawGlyphs(const Napi::CallbackInfo& info) {
5897
6099
  BGlyphOriginsArg(run.Get("positions"), &positionStore);
5898
6100
  size_t count = std::min(nGlyphs, positionStore.size());
5899
6101
  if (count == 0) continue;
5900
- CTFontDrawGlyphs(BFontFrom(fv), glyphs, positionStore.data(),
5901
- (CFIndex)count, ctx);
6102
+ CTFontRef font = BFontFrom(fv);
6103
+ if (BFontScale(font) != 1) {
6104
+ // the origins are the caller's pixels, in text space through the flip
6105
+ BDrawGlyphsAtScale(ctx, font, glyphs, positionStore.data(), count,
6106
+ CGPointZero);
6107
+ continue;
6108
+ }
6109
+ CTFontDrawGlyphs(font, glyphs, positionStore.data(), (CFIndex)count, ctx);
5902
6110
  }
5903
6111
  CGContextRestoreGState(ctx);
5904
6112
  return info.Env().Undefined();
@@ -6060,7 +6268,7 @@ static Napi::Value DrawLayoutGradient(const Napi::CallbackInfo& info) {
6060
6268
  std::vector<CGGlyph> glyphs((size_t)count);
6061
6269
  std::vector<CGPoint> positions((size_t)count);
6062
6270
  CTRunGetGlyphs(run, CFRangeMake(0, 0), glyphs.data());
6063
- CTRunGetPositions(run, CFRangeMake(0, 0), positions.data());
6271
+ BRunPositions(run, &positions);
6064
6272
  for (CFIndex g = 0; g < count; g++) {
6065
6273
  CGAffineTransform t = {1, 0, 0, -1,
6066
6274
  x + L.x + positions[(size_t)g].x,
@@ -6333,7 +6541,7 @@ static Napi::Value LayoutCoverage(const Napi::CallbackInfo& info) {
6333
6541
  glyphs.resize((size_t)count);
6334
6542
  positions.resize((size_t)count);
6335
6543
  CTRunGetGlyphs(run, CFRangeMake(0, 0), glyphs.data());
6336
- CTRunGetPositions(run, CFRangeMake(0, 0), positions.data());
6544
+ BRunPositions(run, &positions);
6337
6545
  for (size_t g = 0; g < (size_t)count; g++) {
6338
6546
  // a glyph shaping deleted, such as a ligature's second half
6339
6547
  if (glyphs[g] == kCGFontIndexInvalid) continue;
@@ -6378,6 +6586,11 @@ static Napi::Value LayoutCoverage(const Napi::CallbackInfo& info) {
6378
6586
  CGContextSetGrayFillColor(ctx, 0, 1);
6379
6587
  CGContextSetTextMatrix(ctx, CGAffineTransformMakeScale(1, -1));
6380
6588
  for (const DrawnGlyph& d : drawn) {
6589
+ if (BFontScale(d.font) != 1) {
6590
+ const CGPoint here = CGPointZero;
6591
+ BDrawGlyphsAtScale(ctx, d.font, &d.glyph, &here, 1, d.origin);
6592
+ continue;
6593
+ }
6381
6594
  // CTFontDrawGlyphs reads positions in text space, through the flip
6382
6595
  const CGPoint at = CGPointMake(d.origin.x, -d.origin.y);
6383
6596
  CTFontDrawGlyphs(d.font, &d.glyph, &at, 1, ctx);