@windowkit/appkit 0.34.0 → 0.35.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
@@ -627,6 +627,61 @@ native.ctxDrawSurfaceFiltered(win, card, 0, 0, 556, 300, 100, 100, 556, 300, {
627
627
  });
628
628
  ```
629
629
 
630
+ - **`native.ctxDrawFilterGraph(dst, src, graph, dx, dy, images?)`** — an SVG filter
631
+ graph (`<filter>` and its `fe*` primitives) run over `src` by Metal compute kernels,
632
+ and what it makes drawn with its corner at (`dx`, `dy`), a `graph.width` x
633
+ `graph.height` rect under the destination's transform, clip, alpha and blend mode, as
634
+ `ctxDrawSurface` draws. It is the macOS half of react-x11-components'
635
+ `docs/prd-svg-filters-gpu.md`: `src` is the source graphic, premultiplied, the filter
636
+ region's size (its top-left `width` x `height` is read), and nothing is read back.
637
+ `graph` is that document's `FilterGraph`, `{ width, height, matrix, primitives,
638
+ precision? }`: `matrix` maps user units to region pixels (what `feTurbulence` and the
639
+ lights are placed by), and each primitive is `{ kind, inputs, sub, space, params }` —
640
+ its element name in lower case, its inputs (a result's index, `'SourceGraphic'`,
641
+ `'SourceAlpha'`, or `null` for the one before), its subregion `[x, y, w, h]` in region
642
+ pixels, `'srgb'` or `'linear'`, and its numbers, with colours premultiplied sRGB in
643
+ 0–1 and lengths in region pixels: `feflood {rgba}`, `feoffset {dx, dy}`,
644
+ `fegaussianblur {sdx, sdy}`, `fedropshadow {rgba, dx, dy, sdx, sdy}`,
645
+ `fecolormatrix {matrix}` (4x5, over straight colour), `fecomponenttransfer {funcs}`
646
+ (four of `null` or `{ type: 'table' | 'discrete', tableValues }`, `{ type: 'linear',
647
+ slope, intercept }`, `{ type: 'gamma', amplitude, exponent, offset }`), `fecomposite
648
+ {op, k}`, `feblend {mode}`, `femerge`, `fetile`, `femorphology {op, rx, ry}`,
649
+ `fedisplacementmap {scale | scaleX, scaleY, xc, yc}` (a channel's index or letter; a
650
+ tainted map is the caller's to resolve, as scale 0), `feconvolvematrix {ox, oy,
651
+ kernel, divisor, bias, tx, ty, edge, preserveAlpha}` (up to 1024 entries),
652
+ `fediffuselighting` and `fespecularlighting {rgba, surfaceScale, kd, ks, exp, light}`
653
+ (`light` `{ kind: 'distant' | 'point' | 'spot', azimuth, elevation, x, y, z, px, py,
654
+ pz, exponent, cone }`, positions in region pixels), `feturbulence {bx, by, octaves,
655
+ fractal, sel, grad}` (the reference code's lattice, 514 selector entries and 4 x 514 x
656
+ 2 gradients, or a `seed` it is made from here) and `feimage {image}`, an index into
657
+ `images`, surfaces the region's size. Each primitive is one pass (two to six for a
658
+ blur) into RGBA16F textures kept between runs, each in its colour space, with a
659
+ result's texture free again after its last read; `precision: 'float'` makes them
660
+ RGBA32F, which matches react-x11-components' `runFilter` within 2 levels where half
661
+ floats lose the colour of a pixel all but transparent that a later primitive makes
662
+ opaque. The source is read where it lies, without a copy. All of a graph or none:
663
+ answers false, drawing nothing, for a primitive or a value it does not take, a region
664
+ past 16384 pixels a side, or no Metal device, so the caller runs the filter itself.
665
+ A FreeHand-sized group (`feTurbulence` of 4 octaves displacing the source) is 6.6ms
666
+ at 2198x1172 and 18ms at 4400x2340 on an M1 Pro, where `runFilter` took 319 and
667
+ 1319. The shaders compile at the first call, some 100–200ms.
668
+ - **`native.filterGraphPrimitives()`** — the primitives `ctxDrawFilterGraph` runs, by
669
+ element name in lower case (`'feturbulence'`, `'fedisplacementmap'`, …), what the
670
+ PRD's `filterGraph.primitives` is: empty where there is no Metal device or its shaders
671
+ did not compile. The first call compiles them.
672
+
673
+ ```js
674
+ native.ctxDrawFilterGraph(win, group, {
675
+ width: 2198, height: 1172, matrix: [1, 0, 0, 1, -40, -1200],
676
+ primitives: [
677
+ { kind: 'feturbulence', inputs: [], sub: [0, 0, 2198, 1172], space: 'linear',
678
+ params: { bx: 0.02, by: 0.02, octaves: 4, fractal: false, sel, grad } },
679
+ { kind: 'fedisplacementmap', inputs: ['SourceGraphic', 0], sub: [0, 0, 2198, 1172],
680
+ space: 'linear', params: { scale: 8, xc: 'R', yc: 'G' } },
681
+ ],
682
+ }, 40, 1200);
683
+ ```
684
+
630
685
  - **`native.ctxSetImageSmoothing(surface, quality)`** — how an image or a surface drawn
631
686
  scaled or turned is resampled: `'none'` (the nearest pixel), `'low'`, `'medium'` or
632
687
  `'high'`, the 2D canvas's `imageSmoothingEnabled` and `imageSmoothingQuality`. It is
@@ -921,6 +976,21 @@ process with no audio, and — only where System Audio Recording is allowed —
921
976
  taps everything and one process; `test/system-audio-threaded.js` lists and
922
977
  refuses from a worker.
923
978
 
979
+ ## Text: fonts macOS would download
980
+
981
+ macOS lists some 1,300 faces it downloads on demand, Hei, Kai and Songti among them, and
982
+ asking AppKit or CoreText for one by name, in a process with an NSApp, puts up "<app> needs
983
+ to download the font …" and holds the call until someone answers. A family list is a
984
+ browser's to write, and Chinese fallback stacks name these families as a matter of course,
985
+ so `matchFont`, `fontByPostScriptName`, `listFonts({ family })` and a pop-up's `fontFamily`
986
+ match only a family or a PostScript name of a face available now — installed, or registered
987
+ by the process — and pass over any other, as they pass over a name nobody has. Nothing is
988
+ downloaded and nothing is asked.
989
+
990
+ - **`fontAvailable(name)`** — whether a family or PostScript name, in any case, is one of
991
+ those: what the verbs above ask first. Read from CoreText's collection of available fonts,
992
+ which activates nothing, and kept until the registered fonts change.
993
+
924
994
  ## Text: at a display's scale
925
995
 
926
996
  A text verb's size is the caller's pixels, and a renderer that draws in device pixels hands
package/binding.gyp CHANGED
@@ -14,7 +14,8 @@
14
14
  "src/player.mm",
15
15
  "src/capture.mm",
16
16
  "src/systemaudio.mm",
17
- "src/displaystream.mm"
17
+ "src/displaystream.mm",
18
+ "src/filtergraph.mm"
18
19
  ],
19
20
  "include_dirs": [
20
21
  "<!@(node -p \"require('node-addon-api').include\")"
@@ -29,6 +30,7 @@
29
30
  "libraries": [
30
31
  "-framework Cocoa",
31
32
  "-framework QuartzCore",
33
+ "-framework Metal",
32
34
  "-framework Accelerate",
33
35
  "-framework CoreText",
34
36
  "-framework CoreGraphics",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@windowkit/appkit",
3
- "version": "0.34.0",
3
+ "version": "0.35.0",
4
4
  "description": "Retained-mode AppKit backend for Node.js: Core Animation (CALayer) layer trees, CoreText layout and drawing, IOSurface presentation, NSMenu, and native control bezels — the macOS half of react-x11.",
5
5
  "author": "Andrey Sidorov <andrey.sidorov@gmail.com>",
6
6
  "license": "MIT",
@@ -43,7 +43,7 @@
43
43
  "install": "node scripts/install.js",
44
44
  "build": "node-gyp rebuild",
45
45
  "demo": "node demo/demo.js",
46
- "test": "node test/app-lifecycle.js && node test/animation.js && node test/layer-transform.js && node test/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/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/filter-graph.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/addon.mm CHANGED
@@ -1874,6 +1874,8 @@ void InitCapture(Napi::Env env, Napi::Object exports);
1874
1874
  void InitSystemAudio(Napi::Env env, Napi::Object exports);
1875
1875
  // src/displaystream.mm — a display or a window as ScreenCaptureKit's stream.
1876
1876
  void InitDisplayStream(Napi::Env env, Napi::Object exports);
1877
+ // filtergraph.mm: ctxDrawFilterGraph, an SVG filter graph run by Metal.
1878
+ void InitFilterGraph(Napi::Env env, Napi::Object exports);
1877
1879
 
1878
1880
  static Napi::Object Init(Napi::Env env, Napi::Object exports) {
1879
1881
  #define FN(js, fn) exports.Set(js, Napi::Function::New(env, fn))
@@ -1925,6 +1927,7 @@ static Napi::Object Init(Napi::Env env, Napi::Object exports) {
1925
1927
  InitCapture(env, exports);
1926
1928
  InitSystemAudio(env, exports);
1927
1929
  InitDisplayStream(env, exports);
1930
+ InitFilterGraph(env, exports);
1928
1931
  return exports;
1929
1932
  }
1930
1933
 
package/src/backend.mm CHANGED
@@ -1774,6 +1774,27 @@ bool CALSurfaceBitmap(Napi::Value v, CALSurfaceBits* out) {
1774
1774
  return true;
1775
1775
  }
1776
1776
 
1777
+ // A surface's parts, for filtergraph.mm's ctxDrawFilterGraph: its context,
1778
+ // its bitmap and the IOSurface under it, if any. False, with the error
1779
+ // pending, where the handle is not a live surface.
1780
+ struct CALSurfaceView {
1781
+ CGContextRef ctx;
1782
+ IOSurfaceRef iosurface;
1783
+ uint8_t* data;
1784
+ size_t width, height, bytesPerRow;
1785
+ };
1786
+ bool CALSurfaceViewOf(Napi::Value v, CALSurfaceView* out) {
1787
+ CALSurface* s = SurfaceFrom(v);
1788
+ if (!s) return false;
1789
+ out->ctx = s->ctx;
1790
+ out->iosurface = s->iosurface;
1791
+ out->data = (uint8_t*)CGBitmapContextGetData(s->ctx);
1792
+ out->width = s->width;
1793
+ out->height = s->height;
1794
+ out->bytesPerRow = CGBitmapContextGetBytesPerRow(s->ctx);
1795
+ return true;
1796
+ }
1797
+
1777
1798
  // For the fire-and-forget drawing verbs: the context to draw into, or a
1778
1799
  // scratch bitmap when the surface is released (the error is already
1779
1800
  // pending; the stroke lands nowhere anyone looks).
@@ -2505,11 +2526,14 @@ static PopUpSpec ParsePopUpSpec(Napi::Object o) {
2505
2526
  return s;
2506
2527
  }
2507
2528
 
2529
+ static bool BFontAvailable(NSString* name);
2530
+
2508
2531
  // The family asked for when the system has it — a face it matched under
2509
- // another name is not it — and the menu font at that size otherwise.
2532
+ // another name is not it, and one it would download is not had (see
2533
+ // BFontAvailable) — and the menu font at that size otherwise.
2510
2534
  static NSFont* PopUpFont(NSString* family, double size) {
2511
2535
  CGFloat sz = size > 0 ? size : [NSFont systemFontSize];
2512
- if (family.length) {
2536
+ if (BFontAvailable(family)) {
2513
2537
  NSFontDescriptor* d = [NSFontDescriptor
2514
2538
  fontDescriptorWithFontAttributes:@{NSFontFamilyAttribute : family}];
2515
2539
  NSFont* f = [NSFont fontWithDescriptor:d size:sz];
@@ -5168,6 +5192,86 @@ static CTFontRef BAtScale(CTFontRef font, double scale) {
5168
5192
  return scaled;
5169
5193
  }
5170
5194
 
5195
+ // --- what is installed -----------------------------------------------------
5196
+ //
5197
+ // macOS lists some 1,300 faces it will download the first time an app asks
5198
+ // for one — Hei, Kai, Songti and the rest of the CJK sets among them — and
5199
+ // asking by name is enough: `fontWithDescriptor:`, `fontWithName:` and
5200
+ // CTFontCreateWithName of such a family, in a process with an NSApp, put up
5201
+ // "<app> needs to download the font …" and block the call until it is
5202
+ // answered. A browser's font stacks name these families as a matter of
5203
+ // course ("PingFang SC", "Hei", …), so every page with a Chinese fallback
5204
+ // stopped its process on a prompt per font. So a name is matched only where
5205
+ // it is a family or a PostScript name of a face this process can use now —
5206
+ // installed, or registered by the process — read from CoreText's collection
5207
+ // of available fonts, which lists no downloadable face and activates
5208
+ // nothing. The names are kept until the registered fonts change.
5209
+
5210
+ static std::atomic<uint64_t> gFontsGeneration{1};
5211
+
5212
+ static void BFontsChanged(CFNotificationCenterRef, void*, CFStringRef,
5213
+ const void*, CFDictionaryRef) {
5214
+ gFontsGeneration++;
5215
+ }
5216
+
5217
+ /** Whether `name` (any case) is a family or a PostScript name of a face
5218
+ * available without a download. Names CoreText keeps hidden (".SF NS")
5219
+ * pass: no download is ever one of them. */
5220
+ static bool BFontAvailable(NSString* name) {
5221
+ if (name.length == 0) return false;
5222
+ if ([name hasPrefix:@"."]) return true;
5223
+ static std::mutex lock;
5224
+ static NSSet<NSString*>* names = nil;
5225
+ static uint64_t built = 0;
5226
+ static dispatch_once_t once;
5227
+ dispatch_once(&once, ^{
5228
+ CFNotificationCenterAddObserver(
5229
+ CFNotificationCenterGetLocalCenter(), NULL, BFontsChanged,
5230
+ kCTFontManagerRegisteredFontsChangedNotification, NULL,
5231
+ CFNotificationSuspensionBehaviorDeliverImmediately);
5232
+ });
5233
+ NSSet<NSString*>* now = nil;
5234
+ {
5235
+ std::lock_guard<std::mutex> guard(lock);
5236
+ const uint64_t generation = gFontsGeneration.load();
5237
+ if (!names || built != generation) {
5238
+ NSMutableSet<NSString*>* all = [NSMutableSet set];
5239
+ CTFontCollectionRef available =
5240
+ CTFontCollectionCreateFromAvailableFonts(NULL);
5241
+ CFArrayRef faces =
5242
+ available ? CTFontCollectionCreateMatchingFontDescriptors(available)
5243
+ : NULL;
5244
+ const CFIndex count = faces ? CFArrayGetCount(faces) : 0;
5245
+ for (CFIndex i = 0; i < count; i++) {
5246
+ CTFontDescriptorRef d =
5247
+ (CTFontDescriptorRef)CFArrayGetValueAtIndex(faces, i);
5248
+ for (CFStringRef attribute :
5249
+ {kCTFontFamilyNameAttribute, kCTFontNameAttribute}) {
5250
+ CFStringRef value =
5251
+ (CFStringRef)CTFontDescriptorCopyAttribute(d, attribute);
5252
+ if (!value) continue;
5253
+ [all addObject:((__bridge NSString*)value).lowercaseString];
5254
+ CFRelease(value);
5255
+ }
5256
+ }
5257
+ if (faces) CFRelease(faces);
5258
+ if (available) CFRelease(available);
5259
+ names = [all copy];
5260
+ built = generation;
5261
+ }
5262
+ now = names;
5263
+ }
5264
+ return [now containsObject:name.lowercaseString];
5265
+ }
5266
+
5267
+ // fontAvailable(name) -> whether a family or PostScript name answers without
5268
+ // macOS downloading a font: what matchFont, fontByPostScriptName and
5269
+ // listFonts ask before they match one.
5270
+ static Napi::Value FontAvailable(const Napi::CallbackInfo& info) {
5271
+ return Napi::Boolean::New(
5272
+ info.Env(), info[0].IsString() && BFontAvailable(BToNSString(info[0])));
5273
+ }
5274
+
5171
5275
  // matchFont({ families: [..], size, weight (100-900), italic, scale? })
5172
5276
  // -> font handle
5173
5277
  // `size` is in the caller's pixels; `scale`, the display's, makes the font
@@ -5192,6 +5296,10 @@ static NSFont* ResolveFamily(NSString* family, double size, double weight,
5192
5296
  font = [NSFont fontWithName:@"Times New Roman" size:size];
5193
5297
  } else if ([lower isEqualToString:@"cursive"]) {
5194
5298
  font = [NSFont fontWithName:@"Snell Roundhand" size:size];
5299
+ } else if (!BFontAvailable(family)) {
5300
+ // not here, or here only for a download (see BFontAvailable): not found,
5301
+ // and the next family in the list gets its turn
5302
+ return nil;
5195
5303
  } else {
5196
5304
  // A named family. Build a descriptor so weight/width participate in
5197
5305
  // matching; verify the match really is this family (CoreText silently
@@ -5817,6 +5925,7 @@ static Napi::Value FontByPostScriptName(const Napi::CallbackInfo& info) {
5817
5925
  NSString* name = BToNSString(info[0]);
5818
5926
  double size = info[1].As<Napi::Number>().DoubleValue();
5819
5927
  const double scale = BScaleOf(info[2]);
5928
+ if (!BFontAvailable(name)) return env.Null(); // nor a download's
5820
5929
  const CGAffineTransform m = CGAffineTransformMakeScale(scale, scale);
5821
5930
  CTFontRef ct = CTFontCreateWithName((__bridge CFStringRef)name,
5822
5931
  size / scale, scale == 1 ? NULL : &m);
@@ -5927,6 +6036,8 @@ static Napi::Value ListFonts(const Napi::CallbackInfo& info) {
5927
6036
  : nil;
5928
6037
  CFArrayRef matches = NULL;
5929
6038
  if (family && family.length > 0) {
6039
+ // a family macOS would download has no faces yet (see BFontAvailable)
6040
+ if (!BFontAvailable(family)) return Napi::Array::New(env);
5930
6041
  CTFontDescriptorRef d = CTFontDescriptorCreateWithAttributes(
5931
6042
  (__bridge CFDictionaryRef)
5932
6043
  @{(__bridge id)kCTFontFamilyNameAttribute : family});
@@ -5983,6 +6094,7 @@ static Napi::Value LoadFontData(const Napi::CallbackInfo& info) {
5983
6094
  CTFontManagerRegisterFontDescriptors((__bridge CFArrayRef)@[ (__bridge id)desc ],
5984
6095
  kCTFontManagerScopeProcess, YES, NULL);
5985
6096
  (void)err;
6097
+ gFontsGeneration++; // the face answers matchFont now, not at the notification
5986
6098
  CTFontRef font = CTFontCreateWithFontDescriptor(desc, 12, NULL);
5987
6099
  CFRelease(desc);
5988
6100
  if (!font) return env.Null();
@@ -8432,6 +8544,7 @@ void InitBackend(Napi::Env env, Napi::Object exports) {
8432
8544
  BFN("surfaceToLayer", SurfaceToLayer);
8433
8545
  BFN("scrollSurface", ScrollSurface);
8434
8546
  BFN("matchFont", MatchFont);
8547
+ BFN("fontAvailable", FontAvailable);
8435
8548
  BFN("fontMetrics", FontMetrics);
8436
8549
  BFN("fontHasGlyph", FontHasGlyph);
8437
8550
  BFN("fontGlyphForCodepoint", FontGlyphForCodepoint);