@windowkit/appkit 0.17.0 → 0.18.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
@@ -506,6 +506,26 @@ native.ctxDrawSurface(win, grid, 0, 0, 2000, 1620, 40, 30, 2000, 1620);
506
506
  native.ctxSetBlendMode(win, 'source-over');
507
507
  ```
508
508
 
509
+ - **`native.ctxDrawSurfaceFaded(dst, src, sx, sy, sw, sh, dx, dy, dw, dh, alpha)`** —
510
+ `ctxDrawSurface` under an alpha below 1, which the caller passes again because it is
511
+ the alpha it set with `ctxSetGlobalAlpha` and CoreGraphics keeps no getter for it.
512
+ CoreGraphics draws an image under an alpha below 1 at some fifteen times what the same
513
+ draw costs at 1, and composites a transparency layer the same way, so a group faded on
514
+ a surface of its own — CSS `opacity`, a fade — cost more than drawing again what was
515
+ on it. This scales the source rect's premultiplied pixels by the alpha into a bitmap
516
+ of their own and draws that at 1: the same colours within a unit a channel, and a
517
+ 556x300 surface in 0.25ms where the alpha path takes 1.24ms on an M1 Pro. The
518
+ destination keeps the alpha it was set to. A source rect off the pixel grid or past
519
+ the source, an IOSurface-backed source, a surface drawn onto itself and an alpha of 1
520
+ or 0 are drawn as `ctxDrawSurface` draws them, under the alpha already set — so a
521
+ caller can call it for every draw under an alpha, and feature-detect the verb to know
522
+ whether a faded surface is cheap here.
523
+
524
+ ```js
525
+ native.ctxSetGlobalAlpha(win, 0.6);
526
+ native.ctxDrawSurfaceFaded(win, card, 0, 0, 556, 300, 100, 100, 556, 300, 0.6);
527
+ ```
528
+
509
529
  ## Text: letter spacing and OpenType features
510
530
 
511
531
  The text verbs a renderer lays paragraphs out and shapes glyph runs with —
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@windowkit/appkit",
3
- "version": "0.17.0",
3
+ "version": "0.18.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/round-rect-xy.js && node test/control-bezels.js && node test/text-features.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/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/surface-faded.js && node test/round-rect-xy.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/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/activation-policy.js"
47
47
  },
48
48
  "dependencies": {
49
49
  "node-addon-api": "^8.3.0"
Binary file
package/src/backend.mm CHANGED
@@ -4094,6 +4094,80 @@ static Napi::Value CtxDrawSurface(const Napi::CallbackInfo& info) {
4094
4094
  return info.Env().Undefined();
4095
4095
  }
4096
4096
 
4097
+ // drawSurfaceFaded(dst, src, sx, sy, sw, sh, dx, dy, dw, dh, alpha)
4098
+ //
4099
+ // drawSurface at `alpha` — the alpha the caller set with ctxSetGlobalAlpha,
4100
+ // passed again because CoreGraphics keeps no getter for it. CoreGraphics
4101
+ // draws an image under an alpha below 1 at some fifteen times what the same
4102
+ // draw costs at 1 — a 556x300 surface, 1.3ms against 0.09 on an M1 Pro — and
4103
+ // composites a transparency layer the same way, so a group faded on a
4104
+ // surface (CSS opacity, a fade) cost more than drawing what was on it again.
4105
+ // The source rect's premultiplied pixels scaled by the alpha into a bitmap
4106
+ // of their own, and that drawn at 1, come to the same colours within a unit
4107
+ // for 0.25ms. A rect off the pixel grid or past the source, an IOSurface the
4108
+ // CPU would have to lock, a surface onto itself and an alpha of 1 or 0 are
4109
+ // drawn as drawSurface draws them, under the alpha already set.
4110
+ static Napi::Value CtxDrawSurfaceFaded(const Napi::CallbackInfo& info) {
4111
+ CALSurface* dst = SurfaceFrom(info[0]);
4112
+ if (!dst) return info.Env().Undefined();
4113
+ CALSurface* src = SurfaceFrom(info[1]);
4114
+ if (!src) return info.Env().Undefined();
4115
+ double sx = info[2].As<Napi::Number>().DoubleValue();
4116
+ double sy = info[3].As<Napi::Number>().DoubleValue();
4117
+ double sw = info[4].As<Napi::Number>().DoubleValue();
4118
+ double sh = info[5].As<Napi::Number>().DoubleValue();
4119
+ double dx = info[6].As<Napi::Number>().DoubleValue();
4120
+ double dy = info[7].As<Napi::Number>().DoubleValue();
4121
+ double dw = info[8].As<Napi::Number>().DoubleValue();
4122
+ double dh = info[9].As<Napi::Number>().DoubleValue();
4123
+ double alpha = info[10].As<Napi::Number>().DoubleValue();
4124
+ bool rows = sx == floor(sx) && sy == floor(sy) && sw == floor(sw) &&
4125
+ sh == floor(sh) && sx >= 0 && sy >= 0 && sw >= 1 && sh >= 1 &&
4126
+ sx + sw <= (double)src->width && sy + sh <= (double)src->height;
4127
+ if (!(alpha > 0 && alpha < 1) || !rows || src->iosurface || src == dst) {
4128
+ return CtxDrawSurface(info);
4129
+ }
4130
+ size_t w = (size_t)sw;
4131
+ size_t h = (size_t)sh;
4132
+ CGColorSpaceRef cs = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
4133
+ CGContextRef faded = CGBitmapContextCreate(
4134
+ NULL, w, h, 8, 0, cs,
4135
+ kCGImageAlphaPremultipliedFirst | (CGBitmapInfo)kCGBitmapByteOrder32Host);
4136
+ CGColorSpaceRelease(cs);
4137
+ const uint8_t* from = (const uint8_t*)CGBitmapContextGetData(src->ctx);
4138
+ uint8_t* to = faded ? (uint8_t*)CGBitmapContextGetData(faded) : nullptr;
4139
+ if (!from || !to) {
4140
+ if (faded) CGContextRelease(faded);
4141
+ return CtxDrawSurface(info);
4142
+ }
4143
+ size_t fromStride = CGBitmapContextGetBytesPerRow(src->ctx);
4144
+ size_t toStride = CGBitmapContextGetBytesPerRow(faded);
4145
+ // premultiplied, so every channel scales with the alpha, whatever order
4146
+ // the host keeps them in: c * a / 255, rounded, in shifts
4147
+ const unsigned a = (unsigned)(alpha * 255 + 0.5);
4148
+ for (size_t y = 0; y < h; y++) {
4149
+ const uint8_t* row = from + ((size_t)sy + y) * fromStride + (size_t)sx * 4;
4150
+ uint8_t* out = to + y * toStride;
4151
+ for (size_t k = 0; k < w * 4; k++) {
4152
+ unsigned t = row[k] * a + 128;
4153
+ out[k] = (uint8_t)((t + (t >> 8)) >> 8);
4154
+ }
4155
+ }
4156
+ CGImageRef image = CGBitmapContextCreateImage(faded);
4157
+ CGContextRelease(faded);
4158
+ if (!image) return CtxDrawSurface(info);
4159
+ CGContextSaveGState(dst->ctx);
4160
+ CGContextSetAlpha(dst->ctx, 1);
4161
+ // the base CTM is flipped; flip back around the destination rect so the
4162
+ // image lands upright
4163
+ CGContextTranslateCTM(dst->ctx, dx, dy + dh);
4164
+ CGContextScaleCTM(dst->ctx, 1, -1);
4165
+ CGContextDrawImage(dst->ctx, CGRectMake(0, 0, dw, dh), image);
4166
+ CGContextRestoreGState(dst->ctx);
4167
+ CGImageRelease(image);
4168
+ return info.Env().Undefined();
4169
+ }
4170
+
4097
4171
  // putImageData(surface, buffer RGBA straight, w, h, dx, dy) — writes pixels
4098
4172
  // directly, transform- and clip-free, per the canvas contract.
4099
4173
  static Napi::Value CtxPutImageData(const Napi::CallbackInfo& info) {
@@ -4774,9 +4848,10 @@ static double CssWeightOfCTFont(CTFontRef ct) {
4774
4848
 
4775
4849
  // fontFromData(buffer) -> { cg: External<CGFont>, familyName,
4776
4850
  // postScriptName, weight, italic }. The CGFont is the process's own handle
4777
- // to the face — no registry round trip, so a face CoreText refuses to
4778
- // register (in-memory data) still renders. Registration is attempted as a
4779
- // best effort so descriptor matching elsewhere can also find it.
4851
+ // to the face — no registry round trip. It reads the face and installs
4852
+ // nothing: the face is never registered with CoreText, so matchFont,
4853
+ // fontByPostScriptName and listFonts go on answering exactly what they did
4854
+ // before the bytes were read (windowkit/appkit#92).
4780
4855
  static Napi::Value FontFromData(const Napi::CallbackInfo& info) {
4781
4856
  Napi::Env env = info.Env();
4782
4857
  Napi::Buffer<uint8_t> buf = info[0].As<Napi::Buffer<uint8_t>>();
@@ -4786,7 +4861,6 @@ static Napi::Value FontFromData(const Napi::CallbackInfo& info) {
4786
4861
  CGFontRef cg = provider ? CGFontCreateWithDataProvider(provider) : NULL;
4787
4862
  if (provider) CGDataProviderRelease(provider);
4788
4863
  if (!cg) return env.Null();
4789
- CTFontManagerRegisterGraphicsFont(cg, NULL); // best effort
4790
4864
  CTFontRef ct = CTFontCreateWithGraphicsFont(cg, 12, NULL, NULL);
4791
4865
  Napi::Object r = Napi::Object::New(env);
4792
4866
  r.Set("cg", Napi::External<void>::New(env, (void*)cg, [](Napi::Env, void* d) {
@@ -7203,6 +7277,7 @@ void InitBackend(Napi::Env env, Napi::Object exports) {
7203
7277
  BFN("ctxFillRects", CtxFillRects);
7204
7278
  BFN("ctxFillLinearGradient", CtxFillLinearGradient);
7205
7279
  BFN("ctxDrawSurface", CtxDrawSurface);
7280
+ BFN("ctxDrawSurfaceFaded", CtxDrawSurfaceFaded);
7206
7281
  BFN("ctxPutImageData", CtxPutImageData);
7207
7282
  BFN("ctxGetImageData", CtxGetImageData);
7208
7283
  BFN("surfaceToLayer", SurfaceToLayer);
@@ -31,10 +31,12 @@
31
31
  // which is what the framework requires for a response that launched the
32
32
  // app (a click on a banner while the app was not running) to be delivered
33
33
  // at all. Its methods carry no thread guarantee, so a response crosses to
34
- // node's loop through a thread-safe function and is then emitted through
35
- // the same backend callback every other event takes; whatever arrives
36
- // before setBackendEventCallback() is held and replayed, in order, at the
37
- // start of the first pump2() with a listener.
34
+ // node's loop through a thread-safe function — the main thread's
35
+ // environment's, made the once, since pump mode delivers on the main thread
36
+ // and nowhere else — and is then emitted through the same backend callback
37
+ // every other event takes; whatever arrives before setBackendEventCallback()
38
+ // is held and replayed, in order, at the start of the first pump2() with a
39
+ // listener.
38
40
  //
39
41
  // Categories are handed to the system as a whole set, and the system keeps
40
42
  // none for an app it has not yet authorized — notificationCategories reads
@@ -57,6 +59,10 @@
57
59
  #import <Cocoa/Cocoa.h>
58
60
  #import <UserNotifications/UserNotifications.h>
59
61
 
62
+ #include <pthread.h>
63
+
64
+ #include <atomic>
65
+ #include <mutex>
60
66
  #include <string>
61
67
  #include <vector>
62
68
 
@@ -132,7 +138,14 @@ static Napi::Value StringOrNull(Napi::Env env, NSString* s) {
132
138
 
133
139
  @class CALNotificationDelegate;
134
140
 
135
- static bool gProbed = false;
141
+ // The centre, the delegate and the bundle check are the process's, not an
142
+ // environment's, so they go up the once — in whichever environment loads the
143
+ // module first, since the delegate has to be in place before
144
+ // finishLaunching whoever got here first. call_once rather than a bare bool:
145
+ // it publishes the outcome below to every later loader's thread, and a verb
146
+ // only ever runs in an environment that has loaded the module, so its read
147
+ // of gCenter is behind this.
148
+ static std::once_flag gProbeOnce;
136
149
  static UNUserNotificationCenter* gCenter = nil;
137
150
  static NSString* gUnavailable = nil; // why, when gCenter is nil
138
151
  static CALNotificationDelegate* gDelegate = nil; // the centre's delegate is weak
@@ -157,10 +170,13 @@ struct NotifEvent {
157
170
 
158
171
  static void CallJsEvent(Napi::Env env, Napi::Function, void*, NotifEvent* ev);
159
172
  using EventTsfn = Napi::TypedThreadSafeFunction<void, NotifEvent, CallJsEvent>;
160
- // Made in the first environment to reach the centre (ProbeCenter) and called
161
- // from the centre's own thread, so through CALTsfn: once that environment
162
- // has begun to end, an event is dropped rather than sent into it.
163
- static CALTsfn gEvents;
173
+ // The main thread's environment's (InitNotifications), called from the
174
+ // centre's own thread, so through CALTsfn: once that environment has begun
175
+ // to end, an event is dropped rather than sent into it. Null until made;
176
+ // leaked with the process.
177
+ static std::atomic<CALTsfn*> gEvents{nullptr};
178
+ // What arrived before a listener, in arrival order. The main thread's: both
179
+ // the function's callback and pump2's replay run there.
164
180
  static std::vector<NotifEvent*> gHeld;
165
181
 
166
182
  static CALEvent EventRecord(const NotifEvent& ev) {
@@ -209,16 +225,19 @@ static void CallJsEvent(Napi::Env env, Napi::Function, void*, NotifEvent* ev) {
209
225
  CALRaiseUncaughtIfPending(env);
210
226
  }
211
227
 
212
- // From any thread: onto node's loop, then to the listener or the held list
213
- // — in pump mode. With threaded mode's channel open the record goes straight
214
- // into it from the centre's own thread.
228
+ // From any thread: onto the main thread's loop, then to the listener or the
229
+ // held list — in pump mode. With threaded mode's channel open the record
230
+ // goes straight into it from the centre's own thread. There is no function
231
+ // to cross on until the main thread has loaded the module, and until then
232
+ // nothing on the main thread could be listening either: dropped.
215
233
  static void QueueEvent(NotifEvent* ev) {
216
234
  if (CALChannelOpen()) {
217
235
  CALEmit(EventRecord(*ev));
218
236
  delete ev;
219
237
  return;
220
238
  }
221
- bool queued = gEvents.Use(false, [ev](napi_threadsafe_function f) {
239
+ CALTsfn* events = gEvents.load();
240
+ bool queued = events && events->Use(false, [ev](napi_threadsafe_function f) {
222
241
  return EventTsfn(f).NonBlockingCall(ev);
223
242
  });
224
243
  if (!queued) delete ev;
@@ -290,12 +309,7 @@ static UNNotificationCategory* DefaultCategory() {
290
309
  options:UNNotificationCategoryOptionCustomDismissAction];
291
310
  }
292
311
 
293
- static void ProbeCenter(Napi::Env env) {
294
- if (gProbed) return;
295
- gProbed = true;
296
- EventTsfn events = EventTsfn::New(env, "appkit:notifications", 0, 1);
297
- events.Unref(env); // events never hold the loop open by themselves
298
- gEvents = CALTsfn::Watch(env, events);
312
+ static void Probe() {
299
313
  @autoreleasepool {
300
314
  NSBundle* main = NSBundle.mainBundle;
301
315
  if (!main.bundleIdentifier) {
@@ -328,6 +342,8 @@ static void ProbeCenter(Napi::Env env) {
328
342
  }
329
343
  }
330
344
 
345
+ static void ProbeCenter() { std::call_once(gProbeOnce, Probe); }
346
+
331
347
  // The centre, or a thrown Error naming why there is none.
332
348
  static UNUserNotificationCenter* CenterOrThrow(Napi::Env env, const char* fn) {
333
349
  if (gCenter) return gCenter;
@@ -957,7 +973,19 @@ static Napi::Value PostNotificationResponse(const Napi::CallbackInfo& info) {
957
973
  // ---------------------------------------------------------------------------
958
974
 
959
975
  void InitNotifications(Napi::Env env, Napi::Object exports) {
960
- ProbeCenter(env);
976
+ ProbeCenter();
977
+ // The event function is the main thread's, made the once: pump mode calls
978
+ // the listener inline and only the main thread may (CALEmit), and the held
979
+ // list is the main thread's too. It used to be made in whichever
980
+ // environment loaded the module first — a worker's, if a worker got there
981
+ // first, and then every pump-mode response crossed to the worker's thread
982
+ // and was dropped there, for good once that worker ended, while the main
983
+ // thread sat with a listener installed.
984
+ if (pthread_main_np() && !gEvents.load()) {
985
+ EventTsfn events = EventTsfn::New(env, "appkit:notifications", 0, 1);
986
+ events.Unref(env); // events never hold the loop open by themselves
987
+ gEvents.store(new CALTsfn(CALTsfn::Watch(env, events)));
988
+ }
961
989
  exports.Set("notificationSettings",
962
990
  Napi::Function::New(env, NotificationSettings));
963
991
  exports.Set("requestNotificationAuthorization",