@windowkit/appkit 0.9.0 → 0.11.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
@@ -42,10 +42,12 @@ npm run demo # hover/click the cards; press "q" to quit
42
42
  ## How it runs
43
43
 
44
44
  Node's main thread *is* the process main thread on macOS, so the addon owns
45
- `NSApplication` directly. Nobody calls `[NSApp run]`; instead JS drives an event pump
46
- (`nextEventMatchingMask:` with `distantPast`) off a `setInterval`. Core Animation
47
- animations execute in the render server, so their smoothness is independent of the pump
48
- cadence — the JS timer only affects input latency.
45
+ `NSApplication` directly. In pump mode, the default, nobody calls `[NSApp run]`; instead JS
46
+ drives an event pump (`nextEventMatchingMask:` with `distantPast`) off a `setInterval`.
47
+ Core Animation animations execute in the render server, so their smoothness is
48
+ independent of the pump cadence — the JS timer only affects input latency. Threaded mode
49
+ (below) turns this around: the main thread stays in `[NSApp run]` and JS moves to a
50
+ Worker.
49
51
 
50
52
  The window uses a **layer-hosting** `NSView` (we own the whole CALayer tree) with
51
53
  `isFlipped = YES`, which makes AppKit give the hosted layer a top-left origin
@@ -55,6 +57,190 @@ handled in native code: `hitTest:` still takes bottom-up points, and
55
57
  window's real composited pixels via `CGWindowListCreateImage`, which needs no
56
58
  screen-recording permission for the process's own windows).
57
59
 
