ravensight-playtest 0.18.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/README.md +202 -17
  2. package/addons/desktop/RavensightDesktop.swift +367 -0
  3. package/addons/mobile/UITests/MobileInputTests.swift +67 -1
  4. package/addons/ravensight_driver/driver.gd +557 -4
  5. package/docs/ADAPTERS.md +39 -7
  6. package/docs/DESKTOP.md +161 -0
  7. package/docs/MOBILE.md +30 -3
  8. package/docs/UNITY.md +189 -0
  9. package/docs/UNREAL.md +166 -0
  10. package/docs/godot-driver.md +109 -1
  11. package/package.json +15 -5
  12. package/src/cli.js +44 -11
  13. package/src/commands/build.js +40 -0
  14. package/src/commands/feature.js +1 -1
  15. package/src/commands/hosted.js +78 -9
  16. package/src/commands/run.js +65 -13
  17. package/src/commands/validate.js +1 -1
  18. package/src/hosted/archivePreflight.js +31 -4
  19. package/src/hosted/buildStatus.js +26 -0
  20. package/src/hosted/buildUpload.js +24 -9
  21. package/src/hosted/nativeBuild.js +87 -0
  22. package/src/hosted/recordedRun.js +15 -3
  23. package/src/run/anygame/genre.js +110 -25
  24. package/src/run/anygame/genre2d.js +139 -0
  25. package/src/run/anygame/index.js +9 -5
  26. package/src/run/anygame/scene3d.js +562 -0
  27. package/src/run/anygame/shared-hashes.json +4 -2
  28. package/src/run/anygame/shared.js +3 -3
  29. package/src/run/args.js +24 -4
  30. package/src/run/drivers/desktop/app.js +104 -0
  31. package/src/run/drivers/desktop/common.js +394 -0
  32. package/src/run/drivers/desktop/driver.js +455 -0
  33. package/src/run/drivers/desktop/helper.js +98 -0
  34. package/src/run/drivers/desktop/keys.js +124 -0
  35. package/src/run/drivers/desktop/output.js +107 -0
  36. package/src/run/drivers/desktop/preflight.js +134 -0
  37. package/src/run/drivers/desktop/runHome.js +158 -0
  38. package/src/run/drivers/desktop3d.js +106 -0
  39. package/src/run/drivers/desktopSequence.js +72 -0
  40. package/src/run/drivers/godot-3d.js +298 -0
  41. package/src/run/drivers/godot.js +473 -31
  42. package/src/run/drivers/index.js +6 -0
  43. package/src/run/drivers/mobile/adb.js +25 -1
  44. package/src/run/drivers/mobile/frame.js +3 -2
  45. package/src/run/drivers/mobile/gestures.js +76 -0
  46. package/src/run/drivers/mobile/lock.js +51 -11
  47. package/src/run/drivers/mobile/multitouch.js +150 -0
  48. package/src/run/drivers/mobile/native.js +231 -31
  49. package/src/run/drivers/mobile/preflight.js +14 -1
  50. package/src/run/drivers/mobile/target.js +22 -1
  51. package/src/run/drivers/stdio.js +154 -13
  52. package/src/run/drivers/unity/app.js +72 -0
  53. package/src/run/drivers/unity/engine.js +58 -0
  54. package/src/run/drivers/unity/link.js +108 -0
  55. package/src/run/drivers/unity/logs.js +76 -0
  56. package/src/run/drivers/unreal/app.js +40 -0
  57. package/src/run/drivers/unreal/driver.js +776 -0
  58. package/src/run/drivers/unreal/frames.js +243 -0
  59. package/src/run/drivers/unreal/logs.js +276 -0
  60. package/src/run/drivers/unreal/preflight.js +61 -0
  61. package/src/run/drivers/web.js +211 -13
  62. package/src/run/drivers/webdriver.js +81 -12
  63. package/src/run/endScreen.js +88 -0
  64. package/src/run/engineErrors.js +16 -0
  65. package/src/run/featureLoop.js +1 -1
  66. package/src/run/fingers.js +99 -0
  67. package/src/run/focusForKeys.js +54 -0
  68. package/src/run/godotTesterProbes.js +21 -2
  69. package/src/run/honesty.js +11 -1
  70. package/src/run/inputs.js +3 -3
  71. package/src/run/intent.js +12 -0
  72. package/src/run/launchArgs.js +58 -0
  73. package/src/run/pauseHook.js +617 -0
  74. package/src/run/personaLoop.js +164 -10
  75. package/src/run/pixels.js +22 -10
  76. package/src/run/planGuard.js +103 -0
  77. package/src/run/replay.js +7 -1
  78. package/src/run/reportChecks.js +24 -4
  79. package/src/run/resume.js +10 -2
  80. package/src/run/sessions.js +175 -0
  81. package/src/run/slowMotion.js +151 -0
  82. package/src/run/startFrom.js +448 -0
  83. package/src/run/testerProbes.js +36 -5
  84. package/src/run/tools.js +191 -10
  85. package/src/run/view3dState.js +125 -0
  86. package/src/run/web3d.js +375 -0
  87. package/src/run/world3d.js +164 -0
  88. package/templates/godot-3d/README.md +3 -2
