@windowkit/appkit 0.12.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
@@ -524,6 +524,37 @@ 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
+
527
558
  ## SF Symbols in a surface
528
559
 
529
560
  The system's icons by name — what `createStatusItem`'s `image` and a menu item's `iconName`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@windowkit/appkit",
3
- "version": "0.12.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/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"
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
@@ -5422,6 +5422,307 @@ static Napi::Value DrawLayoutGradient(const Napi::CallbackInfo& info) {
5422
5422
  return info.Env().Undefined();
5423
5423
  }
5424
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
+
5425
5726
  // ctxSetShadow(surface, blur, dx, dy, r, g, b, a) — blur <= 0 clears.
5426
5727
  static Napi::Value CtxSetShadow(const Napi::CallbackInfo& info) {
5427
5728
  CALSurface* s = SurfaceFrom(info[0]);
@@ -6642,6 +6943,7 @@ void InitBackend(Napi::Env env, Napi::Object exports) {
6642
6943
  BFN("symbolSize", SymbolSize);
6643
6944
  BFN("layoutIndexAt", LayoutIndexAt);
6644
6945
  BFN("layoutCaret", LayoutCaret);
6946
+ BFN("layoutCoverage", LayoutCoverage);
6645
6947
  BFN("pasteboardWriteText", PbWriteTextFn);
6646
6948
  BFN("pasteboardReadText", PbReadTextFn);
6647
6949
  BFN("pasteboardClear", PbClearFn);