@windowkit/appkit 0.12.0 → 0.14.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,69 @@ 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
+ ## Text: a paragraph laid out again
559
+
560
+ Most of a `createLayout` is the text becoming glyphs: the attributed string built from the
561
+ spans, and the typesetter CoreText shapes it with — two thirds of the call over a long
562
+ document. A layout of the same paragraph at another width breaks the same glyphs into other
563
+ lines, which is what a window resize does to every paragraph of a document, and what a
564
+ paragraph's max-content and wrapped measurements are.
565
+
566
+ - **`keep: true`** — the result carries the paragraph's typesetter as `typesetter`.
567
+ - **`typesetter`** — handed to a later `createLayout` in place of `spans`, it lays the same
568
+ text out at that call's `maxWidth`, `align`, `lineHeight`, `maxLines` and `ellipsis`,
569
+ and the layout is the one the spans would have made, line for line and pixel for pixel.
570
+ `rtl` is the typesetter's and ignored beside one.
571
+ - **`native.releaseTypesetter(typesetter)`** — frees it now, where a cache lets one go.
572
+ Idempotent; a released one handed to `createLayout` throws. The finalizer is the safety
573
+ net, and the memory is reported to V8, at about 25 bytes a UTF-16 unit.
574
+ - **`packed: true`** — the geometry as two `Float64Array`s in place of `lines`: `lineData`,
575
+ ten numbers a line (`x`, `y`, `width`, `height`, `baseline`, `ascent`, `descent`,
576
+ `start`, `end`, and how many runs it has), and `runData`, five a run in line order (`x`,
577
+ `width`, `start`, `end`, and `1` when it runs right to left). An object a line and a run
578
+ is a call into V8 a field, and for short paragraphs building them was a sixth of the call.
579
+
580
+ A 50-character paragraph on an M1 Pro: 34 µs a layout from its spans, 16 µs from its kept
581
+ typesetter, 8.6 µs packed.
582
+
583
+ ```js
584
+ const first = native.createLayout({ spans, maxWidth: 600, keep: true });
585
+ const narrower = native.createLayout({ typesetter: first.typesetter, maxWidth: 420, packed: true });
586
+ // narrower.lineData, narrower.runData
587
+ native.releaseTypesetter(first.typesetter);
588
+ ```
589
+
527
590
  ## SF Symbols in a surface
528
591
 
529
592
  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.14.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/text-typesetter.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
@@ -4981,27 +4981,45 @@ static CALLayout* LayoutFrom(Napi::Value v) {
4981
4981
  return (CALLayout*)v.As<Napi::External<void>>().Data();
4982
4982
  }
4983
4983
 
