@windowkit/appkit 0.3.0 → 0.5.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
@@ -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 and
5
- native control bezels. It is the macOS half of [react-x11][react-x11].
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,83 @@ 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 generic RGB, 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. `speed: 0, timeOffset: t` plus a read is how a curve is sampled without
188
+ waiting for it, which is how `test/animation.js` checks every curve above.
189
+
190
+ **The end of an animation.** With an `id`, the animation's delegate forwards
191
+ `animationDidStop:finished:` through `setBackendEventCallback` as
192
+
193
+ ```js
194
+ { type: 'animation-end', id, key, keyPath, finished }
195
+ ```
196
+
197
+ `finished` is `false` for an animation that was removed (`removeAnimation`,
198
+ `removeAllAnimations`) or whose layer left the tree before it ran out. It arrives inside a
199
+ `pump2()`, like a window delegate's events. Without an `id` no delegate is set and nothing is
200
+ reported.
201
+
121
202
  ## Native controls
122
203
 
123
204
  There is no WindowServer API for control drawing — AppKit draws controls in-process via
@@ -160,6 +241,425 @@ vibrancy materials need private API to reproduce; expose real `NSMenu` instead.
160
241
  `native.postMouseEvent(win, 'down'|'up'|'move'|'drag', x, y)` synthesizes events through
161
242
  the real pump — used by the demo's self-test (`CAL_CLICKS="x,y;x,y" npm run demo`).
162
243
 
