noracu 0.2.4 → 0.2.6

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/src/mac-ax.js CHANGED
@@ -1250,14 +1250,71 @@ function opFrontmost(req) {
1250
1250
  }
1251
1251
  return out;
1252
1252
  }
1253
+ // The strips of each display that macOS keeps for the Dock: the display's frame minus its visible frame,
1254
+ // at the bottom, left and right (the top strip is the menu bar). screens: [{ f, v }] — frame and visible
1255
+ // frame in AppKit coordinates (origin bottom-left of the main screen); returns top-left [x, y, w, h].
1256
+ function dockStripsOf(screens) {
1257
+ const mainH = screens.length ? screens[0].f[3] : 0;
1258
+ const out = [];
1259
+ for (const { f, v } of screens) {
1260
+ const [fx, fy, fw] = f, [vx, vy, vw, vh] = v;
1261
+ const tl = (y, h) => mainH - y - h;
1262
+ if (vy > fy) out.push([fx, tl(fy, vy - fy), fw, vy - fy]);
1263
+ if (vx > fx) out.push([fx, tl(vy, vh), vx - fx, vh]);
1264
+ if (fx + fw > vx + vw) out.push([vx + vw, tl(vy, vh), fx + fw - vx - vw, vh]);
1265
+ }
1266
+ return out;
1267
+ }
1268
+ function dockStrips() {
1269
+ const s = $.NSScreen.screens;
1270
+ const screens = [];
1271
+ for (let i = 0; i < Number(s.count); i++) {
1272
+ const sc = s.objectAtIndex(i), f = sc.frame, v = sc.visibleFrame;
1273
+ screens.push({ f: [f.origin.x, f.origin.y, f.size.width, f.size.height].map(Number), v: [v.origin.x, v.origin.y, v.size.width, v.size.height].map(Number) });
1274
+ }
1275
+ return dockStripsOf(screens);
1276
+ }
1277
+ function inRect(x, y, r) { return x >= r[0] && y >= r[1] && x < r[0] + r[2] && y < r[1] + r[3]; }
1278
+ // While a banner or alert shows, Notification Center keeps one full-display window above everything (layer
1279
+ // 23) that lets clicks through except where a notification is drawn (E2 run 2026-11-07, macOS 27.2: a
1280
+ // memory-warning banner at the top right made a point in the middle of the screen read as covered). The
1281
+ // frames of the banners and alerts on screen, from accessibility; null — the whole overlay counts as
1282
+ // covering — when Notification Center's list is open, an element cannot be read, or none is found.
1283
+ function ncDrawnRects() {
1284
+ const a = ncApp();
1285
+ if (!a) return null;
1286
+ const rects = [];
1287
+ let doubt = false;
1288
+ const visit = (el, d) => {
1289
+ if (d > 14 || doubt) return;
1290
+ const v = readNode(el);
1291
+ if (v.__err) { doubt = true; return; }
1292
+ const sr = String(v.AXSubrole || '');
1293
+ if (sr.indexOf('AXNotificationCenter') === 0) {
1294
+ const fr = frameOf(v);
1295
+ if ((sr !== 'AXNotificationCenterBanner' && sr !== 'AXNotificationCenterAlert') || !fr) { doubt = true; return; }
1296
+ rects.push([fr[0] - 4, fr[1] - 4, fr[2] + 8, fr[3] + 8]); // a little margin for the shadow
1297
+ return;
1298
+ }
1299
+ for (const k of v.AXChildren || []) visit(k, d + 1);
1300
+ };
1301
+ for (const w of windowsOf(appElement(a))) visit(w, 0);
1302
+ return doubt || !rects.length ? null : rects;
1303
+ }
1304
+
1253
1305
  // The topmost on-screen window at a point, front to back, as the window server stacks them. Skipped:
1254
1306
  // invisible windows (alpha 0), desktop-level ones (negative layer), and the Dock's full-display overlay,
