Read-only mirror of github.com/ondeinference/xcrs-controlkit.
Mirrored from https://github.com/ondeinference/xcrs-controlkit.git
Synced Nov 24, 19:30 UTC
feature/macos-runner-automation
| 1 | import Foundation |
| 2 | import ImageIO |
| 3 | import NIOCore |
| 4 | import NIOHTTP1 |
| 5 | import NIOPosix |
| 6 | import XCTest |
| 7 | import XCRSControlKit |
| 8 | #if os(iOS) |
| 9 | import UIKit |
| 10 | #endif |
| 11 | |
| 12 | private struct JSONRPCRequest { |
| 13 | let method: String |
| 14 | let params: [String: Any] |
| 15 | let id: Any? |
| 16 | } |
| 17 | |
| 18 | @MainActor |
| 19 | final class ControlKitRPCServer { |
| 20 | // MARK: - Internal |
| 21 | |
| 22 | init() { |
| 23 | port = UInt16(ProcessInfo.processInfo.environment["CONTROLKIT_LISTEN_PORT"] ?? "12004") ?? 12004 |
| 24 | host = ProcessInfo.processInfo.environment["CONTROLKIT_LISTEN_HOST"] ?? "127.0.0.1" |
| 25 | } |
| 26 | |
| 27 | func start() async throws { |
| 28 | let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) |
| 29 | defer { |
| 30 | try? group.syncShutdownGracefully() |
| 31 | } |
| 32 | let requestHandler: (HTTPMethod, String, Data) async -> Data = { [self] method, path, body in |
| 33 | if method == .GET && path == "/health" { |
| 34 | return Data("OK".utf8) |
| 35 | } |
| 36 | return await handle(body) |
| 37 | } |
| 38 | let channel = try await ServerBootstrap(group: group) |
| 39 | .serverChannelOption(ChannelOptions.backlog, value: 256) |
| 40 | .serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) |
| 41 | .childChannelInitializer { channel in |
| 42 | channel.pipeline.configureHTTPServerPipeline().flatMap { |
| 43 | channel.pipeline.addHandler(RPCHandler(requestHandler: requestHandler)) |
| 44 | } |
| 45 | } |
| 46 | .childChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) |
| 47 | .bind(host: host, port: Int(port)) |
| 48 | .get() |
| 49 | try await channel.closeFuture.get() |
| 50 | } |
| 51 | |
| 52 | // MARK: - Private |
| 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", |
| 60 | "device.dump.ui", |
| 61 | "device.hinge.get", |
| 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", |
| 74 | "device.screenshot", |
| 75 | "device.ui.tap", |
| 76 | "device.window.resize" |
| 77 | ] |
| 78 | |
| 79 | private static var platform: XCRSControlKitPlatform { |
| 80 | #if os(tvOS) |
| 81 | return .tvOS |
| 82 | #elseif os(visionOS) |
| 83 | return .visionOS |
| 84 | #elseif os(macOS) |
| 85 | return .macOS |
| 86 | #elseif os(watchOS) |
| 87 | return .watchOS |
| 88 | #else |
| 89 | return .iOS |
| 90 | #endif |
| 91 | } |
| 92 | |
| 93 | private let port: UInt16 |
| 94 | private let host: String |
| 95 | |
| 96 | private func handle(_ body: Data) async -> Data { |
| 97 | do { |
| 98 | if body == Data("health".utf8) { |
| 99 | return try JSONSerialization.data(withJSONObject: ["status": "ok"]) |
| 100 | } |
| 101 | |
| 102 | guard |
| 103 | let object = try JSONSerialization.jsonObject(with: body) as? [String: Any], |
| 104 | let method = object["method"] as? String |
| 105 | else { |
| 106 | return try response(error: -32600, message: "Invalid Request", id: nil) |
| 107 | } |
| 108 | |
| 109 | let request = JSONRPCRequest( |
| 110 | method: method, |
| 111 | params: object["params"] as? [String: Any] ?? [:], |
| 112 | id: object["id"] |
| 113 | ) |
| 114 | return try await dispatch(request) |
| 115 | } catch { |
| 116 | return (try? response(error: -32603, message: error.localizedDescription, id: nil)) ?? Data() |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | private func dispatch(_ request: JSONRPCRequest) async throws -> Data { |
| 121 | switch request.method { |
| 122 | case "device.capabilities": |
| 123 | var capabilities = XCRSControlKitCapabilities.standard(for: Self.platform).values |
| 124 | if await hingeSnapshot() != nil { |
| 125 | capabilities.insert(.hinge) |
| 126 | } |
| 127 | return try response( |
| 128 | result: [ |
| 129 | "platform": Self.platform.rawValue, |
| 130 | "capabilities": capabilities.map(\.rawValue).sorted(), |
| 131 | "methods": Self.supportedMethods |
| 132 | ], |
| 133 | id: request.id |
| 134 | ) |
| 135 | case "device.info": |
| 136 | return try response( |
| 137 | result: [ |
| 138 | "port": port, |
| 139 | "runner": "XCRSControlKit", |
| 140 | "protocolVersion": Self.protocolVersion, |
| 141 | "methods": Self.supportedMethods |
| 142 | ], |
| 143 | id: request.id |
| 144 | ) |
| 145 | case "device.dump.ui": |
| 146 | let target = try requiredApplication(request.params) |
| 147 | let (hierarchy, debugDescription) = try accessibilityHierarchy( |
| 148 | target.application, |
| 149 | name: target.name |
| 150 | ) |
| 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": |
| 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 | } |
| 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": |
| 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": |
| 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") |
| 230 | #else |
| 231 | try tap(request.params) |
| 232 | return try response(result: ["success": true], id: request.id) |
| 233 | #endif |
| 234 | case "device.io.click": |
| 235 | #if os(macOS) |
| 236 | try tap(request.params) |
| 237 | return try response(result: ["success": true], id: request.id) |
| 238 | #else |
| 239 | throw RunnerError.unsupportedInteraction("pointer click") |
| 240 | #endif |
| 241 | case "device.io.spatial.tap": |
| 242 | #if os(visionOS) |
| 243 | try tap(request.params) |
| 244 | return try response(result: ["success": true], id: request.id) |
| 245 | #else |
| 246 | throw RunnerError.unsupportedInteraction("spatial tap") |
| 247 | #endif |
| 248 | case "device.io.swipe": |
| 249 | #if os(iOS) |
| 250 | try swipe(request.params) |
| 251 | return try response(result: ["success": true], id: request.id) |
| 252 | #else |
| 253 | throw RunnerError.unsupportedInteraction("swipe") |
| 254 | #endif |
| 255 | case "device.io.orientation.get": |
| 256 | #if os(iOS) |
| 257 | return try response( |
| 258 | result: ["orientation": Self.orientationName(XCUIDevice.shared.orientation)], |
| 259 | id: request.id |
| 260 | ) |
| 261 | #else |
| 262 | throw RunnerError.unsupportedInteraction("orientation") |
| 263 | #endif |
| 264 | case "device.io.orientation.set": |
| 265 | #if os(iOS) |
| 266 | let name = try stringParameter("orientation", request.params) |
| 267 | guard let orientation = Self.orientation(named: name) else { |
| 268 | throw RunnerError.invalidParameter("orientation") |
| 269 | } |
| 270 | XCUIDevice.shared.orientation = orientation |
| 271 | return try response(result: ["success": true], id: request.id) |
| 272 | #else |
| 273 | throw RunnerError.unsupportedInteraction("orientation") |
| 274 | #endif |
| 275 | case "device.hinge.get": |
| 276 | guard let hinge = await hingeSnapshot() else { |
| 277 | return try response(result: ["status": "unsupported"], id: request.id) |
| 278 | } |
| 279 | return try response( |
| 280 | result: ["status": hinge.status, "angle": hinge.angle], |
| 281 | id: request.id |
| 282 | ) |
| 283 | case "device.io.text": |
| 284 | let text = try stringParameter("text", request.params) |
| 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) |
| 289 | #if os(tvOS) |
| 290 | let press: XCUIRemote.Button |
| 291 | switch button { |
| 292 | case "menu": |
| 293 | press = .menu |
| 294 | case "select": |
| 295 | press = .select |
| 296 | case "playPause": |
| 297 | press = .playPause |
| 298 | case "up": |
| 299 | press = .up |
| 300 | case "down": |
| 301 | press = .down |
| 302 | case "left": |
| 303 | press = .left |
| 304 | case "right": |
| 305 | press = .right |
| 306 | default: |
| 307 | throw RunnerError.unsupportedButton(button) |
| 308 | } |
| 309 | XCUIRemote.shared.press(press) |
| 310 | return try response(result: ["success": true], id: request.id) |
| 311 | #elseif os(iOS) |
| 312 | guard button == "home" else { |
| 313 | throw RunnerError.unsupportedButton(button) |
| 314 | } |
| 315 | XCUIDevice.shared.press(.home) |
| 316 | return try response(result: ["success": true], id: request.id) |
| 317 | #else |
| 318 | throw RunnerError.unsupportedButton(button) |
| 319 | #endif |
| 320 | default: |
| 321 | return try response(error: -32601, message: "Method not found", id: request.id) |
| 322 | } |
| 323 | } |
| 324 | |
| 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, |
| 359 | name: String |
| 360 | ) throws -> (XCRSControlKitAccessibilityNode, String) { |
| 361 | guard application.state == .runningForeground else { |
| 362 | throw RunnerError.applicationNotInForeground(name) |
| 363 | } |
| 364 | let debugDescription = application.debugDescription |
| 365 | guard application.state == .runningForeground else { |
| 366 | throw RunnerError.applicationNotInForeground(name) |
| 367 | } |
| 368 | let hierarchy = try XCRSControlKitAccessibilityParser.parse( |
| 369 | debugDescription: debugDescription |
| 370 | ) |
| 371 | return (hierarchy, debugDescription) |
| 372 | } |
| 373 | |
| 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 | "group": .group, |
| 396 | "scrollview": .scrollView, |
| 397 | "table": .table, |
| 398 | "webview": .webView, |
| 399 | "progressindicator": .progressIndicator, |
| 400 | "datepicker": .datePicker, |
| 401 | "toolbar": .toolbar, |
| 402 | "menu": .menu, |
| 403 | "combobox": .comboBox, |
| 404 | "window": .window, |
| 405 | "other": .other |
| 406 | ] |
| 407 | |
| 408 | private func tapElement( |
| 409 | named element: String, |
| 410 | ofType elementType: XCUIElement.ElementType, |
| 411 | index: Int?, |
| 412 | in application: XCUIApplication, |
| 413 | name: String |
| 414 | ) throws { |
| 415 | guard application.state == .runningForeground else { |
| 416 | throw RunnerError.applicationNotInForeground(name) |
| 417 | } |
| 418 | // macOS controls usually carry their text as `title` (a button's caption), |
| 419 | // not `label`, so match it too there. |
| 420 | #if os(macOS) |
| 421 | let predicate = NSPredicate( |
| 422 | format: "label == %@ OR identifier == %@ OR value == %@ OR title == %@", |
| 423 | element, |
| 424 | element, |
| 425 | element, |
| 426 | element |
| 427 | ) |
| 428 | #else |
| 429 | let predicate = NSPredicate( |
| 430 | format: "label == %@ OR identifier == %@ OR value == %@", |
| 431 | element, |
| 432 | element, |
| 433 | element |
| 434 | ) |
| 435 | #endif |
| 436 | // Web views repeat a control's text on the control and on the static |
| 437 | // text inside it (and often on a nav link too), so callers can narrow |
| 438 | // by type, or pick one of several matches by index (document order). |
| 439 | let matches = application.descendants(matching: elementType).matching(predicate) |
| 440 | let matchCount = matches.count |
| 441 | guard matchCount > 0 else { |
| 442 | throw RunnerError.elementNotFound(element) |
| 443 | } |
| 444 | if let index { |
| 445 | guard index >= 0, index < matchCount else { |
| 446 | throw RunnerError.invalidParameter("index") |
| 447 | } |
| 448 | try activate(matches.element(boundBy: index), named: element) |
| 449 | return |
| 450 | } |
| 451 | guard matchCount == 1 else { |
| 452 | throw RunnerError.ambiguousElement(element, matchCount) |
| 453 | } |
| 454 | try activate(matches.element(boundBy: 0), named: element) |
| 455 | } |
| 456 | |
| 457 | private func activate(_ element: XCUIElement, named name: String) throws { |
| 458 | #if os(tvOS) |
| 459 | guard element.hasFocus else { |
| 460 | throw RunnerError.elementNotFocused(name) |
| 461 | } |
| 462 | XCUIRemote.shared.press(.select) |
| 463 | #else |
| 464 | guard element.isHittable else { |
| 465 | throw RunnerError.elementNotHittable(name) |
| 466 | } |
| 467 | #if os(macOS) |
| 468 | element.click() |
| 469 | #else |
| 470 | element.tap() |
| 471 | #endif |
| 472 | #endif |
| 473 | } |
| 474 | |
| 475 | private func dictionary(_ node: XCRSControlKitAccessibilityNode) throws -> [String: Any] { |
| 476 | let data = try JSONEncoder().encode(node) |
| 477 | guard let object = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { |
| 478 | throw RunnerError.invalidAccessibilityHierarchy |
| 479 | } |
| 480 | return object |
| 481 | } |
| 482 | |
| 483 | /// Like `foregroundApplication`, but fails cleanly when the app is not running. |
| 484 | /// Querying a stopped application records an XCTest failure, which ends the |
| 485 | /// runner's only test case and takes the server down with it. |
| 486 | private func runningApplication(_ params: [String: Any]) throws -> XCUIApplication { |
| 487 | let application = application(params) |
| 488 | guard application.state != .notRunning else { |
| 489 | throw RunnerError.applicationNotRunning( |
| 490 | (params["path"] as? String) ?? (params["bundleId"] as? String) ?? "the app under test" |
| 491 | ) |
| 492 | } |
| 493 | return application |
| 494 | } |
| 495 | |
| 496 | private static func stateName(_ state: XCUIApplication.State) -> String { |
| 497 | switch state { |
| 498 | case .notRunning: return "notRunning" |
| 499 | #if !os(macOS) |
| 500 | case .runningBackgroundSuspended: return "runningBackgroundSuspended" |
| 501 | #endif |
| 502 | case .runningBackground: return "runningBackground" |
| 503 | case .runningForeground: return "runningForeground" |
| 504 | default: return "unknown" |
| 505 | } |
| 506 | } |
| 507 | |
| 508 | /// PNG of the app's main window (`target: "window"`, the default when an app |
| 509 | /// is named) or of the whole main screen (`target: "screen"`), base64-encoded. |
| 510 | /// Pixel sizes are read back from the PNG, so they include the display scale. |
| 511 | private func screenshot(_ params: [String: Any]) throws -> [String: Any] { |
| 512 | let named = !((params["path"] as? String) ?? "").isEmpty |
| 513 | || !((params["bundleId"] as? String) ?? "").isEmpty |
| 514 | let target = (params["target"] as? String) ?? (named ? "window" : "screen") |
| 515 | let png: Data |
| 516 | switch target { |
| 517 | case "screen": |
| 518 | png = XCUIScreen.main.screenshot().pngRepresentation |
| 519 | case "window": |
| 520 | let application = try runningApplication(params) |
| 521 | png = try mainWindow(of: application).screenshot().pngRepresentation |
| 522 | default: |
| 523 | throw RunnerError.invalidParameter("target") |
| 524 | } |
| 525 | var result: [String: Any] = ["png": png.base64EncodedString(), "target": target] |
| 526 | if |
| 527 | let source = CGImageSourceCreateWithData(png as CFData, nil), |
| 528 | let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any] |
| 529 | { |
| 530 | result["width"] = properties[kCGImagePropertyPixelWidth] |
| 531 | result["height"] = properties[kCGImagePropertyPixelHeight] |
| 532 | } |
| 533 | return result |
| 534 | } |
| 535 | |
| 536 | /// The app's largest on-screen window. `windows.firstMatch` is not enough on |
| 537 | /// macOS: WebKit-based apps (Tauri, Electron) also own small hidden helper |
| 538 | /// windows that can come first. |
| 539 | private func mainWindow(of application: XCUIApplication) throws -> XCUIElement { |
| 540 | let windows = application.windows.allElementsBoundByIndex.filter { window in |
| 541 | let frame = window.frame |
| 542 | return frame.width > 1 && frame.height > 1 |
| 543 | } |
| 544 | guard let window = windows.max(by: { left, right in |
| 545 | left.frame.width * left.frame.height < right.frame.width * right.frame.height |
| 546 | }) else { |
| 547 | throw RunnerError.noWindow |
| 548 | } |
| 549 | return window |
| 550 | } |
| 551 | |
| 552 | #if os(macOS) |
| 553 | /// Maps a screen point (the space `device.dump.ui` reports rects in) to a |
| 554 | /// coordinate anchored on the window under it. The application element has |
| 555 | /// no frame of its own on macOS, so it cannot be the anchor there. |
| 556 | private func screenCoordinate( |
| 557 | x: Double, |
| 558 | y: Double, |
| 559 | in application: XCUIApplication |
| 560 | ) throws -> (coordinate: XCUICoordinate, window: XCUIElement) { |
| 561 | let point = CGPoint(x: x, y: y) |
| 562 | let windows = application.windows.allElementsBoundByIndex.filter { window in |
| 563 | let frame = window.frame |
| 564 | return frame.width > 1 && frame.height > 1 |
| 565 | } |
| 566 | guard let window = windows.first(where: { $0.frame.contains(point) }) ?? windows.first else { |
| 567 | throw RunnerError.noWindow |
| 568 | } |
| 569 | let origin = window.frame.origin |
| 570 | let coordinate = window |
| 571 | .coordinate(withNormalizedOffset: .zero) |
| 572 | .withOffset(CGVector(dx: x - origin.x, dy: y - origin.y)) |
| 573 | return (coordinate, window) |
| 574 | } |
| 575 | |
| 576 | private func drag(_ params: [String: Any]) throws { |
| 577 | let application = try runningApplication(params) |
| 578 | let x1 = try doubleParameter("x1", params) |
| 579 | let y1 = try doubleParameter("y1", params) |
| 580 | let start = try screenCoordinate(x: x1, y: y1, in: application).coordinate |
| 581 | // Anchor the end on the same window as the start, so a drag that leaves |
| 582 | // the window (resizing it, dropping onto another app) still lands where |
| 583 | // it was asked to. |
| 584 | let end = start.withOffset(CGVector( |
| 585 | dx: try doubleParameter("x2", params) - x1, |
| 586 | dy: try doubleParameter("y2", params) - y1 |
| 587 | )) |
| 588 | let holdMs = (try? doubleParameter("holdMs", params)) ?? 100 |
| 589 | start.press(forDuration: max(0.05, holdMs / 1000), thenDragTo: end) |
| 590 | } |
| 591 | |
| 592 | private func scroll(_ params: [String: Any]) throws { |
| 593 | let application = try runningApplication(params) |
| 594 | let coordinate = try screenCoordinate( |
| 595 | x: try doubleParameter("x", params), |
| 596 | y: try doubleParameter("y", params), |
| 597 | in: application |
| 598 | ).coordinate |
| 599 | coordinate.scroll( |
| 600 | byDeltaX: (try? doubleParameter("dx", params)) ?? 0, |
| 601 | deltaY: (try? doubleParameter("dy", params)) ?? 0 |
| 602 | ) |
| 603 | } |
| 604 | |
| 605 | private func typeKey(_ params: [String: Any]) throws { |
| 606 | let name = try stringParameter("key", params) |
| 607 | let key: String |
| 608 | if let named = Self.namedKeys[name.lowercased()] { |
| 609 | key = named.rawValue |
| 610 | } else if name.count == 1 { |
| 611 | key = name |
| 612 | } else { |
| 613 | throw RunnerError.unsupportedKey(name) |
| 614 | } |
| 615 | var flags: XCUIElement.KeyModifierFlags = [] |
| 616 | for modifier in (params["modifiers"] as? [String]) ?? [] { |
| 617 | switch modifier.lowercased() { |
| 618 | case "command", "cmd": flags.insert(.command) |
| 619 | case "shift": flags.insert(.shift) |
| 620 | case "option", "alt": flags.insert(.option) |
| 621 | case "control", "ctrl": flags.insert(.control) |
| 622 | case "function", "fn": flags.insert(.function) |
| 623 | default: throw RunnerError.invalidParameter("modifiers") |
| 624 | } |
| 625 | } |
| 626 | try runningApplication(params).typeKey(key, modifierFlags: flags) |
| 627 | } |
| 628 | |
| 629 | private static let namedKeys: [String: XCUIKeyboardKey] = [ |
| 630 | "return": .return, |
| 631 | "enter": .enter, |
| 632 | "escape": .escape, |
| 633 | "tab": .tab, |
| 634 | "space": .space, |
| 635 | "delete": .delete, |
| 636 | "backspace": .delete, |
| 637 | "forwarddelete": .forwardDelete, |
| 638 | "up": .upArrow, |
| 639 | "down": .downArrow, |
| 640 | "left": .leftArrow, |
| 641 | "right": .rightArrow, |
| 642 | "home": .home, |
| 643 | "end": .end, |
| 644 | "pageup": .pageUp, |
| 645 | "pagedown": .pageDown |
| 646 | ] |
| 647 | |
| 648 | /// Resizes the app's main window by dragging its bottom-right corner, then |
| 649 | /// reports the frame the window actually ended up with. Windows enforce their |
| 650 | /// own minimum and maximum sizes, and a full-screen window cannot be resized |
| 651 | /// at all, so callers should compare the returned size with what they asked for. |
| 652 | private func resizeWindow(_ params: [String: Any]) throws -> [String: Any] { |
| 653 | let application = try runningApplication(params) |
| 654 | let window = try mainWindow(of: application) |
| 655 | let width = try doubleParameter("width", params) |
| 656 | let height = try doubleParameter("height", params) |
| 657 | guard width > 0, height > 0 else { |
| 658 | throw RunnerError.invalidParameter(width > 0 ? "height" : "width") |
| 659 | } |
| 660 | // A window cannot grow past the screen edge, so move it first when asked: |
| 661 | // drag a point in the title bar (clear of the traffic lights on the left) |
| 662 | // until the window's top-left corner sits at x, y. |
| 663 | if let x = try? doubleParameter("x", params), let y = try? doubleParameter("y", params) { |
| 664 | let frame = window.frame |
| 665 | let grab = window |
| 666 | .coordinate(withNormalizedOffset: .zero) |
| 667 | .withOffset(CGVector(dx: min(max(frame.width / 2, 100), 160), dy: 8)) |
| 668 | grab.press(forDuration: 0.2, thenDragTo: grab.withOffset(CGVector( |
| 669 | dx: x - frame.origin.x, |
| 670 | dy: y - frame.origin.y |
| 671 | ))) |
| 672 | } |
| 673 | let before = window.frame |
| 674 | // Grab two points inside the corner: far enough in to hit the resize |
| 675 | // area rather than miss the window, close enough not to hit content. |
| 676 | let corner = window |
| 677 | .coordinate(withNormalizedOffset: .zero) |
| 678 | .withOffset(CGVector(dx: before.width - 2, dy: before.height - 2)) |
| 679 | let target = corner.withOffset(CGVector( |
| 680 | dx: width - before.width, |
| 681 | dy: height - before.height |
| 682 | )) |
| 683 | corner.press(forDuration: 0.2, thenDragTo: target) |
| 684 | let after = window.frame |
| 685 | return [ |
| 686 | "x": after.origin.x, |
| 687 | "y": after.origin.y, |
| 688 | "width": after.width, |
| 689 | "height": after.height, |
| 690 | "requestedWidth": width, |
| 691 | "requestedHeight": height, |
| 692 | // The screen edge or the window's own size limits stopped the drag. |
| 693 | "clamped": abs(after.width - width) > 1 || abs(after.height - height) > 1 |
| 694 | ] |
| 695 | } |
| 696 | #endif |
| 697 | |
| 698 | #if !os(tvOS) |
| 699 | /// Maps a point in the application's frame to an `XCUICoordinate`, clamped to the frame. |
| 700 | private func coordinate(x: Double, y: Double, in application: XCUIApplication) throws -> XCUICoordinate { |
| 701 | #if os(macOS) |
| 702 | return try screenCoordinate(x: x, y: y, in: application).coordinate |
| 703 | #else |
| 704 | let frame = application.frame |
| 705 | guard frame.width > 0, frame.height > 0 else { |
| 706 | throw RunnerError.emptyFrame |
| 707 | } |
| 708 | return application.coordinate( |
| 709 | withNormalizedOffset: CGVector( |
| 710 | dx: max(0, min(1, x / Double(frame.width))), |
| 711 | dy: max(0, min(1, y / Double(frame.height))) |
| 712 | ) |
| 713 | ) |
| 714 | #endif |
| 715 | } |
| 716 | |
| 717 | private func tap(_ params: [String: Any]) throws { |
| 718 | let x = try doubleParameter("x", params) |
| 719 | let y = try doubleParameter("y", params) |
| 720 | try coordinate(x: x, y: y, in: runningApplication(params)).tap() |
| 721 | } |
| 722 | #endif |
| 723 | |
| 724 | #if os(iOS) |
| 725 | private func swipe(_ params: [String: Any]) throws { |
| 726 | let application = try runningApplication(params) |
| 727 | let start = try coordinate( |
| 728 | x: try doubleParameter("x1", params), |
| 729 | y: try doubleParameter("y1", params), |
| 730 | in: application |
| 731 | ) |
| 732 | let end = try coordinate( |
| 733 | x: try doubleParameter("x2", params), |
| 734 | y: try doubleParameter("y2", params), |
| 735 | in: application |
| 736 | ) |
| 737 | let durationMs = (try? doubleParameter("durationMs", params)) ?? 300 |
| 738 | start.press(forDuration: max(0.05, durationMs / 1000), thenDragTo: end) |
| 739 | } |
| 740 | |
| 741 | private static func orientationName(_ orientation: UIDeviceOrientation) -> String { |
| 742 | orientation.isLandscape ? "LANDSCAPE" : "PORTRAIT" |
| 743 | } |
| 744 | |
| 745 | private static func orientation(named name: String) -> UIDeviceOrientation? { |
| 746 | switch name.uppercased() { |
| 747 | case "PORTRAIT": |
| 748 | return .portrait |
| 749 | case "LANDSCAPE": |
| 750 | return .landscapeLeft |
| 751 | default: |
| 752 | return nil |
| 753 | } |
| 754 | } |
| 755 | #endif |
| 756 | |
| 757 | private struct HingeSnapshot { |
| 758 | let status: String |
| 759 | let angle: Double |
| 760 | } |
| 761 | |
| 762 | /// Reads the hinge, or returns nil when this platform or device reports none. |
| 763 | private func hingeSnapshot() async -> HingeSnapshot? { |
| 764 | #if os(iOS) |
| 765 | if #available(iOS 27.1, *) { |
| 766 | guard let hinge = await HingeReader.read() else { return nil } |
| 767 | return HingeSnapshot(status: hinge.status, angle: hinge.angle) |
| 768 | } |
| 769 | #endif |
| 770 | return nil |
| 771 | } |
| 772 | |
| 773 | private func stringParameter(_ name: String, _ params: [String: Any]) throws -> String { |
| 774 | guard let value = params[name] as? String, !value.isEmpty else { |
| 775 | throw RunnerError.invalidParameter(name) |
| 776 | } |
| 777 | return value |
| 778 | } |
| 779 | |
| 780 | private func doubleParameter(_ name: String, _ params: [String: Any]) throws -> Double { |
| 781 | if let value = params[name] as? Double { |
| 782 | return value |
| 783 | } |
| 784 | if let value = params[name] as? NSNumber { |
| 785 | return value.doubleValue |
| 786 | } |
| 787 | throw RunnerError.invalidParameter(name) |
| 788 | } |
| 789 | |
| 790 | private func response(result: [String: Any], id: Any?) throws -> Data { |
| 791 | try JSONSerialization.data(withJSONObject: [ |
| 792 | "jsonrpc": "2.0", |
| 793 | "result": result, |
| 794 | "id": id ?? NSNull() |
| 795 | ]) |
| 796 | } |
| 797 | |
| 798 | private func response(error code: Int, message: String, id: Any?) throws -> Data { |
| 799 | try JSONSerialization.data(withJSONObject: [ |
| 800 | "jsonrpc": "2.0", |
| 801 | "error": ["code": code, "message": message], |
| 802 | "id": id ?? NSNull() |
| 803 | ]) |
| 804 | } |
| 805 | } |
| 806 | |
| 807 | private final class RPCHandler: ChannelInboundHandler { |
| 808 | // MARK: - Internal |
| 809 | |
| 810 | typealias InboundIn = HTTPServerRequestPart |
| 811 | typealias OutboundOut = HTTPServerResponsePart |
| 812 | |
| 813 | init(requestHandler: @escaping (HTTPMethod, String, Data) async -> Data) { |
| 814 | self.requestHandler = requestHandler |
| 815 | } |
| 816 | |
| 817 | func channelRead(context: ChannelHandlerContext, data: NIOAny) { |
| 818 | switch unwrapInboundIn(data) { |
| 819 | case .head(let head): |
| 820 | requestHead = head |
| 821 | requestBody.removeAll(keepingCapacity: true) |
| 822 | case .body(var buffer): |
| 823 | if let bytes = buffer.readBytes(length: buffer.readableBytes) { |
| 824 | requestBody.append(contentsOf: bytes) |
| 825 | } |
| 826 | case .end: |
| 827 | guard let requestHead else { |
| 828 | context.close(promise: nil) |
| 829 | return |
| 830 | } |
| 831 | |
| 832 | let method = requestHead.method |
| 833 | let path = requestHead.uri |
| 834 | let body = requestBody |
| 835 | Task { |
| 836 | let responseBody = await requestHandler(method, path, body) |
| 837 | context.eventLoop.execute { |
| 838 | var headers = HTTPHeaders() |
| 839 | headers.add(name: "Content-Type", value: "application/json") |
| 840 | headers.add(name: "Content-Length", value: "\(responseBody.count)") |
| 841 | headers.add(name: "Connection", value: "close") |
| 842 | let responseHead = HTTPResponseHead( |
| 843 | version: requestHead.version, |
| 844 | status: .ok, |
| 845 | headers: headers |
| 846 | ) |
| 847 | var buffer = context.channel.allocator.buffer(capacity: responseBody.count) |
| 848 | buffer.writeBytes(responseBody) |
| 849 | context.write(self.wrapOutboundOut(.head(responseHead)), promise: nil) |
| 850 | context.write(self.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: nil) |
| 851 | context.writeAndFlush(self.wrapOutboundOut(.end(nil))).whenComplete { _ in |
| 852 | context.close(promise: nil) |
| 853 | } |
| 854 | } |
| 855 | } |
| 856 | } |
| 857 | } |
| 858 | |
| 859 | // MARK: - Private |
| 860 | |
| 861 | private let requestHandler: (HTTPMethod, String, Data) async -> Data |
| 862 | private var requestHead: HTTPRequestHead? |
| 863 | private var requestBody = Data() |
| 864 | } |
| 865 | |
| 866 | private enum RunnerError: LocalizedError { |
| 867 | case ambiguousElement(String, Int) |
| 868 | case applicationNotRunning(String) |
| 869 | case applicationNotInForeground(String) |
| 870 | case invalidAccessibilityHierarchy |
| 871 | case invalidParameter(String) |
| 872 | case elementNotFound(String) |
| 873 | case elementNotHittable(String) |
| 874 | case emptyFrame |
| 875 | case elementNotFocused(String) |
| 876 | case noWindow |
| 877 | case unsupportedButton(String) |
| 878 | case unsupportedInteraction(String) |
| 879 | case unsupportedKey(String) |
| 880 | |
| 881 | var errorDescription: String? { |
| 882 | switch self { |
| 883 | case .ambiguousElement(let element, let count): |
| 884 | return "Multiple accessibility elements matched \(element): \(count). Narrow with type (e.g. Button) or pick one with index" |
| 885 | case .applicationNotRunning(let application): |
| 886 | return "Application \(application) is not running" |
| 887 | case .emptyFrame: |
| 888 | return "The application frame is empty, so there is nothing to tap" |
| 889 | case .applicationNotInForeground(let bundleIdentifier): |
| 890 | return "Application is not running in the foreground: \(bundleIdentifier)" |
| 891 | case .invalidAccessibilityHierarchy: |
| 892 | return "Could not serialize the accessibility hierarchy" |
| 893 | case .invalidParameter(let name): |
| 894 | return "Missing or invalid parameter: \(name)" |
| 895 | case .elementNotFound(let element): |
| 896 | return "No accessibility element matched: \(element)" |
| 897 | case .elementNotHittable(let element): |
| 898 | return "Accessibility element is not hittable: \(element)" |
| 899 | case .elementNotFocused(let element): |
| 900 | return "Accessibility element is not focused on tvOS: \(element)" |
| 901 | case .noWindow: |
| 902 | return "The application has no on-screen window" |
| 903 | case .unsupportedKey(let key): |
| 904 | 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" |
| 905 | case .unsupportedButton(let button): |
| 906 | return "Unsupported button: \(button)" |
| 907 | case .unsupportedInteraction(let interaction): |
| 908 | return "Unsupported interaction: \(interaction)" |
| 909 | } |
| 910 | } |
| 911 | } |
| 912 | |
| 913 | #if os(iOS) |
| 914 | /// `UIHinge` is only delivered through a `UIHingeInteraction` attached to a view, |
| 915 | /// so the reader hosts a one-off view in the runner's first window scene. |
| 916 | @available(iOS 27.1, *) |
| 917 | @MainActor |
| 918 | private enum HingeReader { |
| 919 | static func read() async -> (status: String, angle: Double)? { |
| 920 | guard let scene = UIApplication.shared.connectedScenes.compactMap({ $0 as? UIWindowScene }).first else { |
| 921 | return nil |
| 922 | } |
| 923 | let window = scene.windows.first ?? UIWindow(windowScene: scene) |
| 924 | let view = UIView() |
| 925 | window.addSubview(view) |
| 926 | defer { view.removeFromSuperview() } |
| 927 | |
| 928 | let result: (status: String, angle: Double)? = await withCheckedContinuation { continuation in |
| 929 | var resumed = false |
| 930 | let finish: ((status: String, angle: Double)?) -> Void = { value in |
| 931 | guard !resumed else { return } |
| 932 | resumed = true |
| 933 | continuation.resume(returning: value) |
| 934 | } |
| 935 | let interaction = UIHingeInteraction { _, update in |
| 936 | guard let hinge = update.hinge else { |
| 937 | finish(nil) |
| 938 | return |
| 939 | } |
| 940 | finish((statusName(hinge.status), Double(hinge.angle))) |
| 941 | } |
| 942 | view.addInteraction(interaction) |
| 943 | interaction.isEnabled = true |
| 944 | Task { @MainActor in |
| 945 | try? await Task.sleep(nanoseconds: 2_000_000_000) |
| 946 | finish(nil) |
| 947 | } |
| 948 | } |
| 949 | return result |
| 950 | } |
| 951 | |
| 952 | private static func statusName(_ status: UIHinge.Status) -> String { |
| 953 | switch status { |
| 954 | case .closed: return "closed" |
| 955 | case .partiallyOpen: return "partiallyOpen" |
| 956 | case .fullyOpen: return "fullyOpen" |
| 957 | default: return "unknown" |
| 958 | } |
| 959 | } |
| 960 | } |
| 961 | #endif |