@@ -0,0 +1,367 @@
1
+ // Ravensight desktop input helper for macOS.
2
+ //
3
+ // The playtest CLI compiles this file once with swiftc and runs it for the
4
+ // length of one local desktop run. It reads one JSON request per line on
5
+ // stdin and answers one JSON line per request on stdout. It only ever:
6
+ // - reads the on-screen windows of ONE process id (bounds, never contents),
7
+ // - posts keyboard events and pointer moves to that same process id
8
+ // (CGEvent.postToPid): keys, hovers and moves by an amount (mouse look),
9
+ // - sends mouse presses, drags and the wheel at the pointer, as a hand
10
+ // would, only after checking that this process's window is the one on
11
+ // top at that point (a window reads its own buttons; see post below),
12
+ // moving the cursor to each click's point the way a player's hand would, and
13
+ // - brings that process's window to the front before a click.
14
+ // It opens no network connection and writes no file.
15
+ import AppKit
16
+ import ApplicationServices
17
+ import CoreGraphics
18
+ import Foundation
19
+
20
+ setvbuf(stdout, nil, _IOLBF, 0)
21
+
22
+ func reply(_ value: [String: Any]) {
23
+ guard let data = try? JSONSerialization.data(withJSONObject: value),
24
+ let line = String(data: data, encoding: .utf8) else { return }
25
+ print(line)
26
+ }
27
+
28
+ func number(_ value: Any?) -> Double? {
29
+ if let n = value as? NSNumber { return n.doubleValue }
30
+ return nil
31
+ }
32
+
33
+ func gameWindow(_ pid: pid_t) -> [String: Any]? {
34
+ guard let list = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] else { return nil }
35
+ var best: [String: Any]? = nil
36
+ var bestArea = 0.0
37
+ for info in list {
38
+ guard let owner = info[kCGWindowOwnerPID as String] as? NSNumber, owner.int32Value == pid else { continue }
39
+ guard let layer = info[kCGWindowLayer as String] as? NSNumber, layer.intValue == 0 else { continue }
40
+ guard let bounds = info[kCGWindowBounds as String] as? [String: Any],
41
+ let w = number(bounds["Width"]), let h = number(bounds["Height"]), w >= 64, h >= 64 else { continue }
42
+ let area = w * h
43
+ if area > bestArea {
44
+ bestArea = area
45
+ best = [
46
+ "windowId": (info[kCGWindowNumber as String] as? NSNumber)?.intValue ?? 0,
47
+ "x": number(bounds["X"]) ?? 0, "y": number(bounds["Y"]) ?? 0, "width": w, "height": h
48
+ ]
49
+ }
50
+ }
51
+ return best
52
+ }
53
+
54
+ // The process that owns the frontmost ordinary window at a screen point.
55
+ // (Owner and bounds only: reading them needs no Screen Recording.)
56
+ func ownerOnTop(at point: CGPoint) -> pid_t? {
57
+ guard let list = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] else { return nil }
58
+ for info in list {
59
+ guard let layer = info[kCGWindowLayer as String] as? NSNumber, layer.intValue == 0,
60
+ let bounds = info[kCGWindowBounds as String] as? [String: Any],
61
+ let x = number(bounds["X"]), let y = number(bounds["Y"]), let w = number(bounds["Width"]), let h = number(bounds["Height"]) else { continue }
62
+ if CGRect(x: x, y: y, width: w, height: h).contains(point) { return (info[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value }
63
+ }
64
+ return nil
65
+ }
66
+
67
+ // How a press reaches the game. By default every event is posted to the
68
+ // game's process (CGEvent.postToPid), which an engine that reads the system's
69
+ // events itself (Unreal) takes. A window that reads its own buttons (SDL,
70
+ // GLFW, any NSView based engine) never sees a press posted to its process, so
71
+ // a request with "via": "pointer" sends presses, drags and the wheel as the
72
+ // hand's own input at the pointer instead, and only while the game's window
73
+ // is the one on top there: the owner under the point is read again right
74
+ // before every such event, and the whole gesture stops (a held button let go)
75
+ // the moment it is not the game's.
76
+ var viaPointer = false
77
+ let windowEvents: Set<CGEventType> = [.leftMouseDown, .leftMouseUp, .rightMouseDown, .rightMouseUp, .otherMouseDown, .otherMouseUp, .leftMouseDragged, .rightMouseDragged, .otherMouseDragged, .scrollWheel]
78
+ let releaseFor: [CGEventType: CGEventType] = [.leftMouseDown: .leftMouseUp, .rightMouseDown: .rightMouseUp, .otherMouseDown: .otherMouseUp]
79
+ // The button the hand holds down right now, to let go if a gesture stops.
80
+ var held: (type: CGEventType, at: CGPoint, button: CGMouseButton)? = nil
81
+
82
+ func environmentHas(_ pid: pid_t, _ entry: String) -> Bool {
83
+ var mib: [Int32] = [CTL_KERN, KERN_PROCARGS2, pid]
84
+ var size = 0
85
+ guard sysctl(&mib, 3, nil, &size, nil, 0) == 0, size > 0 else { return false }
86
+ var buffer = [UInt8](repeating: 0, count: size)
87
+ guard sysctl(&mib, 3, &buffer, &size, nil, 0) == 0 else { return false }
88
+ // argc, the executable path, then argv and the environment as C strings.
89
+ let target = Array(entry.utf8)
90
+ var start = 4
91
+ for i in 4..<size where buffer[i] == 0 {
92
+ if i - start == target.count && Array(buffer[start..<i]) == target { return true }
93
+ start = i + 1
94
+ }
95
+ return false
96
+ }
97
+
98
+ func launchedPids(executable: String, marker: String) -> [Int] {
99
+ let count = proc_listallpids(nil, 0)
100
+ guard count > 0 else { return [] }
101
+ var pids = [pid_t](repeating: 0, count: Int(count) * 2)
102
+ let found = proc_listallpids(&pids, Int32(pids.count * MemoryLayout<pid_t>.size))
103
+ var out: [Int] = []
104
+ var path = [CChar](repeating: 0, count: 4096)
105
+ for pid in pids.prefix(Int(max(0, found))) where pid > 0 {
106
+ guard proc_pidpath(pid, &path, UInt32(path.count)) > 0, String(cString: path) == executable else { continue }
107
+ var info = proc_bsdinfo()
108
+ guard proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &info, Int32(MemoryLayout<proc_bsdinfo>.size)) > 0, info.pbi_ppid == 1, info.pbi_uid == getuid() else { continue }
109
+ if environmentHas(pid, "RAVENSIGHT_DESKTOP_LAUNCH=" + marker) { out.append(Int(pid)) }
110
+ }
111
+ return out
112
+ }
113
+
114
+ func post(_ event: CGEvent?, _ pid: pid_t) throws {
115
+ guard let event = event else { throw NSError(domain: "ravensight", code: 1, userInfo: [NSLocalizedDescriptionKey: "macOS refused to create the input event"]) }
116
+ guard viaPointer && windowEvents.contains(event.type) else { event.postToPid(pid); return }
117
+ guard ownerOnTop(at: event.location) == pid else { throw NSError(domain: "ravensight", code: 11, userInfo: [NSLocalizedDescriptionKey: "another window came over the game at that point; the input was stopped"]) }
118
+ event.post(tap: .cghidEventTap)
119
+ if let up = releaseFor[event.type] {
120
+ held = (up, event.location, CGMouseButton(rawValue: UInt32(event.getIntegerValueField(.mouseEventButtonNumber))) ?? .left)
121
+ } else if releaseFor.values.contains(event.type) { held = nil }
122
+ }
123
+
124
+ // One press, drag or wheel turn: with "via": "pointer" the game's window is
125
+ // brought forward at the start point first, and a gesture that stops part way
126
+ // lets go of its button where it was pressed.
127
+ func gesture(_ pid: pid_t, at start: CGPoint, _ body: () throws -> Void) throws {
128
+ if viaPointer && !raiseWindow(pid, at: start) { throw NSError(domain: "ravensight", code: 11, userInfo: [NSLocalizedDescriptionKey: "another window covers the game at that point; the input was not sent"]) }
129
+ do { try body() } catch {
130
+ if let h = held { CGEvent(mouseEventSource: nil, mouseType: h.type, mouseCursorPosition: h.at, mouseButton: h.button)?.post(tap: .cghidEventTap); held = nil }
131
+ throw error
132
+ }
133
+ }
134
+
135
+ func pause(_ ms: Double) { if ms > 0 { usleep(useconds_t(min(ms, 10000) * 1000)) } }
136
+
137
+
138
+ func mouseTypes(_ button: String) -> (CGEventType, CGEventType, CGEventType, CGMouseButton) {
139
+ switch button {
140
+ case "right": return (.rightMouseDown, .rightMouseUp, .rightMouseDragged, .right)
141
+ case "middle": return (.otherMouseDown, .otherMouseUp, .otherMouseDragged, .center)
142
+ default: return (.leftMouseDown, .leftMouseUp, .leftMouseDragged, .left)
143
+ }
144
+ }
145
+
146
+ let flagFor: [Int: CGEventFlags] = [56: .maskShift, 60: .maskShift, 59: .maskControl, 62: .maskControl, 58: .maskAlternate, 61: .maskAlternate, 55: .maskCommand, 54: .maskCommand]
147
+
148
+ // Brings the game's window to the front at a point, through Accessibility. A
149
+ // busy Mac can take a moment, so this tries three times before giving up.
150
+ func raiseWindow(_ pid: pid_t, at point: CGPoint) -> Bool {
151
+ if ownerOnTop(at: point) == pid { return true }
152
+ for _ in 0..<3 {
153
+ let app = AXUIElementCreateApplication(pid)
154
+ AXUIElementSetAttributeValue(app, kAXFrontmostAttribute as CFString, kCFBooleanTrue)
155
+ var windows: CFTypeRef?
156
+ if AXUIElementCopyAttributeValue(app, kAXWindowsAttribute as CFString, &windows) == .success, let list = windows as? [AXUIElement] {
157
+ for element in list {
158
+ AXUIElementPerformAction(element, kAXRaiseAction as CFString)
159
+ AXUIElementSetAttributeValue(element, kAXMainAttribute as CFString, kCFBooleanTrue)
160
+ }
161
+ }
162
+ NSRunningApplication(processIdentifier: pid)?.activate(options: [.activateAllWindows])
163
+ for _ in 0..<30 { if ownerOnTop(at: point) == pid { return true }; pause(25) }
164
+ }
165
+ return ownerOnTop(at: point) == pid
166
+ }
167
+
168
+ func handle(_ request: [String: Any]) throws -> [String: Any] {
169
+ let kind = request["kind"] as? String ?? ""
170
+ if kind == "access" {
171
+ return ["accessibility": AXIsProcessTrusted(), "screenCapture": CGPreflightScreenCaptureAccess()]
172
+ }
173
+ if kind == "find" {
174
+ // The game app LaunchServices just started: the one process whose executable
175
+ // is exactly this path, whose parent is launchd and whose environment holds
176
+ // this launch's own marker. More than one is refused by the caller.
177
+ guard let executable = request["executable"] as? String, let marker = request["marker"] as? String, marker.count >= 32 else { throw NSError(domain: "ravensight", code: 12, userInfo: [NSLocalizedDescriptionKey: "find needs an executable and a marker"]) }
178
+ return ["pids": launchedPids(executable: executable, marker: marker)]
179
+ }
180
+ guard let rawPid = number(request["pid"]), rawPid >= 1, rawPid < 1_000_000 else { throw NSError(domain: "ravensight", code: 2, userInfo: [NSLocalizedDescriptionKey: "a process id is required"]) }
181
+ let pid = pid_t(rawPid)
182
+ viaPointer = (request["via"] as? String) == "pointer"
183
+ held = nil
184
+ switch kind {
185
+ case "status":
186
+ return ["running": kill(pid, 0) == 0]
187
+ case "window":
188
+ guard let window = gameWindow(pid) else { return ["found": false] }
189
+ return window.merging(["found": true]) { a, _ in a }
190
+ case "raise":
191
+ // A click lands on whatever window is on top at that point, so the game
192
+ // window is brought to the front first, through Accessibility. A busy Mac
193
+ // can take a moment, so this tries three times before giving up.
194
+ guard let window = gameWindow(pid), let wx = number(window["x"]), let wy = number(window["y"]), let ww = number(window["width"]), let wh = number(window["height"]) else { return ["onTop": false] }
195
+ let point = CGPoint(x: number(request["x"]) ?? wx + ww / 2, y: number(request["y"]) ?? wy + wh / 2)
196
+ return ["onTop": raiseWindow(pid, at: point)]
197
+ case "click":
198
+ guard let x = number(request["x"]), let y = number(request["y"]) else { throw NSError(domain: "ravensight", code: 4, userInfo: [NSLocalizedDescriptionKey: "a point is required"]) }
199
+ let (down, up, _, button) = mouseTypes(request["button"] as? String ?? "left")
200
+ let point = CGPoint(x: x, y: y)
201
+ let hold = number(request["holdMs"]) ?? 0
202
+ let clicks = (request["double"] as? Bool ?? false) ? 2 : 1
203
+ try gesture(pid, at: point) {
204
+ CGWarpMouseCursorPosition(point)
205
+ try post(CGEvent(mouseEventSource: nil, mouseType: .mouseMoved, mouseCursorPosition: point, mouseButton: .left), pid)
206
+ pause(30)
207
+ for count in 1...clicks {
208
+ let press = CGEvent(mouseEventSource: nil, mouseType: down, mouseCursorPosition: point, mouseButton: button)
209
+ press?.setIntegerValueField(.mouseEventClickState, value: Int64(count))
210
+ try post(press, pid)
211
+ pause(max(hold, 40))
212
+ let release = CGEvent(mouseEventSource: nil, mouseType: up, mouseCursorPosition: point, mouseButton: button)
213
+ release?.setIntegerValueField(.mouseEventClickState, value: Int64(count))
214
+ try post(release, pid)
215
+ if count < clicks { pause(80) }
216
+ }
217
+ pause(30)
218
+ }
219
+ return [:]
220
+ case "drag":
221
+ guard let points = request["points"] as? [[String: Any]], points.count >= 2 else { throw NSError(domain: "ravensight", code: 5, userInfo: [NSLocalizedDescriptionKey: "a drag needs two points or more"]) }
222
+ let (down, up, dragged, button) = mouseTypes(request["button"] as? String ?? "left")
223
+ let path = points.compactMap { p -> CGPoint? in
224
+ guard let x = number(p["x"]), let y = number(p["y"]) else { return nil }
225
+ return CGPoint(x: x, y: y)
226
+ }
227
+ let step = (number(request["durationMs"]) ?? 400) / Double(max(1, path.count - 1))
228
+ try gesture(pid, at: path[0]) {
229
+ CGWarpMouseCursorPosition(path[0])
230
+ try post(CGEvent(mouseEventSource: nil, mouseType: .mouseMoved, mouseCursorPosition: path[0], mouseButton: .left), pid)
231
+ pause(30)
232
+ try post(CGEvent(mouseEventSource: nil, mouseType: down, mouseCursorPosition: path[0], mouseButton: button), pid)
233
+ pause(max(number(request["holdMs"]) ?? 0, 30))
234
+ for p in path.dropFirst() {
235
+ pause(step)
236
+ CGWarpMouseCursorPosition(p)
237
+ try post(CGEvent(mouseEventSource: nil, mouseType: dragged, mouseCursorPosition: p, mouseButton: button), pid)
238
+ }
239
+ pause(30)
240
+ try post(CGEvent(mouseEventSource: nil, mouseType: up, mouseCursorPosition: path[path.count - 1], mouseButton: button), pid)
241
+ pause(30)
242
+ }
243
+ return [:]
244
+ case "move":
245
+ // The pointer over a point, no button: a hover.
246
+ guard let x = number(request["x"]), let y = number(request["y"]) else { throw NSError(domain: "ravensight", code: 4, userInfo: [NSLocalizedDescriptionKey: "a point is required"]) }
247
+ let point = CGPoint(x: x, y: y)
248
+ CGWarpMouseCursorPosition(point)
249
+ try post(CGEvent(mouseEventSource: nil, mouseType: .mouseMoved, mouseCursorPosition: point, mouseButton: .left), pid)
250
+ return [:]
251
+ case "look":
252
+ // The mouse moved by an amount, as mouse look reads it: each step is a
253
+ // move event carrying its own delta, from a point that stays inside the
254
+ // window, so a game reading relative motion and one reading positions
255
+ // both see the same turn.
256
+ guard let steps = request["steps"] as? [[String: Any]], !steps.isEmpty, steps.count <= 64,
257
+ let x = number(request["x"]), let y = number(request["y"]) else { throw NSError(domain: "ravensight", code: 9, userInfo: [NSLocalizedDescriptionKey: "a look needs a start point and one to 64 steps"]) }
258
+ let bounds = gameWindow(pid)
259
+ var at = CGPoint(x: x, y: y)
260
+ let stepMs = number(request["stepMs"]) ?? 16
261
+ // Keys held through the whole move, to walk and turn at once.
262
+ let held = (request["codes"] as? [NSNumber] ?? []).prefix(6)
263
+ var flags: CGEventFlags = []
264
+ for code in held { flags.insert(flagFor[code.intValue] ?? []) }
265
+ for code in held {
266
+ let event = CGEvent(keyboardEventSource: nil, virtualKey: CGKeyCode(code.uint16Value), keyDown: true)
267
+ event?.flags = flags
268
+ try post(event, pid)
269
+ }
270
+ if !held.isEmpty { pause(50) }
271
+ defer {
272
+ for code in held.reversed() {
273
+ let event = CGEvent(keyboardEventSource: nil, virtualKey: CGKeyCode(code.uint16Value), keyDown: false)
274
+ try? post(event, pid)
275
+ }
276
+ }
277
+ for step in steps {
278
+ let dx = number(step["dx"]) ?? 0, dy = number(step["dy"]) ?? 0
279
+ var next = CGPoint(x: at.x + dx, y: at.y + dy)
280
+ if let w = bounds, let wx = number(w["x"]), let wy = number(w["y"]), let ww = number(w["width"]), let wh = number(w["height"]) {
281
+ next.x = min(max(next.x, wx + 2), wx + ww - 2)
282
+ next.y = min(max(next.y, wy + 30), wy + wh - 2)
283
+ }
284
+ let event = CGEvent(mouseEventSource: nil, mouseType: .mouseMoved, mouseCursorPosition: next, mouseButton: .left)
285
+ event?.setIntegerValueField(.mouseEventDeltaX, value: Int64(dx))
286
+ event?.setIntegerValueField(.mouseEventDeltaY, value: Int64(dy))
287
+ try post(event, pid)
288
+ at = next
289
+ pause(stepMs)
290
+ }
291
+ return ["x": at.x, "y": at.y]
292
+ case "wheel":
293
+ // The wheel at a point, in notches: positive dy scrolls down, as a
294
+ // browser counts it, which is a negative wheel delta.
295
+ guard let x = number(request["x"]), let y = number(request["y"]) else { throw NSError(domain: "ravensight", code: 4, userInfo: [NSLocalizedDescriptionKey: "a point is required"]) }
296
+ let lines = Int32(max(-100, min(100, number(request["dy"]) ?? 0)))
297
+ let side = Int32(max(-100, min(100, number(request["dx"]) ?? 0)))
298
+ if lines == 0 && side == 0 { throw NSError(domain: "ravensight", code: 10, userInfo: [NSLocalizedDescriptionKey: "a wheel turn needs dy or dx"]) }
299
+ let point = CGPoint(x: x, y: y)
300
+ // The wheel turns under the pointer, so the pointer goes there first.
301
+ CGWarpMouseCursorPosition(point)
302
+ try post(CGEvent(mouseEventSource: nil, mouseType: .mouseMoved, mouseCursorPosition: point, mouseButton: .left), pid)
303
+ let event = CGEvent(scrollWheelEvent2Source: nil, units: .line, wheelCount: 2, wheel1: -lines, wheel2: -side, wheel3: 0)
304
+ event?.location = point
305
+ try gesture(pid, at: point) { try post(event, pid) }
306
+ return [:]
307
+ case "keys":
308
+ // Hold every key code together for holdMs, the modifiers first, then let go in reverse.
309
+ guard let codes = request["codes"] as? [NSNumber], !codes.isEmpty, codes.count <= 6 else { throw NSError(domain: "ravensight", code: 6, userInfo: [NSLocalizedDescriptionKey: "one to six key codes are required"]) }
310
+ let hold = number(request["holdMs"]) ?? 0
311
+ var flags: CGEventFlags = []
312
+ for code in codes { flags.insert(flagFor[code.intValue] ?? []) }
313
+ for code in codes {
314
+ let event = CGEvent(keyboardEventSource: nil, virtualKey: CGKeyCode(code.uint16Value), keyDown: true)
315
+ event?.flags = flags
316
+ try post(event, pid)
317
+ }
318
+ // A held key repeats as a keyboard does: after 500 ms, about thirty times a second.
319
+ if hold > 0, let last = codes.last, flagFor[last.intValue] == nil {
320
+ var waited = 0.0
321
+ while waited < hold {
322
+ let slice = min(waited < 500 ? 500 - waited : 33, hold - waited)
323
+ pause(slice); waited += slice
324
+ if waited >= 500 && waited < hold {
325
+ let repeatEvent = CGEvent(keyboardEventSource: nil, virtualKey: CGKeyCode(last.uint16Value), keyDown: true)
326
+ repeatEvent?.flags = flags
327
+ repeatEvent?.setIntegerValueField(.keyboardEventAutorepeat, value: 1)
328
+ try post(repeatEvent, pid)
329
+ }
330
+ }
331
+ } else { pause(max(hold, 40)) }
332
+ for code in codes.reversed() {
333
+ flags.remove(flagFor[code.intValue] ?? [])
334
+ let event = CGEvent(keyboardEventSource: nil, virtualKey: CGKeyCode(code.uint16Value), keyDown: false)
335
+ event?.flags = flags
336
+ try post(event, pid)
337
+ }
338
+ return [:]
339
+ case "type":
340
+ guard let text = request["text"] as? String, !text.isEmpty, text.count <= 2000 else { throw NSError(domain: "ravensight", code: 7, userInfo: [NSLocalizedDescriptionKey: "type needs 1 to 2000 characters"]) }
341
+ for scalar in text.utf16 {
342
+ var unit = scalar
343
+ for isDown in [true, false] {
344
+ let event = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: isDown)
345
+ event?.keyboardSetUnicodeString(stringLength: 1, unicodeString: &unit)
346
+ try post(event, pid)
347
+ }
348
+ pause(12)
349
+ }
350
+ return [:]
351
+ default:
352
+ throw NSError(domain: "ravensight", code: 8, userInfo: [NSLocalizedDescriptionKey: "unknown request"])
353
+ }
354
+ }
355
+
356
+ reply(["ready": true])
357
+ while let line = readLine(strippingNewline: true) {
358
+ if line.utf8.count > 65536 { reply(["ok": false, "error": "request too large"]); continue }
359
+ guard let data = line.data(using: .utf8),
360
+ let request = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else {
361
+ reply(["ok": false, "error": "invalid request"]); continue
362
+ }
363
+ let id = request["id"] ?? NSNull()
364
+ if (request["kind"] as? String) == "shutdown" { reply(["id": id, "ok": true]); break }
365
+ do { reply(try handle(request).merging(["id": id, "ok": true]) { a, _ in a }) }
366
+ catch { reply(["id": id, "ok": false, "error": error.localizedDescription]) }
367
+ }
@@ -2,7 +2,7 @@ import XCTest
2
2
  import UIKit