4984
- // createLayout({ spans: [{text, font (handle), color:[r,g,b,a]}],
4985
- // maxWidth?, align: 0 left | 0.5 center | 1 right,
4986
- // lineHeight?, maxLines?, ellipsis?, rtl? })
4987
- // -> { handle, width, height,
4988
- // lines: [{x,y,width,height,baseline,descent,start,end,
4989
- // runs:[{x,width,start,end,rtl}]}] }
4990
- static Napi::Value CreateLayout(const Napi::CallbackInfo& info) {
4991
- Napi::Env env = info.Env();
4992
- Napi::Object o = info[0].As<Napi::Object>();
4993
- double maxWidth = BNumOr(o, "maxWidth", 0);
4994
- bool bounded = maxWidth > 0 && std::isfinite(maxWidth);
4995
- double flush = BNumOr(o, "align", 0);
4996
- double lineHeight = BNumOr(o, "lineHeight", 0);
4997
- long maxLines = (long)BNumOr(o, "maxLines", 0);
4998
- bool ellipsis = BBoolOr(o, "ellipsis", false);
4999
- bool rtl = BBoolOr(o, "rtl", false);
5000
- if (ellipsis && maxLines <= 0) maxLines = 1;
4984
+ // --- a paragraph's typesetter, kept -----------------------------------------
4985
+ //
4986
+ // Most of a layout is the text becoming glyphs: the attributed string built
4987
+ // from the spans, and the typesetter CoreText shapes it with — two thirds of
4988
+ // a createLayout over a long document, the lines broken from it the rest. A
4989
+ // layout of the same paragraph at another width breaks the same glyphs into
4990
+ // other lines, so a caller that asks with `keep: true` gets the typesetter
4991
+ // back (`typesetter` on the result) and hands it to the next createLayout of
4992
+ // that text in place of the spans. It holds the shaped text and nothing
4993
+ // about a width: align, lineHeight, maxLines and the ellipsis are the
4994
+ // layout's own. `releaseTypesetter` frees one now; the finalizer is the
4995
+ // safety net, and the bytes are reported to V8 so that it runs.
4996
+ struct CALTypesetter {
4997
+ CTTypesetterRef ts = nullptr;
4998
+ NSAttributedString* text = nil; // strong, under ARC
4999
+ NSDictionary* lastAttrs = nil; // the last span's: the ellipsis token's
5000
+ bool rtl = false;
5001
+ int64_t bytes = 0;
5002
+ void Release(Napi::Env env) {
5003
+ if (ts) CFRelease(ts);
5004
+ ts = nullptr;
5005
+ text = nil;
5006
+ lastAttrs = nil;
5007
+ if (bytes) Napi::MemoryManagement::AdjustExternalMemory(env, -bytes);
5008
+ bytes = 0;
5009
+ }
5010
+ };
5011
+
5012
+ // About what CoreText keeps for a shaped paragraph — its glyphs, their
5013
+ // positions and advances, the string — measured at 25 bytes a UTF-16 unit.
5014
+ static const int64_t kTypesetterBytesPerUnit = 25;
5001
5015
 
5016
+ // The attributed string for `spans` and its typesetter; `ts` stays null for
5017
+ // an empty paragraph.
5018
+ static CALTypesetter* TypesetSpans(Napi::Array spans, bool rtl) {
5019
+ auto* shaped = new CALTypesetter();
5020
+ shaped->rtl = rtl;
5002
5021
  NSMutableAttributedString* as = [[NSMutableAttributedString alloc] init];
5003
5022
  NSDictionary* lastAttrs = nil;
5004
- Napi::Array spans = o.Get("spans").As<Napi::Array>();
5005
5023
  for (uint32_t i = 0; i < spans.Length(); i++) {
5006
5024
  Napi::Object span = spans.Get(i).As<Napi::Object>();
5007
5025
  NSString* text = span.Has("text") && span.Get("text").IsString()
@@ -5035,12 +5053,88 @@ static Napi::Value CreateLayout(const Napi::CallbackInfo& info) {
5035
5053
  [as appendAttributedString:[[NSAttributedString alloc] initWithString:text
5036
5054
  attributes:attrs]];
5037
5055
  }
5056
+ shaped->text = as;
5057
+ shaped->lastAttrs = lastAttrs;
5058
+ if (as.length > 0) {
5059
+ shaped->ts = CTTypesetterCreateWithAttributedString(
5060
+ (__bridge CFAttributedStringRef)as);
5061
+ }
5062
+ return shaped;
5063
+ }
5064
+
5065
+ static void TypesetterFinalize(Napi::Env env, void* d) {
5066
+ auto* shaped = (CALTypesetter*)d;
5067
+ shaped->Release(env);
5068
+ delete shaped;
5069
+ }
5070
+
5071
+ // releaseTypesetter(handle) — free a kept typesetter now. Idempotent; a
5072
+ // createLayout handed a released one throws.
5073
+ static Napi::Value ReleaseTypesetter(const Napi::CallbackInfo& info) {
5074
+ Napi::Env env = info.Env();
5075
+ if (!info[0].IsExternal()) {
5076
+ Napi::TypeError::New(env, "releaseTypesetter: expected a typesetter")
5077
+ .ThrowAsJavaScriptException();
5078
+ return env.Undefined();
5079
+ }
5080
+ ((CALTypesetter*)info[0].As<Napi::External<void>>().Data())->Release(env);
5081
+ return env.Undefined();
5082
+ }
5083
+
5084
+ // createLayout({ spans: [{text, font (handle), color:[r,g,b,a]}],
5085
+ // maxWidth?, align: 0 left | 0.5 center | 1 right,
5086
+ // lineHeight?, maxLines?, ellipsis?, rtl?,
5087
+ // keep?, typesetter?, packed? })
5088
+ // -> { handle, width, height,
5089
+ // lines: [{x,y,width,height,baseline,descent,start,end,
5090
+ // runs:[{x,width,start,end,rtl}]}],
5091
+ // typesetter? }
5092
+ //
5093
+ // `keep: true` returns the paragraph's typesetter as `typesetter`, and a
5094
+ // later createLayout given it in place of `spans` breaks the same shaped
5095
+ // text at its own options — see CALTypesetter; `rtl` is the typesetter's,
5096
+ // and ignored beside one. `packed: true` returns the geometry as two
5097
+ // Float64Arrays in place of `lines`, which is a tenth of the calls into the
5098
+ // engine for a paragraph of a few lines: `lineData`, ten numbers a line —
5099
+ // x, y, width, height, baseline, ascent, descent, start, end and how many
5100
+ // runs it has — and `runData`, five a run in line order — x, width, start,
5101
+ // end, and 1 when it runs right to left.
5102
+ static Napi::Value CreateLayout(const Napi::CallbackInfo& info) {
5103
+ Napi::Env env = info.Env();
5104
+ Napi::Object o = info[0].As<Napi::Object>();
5105
+ double maxWidth = BNumOr(o, "maxWidth", 0);
5106
+ bool bounded = maxWidth > 0 && std::isfinite(maxWidth);
5107
+ double flush = BNumOr(o, "align", 0);
5108
+ double lineHeight = BNumOr(o, "lineHeight", 0);
5109
+ long maxLines = (long)BNumOr(o, "maxLines", 0);
5110
+ bool ellipsis = BBoolOr(o, "ellipsis", false);
5111
+ bool rtl = BBoolOr(o, "rtl", false);
5112
+ bool keep = BBoolOr(o, "keep", false);
5113
+ bool packed = BBoolOr(o, "packed", false);
5114
+ if (ellipsis && maxLines <= 0) maxLines = 1;
5115
+
5116
+ CALTypesetter* shaped = nullptr;
5117
+ bool owned = false;
5118
+ if (o.Has("typesetter") && o.Get("typesetter").IsExternal()) {
5119
+ shaped = (CALTypesetter*)o.Get("typesetter")
5120
+ .As<Napi::External<void>>()
5121
+ .Data();
5122
+ if (!shaped->text) {
5123
+ Napi::Error::New(env, "createLayout: the typesetter was released")
5124
+ .ThrowAsJavaScriptException();
5125
+ return env.Undefined();
5126
+ }
5127
+ } else {
5128
+ shaped = TypesetSpans(o.Get("spans").As<Napi::Array>(), rtl);
5129
+ owned = true;
5130
+ }
5131
+ NSAttributedString* as = shaped->text;
5132
+ NSDictionary* lastAttrs = shaped->lastAttrs;
5133
+ CTTypesetterRef ts = shaped->ts;
5038
5134
 
5039
5135
  auto* layout = new CALLayout();
5040
5136
  long total = (long)as.length;
5041
- if (total > 0) {
5042
- CTTypesetterRef ts =
5043
- CTTypesetterCreateWithAttributedString((__bridge CFAttributedStringRef)as);
5137
+ if (total > 0 && ts) {
5044
5138
  double y = 0;
5045
5139
  long start = 0;
5046
5140
  long lineIndex = 0;
@@ -5132,7 +5226,6 @@ static Napi::Value CreateLayout(const Napi::CallbackInfo& info) {
5132
5226
  if (maxLines > 0 && lineIndex >= maxLines) break;
5133
5227
  }
5134
5228
  layout->height = y;
5135
- CFRelease(ts);
5136
5229
  }
5137
5230
 
5138
5231
  Napi::Object r = Napi::Object::New(env);
@@ -5141,6 +5234,46 @@ static Napi::Value CreateLayout(const Napi::CallbackInfo& info) {
5141
5234
  }));
5142
5235
  r.Set("width", layout->width);
5143
5236
  r.Set("height", layout->height);
5237
+ if (owned && keep) {
5238
+ shaped->bytes = (int64_t)total * kTypesetterBytesPerUnit;
5239
+ if (shaped->bytes)
5240
+ Napi::MemoryManagement::AdjustExternalMemory(env, shaped->bytes);
5241
+ r.Set("typesetter",
5242
+ Napi::External<void>::New(env, shaped, TypesetterFinalize));
5243
+ } else if (owned) {
5244
+ shaped->Release(env);
5245
+ delete shaped;
5246
+ }
5247
+ if (packed) {
5248
+ size_t runCount = 0;
5249
+ for (const CALLine& L : layout->lines) runCount += L.runs.size();
5250
+ Napi::Float64Array lineData =
5251
+ Napi::Float64Array::New(env, layout->lines.size() * 10);
5252
+ Napi::Float64Array runData = Napi::Float64Array::New(env, runCount * 5);
5253
+ size_t li = 0, ri = 0;
5254
+ for (const CALLine& L : layout->lines) {
5255
+ lineData[li++] = L.x;
5256
+ lineData[li++] = L.y;
5257
+ lineData[li++] = L.width;
5258
+ lineData[li++] = L.height;
5259
+ lineData[li++] = L.baseline;
5260
+ lineData[li++] = L.ascent;
5261
+ lineData[li++] = L.descent;
5262
+ lineData[li++] = (double)L.start;
5263
+ lineData[li++] = (double)L.end;
5264
+ lineData[li++] = (double)L.runs.size();
5265
+ for (const CALRun& R : L.runs) {
5266
+ runData[ri++] = R.x;
5267
+ runData[ri++] = R.width;
5268
+ runData[ri++] = (double)R.start;
5269
+ runData[ri++] = (double)R.end;
5270
+ runData[ri++] = R.rtl ? 1 : 0;
5271
+ }
5272
+ }
5273
+ r.Set("lineData", lineData);
5274
+ r.Set("runData", runData);
5275
+ return r;
5276
+ }
5144
5277
  Napi::Array lines = Napi::Array::New(env, layout->lines.size());
5145
5278
  for (size_t i = 0; i < layout->lines.size(); i++) {
5146
5279
  const CALLine& L = layout->lines[i];
@@ -5422,6 +5555,307 @@ static Napi::Value DrawLayoutGradient(const Napi::CallbackInfo& info) {
5422
5555
  return info.Env().Undefined();
5423
5556
  }
5424
5557
 
5558
+ // ---------------------------------------------------------------------------
5559
+ // A layout's coverage, drawn nowhere (sidorares/react-x11#673)
5560
+ // ---------------------------------------------------------------------------
5561
+
5562
+ // The coverage of closed outlines by signed-area accumulation, the algorithm
5563
+ // font-rs and stb_truetype v2 use, ported from ntk's CoverageAccumulator
5564
+ // (lib/rasterize.js) so the X11 text engine and this one rasterize alike. Each
5565
+ // edge deposits the exact area it sweeps through every pixel row it crosses
5566
+ // into a float accumulator, and a prefix sum along each row turns those deltas
5567
+ // into winding-weighted coverage, clamped at one: the non-zero rule, analytic,
5568
+ // no supersampling. Its one approximation is where two contours overlap and
5569
+ // both edges cross the same pixel, as a variable font's stems do at a join:
5570
+ // their partial coverages add there, where the union's would not. Geometry is
5571
+ // y-down pixels with the grid's top-left at (0, 0); an edge outside the grid
5572
+ // piles its coverage onto the border column, as a clipped fill would.
5573
+ class CoverageAccumulator {
5574
+ public:
5575
+ CoverageAccumulator(long width, long height)
5576
+ : width_(width),
5577
+ height_(height),
5578
+ stride_(width + 2), // an edge ending on the right border deposits
5579
+ // its last fraction one cell past the last pixel
5580
+ acc_((size_t)((width + 2) * height), 0.0f) {}
5581
+
5582
+ // One directed edge. A horizontal one sweeps no area.
5583
+ void Edge(double ax, double ay, double bx, double by) {
5584
+ if (ay == by || !std::isfinite(ax) || !std::isfinite(ay) ||
5585
+ !std::isfinite(bx) || !std::isfinite(by))
5586
+ return;
5587
+ double dir = 1, x0 = ax, y0 = ay, x1 = bx, y1 = by;
5588
+ if (ay > by) {
5589
+ dir = -1;
5590
+ x0 = bx;
5591
+ y0 = by;
5592
+ x1 = ax;
5593
+ y1 = ay;
5594
+ }
5595
+ const double dxdy = (x1 - x0) / (y1 - y0);
5596
+ double x = x0;
5597
+ if (y0 < 0) { // enter at row 0 rather than accumulate rows nobody reads
5598
+ x -= y0 * dxdy;
5599
+ y0 = 0;
5600
+ }
5601
+ const double w = (double)width_;
5602
+ const long rowEnd = std::min(height_, (long)std::ceil(y1));
5603
+ for (long y = (long)y0; y < rowEnd; ++y) {
5604
+ float* line = acc_.data() + y * stride_;
5605
+ const double dy = std::min((double)y + 1, y1) - std::max((double)y, y0);
5606
+ const double xnext = x + dxdy * dy;
5607
+ const double d = dy * dir;
5608
+ double xa = std::min(x, xnext), xb = std::max(x, xnext);
5609
+ xa = xa < 0 ? 0 : xa > w ? w : xa;
5610
+ xb = xb < 0 ? 0 : xb > w ? w : xb;
5611
+ const double xaFloor = std::floor(xa);
5612
+ const long x0i = (long)xaFloor;
5613
+ const double xbCeil = std::ceil(xb);
5614
+ const long x1i = (long)xbCeil;
5615
+ if (x1i <= x0i + 1) {
5616
+ // the row's span inside one pixel: split at its midpoint
5617
+ const double xmf = 0.5 * (xa + xb) - xaFloor;
5618
+ Add(line[x0i], d - d * xmf);
5619
+ Add(line[x0i + 1], d * xmf);
5620
+ } else {
5621
+ // a trapezoid across the pixels the span crosses
5622
+ const double s = 1 / (xb - xa);
5623
+ const double x0f = xa - xaFloor;
5624
+ const double a0 = 0.5 * s * (1 - x0f) * (1 - x0f);
5625
+ const double x1f = xb - xbCeil + 1;
5626
+ const double am = 0.5 * s * x1f * x1f;
5627
+ Add(line[x0i], d * a0);
5628
+ if (x1i == x0i + 2) {
5629
+ Add(line[x0i + 1], d * (1 - a0 - am));
5630
+ } else {
5631
+ const double a1 = s * (1.5 - x0f);
5632
+ Add(line[x0i + 1], d * (a1 - a0));
5633
+ for (long xi = x0i + 2; xi < x1i - 1; ++xi) Add(line[xi], d * s);
5634
+ const double a2 = a1 + (double)(x1i - x0i - 3) * s;
5635
+ Add(line[x1i - 1], d * (1 - a2 - am));
5636
+ }
5637
+ Add(line[x1i], d * am);
5638
+ }
5639
+ x = xnext;
5640
+ }
5641
+ }
5642
+
5643
+ // The rows integrated into one byte a pixel, width × height into `out`.
5644
+ void ToAlpha(uint8_t* out) const {
5645
+ for (long y = 0; y < height_; ++y) {
5646
+ const float* line = acc_.data() + y * stride_;
5647
+ uint8_t* row = out + y * width_;
5648
+ double sum = 0;
5649
+ for (long x = 0; x < width_; ++x) {
5650
+ sum += line[x];
5651
+ double c = sum < 0 ? -sum : sum;
5652
+ if (c > 1) c = 1;
5653
+ row[x] = (uint8_t)(c * 255 + 0.5);
5654
+ }
5655
+ }
5656
+ }
5657
+
5658
+ private:
5659
+ // A cell is a float, as ntk's Float32Array is, and a deposit is added to it
5660
+ // in double and rounded once, as JavaScript does: the two stay byte-alike.
5661
+ static void Add(float& cell, double v) { cell = (float)(cell + v); }
5662
+
5663
+ long width_, height_, stride_;
5664
+ std::vector<float> acc_;
5665
+ };
5666
+
5667
+ // A glyph outline walked into the accumulator: every subpath closed, as a
5668
+ // fill closes it, and curves cut into chords the way ntk's flatten does — a
5669
+ // step for every three pixels of the control points' extent, three to
5670
+ // twenty-four of them.
5671
+ struct OutlineWalk {
5672
+ CoverageAccumulator* acc;
5673
+ double x = 0, y = 0; // the pen
5674
+ double sx = 0, sy = 0; // where the subpath began
5675
+
5676
+ void To(double nx, double ny) {
5677
+ acc->Edge(x, y, nx, ny);
5678
+ x = nx;
5679
+ y = ny;
5680
+ }
5681
+ void Close() { To(sx, sy); }
5682
+
5683
+ static int Steps(std::initializer_list<CGPoint> points) {
5684
+ double x0 = INFINITY, y0 = INFINITY, x1 = -INFINITY, y1 = -INFINITY;
5685
+ for (const CGPoint& p : points) {
5686
+ x0 = std::min(x0, (double)p.x);
5687
+ x1 = std::max(x1, (double)p.x);
5688
+ y0 = std::min(y0, (double)p.y);
5689
+ y1 = std::max(y1, (double)p.y);
5690
+ }
5691
+ const double extent = std::max(x1 - x0, y1 - y0);
5692
+ return (int)std::min(24.0, std::max(3.0, std::ceil(extent / 3)));
5693
+ }
5694
+
5695
+ static void Apply(void* info, const CGPathElement* e) {
5696
+ auto* w = (OutlineWalk*)info;
5697
+ const CGPoint* p = e->points;
5698
+ switch (e->type) {
5699
+ case kCGPathElementMoveToPoint:
5700
+ w->Close();
5701
+ w->x = w->sx = p[0].x;
5702
+ w->y = w->sy = p[0].y;
5703
+ break;
5704
+ case kCGPathElementAddLineToPoint:
5705
+ w->To(p[0].x, p[0].y);
5706
+ break;
5707
+ case kCGPathElementAddQuadCurveToPoint: {
5708
+ const double x0 = w->x, y0 = w->y;
5709
+ const int steps = Steps({CGPointMake(x0, y0), p[0], p[1]});
5710
+ for (int i = 1; i <= steps; ++i) {
5711
+ const double t = (double)i / steps, mt = 1 - t;
5712
+ w->To(mt * mt * x0 + 2 * mt * t * p[0].x + t * t * p[1].x,
5713
+ mt * mt * y0 + 2 * mt * t * p[0].y + t * t * p[1].y);
5714
+ }
5715
+ break;
5716
+ }
5717
+ case kCGPathElementAddCurveToPoint: {
5718
+ const double x0 = w->x, y0 = w->y;
5719
+ const int steps = Steps({CGPointMake(x0, y0), p[0], p[1], p[2]});
5720
+ for (int i = 1; i <= steps; ++i) {
5721
+ const double t = (double)i / steps, mt = 1 - t;
5722
+ w->To(mt * mt * mt * x0 + 3 * mt * mt * t * p[0].x +
5723
+ 3 * mt * t * t * p[1].x + t * t * t * p[2].x,
5724
+ mt * mt * mt * y0 + 3 * mt * mt * t * p[0].y +
5725
+ 3 * mt * t * t * p[1].y + t * t * t * p[2].y);
5726
+ }
5727
+ break;
5728
+ }
5729
+ case kCGPathElementCloseSubpath:
5730
+ w->Close();
5731
+ break;
5732
+ }
5733
+ }
5734
+ };
5735
+
5736
+ // A glyph with no outline to fill, drawn instead: Apple Color Emoji's
5737
+ // bitmaps, which come out as their silhouettes.
5738
+ struct DrawnGlyph {
5739
+ CTFontRef font; // the run's, alive as long as the layout
5740
+ CGGlyph glyph;
5741
+ CGPoint origin; // canvas space, y down
5742
+ };
5743
+
5744
+ // layoutCoverage(layoutHandle, pad?) -> { width, height, data } | null
5745
+ //
5746
+ // How much of each pixel a layout's glyphs cover, one byte a pixel, without
5747
+ // drawing the layout anywhere: for text drawn where a surface is not, such as
5748
+ // a GL surface's label atlas or a signed distance field made from a string.
5749
+ // The raster is the layout's box in whole pixels, createLayout's width and
5750
+ // height rounded up, with `pad` pixels round it (a fraction rounds up too).
5751
+ // `data` is width × height bytes, row-major, the top row first, and the
5752
+ // layout's origin is at (pad, pad): the glyphs are where
5753
+ // drawLayout(surface, layout, pad, pad) would draw them, one pixel to one of
5754
+ // the layout's units. Null for anything that is not a layout, and for a layout
5755
+ // with no box and no pad to make one.
5756
+ //
5757
+ // It is the outlines' own coverage, which is what a raster that will be scaled
5758
+ // wants, and not the ink the screen gets. Every glyph's outline goes where the
5759
+ // typesetter put it, unrounded, and the whole layout is filled once, non-zero,
5760
+ // so glyphs that overlap cover a pixel once. CoreText's glyph rasterizer is
5761
+ // not used for it, even with font smoothing off: it snaps nothing, but it
5762
+ // shrinks a small glyph's counters (Menlo's b at 14px comes out 5% heavier
5763
+ // than its outline). CoreGraphics' own path fill is exact to a percent but
5764
+ // costs several times the draw and readback this replaces.
5765
+ //
5766
+ // Ink is the caller's: a span's colour plays no part, so a translucent span
5767
+ // covers what an opaque one does. A glyph with no outline but ink of its own
5768
+ // (Apple Color Emoji's bitmaps) is drawn over the rest into an alpha-only
5769
+ // bitmap, which keeps its alpha: its silhouette.
5770
+ static Napi::Value LayoutCoverage(const Napi::CallbackInfo& info) {
5771
+ Napi::Env env = info.Env();
5772
+ if (info.Length() < 1 || !info[0].IsExternal()) return env.Null();
5773
+ CALLayout* layout = LayoutFrom(info[0]);
5774
+ const double asked = info.Length() > 1 && info[1].IsNumber()
5775
+ ? info[1].As<Napi::Number>().DoubleValue()
5776
+ : 0;
5777
+ const long pad =
5778
+ asked > 0 && std::isfinite(asked) ? (long)std::ceil(asked) : 0;
5779
+ const long width = (long)std::ceil(layout->width) + pad * 2;
5780
+ const long height = (long)std::ceil(layout->height) + pad * 2;
5781
+ if (width <= 0 || height <= 0) return env.Null();
5782
+
5783
+ CoverageAccumulator acc(width, height);
5784
+ OutlineWalk walk{&acc};
5785
+ std::vector<DrawnGlyph> drawn;
5786
+ std::vector<CGGlyph> glyphs;
5787
+ std::vector<CGPoint> positions;
5788
+ for (const CALLine& L : layout->lines) {
5789
+ CFArrayRef runs = CTLineGetGlyphRuns(L.line);
5790
+ for (CFIndex ri = 0; ri < CFArrayGetCount(runs); ri++) {
5791
+ CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(runs, ri);
5792
+ CTFontRef font = (CTFontRef)CFDictionaryGetValue(
5793
+ CTRunGetAttributes(run), kCTFontAttributeName);
5794
+ const CFIndex count = CTRunGetGlyphCount(run);
5795
+ if (!font || count <= 0) continue;
5796
+ glyphs.resize((size_t)count);
5797
+ positions.resize((size_t)count);
5798
+ CTRunGetGlyphs(run, CFRangeMake(0, 0), glyphs.data());
5799
+ CTRunGetPositions(run, CFRangeMake(0, 0), positions.data());
5800
+ for (size_t g = 0; g < (size_t)count; g++) {
5801
+ // a glyph shaping deleted, such as a ligature's second half
5802
+ if (glyphs[g] == kCGFontIndexInvalid) continue;
5803
+ // positions are from the line's origin, y up; outlines are y up
5804
+ // from the glyph's origin, flipped here into canvas space
5805
+ const double ox = pad + L.x + positions[g].x;
5806
+ const double oy = pad + L.baseline - positions[g].y;
5807
+ const CGAffineTransform t = {1, 0, 0, -1, ox, oy};
5808
+ CGPathRef outline = CTFontCreatePathForGlyph(font, glyphs[g], &t);
5809
+ if (outline) {
5810
+ walk.x = walk.sx = walk.y = walk.sy = 0;
5811
+ CGPathApply(outline, &walk, OutlineWalk::Apply);
5812
+ walk.Close();
5813
+ CGPathRelease(outline);
5814
+ continue;
5815
+ }
5816
+ // no outline: a space, or a glyph whose ink is a bitmap
5817
+ CGRect bounds;
5818
+ CTFontGetBoundingRectsForGlyphs(font, kCTFontOrientationDefault,
5819
+ &glyphs[g], &bounds, 1);
5820
+ if (!CGRectIsEmpty(bounds))
5821
+ drawn.push_back({font, glyphs[g], CGPointMake(ox, oy)});
5822
+ }
5823
+ }
5824
+ }
5825
+
5826
+ // A new ArrayBuffer is zeroed, which is "covers nothing".
5827
+ Napi::Uint8Array data = Napi::Uint8Array::New(env, (size_t)(width * height));
5828
+ acc.ToAlpha(data.Data());
5829
+ if (!drawn.empty()) {
5830
+ CGContextRef ctx = CGBitmapContextCreate(
5831
+ data.Data(), (size_t)width, (size_t)height, 8, (size_t)width, NULL,
5832
+ (CGBitmapInfo)kCGImageAlphaOnly);
5833
+ if (ctx) {
5834
+ // top-left origin, y down, as a surface's base CTM has it; the glyph at
5835
+ // the position the run gave it, the way drawLayout draws it
5836
+ CGContextTranslateCTM(ctx, 0, (CGFloat)height);
5837
+ CGContextScaleCTM(ctx, 1, -1);
5838
+ CGContextSetShouldSmoothFonts(ctx, false);
5839
+ CGContextSetShouldSubpixelPositionFonts(ctx, true);
5840
+ CGContextSetShouldSubpixelQuantizeFonts(ctx, false);
5841
+ CGContextSetGrayFillColor(ctx, 0, 1);
5842
+ CGContextSetTextMatrix(ctx, CGAffineTransformMakeScale(1, -1));
5843
+ for (const DrawnGlyph& d : drawn) {
5844
+ // CTFontDrawGlyphs reads positions in text space, through the flip
5845
+ const CGPoint at = CGPointMake(d.origin.x, -d.origin.y);
5846
+ CTFontDrawGlyphs(d.font, &d.glyph, &at, 1, ctx);
5847
+ }
5848
+ CGContextRelease(ctx);
5849
+ }
5850
+ }
5851
+
5852
+ Napi::Object out = Napi::Object::New(env);
5853
+ out.Set("width", (double)width);
5854
+ out.Set("height", (double)height);
5855
+ out.Set("data", data);
5856
+ return out;
5857
+ }
5858
+
5425
5859
  // ctxSetShadow(surface, blur, dx, dy, r, g, b, a) — blur <= 0 clears.
5426
5860
  static Napi::Value CtxSetShadow(const Napi::CallbackInfo& info) {
5427
5861
  CALSurface* s = SurfaceFrom(info[0]);
@@ -6636,12 +7070,14 @@ void InitBackend(Napi::Env env, Napi::Object exports) {
6636
7070
  BFN("listFonts", ListFonts);
6637
7071
  BFN("loadFontData", LoadFontData);
6638
7072
  BFN("createLayout", CreateLayout);
7073
+ BFN("releaseTypesetter", ReleaseTypesetter);
6639
7074
  BFN("drawLayout", DrawLayout);
6640
7075
  BFN("ctxDrawGlyphs", CtxDrawGlyphs);
6641
7076
  BFN("ctxDrawSymbol", CtxDrawSymbol);
6642
7077
  BFN("symbolSize", SymbolSize);
6643
7078
  BFN("layoutIndexAt", LayoutIndexAt);
6644
7079
  BFN("layoutCaret", LayoutCaret);
7080
+ BFN("layoutCoverage", LayoutCoverage);
6645
7081
  BFN("pasteboardWriteText", PbWriteTextFn);
6646
7082
  BFN("pasteboardReadText", PbReadTextFn);
6647
7083
  BFN("pasteboardClear", PbClearFn);