60
+ ## Threaded mode: AppKit on the main thread, JS on a worker
61
+
62
+ Pump mode has two costs. Input waits for the next tick, up to 8 ms. And every modal loop
63
+ AppKit runs — live resize, menu tracking, a drag, `runModal` — runs *inside* `pump2()`,
64
+ so timers, sockets and even microtasks wait for the gesture to end (a drag once held a
65
+ 25 ms interval for 31 s, sidorares/react-x11#484). Threaded mode (windowkit/appkit#49)
66
+ swaps the roles: the process main thread parks in a real `[NSApp run]` for the life of the
67
+ app, and the renderer's JS runs on a `worker_threads` Worker, which no AppKit loop can
68
+ reach. Pump mode stays the default; calling `runMain()` is the switch.
69
+
70
+ ```js
71
+ // main.js — the process main thread
72
+ const { Worker } = require('node:worker_threads');
73
+ const { native } = require('@windowkit/appkit');
74
+ native.initApp();
75
+ new Worker('./renderer.js');
76
+ const code = native.runMain(); // returns when the run ends
77
+ process.exit(code ?? 0); // only this thread may end the process
78
+
79
+ // renderer.js — the worker
80
+ const { native } = require('@windowkit/appkit');
81
+ native.connect((batch) => {
82
+ for (const ev of batch) {
83
+ if (ev.type === 'signal') process.emit(ev.signal); // SIGINT never reaches a Worker
84
+ else route(ev);
85
+ }
86
+ });
87
+ // ...and when the app is done:
88
+ native.requestExit(0);
89
+ ```
90
+
91
+ | verb | |
92
+ | --- | --- |
93
+ | `runMain()` | The process main thread only. Returns the code `requestExit` gave; `null` when the connected environment ended without asking (its own `process.exit`, which in a Worker ends only the worker, or an uncaught error); `128 + n` for a signal with nobody connected to hear it. |
94
+ | `connect(onEvents)` | From the renderer's thread, one environment at a time. `onEvents(batch)` gets an array of the same event objects pump mode's callback gets one by one. |
95
+ | `requestExit(code)` | Any thread. Ends the run; `runMain` returns `code`. |
96
+ | `threaded()` | `runMain` is running. |
97
+ | `windowState(windowNumber)` | `getWindowFrame`'s shape for a `createWindow2` window, from the published copy (below); `null` for no such window. Any thread, either mode. |
98
+ | `activationPolicy()` | The published activation policy. |
99
+ | `pingUI(tag)`, `postModalLoop('menu' \| 'modal', ms)` | Test hooks: a command answered by `ui-pong { tag, mode, drained }` from the UI thread, and a pop-up menu's tracking or an `NSAlert`'s `runModal`, ended by a timer and bracketed by `modal-loop-begin` / `modal-loop-end`. |
100
+
101
+ **Events out.** Every producer builds a plain record (never a JS object off its thread).
102
+ With the channel open, records are appended to one queue, and the first append after a
103
+ delivery makes one threadsafe call. The worker takes the whole queue as one batch, so a
104
+ worker busy for 200 ms gets what it missed together. Consecutive `mousemove` in one window
105
+ folds to the latest position before it crosses. Whatever is emitted before `connect` —
106
+ the launch's URL, input that arrived while the worker started — is the first batch. A
107
+ delivery runs in a callback scope, so a microtask queued inside `onEvents` runs right
108
+ after it. An exception thrown from `onEvents`, or from any callback the bridge answers
109
+ through, is that environment's uncaught exception: `process.on('uncaughtException')` sees
110
+ it, and with no handler the worker ends, and with it the run. The channel holds the
111
+ worker's loop open while any window or status item
112
+ exists, and lets it go when none does, so an app with nothing on screen can end.
113
+
114
+ **Commands in.** The command queue is a version-0 `CFRunLoopSource` on the main run loop, in
115
+ `kCFRunLoopCommonModes`, so it is drained during menu tracking (`NSEventTrackingRunLoopMode`),
116
+ `runModal` (`NSModalPanelRunLoopMode`) and live resize too. Each drain applies its
117
+ batch inside one `CATransaction` with implicit actions off. A command that starts a modal
118
+ loop runs from a run-loop callout of its own once its drain is done, so the rest of the
119
+ batch never waits behind the gesture.
120
+
121
+ **The verbs from a worker** (windowkit/appkit#51). The verbs are the same in both modes.
122
+ Each runs inline on the main thread, as it always has, and is queued from any other
123
+ thread. From a worker, what changes is the shape of what a verb returns, because JS never
124
+ waits on the UI thread (`test/threaded-verbs.js` covers each row):
125
+
126
+ | from a worker | verbs |
127
+ | --- | --- |
128
+ | unchanged, on the calling thread | surfaces, every `ctx*`, layouts and fonts, `pasteboardTypeForMIME`, `pasteboardTypeInfo`, `contentTypeFor`, `colorSpace` |
129
+ | a command, answering nothing | `initApp`, `setActivationPolicy`, `setAppName`, `activateApp`, `showWindow`, `hideWindow`, `setWindowFrame`, `setWindowTitle`, `setWindowMinMax`, `setWindowIgnoresMouseEvents`, `invalidateWindowShadow`, `destroyWindow2`, `setCursor`, `setMainMenu`, `setDockMenu`, `setDockBadge`, `cancelUserAttention`, `setStatusItem`, `setStatusItemMenu`, `removeStatusItem`, `registerDropTypes`, `setDropResponse`, `pasteboardWriteText`, `pasteboardClear`, `cancelPanel`; the test posts `postMouseEvent`, `postKeyEvent`, `postAppleEvent`, `postAccessibilityDisplayChange` |
130
+ | a handle at the call | `createWindow2`, followed by `window-created { handle, windowNumber }`; every event about the window, input included, carries `handle`, so `ev.handle === win` |
131
+ | | `windowRootLayer`, allocated with the window |
132
+ | | `createStatusItem`: its clicks carry the handle, and it is held until `removeStatusItem` |
133
+ | | `requestUserAttention`: a bridge id |
134
+ | | `openPanel` / `savePanel`: the answer through the callback, as before |
135
+ | the published copy | `getWindowFrame`, `windowIsVisible`, `windowNumber` (all `null` until the window is made), `listScreens`, `accessibilityDisplayOptions`, `activationPolicy`, `appInfo`, `pasteboardChangeCount` |
136
+ | a callback, the last argument | `pasteboardReadText`, `snapshotWindow`, `snapshotStatusItem`, `windowNumberAtPoint`, `mainMenuInfo`, `dockMenuInfo`, `statusItemInfo`, `activateMenuItem`, `activateDockMenuItem`, `activateStatusItemMenuItem`, `clickStatusItem`, `dragItems`, `dragItemData`, `dragItemString`, `postDragEvent`. On the main thread each still answers synchronously when no callback is given. |
137
+ | events | `beginDrag`: `drag-session-began`, or `drag-session-ended` with nothing dropped. Its `provide` is a TypeError; give every value up front. |
138
+
139
+ A few verbs behave differently from a worker:
140
+ - **`setDropResponse`** cannot answer the `draggingEntered:` that is running as its event
141
+ crosses. It sets the standing answer for what follows. To make up for it, a drop carries
142
+ `items: [{ types, strings }]`, its text and URL representations read in.
143
+ - **An app-modal panel** can be cancelled with `cancelPanel`, because the queue drains
144
+ inside `runModal`.
145
+ - **`sampleScreenColor` and a location permission request** make their AppKit calls on the
146
+ UI thread.
147
+ - **`pump2` and the first-generation API** (`createWindow`, `pump`, `setEventCallback`,
148
+ `closeWindow`, `windowScale`, `windowContentSize`, `hitTest`, `drawControl`,
149
+ `appearanceIsDark`) throw off the main thread.
150
+
151
+ **Frames from a worker** (windowkit/appkit#52). Pixels stay on the renderer's thread:
152
+ drawing into surfaces, CoreText and `ctxGetImageData` all work there. Layer changes go to
153
+ the UI thread, a frame at a time (`test/threaded-frames.js`):
154
+
155
+ - **One batch per frame.** Between `txBegin` and `txCommit` on a worker, the layer verbs
156
+ record into that thread's frame batch. These are `createLayer` and its kinds, `set*Props`,
157
+ `addSublayer`, `removeFromSuperlayer`, `addAnimation`, `removeAnimation` and
158
+ `removeAllAnimations`, `setContentsImage`, `setLayerContentsIOSurface` and `surfaceToLayer`.
159
+ The outermost `txCommit` posts the batch as one command. The UI thread applies it in the
160
+ order it was recorded, in one commit, with `txBegin`'s options (`disableActions`,
161
+ `duration`, `timing`) as pump mode would have them. A layer verb outside any `txBegin` is a
162
+ command of its own, with actions on, as in pump mode's implicit transaction.
163
+ - **Layers are handles answered at the call.** The `CALayer` is made on the UI thread when
164
+ the frame applies, so no layer is touched by two threads. `addAnimation` still answers its
165
+ duration at the call, and `presentationValue` takes a callback.
166
+ - **Buffers change hands by event.** `surfaceToLayer` takes the bitmap at the call, so later
167
+ drawing does not reach the frame already posted. `setLayerContentsIOSurface` flips when
168
+ the frame applies. The renderer must not draw into the buffer the flip replaced until
169
+ either `surface-released { id }` names it, sent once the frame has been committed, or
170
+ `surfaceIsInUse(surface)` answers false.
171
+
172
+ **The live-resize handshake** (windowkit/appkit#53). In pump mode a resize stays in step for
173
+ free: `window-resize` runs the renderer inside `windowDidResize:` itself, so the new frame
174
+ commits with the moved edge. From a worker the frame comes back later, and without a
175
+ handshake the edge moves first while the content catches up a frame or more behind.
176
+ `setResizeHandshake(win, { waitMs })` turns the handshake on (`0`, the default, is off):
177
+
178
+ - When the window's size changes, whether by a live resize or `setWindowFrame`, the UI thread
179
+ sends `window-resize`.
180
+ - It then waits, never longer than `waitMs`, for a frame batch committed with that size:
181
+ `txCommit({ width, height })`, the renderer echoing the event's size.
182
+ - It applies that batch inline, so the frame lands in the same transaction as the new
183
+ window size.
184
+ - Each wait is reported as `resize-handshake { width, height, live, waited, met }`.
185
+ - A live resize is bracketed by `window-live-resize { phase: 'begin' | 'end' }`, in both
186
+ modes (windowkit/appkit#63). AppKit calls nothing when the pointer stops or lifts, so the
187
+ end is how a renderer knows to run the measured layout it deferred during the drag. The
188
+ published window state (`getWindowFrame`, `windowState`) carries `liveResize` too.
189
+
190
+ JS never waits on the UI thread, so the worst case is the deadline. A frame that misses it
191
+ shows the last frame at the new size, with the root layer's `backgroundColor` in the newly
192
+ exposed edge. The deadline is a strict dispatch timer (`DISPATCH_TIMER_STRICT`, zero
193
+ leeway), not a plain timed wait. Under a lower-QoS task policy, as on a CI runner or under
194
+ `taskpolicy -c utility`, the kernel coalesces timers: a 15 ms timed wait woke only when the
195
+ worker's own 60 ms timer fired.
196
+
197
+ Measured by `test/threaded-resize.js` on an M1 Pro, with 3 ms of layout per frame and a
198
+ 50 ms budget:
199
+
200
+ | | met | waited, p50 |
201
+ | --- | --- | --- |
202
+ | 20 `setWindowFrame` steps | 20 of 20 | 3.07 ms |
203
+ | a live resize (AppKit's own tracking, driven by posted mouse events) | 28 of 28 | 3.11 ms |
204
+ | a frame 60 ms late against a 15 ms budget | no | stopped at the deadline, ~16 ms |
205
+
206
+ **Control bezels** (windowkit/appkit#54). The NSCell or NSControl behind a bezel is made
207
+ on the UI thread. Called from a worker, they used to draw correct pixels and then crash the
208
+ process at exit.
209
+ - `measureControl(params, cb)` answers `cb({ width, height })`.
210
+ - `drawControlIntoSurface(surface, params, cb)` draws straight into the worker's surface,
211
+ with nothing copied, and `cb()` says it is done; until then the renderer leaves the
212
+ surface alone.
213
+
214
+ On the main thread without a callback both answer in the call, as before. Off it, a call
215
+ without a callback is a TypeError.
216
+
217
+ **Published state.** The UI thread keeps a copy, under a lock, of what a renderer reads
218
+ back synchronously: each window's content rect, visibility, occlusion, key state and
219
+ scale; the screen list; the accessibility display options; the activation policy; and the
220
+ pasteboard's change count, polled every 250 ms since another app's write announces
221
+ nothing. While `runMain` runs, `listScreens`, `accessibilityDisplayOptions` and
222
+ `pasteboardChangeCount` answer from it when called off the main thread. On the main
223
+ thread they still ask AppKit live, as in pump mode.
224
+
225
+ **Exit and signals.** Before the run stops, menu tracking is cancelled and an app-modal
226
+ loop stopped, since `[NSApp stop:]` only ends the innermost loop. A drag session or a live
227
+ resize cannot be ended from code, so the exit waits for the button to come up. While the run lasts,
228
+ SIGINT, SIGTERM and SIGHUP are ignored as signals and read through a
229
+ `DISPATCH_SOURCE_TYPE_SIGNAL`, each arriving as `signal { signal: 'SIGINT' }`.
230
+ `applicationShouldTerminate:` answers Cancel and sends `app-quit-request`, as in pump mode.
231
+ A worker's `console.log` and `process.stdout` are forwarded through the main thread's event
232
+ loop, which is parked, so write with `fs.writeSync(1, …)` on the worker. `process.exit`
233
+ there ends only the worker; ending the app is `requestExit`.
234
+
235
+ Measured by `test/threaded.js` on an M1 Pro, macOS 15.2, Node 26:
236
+
237
+ | | |
238
+ | --- | --- |
239
+ | command + event round trip | 0.06 ms p50, 0.10 ms p95 |
240
+ | a microtask queued inside a delivery | ran 0.01 ms later, p50 |
241
+ | commands sent during a pop-up menu's tracking | 65 of 65 applied inside `NSEventTrackingRunLoopMode`; the worker's 5 ms timer's worst gap 8.7 ms |
242
+ | commands sent during an `NSAlert`'s `runModal` | 80 of 80 applied inside `NSModalPanelRunLoopMode`; worst gap 7.1 ms |
243
+
58
244
  ## API sketch
59
245
 
60
246
  ```js
@@ -307,6 +493,37 @@ native.ctxDrawSurface(win, grid, 0, 0, 2000, 1620, 40, 30, 2000, 1620);
307
493
  native.ctxSetBlendMode(win, 'source-over');
308
494
  ```
309
495
 
496
+ ## Text: letter spacing and OpenType features
497
+
498
+ The text verbs a renderer lays paragraphs out and shapes glyph runs with —
499
+ `matchFont`, `createLayout`, `fontShapeText` — take the two adjustments a designed
500
+ interface reaches for past the face and the size:
501
+
502
+ - **`native.fontApplyFeatures(font, features)`** — the font with OpenType features set by
503
+ tag, the sibling of `fontApplyVariations`. An array turns each tag on (`['tnum']`); an
504
+ object sets each tag to its value, `true`/`false` or a number for a feature that selects
505
+ among alternates (`{ tnum: true, liga: false, salt: 2 }`). The settings replace any the
506
+ font carries, and with nothing to set the font itself comes back, so it can be applied
507
+ unconditionally. `tnum` is the one a live readout wants: the system face's digits are
508
+ proportional, and a number that changes while a slider moves reflows with every value.
509
+ - **`letterSpacing`**, in points: a `createLayout` span option, and a third-argument option
510
+ to `fontShapeText` — `{ letterSpacing }` — so a paragraph and a run shaped alone agree.
511
+ It is added after every character, the last on a line included, which is what
512
+ `kCTKernAttributeName` does and what CSS's `letter-spacing` long did; negative values
513
+ tighten. It says nothing about ligatures: a caller that wants CSS's rule turns the
514
+ optional ones off through `fontApplyFeatures` on a spaced span.
515
+
516
+ ```js
517
+ const face = native.matchFont({ families: ['system-ui'], size: 30 });
518
+ const small = native.matchFont({ families: ['system-ui'], size: 11, weight: 600 });
519
+ const readout = native.createLayout({
520
+ spans: [{ text: '487 Hz', font: native.fontApplyFeatures(face, ['tnum']) }],
521
+ });
522
+ const label = native.createLayout({
523
+ spans: [{ text: 'NOISE TYPE', font: small, letterSpacing: 1.26 }],
524
+ });
525
+ ```
526
+
310
527
  ## App lifecycle: open-URL, open-file, reopen, quit
311
528
 
312
529
  The OS talks to the application as a whole through Apple Events: a URL for a scheme
@@ -851,6 +1068,20 @@ native.setAppName('My App');
851
1068
  native.appInfo(); // -> { activationPolicy, name, dockBadge, active }
852
1069
  ```
853
1070
 
1071
+ **Under a launcher** (windowkit/appkit#64), the app's own code may not have run when the app
1072
+ launches. A threaded-mode launcher calls `initApp()` and `runMain()` on the main thread
1073
+ before its worker has imported the app's entry, so the app's `initApp({ activationPolicy })`
1074
+ from the worker comes after `finishLaunching`, by which time an agent app has already shown
1075
+ its Dock tile. Two ways to set the policy before launch:
1076
+ - **`APPKIT_ACTIVATION_POLICY=regular|accessory|prohibited`** is read as the app launches,
1077
+ whichever call launches it. An unknown name is reported on stderr, and the app launches
1078
+ regular.
1079
+ - **`runMain({ activationPolicy })`** is the policy to launch with when `runMain` is what
1080
+ launches the app. If the app is already up, it is a live switch, as `setActivationPolicy` is.
1081
+
1082
+ A policy the code gives before launch (`initApp`, `setActivationPolicy`, `runMain`) wins
1083
+ over the variable. A bundled app says the same with `LSUIElement` in its Info.plist.
1084
+
854
1085
  `dockMenuInfo()` and `activateDockMenuItem([i, j, …])` mirror `mainMenuInfo()` and
855
1086
  `activateMenuItem()` for tests; both go through the delegate method the Dock itself calls.
856
1087
 
@@ -984,6 +1215,7 @@ only what changed.
984
1215
 
985
1216
  - The pump-on-a-timer model means live window resizing/dragging runs AppKit's internal
986
1217
  modal loops; input during those is choppy (Core Animation itself is unaffected).
1218
+ Threaded mode (above) is the way out.
987
1219
  - No `NSWindowDelegate` wiring yet — window resize is observable only by polling
988
1220
  `win.size`; sublayers don't autolayout (by design — the reconciler owns layout).
989
1221
  - One shared event callback for all windows; per-window routing would need the window
package/binding.gyp CHANGED
@@ -8,7 +8,8 @@
8
8
  "src/permissions.mm",
9
9
  "src/notifications.mm",
10
10
  "src/calendars.mm",
11
- "src/screencolor.mm"
11
+ "src/screencolor.mm",
12
+ "src/threaded.mm"
12
13
  ],
13
14
  "include_dirs": [
14
15
  "<!@(node -p \"require('node-addon-api').include\")"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@windowkit/appkit",
3
- "version": "0.9.0",
3
+ "version": "0.11.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/eventkit-permissions.js && node test/calendars.js && node test/calendar-writes.js && node test/screencolor.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/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