@reticlehq/computer 0.0.0-stage → 3.11.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.
Files changed (63) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +12 -0
  3. package/README.md +237 -2
  4. package/bin/attach.mjs +333 -0
  5. package/dist/attach.d.ts +105 -0
  6. package/dist/attach.js +234 -0
  7. package/dist/channels.d.ts +42 -0
  8. package/dist/channels.js +46 -0
  9. package/dist/computer-realm.d.ts +54 -0
  10. package/dist/computer-realm.js +487 -0
  11. package/dist/doctor.d.ts +32 -0
  12. package/dist/doctor.js +42 -0
  13. package/dist/driver.d.ts +227 -0
  14. package/dist/driver.js +73 -0
  15. package/dist/effect.d.ts +60 -0
  16. package/dist/effect.js +158 -0
  17. package/dist/files.d.ts +16 -0
  18. package/dist/files.js +40 -0
  19. package/dist/hud/port.d.ts +44 -0
  20. package/dist/hud/port.js +6 -0
  21. package/dist/index.d.ts +34 -0
  22. package/dist/index.js +22 -0
  23. package/dist/lines.d.ts +34 -0
  24. package/dist/lines.js +80 -0
  25. package/dist/mac/from-ax.d.ts +27 -0
  26. package/dist/mac/from-ax.js +275 -0
  27. package/dist/mac/mac-driver.d.ts +42 -0
  28. package/dist/mac/mac-driver.js +355 -0
  29. package/dist/mac/mac-hud.d.ts +10 -0
  30. package/dist/mac/mac-hud.js +142 -0
  31. package/dist/peer/act-effect.d.ts +9 -0
  32. package/dist/peer/act-effect.js +13 -0
  33. package/dist/peer/commands.d.ts +87 -0
  34. package/dist/peer/commands.js +811 -0
  35. package/dist/peer/form.d.ts +62 -0
  36. package/dist/peer/form.js +103 -0
  37. package/dist/peer/link-switch.d.ts +12 -0
  38. package/dist/peer/link-switch.js +38 -0
  39. package/dist/peer/peer.d.ts +43 -0
  40. package/dist/peer/peer.js +216 -0
  41. package/dist/peer/pointer.d.ts +97 -0
  42. package/dist/peer/pointer.js +289 -0
  43. package/dist/peer/scroll.d.ts +12 -0
  44. package/dist/peer/scroll.js +157 -0
  45. package/dist/peer/seen.d.ts +18 -0
  46. package/dist/peer/seen.js +61 -0
  47. package/dist/peer/select.d.ts +27 -0
  48. package/dist/peer/select.js +78 -0
  49. package/dist/peer/window.d.ts +25 -0
  50. package/dist/peer/window.js +111 -0
  51. package/dist/ui-node.d.ts +93 -0
  52. package/dist/ui-node.js +192 -0
  53. package/dist/win/helper-launch.d.ts +16 -0
  54. package/dist/win/helper-launch.js +57 -0
  55. package/native/linux/Dockerfile +22 -0
  56. package/native/linux/reticle-atspi.py +933 -0
  57. package/native/linux/sandbox.mjs +127 -0
  58. package/native/mac/build/reticle-ax +0 -0
  59. package/native/mac/build/reticle-hud +0 -0
  60. package/native/mac/hud.swift +749 -0
  61. package/native/mac/reticle-ax.swift +1786 -0
  62. package/native/win/reticle-uia.ps1 +620 -0
  63. package/package.json +65 -3
