@windowkit/appkit 0.4.0 → 0.5.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 +513 -3
- package/binding.gyp +13 -2
- package/index.js +79 -4
- package/package.json +3 -2
- package/prebuilds/darwin-arm64/calayers.node +0 -0
- package/prebuilds/darwin-x64/calayers.node +0 -0
- package/src/addon.mm +407 -42
- package/src/backend.mm +2088 -32
- package/src/notifications.mm +951 -0
- package/src/permissions.mm +399 -0
package/README.md
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
# @windowkit/appkit
|
|
2
2
|
|
|
3
3
|
A **retained-mode AppKit backend for Node.js**: Core Animation (CALayer)
|
|
4
|
-
layer trees, CoreText layout and drawing, IOSurface presentation, NSMenu
|
|
5
|
-
native control bezels. It is the macOS
|
|
4
|
+
layer trees, CoreText layout and drawing, IOSurface presentation, NSMenu,
|
|
5
|
+
native control bezels and the privacy (TCC) authorizations. It is the macOS
|
|
6
|
+
half of [react-x11][react-x11].
|
|
6
7
|
Instead of immediate-mode draw calls, you build a persistent tree of layers, mutate their
|
|
7
8
|
properties, and let the macOS WindowServer composite on the GPU — with implicit animations
|
|
8
9
|
and correct retina handling for free.
|
|
@@ -82,9 +83,12 @@ transaction(() => card.set({ position: [400, 300] }),
|
|
|
82
83
|
// no animation (e.g. initial tree construction, reconciler commits)
|
|
83
84
|
withoutAnimations(() => card.set({ opacity: 0.5 }));
|
|
84
85
|
|
|
85
|
-
// explicit animation on any animatable keyPath
|
|
86
|
+
// explicit animation on any animatable keyPath — from/to, keyframes ('values') or a
|
|
87
|
+
// spring ('spring'); a curve by name or by control points; see "Animations"
|
|
86
88
|
card.animate('transform.rotation.z',
|
|
87
89
|
{ from: 0, to: Math.PI * 2, duration: 1, repeat: Infinity, timing: 'linear' });
|
|
90
|
+
card.animate('transform.translation.y',
|
|
91
|
+
{ values: [0, -6, 6, -6, 0], duration: 0.3, timing: [0.33, 1, 0.68, 1], id: 'shake' });
|
|
88
92
|
|
|
89
93
|
// text, two ways
|
|
90
94
|
const label = new TextLayer();
|
|
@@ -118,6 +122,93 @@ app.run({ onTick: () => { if (!win.visible) process.exit(0); } });
|
|
|
118
122
|
win.snapshot('/tmp/out.png'); // real composited pixels of the window
|
|
119
123
|
```
|
|
120
124
|
|
|
125
|
+
## Animations
|
|
126
|
+
|
|
127
|
+
Core Animation runs an animation in the render server: the pump's cadence and a busy JS
|
|
128
|
+
thread do not touch it. The verbs here are shaped for a renderer that keeps its own model
|
|
129
|
+
of what is animating and hands over only the pixels — the layer's model value set under
|
|
130
|
+
`disableActions`, an explicit animation carrying the presentation from where it was to
|
|
131
|
+
where the model now is (react-x11's
|
|
132
|
+
[animation design](https://github.com/sidorares/react-x11/blob/master/docs/architecture/animation.md),
|
|
133
|
+
[#29](https://github.com/windowkit/appkit/issues/29)).
|
|
134
|
+
|
|
135
|
+
```js
|
|
136
|
+
// the model goes straight to its target, with no implicit animation…
|
|
137
|
+
withoutAnimations(() => card.set({ opacity: 1 }));
|
|
138
|
+
// …and an explicit one carries the pixels there
|
|
139
|
+
card.animate('opacity', { from: 0, to: 1, duration: 0.2, timing: [0.33, 1, 0.68, 1], id: 'fade' });
|
|
140
|
+
// native.addAnimation(layer, keyPath, opts, key) is the same call, and returns the
|
|
141
|
+
// duration in seconds — a spring's settling time
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
Three kinds, told apart by which option is present:
|
|
145
|
+
|
|
146
|
+
| options | animation | |
|
|
147
|
+
| -------------------------------------------------------- | --------------------- | ------------------------------------------------------------------------------------------------- |
|
|
148
|
+
| `{ from, to, duration }` | `CABasicAnimation` | `duration` defaults to 0.25s |
|
|
149
|
+
| `{ values, keyTimes?, timings?, calculationMode? }` | `CAKeyframeAnimation` | `keyTimes` one per value in 0..1, never decreasing (evenly spaced when omitted); `timings` one curve per segment; `calculationMode` `linear` (default), `discrete`, `paced`, `cubic`, `cubicPaced` |
|
|
150
|
+
| `{ spring: { mass, stiffness, damping, initialVelocity } \| true, from, to }` | `CASpringAnimation` | CA's defaults for what is omitted (`true` is all of them); the duration is the settling time unless a `duration` cuts it short |
|
|
151
|
+
|
|
152
|
+
A value — `from`, `to`, an entry of `values` — is a number, a point `[x, y]`, or a colour
|
|
153
|
+
`[r, g, b, a]` in generic RGB like every colour in this API.
|
|
154
|
+
|
|
155
|
+
Options every kind takes:
|
|
156
|
+
|
|
157
|
+
| option | |
|
|
158
|
+
| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
159
|
+
| `timing` | a curve name — `linear`, `easeIn`, `easeOut`, `easeInEaseOut`, `default`, or their CSS spellings `ease-in`, `ease-out`, `ease-in-out`, `ease` — or cubic-bezier control points `[x1, y1, x2, y2]`. An unknown name is a `TypeError` |
|
|
160
|
+
| `repeat` | a count, or `Infinity` |
|
|
161
|
+
| `autoreverse` | turn around at the end of each pass |
|
|
162
|
+
| `additive` | the values are deltas over the model value, and several in flight on one key path sum |
|
|
163
|
+
| `cumulative` | each repetition starts where the last ended |
|
|
164
|
+
| `delay` | seconds before it starts; the layer shows `from` while it waits (`fillMode: backwards`) |
|
|
165
|
+
| `speed`, `timeOffset` | `CAMediaTiming`'s; `speed: 0` with a `timeOffset` is an animation paused at that time |
|
|
166
|
+
| `hold` | keep the final value on screen after the end (`removedOnCompletion: NO`, `fillMode: forwards`) — the model value stays what it was |
|
|
167
|
+
| `id` | report the end as a backend event (below) |
|
|
168
|
+
|
|
169
|
+
Control points rather than names are what a renderer with its own interpolator needs: the
|
|
170
|
+
same four numbers evaluate to the same curve on its side and in the render server, where a
|
|
171
|
+
name means whatever each side thinks it means — react-x11's ease-out is
|
|
172
|
+
cubic-bezier(0.33, 1, 0.68, 1), and CA's named `easeOut` is (0, 0, 0.58, 1), a fifth of the
|
|
173
|
+
range apart at t = 0.35. `transaction(fn, { duration, timing })` takes the same forms.
|
|
174
|
+
|
|
175
|
+
**Retargeting without reading back.** Set the model to the new target and add an additive
|
|
176
|
+
animation `from: old − new, to: 0`: the pixels carry on from wherever the previous animation
|
|
177
|
+
had got to, because the previous one is still running and the two sum. That covers every
|
|
178
|
+
numeric key path (`opacity`, `position`, `transform.*`, `cornerRadius`, …). A colour cannot
|
|
179
|
+
be additive; for that there is `presentationValue`.
|
|
180
|
+
|
|
181
|
+
**`native.presentationValue(layer, keyPath)`** (`layer.presentationValue(keyPath)`) — the
|
|
182
|
+
value the render server is showing for that key path right now, animations applied: a
|
|
183
|
+
number, a point or size as `[x, y]`, a rect as `[x, y, w, h]`, a colour as `[r, g, b, a]`, a
|
|
184
|
+
transform as its sixteen components; `null` before the layer's first commit. A colour comes
|
|
185
|
+
back in sRGB, the space it went in, so it can be handed straight back as a `from` —
|
|
186
|
+
but CA interpolates in the display's space, so the components' midpoint there is not this
|
|
187
|
+
space's midpoint.
|
|
188
|
+
|
|
189
|
+
**`native.colorSpace()`** — `'sRGB'`: the space every colour crossing this bridge is in —
|
|
190
|
+
a layer's `backgroundColor`, `borderColor` and `shadowColor`, a shape's fill and stroke,
|
|
191
|
+
a gradient's stops, an animation's `from`/`to`, a presentation value, a text span's ink
|
|
192
|
+
and the surfaces `createSurface` makes. One space, so a colour set on a layer and the
|
|
193
|
+
same colour rastered into a surface composite to the same pixels. (Before 0.6 the layer
|
|
194
|
+
half was Generic RGB, which the compositor converts on its way to the display: `#dbe7f4`
|
|
195
|
+
on a layer showed as (228, 236, 245) beside a surface's (219, 231, 244), and a colour
|
|
196
|
+
animation landed on a model value that did not match its own `to`. A caller that draws
|
|
197
|
+
both ways — react-x11's layer promotion — feature-detects the verb.) `speed: 0, timeOffset: t` plus a read is how a curve is sampled without
|
|
198
|
+
waiting for it, which is how `test/animation.js` checks every curve above.
|
|
199
|
+
|
|
200
|
+
**The end of an animation.** With an `id`, the animation's delegate forwards
|
|
201
|
+
`animationDidStop:finished:` through `setBackendEventCallback` as
|
|
202
|
+
|
|
203
|
+
```js
|
|
204
|
+
{ type: 'animation-end', id, key, keyPath, finished }
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
`finished` is `false` for an animation that was removed (`removeAnimation`,
|
|
208
|
+
`removeAllAnimations`) or whose layer left the tree before it ran out. It arrives inside a
|
|
209
|
+
`pump2()`, like a window delegate's events. Without an `id` no delegate is set and nothing is
|
|
210
|
+
reported.
|
|
211
|
+
|
|
121
212
|
## Native controls
|
|
122
213
|
|
|
123
214
|
There is no WindowServer API for control drawing — AppKit draws controls in-process via
|
|
@@ -160,6 +251,425 @@ vibrancy materials need private API to reproduce; expose real `NSMenu` instead.
|
|
|
160
251
|
`native.postMouseEvent(win, 'down'|'up'|'move'|'drag', x, y)` synthesizes events through
|
|
161
252
|
the real pump — used by the demo's self-test (`CAL_CLICKS="x,y;x,y" npm run demo`).
|
|
162
253
|
|
|
254
|
+
## App lifecycle: open-URL, open-file, reopen, quit
|
|
255
|
+
|
|
256
|
+
The OS talks to the application as a whole through Apple Events: a URL for a scheme
|
|
257
|
+
the bundle registers (`kInternetEventClass/kAEGetURL`), a document handed over by the
|
|
258
|
+
Finder (`kCoreEventClass/kAEOpenDocuments`), a second launch of a running app
|
|
259
|
+
(`kAEReopenApplication`), and Quit from the Dock, the app menu or a logout
|
|
260
|
+
(`kAEQuitApplication`). `native.initApp()` installs an `NSApplicationDelegate` that
|
|
261
|
+
forwards them to the backend event callback and decides nothing itself:
|
|
262
|
+
|
|
263
|
+
| event | payload | from |
|
|
264
|
+
| ------------------ | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
265
|
+
| `app-open-urls` | `{ urls: [string] }` | `application:openURLs:` — scheme URLs as sent, documents as `file://` URLs |
|
|
266
|
+
| `app-reopen` | `{ hasVisibleWindows }` | `applicationShouldHandleReopen:`, answered NO — what a second launch means is the renderer's call |
|
|
267
|
+
| `app-quit-request` | `{}` | `applicationShouldTerminate:`, answered Cancel while a callback is installed — the renderer quits (`process.exit`) or vetoes. With no callback the OS default stands and the process ends |
|
|
268
|
+
|
|
269
|
+
```js
|
|
270
|
+
native.initApp(); // first: the delegate has to precede finishLaunching
|
|
271
|
+
native.setBackendEventCallback((ev) => {
|
|
272
|
+
if (ev.type === 'app-open-urls') route(ev.urls);
|
|
273
|
+
if (ev.type === 'app-reopen' && !ev.hasVisibleWindows) showMainWindow();
|
|
274
|
+
if (ev.type === 'app-quit-request') process.exit(0);
|
|
275
|
+
});
|
|
276
|
+
setInterval(() => native.pump2(), 16);
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
Launch Services delivers the launching Apple Event inside `finishLaunching` — that is,
|
|
280
|
+
inside `initApp()`, before any callback exists. Whatever arrives with nobody listening
|
|
281
|
+
is held and replayed, in order, on the first `pump2()` that has a callback, ahead of
|
|
282
|
+
that tick's input. Registering the scheme itself is an install step, not runtime code:
|
|
283
|
+
`CFBundleURLTypes` (and `CFBundleDocumentTypes` for files) in the bundle's
|
|
284
|
+
`Info.plist`.
|
|
285
|
+
|
|
286
|
+
`native.postAppleEvent('open-url', url)`, `('open-documents', [paths])`, `('reopen')`
|
|
287
|
+
and `('quit')` build the corresponding Apple Event and dispatch it through
|
|
288
|
+
`NSAppleEventManager` as if it had just arrived — how `npm test` exercises the
|
|
289
|
+
delegate without a bundle.
|
|
290
|
+
|
|
291
|
+
## File panels
|
|
292
|
+
|
|
293
|
+
Open and save dialogs are real `NSOpenPanel` / `NSSavePanel`s owned by this process's
|
|
294
|
+
`NSApplication` — not a separate `osascript` — so they can run as a sheet on the window
|
|
295
|
+
that asked, every filter the OS type database knows gets through, and a cancel is a
|
|
296
|
+
cancel rather than a failed subprocess.
|
|
297
|
+
|
|
298
|
+
```js
|
|
299
|
+
const { native } = require('@windowkit/appkit');
|
|
300
|
+
|
|
301
|
+
// With a window handle the panel is a sheet on it: the pump keeps running and the
|
|
302
|
+
// callback fires on a later tick. Without one it is app-modal: the call blocks in
|
|
303
|
+
// AppKit's modal loop until the panel is dismissed, and the callback runs before
|
|
304
|
+
// the call returns.
|
|
305
|
+
native.openPanel({
|
|
306
|
+
window: win._h, // omit for app-modal
|
|
307
|
+
directory: false, // true: choose folders instead of files
|
|
308
|
+
multiple: true,
|
|
309
|
+
message: 'Pick some images',
|
|
310
|
+
prompt: 'Import', // the confirm button's label
|
|
311
|
+
directoryURL: process.env.HOME,
|
|
312
|
+
allowedContentTypes: ['public.png', native.contentTypeFor({ mime: 'image/jpeg' })],
|
|
313
|
+
}, (paths) => { /* ['/Users/…/a.png', …], or null on cancel */ });
|
|
314
|
+
|
|
315
|
+
native.savePanel({
|
|
316
|
+
window: win._h,
|
|
317
|
+
nameFieldStringValue: 'Untitled.txt',
|
|
318
|
+
allowedContentTypes: [native.contentTypeFor({ extension: 'txt' })],
|
|
319
|
+
}, (path) => { /* '/Users/…/Untitled.txt', or null on cancel */ });
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
Both take `title`, `message`, `prompt`, `directoryURL` (a path or `file:` URL),
|
|
323
|
+
`allowedContentTypes` and `canCreateDirectories`; the open panel adds `directory` and
|
|
324
|
+
`multiple`, the save panel `nameFieldStringValue`. Both return a panel handle:
|
|
325
|
+
`native.cancelPanel(handle)` dismisses a sheet that is still up (its callback then gets
|
|
326
|
+
`null`) and reports whether there was one, and `destroyWindow2` answers any sheet still
|
|
327
|
+
attached to the window the same way, so no callback is left waiting.
|
|
328
|
+
|
|
329
|
+
Filters are UTType identifiers, the shape `NSSavePanel.allowedContentTypes` wants;
|
|
330
|
+
mapping extensions and MIME types onto them is the renderer's policy, and
|
|
331
|
+
`native.contentTypeFor({ extension })` / `({ mime })` does the lookup in the OS's own
|
|
332
|
+
database (`'png'` → `'public.png'`, `'application/json'` → `'public.json'`; an
|
|
333
|
+
extension nobody has declared still gets a dynamic type that matches exactly that
|
|
334
|
+
extension). An absent or empty list means any file, and so does a list the OS
|
|
335
|
+
recognises nothing of.
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
## Drag and drop
|
|
339
|
+
|
|
340
|
+
The backend surface's windows (`native.createWindow2`) take drops and begin
|
|
341
|
+
drags through the hosting view — `NSDraggingDestination` and
|
|
342
|
+
`NSDraggingSource` — with every phase reported through the backend event
|
|
343
|
+
callback, the window's number attached, like every other window event.
|
|
344
|
+
Mechanism only: the renderer keeps the policy (what to accept, what a drop
|
|
345
|
+
means). Type names cross the boundary as pasteboard types — UTIs such as
|
|
346
|
+
`public.utf8-plain-text`, `public.file-url`, `public.png` — and mapping a MIME
|
|
347
|
+
vocabulary onto them is the renderer's job; `pasteboardTypeForMIME(mime)` and
|
|
348
|
+
`pasteboardTypeInfo(uti)` read the OS's own table for it (a MIME type no
|
|
349
|
+
declared type claims gets a `dyn.*` identifier that every process computes
|
|
350
|
+
alike).
|
|
351
|
+
|
|
352
|
+
```js
|
|
353
|
+
const { native } = require('@windowkit/appkit');
|
|
354
|
+
const win = native.createWindow2({ width: 640, height: 480, title: 'drop here' });
|
|
355
|
+
|
|
356
|
+
// destination: register, then answer AppKit's questions from inside the callback
|
|
357
|
+
native.registerDropTypes(win, ['public.file-url', 'public.utf8-plain-text']);
|
|
358
|
+
native.setBackendEventCallback((ev) => {
|
|
359
|
+
switch (ev.type) {
|
|
360
|
+
case 'drag-enter': // { windowNumber, x, y, gx, gy, types, itemCount, sourceMask,
|
|
361
|
+
case 'drag-over': // operations, local, sourceWindowNumber?, sequence }
|
|
362
|
+
native.setDropResponse(win, { accept: ev.types.includes('public.file-url'),
|
|
363
|
+
operation: 'copy' });
|
|
364
|
+
break;
|
|
365
|
+
case 'drag-exit': // may carry no position: a drag cancelled mid-air
|
|
366
|
+
break;
|
|
367
|
+
case 'drag-perform': // the drop — read the payload now
|
|
368
|
+
for (let i = 0; i < ev.itemCount; i++)
|
|
369
|
+
console.log(native.dragItemString(i, 'public.file-url'));
|
|
370
|
+
break;
|
|
371
|
+
case 'drag-session-began': // source side: x/y in global top-left coordinates
|
|
372
|
+
case 'drag-session-moved':
|
|
373
|
+
case 'drag-session-ended': // + { operation: 'copy' | 'move' | ... | 'none', dropped }
|
|
374
|
+
break;
|
|
375
|
+
}
|
|
376
|
+
});
|
|
377
|
+
|
|
378
|
+
// source: from a press, once the renderer's own threshold says it is a drag
|
|
379
|
+
native.beginDrag(win, {
|
|
380
|
+
x: press.x, y: press.y, // content coords
|
|
381
|
+
items: [{ 'public.utf8-plain-text': 'hello', 'public.png': null }], // one item; null = lazy
|
|
382
|
+
provide: (type, index) => renderPng(), // asked when a consumer reads the promise
|
|
383
|
+
operations: ['copy', 'move'],
|
|
384
|
+
surface: previewSurface, imageX: node.x, imageY: node.y, // or image: text.render(...)
|
|
385
|
+
});
|
|
386
|
+
```
|
|
387
|
+
|
|
388
|
+
- **`setDropResponse` answers the question being asked.** The callback runs
|
|
389
|
+
synchronously inside `draggingEntered:` / `draggingUpdated:`, so a response
|
|
390
|
+
set during `drag-enter` or `drag-over` is what AppKit gets back for that
|
|
391
|
+
event. It stays in force for the `drag-over` events that follow until
|
|
392
|
+
changed, and resets to a refusal when a new drag enters. `{ accept: false }`
|
|
393
|
+
during `drag-perform` withdraws a drop after a look at the payload.
|
|
394
|
+
`operation` absent picks copy, move, link, generic, private, delete — the
|
|
395
|
+
first the source allows.
|
|
396
|
+
- **`types` is the pasteboard's union, promised translations included**: a
|
|
397
|
+
`public.png` also appears as `public.tiff` and the legacy `Apple PNG
|
|
398
|
+
pasteboard type`, a file URL as `NSFilenamesPboardType`. `dragItems()` lists
|
|
399
|
+
the declared types per item; `dragItemData(index, type)` returns a `Buffer`
|
|
400
|
+
and `dragItemString(index, type)` a string, `null` when the item has no such
|
|
401
|
+
representation. A Finder drag of three files is three items of one
|
|
402
|
+
`public.file-url` each. Read during `drag-perform`: the payload is the
|
|
403
|
+
source's promise, and a source may withdraw it once its session has ended.
|
|
404
|
+
- **`beginDrag` returns at once.** The session is begun from the real
|
|
405
|
+
mouse-down when the pointer is still down in the window (the event the
|
|
406
|
+
renderer's threshold logic is reacting to), and runs on AppKit's own
|
|
407
|
+
tracking from there: the pointer's `mousemove` / `mouseup` stop arriving,
|
|
408
|
+
and `drag-session-ended` is the release. `items` is one entry per dragging
|
|
409
|
+
item, each a map of type → string | bytes | `null`, where `null` is a
|
|
410
|
+
promise answered by `provide(type, index)` when a consumer reads it — so a
|
|
411
|
+
representation nobody asks for is never built. `operations` is the source's
|
|
412
|
+
mask (`operationsOutside` for other applications when it differs),
|
|
413
|
+
`ignoreModifiers` stops Option/Command turning it into copy/link, and
|
|
414
|
+
`slideBack` (default on) animates a refused drop home. The image is a
|
|
415
|
+
`surface` handle or a CGImage `image` (the `text.render` / `controls.render`
|
|
416
|
+
result works whole), placed at `imageX` / `imageY` — centred on the press by
|
|
417
|
+
default — at its own size unless `imageWidth` / `imageHeight` say otherwise.
|
|
418
|
+
A drop on one of our own windows arrives through the destination events of
|
|
419
|
+
that window with `local: true` and the source's `sourceWindowNumber`.
|
|
420
|
+
- **`postDragEvent(win, phase, { x, y, items, operations, local })`** drives
|
|
421
|
+
the destination methods with a dragging info of the bridge's own over a
|
|
422
|
+
private pasteboard — what `postMouseEvent` is to clicks. `'enter'` and
|
|
423
|
+
`'over'` answer the operation the view returned (`'none'` when it refused),
|
|
424
|
+
`'drop'` runs prepare + perform + conclude and answers whether the drop was
|
|
425
|
+
taken. The CI smoke test and a renderer's headless tests drive drops this
|
|
426
|
+
way.
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
## Privacy authorizations (TCC)
|
|
430
|
+
|
|
431
|
+
macOS decides per process whether an app may use the camera, microphone,
|
|
432
|
+
screen, accessibility, input monitoring or location, or send Apple Events to
|
|
433
|
+
another app. The bridge is mechanism only: read the status, raise the system
|
|
434
|
+
prompt where a framework offers one, and deep-link to the Settings pane where
|
|
435
|
+
it does not. Policy — when to ask, what to do with a refusal — stays in the
|
|
436
|
+
renderer.
|
|
437
|
+
|
|
438
|
+
```js
|
|
439
|
+
const { permissions, native } = require('@windowkit/appkit');
|
|
440
|
+
|
|
441
|
+
permissions.status('camera'); // 'authorized' | 'denied' | 'restricted' | 'notDetermined'
|
|
442
|
+
await permissions.request('microphone'); // raises the system prompt; resolves to granted (boolean)
|
|
443
|
+
permissions.status('automation', { target: 'com.apple.finder' }); // Apple Events, per target app
|
|
444
|
+
permissions.openSettings('screen-recording'); // System Settings › Privacy & Security › Screen Recording
|
|
445
|
+
|
|
446
|
+
// the natives underneath, callback-shaped
|
|
447
|
+
native.authorizationStatus(kind, opts?); // never prompts
|
|
448
|
+
native.requestAuthorization(kind, opts?, (granted, status) => {}); // once, asynchronously
|
|
449
|
+
native.openPrivacySettings(kind?); // no kind: the Privacy pane itself
|
|
450
|
+
```
|
|
451
|
+
|
|
452
|
+
| kind | status | request | notes |
|
|
453
|
+
| ------------------------ | ---------------------------------------------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
454
|
+
| `camera`, `microphone` | `AVCaptureDevice authorizationStatusForMediaType:` | `requestAccessForMediaType:` | all four statuses; the prompt is in-process and the answer arrives when the user clicks |
|
|
455
|
+
| `screen-recording` | `CGPreflightScreenCaptureAccess` | `CGRequestScreenCaptureAccess` | a bool, so never `notDetermined`; the "prompt" is the system's go-to-Settings dialog (shown once) and the request resolves at once. A new grant needs a process restart |
|
|
456
|
+
| `accessibility` | `AXIsProcessTrusted` | `AXIsProcessTrustedWithOptions` + prompt | a bool, so never `notDetermined`; go-to-Settings dialog, resolves at once, the grant applies live |
|
|
457
|
+
| `input-monitoring` | `IOHIDCheckAccess` (listen) | `IOHIDRequestAccess` | granted / denied / unknown → `notDetermined`; the request posts the prompt and resolves at once, `notDetermined` while it is still up |
|
|
458
|
+
| `automation` | `AEDeterminePermissionToAutomateTarget` | the same, asking | needs `{ target: bundleId }` of a **running** app, otherwise throws — TCC only answers for a running target. Asking blocks until answered, so it runs off the main thread |
|
|
459
|
+
| `location` | `CLLocationManager.authorizationStatus` | `requestWhenInUseAuthorization` | the answer comes through the delegate on the main run loop, i.e. while `app.run()` is pumping |
|
|
460
|
+
|
|
461
|
+
- A request answers **once, asynchronously** — never inside the call — and
|
|
462
|
+
holds the event loop open until then, like pending I/O.
|
|
463
|
+
- **Attribution.** A bare `node` process is attributed to its *responsible
|
|
464
|
+
process* (Terminal, an IDE) or to `node` itself, and prompts with no
|
|
465
|
+
usage-description strings. A bundled app must carry the keys
|
|
466
|
+
(`NSCameraUsageDescription`, `NSMicrophoneUsageDescription`,
|
|
467
|
+
`NSLocationUsageDescription`, `NSAppleEventsUsageDescription`); without
|
|
468
|
+
them the request never prompts, or TCC ends the process.
|
|
469
|
+
- **Folders** (Desktop, Documents, Downloads) need nothing native: reading the
|
|
470
|
+
directory *is* the prompt and `EPERM` is the denial. `openSettings` also
|
|
471
|
+
takes `'files-and-folders'` and `'full-disk-access'` for their panes.
|
|
472
|
+
- `restricted` is MDM or parental controls: the user cannot grant it.
|
|
473
|
+
## Status item (the menu-bar extra)
|
|
474
|
+
|
|
475
|
+
`NSStatusItem` is the tray. An item shows an image or a title (or both) in the
|
|
476
|
+
system status bar with a tooltip, and either owns a menu or reports clicks. The
|
|
477
|
+
menu takes the same item spec `setMainMenu` does, so the tray, the app menu bar
|
|
478
|
+
and — through react-x11's dbusmenu adapter — a Linux panel share one authoring
|
|
479
|
+
model; activations arrive as the same `menu-activate` events, tagged `menu: 'status'`.
|
|
480
|
+
|
|
481
|
+
```js
|
|
482
|
+
const { native } = require('@windowkit/appkit');
|
|
483
|
+
native.setBackendEventCallback((ev) => {
|
|
484
|
+
if (ev.type === 'status-item-click') { // only without a menu
|
|
485
|
+
// ev.statusItem === item; ev.kind: 'left' | 'right' | 'middle'
|
|
486
|
+
// ev.x/y/width/height: the item's screen rect, top-left global — the
|
|
487
|
+
// anchor for a popup of your own; plus shift/control/option/command
|
|
488
|
+
}
|
|
489
|
+
if (ev.type === 'menu-activate') { /* ev.id from the spec below */ }
|
|
490
|
+
});
|
|
491
|
+
|
|
492
|
+
const item = native.createStatusItem({
|
|
493
|
+
image: 'bell.badge', // SF Symbol name — or a surface handle, or PNG bytes
|
|
494
|
+
title: '3', // beside the image, or alone
|
|
495
|
+
tooltip: 'Notifications',
|
|
496
|
+
length: 'variable', // 'variable' | 'square' | points
|
|
497
|
+
});
|
|
498
|
+
native.setStatusItemMenu(item, [ // setMainMenu's item vocabulary
|
|
499
|
+
{ id: 1, title: 'Open', iconName: 'macwindow' },
|
|
500
|
+
{ separator: true },
|
|
501
|
+
{ id: 2, title: 'Quit', key: 'q' },
|
|
502
|
+
]);
|
|
503
|
+
native.setStatusItem(item, { title: '', visible: false }); // in-place patch
|
|
504
|
+
native.setStatusItemMenu(item, null); // back to click events
|
|
505
|
+
native.removeStatusItem(item);
|
|
506
|
+
```
|
|
507
|
+
|
|
508
|
+
Images are **template** by default (`imageTemplate: false` keeps their colours),
|
|
509
|
+
so a bitmap icon follows the bar's light/dark the way a symbol does; a surface's
|
|
510
|
+
bitmap is taken at the surface's scale, and `imageSize: [w, h]` overrides the
|
|
511
|
+
size in points. With a menu set, a left or right click tracks the menu and no
|
|
512
|
+
click event fires; a middle click is reported either way. The item stays in
|
|
513
|
+
the bar until `removeStatusItem`, whatever happens to the handle, and it is
|
|
514
|
+
visible at creation unless told otherwise — AppKit's own memory of a hidden
|
|
515
|
+
item (user defaults, by creation order) does not carry over.
|
|
516
|
+
|
|
517
|
+
For tests: `statusItemInfo(item)` returns what the bar shows (title, tooltip,
|
|
518
|
+
visibility, image, length, the menu in `mainMenuInfo`'s shape, the screen
|
|
519
|
+
rect), `activateStatusItemMenuItem(item, [i, j, ...])` fires a menu item by
|
|
520
|
+
index path, `clickStatusItem(item, kind)` posts a real press-and-release into
|
|
521
|
+
the item's window (pump afterwards; declined for left/right while a menu is
|
|
522
|
+
set, since that click would open it), and `snapshotStatusItem(item, file)`
|
|
523
|
+
writes the composited item to a PNG.
|
|
524
|
+
|
|
525
|
+
## Dock & app presence
|
|
526
|
+
|
|
527
|
+
The handful of things an app shows outside its own windows — the Dock tile and the name
|
|
528
|
+
the Dock, the ⌘-Tab switcher and the menu bar print for it — as flat natives on
|
|
529
|
+
`ca.native`. Mechanism only: counts, reasons and timing stay in the renderer.
|
|
530
|
+
|
|
531
|
+
```js
|
|
532
|
+
const { native } = require('@windowkit/appkit');
|
|
533
|
+
|
|
534
|
+
// Activation policy. Decide it before the first window so an agent app never
|
|
535
|
+
// flashes a Dock tile: 'regular' (Dock tile, menu bar, ⌘-Tab entry),
|
|
536
|
+
// 'accessory' (none of those, windows still work — LSUIElement), 'prohibited'.
|
|
537
|
+
native.initApp({ activationPolicy: 'accessory' });
|
|
538
|
+
native.setActivationPolicy('regular'); // live switch afterwards -> bool
|
|
539
|
+
|
|
540
|
+
native.setDockBadge('3'); // NSDockTile.badgeLabel; null clears
|
|
541
|
+
const id = native.requestUserAttention('critical'); // Dock bounce until activated;
|
|
542
|
+
// 'informational' bounces once
|
|
543
|
+
native.cancelUserAttention(id); // ignored while the app is active anyway
|
|
544
|
+
|
|
545
|
+
// Dock menu (right-click the tile): one menu's worth of the item vocabulary
|
|
546
|
+
// setMainMenu takes. Activations arrive on the backend event callback as
|
|
547
|
+
// { type: 'menu-activate', id, menu: 'dock' } — menu-bar items say menu: 'main',
|
|
548
|
+
// status-item menus menu: 'status'.
|
|
549
|
+
native.setDockMenu([{ id: 7, title: 'New Window' }, { separator: true },
|
|
550
|
+
{ id: 8, title: 'Recent', items: [{ id: 9, title: '…' }] }]);
|
|
551
|
+
native.setDockMenu(null);
|
|
552
|
+
|
|
553
|
+
// The display name. Best-effort: an unbundled process (node, bun) is renamed in
|
|
554
|
+
// LaunchServices' record of it, which is what the Dock and the switcher read; a
|
|
555
|
+
// bundle's Info.plist wins when it declares CFBundleName/CFBundleDisplayName (-> false).
|
|
556
|
+
native.setAppName('My App');
|
|
557
|
+
|
|
558
|
+
native.appInfo(); // -> { activationPolicy, name, dockBadge, active }
|
|
559
|
+
```
|
|
560
|
+
|
|
561
|
+
`dockMenuInfo()` and `activateDockMenuItem([i, j, …])` mirror `mainMenuInfo()` and
|
|
562
|
+
`activateMenuItem()` for tests; both go through the delegate method the Dock itself calls.
|
|
563
|
+
|
|
564
|
+
## Desktop notifications (UNUserNotificationCenter)
|
|
565
|
+
|
|
566
|
+
Banners, the Notification Center list and action buttons through the
|
|
567
|
+
`UserNotifications` framework — the macOS counterpart of freedesktop's
|
|
568
|
+
`org.freedesktop.Notifications`, and the API that replaced the deprecated
|
|
569
|
+
`NSUserNotification`. Mechanism only: what to say, when to ask, and what to do
|
|
570
|
+
with a refusal stay in the renderer.
|
|
571
|
+
|
|
572
|
+
```js
|
|
573
|
+
const { notifications, native } = require('@windowkit/appkit');
|
|
574
|
+
|
|
575
|
+
const s = await notifications.settings();
|
|
576
|
+
// { available: false, bundleIdentifier: null, reason } — a bare `node`: fall to another rung
|
|
577
|
+
// { available: true, bundleIdentifier, authorizationStatus, — 'notDetermined' | 'denied' | 'authorized' | 'provisional'
|
|
578
|
+
// alert, sound, badge, notificationCenter, lockScreen, — 'notSupported' | 'disabled' | 'enabled'
|
|
579
|
+
// criticalAlert, alertStyle, showPreviews, timeSensitive }
|
|
580
|
+
|
|
581
|
+
await notifications.requestAuthorization(['alert', 'sound', 'badge']); // the system prompt, once per app -> granted
|
|
582
|
+
notifications.setCategories([
|
|
583
|
+
{ id: 'download', actions: [{ id: 'open', title: 'Open', foreground: true },
|
|
584
|
+
{ id: 'trash', title: 'Delete', destructive: true }] },
|
|
585
|
+
]);
|
|
586
|
+
const id = await notifications.post({ title: 'Export finished', body: 'report.pdf — 2.4 MB',
|
|
587
|
+
sound: 'default', categoryId: 'download',
|
|
588
|
+
userInfo: { path: '/tmp/report.pdf' } });
|
|
589
|
+
await notifications.update(id, { title: 'Export finished', body: 'opened' }); // same identifier: replaced in place
|
|
590
|
+
notifications.remove(id); // out of Notification Center
|
|
591
|
+
|
|
592
|
+
native.setBackendEventCallback((ev) => {
|
|
593
|
+
// 'notification-action' { identifier, actionId, categoryId, userInfo } actionId 'default' = a click on the banner
|
|
594
|
+
// 'notification-dismissed' { identifier, reason: 'dismissed', categoryId, userInfo }
|
|
595
|
+
});
|
|
596
|
+
|
|
597
|
+
// the natives underneath, callback-shaped
|
|
598
|
+
native.notificationSettings(cb); // never throws; cb(settings) once, asynchronously
|
|
599
|
+
native.requestNotificationAuthorization(options, cb); // cb(granted, error)
|
|
600
|
+
native.setNotificationCategories(categories); // replaces the set
|
|
601
|
+
native.postNotification(props, cb?) -> identifier; // cb(error | null) once the system has taken it
|
|
602
|
+
native.updateNotification(identifier, props, cb?); // = post with that identifier
|
|
603
|
+
native.removeNotification(identifier | [identifiers]); // delivered and pending
|
|
604
|
+
native.deliveredNotifications(cb); native.notificationCategories(cb); // readback
|
|
605
|
+
native.postNotificationResponse({ identifier, actionId?, dismissed?, ... }); // test-only: a response as the
|
|
606
|
+
// delegate would queue it (no bundle needed)
|
|
607
|
+
```
|
|
608
|
+
|
|
609
|
+
- **The bundle-identity constraint.** The system attributes every banner to an
|
|
610
|
+
app bundle — a `CFBundleIdentifier` Launch Services can see — and
|
|
611
|
+
`UNUserNotificationCenter` raises (`bundleProxyForCurrentProcess is nil`) in
|
|
612
|
+
a process that is none, which is what a bare `node` is. The centre is probed
|
|
613
|
+
once, at `require` time, behind that check; the outcome is
|
|
614
|
+
`settings().available`, with the reason when false. Every other call throws
|
|
615
|
+
an `Error` in that state — never a silent drop — so check `available` and
|
|
616
|
+
fall to another rung (`osascript display notification`, say). To run as a
|
|
617
|
+
bundle, put the executable in `Name.app/Contents/MacOS/` with an
|
|
618
|
+
`Info.plist` that names it and carries `CFBundleIdentifier`, and sign it
|
|
619
|
+
(`codesign --force --deep --sign - Name.app` is enough locally).
|
|
620
|
+
- **Authorization** is the system's prompt, shown once per bundle id; until it
|
|
621
|
+
is granted a post is refused with `UNErrorCodeNotificationsNotAllowed`
|
|
622
|
+
(`error.code === 1`, `error.domain === 'UNErrorDomain'`), and the system
|
|
623
|
+
keeps no categories for the app (`notificationCategories` reads back
|
|
624
|
+
empty). The bridge keeps the last set and hands it over again when a
|
|
625
|
+
request is granted.
|
|
626
|
+
- **The delegate** is installed at `require` time, before `initApp()` finishes
|
|
627
|
+
launching, so a click that launched the app is delivered too. Responses are
|
|
628
|
+
marshalled onto node's loop and emitted through the backend callback;
|
|
629
|
+
anything that arrives before `setBackendEventCallback` is held and replayed
|
|
630
|
+
at the start of the next `pump2()`, ahead of that tick's input. While the
|
|
631
|
+
app is frontmost, `willPresent` still shows the banner (list and sound too).
|
|
632
|
+
- **Dismissals.** The system reports an explicit dismissal only for a category
|
|
633
|
+
carrying `UNNotificationCategoryOptionCustomDismissAction`; every category
|
|
634
|
+
set here carries it (`customDismissAction: false` opts out), and a
|
|
635
|
+
notification with no `categoryId` is filed under a bridge-owned category
|
|
636
|
+
that has it. A banner that times out into Notification Center, or is
|
|
637
|
+
removed by `removeNotification`, is not reported by the system and produces
|
|
638
|
+
no event. `'default'` is the `actionId` of a click on the banner itself, so
|
|
639
|
+
it is not a name for an action of your own.
|
|
640
|
+
- `userInfo` is opaque: `JSON.stringify`'d on the way in and parsed back on
|
|
641
|
+
the way out, so whatever JSON can carry round-trips exactly.
|
|
642
|
+
|
|
643
|
+
## Accessibility display options (reduce motion)
|
|
644
|
+
|
|
645
|
+
System Settings › Accessibility › Display, as `NSWorkspace` reports it — the switch a renderer
|
|
646
|
+
reads before it starts anything that moves on its own ([#31](https://github.com/windowkit/appkit/issues/31)):
|
|
647
|
+
|
|
648
|
+
```js
|
|
649
|
+
native.accessibilityDisplayOptions();
|
|
650
|
+
// -> { reduceMotion, reduceTransparency, increaseContrast, differentiateWithoutColor, invertColors }
|
|
651
|
+
accessibility.displayOptions(); // the same, on the wrapper
|
|
652
|
+
```
|
|
653
|
+
|
|
654
|
+
A change arrives as a backend event with the same five fields:
|
|
655
|
+
|
|
656
|
+
```js
|
|
657
|
+
{ type: 'accessibility-display-changed', reduceMotion, reduceTransparency, increaseContrast,
|
|
658
|
+
differentiateWithoutColor, invertColors }
|
|
659
|
+
```
|
|
660
|
+
|
|
661
|
+
It comes from `NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification`, delivered on the
|
|
662
|
+
main thread inside a `pump2()` like every other event. Nothing is held for a listener that is
|
|
663
|
+
not there yet — a setting is a fact rather than a message — so **install the callback, then
|
|
664
|
+
query**: the query is the state, the events are what changes it from then on.
|
|
665
|
+
|
|
666
|
+
Mechanism only: what to do with `reduceMotion` is the renderer's (react-x11: looping
|
|
667
|
+
`animation`s never start, a `transition` that ends still runs).
|
|
668
|
+
|
|
669
|
+
`native.postAccessibilityDisplayChange()` posts the same notification through the same centre,
|
|
670
|
+
so the observer path can be exercised without touching the user's settings — test-only, like
|
|
671
|
+
`postAppleEvent`; `test/accessibility-display.js` is the check.
|
|
672
|
+
|
|
163
673
|
## Mapping to a React reconciler
|
|
164
674
|
|
|
165
675
|
The shape of a host config on top of this:
|
package/binding.gyp
CHANGED
|
@@ -2,7 +2,12 @@
|
|
|
2
2
|
"targets": [
|
|
3
3
|
{
|
|
4
4
|
"target_name": "calayers",
|
|
5
|
-
"sources": [
|
|
5
|
+
"sources": [
|
|
6
|
+
"src/addon.mm",
|
|
7
|
+
"src/backend.mm",
|
|
8
|
+
"src/permissions.mm",
|
|
9
|
+
"src/notifications.mm"
|
|
10
|
+
],
|
|
6
11
|
"include_dirs": [
|
|
7
12
|
"<!@(node -p \"require('node-addon-api').include\")"
|
|
8
13
|
],
|
|
@@ -19,7 +24,13 @@
|
|
|
19
24
|
"-framework CoreText",
|
|
20
25
|
"-framework CoreGraphics",
|
|
21
26
|
"-framework ImageIO",
|
|
22
|
-
"-framework IOSurface"
|
|
27
|
+
"-framework IOSurface",
|
|
28
|
+
"-framework UniformTypeIdentifiers",
|
|
29
|
+
"-framework AVFoundation",
|
|
30
|
+
"-framework CoreLocation",
|
|
31
|
+
"-framework IOKit",
|
|
32
|
+
"-framework ApplicationServices",
|
|
33
|
+
"-framework UserNotifications"
|
|
23
34
|
]
|
|
24
35
|
}
|
|
25
36
|
}
|