1255
- // which lets clicks through everywhere — only a Dock window as large as a whole display; the Dock itself
1256
- // (its platter) and other Dock-owned strips do cover what is under them.
1307
+ // which lets clicks through — except over the strip macOS keeps for the Dock, where the Dock is drawn:
1308
+ // there the overlay counts as covering (E2 run 2026-11-07: on macOS 27 the Dock has no window of its own
1309
+ // for its platter, so a point under the Dock read as the window behind it). The strip is the whole width
1310
+ // (or height) the Dock reserves, the gaps beside its platter included. Other Dock-owned windows cover
1311
+ // what is under them. Notification Center's full-display overlay (shown with a banner or alert) is
1312
+ // skipped the same way except over a banner or alert frame (ncDrawnRects), or everywhere when those
1313
+ // frames cannot be told.
1257
1314
  function cgTopAt(x, y) {
1258
1315
  const list = cast($.CGWindowListCopyWindowInfo((1 << 0) | (1 << 4), 0)); // on screen only, no desktop elements
1259
1316
  if (!list) return null;
1260
- let screens = null;
1317
+ let screens = null, strips = null, nc;
1261
1318
  for (let i = 0; i < Number(list.count); i++) {
1262
1319
  const d = list.objectAtIndex(i);
1263
1320
  const g = k => { const o = d.objectForKey(ks(k)); return o && !o.isNil() ? o.js : null; };
@@ -1268,9 +1325,17 @@ function cgTopAt(x, y) {
1268
1325
  if (!b || b.isNil()) continue;
1269
1326
  const [bx, by, bw, bh] = ['X', 'Y', 'Width', 'Height'].map(k => Number(b.objectForKey(ks(k)).js));
1270
1327
  if (bw * bh < 4 || x < bx || y < by || x >= bx + bw || y >= by + bh) continue;
1271
- if (owner === 'Dock') {
1328
+ if (owner === 'Dock' || owner === 'Notification Center') {
1272
1329
  if (!screens) screens = displays().map(s => s.frame);
1273
- if (screens.some(f => rectNear(f, [bx, by, bw, bh], 2))) continue;
1330
+ if (screens.some(f => rectNear(f, [bx, by, bw, bh], 2))) {
1331
+ if (owner === 'Dock') {
1332
+ if (!strips) strips = dockStrips();
1333
+ if (!strips.some(r => inRect(x, y, r))) continue;
1334
+ } else {
1335
+ if (nc === undefined) nc = ncDrawnRects();
1336
+ if (nc && !nc.some(r => inRect(x, y, r))) continue;
1337
+ }
1338
+ }
1274
1339
  }
1275
1340
  return { pid: Number(g('kCGWindowOwnerPID')), owner, layer, wid: Number(g('kCGWindowNumber')) };
1276
1341
  }
@@ -1387,7 +1452,8 @@ function opObserveAfter(req) {
1387
1452
  // selection), AXValue replaces the whole value. No key events, so no input method can re-segment it
1388
1453
  // and the clipboard is not touched. Verified by reading the value back (secure fields cannot be read).
1389
1454
  function opInsertText(req) {
1390
- let el, appEl, how = 'focused', label = 'the focused element';
1455
+ // appName: the app whose focused element is written (no target) — the server names it in its result
1456
+ let el, appEl, how = 'focused', label = 'the focused element', appName;
1391
1457
  if (req.target) {
1392
1458
  const r = resolveTarget(req.target, 3000);
1393
1459
  if (r.error) return fail(notDelivered(r.error));
@@ -1397,7 +1463,8 @@ function opInsertText(req) {
1397
1463
  if (!app) return fail(notDelivered({ code: 'APP_NOT_FOUND', message: req.app ? `no running app named "${req.app}"` : 'no frontmost app' }));
1398
1464
  appEl = appElement(app);
1399
1465
  const f = attr(appEl, 'AXFocusedUIElement');
1400
- if (!f || !f.el) return fail(notDelivered({ code: 'ACTION_NOT_SUPPORTED', message: `"${app.name}" reports no focused element`, details: { kind: 'no_focus' } }));
1466
+ appName = app.name;
1467
+ if (!f || !f.el) return fail(notDelivered({ code: 'ACTION_NOT_SUPPORTED', message: `"${app.name}" reports no focused element`, details: { kind: 'no_focus', app: appName } }));
1401
1468
  el = f.el; label = `the focused element of "${app.name}"`;
1402
1469
  }
1403
1470
  const v = readNode(el);
@@ -1408,7 +1475,7 @@ function opInsertText(req) {
1408
1475
  // text-like but read-only through accessibility (a terminal, a custom editor) vs. not text at all
1409
1476
  // (a button, a list, a sheet): the server only falls back to keystrokes for the first kind
1410
1477
  const textlike = TEXT_ROLES.has(roleKey(v)) || v.AXRole === 'AXWebArea' || attr(el, 'AXSelectedTextRange') !== null || attr(el, 'AXInsertionPointLineNumber') !== null;
1411
- return fail(notDelivered({ code: 'ACTION_NOT_SUPPORTED', message: `${label} (${v.AXRole}${v.AXSubrole ? '/' + v.AXSubrole : ''}) takes no text through accessibility${textlike ? '' : ' and is not a text input — focus a text field first'}`, details: { kind: 'not_text', role: v.AXRole, textlike } }));
1478
+ return fail(notDelivered({ code: 'ACTION_NOT_SUPPORTED', message: `${label} (${v.AXRole}${v.AXSubrole ? '/' + v.AXSubrole : ''}) takes no text through accessibility${textlike ? '' : ' and is not a text input — focus a text field first'}`, details: { kind: 'not_text', role: v.AXRole, textlike, app: appName } }));
1412
1479
  }
1413
1480
  const text = String(req.text);
1414
1481
  const secure = v.AXSubrole === 'AXSecureTextField';
@@ -1417,7 +1484,7 @@ function opInsertText(req) {
1417
1484
  const selBefore = attr(el, 'AXSelectedTextRange');
1418
1485
  const beforeSel = JSON.stringify(selBefore);
1419
1486
  if (req.replace && !secure && sameText(before, text)) {
1420
- return { ok: true, mechanism: 'semantic', via: 'AXValue', how, role: v.AXRole, delivery: 'not_delivered', retry: 'safe', reason: 'already', note: `${label} already shows exactly this text — nothing sent` };
1487
+ return { ok: true, mechanism: 'semantic', via: 'AXValue', how, role: v.AXRole, app: appName, delivery: 'not_delivered', retry: 'safe', reason: 'already', note: `${label} already shows exactly this text — nothing sent` };
1421
1488
  }
1422
1489
  // R36: appending through AXValue rewrites the whole value; when the value cannot be read, that would
1423
1490
  // replace what is there with the text — refuse instead
@@ -1432,7 +1499,7 @@ function opInsertText(req) {
1432
1499
  const deadline = now() + WRITE_POLL_MS;
1433
1500
  sleep(150);
1434
1501
  let after = attr(el, 'AXValue');
1435
- const base = { ok: true, mechanism: 'semantic', via, how, role: v.AXRole };
1502
+ const base = { ok: true, mechanism: 'semantic', via, how, role: v.AXRole, app: appName };
1436
1503
  if (secure || typeof after !== 'string') return Object.assign(base, { delivery: 'delivered_unverified', retry: 'unsafe', reason: secure ? 'secure_field' : 'value_unreadable' });
1437
1504
  // CP: the value must be exactly what the write should give — the replaced text, the text over the
1438
1505
  // selection that was there (AXSelectedText), or the old value plus the text (append)
@@ -1998,7 +2065,7 @@ function opWindowOp(req) {
1998
2065
  // ── paste (mac_paste) ────────────────────────────────────────────────────────────────────────────
1999
2066
  // One engine call does the whole paste, so the user's clipboard never leaves this process and nothing
2000
2067
  // can slip in between the steps: focus guard → copy every item and type aside → write the text (marked
2001
- // transient, so clipboard managers skip it) → ⌘V through cliclick, only if the clipboard and the
2068
+ // transient, so clipboard managers skip it) → ⌘V as a key event, only if the clipboard and the
2002
2069
  // frontmost app are still as they were → wait for the paste to show in the focused element (else at
2003
2070
  // least 1 s, and only while the app answers) → put the user's items back, only if nobody else wrote
2004
2071
  // to the clipboard meanwhile. A password manager's concealed item is never copied or put back: the
@@ -2101,9 +2168,21 @@ function focusEvidence(appEl) {
2101
2168
  return { el: f.el, key: JSON.stringify([val, typeof n === 'number' ? n : null, sel || null]), raw, sel: sel || null };
2102
2169
  }
2103
2170
  const PASTE_MIN_HOLD_MS = 300;
2171
+ // The current keyboard layout's id (e.g. com.apple.keylayout.US), or null when it cannot be read.
2172
+ function keyboardLayoutId() {
2173
+ try {
2174
+ ObjC.import('Carbon');
2175
+ const s = $.TISCopyCurrentKeyboardLayoutInputSource();
2176
+ return String(ObjC.castRefToObject($.TISGetInputSourceProperty(s, $.kTISPropertyInputSourceID)).js);
2177
+ } catch (e) { return null; }
2178
+ }
2104
2179
  function opPaste(req) {
2105
2180
  const text = String(req.text === undefined || req.text === null ? '' : req.text);
2106
2181
  if (!text) return invalid('text required');
2182
+ // ⌘V goes to the key that carries V in this layout (0.2.6: key code 9 is K on Dvorak, C on Workman — ⌘C would
2183
+ // copy over the text noracu put on the clipboard)
2184
+ const vKey = keyCodeForChar('v', KEY_FLAGS.cmd);
2185
+ if (vKey === null) return fail(notDelivered({ code: 'ACTION_NOT_SUPPORTED', message: `no key types "v" in the keyboard layout ${keyboardLayoutId() || '(unknown)'}, so ⌘V cannot be sent — nothing was pasted; mac_type types without the clipboard`, details: { kind: 'keyboard_layout' } }));
2107
2186
  const front = frontApp();
2108
2187
  if (!front) return fail(notDelivered({ code: 'FOCUS_UNKNOWN', message: 'could not read the frontmost app — nothing was pasted' }));
2109
2188
  let target = front;
@@ -2164,17 +2243,15 @@ function opPaste(req) {
2164
2243
  const restored = putBack(ours);
2165
2244
  return fail(notDelivered({ code: 'FOCUS_LOST', message: `the frontmost app changed to "${f2 ? f2.name : 'unknown'}" just before the paste — nothing was pasted (clipboard restored: ${restored})` }));
2166
2245
  }
2167
- const tool = req.cliclick || '/opt/homebrew/bin/cliclick';
2168
- const k = runTool(tool, ['kd:cmd', 't:v', 'ku:cmd'], 10000);
2169
- if (!k.started) {
2246
+ // ⌘V is the V key itself (vKey, found above) with the ⌘ flag, posted here. cliclick's `kd:cmd t:v ku:cmd`
2247
+ // types text, not that key: on macOS 27.2 TextEdit got a plain "v", or nothing, instead of a paste
2248
+ // (E2 run 2026-11-07, T7).
2249
+ const sent = postKey(vKey, [[MOD_KEYCODES.cmd, KEY_FLAGS.cmd]], 0);
2250
+ releaseStuckModifiers(['cmd']);
2251
+ if (!sent) {
2252
+ // the V key was never posted (postKey creates both events before posting either)
2170
2253
  const restored = putBack(ours);
2171
- return fail(notDelivered({ code: 'INTERNAL', message: `cliclick could not start: ${k.error} — nothing was pasted (clipboard restored: ${restored})` }));
2172
- }
2173
- if (k.timedOut || k.status !== 0) {
2174
- // ⌘V may or may not have gone out (and ⌘ may still be down): release ⌘, keep our text on the
2175
- // clipboard — a late paste must at worst repeat the text, never the user's clipboard
2176
- runTool(tool, ['ku:cmd'], 2000);
2177
- return fail({ code: 'ACTION_FAILED', message: `cliclick ${k.timedOut ? 'timed out' : `exited ${k.status}`} while sending ⌘V — the paste may or may not have happened (clipboard restored: false (paste_uncertain))`, delivery: 'unknown', retry: 'unsafe' });
2254
+ return fail(notDelivered({ code: 'ACTION_FAILED', message: `could not create the keyboard events for ⌘V — nothing was pasted (clipboard restored: ${restored})` }));
2178
2255
  }
2179
2256
  // the paste is done when the focused element shows it; without that evidence the clipboard stays
2180
2257
  // ours for at least hold_ms, so an app that reads it late does not get the user's clipboard instead
@@ -2217,6 +2294,9 @@ function opClipboard(req) {
2217
2294
  const out = { ok: true, types: types.slice(0, 20), change_count: Number(pb.changeCount) };
2218
2295
  // a concealed mark on any item (types lists only the first item's) withholds the whole clipboard
2219
2296
  if (types.indexOf('org.nspasteboard.ConcealedType') >= 0 || pbItemTypes().indexOf('org.nspasteboard.ConcealedType') >= 0) { out.concealed = true; out.note = 'the clipboard holds an item marked concealed (e.g. a password manager copy); its content is not returned'; return out; }
2297
+ // review 0.2.6 #4: Universal Clipboard content lives on the other device until it is read — say where
2298
+ // it came from (mac_paste refuses it; reading it is what this tool is for)
2299
+ if (types.indexOf(PB_REMOTE) >= 0) { out.remote = true; out.note = 'Universal Clipboard content copied on another device: reading it makes macOS fetch it from that device'; }
2220
2300
  const fmt = req.format || 'auto';
2221
2301
  if (fmt === 'auto' || fmt === 'files') {
2222
2302
  const items = pb.pasteboardItems;
@@ -2509,6 +2589,22 @@ function opMenu(req) {
2509
2589
  // keypad flag, as hardware sends them. The server's focus guard runs before this op.
2510
2590
  const KEY_FLAGS = { cmd: 0x100000, shift: 0x20000, alt: 0x80000, ctrl: 0x40000, fn: 0x800000 };
2511
2591
  const MOD_KEYCODES = { cmd: 55, shift: 56, alt: 58, ctrl: 59 }; // left-hand keys; fn is a flag only (pressing Fn alone can switch input source)
2592
+ // The key that types `ch` in the current keyboard layout while `flags` are held: AppKit is asked what each key of
2593
+ // the main block gives (charactersIgnoringModifiers of a created, never posted, key event), so ⌘V and ⌘C land on
2594
+ // whatever key carries V or C in this layout — QWERTY, AZERTY, Dvorak, Workman… (0.2.6, review: a fixed key code
2595
+ // 9 is K on Dvorak and C on Workman). With ⌘ in the flags, layouts that switch to QWERTY for ⌘ shortcuts answer
2596
+ // for that. null when no key types it. Checked on macOS 27.2 with the Pinyin layout: v → 9, a → 0, c → 8.
2597
+ function keyCodeForChar(ch, flags) {
2598
+ const src = $.CGEventSourceCreate($.kCGEventSourceStateHIDSystemState);
2599
+ for (let k = 0; k <= 50; k++) {
2600
+ const e = $.CGEventCreateKeyboardEvent(src, k, true);
2601
+ if (!e) continue;
2602
+ $.CGEventSetFlags(e, flags);
2603
+ const ns = $.NSEvent.eventWithCGEvent(e);
2604
+ if (ns && !ns.isNil() && ns.charactersIgnoringModifiers.js === ch) return k;
2605
+ }
2606
+ return null;
2607
+ }
2512
2608
  const FLAG_NUMPAD = 0x200000;
2513
2609
  const HELD_MASK = KEY_FLAGS.cmd | KEY_FLAGS.shift | KEY_FLAGS.alt | KEY_FLAGS.ctrl;
2514
2610
  const EV_FLAGS_CHANGED = 12;
@@ -2560,9 +2656,27 @@ function releaseStuckModifiers(names) {
2560
2656
  return names.filter(m => MOD_KEYCODES[m] && (left & KEY_FLAGS[m]));
2561
2657
  }
2562
2658
  function opKey(req) {
2563
- const code = req.code;
2659
+ let code = req.code;
2660
+ let mods = Array.isArray(req.mods) ? req.mods.slice() : [];
2661
+ if (typeof req.char === 'string') {
2662
+ // a chord on a character key (cmd-c, cmd-shift-v…): the key that carries that character in this layout
2663
+ if (!/^[\x21-\x7e]$/.test(req.char)) return fail(notDelivered({ code: 'INVALID_ARGS', message: 'key: char must be one printable ASCII character' }));
2664
+ // the key is looked up by its unshifted character (AppKit reports "V" for the V key with Shift held); an
2665
+ // uppercase letter means Shift; a character found only with Shift ("+" on a US keyboard) adds Shift
2666
+ let ch = req.char;
2667
+ if (/^[A-Z]$/.test(ch)) { ch = ch.toLowerCase(); if (mods.indexOf('shift') < 0) mods.push('shift'); }
2668
+ const base = mods.indexOf('cmd') >= 0 ? KEY_FLAGS.cmd : 0;
2669
+ code = keyCodeForChar(ch, base);
2670
+ if (code === null) {
2671
+ code = keyCodeForChar(ch, base | KEY_FLAGS.shift);
2672
+ if (code !== null && mods.indexOf('shift') < 0) mods.push('shift');
2673
+ }
2674
+ if (code === null) {
2675
+ const layout = keyboardLayoutId();
2676
+ return fail(notDelivered({ code: 'ACTION_NOT_SUPPORTED', message: `no key types "${req.char}" in the keyboard layout ${layout || '(unknown)'} — nothing was sent`, details: { kind: 'keyboard_layout' } }));
2677
+ }
2678
+ }
2564
2679
  if (!Number.isInteger(code) || code < 0 || code > 127) return fail(notDelivered({ code: 'INVALID_ARGS', message: 'key: code must be an integer 0-127' }));
2565
- const mods = Array.isArray(req.mods) ? req.mods : [];
2566
2680
  const modKeys = [];
2567
2681
  let extra = 0;
2568
2682
  for (const m of mods) {
@@ -2575,7 +2689,7 @@ function opKey(req) {
2575
2689
  const sent = postKey(code, modKeys, extra);
2576
2690
  const stuck = releaseStuckModifiers(mods.filter(m => m !== 'fn'));
2577
2691
  if (!sent) return fail(notDelivered({ code: 'ACTION_FAILED', message: 'key: could not create the keyboard events', details: stuck.length ? { modifiers_still_held: stuck } : undefined }));
2578
- const out = { ok: true, delivery: 'delivered_unverified', retry: 'unsafe', flags: modKeys.reduce((a, [, f]) => a | f, 0) | extra };
2692
+ const out = { ok: true, delivery: 'delivered_unverified', retry: 'unsafe', flags: modKeys.reduce((a, [, f]) => a | f, 0) | extra, code };
2579
2693
  if (stuck.length) out.note = `the system still reports ${stuck.join('+')} held — press and release it on the keyboard`;
2580
2694
  return out;
2581
2695
  }