@windowkit/appkit 0.33.0 → 0.34.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
@@ -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
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.0",
3
+ "version": "0.34.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/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/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/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>
@@ -913,9 +915,14 @@ static char kDelegateKey;
913
915
  - (BOOL)acceptsFirstResponder { return YES; }
914
916
  - (BOOL)isFlipped { return YES; }
915
917
  - (void)keyDown:(NSEvent*)event { (void)event; } // no beep; JS observes keys
918
+ // AppKit asks again at every change of the view's geometry, which is every
919
+ // step of a live resize. An area of `NSTrackingInVisibleRect` follows the
920
+ // visible rect by itself, so it is made once: made again, each step crossed
921
+ // the pointer out of the view and back in, which a window answers as a leave
922
+ // and an enter where the pointer never moved.
916
923
  - (void)updateTrackingAreas {
917
924
  [super updateTrackingAreas];
918
- if (tracking_) [self removeTrackingArea:tracking_];
925
+ if (tracking_) return;
919
926
  tracking_ = [[NSTrackingArea alloc]
920
927
  initWithRect:NSZeroRect
921
928
  options:(NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved |
@@ -4741,6 +4748,204 @@ static Napi::Value CtxDrawSurfaceFaded(const Napi::CallbackInfo& info) {
4741
4748
  return info.Env().Undefined();
4742
4749
  }
4743
4750
 
4751
+ // drawSurfaceFiltered(dst, src, sx, sy, sw, sh, dx, dy, dw, dh, filter)
4752
+ //
4753
+ // drawSurface through a CSS filter list: `filter` is `{ matrices, alpha,
4754
+ // blur }` — the colour functions in the order written, each twelve numbers,
4755
+ // three rows of red, green and blue weights and an offset over straight
4756
+ // colour in 0–1, clamped to 0–1 before the next; what alpha is multiplied
4757
+ // by; and the standard deviation of a Gaussian blur in SOURCE pixels, 0 for
4758
+ // none. react-x11's src/backend/filter.js is the model, and the caller
4759
+ // converts a blur given in destination units.
4760
+ //
4761
+ // Run by Accelerate's vImage over the source rect's premultiplied pixels,
4762
+ // on the calling thread. A colour function is a 4x4 integer matrix over
4763
+ // premultiplied colour, its offset carried by alpha — exact, since a matrix
4764
+ // over straight colour that leaves alpha as it is is a linear map on
4765
+ // premultiplied colour — and the clamp to 0–1 after it is a clip of each
4766
+ // channel to its pixel's alpha. The blur is three box blurs that come to the
4767
+ // Gaussian (Kovesi, "Fast almost-Gaussian filtering", 2010), as filter.js's
4768
+ // is, with nothing past the source rect, and the drawing reaches three
4769
+ // deviations past the destination rect, scaled as the rect is. The colour
4770
+ // functions run after it, where they commute with it but for the clamps.
4771
+ //
4772
+ // The result is drawn as drawSurface draws, under the destination's state:
4773
+ // its CTM, clip, global alpha and blend mode. On the CPU in JavaScript the
4774
+ // same draw read the pixels back, ran the matrices or the blur over them a
4775
+ // pixel at a time and wrote them into a bitmap of their own: 15 ms for a
4776
+ // 1281x961 surface on an M1 Pro, where this is 2.6 for a colour function and
4777
+ // 3.9 for a blur. Core Image was measured too, and came to 4.2 and 7.3: the
4778
+ // surfaces here are bitmaps in main memory, which it uploads and reads back
4779
+ // at every draw. Answers true where it drew, false where there was nothing
4780
+ // to draw.
4781
+ static Napi::Value CtxDrawSurfaceFiltered(const Napi::CallbackInfo& info) {
4782
+ Napi::Env env = info.Env();
4783
+ CALSurface* dst = SurfaceFrom(info[0]);
4784
+ CALSurface* src = SurfaceFrom(info[1]);
4785
+ if (!dst || !src || info.Length() < 11 || !info[10].IsObject()) {
4786
+ return Napi::Boolean::New(env, false);
4787
+ }
4788
+ double sx = info[2].As<Napi::Number>().DoubleValue();
4789
+ double sy = info[3].As<Napi::Number>().DoubleValue();
4790
+ double sw = info[4].As<Napi::Number>().DoubleValue();
4791
+ double sh = info[5].As<Napi::Number>().DoubleValue();
4792
+ double dx = info[6].As<Napi::Number>().DoubleValue();
4793
+ double dy = info[7].As<Napi::Number>().DoubleValue();
4794
+ double dw = info[8].As<Napi::Number>().DoubleValue();
4795
+ double dh = info[9].As<Napi::Number>().DoubleValue();
4796
+ Napi::Object spec = info[10].As<Napi::Object>();
4797
+ auto number = [&](const char* key, double fallback) {
4798
+ Napi::Value v = spec.Get(key);
4799
+ return v.IsNumber() ? v.As<Napi::Number>().DoubleValue() : fallback;
4800
+ };
4801
+ double alpha = number("alpha", 1);
4802
+ double blur = number("blur", 0);
4803
+ std::vector<std::array<double, 12>> matrices;
4804
+ Napi::Value list = spec.Get("matrices");
4805
+ if (list.IsObject()) {
4806
+ Napi::Object rows = list.As<Napi::Object>();
4807
+ uint32_t count = rows.Get("length").IsNumber()
4808
+ ? rows.Get("length").As<Napi::Number>().Uint32Value()
4809
+ : 0;
4810
+ for (uint32_t i = 0; i < count; i++) {
4811
+ Napi::Value m = rows.Get(i);
4812
+ if (!m.IsObject()) continue;
4813
+ Napi::Object row = m.As<Napi::Object>();
4814
+ std::array<double, 12> v{};
4815
+ for (uint32_t k = 0; k < 12; k++) {
4816
+ Napi::Value x = row.Get(k);
4817
+ v[k] = x.IsNumber() ? x.As<Napi::Number>().DoubleValue() : 0;
4818
+ }
4819
+ matrices.push_back(v);
4820
+ }
4821
+ }
4822
+ if (!(sw > 0 && sh > 0) || dw == 0 || dh == 0 || !std::isfinite(sx) ||
4823
+ !std::isfinite(sy) || !std::isfinite(sw) || !std::isfinite(sh) ||
4824
+ !std::isfinite(alpha) || !std::isfinite(blur)) {
4825
+ return Napi::Boolean::New(env, false);
4826
+ }
4827
+ alpha = std::min(1.0, std::max(0.0, alpha));
4828
+ if (!(blur > 0)) blur = 0;
4829
+
4830
+ // the source rect on the pixel grid, and the blur's reach round it
4831
+ long x0 = (long)floor(sx);
4832
+ long y0 = (long)floor(sy);
4833
+ long w = (long)ceil(sx + sw) - x0;
4834
+ long h = (long)ceil(sy + sh) - y0;
4835
+ long margin = blur > 0 ? (long)ceil(3 * blur) : 0;
4836
+ long W = w + 2 * margin;
4837
+ long H = h + 2 * margin;
4838
+ if (W <= 0 || H <= 0 || W > 32768 || H > 32768) {
4839
+ return Napi::Boolean::New(env, false);
4840
+ }
4841
+ CGColorSpaceRef cs = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
4842
+ CGContextRef work = CGBitmapContextCreate(
4843
+ NULL, W, H, 8, 0, cs,
4844
+ kCGImageAlphaPremultipliedFirst | (CGBitmapInfo)kCGBitmapByteOrder32Host);
4845
+ CGColorSpaceRelease(cs);
4846
+ if (!work) return Napi::Boolean::New(env, false);
4847
+ uint8_t* base = (uint8_t*)CGBitmapContextGetData(work);
4848
+ size_t stride = CGBitmapContextGetBytesPerRow(work);
4849
+ memset(base, 0, stride * H);
4850
+ // what of the rect is in the source: the rest is nothing
4851
+ if (src->iosurface) IOSurfaceLock(src->iosurface, kIOSurfaceLockReadOnly, nullptr);
4852
+ const uint8_t* from = (const uint8_t*)CGBitmapContextGetData(src->ctx);
4853
+ size_t fromStride = CGBitmapContextGetBytesPerRow(src->ctx);
4854
+ long left = std::max(0L, x0);
4855
+ long right = std::min((long)src->width, x0 + w);
4856
+ if (from && right > left) {
4857
+ for (long y = 0; y < h; y++) {
4858
+ long row = y0 + y;
4859
+ if (row < 0 || row >= (long)src->height) continue;
4860
+ memcpy(base + (y + margin) * stride + (left - x0 + margin) * 4,
4861
+ from + row * fromStride + left * 4, (right - left) * 4);
4862
+ }
4863
+ }
4864
+ if (src->iosurface) IOSurfaceUnlock(src->iosurface, kIOSurfaceLockReadOnly, nullptr);
4865
+
4866
+ vImage_Buffer buf = {base, (vImagePixelCount)H, (vImagePixelCount)W, stride};
4867
+ if (blur > 0) {
4868
+ // three box blurs whose widths come to the Gaussian, as filter.js's
4869
+ // boxRadii works them out
4870
+ double ideal = sqrt(12 * blur * blur / 3 + 1);
4871
+ long lower = (long)floor(ideal);
4872
+ if (lower % 2 == 0) lower -= 1;
4873
+ long upper = lower + 2;
4874
+ long m = lround((12 * blur * blur - 3.0 * lower * lower - 12.0 * lower - 9) /
4875
+ (-4.0 * lower - 4));
4876
+ vImage_Buffer other = buf;
4877
+ other.data = malloc(stride * H);
4878
+ Pixel_8888 clear = {0, 0, 0, 0};
4879
+ size_t scratch = (size_t)vImageBoxConvolve_ARGB8888(
4880
+ &buf, &other, NULL, 0, 0, (uint32_t)upper, (uint32_t)upper, clear,
4881
+ kvImageGetTempBufferSize | kvImageBackgroundColorFill);
4882
+ void* temp = scratch > 0 ? malloc(scratch) : nullptr;
4883
+ vImage_Buffer* a = &buf;
4884
+ vImage_Buffer* b = &other;
4885
+ for (long i = 0; other.data && i < 3; i++) {
4886
+ uint32_t d = (uint32_t)(i < m ? lower : upper);
4887
+ if (d < 3) continue;
4888
+ vImageBoxConvolve_ARGB8888(a, b, temp, 0, 0, d, d, clear,
4889
+ kvImageBackgroundColorFill);
4890
+ std::swap(a, b);
4891
+ }
4892
+ if (a != &buf) memcpy(buf.data, a->data, stride * H);
4893
+ free(other.data);
4894
+ free(temp);
4895
+ }
4896
+ // vImage numbers a pixel's channels as they are in memory: blue, green,
4897
+ // red, alpha in a host-order premultiplied-first bitmap. A matrix entry
4898
+ // M[in * 4 + out] weighs channel `in` into channel `out`, over 256.
4899
+ const int32_t D = 256;
4900
+ enum { B = 0, G = 1, R = 2, A = 3 };
4901
+ auto weigh = [&](int16_t* M, int in, int out, double v) {
4902
+ M[in * 4 + out] = (int16_t)std::max(-32768.0, std::min(32767.0, round(v * D)));
4903
+ };
4904
+ for (size_t i = 0; i < matrices.size(); i++) {
4905
+ const auto& m = matrices[i];
4906
+ double fade = i + 1 == matrices.size() ? alpha : 1;
4907
+ int16_t M[16] = {0};
4908
+ const int outs[3] = {R, G, B};
4909
+ for (int r = 0; r < 3; r++) {
4910
+ weigh(M, R, outs[r], m[r * 4] * fade);
4911
+ weigh(M, G, outs[r], m[r * 4 + 1] * fade);
4912
+ weigh(M, B, outs[r], m[r * 4 + 2] * fade);
4913
+ weigh(M, A, outs[r], m[r * 4 + 3] * fade);
4914
+ }
4915
+ weigh(M, A, A, fade);
4916
+ vImageMatrixMultiply_ARGB8888(&buf, &buf, M, D, NULL, NULL, kvImageNoFlags);
4917
+ // each function's result in 0–1 of straight colour: no channel past
4918
+ // its alpha (the alpha last, as RGBA and BGRA both have it)
4919
+ vImageClipToAlpha_RGBA8888(&buf, &buf, kvImageNoFlags);
4920
+ }
4921
+ if (matrices.empty() && alpha < 1) {
4922
+ int16_t M[16] = {0};
4923
+ for (int k = 0; k < 4; k++) weigh(M, k, k, alpha);
4924
+ vImageMatrixMultiply_ARGB8888(&buf, &buf, M, D, NULL, NULL, kvImageNoFlags);
4925
+ }
4926
+
4927
+ CGImageRef done = CGBitmapContextCreateImage(work);
4928
+ CGContextRelease(work);
4929
+ if (!done) return Napi::Boolean::New(env, false);
4930
+ // where the pixels land: the destination rect, moved for the source
4931
+ // rect's grid and grown by the blur's reach, scaled as the rect is
4932
+ double kx = dw / sw;
4933
+ double ky = dh / sh;
4934
+ double ox = dx + (x0 - margin - sx) * kx;
4935
+ double oy = dy + (y0 - margin - sy) * ky;
4936
+ double ow = W * kx;
4937
+ double oh = H * ky;
4938
+ CGContextSaveGState(dst->ctx);
4939
+ // the base CTM is flipped; flip back around the destination rect so the
4940
+ // image lands upright
4941
+ CGContextTranslateCTM(dst->ctx, ox, oy + oh);
4942
+ CGContextScaleCTM(dst->ctx, 1, -1);
4943
+ CGContextDrawImage(dst->ctx, CGRectMake(0, 0, ow, oh), done);
4944
+ CGContextRestoreGState(dst->ctx);
4945
+ CGImageRelease(done);
4946
+ return Napi::Boolean::New(env, true);
4947
+ }
4948
+
4744
4949
  // putImageData(surface, buffer RGBA straight, w, h, dx, dy) — writes pixels
4745
4950
  // directly, transform- and clip-free, per the canvas contract.
4746
4951
  static Napi::Value CtxPutImageData(const Napi::CallbackInfo& info) {
@@ -8221,6 +8426,7 @@ void InitBackend(Napi::Env env, Napi::Object exports) {
8221
8426
  BFN("ctxFillRadialGradient", CtxFillRadialGradient);
8222
8427
  BFN("ctxDrawSurface", CtxDrawSurface);
8223
8428
  BFN("ctxDrawSurfaceFaded", CtxDrawSurfaceFaded);
8429
+ BFN("ctxDrawSurfaceFiltered", CtxDrawSurfaceFiltered);
8224
8430
  BFN("ctxPutImageData", CtxPutImageData);
8225
8431
  BFN("ctxGetImageData", CtxGetImageData);
8226
8432
  BFN("surfaceToLayer", SurfaceToLayer);