3
3
 
4
4
  private enum BridgeError: Error {
5
- case invalidConfiguration, invalidCommand, invalidCoordinate, applicationNotRunning, network, deadline
5
+ case invalidConfiguration, invalidCommand, invalidCoordinate, applicationNotRunning, network, deadline, unsupportedInput
6
6
  }
7
7
 
8
8
  @MainActor
@@ -105,6 +105,15 @@ final class MobileInputTests: XCTestCase {
105
105
  let dy = ((command["toY"] as? NSNumber)?.doubleValue ?? 0) - ((command["y"] as? NSNumber)?.doubleValue ?? 0)
106
106
  let velocity = XCUIGestureVelocity(rawValue: max(1, hypot(dx, dy) / duration))
107
107
  start.press(forDuration: hold, thenDragTo: end, withVelocity: velocity, thenHoldForDuration: 0)
108
+ case "pinch":
109
+ // The system's own two finger pinch, around the middle of the app.
110
+ let scale = try number(command, "scale", maximum: 5)
111
+ guard scale >= 0.2, scale != 1 else { throw BridgeError.invalidCommand }
112
+ let duration = max(0.1, try number(command, "durationMs", fallback: 600) / 1000)
113
+ let speed = max(0.5, abs(log(scale)) / duration * 2)
114
+ target.pinch(withScale: CGFloat(scale), velocity: CGFloat(scale > 1 ? speed : -speed))
115
+ case "touches":
116
+ try synthesizeFingers(command, target)
108
117
  case "type":
109
118
  guard let text = command["text"] as? String, text.count <= 4096 else { throw BridgeError.invalidCommand }
110
119
  target.typeText(text)
@@ -118,6 +127,63 @@ final class MobileInputTests: XCTestCase {
118
127
  return [:]
119
128
  }
120
129
 
130
+ // Two fingers at once, each on its own path and clock, as one synthesized event: the event paths XCTest itself
131
+ // plays gestures with. They are not public API, so each is looked up by name and a runner without them answers
132
+ // unsupportedInput, which the CLI reports as a limit of the tool. Points are the app's own, as `point` checks them.
133
+ private func synthesizeFingers(_ command: [String: Any], _ target: XCUIApplication) throws {
134
+ guard let fingers = command["fingers"] as? [[String: Any]], (1...2).contains(fingers.count) else { throw BridgeError.invalidCommand }
135
+ guard let pathClass = NSClassFromString("XCPointerEventPath") as? NSObject.Type,
136
+ let recordClass = NSClassFromString("XCSynthesizedEventRecord") as? NSObject.Type else { throw BridgeError.unsupportedInput }
137
+ typealias InitPath = @convention(c) (AnyObject, Selector, CGPoint, Double) -> AnyObject?
138
+ typealias MovePath = @convention(c) (AnyObject, Selector, CGPoint, Double) -> Void
139
+ typealias LiftPath = @convention(c) (AnyObject, Selector, Double) -> Void
140
+ typealias InitRecord = @convention(c) (AnyObject, Selector, NSString, Int) -> AnyObject?
141
+ typealias AddPath = @convention(c) (AnyObject, Selector, AnyObject) -> Void
142
+ typealias Synthesize = @convention(c) (AnyObject, Selector, AnyObject, @escaping @convention(block) (Bool, NSError?) -> Void) -> AnyObject?
143
+ func call<T>(_ object: AnyObject, _ name: String, as type: T.Type) throws -> (Selector, T) {
144
+ let selector = NSSelectorFromString(name)
145
+ guard let object = object as? NSObject, object.responds(to: selector) else { throw BridgeError.unsupportedInput }
146
+ return (selector, unsafeBitCast(object.method(for: selector), to: type))
147
+ }
148
+ let frame = target.frame
149
+ let at = { (raw: Any?) throws -> CGPoint in
150
+ guard let p = raw as? [String: Any], let x = (p["x"] as? NSNumber)?.doubleValue, let y = (p["y"] as? NSNumber)?.doubleValue,
151
+ x.isFinite, y.isFinite, frame.contains(CGPoint(x: x, y: y)) else { throw BridgeError.invalidCoordinate }
152
+ // The event paths take the screen's own points, which in landscape are not the app's: a point given as the app
153
+ // shows it landed a quarter turn away. XCTest turns it, as it does for its own gestures.
154
+ return target.coordinate(withNormalizedOffset: .zero).withOffset(CGVector(dx: x - frame.minX, dy: y - frame.minY)).screenPoint
155
+ }
156
+ let orientation = (target.value(forKey: "interfaceOrientation") as? NSNumber)?.intValue ?? 1
157
+ guard let recordAlloc = recordClass.perform(NSSelectorFromString("alloc"))?.takeUnretainedValue() else { throw BridgeError.unsupportedInput }
158
+ let (initRecord, makeRecord) = try call(recordAlloc, "initWithName:interfaceOrientation:", as: InitRecord.self)
159
+ guard let record = makeRecord(recordAlloc, initRecord, "ravensight touches" as NSString, orientation) else { throw BridgeError.unsupportedInput }
160
+ let (addSelector, add) = try call(record, "addPointerEventPath:", as: AddPath.self)
161
+ for finger in fingers {
162
+ guard let points = finger["path"] as? [Any], (1...6).contains(points.count) else { throw BridgeError.invalidCommand }
163
+ let start = try number(finger, "atMs", maximum: 3000) / 1000
164
+ let hold = max(0.04, try number(finger, "holdMs", fallback: 600, maximum: 4000) / 1000)
165
+ let path = try points.map(at)
166
+ guard let pathAlloc = pathClass.perform(NSSelectorFromString("alloc"))?.takeUnretainedValue() else { throw BridgeError.unsupportedInput }
167
+ let (initPath, makePath) = try call(pathAlloc, "initForTouchAtPoint:offset:", as: InitPath.self)
168
+ guard let eventPath = makePath(pathAlloc, initPath, path[0], start) else { throw BridgeError.unsupportedInput }
169
+ let (moveSelector, move) = try call(eventPath, "moveToPoint:atOffset:", as: MovePath.self)
170
+ for (index, point) in path.enumerated().dropFirst() {
171
+ move(eventPath, moveSelector, point, start + hold * Double(index) / Double(path.count - 1))
172
+ }
173
+ let (liftSelector, lift) = try call(eventPath, "liftUpAtOffset:", as: LiftPath.self)
174
+ lift(eventPath, liftSelector, start + hold)
175
+ add(record, addSelector, eventPath)
176
+ }
177
+ guard let synthesizer = (XCUIDevice.shared as NSObject).value(forKey: "eventSynthesizer") as AnyObject? else { throw BridgeError.unsupportedInput }
178
+ let (synthesizeSelector, synthesize) = try call(synthesizer, "synthesizeEvent:completion:", as: Synthesize.self)
179
+ var finished = false, succeeded = false
180
+ _ = synthesize(synthesizer, synthesizeSelector, record) { ok, _ in succeeded = ok; finished = true }
181
+ // The completion may come on this thread's run loop: it is turned, never blocked.
182
+ let deadline = Date().addingTimeInterval(10)
183
+ while !finished && Date() < deadline { RunLoop.current.run(until: Date().addingTimeInterval(0.02)) }
184
+ guard finished, succeeded else { throw BridgeError.unsupportedInput }
185
+ }
186
+
121
187
  func testServe() throws {
122
188
  continueAfterFailure = false
123
189
  guard let raw = ProcessInfo.processInfo.environment["RAVENSIGHT_MOBILE_URL"],