@ondeinference / xcrs-controlkit Mirror · read-only
Fork 0

Read-only mirror of github.com/ondeinference/xcrs-controlkit.

Mirrored from https://github.com/ondeinference/xcrs-controlkit.git

Synced Nov 24, 19:30 UTC

1 import Foundation
2
3 /// The Apple platform represented by a ControlKit runner.
4 public enum XCRSControlKitPlatform: String, Codable, CaseIterable, Sendable {
5 case iOS
6 case iPadOS
7 case tvOS
8 case watchOS
9 case visionOS
10 case macOS
11 }
12
13 /// An operation supported by a ControlKit runner.
14 public enum XCRSControlKitCapability: String, Codable, CaseIterable, Sendable {
15 case accessibility
16 case screenshot
17 case appLifecycle
18 case touch
19 case textInput
20 case swipe
21 case orientation
22 case remoteButtons
23 case keyboard
24 case pointer
25 case spatialInteraction
26 case pairedDevice
27 /// Reports a hinge angle and fold state. Advertised at runtime, only by foldable devices.
28 case hinge
29 }
30
31 /// A simulator or device controlled by a runner.
32 public struct XCRSControlKitTarget: Codable, Equatable, Sendable {
33 // MARK: - Public
34
35 public let platform: XCRSControlKitPlatform
36 public let identifier: String
37 public let name: String?
38
39 public init(
40 platform: XCRSControlKitPlatform,
41 identifier: String,
42 name: String? = nil
43 ) {
44 self.platform = platform
45 self.identifier = identifier
46 self.name = name
47 }
48 }
49
50 /// The capabilities advertised by a runner.
51 public struct XCRSControlKitCapabilities: Codable, Equatable, Sendable {
52 // MARK: - Public
53
54 public let platform: XCRSControlKitPlatform
55 public let values: Set<XCRSControlKitCapability>
56
57 public init(
58 platform: XCRSControlKitPlatform,
59 values: Set<XCRSControlKitCapability>
60 ) {
61 self.platform = platform
62 self.values = values
63 }
64
65 public func supports(_ capability: XCRSControlKitCapability) -> Bool {
66 values.contains(capability)
67 }
68
69 public static func standard(
70 for platform: XCRSControlKitPlatform
71 ) -> Self {
72 let values: Set<XCRSControlKitCapability>
73
74 switch platform {
75 case .iOS, .iPadOS:
76 values = [
77 .accessibility,
78 .screenshot,
79 .appLifecycle,
80 .touch,
81 .textInput,
82 .swipe,
83 .orientation
84 ]
85 case .tvOS:
86 values = [
87 .accessibility,
88 .screenshot,
89 .appLifecycle,
90 .remoteButtons
91 ]
92 case .watchOS:
93 values = [
94 .accessibility,
95 .screenshot,
96 .appLifecycle,
97 .pairedDevice
98 ]
99 case .visionOS:
100 values = [
101 .accessibility,
102 .screenshot,
103 .appLifecycle,
104 .spatialInteraction
105 ]
106 case .macOS:
107 values = [
108 .accessibility,
109 .screenshot,
110 .appLifecycle,
111 .keyboard,
112 .pointer
113 ]
114 }
115
116 return Self(platform: platform, values: values)
117 }
118 }
119
120 /// A screen-space rectangle reported by the accessibility hierarchy.
121 public struct XCRSControlKitRect: Codable, Equatable, Sendable {
122 // MARK: - Public
123
124 public let x: Double
125 public let y: Double
126 public let width: Double
127 public let height: Double
128
129 public init(x: Double, y: Double, width: Double, height: Double) {
130 self.x = x
131 self.y = y
132 self.width = width
133 self.height = height
134 }
135 }
136
137 /// A transport-stable accessibility element returned by `device.dump.ui`.
138 public struct XCRSControlKitAccessibilityNode: Codable, Equatable, Sendable {
139 // MARK: - Public
140
141 public let type: String
142 public let label: String?
143 public let name: String?
144 public let value: String?
145 public let placeholderValue: String?
146 public let rawIdentifier: String?
147 public let rect: XCRSControlKitRect
148 public let depth: Int?
149 public let enabled: Bool?
150 public let selected: Bool?
151 public let focused: Bool?
152 public let hittable: Bool?
153 public let children: [XCRSControlKitAccessibilityNode]
154
155 public init(
156 type: String,
157 label: String? = nil,
158 name: String? = nil,
159 value: String? = nil,
160 placeholderValue: String? = nil,
161 rawIdentifier: String? = nil,
162 rect: XCRSControlKitRect,
163 depth: Int? = nil,
164 enabled: Bool? = nil,
165 selected: Bool? = nil,
166 focused: Bool? = nil,
167 hittable: Bool? = nil,
168 children: [XCRSControlKitAccessibilityNode] = []
169 ) {
170 self.type = type
171 self.label = label
172 self.name = name
173 self.value = value
174 self.placeholderValue = placeholderValue
175 self.rawIdentifier = rawIdentifier
176 self.rect = rect
177 self.depth = depth
178 self.enabled = enabled
179 self.selected = selected
180 self.focused = focused
181 self.hittable = hittable
182 self.children = children
183 }
184 }
185
186 /// Converts XCTest's single-snapshot hierarchy into ControlKit nodes.
187 public enum XCRSControlKitAccessibilityParser {
188 // MARK: - Public
189
190 public static func parse(
191 debugDescription: String
192 ) throws -> XCRSControlKitAccessibilityNode {
193 let lines = debugDescription.components(separatedBy: .newlines)
194 guard
195 let subtreeStart = lines.firstIndex(of: "Element subtree:"),
196 let subtreeEnd = lines[subtreeStart...].firstIndex(of: "Path to element:")
197 else {
198 throw XCRSControlKitError.invalidRequest(
199 "XCTest did not return an accessibility subtree"
200 )
201 }
202
203 let nodes = lines[lines.index(after: subtreeStart)..<subtreeEnd]
204 .compactMap(parseLine)
205 guard !nodes.isEmpty else {
206 throw XCRSControlKitError.invalidRequest(
207 "XCTest returned an empty accessibility subtree"
208 )
209 }
210
211 var index = 0
212 let root = tree(from: nodes, at: &index, depth: 0)
213 guard index == nodes.endIndex else {
214 throw XCRSControlKitError.invalidRequest(
215 "XCTest returned multiple root accessibility elements"
216 )
217 }
218 return root
219 }
220
221 // MARK: - Private
222
223 private struct ParsedNode {
224 let node: XCRSControlKitAccessibilityNode
225 let indentation: Int
226 }
227
228 private static func parseLine(
229 _ line: String
230 ) -> ParsedNode? {
231 let indentation = line.prefix(while: { $0 == " " }).count
232 var content = line.trimmingCharacters(in: .whitespaces)
233 if content.first == "→" {
234 content.removeFirst()
235 }
236 guard let typeEnd = content.firstIndex(of: ",") else {
237 return nil
238 }
239
240 let type = String(content[..<typeEnd])
241 let identifier = quotedAttribute("identifier", in: content)
242 let rect = rectangle(in: content) ?? XCRSControlKitRect(
243 x: 0,
244 y: 0,
245 width: 0,
246 height: 0
247 )
248 return ParsedNode(
249 node: XCRSControlKitAccessibilityNode(
250 type: type,
251 // macOS reports a control's visible text as `title` (buttons,
252 // links, menu items) and rarely sets `label`, so title stands in.
253 label: quotedAttribute("label", in: content)
254 ?? quotedAttribute("title", in: content),
255 name: identifier,
256 value: quotedAttribute("value", in: content)
257 ?? unquotedValue(in: content),
258 placeholderValue: quotedAttribute("placeholderValue", in: content),
259 rawIdentifier: identifier,
260 rect: rect,
261 enabled: !hasStandaloneAttribute("Disabled", in: content),
262 selected: hasStandaloneAttribute("Selected", in: content),
263 focused: hasStandaloneAttribute("Focused", in: content)
264 ),
265 indentation: indentation
266 )
267 }
268
269 private static func tree(
270 from nodes: [ParsedNode],
271 at index: inout Int,
272 depth: Int
273 ) -> XCRSControlKitAccessibilityNode {
274 let parsedNode = nodes[index]
275 index += 1
276
277 var children: [XCRSControlKitAccessibilityNode] = []
278 while index < nodes.count, nodes[index].indentation > parsedNode.indentation {
279 children.append(tree(from: nodes, at: &index, depth: depth + 1))
280 }
281
282 let node = parsedNode.node
283 return XCRSControlKitAccessibilityNode(
284 type: node.type,
285 label: node.label,
286 name: node.name,
287 value: node.value,
288 placeholderValue: node.placeholderValue,
289 rawIdentifier: node.rawIdentifier,
290 rect: node.rect,
291 depth: depth,
292 enabled: node.enabled,
293 selected: node.selected,
294 focused: node.focused,
295 hittable: node.hittable,
296 children: children
297 )
298 }
299
300 private static func rectangle(in line: String) -> XCRSControlKitRect? {
301 guard
302 let rectangleStart = line.range(of: "{{")?.upperBound,
303 let rectangleEnd = line[rectangleStart...].range(of: "}}")?.lowerBound
304 else {
305 return nil
306 }
307
308 let components = line[rectangleStart..<rectangleEnd]
309 .split(whereSeparator: { character in
310 character == "{" || character == "}" || character == ","
311 })
312 .map { $0.trimmingCharacters(in: .whitespaces) }
313 .filter { !$0.isEmpty }
314 guard
315 components.count == 4,
316 let x = Double(components[0]),
317 let y = Double(components[1]),
318 let width = Double(components[2]),
319 let height = Double(components[3])
320 else {
321 return nil
322 }
323 return XCRSControlKitRect(
324 x: x,
325 y: y,
326 width: width,
327 height: height
328 )
329 }
330
331 private static func quotedAttribute(
332 _ name: String,
333 in line: String
334 ) -> String? {
335 let prefix = "\(name): '"
336 guard let valueStart = line.range(of: prefix)?.upperBound else {
337 return nil
338 }
339
340 var index = valueStart
341 while index < line.endIndex {
342 let character = line[index]
343 if character == "'", isClosingQuote(at: index, in: line) {
344 let value = String(line[valueStart..<index])
345 return value.isEmpty ? nil : value
346 }
347 index = line.index(after: index)
348 }
349
350 return nil
351 }
352
353 /// macOS prints a static text's value without quotes, as the last attribute:
354 /// `StaticText, 0x1, {{0.0, 0.0}, {10.0, 10.0}}, value: No file selected`.
355 /// It runs to the end of the line, less any trailing standalone flags.
356 private static func unquotedValue(in line: String) -> String? {
357 // Find the separator outside any quoted attribute, so a `, value: ` that
358 // sits inside a quoted `title`/`label`/`placeholderValue` is not mistaken
359 // for the real value attribute.
360 let separator = ", value: "
361 var index = line.startIndex
362 var quoted = false
363 var valueStart: String.Index?
364 while index < line.endIndex {
365 let character = line[index]
366 if character == "'" {
367 if quoted {
368 if isClosingQuote(at: index, in: line) {
369 quoted = false
370 }
371 } else {
372 quoted = true
373 }
374 } else if character == ",", !quoted, line[index...].hasPrefix(separator) {
375 valueStart = line.index(index, offsetBy: separator.count)
376 break
377 }
378 index = line.index(after: index)
379 }
380 guard
381 let valueStart,
382 line[valueStart...].first != "'"
383 else {
384 return nil
385 }
386 var value = String(line[valueStart...])
387 let flags = ["Disabled", "Selected", "Focused"]
388 var stripped = true
389 while stripped {
390 stripped = false
391 for flag in flags where value.hasSuffix(", \(flag)") {
392 value.removeLast(flag.count + 2)
393 stripped = true
394 }
395 }
396 value = value.trimmingCharacters(in: .whitespaces)
397 return value.isEmpty ? nil : value
398 }
399
400 private static func hasStandaloneAttribute(
401 _ attribute: String,
402 in line: String
403 ) -> Bool {
404 var segmentStart = line.startIndex
405 var index = line.startIndex
406 var quoted = false
407
408 while index < line.endIndex {
409 let character = line[index]
410 if character == "'" {
411 if quoted {
412 if isClosingQuote(at: index, in: line) {
413 quoted = false
414 }
415 } else {
416 quoted = true
417 }
418 } else if character == ",", !quoted {
419 if line[segmentStart..<index].trimmingCharacters(in: .whitespaces) == attribute {
420 return true
421 }
422 segmentStart = line.index(after: index)
423 }
424 index = line.index(after: index)
425 }
426
427 return line[segmentStart...].trimmingCharacters(in: .whitespaces) == attribute
428 }
429
430 private static func isClosingQuote(
431 at quoteIndex: String.Index,
432 in line: String
433 ) -> Bool {
434 var backslashCount = 0
435 var index = quoteIndex
436 while index > line.startIndex {
437 let previousIndex = line.index(before: index)
438 guard line[previousIndex] == "\\" else {
439 break
440 }
441 backslashCount += 1
442 index = previousIndex
443 }
444 guard backslashCount.isMultiple(of: 2) else {
445 return false
446 }
447
448 index = line.index(after: quoteIndex)
449 while index < line.endIndex, line[index].isWhitespace {
450 index = line.index(after: index)
451 }
452 return index == line.endIndex || line[index] == "," || line[index] == "}"
453 }
454 }
455
456 /// A transport-neutral command sent to a runner.
457 public struct XCRSControlKitRequest: Codable, Equatable, Sendable {
458 // MARK: - Public
459
460 public let id: String
461 public let method: String
462 public let parameters: [String: String]
463
464 public init(
465 id: String = UUID().uuidString,
466 method: String,
467 parameters: [String: String] = [:]
468 ) {
469 self.id = id
470 self.method = method
471 self.parameters = parameters
472 }
473 }
474
475 /// Errors shared by package consumers and platform runners.
476 public enum XCRSControlKitError: Error, Equatable, Sendable {
477 case unsupportedPlatform(XCRSControlKitPlatform)
478 case unsupportedCapability(XCRSControlKitCapability)
479 case invalidRequest(String)
480 case transport(String)
481 }