@windowkit/appkit 0.33.1 → 0.34.1

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
@@ -605,6 +605,28 @@ native.ctxSetGlobalAlpha(win, 0.6);
605
605
  native.ctxDrawSurfaceFaded(win, card, 0, 0, 556, 300, 100, 100, 556, 300, 0.6);
606
606
  ```
607
607
 
608
+ - **`native.ctxDrawSurfaceFiltered(dst, src, sx, sy, sw, sh, dx, dy, dw, dh, filter)`** —
609
+ `ctxDrawSurface` through a CSS filter list, canvas's `filter`: `filter` is
610
+ `{ matrices, alpha, blur }`, the colour functions in the order written (each twelve
611
+ numbers, three rows of red, green and blue weights and an offset over straight colour
612
+ in 0–1, clamped to 0–1 before the next), what alpha is multiplied by, and the standard
613
+ deviation of a Gaussian blur in source pixels. The blur is of premultiplied colour with
614
+ nothing past the source rect, so the drawing reaches three deviations past the
615
+ destination rect. Run by vImage on the calling thread, and drawn under the
616
+ destination's state as `ctxDrawSurface` draws: a 1281x961 surface in 2.6ms through a
617
+ colour function and 3.9ms through a blur on an M1 Pro, where reading the pixels back and
618
+ filtering them in JavaScript took 15. Answers true where it drew and false where there
619
+ was nothing to draw, so a caller can feature-detect the verb and keep its own path.
620
+
621
+ ```js
622
+ const grayscale = [0.2126, 0.7152, 0.0722, 0, 0.2126, 0.7152, 0.0722, 0, 0.2126, 0.7152, 0.0722, 0];
623
+ native.ctxDrawSurfaceFiltered(win, card, 0, 0, 556, 300, 100, 100, 556, 300, {
624
+ matrices: [grayscale],
625
+ alpha: 1,
626
+ blur: 3,
627
+ });
628
+ ```
629
+
608
630
  - **`native.ctxSetImageSmoothing(surface, quality)`** — how an image or a surface drawn
609
631
  scaled or turned is resampled: `'none'` (the nearest pixel), `'low'`, `'medium'` or
610
632
  `'high'`, the 2D canvas's `imageSmoothingEnabled` and `imageSmoothingQuality`. It is
@@ -899,6 +921,21 @@ process with no audio, and — only where System Audio Recording is allowed —
899
921
  taps everything and one process; `test/system-audio-threaded.js` lists and
900
922
  refuses from a worker.
901
923
 
924
+ ## Text: fonts macOS would download
925
+
926
+ macOS lists some 1,300 faces it downloads on demand, Hei, Kai and Songti among them, and
927
+ asking AppKit or CoreText for one by name, in a process with an NSApp, puts up "<app> needs
928
+ to download the font …" and holds the call until someone answers. A family list is a
929
+ browser's to write, and Chinese fallback stacks name these families as a matter of course,
930
+ so `matchFont`, `fontByPostScriptName`, `listFonts({ family })` and a pop-up's `fontFamily`
931
+ match only a family or a PostScript name of a face available now — installed, or registered
932
+ by the process — and pass over any other, as they pass over a name nobody has. Nothing is
933
+ downloaded and nothing is asked.
934
+
935
+ - **`fontAvailable(name)`** — whether a family or PostScript name, in any case, is one of
936
+ those: what the verbs above ask first. Read from CoreText's collection of available fonts,
937
+ which activates nothing, and kept until the registered fonts change.
938
+
902
939
  ## Text: at a display's scale
903
940
 
904
941
  A text verb's size is the caller's pixels, and a renderer that draws in device pixels hands
package/binding.gyp CHANGED
@@ -29,6 +29,7 @@
29
29
  "libraries": [
30
30
  "-framework Cocoa",
31
31
  "-framework QuartzCore",
32
+ "-framework Accelerate",
32
33
  "-framework CoreText",
33
34
  "-framework CoreGraphics",
34
35
  "-framework ImageIO",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@windowkit/appkit",
3
- "version": "0.33.1",
3
+ "version": "0.34.1",
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/contents-gravity.js && node test/contents-center.js && node test/accessibility-display.js && node test/ignores-mouse-events.js && node test/popup-menu.js && node test/pasteboard-write.js && node test/surface-blit.js && node test/surface-faded.js && node test/image-smoothing.js && node test/surface-colorspace.js && node test/video-surface.js && node test/player.js && node test/player-vp9.js && node test/capture.js && node test/capture-threaded.js && node test/display-stream.js && node test/system-audio.js && node test/system-audio-threaded.js && node test/round-rect-xy.js && node test/clip-rule.js && node test/radial-gradient.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-justify.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/resize-no-crossing.js && node test/window-states.js && node test/threaded-window-states.js && node test/activation-policy.js && node test/last-input.js"
46
+ "test": "node test/app-lifecycle.js && node test/animation.js && node test/layer-transform.js && node test/contents-gravity.js && node test/contents-center.js && node test/accessibility-display.js && node test/ignores-mouse-events.js && node test/popup-menu.js && node test/pasteboard-write.js && node test/surface-blit.js && node test/surface-faded.js && node test/surface-filtered.js && node test/image-smoothing.js && node test/surface-colorspace.js && node test/video-surface.js && node test/player.js && node test/player-vp9.js && node test/capture.js && node test/capture-threaded.js && node test/display-stream.js && node test/system-audio.js && node test/system-audio-threaded.js && node test/round-rect-xy.js && node test/clip-rule.js && node test/radial-gradient.js && node test/control-bezels.js && node test/text-features.js && node test/font-from-data.js && node test/font-download.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-justify.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/resize-no-crossing.js && node test/window-states.js && node test/threaded-window-states.js && node test/activation-policy.js && node test/last-input.js"
47
47
  },
48
48
  "dependencies": {
49
49
  "node-addon-api": "^8.3.0"
Binary file
package/src/backend.mm CHANGED
@@ -20,11 +20,13 @@
20
20
  #import <QuartzCore/QuartzCore.h>
21
21
  #import <CoreText/CoreText.h>
22
22
  #import <IOSurface/IOSurface.h>
23
+ #import <Accelerate/Accelerate.h>
23
24
  #import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
24
25
  #include <objc/runtime.h>
25
26
  #include <dlfcn.h>
26
27
  #include <pthread.h>
27
28
 
29
+ #include <array>
28
30
  #include <atomic>
29
31
  #include <cmath>
30
32
  #include <memory>
@@ -2503,11 +2505,14 @@ static PopUpSpec ParsePopUpSpec(Napi::Object o) {
2503
2505
  return s;
2504
2506
  }
2505
2507
 
2508
+ static bool BFontAvailable(NSString* name);
2509
+
2506
2510
  // The family asked for when the system has it — a face it matched under
2507
- // another name is not it — and the menu font at that size otherwise.
2511
+ // another name is not it, and one it would download is not had (see
2512
+ // BFontAvailable) — and the menu font at that size otherwise.
2508
2513
  static NSFont* PopUpFont(NSString* family, double size) {
2509
2514
  CGFloat sz = size > 0 ? size : [NSFont systemFontSize];
2510
- if (family.length) {
2515
+ if (BFontAvailable(family)) {
2511
2516
  NSFontDescriptor* d = [NSFontDescriptor
2512
2517
  fontDescriptorWithFontAttributes:@{NSFontFamilyAttribute : family}];
2513
2518
  NSFont* f = [NSFont fontWithDescriptor:d size:sz];
@@ -4746,6 +4751,204 @@ static Napi::Value CtxDrawSurfaceFaded(const Napi::CallbackInfo& info) {
4746
4751
  return info.Env().Undefined();
4747
4752
  }
4748
4753
 
4754
+ // drawSurfaceFiltered(dst, src, sx, sy, sw, sh, dx, dy, dw, dh, filter)
4755
+ //
4756
+ // drawSurface through a CSS filter list: `filter` is `{ matrices, alpha,
4757
+ // blur }` — the colour functions in the order written, each twelve numbers,
4758
+ // three rows of red, green and blue weights and an offset over straight
4759
+ // colour in 0–1, clamped to 0–1 before the next; what alpha is multiplied
4760
+ // by; and the standard deviation of a Gaussian blur in SOURCE pixels, 0 for
4761
+ // none. react-x11's src/backend/filter.js is the model, and the caller
4762
+ // converts a blur given in destination units.
4763
+ //
4764
+ // Run by Accelerate's vImage over the source rect's premultiplied pixels,
4765
+ // on the calling thread. A colour function is a 4x4 integer matrix over
4766
+ // premultiplied colour, its offset carried by alpha — exact, since a matrix
4767
+ // over straight colour that leaves alpha as it is is a linear map on
4768
+ // premultiplied colour — and the clamp to 0–1 after it is a clip of each
4769
+ // channel to its pixel's alpha. The blur is three box blurs that come to the
4770
+ // Gaussian (Kovesi, "Fast almost-Gaussian filtering", 2010), as filter.js's
4771
+ // is, with nothing past the source rect, and the drawing reaches three
4772
+ // deviations past the destination rect, scaled as the rect is. The colour
4773
+ // functions run after it, where they commute with it but for the clamps.
4774
+ //
4775
+ // The result is drawn as drawSurface draws, under the destination's state:
4776
+ // its CTM, clip, global alpha and blend mode. On the CPU in JavaScript the
4777
+ // same draw read the pixels back, ran the matrices or the blur over them a
4778
+ // pixel at a time and wrote them into a bitmap of their own: 15 ms for a
4779
+ // 1281x961 surface on an M1 Pro, where this is 2.6 for a colour function and
4780
+ // 3.9 for a blur. Core Image was measured too, and came to 4.2 and 7.3: the
4781
+ // surfaces here are bitmaps in main memory, which it uploads and reads back
4782
+ // at every draw. Answers true where it drew, false where there was nothing
4783
+ // to draw.
4784
+ static Napi::Value CtxDrawSurfaceFiltered(const Napi::CallbackInfo& info) {
4785
+ Napi::Env env = info.Env();
4786
+ CALSurface* dst = SurfaceFrom(info[0]);
4787
+ CALSurface* src = SurfaceFrom(info[1]);
4788
+ if (!dst || !src || info.Length() < 11 || !info[10].IsObject()) {
4789
+ return Napi::Boolean::New(env, false);
4790
+ }
4791
+ double sx = info[2].As<Napi::Number>().DoubleValue();
4792
+ double sy = info[3].As<Napi::Number>().DoubleValue();
4793
+ double sw = info[4].As<Napi::Number>().DoubleValue();
4794
+ double sh = info[5].As<Napi::Number>().DoubleValue();
4795
+ double dx = info[6].As<Napi::Number>().DoubleValue();
4796
+ double dy = info[7].As<Napi::Number>().DoubleValue();
4797
+ double dw = info[8].As<Napi::Number>().DoubleValue();
4798
+ double dh = info[9].As<Napi::Number>().DoubleValue();
4799
+ Napi::Object spec = info[10].As<Napi::Object>();
4800
+ auto number = [&](const char* key, double fallback) {
4801
+ Napi::Value v = spec.Get(key);
4802
+ return v.IsNumber() ? v.As<Napi::Number>().DoubleValue() : fallback;
4803
+ };
4804
+ double alpha = number("alpha", 1);
4805
+ double blur = number("blur", 0);
4806
+ std::vector<std::array<double, 12>> matrices;
4807
+ Napi::Value list = spec.Get("matrices");
4808
+ if (list.IsObject()) {
4809
+ Napi::Object rows = list.As<Napi::Object>();
4810
+ uint32_t count = rows.Get("length").IsNumber()
4811
+ ? rows.Get("length").As<Napi::Number>().Uint32Value()
4812
+ : 0;
4813
+ for (uint32_t i = 0; i < count; i++) {
4814
+ Napi::Value m = rows.Get(i);
4815
+ if (!m.IsObject()) continue;
4816
+ Napi::Object row = m.As<Napi::Object>();
4817
+ std::array<double, 12> v{};
4818
+ for (uint32_t k = 0; k < 12; k++) {
4819
+ Napi::Value x = row.Get(k);
4820
+ v[k] = x.IsNumber() ? x.As<Napi::Number>().DoubleValue() : 0;
4821
+ }
4822
+ matrices.push_back(v);
4823
+ }
4824
+ }
4825
+ if (!(sw > 0 && sh > 0) || dw == 0 || dh == 0 || !std::isfinite(sx) ||
4826
+ !std::isfinite(sy) || !std::isfinite(sw) || !std::isfinite(sh) ||
4827
+ !std::isfinite(alpha) || !std::isfinite(blur)) {
4828
+ return Napi::Boolean::New(env, false);
4829
+ }
4830
+ alpha = std::min(1.0, std::max(0.0, alpha));
4831
+ if (!(blur > 0)) blur = 0;
4832
+
4833
+ // the source rect on the pixel grid, and the blur's reach round it
4834
+ long x0 = (long)floor(sx);
4835
+ long y0 = (long)floor(sy);
4836
+ long w = (long)ceil(sx + sw) - x0;
4837
+ long h = (long)ceil(sy + sh) - y0;
4838
+ long margin = blur > 0 ? (long)ceil(3 * blur) : 0;
4839
+ long W = w + 2 * margin;
4840
+ long H = h + 2 * margin;
4841
+ if (W <= 0 || H <= 0 || W > 32768 || H > 32768) {
4842
+ return Napi::Boolean::New(env, false);
4843
+ }
4844
+ CGColorSpaceRef cs = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
4845
+ CGContextRef work = CGBitmapContextCreate(
4846
+ NULL, W, H, 8, 0, cs,
4847
+ kCGImageAlphaPremultipliedFirst | (CGBitmapInfo)kCGBitmapByteOrder32Host);
4848
+ CGColorSpaceRelease(cs);
4849
+ if (!work) return Napi::Boolean::New(env, false);
4850
+ uint8_t* base = (uint8_t*)CGBitmapContextGetData(work);
4851
+ size_t stride = CGBitmapContextGetBytesPerRow(work);
4852
+ memset(base, 0, stride * H);
4853
+ // what of the rect is in the source: the rest is nothing
4854
+ if (src->iosurface) IOSurfaceLock(src->iosurface, kIOSurfaceLockReadOnly, nullptr);
4855
+ const uint8_t* from = (const uint8_t*)CGBitmapContextGetData(src->ctx);
4856
+ size_t fromStride = CGBitmapContextGetBytesPerRow(src->ctx);
4857
+ long left = std::max(0L, x0);
4858
+ long right = std::min((long)src->width, x0 + w);
4859
+ if (from && right > left) {
4860
+ for (long y = 0; y < h; y++) {
4861
+ long row = y0 + y;
4862
+ if (row < 0 || row >= (long)src->height) continue;
4863
+ memcpy(base + (y + margin) * stride + (left - x0 + margin) * 4,
4864
+ from + row * fromStride + left * 4, (right - left) * 4);
4865
+ }
4866
+ }
4867
+ if (src->iosurface) IOSurfaceUnlock(src->iosurface, kIOSurfaceLockReadOnly, nullptr);
4868
+
4869
+ vImage_Buffer buf = {base, (vImagePixelCount)H, (vImagePixelCount)W, stride};
4870
+ if (blur > 0) {
4871
+ // three box blurs whose widths come to the Gaussian, as filter.js's
4872
+ // boxRadii works them out
4873
+ double ideal = sqrt(12 * blur * blur / 3 + 1);
4874
+ long lower = (long)floor(ideal);
4875
+ if (lower % 2 == 0) lower -= 1;
4876
+ long upper = lower + 2;
4877
+ long m = lround((12 * blur * blur - 3.0 * lower * lower - 12.0 * lower - 9) /
4878
+ (-4.0 * lower - 4));
4879
+ vImage_Buffer other = buf;
4880
+ other.data = malloc(stride * H);
4881
+ Pixel_8888 clear = {0, 0, 0, 0};
4882
+ size_t scratch = (size_t)vImageBoxConvolve_ARGB8888(
4883
+ &buf, &other, NULL, 0, 0, (uint32_t)upper, (uint32_t)upper, clear,
4884
+ kvImageGetTempBufferSize | kvImageBackgroundColorFill);
4885
+ void* temp = scratch > 0 ? malloc(scratch) : nullptr;
4886
+ vImage_Buffer* a = &buf;
4887
+ vImage_Buffer* b = &other;
4888
+ for (long i = 0; other.data && i < 3; i++) {
4889
+ uint32_t d = (uint32_t)(i < m ? lower : upper);
4890
+ if (d < 3) continue;
4891
+ vImageBoxConvolve_ARGB8888(a, b, temp, 0, 0, d, d, clear,
4892
+ kvImageBackgroundColorFill);
4893
+ std::swap(a, b);
4894
+ }
4895
+ if (a != &buf) memcpy(buf.data, a->data, stride * H);
4896
+ free(other.data);
4897
+ free(temp);
4898
+ }
4899
+ // vImage numbers a pixel's channels as they are in memory: blue, green,
4900
+ // red, alpha in a host-order premultiplied-first bitmap. A matrix entry
4901
+ // M[in * 4 + out] weighs channel `in` into channel `out`, over 256.
4902
+ const int32_t D = 256;
4903
+ enum { B = 0, G = 1, R = 2, A = 3 };
4904
+ auto weigh = [&](int16_t* M, int in, int out, double v) {
4905
+ M[in * 4 + out] = (int16_t)std::max(-32768.0, std::min(32767.0, round(v * D)));
4906
+ };
4907
+ for (size_t i = 0; i < matrices.size(); i++) {
4908
+ const auto& m = matrices[i];
4909
+ double fade = i + 1 == matrices.size() ? alpha : 1;
4910
+ int16_t M[16] = {0};
4911
+ const int outs[3] = {R, G, B};
4912
+ for (int r = 0; r < 3; r++) {
4913
+ weigh(M, R, outs[r], m[r * 4] * fade);
4914
+ weigh(M, G, outs[r], m[r * 4 + 1] * fade);
4915
+ weigh(M, B, outs[r], m[r * 4 + 2] * fade);
4916
+ weigh(M, A, outs[r], m[r * 4 + 3] * fade);
4917
+ }
4918
+ weigh(M, A, A, fade);
4919
+ vImageMatrixMultiply_ARGB8888(&buf, &buf, M, D, NULL, NULL, kvImageNoFlags);
4920
+ // each function's result in 0–1 of straight colour: no channel past
4921
+ // its alpha (the alpha last, as RGBA and BGRA both have it)
4922
+ vImageClipToAlpha_RGBA8888(&buf, &buf, kvImageNoFlags);
4923
+ }
4924
+ if (matrices.empty() && alpha < 1) {
4925
+ int16_t M[16] = {0};
4926
+ for (int k = 0; k < 4; k++) weigh(M, k, k, alpha);
4927
+ vImageMatrixMultiply_ARGB8888(&buf, &buf, M, D, NULL, NULL, kvImageNoFlags);
4928
+ }
4929
+
4930
+ CGImageRef done = CGBitmapContextCreateImage(work);
4931
+ CGContextRelease(work);
4932
+ if (!done) return Napi::Boolean::New(env, false);
4933
+ // where the pixels land: the destination rect, moved for the source
4934
+ // rect's grid and grown by the blur's reach, scaled as the rect is
4935
+ double kx = dw / sw;
4936
+ double ky = dh / sh;
4937
+ double ox = dx + (x0 - margin - sx) * kx;
4938
+ double oy = dy + (y0 - margin - sy) * ky;
4939
+ double ow = W * kx;
4940
+ double oh = H * ky;
4941
+ CGContextSaveGState(dst->ctx);
4942
+ // the base CTM is flipped; flip back around the destination rect so the
4943
+ // image lands upright
4944
+ CGContextTranslateCTM(dst->ctx, ox, oy + oh);
4945
+ CGContextScaleCTM(dst->ctx, 1, -1);
4946
+ CGContextDrawImage(dst->ctx, CGRectMake(0, 0, ow, oh), done);
4947
+ CGContextRestoreGState(dst->ctx);
4948
+ CGImageRelease(done);
4949
+ return Napi::Boolean::New(env, true);
4950
+ }
4951
+
4749
4952
  // putImageData(surface, buffer RGBA straight, w, h, dx, dy) — writes pixels
4750
4953
  // directly, transform- and clip-free, per the canvas contract.
4751
4954
  static Napi::Value CtxPutImageData(const Napi::CallbackInfo& info) {
@@ -4968,6 +5171,86 @@ static CTFontRef BAtScale(CTFontRef font, double scale) {
4968
5171
  return scaled;
4969
5172
  }
4970
5173
 
5174
+ // --- what is installed -----------------------------------------------------
5175
+ //
5176
+ // macOS lists some 1,300 faces it will download the first time an app asks
5177
+ // for one — Hei, Kai, Songti and the rest of the CJK sets among them — and
5178
+ // asking by name is enough: `fontWithDescriptor:`, `fontWithName:` and
5179
+ // CTFontCreateWithName of such a family, in a process with an NSApp, put up
5180
+ // "<app> needs to download the font …" and block the call until it is
5181
+ // answered. A browser's font stacks name these families as a matter of
5182
+ // course ("PingFang SC", "Hei", …), so every page with a Chinese fallback
5183
+ // stopped its process on a prompt per font. So a name is matched only where
5184
+ // it is a family or a PostScript name of a face this process can use now —
5185
+ // installed, or registered by the process — read from CoreText's collection
5186
+ // of available fonts, which lists no downloadable face and activates
5187
+ // nothing. The names are kept until the registered fonts change.
5188
+
5189
+ static std::atomic<uint64_t> gFontsGeneration{1};
5190
+
5191
+ static void BFontsChanged(CFNotificationCenterRef, void*, CFStringRef,
5192
+ const void*, CFDictionaryRef) {
5193
+ gFontsGeneration++;
5194
+ }
5195
+
5196
+ /** Whether `name` (any case) is a family or a PostScript name of a face
5197
+ * available without a download. Names CoreText keeps hidden (".SF NS")
5198
+ * pass: no download is ever one of them. */
5199
+ static bool BFontAvailable(NSString* name) {
5200
+ if (name.length == 0) return false;
5201
+ if ([name hasPrefix:@"."]) return true;
5202
+ static std::mutex lock;
5203
+ static NSSet<NSString*>* names = nil;
5204
+ static uint64_t built = 0;
5205
+ static dispatch_once_t once;
5206
+ dispatch_once(&once, ^{
5207
+ CFNotificationCenterAddObserver(
5208
+ CFNotificationCenterGetLocalCenter(), NULL, BFontsChanged,
5209
+ kCTFontManagerRegisteredFontsChangedNotification, NULL,
5210
+ CFNotificationSuspensionBehaviorDeliverImmediately);
5211
+ });
5212
+ NSSet<NSString*>* now = nil;
5213
+ {
5214
+ std::lock_guard<std::mutex> guard(lock);
5215
+ const uint64_t generation = gFontsGeneration.load();
5216
+ if (!names || built != generation) {
5217
+ NSMutableSet<NSString*>* all = [NSMutableSet set];
5218
+ CTFontCollectionRef available =
5219
+ CTFontCollectionCreateFromAvailableFonts(NULL);
5220
+ CFArrayRef faces =
5221
+ available ? CTFontCollectionCreateMatchingFontDescriptors(available)
5222
+ : NULL;
5223
+ const CFIndex count = faces ? CFArrayGetCount(faces) : 0;
5224
+ for (CFIndex i = 0; i < count; i++) {
5225
+ CTFontDescriptorRef d =
5226
+ (CTFontDescriptorRef)CFArrayGetValueAtIndex(faces, i);
5227
+ for (CFStringRef attribute :
5228
+ {kCTFontFamilyNameAttribute, kCTFontNameAttribute}) {
5229
+ CFStringRef value =
5230
+ (CFStringRef)CTFontDescriptorCopyAttribute(d, attribute);
5231
+ if (!value) continue;
5232
+ [all addObject:((__bridge NSString*)value).lowercaseString];
5233
+ CFRelease(value);
5234
+ }
5235
+ }
5236
+ if (faces) CFRelease(faces);
5237
+ if (available) CFRelease(available);
5238
+ names = [all copy];
5239
+ built = generation;
5240
+ }
5241
+ now = names;
5242
+ }
5243
+ return [now containsObject:name.lowercaseString];
5244
+ }
5245
+
5246
+ // fontAvailable(name) -> whether a family or PostScript name answers without
5247
+ // macOS downloading a font: what matchFont, fontByPostScriptName and
5248
+ // listFonts ask before they match one.
5249
+ static Napi::Value FontAvailable(const Napi::CallbackInfo& info) {
5250
+ return Napi::Boolean::New(
5251
+ info.Env(), info[0].IsString() && BFontAvailable(BToNSString(info[0])));
5252
+ }
5253
+
4971
5254
  // matchFont({ families: [..], size, weight (100-900), italic, scale? })
4972
5255
  // -> font handle
4973
5256
  // `size` is in the caller's pixels; `scale`, the display's, makes the font
@@ -4992,6 +5275,10 @@ static NSFont* ResolveFamily(NSString* family, double size, double weight,
4992
5275
  font = [NSFont fontWithName:@"Times New Roman" size:size];
4993
5276
  } else if ([lower isEqualToString:@"cursive"]) {
4994
5277
  font = [NSFont fontWithName:@"Snell Roundhand" size:size];
5278
+ } else if (!BFontAvailable(family)) {
5279
+ // not here, or here only for a download (see BFontAvailable): not found,
5280
+ // and the next family in the list gets its turn
5281
+ return nil;
4995
5282
  } else {
4996
5283
  // A named family. Build a descriptor so weight/width participate in
4997
5284
  // matching; verify the match really is this family (CoreText silently
@@ -5617,6 +5904,7 @@ static Napi::Value FontByPostScriptName(const Napi::CallbackInfo& info) {
5617
5904
  NSString* name = BToNSString(info[0]);
5618
5905
  double size = info[1].As<Napi::Number>().DoubleValue();
5619
5906
  const double scale = BScaleOf(info[2]);
5907
+ if (!BFontAvailable(name)) return env.Null(); // nor a download's
5620
5908
  const CGAffineTransform m = CGAffineTransformMakeScale(scale, scale);
5621
5909
  CTFontRef ct = CTFontCreateWithName((__bridge CFStringRef)name,
5622
5910
  size / scale, scale == 1 ? NULL : &m);
@@ -5727,6 +6015,8 @@ static Napi::Value ListFonts(const Napi::CallbackInfo& info) {
5727
6015
  : nil;
5728
6016
  CFArrayRef matches = NULL;
5729
6017
  if (family && family.length > 0) {
6018
+ // a family macOS would download has no faces yet (see BFontAvailable)
6019
+ if (!BFontAvailable(family)) return Napi::Array::New(env);
5730
6020
  CTFontDescriptorRef d = CTFontDescriptorCreateWithAttributes(
5731
6021
  (__bridge CFDictionaryRef)
5732
6022
  @{(__bridge id)kCTFontFamilyNameAttribute : family});
@@ -5783,6 +6073,7 @@ static Napi::Value LoadFontData(const Napi::CallbackInfo& info) {
5783
6073
  CTFontManagerRegisterFontDescriptors((__bridge CFArrayRef)@[ (__bridge id)desc ],
5784
6074
  kCTFontManagerScopeProcess, YES, NULL);
5785
6075
  (void)err;
6076
+ gFontsGeneration++; // the face answers matchFont now, not at the notification
5786
6077
  CTFontRef font = CTFontCreateWithFontDescriptor(desc, 12, NULL);
5787
6078
  CFRelease(desc);
5788
6079
  if (!font) return env.Null();
@@ -8226,11 +8517,13 @@ void InitBackend(Napi::Env env, Napi::Object exports) {
8226
8517
  BFN("ctxFillRadialGradient", CtxFillRadialGradient);
8227
8518
  BFN("ctxDrawSurface", CtxDrawSurface);
8228
8519
  BFN("ctxDrawSurfaceFaded", CtxDrawSurfaceFaded);
8520
+ BFN("ctxDrawSurfaceFiltered", CtxDrawSurfaceFiltered);
8229
8521
  BFN("ctxPutImageData", CtxPutImageData);
8230
8522
  BFN("ctxGetImageData", CtxGetImageData);
8231
8523
  BFN("surfaceToLayer", SurfaceToLayer);
8232
8524
  BFN("scrollSurface", ScrollSurface);
8233
8525
  BFN("matchFont", MatchFont);
8526
+ BFN("fontAvailable", FontAvailable);
8234
8527
  BFN("fontMetrics", FontMetrics);
8235
8528
  BFN("fontHasGlyph", FontHasGlyph);
8236
8529
  BFN("fontGlyphForCodepoint", FontGlyphForCodepoint);