4
import NIOPosix
5
import XCTest
6
import XCRSControlKit
7
+#if os(iOS)
8
+import UIKit
9
+#endif
10
11
private struct JSONRPCRequest {
12
let method: String
56
"device.apps.terminate",
57
"device.capabilities",
58
"device.dump.ui",
56
- "device.ui.tap",
59
+ "device.hinge.get",
60
"device.info",
61
"device.io.button",
62
"device.io.click",
63
+ "device.io.orientation.get",
64
+ "device.io.orientation.set",
65
"device.io.spatial.tap",
66
+ "device.io.swipe",
67
"device.io.tap",
62
- "device.io.text"
68
+ "device.io.text",
69
+ "device.ui.tap"
70
]
71
72
private static var platform: XCRSControlKitPlatform {
113
private func dispatch(_ request: JSONRPCRequest) async throws -> Data {
114
switch request.method {
115
case "device.capabilities":
116
+ var capabilities = XCRSControlKitCapabilities.standard(for: Self.platform).values
117
+ if await hingeSnapshot() != nil {
118
+ capabilities.insert(.hinge)
119
+ }
120
return try response(
121
result: [
122
"platform": Self.platform.rawValue,
112
- "capabilities": XCRSControlKitCapabilities.standard(for: Self.platform).values.map(\.rawValue).sorted(),
123
+ "capabilities": capabilities.map(\.rawValue).sorted(),
124
"methods": Self.supportedMethods
125
],
126
id: request.id
182
#else
183
throw RunnerError.unsupportedInteraction("spatial tap")
184
#endif
185
+ case "device.io.swipe":
186
+ #if os(iOS)
187
+ try swipe(request.params)
188
+ return try response(result: ["success": true], id: request.id)
189
+ #else
190
+ throw RunnerError.unsupportedInteraction("swipe")
191
+ #endif
192
+ case "device.io.orientation.get":
193
+ #if os(iOS)
194
+ return try response(
195
+ result: ["orientation": Self.orientationName(XCUIDevice.shared.orientation)],
196
+ id: request.id
197
+ )
198
+ #else
199
+ throw RunnerError.unsupportedInteraction("orientation")
200
+ #endif
201
+ case "device.io.orientation.set":
202
+ #if os(iOS)
203
+ let name = try stringParameter("orientation", request.params)
204
+ guard let orientation = Self.orientation(named: name) else {
205
+ throw RunnerError.invalidParameter("orientation")
206
+ }
207
+ XCUIDevice.shared.orientation = orientation
208
+ return try response(result: ["success": true], id: request.id)
209
+ #else
210
+ throw RunnerError.unsupportedInteraction("orientation")
211
+ #endif
212
+ case "device.hinge.get":
213
+ guard let hinge = await hingeSnapshot() else {
214
+ return try response(result: ["status": "unsupported"], id: request.id)
215
+ }
216
+ return try response(
217
+ result: ["status": hinge.status, "angle": hinge.angle],
218
+ id: request.id
219
+ )
220
case "device.io.text":
221
let text = try stringParameter("text", request.params)
222
foregroundApplication(request.params).typeText(text)
330
return object
331
}
332
287
- #if !os(tvOS)
288
- private func tap(_ params: [String: Any]) throws {
289
- let x = try doubleParameter("x", params)
290
- let y = try doubleParameter("y", params)
333
+ /// Like `foregroundApplication`, but fails cleanly when the app is not running.
334
+ /// Querying a stopped application records an XCTest failure, which ends the
335
+ /// runner's only test case and takes the server down with it.
336
+ private func runningApplication(_ params: [String: Any]) throws -> XCUIApplication {
337
let application = foregroundApplication(params)
338
+ guard application.state != .notRunning else {
339
+ throw RunnerError.applicationNotRunning((params["bundleId"] as? String) ?? "the app under test")
340
+ }
341
+ return application
342
+ }
343
+
344
+ #if !os(tvOS)
345
+ /// Maps a point in the application's frame to an `XCUICoordinate`, clamped to the frame.
346
+ private func coordinate(x: Double, y: Double, in application: XCUIApplication) throws -> XCUICoordinate {
347
let frame = application.frame
293
- let coordinate = application.coordinate(
348
+ guard frame.width > 0, frame.height > 0 else {
349
+ throw RunnerError.emptyFrame
350
+ }
351
+ return application.coordinate(
352
withNormalizedOffset: CGVector(
353
dx: max(0, min(1, x / Double(frame.width))),
354
dy: max(0, min(1, y / Double(frame.height)))
355
)
356
)
299
- coordinate.tap()
357
+ }
358
+
359
+ private func tap(_ params: [String: Any]) throws {
360
+ let x = try doubleParameter("x", params)
361
+ let y = try doubleParameter("y", params)
362
+ try coordinate(x: x, y: y, in: runningApplication(params)).tap()
363
+ }
364
+ #endif
365
+
366
+ #if os(iOS)
367
+ private func swipe(_ params: [String: Any]) throws {
368
+ let application = try runningApplication(params)
369
+ let start = try coordinate(
370
+ x: try doubleParameter("x1", params),
371
+ y: try doubleParameter("y1", params),
372
+ in: application
373
+ )
374
+ let end = try coordinate(
375
+ x: try doubleParameter("x2", params),
376
+ y: try doubleParameter("y2", params),
377
+ in: application
378
+ )
379
+ let durationMs = (try? doubleParameter("durationMs", params)) ?? 300
380
+ start.press(forDuration: max(0.05, durationMs / 1000), thenDragTo: end)
381
+ }
382
+
383
+ private static func orientationName(_ orientation: UIDeviceOrientation) -> String {
384
+ orientation.isLandscape ? "LANDSCAPE" : "PORTRAIT"
385
+ }
386
+
387
+ private static func orientation(named name: String) -> UIDeviceOrientation? {
388
+ switch name.uppercased() {
389
+ case "PORTRAIT":
390
+ return .portrait
391
+ case "LANDSCAPE":
392
+ return .landscapeLeft
393
+ default:
394
+ return nil
395
+ }
396
}
397
#endif
398
399
+ private struct HingeSnapshot {
400
+ let status: String
401
+ let angle: Double
402
+ }
403
+
404
+ /// Reads the hinge, or returns nil when this platform or device reports none.
405
+ private func hingeSnapshot() async -> HingeSnapshot? {
406
+ #if os(iOS)
407
+ if #available(iOS 27.1, *) {
408
+ guard let hinge = await HingeReader.read() else { return nil }
409
+ return HingeSnapshot(status: hinge.status, angle: hinge.angle)
410
+ }
411
+ #endif
412
+ return nil
413
+ }
414
+
415
private func stringParameter(_ name: String, _ params: [String: Any]) throws -> String {
416
guard let value = params[name] as? String, !value.isEmpty else {
417
throw RunnerError.invalidParameter(name)
507
508
private enum RunnerError: LocalizedError {
509
case ambiguousElement(String, Int)
510
+ case applicationNotRunning(String)
511
case applicationNotInForeground(String)
512
case invalidAccessibilityHierarchy
513
case invalidParameter(String)
514
case elementNotFound(String)
515
case elementNotHittable(String)
516
+ case emptyFrame
517
case elementNotFocused(String)
518
case unsupportedButton(String)
519
case unsupportedInteraction(String)
522
switch self {
523
case .ambiguousElement(let element, let count):
524
return "Multiple accessibility elements matched \(element): \(count)"
525
+ case .applicationNotRunning(let application):
526
+ return "Application \(application) is not running"
527
+ case .emptyFrame:
528
+ return "The application frame is empty, so there is nothing to tap"
529
case .applicationNotInForeground(let bundleIdentifier):
530
return "Application is not running in the foreground: \(bundleIdentifier)"
531
case .invalidAccessibilityHierarchy:
545
}
546
}
547
}
548
+
549
+#if os(iOS)
550
+/// `UIHinge` is only delivered through a `UIHingeInteraction` attached to a view,
551
+/// so the reader hosts a one-off view in the runner's first window scene.
552
+@available(iOS 27.1, *)
553
+@MainActor
554
+private enum HingeReader {
555
+ static func read() async -> (status: String, angle: Double)? {
556
+ guard let scene = UIApplication.shared.connectedScenes.compactMap({ $0 as? UIWindowScene }).first else {
557
+ return nil
558
+ }
559
+ let window = scene.windows.first ?? UIWindow(windowScene: scene)
560
+ let view = UIView()
561
+ window.addSubview(view)
562
+ defer { view.removeFromSuperview() }
563
+
564
+ let result: (status: String, angle: Double)? = await withCheckedContinuation { continuation in
565
+ var resumed = false
566
+ let finish: ((status: String, angle: Double)?) -> Void = { value in
567
+ guard !resumed else { return }
568
+ resumed = true
569
+ continuation.resume(returning: value)
570
+ }
571
+ let interaction = UIHingeInteraction { _, update in
572
+ guard let hinge = update.hinge else {
573
+ finish(nil)
574
+ return
575
+ }
576
+ finish((statusName(hinge.status), Double(hinge.angle)))
577
+ }
578
+ view.addInteraction(interaction)
579
+ interaction.isEnabled = true
580
+ Task { @MainActor in
581
+ try? await Task.sleep(nanoseconds: 2_000_000_000)
582
+ finish(nil)
583
+ }
584
+ }
585
+ return result
586
+ }
587
+
588
+ private static func statusName(_ status: UIHinge.Status) -> String {
589
+ switch status {
590
+ case .closed: return "closed"
591
+ case .partiallyOpen: return "partiallyOpen"
592
+ case .fullyOpen: return "fullyOpen"
593
+ default: return "unknown"
594
+ }
595
+ }
596
+}
597
+#endif