1
import Foundation
2
+import ImageIO
3
import NIOCore
4
import NIOHTTP1
5
import NIOPosix
53
54
private static let protocolVersion = 1
55
private static let supportedMethods = [
56
+ "device.apps.activate",
57
"device.apps.launch",
58
"device.apps.terminate",
59
"device.capabilities",
62
"device.info",
63
"device.io.button",
64
"device.io.click",
65
+ "device.io.drag",
66
+ "device.io.key",
67
"device.io.orientation.get",
68
"device.io.orientation.set",
69
+ "device.io.scroll",
70
"device.io.spatial.tap",
71
"device.io.swipe",
72
"device.io.tap",
73
"device.io.text",
69
- "device.ui.tap"
74
+ "device.screenshot",
75
+ "device.ui.tap",
76
+ "device.window.resize"
77
]
78
79
private static var platform: XCRSControlKitPlatform {
143
id: request.id
144
)
145
case "device.dump.ui":
139
- let bundleIdentifier = try stringParameter("bundleId", request.params)
140
- let application = XCUIApplication(bundleIdentifier: bundleIdentifier)
141
- let hierarchy = try accessibilityHierarchy(
142
- application,
143
- bundleIdentifier: bundleIdentifier
146
+ let target = try requiredApplication(request.params)
147
+ let (hierarchy, debugDescription) = try accessibilityHierarchy(
148
+ target.application,
149
+ name: target.name
150
)
145
- return try response(result: dictionary(hierarchy), id: request.id)
151
+ var result = try dictionary(hierarchy)
152
+ if (request.params["raw"] as? Bool) == true {
153
+ result["debugDescription"] = debugDescription
154
+ }
155
+ return try response(result: result, id: request.id)
156
case "device.ui.tap":
147
- let bundleIdentifier = try stringParameter("bundleId", request.params)
157
+ let target = try requiredApplication(request.params)
158
let element = try stringParameter("element", request.params)
159
.trimmingCharacters(in: .whitespacesAndNewlines)
160
guard !element.isEmpty else {
161
throw RunnerError.invalidParameter("element")
162
}
153
- try tapElement(named: element, in: bundleIdentifier)
163
+ let elementType: XCUIElement.ElementType
164
+ if let typeName = request.params["type"] as? String, !typeName.isEmpty {
165
+ guard let resolved = Self.elementTypes[typeName.lowercased()] else {
166
+ throw RunnerError.invalidParameter("type")
167
+ }
168
+ elementType = resolved
169
+ } else {
170
+ elementType = .any
171
+ }
172
+ let index = (request.params["index"] as? NSNumber)?.intValue
173
+ try tapElement(
174
+ named: element,
175
+ ofType: elementType,
176
+ index: index,
177
+ in: target.application,
178
+ name: target.name
179
+ )
180
return try response(result: ["success": true], id: request.id)
181
case "device.apps.launch":
156
- let bundleIdentifier = try stringParameter("bundleId", request.params)
157
- let application = XCUIApplication(bundleIdentifier: bundleIdentifier)
158
- application.launch()
182
+ try requiredApplication(request.params).application.launch()
183
return try response(result: ["success": true], id: request.id)
184
+ case "device.apps.activate":
185
+ // Unlike launch, activate leaves an already-running app alone and only
186
+ // brings it to the foreground. launch() on an app that something else
187
+ // started (Finder, `open`, a second copy at another path) can block
188
+ // for minutes and then fail with "does not have a process ID".
189
+ let application = try requiredApplication(request.params).application
190
+ application.activate()
191
+ return try response(
192
+ result: ["success": true, "state": Self.stateName(application.state)],
193
+ id: request.id
194
+ )
195
case "device.apps.terminate":
161
- let bundleIdentifier = try stringParameter("bundleId", request.params)
162
- XCUIApplication(bundleIdentifier: bundleIdentifier).terminate()
196
+ try requiredApplication(request.params).application.terminate()
197
+ return try response(result: ["success": true], id: request.id)
198
+ case "device.screenshot":
199
+ return try response(result: screenshot(request.params), id: request.id)
200
+ case "device.io.drag":
201
+ #if os(macOS)
202
+ try drag(request.params)
203
+ return try response(result: ["success": true], id: request.id)
204
+ #else
205
+ throw RunnerError.unsupportedInteraction("pointer drag")
206
+ #endif
207
+ case "device.io.scroll":
208
+ #if os(macOS)
209
+ try scroll(request.params)
210
+ return try response(result: ["success": true], id: request.id)
211
+ #else
212
+ throw RunnerError.unsupportedInteraction("scroll wheel")
213
+ #endif
214
+ case "device.io.key":
215
+ #if os(macOS)
216
+ try typeKey(request.params)
217
return try response(result: ["success": true], id: request.id)
218
+ #else
219
+ throw RunnerError.unsupportedInteraction("keyboard shortcut")
220
+ #endif
221
+ case "device.window.resize":
222
+ #if os(macOS)
223
+ return try response(result: resizeWindow(request.params), id: request.id)
224
+ #else
225
+ throw RunnerError.unsupportedInteraction("window resize")
226
+ #endif
227
case "device.io.tap":
228
#if os(tvOS) || os(visionOS) || os(macOS)
229
throw RunnerError.unsupportedInteraction("touch")
282
)
283
case "device.io.text":
284
let text = try stringParameter("text", request.params)
222
- foregroundApplication(request.params).typeText(text)
285
+ application(request.params).typeText(text)
286
return try response(result: ["success": true], id: request.id)
287
case "device.io.button":
288
let button = try stringParameter("button", request.params)
322
}
323
}
324
262
- private func foregroundApplication(_ params: [String: Any]) -> XCUIApplication {
263
- if let bundleIdentifier = params["bundleId"] as? String {
325
+ /// Resolves the app a request targets.
326
+ ///
327
+ /// On macOS `path` wins over `bundleId`: a bundle identifier resolves through
328
+ /// LaunchServices, which picks one copy when several are installed (an App
329
+ /// Store build in /Applications and a staged build elsewhere, say), and the
330
+ /// runner then reports the copy you actually started as "not in the
331
+ /// foreground". A path names exactly one bundle.
332
+ private func application(_ params: [String: Any]) -> XCUIApplication {
333
+ #if os(macOS)
334
+ if let path = params["path"] as? String, !path.isEmpty {
335
+ return XCUIApplication(url: URL(fileURLWithPath: path))
336
+ }
337
+ #endif
338
+ if let bundleIdentifier = params["bundleId"] as? String, !bundleIdentifier.isEmpty {
339
return XCUIApplication(bundleIdentifier: bundleIdentifier)
340
}
341
return XCUIApplication()
342
}
343
344
+ /// Like `application(_:)`, but the request must name the app.
345
+ private func requiredApplication(
346
+ _ params: [String: Any]
347
+ ) throws -> (application: XCUIApplication, name: String) {
348
+ #if os(macOS)
349
+ if let path = params["path"] as? String, !path.isEmpty {
350
+ return (application(params), path)
351
+ }
352
+ #endif
353
+ let bundleIdentifier = try stringParameter("bundleId", params)
354
+ return (XCUIApplication(bundleIdentifier: bundleIdentifier), bundleIdentifier)
355
+ }
356
+
357
private func accessibilityHierarchy(
358
_ application: XCUIApplication,
271
- bundleIdentifier: String
272
- ) throws -> XCRSControlKitAccessibilityNode {
359
+ name: String
360
+ ) throws -> (XCRSControlKitAccessibilityNode, String) {
361
guard application.state == .runningForeground else {
274
- throw RunnerError.applicationNotInForeground(bundleIdentifier)
362
+ throw RunnerError.applicationNotInForeground(name)
363
}
364
let debugDescription = application.debugDescription
365
guard application.state == .runningForeground else {
278
- throw RunnerError.applicationNotInForeground(bundleIdentifier)
366
+ throw RunnerError.applicationNotInForeground(name)
367
}
280
- return try XCRSControlKitAccessibilityParser.parse(
368
+ let hierarchy = try XCRSControlKitAccessibilityParser.parse(
369
debugDescription: debugDescription
370
)
371
+ return (hierarchy, debugDescription)
372
}
373
285
- private func tapElement(named element: String, in bundleIdentifier: String) throws {
286
- let application = XCUIApplication(bundleIdentifier: bundleIdentifier)
374
+ /// Element types `device.ui.tap` can narrow a match to, by the names
375
+ /// `device.dump.ui` reports in `type`.
376
+ private static let elementTypes: [String: XCUIElement.ElementType] = [
377
+ "button": .button,
378
+ "link": .link,
379
+ "statictext": .staticText,
380
+ "textfield": .textField,
381
+ "securetextfield": .secureTextField,
382
+ "textview": .textView,
383
+ "searchfield": .searchField,
384
+ "checkbox": .checkBox,
385
+ "radiobutton": .radioButton,
386
+ "switch": .switch,
387
+ "toggle": .toggle,
388
+ "slider": .slider,
389
+ "image": .image,
390
+ "cell": .cell,
391
+ "menuitem": .menuItem,
392
+ "menubaritem": .menuBarItem,
393
+ "popupbutton": .popUpButton,
394
+ "tab": .tab,
395
+ "other": .other
396
+ ]
397
+
398
+ private func tapElement(
399
+ named element: String,
400
+ ofType elementType: XCUIElement.ElementType,
401
+ index: Int?,
402
+ in application: XCUIApplication,
403
+ name: String
404
+ ) throws {
405
guard application.state == .runningForeground else {
288
- throw RunnerError.applicationNotInForeground(bundleIdentifier)
406
+ throw RunnerError.applicationNotInForeground(name)
407
}
408
+ // macOS controls usually carry their text as `title` (a button's caption),
409
+ // not `label`, so match it too there.
410
+ #if os(macOS)
411
+ let predicate = NSPredicate(
412
+ format: "label == %@ OR identifier == %@ OR value == %@ OR title == %@",
413
+ element,
414
+ element,
415
+ element,
416
+ element
417
+ )
418
+ #else
419
let predicate = NSPredicate(
420
format: "label == %@ OR identifier == %@ OR value == %@",
421
element,
422
element,
423
element
424
)
296
- let matches = application.descendants(matching: .any).matching(predicate)
425
+ #endif
426
+ // Web views repeat a control's text on the control and on the static
427
+ // text inside it (and often on a nav link too), so callers can narrow
428
+ // by type, or pick one of several matches by index (document order).
429
+ let matches = application.descendants(matching: elementType).matching(predicate)
430
let matchCount = matches.count
431
guard matchCount > 0 else {
432
throw RunnerError.elementNotFound(element)
433
}
434
+ if let index {
435
+ guard index >= 0, index < matchCount else {
436
+ throw RunnerError.invalidParameter("index")
437
+ }
438
+ try activate(matches.element(boundBy: index), named: element)
439
+ return
440
+ }
441
guard matchCount == 1 else {
442
throw RunnerError.ambiguousElement(element, matchCount)
443
}
474
/// Querying a stopped application records an XCTest failure, which ends the
475
/// runner's only test case and takes the server down with it.
476
private func runningApplication(_ params: [String: Any]) throws -> XCUIApplication {
337
- let application = foregroundApplication(params)
477
+ let application = application(params)
478
guard application.state != .notRunning else {
339
- throw RunnerError.applicationNotRunning((params["bundleId"] as? String) ?? "the app under test")
479
+ throw RunnerError.applicationNotRunning(
480
+ (params["path"] as? String) ?? (params["bundleId"] as? String) ?? "the app under test"
481
+ )
482
}
483
return application
484
}
485
486
+ private static func stateName(_ state: XCUIApplication.State) -> String {
487
+ switch state {
488
+ case .notRunning: return "notRunning"
489
+ #if !os(macOS)
490
+ case .runningBackgroundSuspended: return "runningBackgroundSuspended"
491
+ #endif
492
+ case .runningBackground: return "runningBackground"
493
+ case .runningForeground: return "runningForeground"
494
+ default: return "unknown"
495
+ }
496
+ }
497
+
498
+ /// PNG of the app's main window (`target: "window"`, the default when an app
499
+ /// is named) or of the whole main screen (`target: "screen"`), base64-encoded.
500
+ /// Pixel sizes are read back from the PNG, so they include the display scale.
501
+ private func screenshot(_ params: [String: Any]) throws -> [String: Any] {
502
+ let named = params["path"] != nil || params["bundleId"] != nil
503
+ let target = (params["target"] as? String) ?? (named ? "window" : "screen")
504
+ let png: Data
505
+ switch target {
506
+ case "screen":
507
+ png = XCUIScreen.main.screenshot().pngRepresentation
508
+ case "window":
509
+ let application = try runningApplication(params)
510
+ png = try mainWindow(of: application).screenshot().pngRepresentation
511
+ default:
512
+ throw RunnerError.invalidParameter("target")
513
+ }
514
+ var result: [String: Any] = ["png": png.base64EncodedString(), "target": target]
515
+ if
516
+ let source = CGImageSourceCreateWithData(png as CFData, nil),
517
+ let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any]
518
+ {
519
+ result["width"] = properties[kCGImagePropertyPixelWidth]
520
+ result["height"] = properties[kCGImagePropertyPixelHeight]
521
+ }
522
+ return result
523
+ }
524
+
525
+ /// The app's largest on-screen window. `windows.firstMatch` is not enough on
526
+ /// macOS: WebKit-based apps (Tauri, Electron) also own small hidden helper
527
+ /// windows that can come first.
528
+ private func mainWindow(of application: XCUIApplication) throws -> XCUIElement {
529
+ let windows = application.windows.allElementsBoundByIndex.filter { window in
530
+ let frame = window.frame
531
+ return frame.width > 1 && frame.height > 1
532
+ }
533
+ guard let window = windows.max(by: { left, right in
534
+ left.frame.width * left.frame.height < right.frame.width * right.frame.height
535
+ }) else {
536
+ throw RunnerError.noWindow
537
+ }
538
+ return window
539
+ }
540
+
541
+ #if os(macOS)
542
+ /// Maps a screen point (the space `device.dump.ui` reports rects in) to a
543
+ /// coordinate anchored on the window under it. The application element has
544
+ /// no frame of its own on macOS, so it cannot be the anchor there.
545
+ private func screenCoordinate(
546
+ x: Double,
547
+ y: Double,
548
+ in application: XCUIApplication
549
+ ) throws -> (coordinate: XCUICoordinate, window: XCUIElement) {
550
+ let point = CGPoint(x: x, y: y)
551
+ let windows = application.windows.allElementsBoundByIndex.filter { window in
552
+ let frame = window.frame
553
+ return frame.width > 1 && frame.height > 1
554
+ }
555
+ guard let window = windows.first(where: { $0.frame.contains(point) }) ?? windows.first else {
556
+ throw RunnerError.noWindow
557
+ }
558
+ let origin = window.frame.origin
559
+ let coordinate = window
560
+ .coordinate(withNormalizedOffset: .zero)
561
+ .withOffset(CGVector(dx: x - origin.x, dy: y - origin.y))
562
+ return (coordinate, window)
563
+ }
564
+
565
+ private func drag(_ params: [String: Any]) throws {
566
+ let application = try runningApplication(params)
567
+ let x1 = try doubleParameter("x1", params)
568
+ let y1 = try doubleParameter("y1", params)
569
+ let start = try screenCoordinate(x: x1, y: y1, in: application).coordinate
570
+ // Anchor the end on the same window as the start, so a drag that leaves
571
+ // the window (resizing it, dropping onto another app) still lands where
572
+ // it was asked to.
573
+ let end = start.withOffset(CGVector(
574
+ dx: try doubleParameter("x2", params) - x1,
575
+ dy: try doubleParameter("y2", params) - y1
576
+ ))
577
+ let holdMs = (try? doubleParameter("holdMs", params)) ?? 100
578
+ start.press(forDuration: max(0.05, holdMs / 1000), thenDragTo: end)
579
+ }
580
+
581
+ private func scroll(_ params: [String: Any]) throws {
582
+ let application = try runningApplication(params)
583
+ let coordinate = try screenCoordinate(
584
+ x: try doubleParameter("x", params),
585
+ y: try doubleParameter("y", params),
586
+ in: application
587
+ ).coordinate
588
+ coordinate.scroll(
589
+ byDeltaX: (try? doubleParameter("dx", params)) ?? 0,
590
+ deltaY: (try? doubleParameter("dy", params)) ?? 0
591
+ )
592
+ }
593
+
594
+ private func typeKey(_ params: [String: Any]) throws {
595
+ let name = try stringParameter("key", params)
596
+ let key: String
597
+ if let named = Self.namedKeys[name.lowercased()] {
598
+ key = named.rawValue
599
+ } else if name.count == 1 {
600
+ key = name
601
+ } else {
602
+ throw RunnerError.unsupportedKey(name)
603
+ }
604
+ var flags: XCUIElement.KeyModifierFlags = []
605
+ for modifier in (params["modifiers"] as? [String]) ?? [] {
606
+ switch modifier.lowercased() {
607
+ case "command", "cmd": flags.insert(.command)
608
+ case "shift": flags.insert(.shift)
609
+ case "option", "alt": flags.insert(.option)
610
+ case "control", "ctrl": flags.insert(.control)
611
+ case "function", "fn": flags.insert(.function)
612
+ default: throw RunnerError.invalidParameter("modifiers")
613
+ }
614
+ }
615
+ application(params).typeKey(key, modifierFlags: flags)
616
+ }
617
+
618
+ private static let namedKeys: [String: XCUIKeyboardKey] = [
619
+ "return": .return,
620
+ "enter": .enter,
621
+ "escape": .escape,
622
+ "tab": .tab,
623
+ "space": .space,
624
+ "delete": .delete,
625
+ "backspace": .delete,
626
+ "forwarddelete": .forwardDelete,
627
+ "up": .upArrow,
628
+ "down": .downArrow,
629
+ "left": .leftArrow,
630
+ "right": .rightArrow,
631
+ "home": .home,
632
+ "end": .end,
633
+ "pageup": .pageUp,
634
+ "pagedown": .pageDown
635
+ ]
636
+
637
+ /// Resizes the app's main window by dragging its bottom-right corner, then
638
+ /// reports the frame the window actually ended up with. Windows enforce their
639
+ /// own minimum and maximum sizes, and a full-screen window cannot be resized
640
+ /// at all, so callers should compare the returned size with what they asked for.
641
+ private func resizeWindow(_ params: [String: Any]) throws -> [String: Any] {
642
+ let application = try runningApplication(params)
643
+ let window = try mainWindow(of: application)
644
+ let width = try doubleParameter("width", params)
645
+ let height = try doubleParameter("height", params)
646
+ guard width > 0, height > 0 else {
647
+ throw RunnerError.invalidParameter(width > 0 ? "height" : "width")
648
+ }
649
+ // A window cannot grow past the screen edge, so move it first when asked:
650
+ // drag a point in the title bar (clear of the traffic lights on the left)
651
+ // until the window's top-left corner sits at x, y.
652
+ if let x = try? doubleParameter("x", params), let y = try? doubleParameter("y", params) {
653
+ let frame = window.frame
654
+ let grab = window
655
+ .coordinate(withNormalizedOffset: .zero)
656
+ .withOffset(CGVector(dx: min(frame.width / 2, 160), dy: 8))
657
+ grab.press(forDuration: 0.2, thenDragTo: grab.withOffset(CGVector(
658
+ dx: x - frame.origin.x,
659
+ dy: y - frame.origin.y
660
+ )))
661
+ }
662
+ let before = window.frame
663
+ // Grab two points inside the corner: far enough in to hit the resize
664
+ // area rather than miss the window, close enough not to hit content.
665
+ let corner = window
666
+ .coordinate(withNormalizedOffset: .zero)
667
+ .withOffset(CGVector(dx: before.width - 2, dy: before.height - 2))
668
+ let target = corner.withOffset(CGVector(
669
+ dx: width - before.width,
670
+ dy: height - before.height
671
+ ))
672
+ corner.press(forDuration: 0.2, thenDragTo: target)
673
+ let after = window.frame
674
+ return [
675
+ "x": after.origin.x,
676
+ "y": after.origin.y,
677
+ "width": after.width,
678
+ "height": after.height,
679
+ "requestedWidth": width,
680
+ "requestedHeight": height,
681
+ // The screen edge or the window's own size limits stopped the drag.
682
+ "clamped": abs(after.width - width) > 1 || abs(after.height - height) > 1
683
+ ]
684
+ }
685
+ #endif
686
+
687
#if !os(tvOS)
688
/// Maps a point in the application's frame to an `XCUICoordinate`, clamped to the frame.
689
private func coordinate(x: Double, y: Double, in application: XCUIApplication) throws -> XCUICoordinate {
690
+ #if os(macOS)
691
+ return try screenCoordinate(x: x, y: y, in: application).coordinate
692
+ #else
693
let frame = application.frame
694
guard frame.width > 0, frame.height > 0 else {
695
throw RunnerError.emptyFrame
700
dy: max(0, min(1, y / Double(frame.height)))
701
)
702
)
703
+ #endif
704
}
705
706
private func tap(_ params: [String: Any]) throws {
862
case elementNotHittable(String)
863
case emptyFrame
864
case elementNotFocused(String)
865
+ case noWindow
866
case unsupportedButton(String)
867
case unsupportedInteraction(String)
868
+ case unsupportedKey(String)
869
870
var errorDescription: String? {
871
switch self {
872
case .ambiguousElement(let element, let count):
524
- return "Multiple accessibility elements matched \(element): \(count)"
873
+ return "Multiple accessibility elements matched \(element): \(count). Narrow with type (e.g. Button) or pick one with index"
874
case .applicationNotRunning(let application):
875
return "Application \(application) is not running"
876
case .emptyFrame:
887
return "Accessibility element is not hittable: \(element)"
888
case .elementNotFocused(let element):
889
return "Accessibility element is not focused on tvOS: \(element)"
890
+ case .noWindow:
891
+ return "The application has no on-screen window"
892
+ case .unsupportedKey(let key):
893
+ return "Unsupported key: \(key). Use a single character or one of return, enter, escape, tab, space, delete, forwardDelete, up, down, left, right, home, end, pageUp, pageDown"
894
case .unsupportedButton(let button):
895
return "Unsupported button: \(button)"
896
case .unsupportedInteraction(let interaction):