@windowkit/appkit 0.11.0 → 0.13.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*`, layouts and fonts, `pasteboardTypeForMIME`, `pasteboardTypeInfo`, `contentTypeFor`, `colorSpace` |
128
+ | unchanged, on the calling thread | 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`; 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 |
@@ -524,6 +524,72 @@ const label = native.createLayout({
524
524
  });
525
525
  ```
526
526
 
527
+ ## Text: a layout's coverage
528
+
529
+ - **`native.layoutCoverage(layout, pad?)`** — `{ width, height, data }`: how much of each
530
+ pixel a `createLayout` layout's glyphs cover, one byte a pixel, without drawing the layout
531
+ anywhere. It is for text drawn where a surface is not, such as a GL surface's label atlas
532
+ or a signed distance field made from a string. The raster is the layout's box in whole
533
+ pixels (its `width` and `height` rounded up) with `pad` pixels round it, and a fractional
534
+ pad rounds up. `data` is a `Uint8Array` of `width × height` bytes, row-major, the top row
535
+ first, and the layout's origin, the `x, y` that `drawLayout` is handed, is at
536
+ `(pad, pad)`. `null` for anything that is not a layout, and for an empty layout with no
537
+ pad.
538
+
539
+ It is the outlines' own coverage, not the ink the screen gets. Every glyph's outline goes
540
+ where the typesetter put it, unrounded, and the layout is filled once with the non-zero rule,
541
+ so glyphs that overlap cover a pixel once. The fill is signed-area accumulation, the
542
+ rasterizer ntk (react-x11's X11 text engine) uses, so the two give the same bytes for the
543
+ same outlines at the same positions. Nothing is smoothed, nothing is held on a glyph cache's
544
+ subpixel grid, and a span's colour plays no part: a translucent span covers what an opaque
545
+ one does. A glyph with no outline but ink of its own, Apple Color Emoji's bitmaps, comes out
546
+ as its silhouette. The same layout drawn by `drawLayout` onto a transparent surface is
547
+ 30–45% heavier at text sizes, which is font smoothing, and its glyphs sit on half pixels.
548
+
549
+ It runs on the calling thread in threaded mode too, and answers the same bytes there.
550
+
551
+ ```js
552
+ const font = native.matchFont({ families: ['system-ui'], size: 26 });
553
+ const label = native.createLayout({ spans: [{ text: 'Hamburg', font }] });
554
+ const { width, height, data } = native.layoutCoverage(label.handle, 4);
555
+ // data[y * width + x] is 0-255, and the text's origin is at (4, 4)
556
+ ```
557
+
558
+ ## SF Symbols in a surface
559
+
560
+ The system's icons by name — what `createStatusItem`'s `image` and a menu item's `iconName`
561
+ already take — drawn into a surface, for a renderer's own content:
562
+
563
+ - **`native.ctxDrawSymbol(surface, name, x, y, width, height, options?)`** — the symbol fitted
564
+ into the rect, centred and keeping its proportions, in the **current fill colour**. A symbol
565
+ is a template, its shape in whatever colour it is drawn with, so it is drawn the way
566
+ `ctxDrawGlyphs` draws a run: through the surface's CTM and clip, at its global alpha and
567
+ blend mode, over what is already there. Answers `false`, drawing nothing, for a name the
568
+ catalogue does not know — a name from another platform's icon theme simply misses.
569
+ - **`native.symbolSize(name, options?)`** — `{ width, height }` in points, the padding the
570
+ symbol is designed with included, or `null` for an unknown name: the box a symbol sits in
571
+ beside text of the same point size.
572
+
573
+ | option | |
574
+ | --------------- | ----------------------------------------------------------------------------- |
575
+ | `pointSize` | the size it is designed for, default 13 — the size of the text beside it |
576
+ | `weight` | 100-900, default 400: the nearest of AppKit's weights, as `matchFont` maps it |
577
+ | `scale` | `'small'`, `'medium'` (default) or `'large'`, relative to the point size |
578
+ | `variableValue` | 0-1, how much of a variable symbol shows — macOS 13 and later, ignored before |
579
+
580
+ Both run on the calling thread in threaded mode too, and draw the same pixels there.
581
+
582
+ ```js
583
+ const s = native.createSurface(96, 96, 2);
584
+ native.ctxSetFillColor(s, 0.2, 0.4, 0.8, 1);
585
+ const { width, height } = native.symbolSize('speaker.wave.3.fill', { pointSize: 20 });
586
+ native.ctxDrawSymbol(s, 'speaker.wave.3.fill', 8, 8, width * 2, height * 2, {
587
+ pointSize: 20,
588
+ weight: 600,
589
+ variableValue: 0.66,
590
+ });
591
+ ```
592
+
527
593
  ## App lifecycle: open-URL, open-file, reopen, quit
528
594
 
529
595
  The OS talks to the application as a whole through Apple Events: a URL for a scheme
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@windowkit/appkit",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "description": "Retained-mode AppKit backend for Node.js: Core Animation (CALayer) layer trees, CoreText layout and drawing, IOSurface presentation, NSMenu, and native control bezels — the macOS half of react-x11.",
5
5
  "author": "Andrey Sidorov <andrey.sidorov@gmail.com>",
6
6
  "license": "MIT",
@@ -43,7 +43,7 @@
43
43
  "install": "node scripts/install.js",
44
44
  "build": "node-gyp rebuild",
45
45
  "demo": "node demo/demo.js",
46
- "test": "node test/app-lifecycle.js && node test/animation.js && node test/accessibility-display.js && node test/ignores-mouse-events.js && node test/surface-blit.js && node test/text-features.js && node test/eventkit-permissions.js && node test/calendars.js && node test/calendar-writes.js && node test/screencolor.js && node test/threaded.js && node test/threaded-verbs.js && node test/threaded-frames.js && node test/threaded-resize.js && node test/ending-worker.js && node test/live-resize.js && node test/activation-policy.js"
46
+ "test": "node test/app-lifecycle.js && node test/animation.js && node test/accessibility-display.js && node test/ignores-mouse-events.js && node test/surface-blit.js && node test/text-features.js && node test/text-coverage.js && node test/symbols.js && node test/eventkit-permissions.js && node test/calendars.js && node test/calendar-writes.js && node test/screencolor.js && node test/threaded.js && node test/threaded-verbs.js && node test/threaded-frames.js && node test/threaded-resize.js && node test/ending-worker.js && node test/live-resize.js && node test/activation-policy.js"
47
47
  },
48
48
  "dependencies": {
49
49
  "node-addon-api": "^8.3.0"
Binary file
package/src/backend.mm CHANGED
@@ -4196,19 +4196,24 @@ static Napi::Value ScrollSurface(const Napi::CallbackInfo& info) {
4196
4196
  // fonts + text layout (CoreText)
4197
4197
  // ---------------------------------------------------------------------------
4198
4198
 
4199
+ // A CSS weight, 100-900, as the nearest of AppKit's named weights — what a
4200
+ // face and an SF Symbol are both configured with.
4201
+ static NSFontWeight FontWeightFromCss(double weight) {
4202
+ if (weight <= 150) return NSFontWeightUltraLight;
4203
+ if (weight <= 250) return NSFontWeightThin;
4204
+ if (weight <= 350) return NSFontWeightLight;
4205
+ if (weight <= 450) return NSFontWeightRegular;
4206
+ if (weight <= 550) return NSFontWeightMedium;
4207
+ if (weight <= 650) return NSFontWeightSemibold;
4208
+ if (weight <= 750) return NSFontWeightBold;
4209
+ if (weight <= 850) return NSFontWeightHeavy;
4210
+ return NSFontWeightBlack;
4211
+ }
4212
+
4199
4213
  // matchFont({ families: [..], size, weight (100-900), italic }) -> font handle
4200
4214
  static NSFont* ResolveFamily(NSString* family, double size, double weight,
4201
4215
  bool italic) {
4202
- NSFontWeight w = NSFontWeightRegular;
4203
- if (weight <= 150) w = NSFontWeightUltraLight;
4204
- else if (weight <= 250) w = NSFontWeightThin;
4205
- else if (weight <= 350) w = NSFontWeightLight;
4206
- else if (weight <= 450) w = NSFontWeightRegular;
4207
- else if (weight <= 550) w = NSFontWeightMedium;
4208
- else if (weight <= 650) w = NSFontWeightSemibold;
4209
- else if (weight <= 750) w = NSFontWeightBold;
4210
- else if (weight <= 850) w = NSFontWeightHeavy;
4211
- else w = NSFontWeightBlack;
4216
+ NSFontWeight w = FontWeightFromCss(weight);
4212
4217
 
4213
4218
  NSFont* font = nil;
4214
4219
  NSString* lower = family.lowercaseString;
@@ -5229,6 +5234,121 @@ static Napi::Value CtxDrawGlyphs(const Napi::CallbackInfo& info) {
5229
5234
  return info.Env().Undefined();
5230
5235
  }
5231
5236
 
5237
+ // ---------------------------------------------------------------------------
5238
+ // SF Symbols, drawn in a surface (sidorares/react-x11#591)
5239
+ // ---------------------------------------------------------------------------
5240
+ //
5241
+ // The system's icons by name — what a status item and a menu item already
5242
+ // take — for a renderer drawing its own content. A symbol is a template: its
5243
+ // shape, in whatever colour it is drawn with, so it is drawn here the way a
5244
+ // glyph run is, in the current fill colour, and tints the way text does.
5245
+
5246
+ // The symbol's image for (name, options), or nil for a name the catalogue
5247
+ // does not know. Options: pointSize (default 13), weight (100-900, default
5248
+ // 400), scale ('small' | 'medium' | 'large', default 'medium'),
5249
+ // variableValue (0-1, macOS 13 and later; ignored before).
5250
+ static NSImage* SymbolImage(Napi::Value nameValue, Napi::Value optionsValue) {
5251
+ if (!nameValue.IsString()) {
5252
+ Napi::TypeError::New(nameValue.Env(), "expected a symbol name")
5253
+ .ThrowAsJavaScriptException();
5254
+ return nil;
5255
+ }
5256
+ NSString* name = BToNSString(nameValue);
5257
+ double pointSize = 13, weight = 400, variable = NAN;
5258
+ NSImageSymbolScale scale = NSImageSymbolScaleMedium;
5259
+ if (optionsValue.IsObject()) {
5260
+ Napi::Object o = optionsValue.As<Napi::Object>();
5261
+ pointSize = BNumOr(o, "pointSize", 13);
5262
+ weight = BNumOr(o, "weight", 400);
5263
+ NSString* s = BStrOr(o, "scale", @"medium");
5264
+ if ([s isEqualToString:@"small"]) scale = NSImageSymbolScaleSmall;
5265
+ else if ([s isEqualToString:@"large"]) scale = NSImageSymbolScaleLarge;
5266
+ if (o.Has("variableValue") && o.Get("variableValue").IsNumber())
5267
+ variable = o.Get("variableValue").As<Napi::Number>().DoubleValue();
5268
+ }
5269
+ NSImage* img = nil;
5270
+ if (!std::isnan(variable)) {
5271
+ if (@available(macOS 13.0, *)) {
5272
+ img = [NSImage imageWithSystemSymbolName:name
5273
+ variableValue:variable
5274
+ accessibilityDescription:nil];
5275
+ }
5276
+ }
5277
+ if (!img) {
5278
+ img = [NSImage imageWithSystemSymbolName:name accessibilityDescription:nil];
5279
+ }
5280
+ if (!img) return nil;
5281
+ NSImageSymbolConfiguration* cfg = [NSImageSymbolConfiguration
5282
+ configurationWithPointSize:pointSize
5283
+ weight:FontWeightFromCss(weight)
5284
+ scale:scale];
5285
+ return [img imageWithSymbolConfiguration:cfg];
5286
+ }
5287
+
5288
+ // symbolSize(name, options?) -> { width, height } in points, or null for a
5289
+ // name the catalogue does not know. The image's size, the padding the symbol
5290
+ // is designed with included: the box a symbol sits in beside text.
5291
+ static Napi::Value SymbolSize(const Napi::CallbackInfo& info) {
5292
+ Napi::Env env = info.Env();
5293
+ @autoreleasepool {
5294
+ NSImage* img = SymbolImage(info[0], info.Length() > 1 ? info[1] : env.Undefined());
5295
+ if (env.IsExceptionPending()) return env.Undefined();
5296
+ if (!img) return env.Null();
5297
+ Napi::Object out = Napi::Object::New(env);
5298
+ out.Set("width", img.size.width);
5299
+ out.Set("height", img.size.height);
5300
+ return out;
5301
+ }
5302
+ }
5303
+
5304
+ // ctxDrawSymbol(surface, name, x, y, width, height, options?) -> boolean
5305
+ // The symbol fitted into the rect, centred, keeping its proportions, in the
5306
+ // current fill colour — so it follows the surface CTM, clip, global alpha and
5307
+ // blend mode like every other ctx verb. Answers false, drawing nothing, for a
5308
+ // name the catalogue does not know. Options as symbolSize's.
5309
+ static Napi::Value CtxDrawSymbol(const Napi::CallbackInfo& info) {
5310
+ Napi::Env env = info.Env();
5311
+ CALSurface* s = SurfaceFrom(info[0]);
5312
+ if (!s) return env.Undefined();
5313
+ @autoreleasepool {
5314
+ NSImage* img = SymbolImage(info[1], info.Length() > 6 ? info[6] : env.Undefined());
5315
+ if (env.IsExceptionPending()) return env.Undefined();
5316
+ if (!img) return Napi::Boolean::New(env, false);
5317
+ double x = info[2].As<Napi::Number>().DoubleValue();
5318
+ double y = info[3].As<Napi::Number>().DoubleValue();
5319
+ double w = info[4].As<Napi::Number>().DoubleValue();
5320
+ double h = info[5].As<Napi::Number>().DoubleValue();
5321
+ NSSize size = img.size;
5322
+ if (!(w > 0 && h > 0 && size.width > 0 && size.height > 0))
5323
+ return Napi::Boolean::New(env, true);
5324
+ double k = std::min(w / size.width, h / size.height);
5325
+ CGRect rect = CGRectMake(x + (w - size.width * k) / 2, y + (h - size.height * k) / 2,
5326
+ size.width * k, size.height * k);
5327
+ CGContextRef ctx = s->ctx;
5328
+ CGContextSaveGState(ctx);
5329
+ // The template's shape into a layer of its own, then the fill colour
5330
+ // through it: the layer composites once with the context's alpha, blend
5331
+ // mode and clip, as a glyph run's ink does.
5332
+ CGContextBeginTransparencyLayerWithRect(ctx, rect, NULL);
5333
+ // the surface's base CTM is y-down, so the context is a flipped one
5334
+ NSGraphicsContext* g = [NSGraphicsContext graphicsContextWithCGContext:ctx flipped:YES];
5335
+ [NSGraphicsContext saveGraphicsState];
5336
+ [NSGraphicsContext setCurrentContext:g];
5337
+ [img drawInRect:NSRectFromCGRect(rect)
5338
+ fromRect:NSZeroRect
5339
+ operation:NSCompositingOperationSourceOver
5340
+ fraction:1.0
5341
+ respectFlipped:YES
5342
+ hints:nil];
5343
+ [NSGraphicsContext restoreGraphicsState];
5344
+ CGContextSetBlendMode(ctx, kCGBlendModeSourceIn);
5345
+ CGContextFillRect(ctx, rect);
5346
+ CGContextEndTransparencyLayer(ctx);
5347
+ CGContextRestoreGState(ctx);
5348
+ return Napi::Boolean::New(env, true);
5349
+ }
5350
+ }
5351
+
5232
5352
  // drawLayoutGradient(surface, layoutHandle, x, y, x0, y0, x1, y1,
5233
5353
  // stops [offset,r,g,b,a,...])
5234
5354
  // The glyph outlines become the clip and a linear gradient fills through
@@ -5302,6 +5422,307 @@ static Napi::Value DrawLayoutGradient(const Napi::CallbackInfo& info) {
5302
5422
  return info.Env().Undefined();
5303
5423
  }
5304
5424
 
5425
+ // ---------------------------------------------------------------------------
5426
+ // A layout's coverage, drawn nowhere (sidorares/react-x11#673)
5427
+ // ---------------------------------------------------------------------------
5428
+
5429
+ // The coverage of closed outlines by signed-area accumulation, the algorithm
5430
+ // font-rs and stb_truetype v2 use, ported from ntk's CoverageAccumulator
5431
+ // (lib/rasterize.js) so the X11 text engine and this one rasterize alike. Each
5432
+ // edge deposits the exact area it sweeps through every pixel row it crosses
5433
+ // into a float accumulator, and a prefix sum along each row turns those deltas
5434
+ // into winding-weighted coverage, clamped at one: the non-zero rule, analytic,
5435
+ // no supersampling. Its one approximation is where two contours overlap and
5436
+ // both edges cross the same pixel, as a variable font's stems do at a join:
5437
+ // their partial coverages add there, where the union's would not. Geometry is
5438
+ // y-down pixels with the grid's top-left at (0, 0); an edge outside the grid
5439
+ // piles its coverage onto the border column, as a clipped fill would.
5440
+ class CoverageAccumulator {
5441
+ public:
5442
+ CoverageAccumulator(long width, long height)
5443
+ : width_(width),
5444
+ height_(height),
5445
+ stride_(width + 2), // an edge ending on the right border deposits
5446
+ // its last fraction one cell past the last pixel
5447
+ acc_((size_t)((width + 2) * height), 0.0f) {}
5448
+
5449
+ // One directed edge. A horizontal one sweeps no area.
5450
+ void Edge(double ax, double ay, double bx, double by) {
5451
+ if (ay == by || !std::isfinite(ax) || !std::isfinite(ay) ||
5452
+ !std::isfinite(bx) || !std::isfinite(by))
5453
+ return;
5454
+ double dir = 1, x0 = ax, y0 = ay, x1 = bx, y1 = by;
5455
+ if (ay > by) {
5456
+ dir = -1;
5457
+ x0 = bx;
5458
+ y0 = by;
5459
+ x1 = ax;
5460
+ y1 = ay;
5461
+ }
5462
+ const double dxdy = (x1 - x0) / (y1 - y0);
5463
+ double x = x0;
5464
+ if (y0 < 0) { // enter at row 0 rather than accumulate rows nobody reads
5465
+ x -= y0 * dxdy;
5466
+ y0 = 0;
5467
+ }
5468
+ const double w = (double)width_;
5469
+ const long rowEnd = std::min(height_, (long)std::ceil(y1));
5470
+ for (long y = (long)y0; y < rowEnd; ++y) {
5471
+ float* line = acc_.data() + y * stride_;
5472
+ const double dy = std::min((double)y + 1, y1) - std::max((double)y, y0);
5473
+ const double xnext = x + dxdy * dy;
5474
+ const double d = dy * dir;
5475
+ double xa = std::min(x, xnext), xb = std::max(x, xnext);
5476
+ xa = xa < 0 ? 0 : xa > w ? w : xa;
5477
+ xb = xb < 0 ? 0 : xb > w ? w : xb;
5478
+ const double xaFloor = std::floor(xa);
5479
+ const long x0i = (long)xaFloor;
5480
+ const double xbCeil = std::ceil(xb);
5481
+ const long x1i = (long)xbCeil;
5482
+ if (x1i <= x0i + 1) {
5483
+ // the row's span inside one pixel: split at its midpoint
5484
+ const double xmf = 0.5 * (xa + xb) - xaFloor;
5485
+ Add(line[x0i], d - d * xmf);
5486
+ Add(line[x0i + 1], d * xmf);
5487
+ } else {
5488
+ // a trapezoid across the pixels the span crosses
5489
+ const double s = 1 / (xb - xa);
5490
+ const double x0f = xa - xaFloor;
5491
+ const double a0 = 0.5 * s * (1 - x0f) * (1 - x0f);
5492
+ const double x1f = xb - xbCeil + 1;
5493
+ const double am = 0.5 * s * x1f * x1f;
5494
+ Add(line[x0i], d * a0);
5495
+ if (x1i == x0i + 2) {
5496
+ Add(line[x0i + 1], d * (1 - a0 - am));
5497
+ } else {
5498
+ const double a1 = s * (1.5 - x0f);
5499
+ Add(line[x0i + 1], d * (a1 - a0));
5500
+ for (long xi = x0i + 2; xi < x1i - 1; ++xi) Add(line[xi], d * s);
5501
+ const double a2 = a1 + (double)(x1i - x0i - 3) * s;
5502
+ Add(line[x1i - 1], d * (1 - a2 - am));
5503
+ }
5504
+ Add(line[x1i], d * am);
5505
+ }
5506
+ x = xnext;
5507
+ }
5508
+ }
5509
+
5510
+ // The rows integrated into one byte a pixel, width × height into `out`.
5511
+ void ToAlpha(uint8_t* out) const {
5512
+ for (long y = 0; y < height_; ++y) {
5513
+ const float* line = acc_.data() + y * stride_;
5514
+ uint8_t* row = out + y * width_;
5515
+ double sum = 0;
5516
+ for (long x = 0; x < width_; ++x) {
5517
+ sum += line[x];
5518
+ double c = sum < 0 ? -sum : sum;
5519
+ if (c > 1) c = 1;
5520
+ row[x] = (uint8_t)(c * 255 + 0.5);
5521
+ }
5522
+ }
5523
+ }
5524
+
5525
+ private:
5526
+ // A cell is a float, as ntk's Float32Array is, and a deposit is added to it
5527
+ // in double and rounded once, as JavaScript does: the two stay byte-alike.
5528
+ static void Add(float& cell, double v) { cell = (float)(cell + v); }
5529
+
5530
+ long width_, height_, stride_;
5531
+ std::vector<float> acc_;
5532
+ };
5533
+
5534
+ // A glyph outline walked into the accumulator: every subpath closed, as a
5535
+ // fill closes it, and curves cut into chords the way ntk's flatten does — a
5536
+ // step for every three pixels of the control points' extent, three to
5537
+ // twenty-four of them.
5538
+ struct OutlineWalk {
5539
+ CoverageAccumulator* acc;
5540
+ double x = 0, y = 0; // the pen
5541
+ double sx = 0, sy = 0; // where the subpath began
5542
+
5543
+ void To(double nx, double ny) {
5544
+ acc->Edge(x, y, nx, ny);
5545
+ x = nx;
5546
+ y = ny;
5547
+ }
5548
+ void Close() { To(sx, sy); }
5549
+
5550
+ static int Steps(std::initializer_list<CGPoint> points) {
5551
+ double x0 = INFINITY, y0 = INFINITY, x1 = -INFINITY, y1 = -INFINITY;
5552
+ for (const CGPoint& p : points) {
5553
+ x0 = std::min(x0, (double)p.x);
5554
+ x1 = std::max(x1, (double)p.x);
5555
+ y0 = std::min(y0, (double)p.y);
5556
+ y1 = std::max(y1, (double)p.y);
5557
+ }
5558
+ const double extent = std::max(x1 - x0, y1 - y0);
5559
+ return (int)std::min(24.0, std::max(3.0, std::ceil(extent / 3)));
5560
+ }
5561
+
5562
+ static void Apply(void* info, const CGPathElement* e) {
5563
+ auto* w = (OutlineWalk*)info;
5564
+ const CGPoint* p = e->points;
5565
+ switch (e->type) {
5566
+ case kCGPathElementMoveToPoint:
5567
+ w->Close();
5568
+ w->x = w->sx = p[0].x;
5569
+ w->y = w->sy = p[0].y;
5570
+ break;
5571
+ case kCGPathElementAddLineToPoint:
5572
+ w->To(p[0].x, p[0].y);
5573
+ break;
5574
+ case kCGPathElementAddQuadCurveToPoint: {
5575
+ const double x0 = w->x, y0 = w->y;
5576
+ const int steps = Steps({CGPointMake(x0, y0), p[0], p[1]});
5577
+ for (int i = 1; i <= steps; ++i) {
5578
+ const double t = (double)i / steps, mt = 1 - t;
5579
+ w->To(mt * mt * x0 + 2 * mt * t * p[0].x + t * t * p[1].x,
5580
+ mt * mt * y0 + 2 * mt * t * p[0].y + t * t * p[1].y);
5581
+ }
5582
+ break;
5583
+ }
5584
+ case kCGPathElementAddCurveToPoint: {
5585
+ const double x0 = w->x, y0 = w->y;
5586
+ const int steps = Steps({CGPointMake(x0, y0), p[0], p[1], p[2]});
5587
+ for (int i = 1; i <= steps; ++i) {
5588
+ const double t = (double)i / steps, mt = 1 - t;
5589
+ w->To(mt * mt * mt * x0 + 3 * mt * mt * t * p[0].x +
5590
+ 3 * mt * t * t * p[1].x + t * t * t * p[2].x,
5591
+ mt * mt * mt * y0 + 3 * mt * mt * t * p[0].y +
5592
+ 3 * mt * t * t * p[1].y + t * t * t * p[2].y);
5593
+ }
5594
+ break;
5595
+ }
5596
+ case kCGPathElementCloseSubpath:
5597
+ w->Close();
5598
+ break;
5599
+ }
5600
+ }
5601
+ };
5602
+
5603
+ // A glyph with no outline to fill, drawn instead: Apple Color Emoji's
5604
+ // bitmaps, which come out as their silhouettes.
5605
+ struct DrawnGlyph {
5606
+ CTFontRef font; // the run's, alive as long as the layout
5607
+ CGGlyph glyph;
5608
+ CGPoint origin; // canvas space, y down
5609
+ };
5610
+
5611
+ // layoutCoverage(layoutHandle, pad?) -> { width, height, data } | null
5612
+ //
5613
+ // How much of each pixel a layout's glyphs cover, one byte a pixel, without
5614
+ // drawing the layout anywhere: for text drawn where a surface is not, such as
5615
+ // a GL surface's label atlas or a signed distance field made from a string.
5616
+ // The raster is the layout's box in whole pixels, createLayout's width and
5617
+ // height rounded up, with `pad` pixels round it (a fraction rounds up too).
5618
+ // `data` is width × height bytes, row-major, the top row first, and the
5619
+ // layout's origin is at (pad, pad): the glyphs are where
5620
+ // drawLayout(surface, layout, pad, pad) would draw them, one pixel to one of
5621
+ // the layout's units. Null for anything that is not a layout, and for a layout
5622
+ // with no box and no pad to make one.
5623
+ //
5624
+ // It is the outlines' own coverage, which is what a raster that will be scaled
5625
+ // wants, and not the ink the screen gets. Every glyph's outline goes where the
5626
+ // typesetter put it, unrounded, and the whole layout is filled once, non-zero,
5627
+ // so glyphs that overlap cover a pixel once. CoreText's glyph rasterizer is
5628
+ // not used for it, even with font smoothing off: it snaps nothing, but it
5629
+ // shrinks a small glyph's counters (Menlo's b at 14px comes out 5% heavier
5630
+ // than its outline). CoreGraphics' own path fill is exact to a percent but
5631
+ // costs several times the draw and readback this replaces.
5632
+ //
5633
+ // Ink is the caller's: a span's colour plays no part, so a translucent span
5634
+ // covers what an opaque one does. A glyph with no outline but ink of its own
5635
+ // (Apple Color Emoji's bitmaps) is drawn over the rest into an alpha-only
5636
+ // bitmap, which keeps its alpha: its silhouette.
5637
+ static Napi::Value LayoutCoverage(const Napi::CallbackInfo& info) {
5638
+ Napi::Env env = info.Env();
5639
+ if (info.Length() < 1 || !info[0].IsExternal()) return env.Null();
5640
+ CALLayout* layout = LayoutFrom(info[0]);
5641
+ const double asked = info.Length() > 1 && info[1].IsNumber()
5642
+ ? info[1].As<Napi::Number>().DoubleValue()
5643
+ : 0;
5644
+ const long pad =
5645
+ asked > 0 && std::isfinite(asked) ? (long)std::ceil(asked) : 0;
5646
+ const long width = (long)std::ceil(layout->width) + pad * 2;
5647
+ const long height = (long)std::ceil(layout->height) + pad * 2;
5648
+ if (width <= 0 || height <= 0) return env.Null();
5649
+
5650
+ CoverageAccumulator acc(width, height);
5651
+ OutlineWalk walk{&acc};
5652
+ std::vector<DrawnGlyph> drawn;
5653
+ std::vector<CGGlyph> glyphs;
5654
+ std::vector<CGPoint> positions;
5655
+ for (const CALLine& L : layout->lines) {
5656
+ CFArrayRef runs = CTLineGetGlyphRuns(L.line);
5657
+ for (CFIndex ri = 0; ri < CFArrayGetCount(runs); ri++) {
5658
+ CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(runs, ri);
5659
+ CTFontRef font = (CTFontRef)CFDictionaryGetValue(
5660
+ CTRunGetAttributes(run), kCTFontAttributeName);
5661
+ const CFIndex count = CTRunGetGlyphCount(run);
5662
+ if (!font || count <= 0) continue;
5663
+ glyphs.resize((size_t)count);
5664
+ positions.resize((size_t)count);
5665
+ CTRunGetGlyphs(run, CFRangeMake(0, 0), glyphs.data());
5666
+ CTRunGetPositions(run, CFRangeMake(0, 0), positions.data());
5667
+ for (size_t g = 0; g < (size_t)count; g++) {
5668
+ // a glyph shaping deleted, such as a ligature's second half
5669
+ if (glyphs[g] == kCGFontIndexInvalid) continue;
5670
+ // positions are from the line's origin, y up; outlines are y up
5671
+ // from the glyph's origin, flipped here into canvas space
5672
+ const double ox = pad + L.x + positions[g].x;
5673
+ const double oy = pad + L.baseline - positions[g].y;
5674
+ const CGAffineTransform t = {1, 0, 0, -1, ox, oy};
5675
+ CGPathRef outline = CTFontCreatePathForGlyph(font, glyphs[g], &t);
5676
+ if (outline) {
5677
+ walk.x = walk.sx = walk.y = walk.sy = 0;
5678
+ CGPathApply(outline, &walk, OutlineWalk::Apply);
5679
+ walk.Close();
5680
+ CGPathRelease(outline);
5681
+ continue;
5682
+ }
5683
+ // no outline: a space, or a glyph whose ink is a bitmap
5684
+ CGRect bounds;
5685
+ CTFontGetBoundingRectsForGlyphs(font, kCTFontOrientationDefault,
5686
+ &glyphs[g], &bounds, 1);
5687
+ if (!CGRectIsEmpty(bounds))
5688
+ drawn.push_back({font, glyphs[g], CGPointMake(ox, oy)});
5689
+ }
5690
+ }
5691
+ }
5692
+
5693
+ // A new ArrayBuffer is zeroed, which is "covers nothing".
5694
+ Napi::Uint8Array data = Napi::Uint8Array::New(env, (size_t)(width * height));
5695
+ acc.ToAlpha(data.Data());
5696
+ if (!drawn.empty()) {
5697
+ CGContextRef ctx = CGBitmapContextCreate(
5698
+ data.Data(), (size_t)width, (size_t)height, 8, (size_t)width, NULL,
5699
+ (CGBitmapInfo)kCGImageAlphaOnly);
5700
+ if (ctx) {
5701
+ // top-left origin, y down, as a surface's base CTM has it; the glyph at
5702
+ // the position the run gave it, the way drawLayout draws it
5703
+ CGContextTranslateCTM(ctx, 0, (CGFloat)height);
5704
+ CGContextScaleCTM(ctx, 1, -1);
5705
+ CGContextSetShouldSmoothFonts(ctx, false);
5706
+ CGContextSetShouldSubpixelPositionFonts(ctx, true);
5707
+ CGContextSetShouldSubpixelQuantizeFonts(ctx, false);
5708
+ CGContextSetGrayFillColor(ctx, 0, 1);
5709
+ CGContextSetTextMatrix(ctx, CGAffineTransformMakeScale(1, -1));
5710
+ for (const DrawnGlyph& d : drawn) {
5711
+ // CTFontDrawGlyphs reads positions in text space, through the flip
5712
+ const CGPoint at = CGPointMake(d.origin.x, -d.origin.y);
5713
+ CTFontDrawGlyphs(d.font, &d.glyph, &at, 1, ctx);
5714
+ }
5715
+ CGContextRelease(ctx);
5716
+ }
5717
+ }
5718
+
5719
+ Napi::Object out = Napi::Object::New(env);
5720
+ out.Set("width", (double)width);
5721
+ out.Set("height", (double)height);
5722
+ out.Set("data", data);
5723
+ return out;
5724
+ }
5725
+
5305
5726
  // ctxSetShadow(surface, blur, dx, dy, r, g, b, a) — blur <= 0 clears.
5306
5727
  static Napi::Value CtxSetShadow(const Napi::CallbackInfo& info) {
5307
5728
  CALSurface* s = SurfaceFrom(info[0]);
@@ -6518,8 +6939,11 @@ void InitBackend(Napi::Env env, Napi::Object exports) {
6518
6939
  BFN("createLayout", CreateLayout);
6519
6940
  BFN("drawLayout", DrawLayout);
6520
6941
  BFN("ctxDrawGlyphs", CtxDrawGlyphs);
6942
+ BFN("ctxDrawSymbol", CtxDrawSymbol);
6943
+ BFN("symbolSize", SymbolSize);
6521
6944
  BFN("layoutIndexAt", LayoutIndexAt);
6522
6945
  BFN("layoutCaret", LayoutCaret);
6946
+ BFN("layoutCoverage", LayoutCoverage);
6523
6947
  BFN("pasteboardWriteText", PbWriteTextFn);
6524
6948
  BFN("pasteboardReadText", PbReadTextFn);
6525
6949
  BFN("pasteboardClear", PbClearFn);