@@ -0,0 +1,1786 @@
1
+ // reticle-ax: reads and drives one macOS application through the Accessibility API.
2
+ //
3
+ // reticle-ax tree <pid>
4
+ // reticle-ax reach <pid> <path> <role> <name>
5
+ // reticle-ax act <pid> <path> <role> <name> press|set|type|key|window [value] [budgetMs] [user-path|direct][:quietMs] [folder...]
6
+ //
7
+ // <path> is the child index at each level from the application element, joined by ".", "" for the
8
+ // application. <role> and <name> are what the caller last read there. If the element at <path> is
9
+ // now a different one, the helper refuses: it never acts on an element the caller did not choose.
10
+ //
11
+ // By default the helper acts only on an element a person could click (`user-path`). `direct` acts on
12
+ // an element under another view or window too, and the result says a person could not reach it.
13
+ //
14
+ // Each <folder> is watched while the helper waits: a file written there is an effect too, so the
15
+ // wait ends when the files and the tree are quiet, not only when the tree changed.
16
+ //
17
+ // Output is one JSON object on stdout. The helper decides nothing. It reports what it read.
18
+ //
19
+ // reticle-ax web-tree <pid> on|off (Electron: its accessibility switch)
20
+ // reticle-ax web-tree <pid> try (any other app: the screen reader's switch, kept if it adds)
21
+ // reticle-ax capture <pid> <file.png> [screen] (a picture of the application's window, or of
22
+ // the whole display that holds it)
23
+ // reticle-ax apps (the applications that are open: name, process, pid)
24
+ // reticle-ax serve (one command for each line on standard input, as a JSON list of words)
25
+ import AppKit
26
+ import ApplicationServices
27
+ import Foundation
28
+ import ScreenCaptureKit
29
+ import Security
30
+ import Vision
31
+
32
+ let attributes =
33
+ [
34
+ kAXRoleAttribute, kAXSubroleAttribute, kAXTitleAttribute, kAXDescriptionAttribute,
35
+ kAXValueAttribute, kAXEnabledAttribute, kAXFocusedAttribute, kAXPositionAttribute,
36
+ kAXSizeAttribute, kAXChildrenAttribute, kAXIdentifierAttribute, kAXSelectedAttribute,
37
+ // The `id` of an element in a web view. A web view does not give it as the identifier.
38
+ "AXDOMIdentifier",
39
+ // The words a person gets when the pointer rests on the element.
40
+ kAXHelpAttribute,
41
+ ] as CFArray
42
+
43
+ func values(_ element: AXUIElement) -> [AnyObject]? {
44
+ var out: CFArray?
45
+ guard AXUIElementCopyMultipleAttributeValues(element, attributes, [], &out) == .success else {
46
+ return nil
47
+ }
48
+ return out as? [AnyObject]
49
+ }
50
+
51
+ func text(_ value: AnyObject) -> String? {
52
+ if let s = value as? String { return s }
53
+ if let n = value as? NSNumber, CFGetTypeID(n) != AXValueGetTypeID() { return n.stringValue }
54
+ return nil
55
+ }
56
+
57
+ func frame(_ position: AnyObject, _ size: AnyObject) -> CGRect? {
58
+ guard CFGetTypeID(position) == AXValueGetTypeID(), CFGetTypeID(size) == AXValueGetTypeID() else {
59
+ return nil
60
+ }
61
+ var p = CGPoint.zero
62
+ var s = CGSize.zero
63
+ guard AXValueGetValue(position as! AXValue, .cgPoint, &p),
64
+ AXValueGetValue(size as! AXValue, .cgSize, &s)
65
+ else { return nil }
66
+ // Numbers gives an infinite size for an element of its sheet. JSON has no infinity, and the
67
+ // helper ended with an exception when it wrote the tree.
68
+ guard [p.x, p.y, s.width, s.height].allSatisfy({ $0.isFinite }) else { return nil }
69
+ return CGRect(origin: p, size: s)
70
+ }
71
+
72
+ /// The element as a dictionary. `unread` counts elements the API refused to describe, so a reader
73
+ /// can tell a small tree from a tree with holes in it.
74
+ func readElement(_ element: AXUIElement, _ depth: Int, _ unread: inout Int) -> [String: Any] {
75
+ guard let v = values(element) else {
76
+ unread += 1
77
+ return ["role": "", "children": [Any]()]
78
+ }
79
+ var node: [String: Any] = ["role": text(v[0]) ?? ""]
80
+ if let s = text(v[1]) { node["subrole"] = s }
81
+ if let s = text(v[2]), !s.isEmpty { node["title"] = s }
82
+ if let s = text(v[3]), !s.isEmpty { node["description"] = s }
83
+ if let s = text(v[4]) { node["value"] = s }
84
+ if let b = v[5] as? Bool { node["enabled"] = b }
85
+ if let b = v[6] as? Bool { node["focused"] = b }
86
+ if let r = frame(v[7], v[8]) {
87
+ node["frame"] = [r.origin.x, r.origin.y, r.size.width, r.size.height]
88
+ }
89
+ if let s = text(v[10]), !s.isEmpty {
90
+ node["id"] = s
91
+ } else if v.count > 12, let s = text(v[12]), !s.isEmpty {
92
+ node["id"] = s
93
+ }
94
+ if let b = v[11] as? Bool, b { node["selected"] = true }
95
+ if v.count > 13, let s = text(v[13]), !s.isEmpty { node["help"] = s }
96
+ var children = depth < 80 ? (v[9] as? [AXUIElement]) ?? [] : []
97
+ // A table gives every row it has, and makes each one when it is asked. A table of 5,000 rows
98
+ // did not answer in four minutes. A person sees the rows that are on the screen, so those are
99
+ // the rows that are read. Each keeps its place in the whole list as "i", and "notShown" says how
100
+ // many rows were left out.
101
+ var places: [Int]?
102
+ let role = text(v[0]) ?? ""
103
+ // The menu bar of an application that is not in front is not on the screen: a person cannot
104
+ // see it or press it, and a press on it is refused. It is given no size and its menus are not
105
+ // read. They are most of the elements of an application, and each one costs a call.
106
+ // The items at the right of the menu bar (Control Centre, Wi-Fi, Focus) are on the screen when
107
+ // their application is not in front. Control Centre gave them as its menu bar, and they were
108
+ // dropped, so its toggles (Stage Manager among them) could not be pressed.
109
+ if role == "AXMenuBar" && !menuBarOnScreen && !isMenuExtras(children) {
110
+ children = []
111
+ if let r = frame(v[7], v[8]) { node["frame"] = [r.origin.x, r.origin.y, 0, 0] }
112
+ }
113
+ // A column of Finder's column view is a scroll area with no children: its list is given only as
114
+ // its contents. Every file of the column was missing, so no file could be opened from there.
115
+ if role == "AXScrollArea" && children.isEmpty && depth < 80 {
116
+ var contents: AnyObject?
117
+ if AXUIElementCopyAttributeValue(element, "AXContents" as CFString, &contents) == .success {
118
+ children = (contents as? [AXUIElement]) ?? []
119
+ }
120
+ }
121
+ // A list (that column, with a thousand files) gives the items on the screen as a table does.
122
+ let isList = role == "AXList"
123
+ if role == "AXTable" || role == "AXOutline" || isList {
124
+ var visible: AnyObject?
125
+ let shown = isList ? kAXVisibleChildrenAttribute : kAXVisibleRowsAttribute
126
+ if AXUIElementCopyAttributeValue(element, shown as CFString, &visible)
127
+ == .success, let rows = visible as? [AXUIElement]
128
+ {
129
+ let all = children
130
+ let found = rows.compactMap { row in all.firstIndex { CFEqual($0, row) } }
131
+ // Chromium gives an ARIA tree (Discord's servers) as an outline whose visible rows are an
132
+ // empty list, and its items are not rows at all. That read as "no row is on the screen", and
133
+ // every server was dropped. Visible rows that name none of the children of a short one are
134
+ // not believed.
135
+ // A long one is believed: a column of Finder whose window is not on the screen gives no
136
+ // visible item, and its 48,336 items were read one by one for half an hour, which hung
137
+ // Finder. A short one is read whole: Finder gives no visible item for the column of a
138
+ // window it has just opened, and what is out of the window is left out by its place.
139
+ let believed = all.count > shortList
140
+ if found.isEmpty && !all.isEmpty && !believed { return finish(node, all, nil) }
141
+ places = found
142
+ children = found.map { all[$0] }
143
+ // The rows that are not on the screen. The columns are left out too, and they are not
144
+ // counted: they hold the same cells a second time, so nothing in them is hidden.
145
+ var every: AnyObject?
146
+ var total = all.count
147
+ if !isList {
148
+ total =
149
+ AXUIElementCopyAttributeValue(element, kAXRowsAttribute as CFString, &every) == .success
150
+ ? (every as? [AXUIElement])?.count ?? children.count : children.count
151
+ }
152
+ node["notShown"] = max(0, total - children.count)
153
+ }
154
+ }
155
+ return finish(node, children, places)
156
+
157
+ /// The node with its children read: each keeps its place in the whole list when only some were.
158
+ func finish(_ node: [String: Any], _ children: [AXUIElement], _ places: [Int]?) -> [String: Any] {
159
+ var node = node
160
+ var kids: [[String: Any]] = []
161
+ // The read has a budget: past it, what an element holds is not read, and is counted as not
162
+ // shown on that element, so the loss is said where it is.
163
+ if readBudget <= 0 && !children.isEmpty {
164
+ node["notShown"] = ((node["notShown"] as? Int) ?? 0) + children.count
165
+ node["children"] = kids
166
+ return node
167
+ }
168
+ readBudget -= children.count
169
+ for (order, child) in children.enumerated() {
170
+ var one = readElement(child, depth + 1, &unread)
171
+ if let places { one["i"] = places[order] }
172
+ kids.append(one)
173
+ }
174
+ node["children"] = kids
175
+ return node
176
+ }
177
+ }
178
+
179
+ /// True when the menu bar on the screen is the one of this application: the application is the
180
+ /// one in front. Two sources, and either one is enough.
181
+ ///
182
+ /// The workspace names the application in front. It learns of a change from the run loop, so the
183
+ /// loop is run once first. The window server names the owner of the topmost ordinary window, and
184
+ /// it is never old. The window alone was not enough: an application whose top window is an alert
185
+ /// or a panel has it on another layer, and its menu bar was then not read.
186
+ /// An old "in front" costs only time: the menu bar is read, and a press on it is refused.
187
+ func isInFront(_ pid: pid_t) -> Bool {
188
+ RunLoop.current.run(until: Date())
189
+ if NSWorkspace.shared.frontmostApplication?.processIdentifier == pid { return true }
190
+ let options: CGWindowListOption = [.optionOnScreenOnly, .excludeDesktopElements]
191
+ let list = CGWindowListCopyWindowInfo(options, kCGNullWindowID) as? [[String: Any]] ?? []
192
+ let top = list.first { ($0[kCGWindowLayer as String] as? Int) == 0 }
193
+ return (top?[kCGWindowOwnerPID as String] as? pid_t) == pid
194
+ }
195
+
196
+ /// The menu bar of the application being read is on the screen. Set for each read.
197
+ var menuBarOnScreen = true
198
+
199
+ /// A menu bar of items at the right of the screen, which are on the screen at all times.
200
+ func isMenuExtras(_ items: [AXUIElement]) -> Bool {
201
+ guard let first = items.first else { return false }
202
+ var subrole: AnyObject?
203
+ AXUIElementCopyAttributeValue(first, kAXSubroleAttribute as CFString, &subrole)
204
+ return (subrole as? String) == "AXMenuExtra"
205
+ }
206
+
207
+ /// The most elements one read takes. An application answers an element in about a millisecond, and
208
+ /// Finder in up to twenty: a read with no end ran for half an hour on a folder of 48,336 files.
209
+ let readLimit = 20_000
210
+ /// A list this long or shorter is read whole when it names no visible item.
211
+ let shortList = 200
212
+ /// What is left of the budget of the read that runs now.
213
+ var readBudget = readLimit
214
+
215
+ /// The largest visible window of the application on screen: its number and its rect in points.
216
+ func mainWindow(_ pid: pid_t) -> (id: Int, rect: CGRect)? {
217
+ let options: CGWindowListOption = [.optionOnScreenOnly, .excludeDesktopElements]
218
+ let list = CGWindowListCopyWindowInfo(options, kCGNullWindowID) as? [[String: Any]] ?? []
219
+ var best: (id: Int, rect: CGRect)?
220
+ for window in list where (window[kCGWindowOwnerPID as String] as? pid_t) == pid {
221
+ guard let bounds = window[kCGWindowBounds as String] as? NSDictionary,
222
+ let rect = CGRect(dictionaryRepresentation: bounds),
223
+ let id = window[kCGWindowNumber as String] as? Int,
224
+ (window[kCGWindowAlpha as String] as? Double ?? 1) > 0, rect.width > 40, rect.height > 40
225
+ else { continue }
226
+ if let b = best, b.rect.width * b.rect.height >= rect.width * rect.height { continue }
227
+ best = (id, rect)
228
+ }
229
+ return best
230
+ }
231
+
232
+ /// A picture of one window, made small: `pictureWidth` pixels wide, 4 bytes for each pixel.
233
+ /// A canvas (a photo, a video frame, a drawing) has no elements, so its pixels are its effect.
234
+ let pictureWidth = 240
235
+ /// Waits for async work on a thread that has nothing else to do. The helper answers one command
236
+ /// at a time, so a blocked thread costs nothing.
237
+ func waitFor<T>(_ work: @escaping () async -> T?) -> T? {
238
+ let done = DispatchSemaphore(value: 0)
239
+ var out: T?
240
+ Task {
241
+ out = await work()
242
+ done.signal()
243
+ }
244
+ done.wait()
245
+ return out
246
+ }
247
+ /// The filter of the last window drawn, kept: to find a window again costs more than the picture.
248
+ var pictureFilter: (id: Int, filter: Any)?
249
+ /// A small picture of a window, drawn by the window server in this process: about 35 ms, where a
250
+ /// run of `screencapture` and a PNG to decode took 90 ms or more.
251
+ func windowImage(_ id: Int) -> CGImage? {
252
+ if #available(macOS 14.0, *) {
253
+ var filter = pictureFilter?.id == id ? pictureFilter?.filter as? SCContentFilter : nil
254
+ if filter == nil {
255
+ filter = waitFor {
256
+ let content = try? await SCShareableContent.excludingDesktopWindows(
257
+ false, onScreenWindowsOnly: true)
258
+ return content?.windows.first { $0.windowID == CGWindowID(id) }
259
+ .map { SCContentFilter(desktopIndependentWindow: $0) }
260
+ }
261
+ if let filter { pictureFilter = (id, filter) }
262
+ }
263
+ if let filter {
264
+ let config = SCStreamConfiguration()
265
+ config.width = pictureWidth
266
+ config.height = max(1, Int(Double(pictureWidth) * Double(filter.contentRect.height)
267
+ / Double(max(filter.contentRect.width, 1))))
268
+ config.showsCursor = false
269
+ if let image = waitFor({
270
+ try? await SCScreenshotManager.captureImage(contentFilter: filter, configuration: config)
271
+ }) {
272
+ return image
273
+ }
274
+ }
275
+ }
276
+ let path = NSTemporaryDirectory() + "reticle-pixels-\(getpid())-\(id).png"
277
+ defer { try? FileManager.default.removeItem(atPath: path) }
278
+ let shot = Process()
279
+ shot.executableURL = URL(fileURLWithPath: "/usr/sbin/screencapture")
280
+ shot.arguments = ["-x", "-o", "-l", String(id), "-t", "png", path]
281
+ try? shot.run()
282
+ shot.waitUntilExit()
283
+ guard shot.terminationStatus == 0 else { return nil }
284
+ return NSImage(contentsOfFile: path)?.cgImage(forProposedRect: nil, context: nil, hints: nil)
285
+ }
286
+ func windowPixels(_ id: Int) -> (bytes: [UInt8], width: Int, height: Int)? {
287
+ guard let image = windowImage(id), image.width > 0 else { return nil }
288
+ let width = min(pictureWidth, image.width)
289
+ let height = max(1, image.height * width / image.width)
290
+ var bytes = [UInt8](repeating: 0, count: width * height * 4)
291
+ let drawn = bytes.withUnsafeMutableBytes { raw -> Bool in
292
+ guard
293
+ let context = CGContext(
294
+ data: raw.baseAddress, width: width, height: height, bitsPerComponent: 8,
295
+ bytesPerRow: width * 4, space: CGColorSpaceCreateDeviceRGB(),
296
+ bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)
297
+ else { return false }
298
+ context.interpolationQuality = .medium
299
+ context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
300
+ return true
301
+ }
302
+ return drawn ? (bytes, width, height) : nil
303
+ }
304
+
305
+ /// What part of the window changed between two pictures, and the box around the change in screen
306
+ /// points. A pixel counts when one channel moved more than `pixelStep`: less is the noise of the
307
+ /// scaling and of a blinking caret's edge.
308
+ let pixelStep = 24
309
+ typealias Pixels = (bytes: [UInt8], width: Int, height: Int)
310
+
311
+ /// The pixels that differ between two pictures of the same size.
312
+ func pixelsMoved(_ a: Pixels, _ b: Pixels) -> [Bool] {
313
+ guard a.width == b.width, a.height == b.height else { return [] }
314
+ var moved = [Bool](repeating: false, count: a.width * a.height)
315
+ for p in 0..<moved.count {
316
+ for c in 0..<3 {
317
+ let i = p * 4 + c
318
+ if abs(Int(a.bytes[i]) - Int(b.bytes[i])) > pixelStep { moved[p] = true }
319
+ }
320
+ }
321
+ return moved
322
+ }
323
+
324
+ /// The pixels that moved by themselves, made a little wider: a video, a spinner or a caret moves
325
+ /// between two pictures with no action, and its edge moves a pixel more in the next frame.
326
+ func movingMask(_ pairs: [(Pixels, Pixels)], width: Int, height: Int) -> [Bool] {
327
+ var mask = [Bool](repeating: false, count: width * height)
328
+ for (a, b) in pairs {
329
+ let moved = pixelsMoved(a, b)
330
+ guard moved.count == mask.count else { continue }
331
+ for y in 0..<height {
332
+ for x in 0..<width where moved[y * width + x] {
333
+ for yy in max(0, y - 2)...min(height - 1, y + 2) {
334
+ for xx in max(0, x - 2)...min(width - 1, x + 2) { mask[yy * width + xx] = true }
335
+ }
336
+ }
337
+ }
338
+ }
339
+ return mask
340
+ }
341
+
342
+ /// What part of the window changed, leaving out the pixels in `moving`, which change by
343
+ /// themselves. `moving` in the answer is the part of the window that moved with no action: a
344
+ /// change there cannot be told from the action's effect, so it is not counted as one.
345
+ func pixelChange(_ a: Pixels, _ b: Pixels, window: CGRect, moving: [Bool] = []) -> [String: Any]? {
346
+ guard a.width == b.width, a.height == b.height else {
347
+ // The window changed its size: all of it is new.
348
+ return ["changed": 1.0, "box": [window.origin.x, window.origin.y, window.width, window.height]]
349
+ }
350
+ let moved = pixelsMoved(a, b)
351
+ let still = moving.count == moved.count ? moving : [Bool](repeating: false, count: moved.count)
352
+ let movingPart = Double(still.filter { $0 }.count) / Double(max(1, still.count))
353
+ let rounded = { (n: Double) in (n * 10_000).rounded() / 10_000 }
354
+ var count = 0
355
+ var minX = a.width, minY = a.height, maxX = -1, maxY = -1
356
+ for y in 0..<a.height {
357
+ for x in 0..<a.width {
358
+ let p = y * a.width + x
359
+ guard moved[p], !still[p] else { continue }
360
+ count += 1
361
+ minX = min(minX, x)
362
+ maxX = max(maxX, x)
363
+ minY = min(minY, y)
364
+ maxY = max(maxY, y)
365
+ }
366
+ }
367
+ let extra: [String: Any] = movingPart > 0 ? ["moving": rounded(movingPart)] : [:]
368
+ guard count > 0 else { return ["changed": 0.0].merging(extra) { $1 } }
369
+ // The first row in the memory of a bitmap context is the top of the picture.
370
+ let sx = window.width / Double(a.width)
371
+ let sy = window.height / Double(a.height)
372
+ let top = minY
373
+ return extra.merging([
374
+ "changed": rounded(Double(count) / Double(a.width * a.height)),
375
+ "box": [
376
+ (window.origin.x + Double(minX) * sx).rounded(), (window.origin.y + Double(top) * sy).rounded(),
377
+ (Double(maxX - minX + 1) * sx).rounded(), (Double(maxY - minY + 1) * sy).rounded(),
378
+ ],
379
+ ]) { $1 }
380
+ }
381
+
382
+ /// A container by its role and its frame: the switch adds elements before it, so a path of child
383
+ /// indexes names another element after it.
384
+ func containerKey(_ node: [String: Any]) -> String? {
385
+ guard let role = node["role"] as? String, ["AXScrollArea", "AXGroup", "AXSplitGroup"].contains(role),
386
+ let frame = node["frame"] as? [Double], frame.count == 4, frame[2] > 0, frame[3] > 0
387
+ else { return nil }
388
+ return "\(role)@\(frame.map { Int($0.rounded()) })"
389
+ }
390
+
391
+ func hasContent(_ node: [String: Any]) -> Bool {
392
+ (node["children"] as? [[String: Any]] ?? []).contains { ($0["role"] as? String) != "AXScrollBar" }
393
+ }
394
+
395
+ /// The containers that hold nothing but scroll bars.
396
+ func emptyContainers(_ node: [String: Any]) -> Set<String> {
397
+ var found: Set<String> = []
398
+ if !hasContent(node), let key = containerKey(node) { found.insert(key) }
399
+ for child in node["children"] as? [[String: Any]] ?? [] { found.formUnion(emptyContainers(child)) }
400
+ return found
401
+ }
402
+
403
+ /// Which of the containers in `places` now hold content other than scroll bars.
404
+ func filledContainers(_ node: [String: Any], among places: Set<String>) -> Set<String> {
405
+ var filled: Set<String> = []
406
+ if hasContent(node), let key = containerKey(node), places.contains(key) { filled.insert(key) }
407
+ for child in node["children"] as? [[String: Any]] ?? [] {
408
+ filled.formUnion(filledContainers(child, among: places))
409
+ }
410
+ return filled
411
+ }
412
+
413
+ func snapshot(_ app: AXUIElement) -> (tree: [String: Any], unread: Int, json: Data) {
414
+ readBudget = readLimit
415
+ var unread = 0
416
+ var pid: pid_t = 0
417
+ AXUIElementGetPid(app, &pid)
418
+ menuBarOnScreen = isInFront(pid)
419
+ var tree = readElement(app, 0, &unread)
420
+ // An application that is busy can refuse its first read. Ask once more before the caller gets
421
+ // a tree with nothing in it. A second refusal is reported as it is, in `unread`.
422
+ if (tree["role"] as? String) == "" {
423
+ unread = 0
424
+ tree = readElement(app, 0, &unread)
425
+ }
426
+ let json = (try? JSONSerialization.data(withJSONObject: tree, options: [.sortedKeys])) ?? Data()
427
+ return (tree, unread, json)
428
+ }
429
+
430
+ /// The answer to one command. A command ends when it throws its answer, at any depth.
431
+ struct Answer: Error {
432
+ let body: [String: Any]
433
+ }
434
+
435
+ func emit(_ object: [String: Any]) throws -> Never {
436
+ throw Answer(body: object)
437
+ }
438
+
439
+ func child(_ element: AXUIElement, _ index: Int) -> AXUIElement? {
440
+ var value: AnyObject?
441
+ var children: [AXUIElement] = []
442
+ if AXUIElementCopyAttributeValue(element, kAXChildrenAttribute as CFString, &value) == .success {
443
+ children = (value as? [AXUIElement]) ?? []
444
+ }
445
+ // As the read does: a column of Finder gives its list only as its contents. The way to a file
446
+ // went through its children, found none, and every click on a file there was "stale".
447
+ if children.isEmpty,
448
+ AXUIElementCopyAttributeValue(element, "AXContents" as CFString, &value) == .success
449
+ {
450
+ children = (value as? [AXUIElement]) ?? []
451
+ }
452
+ guard index >= 0, index < children.count else { return nil }
453
+ return children[index]
454
+ }
455
+
456
+ /// The visible part of the screen that holds most of `window`, in the top-left points of the
457
+ /// Accessibility API: the screen without the menu bar and the Dock.
458
+ func visibleArea(of window: AXUIElement) -> CGRect? {
459
+ var position: AnyObject?
460
+ var size: AnyObject?
461
+ AXUIElementCopyAttributeValue(window, kAXPositionAttribute as CFString, &position)
462
+ AXUIElementCopyAttributeValue(window, kAXSizeAttribute as CFString, &size)
463
+ guard let main = NSScreen.screens.first else { return nil }
464
+ let top = main.frame.height
465
+ let middle = position.flatMap { p in size.flatMap { frame(p, $0) } }.map {
466
+ CGPoint(x: $0.midX, y: top - $0.midY)
467
+ }
468
+ let screen =
469
+ middle.flatMap { m in NSScreen.screens.first { $0.frame.contains(m) } } ?? NSScreen.main ?? main
470
+ let visible = screen.visibleFrame
471
+ return CGRect(x: visible.minX, y: top - visible.maxY, width: visible.width, height: visible.height)
472
+ }
473
+
474
+ /// What a person sees of `window`: its frame, and whether it is minimized or in full screen. A
475
+ /// minimized window keeps its frame in the Accessibility API, so the frame alone does not say it.
476
+ func windowState(_ window: AXUIElement, wanted: CGRect?) -> [String: Any] {
477
+ var position: AnyObject?
478
+ var size: AnyObject?
479
+ var minimized: AnyObject?
480
+ var full: AnyObject?
481
+ AXUIElementCopyAttributeValue(window, kAXPositionAttribute as CFString, &position)
482
+ AXUIElementCopyAttributeValue(window, kAXSizeAttribute as CFString, &size)
483
+ AXUIElementCopyAttributeValue(window, kAXMinimizedAttribute as CFString, &minimized)
484
+ AXUIElementCopyAttributeValue(window, "AXFullScreen" as CFString, &full)
485
+ var state: [String: Any] = [
486
+ "minimized": (minimized as? Bool) ?? false, "fullscreen": (full as? Bool) ?? false,
487
+ ]
488
+ if let p = position, let s = size, let rect = frame(p, s) {
489
+ state["frame"] = [rect.minX, rect.minY, rect.width, rect.height]
490
+ }
491
+ if let w = wanted { state["wanted"] = [w.minX, w.minY, w.width, w.height] }
492
+ return state
493
+ }
494
+
495
+ /// Gives `window` an arrangement: minimize, zoom, fullscreen, restore, left, right, or
496
+ /// "frame:x,y,width,height". The position is set again after the size: a window that grows
497
+ /// against the edge of the screen is moved by the system. Absent answer: no such arrangement.
498
+ func arrange(_ window: AXUIElement, _ how: String) -> (AXError, CGRect?)? {
499
+ func set(_ attribute: String, _ value: CFTypeRef) -> AXError {
500
+ AXUIElementSetAttributeValue(window, attribute as CFString, value)
501
+ }
502
+ func place(_ rect: CGRect) -> AXError {
503
+ var origin = rect.origin
504
+ var size = rect.size
505
+ guard let p = AXValueCreate(.cgPoint, &origin), let s = AXValueCreate(.cgSize, &size) else {
506
+ return .failure
507
+ }
508
+ _ = set(kAXPositionAttribute, p)
509
+ let sized = set(kAXSizeAttribute, s)
510
+ _ = set(kAXPositionAttribute, p)
511
+ return sized
512
+ }
513
+ let area = visibleArea(of: window)
514
+ switch how {
515
+ case "minimize": return (set(kAXMinimizedAttribute, kCFBooleanTrue), nil)
516
+ case "fullscreen": return (set("AXFullScreen", kCFBooleanTrue), nil)
517
+ case "restore":
518
+ _ = set("AXFullScreen", kCFBooleanFalse)
519
+ return (set(kAXMinimizedAttribute, kCFBooleanFalse), nil)
520
+ case "zoom":
521
+ guard let a = area else { return (.failure, nil) }
522
+ return (place(a), a)
523
+ case "left", "right":
524
+ guard let a = area else { return (.failure, nil) }
525
+ let half = a.width / 2
526
+ let rect = CGRect(x: how == "left" ? a.minX : a.minX + half, y: a.minY, width: half, height: a.height)
527
+ return (place(rect), rect)
528
+ default:
529
+ let numbers = how.hasPrefix("frame:")
530
+ ? how.dropFirst(6).split(separator: ",").compactMap { Double($0) } : []
531
+ guard numbers.count == 4 else { return nil }
532
+ let rect = CGRect(x: numbers[0], y: numbers[1], width: numbers[2], height: numbers[3])
533
+ return (place(rect), rect)
534
+ }
535
+ }
536
+
537
+ /// The name of the HUD program of the realm. Its windows take no click: the pointer and the glow
538
+ /// let every click through to what is under them.
539
+ let hudProgram = "reticle-hud"
540
+
541
+ /// The application that owns the frontmost window at a point, from the window server's own list.
542
+ /// It needs no answer from any application. The windows of the HUD are not counted: the pointer
543
+ /// rests on the last target, and it was named as the window over the next one.
544
+ func windowOwner(at point: CGPoint) -> (pid: pid_t, name: String, layer: Int)? {
545
+ let options: CGWindowListOption = [.optionOnScreenOnly, .excludeDesktopElements]
546
+ guard let list = CGWindowListCopyWindowInfo(options, kCGNullWindowID) as? [[String: Any]] else {
547
+ return nil
548
+ }
549
+ for window in list {
550
+ guard let bounds = window[kCGWindowBounds as String] as? NSDictionary,
551
+ let rect = CGRect(dictionaryRepresentation: bounds), rect.contains(point),
552
+ (window[kCGWindowAlpha as String] as? Double ?? 1) > 0,
553
+ window[kCGWindowOwnerName as String] as? String != hudProgram,
554
+ let pid = window[kCGWindowOwnerPID as String] as? pid_t
555
+ else { continue }
556
+ return (
557
+ pid, window[kCGWindowOwnerName as String] as? String ?? "",
558
+ window[kCGWindowLayer as String] as? Int ?? 0
559
+ )
560
+ }
561
+ return nil
562
+ }
563
+
564
+ /// The windows of an application that the window server has and that are not on the screen now:
565
+ /// on another Space, or made small in the Dock. The Accessibility API does not list them, so an
566
+ /// application with all its windows there reads as an application with none.
567
+ func windowsNotOnScreen(_ pid: pid_t) -> Int {
568
+ func count(_ options: CGWindowListOption) -> Int {
569
+ let list = CGWindowListCopyWindowInfo(options, kCGNullWindowID) as? [[String: Any]] ?? []
570
+ return list.filter {
571
+ ($0[kCGWindowOwnerPID as String] as? pid_t) == pid
572
+ && ($0[kCGWindowLayer as String] as? Int) == 0
573
+ && (($0[kCGWindowBounds as String] as? [String: Any])?["Height"] as? Double ?? 0) > 60
574
+ }.count
575
+ }
576
+ return max(
577
+ 0, count([.optionAll, .excludeDesktopElements])
578
+ - count([.optionOnScreenOnly, .excludeDesktopElements]))
579
+ }
580
+
581
+ enum Reach {
582
+ case yes
583
+ /// Another element is on top at that point. `by` says which.
584
+ case no(by: String)
585
+ /// The operating system did not answer. Nothing is known about the element.
586
+ case unknown(code: Int)
587
+ }
588
+
589
+ /// Whether `hit`, the answer of a hit test at the middle of `target`, is an empty layer that a
590
+ /// click goes through. Chromium answers a hit test with an empty group over the whole window that
591
+ /// has `pointer-events: none`, as the layer that Discord keeps for its popups, and the realm then
592
+ /// refused every button of Discord. The backdrop of an open dialog is an empty group too, and a
593
+ /// click on it does not go through (it closes the dialog). So the layer passes only when no open
594
+ /// dialog near it is without the target.
595
+ func passesThrough(_ hit: AXUIElement, to target: AXUIElement) -> Bool {
596
+ var hitPid: pid_t = 0
597
+ var targetPid: pid_t = 0
598
+ AXUIElementGetPid(hit, &hitPid)
599
+ AXUIElementGetPid(target, &targetPid)
600
+ var count: CFIndex = 0
601
+ AXUIElementGetAttributeValueCount(hit, kAXChildrenAttribute as CFString, &count)
602
+ guard hitPid == targetPid, count == 0, let v = values(hit), text(v[0]) == "AXGroup",
603
+ (text(v[2]) ?? "").isEmpty, (text(v[3]) ?? "").isEmpty
604
+ else { return false }
605
+ func parent(_ e: AXUIElement) -> AXUIElement? {
606
+ var up: AnyObject?
607
+ guard AXUIElementCopyAttributeValue(e, kAXParentAttribute as CFString, &up) == .success,
608
+ let found = up, CFGetTypeID(found) == AXUIElementGetTypeID()
609
+ else { return nil }
610
+ return (found as! AXUIElement)
611
+ }
612
+ func holdsTarget(_ dialog: AXUIElement) -> Bool {
613
+ var at: AXUIElement? = target
614
+ for _ in 0..<80 {
615
+ guard let now = at else { return false }
616
+ if CFEqual(now, dialog) { return true }
617
+ at = parent(now)
618
+ }
619
+ return false
620
+ }
621
+ // A popup is drawn after its backdrop: a later sibling with content that does not hold the
622
+ // target is in front of it, with a mark of a dialog or not. Discord's empty layer has no such
623
+ // sibling.
624
+ var siblings: AnyObject?
625
+ if let up = parent(hit),
626
+ AXUIElementCopyAttributeValue(up, kAXChildrenAttribute as CFString, &siblings) == .success,
627
+ let all = siblings as? [AXUIElement],
628
+ let index = all.firstIndex(where: { CFEqual($0, hit) })
629
+ {
630
+ for later in all[(index + 1)...] {
631
+ var size: CFIndex = 0
632
+ AXUIElementGetAttributeValueCount(later, kAXChildrenAttribute as CFString, &size)
633
+ if size > 0 && !holdsTarget(later) { return false }
634
+ }
635
+ }
636
+ // The dialogs near the layer: in the parent of the layer, a few levels down.
637
+ var level = parent(hit).map { [$0] } ?? []
638
+ for _ in 0..<4 {
639
+ var next: [AXUIElement] = []
640
+ for element in level {
641
+ var role: AnyObject?
642
+ var subrole: AnyObject?
643
+ AXUIElementCopyAttributeValue(element, kAXRoleAttribute as CFString, &role)
644
+ AXUIElementCopyAttributeValue(element, kAXSubroleAttribute as CFString, &subrole)
645
+ let isDialog =
646
+ role as? String == "AXSheet" || subrole as? String == "AXApplicationDialog"
647
+ || subrole as? String == "AXDialog"
648
+ if isDialog && !holdsTarget(element) { return false }
649
+ var kids: AnyObject?
650
+ AXUIElementCopyAttributeValue(element, kAXChildrenAttribute as CFString, &kids)
651
+ next += (kids as? [AXUIElement]) ?? []
652
+ }
653
+ level = next
654
+ }
655
+ return true
656
+ }
657
+
658
+ /// Whether a person who clicks the middle of `target` reaches `target`: the topmost element on the
659
+ /// screen at that point is the target or sits inside it.
660
+ ///
661
+ /// A call that fails is not "covered". A busy machine fails this call now and then, so it is asked
662
+ /// three times, and a failure is reported as its own answer.
663
+ func reach(_ target: AXUIElement, _ rect: CGRect) -> Reach {
664
+ let system = AXUIElementCreateSystemWide()
665
+ var code = AXError.failure
666
+ for attempt in 0..<3 {
667
+ if attempt > 0 { Thread.sleep(forTimeInterval: 0.04) }
668
+ var hit: AXUIElement?
669
+ code = AXUIElementCopyElementAtPosition(system, Float(rect.midX), Float(rect.midY), &hit)
670
+ guard code == .success, let top = hit else { continue }
671
+ var at = top
672
+ // Up to the target from what is under the point. A web page nests deep: the text under the
673
+ // middle of Slack's page in Dia was 15 levels below its document, and 8 levels refused it.
674
+ for _ in 0..<64 {
675
+ if CFEqual(at, target) { return .yes }
676
+ var parent: AnyObject?
677
+ guard AXUIElementCopyAttributeValue(at, kAXParentAttribute as CFString, &parent) == .success,
678
+ let up = parent, CFGetTypeID(up) == AXUIElementGetTypeID()
679
+ else { break }
680
+ at = up as! AXUIElement
681
+ }
682
+ // A text or a picture that takes no click is not the answer of a hit test: the system gives
683
+ // the element that holds it. That is no cover. Only for those two roles, and only for an
684
+ // element near above the target: a button that is not the answer has something on top of it.
685
+ var targetRole: AnyObject?
686
+ AXUIElementCopyAttributeValue(target, kAXRoleAttribute as CFString, &targetRole)
687
+ if let role = targetRole as? String, role == "AXStaticText" || role == "AXImage" {
688
+ var up = target
689
+ for _ in 0..<3 {
690
+ var parent: AnyObject?
691
+ guard AXUIElementCopyAttributeValue(up, kAXParentAttribute as CFString, &parent) == .success,
692
+ let above = parent, CFGetTypeID(above) == AXUIElementGetTypeID()
693
+ else { break }
694
+ up = above as! AXUIElement
695
+ if CFEqual(up, top) { return .yes }
696
+ }
697
+ }
698
+ if passesThrough(top, to: target) { return .yes }
699
+ // A bare window as the answer says nothing about the point: a plain view with no element of
700
+ // its own over the target (the fixture's Cover) answers so, and so does Dia's profile sidebar.
701
+ // The two cannot be told apart here, so it stays "covered". A point from the picture still works.
702
+ let v = values(top)
703
+ let role = v.flatMap { text($0[0]) } ?? "element"
704
+ let name = v.flatMap { text($0[2]) ?? text($0[3]) } ?? ""
705
+ var owner: pid_t = 0
706
+ AXUIElementGetPid(top, &owner)
707
+ let app = NSRunningApplication(processIdentifier: owner)?.localizedName ?? "pid \(owner)"
708
+ let front = windowOwner(at: CGPoint(x: rect.midX, y: rect.midY))
709
+ let server = front.map { "; front window: \($0.name) layer \($0.layer)" } ?? "; front window: none"
710
+ // The words of an element of ANOTHER application are not said: they are what the person has
711
+ // open there (the subject of a mail was reported once), and the caller needs only the
712
+ // application to know what covers the target.
713
+ var own: pid_t = 0
714
+ AXUIElementGetPid(target, &own)
715
+ let what = owner == own ? "\(role) \"\(name)\"" : "a \(role)"
716
+ return .no(by: "\(what) of \(app)\(server)")
717
+ }
718
+ return .unknown(code: Int(code.rawValue))
719
+ }
720
+
721
+ /// How long the application must show no change before an action is called finished: 500 ms, the
722
+ /// quiet time the engine uses for a web page. The fixture holds it: an effect in two steps, 300 ms
723
+ /// apart, is cut off after the first step with a quiet time of 100 ms. A caller that knows its
724
+ /// application can set another time in the environment.
725
+ let quietNeededMs = Int(ProcessInfo.processInfo.environment["RETICLE_AX_QUIET_MS"] ?? "") ?? 500
726
+
727
+ /// The processes that a process started, and the ones those started.
728
+ func descendants(_ pid: pid_t, _ depth: Int = 0) -> [pid_t] {
729
+ guard depth < 6 else { return [] }
730
+ var buffer = [pid_t](repeating: 0, count: 512)
731
+ let size = Int32(buffer.count * MemoryLayout<pid_t>.size)
732
+ let found = Int(proc_listchildpids(pid, &buffer, size))
733
+ guard found > 0 else { return [] }
734
+ let children = buffer.prefix(min(found, buffer.count)).filter { $0 > 0 }
735
+ return children + children.flatMap { descendants($0, depth + 1) }
736
+ }
737
+
738
+ /// The bytes that a process and the processes it started have written to disk, as the kernel
739
+ /// counts them. It is a fact from the operating system and not from the application: an
740
+ /// application that says "saved" and wrote nothing has a count that did not move.
741
+ ///
742
+ /// An application made of several processes (a browser, an Electron application) writes from a
743
+ /// child, so the children are counted too. Two writers are not counted: a helper that the system
744
+ /// started for the application, which is not its child, and a child that wrote and ended before
745
+ /// the count was read. The caller must not read zero as "no write anywhere".
746
+ /// nil when the kernel does not answer for the process itself.
747
+ func bytesWritten(_ pid: pid_t) -> UInt64? {
748
+ func one(_ pid: pid_t) -> UInt64? {
749
+ var info = rusage_info_v4()
750
+ let result = withUnsafeMutablePointer(to: &info) {
751
+ $0.withMemoryRebound(to: rusage_info_t?.self, capacity: 1) {
752
+ proc_pid_rusage(pid, RUSAGE_INFO_V4, $0)
753
+ }
754
+ }
755
+ return result == 0 ? info.ri_diskio_byteswritten : nil
756
+ }
757
+ guard let own = one(pid) else { return nil }
758
+ return descendants(pid).reduce(own) { $0 + (one($1) ?? 0) }
759
+ }
760
+
761
+ /// Whether a running application is in a sandbox, asked of its code signature. nil when the
762
+ /// system does not answer.
763
+ ///
764
+ /// It was asked of the file system before: is there a folder for the application in
765
+ /// ~/Library/Containers. macOS guards that folder, and a look into it can put a question on the
766
+ /// person's screen ("would like to access data from other apps"). The signature needs no such
767
+ /// look.
768
+ func sandboxed(_ pid: pid_t) -> Bool? {
769
+ var code: SecCode?
770
+ let attributes = [kSecGuestAttributePid: pid] as CFDictionary
771
+ guard SecCodeCopyGuestWithAttributes(nil, attributes, [], &code) == errSecSuccess, let code
772
+ else { return nil }
773
+ var fixed: SecStaticCode?
774
+ guard SecCodeCopyStaticCode(code, [], &fixed) == errSecSuccess, let fixed else { return nil }
775
+ var info: CFDictionary?
776
+ let flags = SecCSFlags(rawValue: kSecCSSigningInformation)
777
+ guard SecCodeCopySigningInformation(fixed, flags, &info) == errSecSuccess,
778
+ let facts = info as? [String: Any]
779
+ else { return nil }
780
+ let entitlements = facts[kSecCodeInfoEntitlementsDict as String] as? [String: Any]
781
+ return (entitlements?["com.apple.security.app-sandbox"] as? Bool) == true
782
+ }
783
+
784
+ /// The settings of an application: the values in its preferences domain, each as text.
785
+ ///
786
+ /// nil when they cannot be read from outside the application. An application in a sandbox keeps
787
+ /// its settings in its own container, and a read from here gives nothing: that is "not read", and
788
+ /// it must not be taken for "no setting changed".
789
+ func settings(_ pid: pid_t) -> [String: String]? {
790
+ guard let app = NSRunningApplication(processIdentifier: pid),
791
+ let domain = app.bundleIdentifier ?? app.executableURL?.lastPathComponent
792
+ else { return nil }
793
+ // An application in a sandbox: not read. Nil too when the question has no answer.
794
+ guard sandboxed(pid) == false else { return nil }
795
+ CFPreferencesAppSynchronize(domain as CFString)
796
+ let all =
797
+ CFPreferencesCopyMultiple(
798
+ nil, domain as CFString, kCFPreferencesCurrentUser, kCFPreferencesAnyHost) as? [String: Any]
799
+ ?? [:]
800
+ return all.mapValues { String(describing: $0) }
801
+ }
802
+
803
+ /// The settings that are different after an action: new, changed or gone.
804
+ ///
805
+ /// The whole values are compared. A value is given in its first 200 characters, and "cut" says so
806
+ /// when there was more: a change past that place is still a change, and the reader is told that
807
+ /// the two texts it sees are not the whole of it.
808
+ func settingsChanged(_ before: [String: String], _ after: [String: String]) -> [[String: Any]] {
809
+ Set(before.keys).union(after.keys).sorted().compactMap { key -> [String: Any]? in
810
+ let old = before[key] ?? ""
811
+ let new = after[key] ?? ""
812
+ guard before[key] != after[key] else { return nil }
813
+ var change: [String: Any] = ["key": key, "old": String(old.prefix(200)), "new": String(new.prefix(200))]
814
+ if old.count > 200 || new.count > 200 { change["cut"] = true }
815
+ return change
816
+ }
817
+ }
818
+
819
+ /// The clipboard. Its change count goes up each time something is put on it. The helper reads the
820
+ /// count and never the content: what a person copied is not the realm's to read.
821
+ ///
822
+ /// A check can name another clipboard in the environment, so that it does not write over the one
823
+ /// the person at the machine uses.
824
+ let clipboard: NSPasteboard = {
825
+ if let name = ProcessInfo.processInfo.environment["RETICLE_AX_PASTEBOARD"], !name.isEmpty {
826
+ return NSPasteboard(name: NSPasteboard.Name(name))
827
+ }
828
+ return NSPasteboard.general
829
+ }()
830
+
831
+ /// The applications this process has read once. See the first read, in `tree`.
832
+ var readBefore = Set<pid_t>()
833
+
834
+ /// Key codes of the ANSI keyboard. A letter here is the key at that place, for a shortcut.
835
+ let keyCodes: [String: CGKeyCode] = [
836
+ "return": 36, "enter": 36, "tab": 48, "space": 49, "escape": 53, "backspace": 51, "delete": 117,
837
+ "arrowleft": 123, "arrowright": 124, "arrowdown": 125, "arrowup": 126, "home": 115, "end": 119,
838
+ "pageup": 116, "pagedown": 121,
839
+ "a": 0, "s": 1, "d": 2, "f": 3, "h": 4, "g": 5, "z": 6, "x": 7, "c": 8, "v": 9, "b": 11, "q": 12,
840
+ "w": 13, "e": 14, "r": 15, "y": 16, "t": 17, "o": 31, "u": 32, "i": 34, "p": 35, "l": 37, "j": 38,
841
+ "k": 40, "n": 45, "m": 46,
842
+ // Digits and marks: shortcuts such as Command-1 or Command-= use them.
843
+ "1": 18, "2": 19, "3": 20, "4": 21, "5": 23, "6": 22, "7": 26, "8": 28, "9": 25, "0": 29,
844
+ "-": 27, "=": 24, "[": 33, "]": 30, "\\": 42, ";": 41, "'": 39, ",": 43, ".": 47, "/": 44,
845
+ "`": 50,
846
+ // The function keys: editors of video and sound use them (Shift-F12 appends a clip in Resolve).
847
+ "f1": 122, "f2": 120, "f3": 99, "f4": 118, "f5": 96, "f6": 97, "f7": 98, "f8": 100, "f9": 101,
848
+ "f10": 109, "f11": 103, "f12": 111,
849
+ ]
850
+ let modifierFlags: [String: CGEventFlags] = [
851
+ "meta": .maskCommand, "shift": .maskShift, "alt": .maskAlternate, "control": .maskControl,
852
+ ]
853
+
854
+ /// One command: `args` are the words of a command line, the program name first.
855
+ /// The screen is locked, as the session says it.
856
+ func screenIsLocked() -> Bool {
857
+ let session = CGSessionCopyCurrentDictionary() as? [String: Any]
858
+ return (session?["CGSSessionScreenIsLocked"] as? Bool) == true
859
+ }
860
+
861
+ /// The process is there, and it is not one that ended and waits to be collected by its parent.
862
+ ///
863
+ /// The system is asked for the path of the program: it has none for a process that ended. The
864
+ /// list of running applications was asked before. It said "not there" for a moment while an
865
+ /// application came to the front, and the realm then said that a living application had ended.
866
+ func isRunning(_ pid: pid_t) -> Bool {
867
+ if kill(pid, 0) != 0 && errno == ESRCH { return false }
868
+ var path = [CChar](repeating: 0, count: 4096)
869
+ return proc_pidpath(pid, &path, UInt32(path.count)) > 0
870
+ }
871
+
872
+ func run(_ args: [String]) throws {
873
+ if args.count >= 2, args[1] == "apps" {
874
+ // The applications a person could mean by a name: the name they see, and the name of the
875
+ // process. Only names and numbers, and only of applications that have a face.
876
+ let list = NSWorkspace.shared.runningApplications
877
+ .filter { $0.activationPolicy != .prohibited && !$0.isTerminated && kill($0.processIdentifier, 0) == 0 }
878
+ .map { app -> [String: Any] in
879
+ [
880
+ "name": app.localizedName ?? "",
881
+ "process": app.executableURL?.lastPathComponent ?? "",
882
+ "pid": Int(app.processIdentifier),
883
+ // In the Dock, with windows of its own: what a person calls an application.
884
+ "regular": app.activationPolicy == .regular,
885
+ // When it was started. Of two with one name, the caller takes the newer one.
886
+ "launched": app.launchDate?.timeIntervalSince1970 ?? 0,
887
+ ]
888
+ }
889
+ try emit(["apps": list])
890
+ }
891
+ if args.count >= 2, args[1] == "texts" {
892
+ // The words in a picture, each with its box in the pixels of the picture: the same space as a
893
+ // `point` of a picture. A canvas, a game or a remote desktop has no elements, and its words
894
+ // are what an agent looks for. Vision reads them on this machine; nothing leaves it.
895
+ guard args.count >= 3, let image = NSImage(contentsOfFile: args[2]),
896
+ let picture = image.cgImage(forProposedRect: nil, context: nil, hints: nil)
897
+ else { try emit(["error": "usage"]) }
898
+ let request = VNRecognizeTextRequest()
899
+ request.recognitionLevel = .accurate
900
+ request.usesLanguageCorrection = false
901
+ try? VNImageRequestHandler(cgImage: picture, options: [:]).perform([request])
902
+ let width = Double(picture.width)
903
+ let height = Double(picture.height)
904
+ let found: [[String: Any]] = (request.results ?? []).compactMap { seen in
905
+ guard let best = seen.topCandidates(1).first else { return nil }
906
+ // Vision's box is a fraction, from the bottom left. The picture's points are from the top left.
907
+ let box = seen.boundingBox
908
+ return [
909
+ "text": best.string, "confidence": Double(best.confidence),
910
+ "box": [
911
+ (box.minX * width).rounded(), ((1 - box.maxY) * height).rounded(),
912
+ (box.width * width).rounded(), (box.height * height).rounded(),
913
+ ],
914
+ ]
915
+ }
916
+ try emit(["texts": found])
917
+ }
918
+
919
+ guard args.count >= 3, let pid = Int32(args[2]) else {
920
+ try emit(["error": "usage"])
921
+ }
922
+ guard AXIsProcessTrusted() else {
923
+ try emit(["error": "not-trusted"])
924
+ }
925
+ // An application that ended gives a read with nothing in it, and that looked like an
926
+ // application with no window. Say that it ended.
927
+ guard isRunning(pid) else {
928
+ try emit(["error": "app-gone"])
929
+ }
930
+ // With the screen locked, the system gives no window of any application: the application read
931
+ // as one with no window, and nothing said why.
932
+ guard !screenIsLocked() else {
933
+ try emit(["error": "screen-locked"])
934
+ }
935
+ // Not the realm's own window. Pause in that window is for the person at the machine: a realm
936
+ // that can read the window can press Resume in it, and the pause is then worth nothing. The
937
+ // check of the window sets this name in the environment, and nothing else does.
938
+ var program = [CChar](repeating: 0, count: 4096)
939
+ if proc_pidpath(pid, &program, UInt32(program.count)) > 0,
940
+ URL(fileURLWithPath: String(cString: program)).lastPathComponent == hudProgram,
941
+ ProcessInfo.processInfo.environment["RETICLE_AX_CHECKS_ITS_OWN_WINDOW"] == nil
942
+ {
943
+ try emit(["error": "own-window"])
944
+ }
945
+ let app = AXUIElementCreateApplication(pid)
946
+
947
+ if args[1] == "web-tree" {
948
+ // An Electron application gives its tree with no switch, and then does nothing for a press:
949
+ // the press is answered with "done" and the page never gets it. With this attribute on, the
950
+ // press works. It is the attribute that Electron documents for a tool that is not a screen
951
+ // reader. It costs the application some speed, so it is set only when the person asks, and
952
+ // set back when the realm leaves.
953
+ if args.count > 3 && args[3] == "try" {
954
+ // Some native applications build part of their tree only for a screen reader: Numbers gives
955
+ // its sheet as an empty scroll area, and with this switch every cell with its value. Set it,
956
+ // and keep it only when the tree grew: for an application that already gives all of it, the
957
+ // switch only costs speed.
958
+ var before = snapshot(app)
959
+ for _ in 0..<12 {
960
+ Thread.sleep(forTimeInterval: 0.15)
961
+ let again = snapshot(app)
962
+ if again.json == before.json { break }
963
+ before = again
964
+ }
965
+ // Not any growth: a feed or a list that loads by itself grows too, and would keep a switch
966
+ // that only costs it speed. The switch is kept when a container that held nothing but its
967
+ // scroll bars now holds content, as the sheet of Numbers does.
968
+ let empty = emptyContainers(before.tree)
969
+ AXUIElementSetAttributeValue(app, "AXEnhancedUserInterface" as CFString, kCFBooleanTrue)
970
+ readBefore.remove(pid)
971
+ var grew = false
972
+ var last = before.json
973
+ let until = Date().addingTimeInterval(3)
974
+ while Date() < until {
975
+ Thread.sleep(forTimeInterval: 0.15)
976
+ let now = snapshot(app)
977
+ if !empty.isDisjoint(with: filledContainers(now.tree, among: empty)) { grew = true }
978
+ if grew && now.json == last { break }
979
+ last = now.json
980
+ }
981
+ if !grew {
982
+ AXUIElementSetAttributeValue(app, "AXEnhancedUserInterface" as CFString, kCFBooleanFalse)
983
+ }
984
+ try emit(["set": grew])
985
+ }
986
+ let on = args.count > 3 && args[3] == "on"
987
+ if on {
988
+ // An application that just started has no window yet. A switch that is set then is in
989
+ // effect at a time nobody knows, and the wait below ends too soon. Wait for a window first,
990
+ // five seconds at most: an application with no window at all gets the switch as before.
991
+ let until = Date().addingTimeInterval(5)
992
+ while Date() < until {
993
+ var windows: AnyObject?
994
+ AXUIElementCopyAttributeValue(app, kAXWindowsAttribute as CFString, &windows)
995
+ if let list = windows as? [AXUIElement], !list.isEmpty { break }
996
+ Thread.sleep(forTimeInterval: 0.15)
997
+ }
998
+ }
999
+ // The tree as it is before the switch, read until two reads agree: a web view makes its tree
1000
+ // when it is first asked, and that first growth must not be taken for the switch.
1001
+ var before = snapshot(app).json
1002
+ for _ in 0..<12 {
1003
+ Thread.sleep(forTimeInterval: 0.15)
1004
+ let again = snapshot(app).json
1005
+ if again == before { break }
1006
+ before = again
1007
+ }
1008
+ let result = AXUIElementSetAttributeValue(
1009
+ app, "AXManualAccessibility" as CFString, on ? kCFBooleanTrue : kCFBooleanFalse)
1010
+ // The second switch, the one a screen reader sets. Electron does a press with the first one
1011
+ // alone. Chrome does not: it gives its tree, answers "done" to a press, and the page gets no
1012
+ // click. With this one the click comes. Its answer is not read: Chrome says "not implemented"
1013
+ // and takes it.
1014
+ _ = AXUIElementSetAttributeValue(
1015
+ app, "AXEnhancedUserInterface" as CFString, on ? kCFBooleanTrue : kCFBooleanFalse)
1016
+ readBefore.remove(pid)
1017
+ // The switch is not in effect at once. For some seconds the application gives the same tree
1018
+ // as before, answers "done" to a press, and loses the press. When the switch is in effect the
1019
+ // tree is another one (a heading gets its level, for one). So wait until the tree has changed
1020
+ // and two reads agree, for five seconds at most. With no change in that time, the tree was
1021
+ // the full one already.
1022
+ if on && result == .success {
1023
+ var last = before
1024
+ var changed = false
1025
+ // By the clock, and not by a count of reads: a read of a large page takes time of its own.
1026
+ let until = Date().addingTimeInterval(5)
1027
+ while Date() < until {
1028
+ Thread.sleep(forTimeInterval: 0.15)
1029
+ let now = snapshot(app).json
1030
+ if now != before { changed = true }
1031
+ if changed && now == last { break }
1032
+ last = now
1033
+ }
1034
+ } else if on {
1035
+ // Chrome refuses the first switch and takes the second one. Its tree does not change when
1036
+ // the switch is in effect, so there is nothing to wait for but time. Measured on Chrome: a
1037
+ // press is lost up to 2.4 s after the switch, and it comes from 3.3 s on.
1038
+ // ponytail: a fixed four seconds. Wait for a true sign when one is found.
1039
+ Thread.sleep(forTimeInterval: 4)
1040
+ }
1041
+ try emit(["set": result == .success])
1042
+ }
1043
+
1044
+ if args[1] == "capture" {
1045
+ // A picture of the application's own window, and of nothing else: the window server draws
1046
+ // the window by its number, also when another window is over it. For an application that
1047
+ // gives no elements (a canvas, a game), the picture is what there is to read.
1048
+ guard args.count >= 4 else { try emit(["error": "usage"]) }
1049
+ guard CGPreflightScreenCaptureAccess() else {
1050
+ try emit(["ok": false, "reason": "no-screen-recording-permission"])
1051
+ }
1052
+ let best = mainWindow(pid)
1053
+ // "screen": the whole display that holds the application's window, with every application
1054
+ // on it. An overlay of another application, or a dialog of the system, is there too.
1055
+ if args.count >= 5, args[4] == "screen" {
1056
+ var displays = [CGDirectDisplayID](repeating: 0, count: 16)
1057
+ var count: UInt32 = 0
1058
+ CGGetActiveDisplayList(16, &displays, &count)
1059
+ let active = Array(displays.prefix(Int(count)))
1060
+ let display =
1061
+ best.flatMap { b in active.first { CGDisplayBounds($0).intersects(b.rect) } }
1062
+ ?? CGMainDisplayID()
1063
+ let bounds = CGDisplayBounds(display)
1064
+ // screencapture numbers the displays from 1, in the order of the active list.
1065
+ let number = (active.firstIndex(of: display) ?? 0) + 1
1066
+ let shot = Process()
1067
+ shot.executableURL = URL(fileURLWithPath: "/usr/sbin/screencapture")
1068
+ shot.arguments = ["-x", "-D", String(number), args[3]]
1069
+ try? shot.run()
1070
+ shot.waitUntilExit()
1071
+ guard shot.terminationStatus == 0, FileManager.default.fileExists(atPath: args[3]) else {
1072
+ try emit(["ok": false, "reason": "the capture failed"])
1073
+ }
1074
+ let scale = Double(CGDisplayPixelsWide(display)) / Double(max(bounds.width, 1))
1075
+ let pixels = NSImage(contentsOfFile: args[3])?.representations.first?.pixelsWide ?? 0
1076
+ var answer: [String: Any] = [
1077
+ "ok": true, "path": args[3],
1078
+ "scale": pixels > 0 ? Double(pixels) / Double(bounds.width) : scale,
1079
+ "window": [bounds.origin.x, bounds.origin.y, bounds.width, bounds.height],
1080
+ ]
1081
+ if let b = best {
1082
+ answer["appWindow"] = [b.rect.origin.x, b.rect.origin.y, b.rect.width, b.rect.height]
1083
+ }
1084
+ try emit(answer)
1085
+ }
1086
+ guard let window = best else { try emit(["ok": false, "reason": "no-window-on-this-screen"]) }
1087
+ let shot = Process()
1088
+ shot.executableURL = URL(fileURLWithPath: "/usr/sbin/screencapture")
1089
+ // -x: no sound. -o: no shadow, so the picture is the window and its points are the window's.
1090
+ shot.arguments = ["-x", "-o", "-l", String(window.id), args[3]]
1091
+ try? shot.run()
1092
+ shot.waitUntilExit()
1093
+ guard shot.terminationStatus == 0, FileManager.default.fileExists(atPath: args[3]) else {
1094
+ try emit(["ok": false, "reason": "the capture failed"])
1095
+ }
1096
+ let scale =
1097
+ NSScreen.screens.first { $0.frame.intersects(window.rect) }?.backingScaleFactor ?? 2
1098
+ try emit([
1099
+ "ok": true, "path": args[3], "scale": Double(scale),
1100
+ "window": [window.rect.origin.x, window.rect.origin.y, window.rect.width, window.rect.height],
1101
+ ])
1102
+ }
1103
+
1104
+ if args[1] == "tree" {
1105
+ let started = Date()
1106
+ var shot = snapshot(app)
1107
+ // The first read of an application can be less than the application has. A web view makes
1108
+ // its accessibility tree when it is first asked, and the first answer had an empty group
1109
+ // where the page is. So the first read of each application is read again until two reads
1110
+ // agree, for a second at most.
1111
+ if !readBefore.contains(pid) {
1112
+ readBefore.insert(pid)
1113
+ for _ in 0..<8 {
1114
+ Thread.sleep(forTimeInterval: 0.12)
1115
+ let again = snapshot(app)
1116
+ let same = again.json == shot.json
1117
+ shot = again
1118
+ if same { break }
1119
+ }
1120
+ }
1121
+ try emit([
1122
+ "tree": shot.tree, "unread": shot.unread, "windowsNotOnScreen": windowsNotOnScreen(pid),
1123
+ "readMs": Int(Date().timeIntervalSince(started) * 1000),
1124
+ ])
1125
+ }
1126
+
1127
+ let onlyReach = args[1] == "reach"
1128
+ guard (args[1] == "act" && args.count >= 7) || (onlyReach && args.count >= 6) else {
1129
+ try emit(["error": "usage"])
1130
+ }
1131
+ let path = args[3].split(separator: ".").compactMap { Int($0) }
1132
+ let action = onlyReach ? "" : args[6]
1133
+ let value = args.count > 7 ? args[7] : ""
1134
+ let budgetMs = args.count > 8 ? Int(args[8]) ?? 1000 : 1000
1135
+ // The way to deliver, and after ":" the quiet time for this action when the caller gives one.
1136
+ let how = args.count > 9 ? args[9].split(separator: ":").map(String.init) : []
1137
+ let direct = how.first == "direct"
1138
+ // In the foreground: the application is brought to the front and the real pointer is used, as
1139
+ // a person uses it. It takes the pointer and the keyboard of the person at the machine for a
1140
+ // moment, so a caller asks for it by name. The pointer and the application that was in front
1141
+ // are put back after the action.
1142
+ let foreground = how.first == "foreground"
1143
+ /// A key goes to the application alone, with no use of the keyboard of the person at the machine.
1144
+ /// In the foreground it goes the way a real key goes: a panel that the system draws for the
1145
+ /// application (the save panel, the open panel) is another process, and a key that is sent to
1146
+ /// the application does not reach it.
1147
+ ///
1148
+ /// A real key goes to whatever application has the keyboard. So it is sent only when the system
1149
+ /// says that THIS application has it. A key that was meant for this application was once typed
1150
+ /// into the terminal of the person at the machine, because the application had not taken the
1151
+ /// keyboard. When it has not, no key is sent at all, and the action is refused.
1152
+ func hasKeyboard() -> Bool {
1153
+ RunLoop.current.run(until: Date())
1154
+ return NSWorkspace.shared.frontmostApplication?.processIdentifier == pid
1155
+ }
1156
+ func deliver(_ event: CGEvent) {
1157
+ if foreground { event.post(tap: .cghidEventTap) } else { event.postToPid(pid) }
1158
+ }
1159
+ let quietWanted = how.count > 1 ? Int(how[1]) ?? quietNeededMs : quietNeededMs
1160
+ let folders = Array(args.dropFirst(10))
1161
+
1162
+ /// The names, sizes and change times of every file in the watched folders, as one string.
1163
+ func filesNow() -> String {
1164
+ var out = ""
1165
+ for folder in folders {
1166
+ let keys: [URLResourceKey] = [.fileSizeKey, .contentModificationDateKey]
1167
+ guard
1168
+ let walk = FileManager.default.enumerator(
1169
+ at: URL(fileURLWithPath: folder), includingPropertiesForKeys: keys)
1170
+ else { continue }
1171
+ for case let url as URL in walk {
1172
+ let v = try? url.resourceValues(forKeys: Set(keys))
1173
+ out += "\(url.path)|\(v?.fileSize ?? -1)|\(v?.contentModificationDate?.timeIntervalSince1970 ?? 0)\n"
1174
+ }
1175
+ }
1176
+ return out
1177
+ }
1178
+
1179
+ var target = app
1180
+ for index in path {
1181
+ guard let next = child(target, index) else {
1182
+ try emit(["refused": "stale", "detail": "no element at the path"])
1183
+ }
1184
+ target = next
1185
+ }
1186
+ guard var now = values(target) else {
1187
+ try emit(["refused": "stale", "detail": "the element does not answer"])
1188
+ }
1189
+ let nameNow = [text(now[2]), text(now[3])].compactMap { $0 }.first { !$0.isEmpty } ?? ""
1190
+ guard text(now[0]) == args[4], nameNow == args[5] else {
1191
+ try emit(["refused": "stale", "detail": "a different element is at the path"])
1192
+ }
1193
+ if onlyReach {
1194
+ // Asks one thing and acts on nothing: can a person see and click this element now?
1195
+ switch frame(now[7], now[8]).map({ reach(target, $0) }) ?? .unknown(code: -1) {
1196
+ case .yes: try emit(["reach": "yes"])
1197
+ case .no(let by): try emit(["reach": "no", "detail": by])
1198
+ case .unknown(let code): try emit(["reach": "unknown", "detail": "the hit test failed with \(code)"])
1199
+ }
1200
+ }
1201
+ // An application with no window on the screen (all on another desktop, or in another set of
1202
+ // Stage Manager) says that it is not enabled. That is when a person brings it to the front, and
1203
+ // the realm refused to: Finder could not be brought back. A control that is off is refused.
1204
+ let raisesApp = action == "raise" && text(now[0]) == "AXApplication"
1205
+ if let enabled = now[5] as? Bool, !enabled, !raisesApp {
1206
+ try emit(["refused": "disabled"])
1207
+ }
1208
+
1209
+ var appBefore: NSRunningApplication?
1210
+ var pointerBefore: CGPoint?
1211
+ if foreground {
1212
+ // Not while the person at the machine types or moves the pointer: a key or a click of theirs
1213
+ // would land in the application that is brought to the front. Wait for a moment with no
1214
+ // input from them, and refuse when there is none in five seconds.
1215
+ func idleSeconds() -> Double {
1216
+ let any = CGEventType(rawValue: ~0)!
1217
+ return CGEventSource.secondsSinceLastEventType(.hidSystemState, eventType: any)
1218
+ }
1219
+ var waited = 0.0
1220
+ while idleSeconds() < 0.8 && waited < 5 {
1221
+ Thread.sleep(forTimeInterval: 0.1)
1222
+ waited += 0.1
1223
+ }
1224
+ guard idleSeconds() >= 0.8 else {
1225
+ try emit(["refused": "person-active", "detail": "the person at the machine is typing or moving the pointer"])
1226
+ }
1227
+ RunLoop.current.run(until: Date())
1228
+ appBefore = NSWorkspace.shared.frontmostApplication
1229
+ pointerBefore = CGEvent(source: nil)?.location
1230
+ // Two ways to bring it to the front, and the first is the one that works on a new macOS: a
1231
+ // tool for accessibility may say that an application is the one in front. The plain request
1232
+ // to activate is one the system is free to pass over, and it did for an application that was
1233
+ // opened in the background.
1234
+ AXUIElementSetAttributeValue(app, kAXFrontmostAttribute as CFString, kCFBooleanTrue)
1235
+ NSRunningApplication(processIdentifier: pid)?.activate(options: [])
1236
+ // Not long: an application that never takes the front (a panel, an accessory) is acted on
1237
+ // where it is, and the reach test below says if a person could click it.
1238
+ for _ in 0..<12 where !isInFront(pid) { Thread.sleep(forTimeInterval: 0.05) }
1239
+ }
1240
+ /// Puts the pointer and the application in front back as they were. Not after a hover or a
1241
+ /// raise: what those are for is gone when the pointer or the application goes away.
1242
+ func putBack() {
1243
+ guard foreground, action != "hover", action != "raise" else { return }
1244
+ if let was = pointerBefore { CGWarpMouseCursorPosition(was) }
1245
+ if let was = appBefore, was.processIdentifier != pid {
1246
+ // The same two ways as above: the plain request alone can be passed over, and the person
1247
+ // would then be left with the keyboard in the wrong application.
1248
+ AXUIElementSetAttributeValue(
1249
+ AXUIElementCreateApplication(was.processIdentifier), kAXFrontmostAttribute as CFString,
1250
+ kCFBooleanTrue)
1251
+ was.activate(options: [])
1252
+ }
1253
+ }
1254
+
1255
+ let before = snapshot(app)
1256
+ let filesBefore = filesNow()
1257
+ let writtenBefore = bytesWritten(pid)
1258
+ let settingsBefore = settings(pid)
1259
+ let clipboardBefore = clipboard.changeCount
1260
+ var canReach = false
1261
+ var coveredBy = ""
1262
+ // To bring an application to the front, nothing has to be reached: an application with no
1263
+ // window has no place on the screen at all, and it can still come to the front.
1264
+ // A pointer action at a given point goes to that point, not to the middle of the element: the
1265
+ // point has its own test below. A hover at the edge of a window that a sidebar covers was
1266
+ // refused here, because the middle of the window was under that sidebar.
1267
+ // A drag from a point gives four numbers, and the wheel at a point gives three.
1268
+ // A pointer action carries its points first, and after "|" how the hand holds it: the keys held
1269
+ // ("mods=shift+alt") and how long the button stays down ("hold=500"). Only for the pointer: a
1270
+ // text that is typed can hold a "|" of its own.
1271
+ let pointerActions: Set<String> = ["click", "dblclick", "rightclick", "hover", "drag", "wheel"]
1272
+ let handParts = pointerActions.contains(action) ? value.components(separatedBy: "|") : [value]
1273
+ let pointValue = handParts.first ?? ""
1274
+ var hand: [String: String] = [:]
1275
+ for part in handParts.dropFirst() {
1276
+ let pair = part.split(separator: "=", maxSplits: 1).map(String.init)
1277
+ if pair.count == 2 { hand[pair[0]] = pair[1] }
1278
+ }
1279
+ // A canvas shows its effect only in pixels: take the window's picture before the hand moves.
1280
+ // Only for a pointer in the foreground, where the window is on the screen to be drawn.
1281
+ // The realm asks for it ("pixels=1") only for a point of a picture or an element that can be a
1282
+ // canvas: each picture costs time, and a button shows its effect in its elements.
1283
+ let pictureWindow = foreground && pointerActions.contains(action) && action != "hover"
1284
+ && hand["pixels"] == "1" ? mainWindow(pid) : nil
1285
+ // A window that just came to the front draws itself again (a selection turns from grey to
1286
+ // blue). That redraw is not the action's effect: wait for it before the first picture.
1287
+ if pictureWindow != nil, let was = appBefore, was.processIdentifier != pid {
1288
+ Thread.sleep(forTimeInterval: 0.2)
1289
+ }
1290
+ // Two pictures, a moment apart: what moves between them moves by itself (a video that plays).
1291
+ let pixelsEarlier = pictureWindow.flatMap { windowPixels($0.id) }
1292
+ if pixelsEarlier != nil { Thread.sleep(forTimeInterval: 0.1) }
1293
+ let pixelsBefore = pictureWindow.flatMap { windowPixels($0.id) }
1294
+ let pointNumbers = pointValue.split(separator: ",").compactMap({ Double($0) })
1295
+ let pointCount = ["click": 2, "dblclick": 2, "rightclick": 2, "hover": 2, "wheel": 3]
1296
+ // A drag from a point is four numbers or more: a start, then each point of its path.
1297
+ let atPoint =
1298
+ action == "drag"
1299
+ ? pointNumbers.count >= 4 && pointNumbers.count % 2 == 0
1300
+ : pointCount[action] == pointNumbers.count
1301
+ // A key to the application as a whole aims at no point, so the test of a click does not apply:
1302
+ // the middle of the Dock is under the menu bar of the application in front. A key to a field
1303
+ // keeps the test.
1304
+ // Typing is keys too: a person types into the application in front, not at a point of it.
1305
+ // A key to a window or to the page of a browser goes to what has the keyboard there, as to the
1306
+ // application: Slack's search shortcut was refused because its window was "covered" at its middle.
1307
+ let keyRoles: Set<String> = ["AXApplication", "AXWindow", "AXWebArea"]
1308
+ let keyToApp = (action == "key" || action == "type") && keyRoles.contains(text(now[0]) ?? "")
1309
+ let needsReach = !direct && action != "raise" && !atPoint && !keyToApp
1310
+ var reached = frame(now[7], now[8]).map({ reach(target, $0) }) ?? .unknown(code: -1)
1311
+ // Stage Manager keeps a window in its strip at the side until its application comes to the
1312
+ // front, and then slides it to the middle. The element is then covered by the strip, and its
1313
+ // place is the old one: a click was refused, and would have gone to the old place. Read the
1314
+ // element again while the window moves, three seconds at most: Slack's window, brought from
1315
+ // another Space, was still moving after a second and a half.
1316
+ if foreground, case .no = reached {
1317
+ let until = Date().addingTimeInterval(3.0)
1318
+ while Date() < until {
1319
+ Thread.sleep(forTimeInterval: 0.1)
1320
+ guard let fresh = values(target) else { break }
1321
+ now = fresh
1322
+ reached = frame(now[7], now[8]).map({ reach(target, $0) }) ?? .unknown(code: -1)
1323
+ if case .yes = reached { break }
1324
+ }
1325
+ }
1326
+ // A part of the element can be under another view (a handle of a table lies on the middle of a
1327
+ // cell). A person clicks the part they can see: try the middle of each quarter.
1328
+ var visiblePoint: CGPoint?
1329
+ if foreground, case .no = reached, let rect = frame(now[7], now[8]) {
1330
+ for (fx, fy) in [(0.25, 0.5), (0.75, 0.5), (0.5, 0.25), (0.5, 0.75)] {
1331
+ let point = CGPoint(x: rect.minX + rect.width * fx, y: rect.minY + rect.height * fy)
1332
+ if case .yes = reach(target, CGRect(origin: point, size: .zero)) {
1333
+ visiblePoint = point
1334
+ reached = .yes
1335
+ break
1336
+ }
1337
+ }
1338
+ }
1339
+ switch reached {
1340
+ case .yes: canReach = true
1341
+ case .no(let by):
1342
+ coveredBy = by
1343
+ if needsReach {
1344
+ putBack()
1345
+ try emit(["refused": "unreachable", "detail": by])
1346
+ }
1347
+ case .unknown(let code):
1348
+ if needsReach {
1349
+ putBack()
1350
+ try emit(["refused": "reach-unknown", "detail": "the hit test failed with \(code)"])
1351
+ }
1352
+ }
1353
+
1354
+ let started = Date()
1355
+ let result: AXError
1356
+ /// The window that `window` arranged, and the frame it was given: read again after the wait.
1357
+ var arranged: AXUIElement?
1358
+ var wantedFrame: CGRect?
1359
+ switch action {
1360
+ case "press":
1361
+ var targetRole: AnyObject?
1362
+ AXUIElementCopyAttributeValue(target, kAXRoleAttribute as CFString, &targetRole)
1363
+ // The words of a row: a text, a field or a picture inside it. A click of a person on them
1364
+ // chooses the row, or the item of a list (a file in a column of Finder). Only these: a button
1365
+ // or a box inside a row that refuses its press (it is busy, or it is off) must be reported as
1366
+ // refused, and never turned into a choice of its row that the answer then calls done.
1367
+ let isWords = ["AXStaticText", "AXTextField", "AXImage"].contains(targetRole as? String ?? "")
1368
+ // The words are not pressed when a row or an item holds them: the name field of a file in
1369
+ // Finder says yes to a press and to "selected", and nothing is chosen. The choice is read
1370
+ // again after it, because Finder chooses the file and answers with an error.
1371
+ var done: AXError?
1372
+ if isWords {
1373
+ var up = target
1374
+ for _ in 0..<4 {
1375
+ var parent: AnyObject?
1376
+ guard AXUIElementCopyAttributeValue(up, kAXParentAttribute as CFString, &parent) == .success,
1377
+ let above = parent, CFGetTypeID(above) == AXUIElementGetTypeID()
1378
+ else { break }
1379
+ let item = up
1380
+ up = above as! AXUIElement
1381
+ let role = values(up).flatMap { text($0[0]) }
1382
+ if role == "AXRow" {
1383
+ done = AXUIElementSetAttributeValue(up, kAXSelectedAttribute as CFString, kCFBooleanTrue)
1384
+ break
1385
+ }
1386
+ if role == "AXList" {
1387
+ AXUIElementSetAttributeValue(up, kAXSelectedChildrenAttribute as CFString, [item] as CFArray)
1388
+ var chosen: AnyObject?
1389
+ AXUIElementCopyAttributeValue(up, kAXSelectedChildrenAttribute as CFString, &chosen)
1390
+ let picked = ((chosen as? [AXUIElement]) ?? []).contains { CFEqual($0, item) }
1391
+ done = picked ? .success : .failure
1392
+ break
1393
+ }
1394
+ }
1395
+ }
1396
+ if done == nil {
1397
+ let pressed = AXUIElementPerformAction(target, kAXPressAction as CFString)
1398
+ // A row of a table has no press. A click on it chooses it, so choose it.
1399
+ done =
1400
+ pressed == .actionUnsupported && !isWords
1401
+ ? AXUIElementSetAttributeValue(target, kAXSelectedAttribute as CFString, kCFBooleanTrue)
1402
+ : pressed
1403
+ }
1404
+ result = done ?? .failure
1405
+ case "set":
1406
+ // An element whose value is a number (a slider, a scroll bar) takes a number, not its text.
1407
+ let number = now[4] is NSNumber ? Double(value).map { NSNumber(value: $0) } : nil
1408
+ result = AXUIElementSetAttributeValue(
1409
+ target, kAXValueAttribute as CFString, number ?? (value as CFString))
1410
+ case "type":
1411
+ if foreground && !hasKeyboard() {
1412
+ putBack()
1413
+ try emit(["refused": "no-keyboard", "detail": "the application did not take the keyboard"])
1414
+ }
1415
+ // Key events, one for each character, sent to the application and not to the screen: the
1416
+ // pointer and the keyboard of the person at the machine are not used. The element takes the
1417
+ // keyboard first, as a click in it does. Delivery proves nothing here. The caller reads the
1418
+ // value after it.
1419
+ _ = AXUIElementSetAttributeValue(target, kAXFocusedAttribute as CFString, kCFBooleanTrue)
1420
+ let source = CGEventSource(stateID: .hidSystemState)
1421
+ for unit in value.utf16 {
1422
+ var character = [unit]
1423
+ for down in [true, false] {
1424
+ guard let event = CGEvent(keyboardEventSource: source, virtualKey: 0, keyDown: down) else {
1425
+ continue
1426
+ }
1427
+ event.keyboardSetUnicodeString(stringLength: 1, unicodeString: &character)
1428
+ deliver(event)
1429
+ }
1430
+ usleep(4000)
1431
+ }
1432
+ result = .success
1433
+ case "key":
1434
+ // The shortcuts of Mission Control and the desktops. The system takes them before any
1435
+ // application does, so they need no application with the keyboard: the Dock, which holds
1436
+ // Mission Control, never has it. No other key goes without that check.
1437
+ let systemShortcuts: Set<String> = [
1438
+ "control+arrowup", "control+arrowdown", "control+arrowleft", "control+arrowright",
1439
+ ]
1440
+ if foreground && !hasKeyboard() && !systemShortcuts.contains(value.lowercased()) {
1441
+ putBack()
1442
+ try emit(["refused": "no-keyboard", "detail": "the application did not take the keyboard"])
1443
+ }
1444
+ // One key, with its modifiers: "Return", "Tab", "Meta+s". Sent to the application, as "type" is.
1445
+ let parts = value.split(separator: "+").map(String.init)
1446
+ guard let name = parts.last, let code = keyCodes[name.lowercased()] else {
1447
+ try emit(["error": "unknown-key"])
1448
+ }
1449
+ var flags: CGEventFlags = []
1450
+ for modifier in parts.dropLast() {
1451
+ guard let flag = modifierFlags[modifier.lowercased()] else { try emit(["error": "unknown-key"]) }
1452
+ flags.insert(flag)
1453
+ }
1454
+ // A real arrow key comes with the flags of the number pad and of Fn. The system matches its
1455
+ // shortcuts on the whole set of flags, so Control+Up with no such flags did not open Mission
1456
+ // Control. Only for those shortcuts: an arrow to a list in the background moved nothing with them.
1457
+ if systemShortcuts.contains(value.lowercased()) {
1458
+ flags.formUnion([.maskNumericPad, .maskSecondaryFn])
1459
+ }
1460
+ _ = AXUIElementSetAttributeValue(target, kAXFocusedAttribute as CFString, kCFBooleanTrue)
1461
+ let source = CGEventSource(stateID: .hidSystemState)
1462
+ for down in [true, false] {
1463
+ guard let event = CGEvent(keyboardEventSource: source, virtualKey: code, keyDown: down) else {
1464
+ continue
1465
+ }
1466
+ event.flags = flags
1467
+ deliver(event)
1468
+ }
1469
+ // A key with flags, posted to the system, leaves those flags held in its state when no key of
1470
+ // a modifier went up: Control, Fn and the number pad stayed held after Control+Up, and every
1471
+ // key typed after it on the machine was a Control key. Let them go, as a hand lets go.
1472
+ if foreground && !flags.isEmpty, let release = CGEvent(source: source) {
1473
+ release.type = .flagsChanged
1474
+ release.flags = []
1475
+ deliver(release)
1476
+ }
1477
+ result = .success
1478
+ case "menu":
1479
+ // The menu a right-click gives, asked for by name. No pointer is used.
1480
+ result = AXUIElementPerformAction(target, kAXShowMenuAction as CFString)
1481
+ case "window":
1482
+ // The window of the element, arranged as a person does it with its buttons and the Window
1483
+ // menu. No pointer: the window is set through the Accessibility API, also in the background.
1484
+ var window = target
1485
+ if text(now[0]) == "AXApplication" {
1486
+ // On the application, as a person uses its tile in the Dock: `restore` brings back a window
1487
+ // that is minimized or in full screen, and the others arrange the main window.
1488
+ var all: AnyObject?
1489
+ AXUIElementCopyAttributeValue(target, kAXWindowsAttribute as CFString, &all)
1490
+ let windows = (all as? [AXUIElement]) ?? []
1491
+ func flag(_ w: AXUIElement, _ name: String) -> Bool {
1492
+ var v: AnyObject?
1493
+ AXUIElementCopyAttributeValue(w, name as CFString, &v)
1494
+ return (v as? Bool) ?? false
1495
+ }
1496
+ var main: AnyObject?
1497
+ AXUIElementCopyAttributeValue(target, kAXMainWindowAttribute as CFString, &main)
1498
+ let hidden = windows.first { flag($0, kAXMinimizedAttribute) || flag($0, "AXFullScreen") }
1499
+ let chosen =
1500
+ value == "restore" ? hidden : (main.map { $0 as! AXUIElement } ?? windows.first)
1501
+ guard let found = chosen else {
1502
+ try emit(["refused": "no-window", "detail": "the application has no such window"])
1503
+ }
1504
+ window = found
1505
+ } else if text(now[0]) != "AXWindow" {
1506
+ var holder: AnyObject?
1507
+ guard AXUIElementCopyAttributeValue(target, kAXWindowAttribute as CFString, &holder) == .success,
1508
+ let found = holder, CFGetTypeID(found) == AXUIElementGetTypeID()
1509
+ else { try emit(["refused": "no-window", "detail": "the element is in no window"]) }
1510
+ window = found as! AXUIElement
1511
+ }
1512
+ arranged = window
1513
+ guard let (done, wanted) = arrange(window, value) else {
1514
+ try emit(["refused": "bad-value", "detail": "no arrangement \(value)"])
1515
+ }
1516
+ wantedFrame = wanted
1517
+ result = done
1518
+ case "raise":
1519
+ // The application is in front already: that was done above. Give the element the keyboard.
1520
+ guard foreground else { try emit(["refused": "needs-foreground"]) }
1521
+ _ = AXUIElementSetAttributeValue(target, kAXFocusedAttribute as CFString, kCFBooleanTrue)
1522
+ result = isInFront(pid) ? .success : .cannotComplete
1523
+ case "click", "dblclick", "rightclick", "hover", "drag", "wheel":
1524
+ // The real pointer. Only in the foreground: a pointer event that is sent to one application
1525
+ // in the background is not taken by it.
1526
+ guard foreground, let rect = frame(now[7], now[8]) else {
1527
+ try emit(["refused": "needs-foreground"])
1528
+ }
1529
+ // The middle of the element, or the point the caller gives as "x,y" on the screen: for an
1530
+ // application that gives no elements, a point in its picture is all a caller has.
1531
+ // The start of a drag is its first two numbers, and the point of the wheel its last two.
1532
+ let numbers = pointNumbers
1533
+ let given: [Double]
1534
+ switch action {
1535
+ case "drag": given = numbers.count >= 4 ? Array(numbers[0..<2]) : []
1536
+ case "wheel": given = numbers.count == 3 ? Array(numbers[1..<3]) : []
1537
+ default: given = numbers
1538
+ }
1539
+ let at =
1540
+ given.count == 2
1541
+ ? CGPoint(x: given[0], y: given[1]) : (visiblePoint ?? CGPoint(x: rect.midX, y: rect.midY))
1542
+ if given.count == 2 {
1543
+ // The reach test above is for the middle of the element. A point is another place: when a
1544
+ // window of another application is at that point, the click would go to that application.
1545
+ var hit: AXUIElement?
1546
+ var owner: pid_t = 0
1547
+ let found =
1548
+ AXUIElementCopyElementAtPosition(
1549
+ AXUIElementCreateSystemWide(), Float(at.x), Float(at.y), &hit) == .success
1550
+ if let top = hit { AXUIElementGetPid(top, &owner) }
1551
+ // A part of a window that gives no element (the pinned tabs of Dia's sidebar) fails the hit
1552
+ // test. The window server still knows whose window is in front at that point.
1553
+ let frontIsOwn = !found && windowOwner(at: at)?.pid == pid
1554
+ guard (found && owner == pid) || frontIsOwn else {
1555
+ putBack()
1556
+ let other = NSRunningApplication(processIdentifier: owner)?.localizedName ?? "another application"
1557
+ try emit([
1558
+ "refused": "unreachable",
1559
+ "detail": found ? "a window of \(other)" : "nothing this realm can name",
1560
+ ])
1561
+ }
1562
+ }
1563
+ let source = CGEventSource(stateID: .hidSystemState)
1564
+ // The keys a hand holds through the action: shift-click to add to a choice, option-drag to make
1565
+ // a copy, shift-drag for a straight line.
1566
+ var held: CGEventFlags = []
1567
+ for name in (hand["mods"] ?? "").lowercased().split(separator: "+") {
1568
+ switch name {
1569
+ case "shift": held.insert(.maskShift)
1570
+ case "alt", "option": held.insert(.maskAlternate)
1571
+ case "control", "ctrl": held.insert(.maskControl)
1572
+ case "meta", "command", "cmd": held.insert(.maskCommand)
1573
+ default: break
1574
+ }
1575
+ }
1576
+ let holdSeconds = min(10, max(0, Double(hand["hold"] ?? "0") ?? 0) / 1000)
1577
+ func send(_ type: CGEventType, _ point: CGPoint, _ button: CGMouseButton, clicks: Int64 = 1) {
1578
+ guard
1579
+ let event = CGEvent(
1580
+ mouseEventSource: source, mouseType: type, mouseCursorPosition: point, mouseButton: button)
1581
+ else { return }
1582
+ event.setIntegerValueField(.mouseEventClickState, value: clicks)
1583
+ if !held.isEmpty { event.flags = held }
1584
+ event.post(tap: .cghidEventTap)
1585
+ Thread.sleep(forTimeInterval: 0.03)
1586
+ }
1587
+ func flagsTo(_ flags: CGEventFlags) {
1588
+ guard let change = CGEvent(source: source) else { return }
1589
+ change.type = .flagsChanged
1590
+ change.flags = flags
1591
+ change.post(tap: .cghidEventTap)
1592
+ Thread.sleep(forTimeInterval: 0.02)
1593
+ }
1594
+ // Pressed before the pointer moves, and let go after it, whatever the action did.
1595
+ if !held.isEmpty { flagsTo(held) }
1596
+ defer { if !held.isEmpty { flagsTo([]) } }
1597
+ send(.mouseMoved, at, .left)
1598
+ // A second small move: a view learns that the pointer came in from a move inside it, and one
1599
+ // jump to its middle did not always tell it.
1600
+ send(.mouseMoved, CGPoint(x: at.x + 1, y: at.y + 1), .left)
1601
+ send(.mouseMoved, at, .left)
1602
+ switch action {
1603
+ case "click":
1604
+ // "count=3" is a triple-click (a line or a paragraph), "button=middle" the middle button.
1605
+ let middle = hand["button"] == "middle"
1606
+ let count = Int64(min(3, max(1, Int(hand["count"] ?? "1") ?? 1)))
1607
+ for n in 1...count {
1608
+ send(middle ? .otherMouseDown : .leftMouseDown, at, middle ? .center : .left, clicks: n)
1609
+ if holdSeconds > 0 && n == count { Thread.sleep(forTimeInterval: holdSeconds) }
1610
+ send(middle ? .otherMouseUp : .leftMouseUp, at, middle ? .center : .left, clicks: n)
1611
+ }
1612
+ case "dblclick":
1613
+ for count in [Int64(1), 2] {
1614
+ send(.leftMouseDown, at, .left, clicks: count)
1615
+ send(.leftMouseUp, at, .left, clicks: count)
1616
+ }
1617
+ case "rightclick":
1618
+ send(.rightMouseDown, at, .right)
1619
+ send(.rightMouseUp, at, .right)
1620
+ case "wheel":
1621
+ // Lines of the wheel over the element, in small turns as a hand gives them. More than 0 is
1622
+ // down; the system counts a turn up as more than 0, so the sign is turned over.
1623
+ // "across=5" in the hand turns it to the side: more than 0 is to the right.
1624
+ let lines = Int32(numbers.first ?? 0)
1625
+ let across = Int32(hand["across"] ?? "0") ?? 0
1626
+ let step: Int32 = lines == 0 ? 0 : (lines > 0 ? -3 : 3)
1627
+ let side: Int32 = across == 0 ? 0 : (across > 0 ? -3 : 3)
1628
+ for _ in 0..<max(1, max(abs(Int(lines)), abs(Int(across))) / 3) {
1629
+ guard
1630
+ let turn = CGEvent(
1631
+ scrollWheelEvent2Source: source, units: .line, wheelCount: 2, wheel1: step,
1632
+ wheel2: side, wheel3: 0)
1633
+ else { break }
1634
+ turn.location = at
1635
+ turn.post(tap: .cghidEventTap)
1636
+ Thread.sleep(forTimeInterval: 0.02)
1637
+ }
1638
+ case "drag":
1639
+ // To the point "x,y" on the screen, in steps: an application that follows a drag reads
1640
+ // where the pointer is on the way.
1641
+ // "x,y" of the end, from the element; or "x,y,x,y,..." from a start through each point of a
1642
+ // path: a stroke of a brush, a lasso, a curve. Each part of the way is walked in small steps,
1643
+ // as a hand moves, so an application that draws where the pointer is draws all of it.
1644
+ guard numbers.count >= 2 && numbers.count % 2 == 0 else { try emit(["error": "drag-needs-a-point"]) }
1645
+ var way: [CGPoint] = numbers.count == 2 ? [at] : []
1646
+ for i in stride(from: 0, to: numbers.count, by: 2) { way.append(CGPoint(x: numbers[i], y: numbers[i + 1])) }
1647
+ send(.leftMouseDown, way[0], .left)
1648
+ if holdSeconds > 0 { Thread.sleep(forTimeInterval: holdSeconds) }
1649
+ for (from, to) in zip(way, way.dropFirst()) {
1650
+ let length = hypot(to.x - from.x, to.y - from.y)
1651
+ let steps = max(4, min(40, Int(length / 6)))
1652
+ for step in 1...steps {
1653
+ let part = CGFloat(step) / CGFloat(steps)
1654
+ send(.leftMouseDragged, CGPoint(x: from.x + (to.x - from.x) * part, y: from.y + (to.y - from.y) * part), .left)
1655
+ }
1656
+ }
1657
+ send(.leftMouseUp, way[way.count - 1], .left)
1658
+ default: break
1659
+ }
1660
+ result = .success
1661
+ default: try emit(["error": "unknown-action"])
1662
+ }
1663
+
1664
+ // Wait for the application to finish. Notifications from AXObserver are not dependable from one
1665
+ // application to the next, and a read is cheap, so read again until the application is quiet.
1666
+ //
1667
+ // Quiet is a length of TIME with no change, not a number of reads. It was two reads that agree,
1668
+ // and when a read took 60 ms that was a long time. With a read of 5 ms it was 50 ms: a menu that
1669
+ // shows its choice for a moment before it closes was called finished before it ran its action.
1670
+ // An action that is called finished too soon gives a false "no effect".
1671
+ //
1672
+ // When nothing has changed at all, spend the whole budget: an early "nothing changed" is a false
1673
+ // result for every effect that takes longer than the first read.
1674
+ // A choice in a menu is not finished while its menu is on the screen. The menu shows the choice
1675
+ // for a moment, closes, and only then runs the action. No length of quiet time is right for
1676
+ // every application here, so this is a fact that is read: the menu that held the target.
1677
+ var menu: AXUIElement?
1678
+ var up: AXUIElement = target
1679
+ for _ in 0..<6 {
1680
+ var parent: AnyObject?
1681
+ guard AXUIElementCopyAttributeValue(up, kAXParentAttribute as CFString, &parent) == .success,
1682
+ let next = parent, CFGetTypeID(next) == AXUIElementGetTypeID()
1683
+ else { break }
1684
+ up = next as! AXUIElement
1685
+ if let v = values(up), text(v[0]) == "AXMenu" {
1686
+ menu = up
1687
+ break
1688
+ }
1689
+ }
1690
+ func menuShows() -> Bool {
1691
+ guard let menu, let v = values(menu), let rect = frame(v[7], v[8]) else { return false }
1692
+ return rect.width > 0 && rect.height > 0
1693
+ }
1694
+
1695
+ func sameButFocus(_ json: Data) -> String {
1696
+ String(decoding: json, as: UTF8.self).replacingOccurrences(
1697
+ of: "\"focused\":true", with: "\"focused\":false")
1698
+ }
1699
+ let startButFocus = sameButFocus(before.json)
1700
+ var last = before.json
1701
+ var lastFiles = filesBefore
1702
+ var after = before
1703
+ var quietSince = Date()
1704
+ func elapsedMs() -> Int { Int(Date().timeIntervalSince(started) * 1000) }
1705
+ func quietMs() -> Int { Int(Date().timeIntervalSince(quietSince) * 1000) }
1706
+ while elapsedMs() < budgetMs {
1707
+ Thread.sleep(forTimeInterval: 0.025)
1708
+ after = snapshot(app)
1709
+ let files = filesNow()
1710
+ if after.json != last || files != lastFiles || menuShows() { quietSince = Date() }
1711
+ last = after.json
1712
+ lastFiles = files
1713
+ // The keyboard coming to the target is not an effect. A button in a web view takes the
1714
+ // keyboard when it is pressed. That was "a change", so the wait ended before a slow effect,
1715
+ // and the next action was given that effect.
1716
+ if quietMs() >= quietWanted && (sameButFocus(after.json) != startButFocus || files != filesBefore) {
1717
+ break
1718
+ }
1719
+ }
1720
+ let settled = quietMs() >= quietWanted
1721
+ // Before the app in front is put back: the window then draws itself as one in the back.
1722
+ // The tree shows no change: the pixels can. Taken only then, so an action with elements pays
1723
+ // nothing more. A window that moved or is gone is not compared.
1724
+ var pixels: [String: Any]?
1725
+ if after.json == before.json, let window = pictureWindow, let was = pixelsBefore,
1726
+ let now = mainWindow(pid), now.id == window.id, now.rect.origin == window.rect.origin,
1727
+ let seen = windowPixels(now.id)
1728
+ {
1729
+ // And two after it: a motion that started with the action, or that is slow, shows there.
1730
+ Thread.sleep(forTimeInterval: 0.1)
1731
+ let later = windowPixels(now.id)
1732
+ var pairs: [(Pixels, Pixels)] = []
1733
+ if let earlier = pixelsEarlier { pairs.append((earlier, was)) }
1734
+ if let later { pairs.append((seen, later)) }
1735
+ pixels = pixelChange(was, seen, window: now.rect,
1736
+ moving: movingMask(pairs, width: was.width, height: was.height))
1737
+ }
1738
+ putBack()
1739
+ var changedSettings: [[String: Any]]?
1740
+ if let was = settingsBefore, let now = settings(pid) { changedSettings = settingsChanged(was, now) }
1741
+ var wrote: UInt64?
1742
+ if let was = writtenBefore, let now = bytesWritten(pid), now >= was { wrote = now - was }
1743
+
1744
+ try emit([
1745
+ "delivered": result == .success, "axError": Int(result.rawValue), "reachable": canReach,
1746
+ // The application ended while the action ran: it quit, or it crashed.
1747
+ "appGone": !isRunning(pid),
1748
+ "coveredBy": coveredBy,
1749
+ "settled": settled, "waitedMs": elapsedMs(), "budgetMs": budgetMs,
1750
+ "before": before.tree, "after": after.tree, "unreadBefore": before.unread,
1751
+ "unreadAfter": after.unread,
1752
+ ].merging(wrote.map { ["bytesWritten": $0] } ?? [:]) { $1 }
1753
+ .merging(changedSettings.map { ["settingsChanged": $0] } ?? [:]) { $1 }
1754
+ .merging(["clipboardChanged": clipboard.changeCount != clipboardBefore]) { $1 }
1755
+ .merging(pixels.map { ["pixels": $0] } ?? [:]) { $1 }
1756
+ .merging(arranged.map { ["windowState": windowState($0, wanted: wantedFrame)] } ?? [:]) { $1 })
1757
+ }
1758
+
1759
+ func write(_ object: [String: Any]) {
1760
+ let data = (try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys])) ?? Data()
1761
+ FileHandle.standardOutput.write(data)
1762
+ FileHandle.standardOutput.write("\n".data(using: .utf8)!)
1763
+ }
1764
+
1765
+ func answer(_ args: [String]) -> [String: Any] {
1766
+ do {
1767
+ try run(args)
1768
+ } catch let answer as Answer {
1769
+ return answer.body
1770
+ } catch {
1771
+ return ["error": "\(error)"]
1772
+ }
1773
+ return ["error": "no-answer"]
1774
+ }
1775
+
1776
+ // `reticle-ax serve` stays open: each line on standard input is one command, as a JSON list of its
1777
+ // words, and each answer is one line. Starting a process for each command costs more than most
1778
+ // commands do. Any other first word runs that one command and ends.
1779
+ if CommandLine.arguments.count > 1, CommandLine.arguments[1] == "serve" {
1780
+ while let line = readLine() {
1781
+ let words = (try? JSONSerialization.jsonObject(with: Data(line.utf8))) as? [String]
1782
+ write(words.map { answer(["reticle-ax"] + $0) } ?? ["error": "usage"])
1783
+ }
1784
+ } else {
1785
+ write(answer(CommandLine.arguments))
1786
+ }