244
+ ## App lifecycle: open-URL, open-file, reopen, quit
245
+
246
+ The OS talks to the application as a whole through Apple Events: a URL for a scheme
247
+ the bundle registers (`kInternetEventClass/kAEGetURL`), a document handed over by the
248
+ Finder (`kCoreEventClass/kAEOpenDocuments`), a second launch of a running app
249
+ (`kAEReopenApplication`), and Quit from the Dock, the app menu or a logout
250
+ (`kAEQuitApplication`). `native.initApp()` installs an `NSApplicationDelegate` that
251
+ forwards them to the backend event callback and decides nothing itself:
252
+
253
+ | event | payload | from |
254
+ | ------------------ | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
255
+ | `app-open-urls` | `{ urls: [string] }` | `application:openURLs:` — scheme URLs as sent, documents as `file://` URLs |
256
+ | `app-reopen` | `{ hasVisibleWindows }` | `applicationShouldHandleReopen:`, answered NO — what a second launch means is the renderer's call |
257
+ | `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 |
258
+
259
+ ```js
260
+ native.initApp(); // first: the delegate has to precede finishLaunching
261
+ native.setBackendEventCallback((ev) => {
262
+ if (ev.type === 'app-open-urls') route(ev.urls);
263
+ if (ev.type === 'app-reopen' && !ev.hasVisibleWindows) showMainWindow();
264
+ if (ev.type === 'app-quit-request') process.exit(0);
265
+ });
266
+ setInterval(() => native.pump2(), 16);
267
+ ```
268
+
269
+ Launch Services delivers the launching Apple Event inside `finishLaunching` — that is,
270
+ inside `initApp()`, before any callback exists. Whatever arrives with nobody listening
271
+ is held and replayed, in order, on the first `pump2()` that has a callback, ahead of
272
+ that tick's input. Registering the scheme itself is an install step, not runtime code:
273
+ `CFBundleURLTypes` (and `CFBundleDocumentTypes` for files) in the bundle's
274
+ `Info.plist`.
275
+
276
+ `native.postAppleEvent('open-url', url)`, `('open-documents', [paths])`, `('reopen')`
277
+ and `('quit')` build the corresponding Apple Event and dispatch it through
278
+ `NSAppleEventManager` as if it had just arrived — how `npm test` exercises the
279
+ delegate without a bundle.
280
+
281
+ ## File panels
282
+
283
+ Open and save dialogs are real `NSOpenPanel` / `NSSavePanel`s owned by this process's
284
+ `NSApplication` — not a separate `osascript` — so they can run as a sheet on the window
285
+ that asked, every filter the OS type database knows gets through, and a cancel is a
286
+ cancel rather than a failed subprocess.
287
+
288
+ ```js
289
+ const { native } = require('@windowkit/appkit');
290
+
291
+ // With a window handle the panel is a sheet on it: the pump keeps running and the
292
+ // callback fires on a later tick. Without one it is app-modal: the call blocks in
293
+ // AppKit's modal loop until the panel is dismissed, and the callback runs before
294
+ // the call returns.
295
+ native.openPanel({
296
+ window: win._h, // omit for app-modal
297
+ directory: false, // true: choose folders instead of files
298
+ multiple: true,
299
+ message: 'Pick some images',
300
+ prompt: 'Import', // the confirm button's label
301
+ directoryURL: process.env.HOME,
302
+ allowedContentTypes: ['public.png', native.contentTypeFor({ mime: 'image/jpeg' })],
303
+ }, (paths) => { /* ['/Users/…/a.png', …], or null on cancel */ });
304
+
305
+ native.savePanel({
306
+ window: win._h,
307
+ nameFieldStringValue: 'Untitled.txt',
308
+ allowedContentTypes: [native.contentTypeFor({ extension: 'txt' })],
309
+ }, (path) => { /* '/Users/…/Untitled.txt', or null on cancel */ });
310
+ ```
311
+
312
+ Both take `title`, `message`, `prompt`, `directoryURL` (a path or `file:` URL),
313
+ `allowedContentTypes` and `canCreateDirectories`; the open panel adds `directory` and
314
+ `multiple`, the save panel `nameFieldStringValue`. Both return a panel handle:
315
+ `native.cancelPanel(handle)` dismisses a sheet that is still up (its callback then gets
316
+ `null`) and reports whether there was one, and `destroyWindow2` answers any sheet still
317
+ attached to the window the same way, so no callback is left waiting.
318
+
319
+ Filters are UTType identifiers, the shape `NSSavePanel.allowedContentTypes` wants;
320
+ mapping extensions and MIME types onto them is the renderer's policy, and
321
+ `native.contentTypeFor({ extension })` / `({ mime })` does the lookup in the OS's own
322
+ database (`'png'` → `'public.png'`, `'application/json'` → `'public.json'`; an
323
+ extension nobody has declared still gets a dynamic type that matches exactly that
324
+ extension). An absent or empty list means any file, and so does a list the OS
325
+ recognises nothing of.
326
+
327
+
328
+ ## Drag and drop
329
+
330
+ The backend surface's windows (`native.createWindow2`) take drops and begin
331
+ drags through the hosting view — `NSDraggingDestination` and
332
+ `NSDraggingSource` — with every phase reported through the backend event
333
+ callback, the window's number attached, like every other window event.
334
+ Mechanism only: the renderer keeps the policy (what to accept, what a drop
335
+ means). Type names cross the boundary as pasteboard types — UTIs such as
336
+ `public.utf8-plain-text`, `public.file-url`, `public.png` — and mapping a MIME
337
+ vocabulary onto them is the renderer's job; `pasteboardTypeForMIME(mime)` and
338
+ `pasteboardTypeInfo(uti)` read the OS's own table for it (a MIME type no
339
+ declared type claims gets a `dyn.*` identifier that every process computes
340
+ alike).
341
+
342
+ ```js
343
+ const { native } = require('@windowkit/appkit');
344
+ const win = native.createWindow2({ width: 640, height: 480, title: 'drop here' });
345
+
346
+ // destination: register, then answer AppKit's questions from inside the callback
347
+ native.registerDropTypes(win, ['public.file-url', 'public.utf8-plain-text']);
348
+ native.setBackendEventCallback((ev) => {
349
+ switch (ev.type) {
350
+ case 'drag-enter': // { windowNumber, x, y, gx, gy, types, itemCount, sourceMask,
351
+ case 'drag-over': // operations, local, sourceWindowNumber?, sequence }
352
+ native.setDropResponse(win, { accept: ev.types.includes('public.file-url'),
353
+ operation: 'copy' });
354
+ break;
355
+ case 'drag-exit': // may carry no position: a drag cancelled mid-air
356
+ break;
357
+ case 'drag-perform': // the drop — read the payload now
358
+ for (let i = 0; i < ev.itemCount; i++)
359
+ console.log(native.dragItemString(i, 'public.file-url'));
360
+ break;
361
+ case 'drag-session-began': // source side: x/y in global top-left coordinates
362
+ case 'drag-session-moved':
363
+ case 'drag-session-ended': // + { operation: 'copy' | 'move' | ... | 'none', dropped }
364
+ break;
365
+ }
366
+ });
367
+
368
+ // source: from a press, once the renderer's own threshold says it is a drag
369
+ native.beginDrag(win, {
370
+ x: press.x, y: press.y, // content coords
371
+ items: [{ 'public.utf8-plain-text': 'hello', 'public.png': null }], // one item; null = lazy
372
+ provide: (type, index) => renderPng(), // asked when a consumer reads the promise
373
+ operations: ['copy', 'move'],
374
+ surface: previewSurface, imageX: node.x, imageY: node.y, // or image: text.render(...)
375
+ });
376
+ ```
377
+
378
+ - **`setDropResponse` answers the question being asked.** The callback runs
379
+ synchronously inside `draggingEntered:` / `draggingUpdated:`, so a response
380
+ set during `drag-enter` or `drag-over` is what AppKit gets back for that
381
+ event. It stays in force for the `drag-over` events that follow until
382
+ changed, and resets to a refusal when a new drag enters. `{ accept: false }`
383
+ during `drag-perform` withdraws a drop after a look at the payload.
384
+ `operation` absent picks copy, move, link, generic, private, delete — the
385
+ first the source allows.
386
+ - **`types` is the pasteboard's union, promised translations included**: a
387
+ `public.png` also appears as `public.tiff` and the legacy `Apple PNG
388
+ pasteboard type`, a file URL as `NSFilenamesPboardType`. `dragItems()` lists
389
+ the declared types per item; `dragItemData(index, type)` returns a `Buffer`
390
+ and `dragItemString(index, type)` a string, `null` when the item has no such
391
+ representation. A Finder drag of three files is three items of one
392
+ `public.file-url` each. Read during `drag-perform`: the payload is the
393
+ source's promise, and a source may withdraw it once its session has ended.
394
+ - **`beginDrag` returns at once.** The session is begun from the real
395
+ mouse-down when the pointer is still down in the window (the event the
396
+ renderer's threshold logic is reacting to), and runs on AppKit's own
397
+ tracking from there: the pointer's `mousemove` / `mouseup` stop arriving,
398
+ and `drag-session-ended` is the release. `items` is one entry per dragging
399
+ item, each a map of type → string | bytes | `null`, where `null` is a
400
+ promise answered by `provide(type, index)` when a consumer reads it — so a
401
+ representation nobody asks for is never built. `operations` is the source's
402
+ mask (`operationsOutside` for other applications when it differs),
403
+ `ignoreModifiers` stops Option/Command turning it into copy/link, and
404
+ `slideBack` (default on) animates a refused drop home. The image is a
405
+ `surface` handle or a CGImage `image` (the `text.render` / `controls.render`
406
+ result works whole), placed at `imageX` / `imageY` — centred on the press by
407
+ default — at its own size unless `imageWidth` / `imageHeight` say otherwise.
408
+ A drop on one of our own windows arrives through the destination events of
409
+ that window with `local: true` and the source's `sourceWindowNumber`.
410
+ - **`postDragEvent(win, phase, { x, y, items, operations, local })`** drives
411
+ the destination methods with a dragging info of the bridge's own over a
412
+ private pasteboard — what `postMouseEvent` is to clicks. `'enter'` and
413
+ `'over'` answer the operation the view returned (`'none'` when it refused),
414
+ `'drop'` runs prepare + perform + conclude and answers whether the drop was
415
+ taken. The CI smoke test and a renderer's headless tests drive drops this
416
+ way.
417
+
418
+
419
+ ## Privacy authorizations (TCC)
420
+
421
+ macOS decides per process whether an app may use the camera, microphone,
422
+ screen, accessibility, input monitoring or location, or send Apple Events to
423
+ another app. The bridge is mechanism only: read the status, raise the system
424
+ prompt where a framework offers one, and deep-link to the Settings pane where
425
+ it does not. Policy — when to ask, what to do with a refusal — stays in the
426
+ renderer.
427
+
428
+ ```js
429
+ const { permissions, native } = require('@windowkit/appkit');
430
+
431
+ permissions.status('camera'); // 'authorized' | 'denied' | 'restricted' | 'notDetermined'
432
+ await permissions.request('microphone'); // raises the system prompt; resolves to granted (boolean)
433
+ permissions.status('automation', { target: 'com.apple.finder' }); // Apple Events, per target app
434
+ permissions.openSettings('screen-recording'); // System Settings › Privacy & Security › Screen Recording
435
+
436
+ // the natives underneath, callback-shaped
437
+ native.authorizationStatus(kind, opts?); // never prompts
438
+ native.requestAuthorization(kind, opts?, (granted, status) => {}); // once, asynchronously
439
+ native.openPrivacySettings(kind?); // no kind: the Privacy pane itself
440
+ ```
441
+
442
+ | kind | status | request | notes |
443
+ | ------------------------ | ---------------------------------------------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
444
+ | `camera`, `microphone` | `AVCaptureDevice authorizationStatusForMediaType:` | `requestAccessForMediaType:` | all four statuses; the prompt is in-process and the answer arrives when the user clicks |
445
+ | `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 |
446
+ | `accessibility` | `AXIsProcessTrusted` | `AXIsProcessTrustedWithOptions` + prompt | a bool, so never `notDetermined`; go-to-Settings dialog, resolves at once, the grant applies live |
447
+ | `input-monitoring` | `IOHIDCheckAccess` (listen) | `IOHIDRequestAccess` | granted / denied / unknown → `notDetermined`; the request posts the prompt and resolves at once, `notDetermined` while it is still up |
448
+ | `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 |
449
+ | `location` | `CLLocationManager.authorizationStatus` | `requestWhenInUseAuthorization` | the answer comes through the delegate on the main run loop, i.e. while `app.run()` is pumping |
450
+
451
+ - A request answers **once, asynchronously** — never inside the call — and
452
+ holds the event loop open until then, like pending I/O.
453
+ - **Attribution.** A bare `node` process is attributed to its *responsible
454
+ process* (Terminal, an IDE) or to `node` itself, and prompts with no
455
+ usage-description strings. A bundled app must carry the keys
456
+ (`NSCameraUsageDescription`, `NSMicrophoneUsageDescription`,
457
+ `NSLocationUsageDescription`, `NSAppleEventsUsageDescription`); without
458
+ them the request never prompts, or TCC ends the process.
459
+ - **Folders** (Desktop, Documents, Downloads) need nothing native: reading the
460
+ directory *is* the prompt and `EPERM` is the denial. `openSettings` also
461
+ takes `'files-and-folders'` and `'full-disk-access'` for their panes.
462
+ - `restricted` is MDM or parental controls: the user cannot grant it.
463
+ ## Status item (the menu-bar extra)
464
+
465
+ `NSStatusItem` is the tray. An item shows an image or a title (or both) in the
466
+ system status bar with a tooltip, and either owns a menu or reports clicks. The
467
+ menu takes the same item spec `setMainMenu` does, so the tray, the app menu bar
468
+ and — through react-x11's dbusmenu adapter — a Linux panel share one authoring
469
+ model; activations arrive as the same `menu-activate` events, tagged `menu: 'status'`.
470
+
471
+ ```js
472
+ const { native } = require('@windowkit/appkit');
473
+ native.setBackendEventCallback((ev) => {
474
+ if (ev.type === 'status-item-click') { // only without a menu
475
+ // ev.statusItem === item; ev.kind: 'left' | 'right' | 'middle'
476
+ // ev.x/y/width/height: the item's screen rect, top-left global — the
477
+ // anchor for a popup of your own; plus shift/control/option/command
478
+ }
479
+ if (ev.type === 'menu-activate') { /* ev.id from the spec below */ }
480
+ });
481
+
482
+ const item = native.createStatusItem({
483
+ image: 'bell.badge', // SF Symbol name — or a surface handle, or PNG bytes
484
+ title: '3', // beside the image, or alone
485
+ tooltip: 'Notifications',
486
+ length: 'variable', // 'variable' | 'square' | points
487
+ });
488
+ native.setStatusItemMenu(item, [ // setMainMenu's item vocabulary
489
+ { id: 1, title: 'Open', iconName: 'macwindow' },
490
+ { separator: true },
491
+ { id: 2, title: 'Quit', key: 'q' },
492
+ ]);
493
+ native.setStatusItem(item, { title: '', visible: false }); // in-place patch
494
+ native.setStatusItemMenu(item, null); // back to click events
495
+ native.removeStatusItem(item);
496
+ ```
497
+
498
+ Images are **template** by default (`imageTemplate: false` keeps their colours),
499
+ so a bitmap icon follows the bar's light/dark the way a symbol does; a surface's
500
+ bitmap is taken at the surface's scale, and `imageSize: [w, h]` overrides the
501
+ size in points. With a menu set, a left or right click tracks the menu and no
502
+ click event fires; a middle click is reported either way. The item stays in
503
+ the bar until `removeStatusItem`, whatever happens to the handle, and it is
504
+ visible at creation unless told otherwise — AppKit's own memory of a hidden
505
+ item (user defaults, by creation order) does not carry over.
506
+
507
+ For tests: `statusItemInfo(item)` returns what the bar shows (title, tooltip,
508
+ visibility, image, length, the menu in `mainMenuInfo`'s shape, the screen
509
+ rect), `activateStatusItemMenuItem(item, [i, j, ...])` fires a menu item by
510
+ index path, `clickStatusItem(item, kind)` posts a real press-and-release into
511
+ the item's window (pump afterwards; declined for left/right while a menu is
512
+ set, since that click would open it), and `snapshotStatusItem(item, file)`
513
+ writes the composited item to a PNG.
514
+
515
+ ## Dock & app presence
516
+
517
+ The handful of things an app shows outside its own windows — the Dock tile and the name
518
+ the Dock, the ⌘-Tab switcher and the menu bar print for it — as flat natives on
519
+ `ca.native`. Mechanism only: counts, reasons and timing stay in the renderer.
520
+
521
+ ```js
522
+ const { native } = require('@windowkit/appkit');
523
+
524
+ // Activation policy. Decide it before the first window so an agent app never
525
+ // flashes a Dock tile: 'regular' (Dock tile, menu bar, ⌘-Tab entry),
526
+ // 'accessory' (none of those, windows still work — LSUIElement), 'prohibited'.
527
+ native.initApp({ activationPolicy: 'accessory' });
528
+ native.setActivationPolicy('regular'); // live switch afterwards -> bool
529
+
530
+ native.setDockBadge('3'); // NSDockTile.badgeLabel; null clears
531
+ const id = native.requestUserAttention('critical'); // Dock bounce until activated;
532
+ // 'informational' bounces once
533
+ native.cancelUserAttention(id); // ignored while the app is active anyway
534
+
535
+ // Dock menu (right-click the tile): one menu's worth of the item vocabulary
536
+ // setMainMenu takes. Activations arrive on the backend event callback as
537
+ // { type: 'menu-activate', id, menu: 'dock' } — menu-bar items say menu: 'main',
538
+ // status-item menus menu: 'status'.
539
+ native.setDockMenu([{ id: 7, title: 'New Window' }, { separator: true },
540
+ { id: 8, title: 'Recent', items: [{ id: 9, title: '…' }] }]);
541
+ native.setDockMenu(null);
542
+
543
+ // The display name. Best-effort: an unbundled process (node, bun) is renamed in
544
+ // LaunchServices' record of it, which is what the Dock and the switcher read; a
545
+ // bundle's Info.plist wins when it declares CFBundleName/CFBundleDisplayName (-> false).
546
+ native.setAppName('My App');
547
+
548
+ native.appInfo(); // -> { activationPolicy, name, dockBadge, active }
549
+ ```
550
+
551
+ `dockMenuInfo()` and `activateDockMenuItem([i, j, …])` mirror `mainMenuInfo()` and
552
+ `activateMenuItem()` for tests; both go through the delegate method the Dock itself calls.
553
+
554
+ ## Desktop notifications (UNUserNotificationCenter)
555
+
556
+ Banners, the Notification Center list and action buttons through the
557
+ `UserNotifications` framework — the macOS counterpart of freedesktop's
558
+ `org.freedesktop.Notifications`, and the API that replaced the deprecated
559
+ `NSUserNotification`. Mechanism only: what to say, when to ask, and what to do
560
+ with a refusal stay in the renderer.
561
+
562
+ ```js
563
+ const { notifications, native } = require('@windowkit/appkit');
564
+
565
+ const s = await notifications.settings();
566
+ // { available: false, bundleIdentifier: null, reason } — a bare `node`: fall to another rung
567
+ // { available: true, bundleIdentifier, authorizationStatus, — 'notDetermined' | 'denied' | 'authorized' | 'provisional'
568
+ // alert, sound, badge, notificationCenter, lockScreen, — 'notSupported' | 'disabled' | 'enabled'
569
+ // criticalAlert, alertStyle, showPreviews, timeSensitive }
570
+
571
+ await notifications.requestAuthorization(['alert', 'sound', 'badge']); // the system prompt, once per app -> granted
572
+ notifications.setCategories([
573
+ { id: 'download', actions: [{ id: 'open', title: 'Open', foreground: true },
574
+ { id: 'trash', title: 'Delete', destructive: true }] },
575
+ ]);
576
+ const id = await notifications.post({ title: 'Export finished', body: 'report.pdf — 2.4 MB',
577
+ sound: 'default', categoryId: 'download',
578
+ userInfo: { path: '/tmp/report.pdf' } });
579
+ await notifications.update(id, { title: 'Export finished', body: 'opened' }); // same identifier: replaced in place
580
+ notifications.remove(id); // out of Notification Center
581
+
582
+ native.setBackendEventCallback((ev) => {
583
+ // 'notification-action' { identifier, actionId, categoryId, userInfo } actionId 'default' = a click on the banner
584
+ // 'notification-dismissed' { identifier, reason: 'dismissed', categoryId, userInfo }
585
+ });
586
+
587
+ // the natives underneath, callback-shaped
588
+ native.notificationSettings(cb); // never throws; cb(settings) once, asynchronously
589
+ native.requestNotificationAuthorization(options, cb); // cb(granted, error)
590
+ native.setNotificationCategories(categories); // replaces the set
591
+ native.postNotification(props, cb?) -> identifier; // cb(error | null) once the system has taken it
592
+ native.updateNotification(identifier, props, cb?); // = post with that identifier
593
+ native.removeNotification(identifier | [identifiers]); // delivered and pending
594
+ native.deliveredNotifications(cb); native.notificationCategories(cb); // readback
595
+ native.postNotificationResponse({ identifier, actionId?, dismissed?, ... }); // test-only: a response as the
596
+ // delegate would queue it (no bundle needed)
597
+ ```
598
+
599
+ - **The bundle-identity constraint.** The system attributes every banner to an
600
+ app bundle — a `CFBundleIdentifier` Launch Services can see — and
601
+ `UNUserNotificationCenter` raises (`bundleProxyForCurrentProcess is nil`) in
602
+ a process that is none, which is what a bare `node` is. The centre is probed
603
+ once, at `require` time, behind that check; the outcome is
604
+ `settings().available`, with the reason when false. Every other call throws
605
+ an `Error` in that state — never a silent drop — so check `available` and
606
+ fall to another rung (`osascript display notification`, say). To run as a
607
+ bundle, put the executable in `Name.app/Contents/MacOS/` with an
608
+ `Info.plist` that names it and carries `CFBundleIdentifier`, and sign it
609
+ (`codesign --force --deep --sign - Name.app` is enough locally).
610
+ - **Authorization** is the system's prompt, shown once per bundle id; until it
611
+ is granted a post is refused with `UNErrorCodeNotificationsNotAllowed`
612
+ (`error.code === 1`, `error.domain === 'UNErrorDomain'`), and the system
613
+ keeps no categories for the app (`notificationCategories` reads back
614
+ empty). The bridge keeps the last set and hands it over again when a
615
+ request is granted.
616
+ - **The delegate** is installed at `require` time, before `initApp()` finishes
617
+ launching, so a click that launched the app is delivered too. Responses are
618
+ marshalled onto node's loop and emitted through the backend callback;
619
+ anything that arrives before `setBackendEventCallback` is held and replayed
620
+ at the start of the next `pump2()`, ahead of that tick's input. While the
621
+ app is frontmost, `willPresent` still shows the banner (list and sound too).
622
+ - **Dismissals.** The system reports an explicit dismissal only for a category
623
+ carrying `UNNotificationCategoryOptionCustomDismissAction`; every category
624
+ set here carries it (`customDismissAction: false` opts out), and a
625
+ notification with no `categoryId` is filed under a bridge-owned category
626
+ that has it. A banner that times out into Notification Center, or is
627
+ removed by `removeNotification`, is not reported by the system and produces
628
+ no event. `'default'` is the `actionId` of a click on the banner itself, so
629
+ it is not a name for an action of your own.
630
+ - `userInfo` is opaque: `JSON.stringify`'d on the way in and parsed back on
631
+ the way out, so whatever JSON can carry round-trips exactly.
632
+
633
+ ## Accessibility display options (reduce motion)
634
+
635
+ System Settings › Accessibility › Display, as `NSWorkspace` reports it — the switch a renderer
636
+ reads before it starts anything that moves on its own ([#31](https://github.com/windowkit/appkit/issues/31)):
637
+
638
+ ```js
639
+ native.accessibilityDisplayOptions();
640
+ // -> { reduceMotion, reduceTransparency, increaseContrast, differentiateWithoutColor, invertColors }
641
+ accessibility.displayOptions(); // the same, on the wrapper
642
+ ```
643
+
644
+ A change arrives as a backend event with the same five fields:
645
+
646
+ ```js
647
+ { type: 'accessibility-display-changed', reduceMotion, reduceTransparency, increaseContrast,
648
+ differentiateWithoutColor, invertColors }
649
+ ```
650
+
651
+ It comes from `NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification`, delivered on the
652
+ main thread inside a `pump2()` like every other event. Nothing is held for a listener that is
653
+ not there yet — a setting is a fact rather than a message — so **install the callback, then
654
+ query**: the query is the state, the events are what changes it from then on.
655
+
656
+ Mechanism only: what to do with `reduceMotion` is the renderer's (react-x11: looping
657
+ `animation`s never start, a `transition` that ends still runs).
658
+
659
+ `native.postAccessibilityDisplayChange()` posts the same notification through the same centre,
660
+ so the observer path can be exercised without touching the user's settings — test-only, like
661
+ `postAppleEvent`; `test/accessibility-display.js` is the check.
662
+
163
663
  ## Mapping to a React reconciler
164
664
 
165
665
  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": ["src/addon.mm", "src/backend.mm"],
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
  }