@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 result of one `xcrs-host-inspect` invocation, returned instead of
4 /// exiting so the command surface stays testable.
5 public struct HostInspectInvocationResult: Sendable {
6 public let exitCode: Int32
7 public let standardOutput: String
8 public let standardError: String
9
10 public init(exitCode: Int32, standardOutput: String, standardError: String) {
11 self.exitCode = exitCode
12 self.standardOutput = standardOutput
13 self.standardError = standardError
14 }
15 }
16
17 #if os(macOS)
18
19 import ApplicationServices
20 import CoreGraphics
21 import ImageIO
22 import Vision
23
24 /// Errors surfaced to the `xcrs-host-inspect` command line.
25 public enum HostInspectError: Error, CustomStringConvertible {
26 /// The invocation itself is wrong, so the CLI answers with the usage text.
27 case usage(String)
28 /// The request was well formed but could not be carried out.
29 case failure(String)
30
31 public var description: String {
32 switch self {
33 case .usage(let message), .failure(let message):
34 return message
35 }
36 }
37 }
38
39 /// Converts between the coordinate space a caller reasons about and image
40 /// pixels. A Retina screenshot is two pixels per point, so `--scale 2` accepts
41 /// and reports points; the default of `1` accepts and reports pixels.
42 public struct HostInspectScale: Equatable, Sendable {
43 public let pixelsPerUnit: Double
44
45 public init(pixelsPerUnit: Double) throws {
46 guard pixelsPerUnit > 0, pixelsPerUnit.isFinite else {
47 throw HostInspectError.usage("--scale must be a positive number")
48 }
49 self.pixelsPerUnit = pixelsPerUnit
50 }
51
52 private init(validated pixelsPerUnit: Double) {
53 self.pixelsPerUnit = pixelsPerUnit
54 }
55
56 public static let pixels = HostInspectScale(validated: 1)
57
58 public func pixels(fromUnits units: Double) -> Double {
59 units * pixelsPerUnit
60 }
61
62 public func units(fromPixels pixels: Double) -> Double {
63 pixels / pixelsPerUnit
64 }
65
66 public func units(fromPixels pixels: Int) -> Double {
67 units(fromPixels: Double(pixels))
68 }
69 }
70
71 public struct HostInspectRect: Codable, Equatable, Sendable {
72 public let x: Double
73 public let y: Double
74 public let width: Double
75 public let height: Double
76
77 public init(x: Double, y: Double, width: Double, height: Double) {
78 self.x = x
79 self.y = y
80 self.width = width
81 self.height = height
82 }
83 }
84
85 /// The image a result was read from, in both pixels and caller units.
86 public struct HostInspectImage: Codable, Equatable, Sendable {
87 public let path: String
88 public let pixelWidth: Int
89 public let pixelHeight: Int
90 public let scale: Double
91 public let width: Double
92 public let height: Double
93 }
94
95 public struct HostWindow: Codable, Equatable, Sendable {
96 public let id: Int
97 public let owner: String
98 public let title: String
99 public let layer: Int
100 /// Screen points in the global display space, unaffected by `--scale`.
101 public let bounds: HostInspectRect
102 }
103
104 public struct HostWindowList: Codable, Equatable, Sendable {
105 public let windows: [HostWindow]
106 }
107
108 public struct HostRecognizedText: Codable, Equatable, Sendable {
109 public let text: String
110 public let confidence: Double
111 public let x: Double
112 public let y: Double
113 public let width: Double
114 public let height: Double
115 }
116
117 public struct HostOcrResult: Codable, Equatable, Sendable {
118 public let image: HostInspectImage
119 /// The languages the request was configured with; empty means Vision's
120 /// own default.
121 public let languages: [String]
122 /// Reading order: top to bottom, then left to right.
123 public let results: [HostRecognizedText]
124 }
125
126 public struct HostCropResult: Codable, Equatable, Sendable {
127 public let image: HostInspectImage
128 /// The requested rect, in caller units.
129 public let rect: HostInspectRect
130 public let out: String
131 public let pixelWidth: Int
132 public let pixelHeight: Int
133 }
134
135 public enum HostProbeAxis: String, Codable, Sendable {
136 case row
137 case column
138 }
139
140 public struct HostColorRun: Codable, Equatable, Sendable {
141 /// Run extent in caller units.
142 public let start: Double
143 public let end: Double
144 public let width: Double
145 /// Quantised `#rrggbb`, so low-order noise does not split a surface.
146 public let color: String
147 }
148
149 public struct HostPostureResult: Codable, Equatable, Sendable {
150 /// The Device Hub window that was driven.
151 public let window: String
152 /// The posture button that was pressed.
153 public let button: String
154 }
155
156 public struct HostProbeResult: Codable, Equatable, Sendable {
157 public let image: HostInspectImage
158 public let axis: HostProbeAxis
159 /// The probed row (y) or column (x), in caller units.
160 public let position: Double
161 public let from: Double
162 public let to: Double
163 public let runs: [HostColorRun]
164 }
165
166 /// Reads a screenshot or the host window server. Every image coordinate in the
167 /// output is expressed in caller units; `windows` reports screen points.
168 public enum HostInspect {
169 /// Vision reports bounding boxes in normalised space, so lines whose
170 /// vertical centres differ by less than this are treated as one line.
171 private static let readingOrderTolerance = 0.01
172 private static let quantizationShift: UInt8 = 3
173
174 public static func windows(owner: String?) throws -> HostWindowList {
175 guard
176 let entries = CGWindowListCopyWindowInfo(
177 [.optionOnScreenOnly, .excludeDesktopElements],
178 kCGNullWindowID
179 ) as? [[String: Any]]
180 else {
181 throw HostInspectError.failure("the window server did not return a window list")
182 }
183
184 var windows: [HostWindow] = []
185 for entry in entries {
186 let ownerName = entry[kCGWindowOwnerName as String] as? String ?? ""
187 if let owner, !ownerName.lowercased().contains(owner.lowercased()) {
188 continue
189 }
190 guard
191 let bounds = entry[kCGWindowBounds as String] as? [String: Any],
192 let rect = CGRect(dictionaryRepresentation: bounds as CFDictionary)
193 else {
194 continue
195 }
196
197 windows.append(
198 HostWindow(
199 id: entry[kCGWindowNumber as String] as? Int ?? 0,
200 owner: ownerName,
201 title: entry[kCGWindowName as String] as? String ?? "",
202 layer: entry[kCGWindowLayer as String] as? Int ?? 0,
203 bounds: HostInspectRect(
204 x: rect.origin.x,
205 y: rect.origin.y,
206 width: rect.size.width,
207 height: rect.size.height
208 )
209 )
210 )
211 }
212
213 windows.sort { ($0.layer, $0.id) < ($1.layer, $1.id) }
214 return HostWindowList(windows: windows)
215 }
216
217 /// The Device Hub buttons that set a foldable simulator's hinge, by posture.
218 static let devicePostureButtons = [
219 "closed": "Closed",
220 "partiallyOpen": "Partially Open",
221 "open": "Open"
222 ]
223
224 /// Presses the hinge button in the Device Hub window for `device` through the
225 /// macOS accessibility API. The window does not need to be in front. The
226 /// calling process needs the Accessibility permission.
227 public static func setDeviceHubPosture(device: String, posture: String) throws -> HostPostureResult {
228 guard let label = devicePostureButtons[posture] else {
229 throw HostInspectError.usage(
230 "--posture must be one of \(devicePostureButtons.keys.sorted().joined(separator: ", ")), got \(posture)"
231 )
232 }
233 guard AXIsProcessTrusted() else {
234 throw HostInspectError.failure(
235 "Accessibility access is required to press Device Hub buttons. Allow the app that runs xcrs in System Settings > Privacy & Security > Accessibility, then try again."
236 )
237 }
238
239 // A command-line process gets no live NSWorkspace updates, so find Device
240 // Hub's pid through the window server instead.
241 let entries = CGWindowListCopyWindowInfo([.optionAll], kCGNullWindowID) as? [[String: Any]] ?? []
242 let hubs = Set(
243 entries.compactMap { entry -> pid_t? in
244 guard entry[kCGWindowOwnerName as String] as? String == "Device Hub" else { return nil }
245 return (entry[kCGWindowOwnerPID as String] as? Int).map { pid_t($0) }
246 }
247 ).sorted()
248 guard !hubs.isEmpty else {
249 throw HostInspectError.failure("Device Hub is not running. Open it with the device's window visible, then try again.")
250 }
251
252 // Device Hub titles a simulator's window "<name> – <runtime>".
253 var windows: [AXUIElement] = []
254 for hub in hubs {
255 let application = AXUIElementCreateApplication(hub)
256 for window in axChildren(application, attribute: kAXWindowsAttribute) {
257 let title = axString(window, kAXTitleAttribute)
258 if title == device || (
259 title.hasPrefix(device)
260 && title.dropFirst(device.count).unicodeScalars.first
261 .map(CharacterSet.whitespaces.contains) == true
262 ) {
263 windows.append(window)
264 }
265 }
266 }
267 guard windows.count == 1, let window = windows.first else {
268 throw HostInspectError.failure(
269 windows.isEmpty
270 ? "Device Hub has no open window for '\(device)'. Open the device in Device Hub, then try again."
271 : "Device Hub has \(windows.count) windows for '\(device)'; close the extras so the target is unambiguous."
272 )
273 }
274 guard let button = findAXButton(in: window, description: label, depth: 0) else {
275 throw HostInspectError.failure(
276 "the '\(device)' window has no '\(label)' button; the device may not be foldable."
277 )
278 }
279 let status = AXUIElementPerformAction(button, kAXPressAction as CFString)
280 guard status == .success else {
281 throw HostInspectError.failure("pressing '\(label)' failed (AXError \(status.rawValue))")
282 }
283 return HostPostureResult(window: axString(window, kAXTitleAttribute), button: label)
284 }
285
286 private static func axString(_ element: AXUIElement, _ attribute: String) -> String {
287 var value: CFTypeRef?
288 guard AXUIElementCopyAttributeValue(element, attribute as CFString, &value) == .success else {
289 return ""
290 }
291 return value as? String ?? ""
292 }
293
294 private static func axChildren(_ element: AXUIElement, attribute: String = kAXChildrenAttribute) -> [AXUIElement] {
295 var value: CFTypeRef?
296 guard AXUIElementCopyAttributeValue(element, attribute as CFString, &value) == .success else {
297 return []
298 }
299 return value as? [AXUIElement] ?? []
300 }
301
302 private static func findAXButton(in element: AXUIElement, description: String, depth: Int) -> AXUIElement? {
303 if axString(element, kAXRoleAttribute) == kAXButtonRole,
304 axString(element, kAXDescriptionAttribute) == description {
305 return element
306 }
307 guard depth < 12 else { return nil }
308 for child in axChildren(element) {
309 if let found = findAXButton(in: child, description: description, depth: depth + 1) {
310 return found
311 }
312 }
313 return nil
314 }
315
316 public static func recognizeText(
317 image path: String,
318 scale: HostInspectScale,
319 languages: [String]
320 ) throws -> HostOcrResult {
321 let image = try loadImage(at: path)
322 let request = VNRecognizeTextRequest()
323 request.recognitionLevel = .accurate
324 request.usesLanguageCorrection = false
325 if !languages.isEmpty {
326 request.recognitionLanguages = languages
327 }
328
329 do {
330 try VNImageRequestHandler(cgImage: image, options: [:]).perform([request])
331 } catch {
332 throw HostInspectError.failure(
333 "text recognition failed for \(path): \(error.localizedDescription)"
334 )
335 }
336
337 let observations = request.results ?? []
338 // Vision's origin is the bottom-left corner, so a larger midY is nearer
339 // the top of the image.
340 let ordered = observations.sorted { first, second in
341 let firstMidY = first.boundingBox.midY
342 let secondMidY = second.boundingBox.midY
343 if abs(firstMidY - secondMidY) > readingOrderTolerance {
344 return firstMidY > secondMidY
345 }
346 return first.boundingBox.minX < second.boundingBox.minX
347 }
348
349 let width = Double(image.width)
350 let height = Double(image.height)
351 let results = ordered.compactMap { observation -> HostRecognizedText? in
352 guard let candidate = observation.topCandidates(1).first else { return nil }
353 let box = observation.boundingBox
354 return HostRecognizedText(
355 text: candidate.string,
356 confidence: Double(candidate.confidence),
357 x: scale.units(fromPixels: box.minX * width),
358 y: scale.units(fromPixels: (1 - box.maxY) * height),
359 width: scale.units(fromPixels: box.width * width),
360 height: scale.units(fromPixels: box.height * height)
361 )
362 }
363
364 return HostOcrResult(
365 image: describe(image, path: path, scale: scale),
366 languages: languages,
367 results: results
368 )
369 }
370
371 public static func crop(
372 image path: String,
373 rect: HostInspectRect,
374 scale: HostInspectScale,
375 out: String
376 ) throws -> HostCropResult {
377 let image = try loadImage(at: path)
378 let pixelRect = CGRect(
379 x: scale.pixels(fromUnits: rect.x).rounded(),
380 y: scale.pixels(fromUnits: rect.y).rounded(),
381 width: scale.pixels(fromUnits: rect.width).rounded(),
382 height: scale.pixels(fromUnits: rect.height).rounded()
383 )
384 guard pixelRect.width >= 1, pixelRect.height >= 1 else {
385 throw HostInspectError.usage("crop rect is smaller than one pixel: \(describe(rect))")
386 }
387 guard
388 pixelRect.minX >= 0, pixelRect.minY >= 0,
389 pixelRect.maxX <= CGFloat(image.width), pixelRect.maxY <= CGFloat(image.height)
390 else {
391 throw HostInspectError.failure(
392 "crop rect \(describe(rect)) is outside the "
393 + "\(image.width)x\(image.height) px image"
394 )
395 }
396 guard let cropped = image.cropping(to: pixelRect) else {
397 throw HostInspectError.failure("CoreGraphics refused to crop \(describe(pixelRect))")
398 }
399
400 let url = URL(fileURLWithPath: out)
401 guard
402 let destination = CGImageDestinationCreateWithURL(
403 url as CFURL,
404 "public.png" as CFString,
405 1,
406 nil
407 )
408 else {
409 throw HostInspectError.failure("cannot write a PNG to \(out)")
410 }
411 CGImageDestinationAddImage(destination, cropped, nil)
412 guard CGImageDestinationFinalize(destination) else {
413 throw HostInspectError.failure("cannot write a PNG to \(out)")
414 }
415
416 return HostCropResult(
417 image: describe(image, path: path, scale: scale),
418 rect: rect,
419 out: out,
420 pixelWidth: cropped.width,
421 pixelHeight: cropped.height
422 )
423 }
424
425 public static func probe(
426 image path: String,
427 axis: HostProbeAxis,
428 position: Double,
429 from: Double?,
430 to: Double?,
431 scale: HostInspectScale
432 ) throws -> HostProbeResult {
433 let image = try loadImage(at: path)
434 let extent = axis == .row ? image.height : image.width
435
436 let positionPixel = Int(scale.pixels(fromUnits: position).rounded())
437 guard positionPixel >= 0, positionPixel < extent else {
438 throw HostInspectError.failure(
439 "probe position \(position) is outside the "
440 + "\(axis == .row ? "height \(image.height)" : "width \(image.width)") px image"
441 )
442 }
443
444 let startPixel = clamp(
445 Int(scale.pixels(fromUnits: from ?? scale.units(fromPixels: 0)).rounded()),
446 lower: 0,
447 upper: extent
448 )
449 let endPixel = clamp(
450 Int(scale.pixels(fromUnits: to ?? scale.units(fromPixels: extent)).rounded()),
451 lower: 0,
452 upper: extent
453 )
454 guard endPixel > startPixel else {
455 throw HostInspectError.usage(
456 "--from must be smaller than --to (got \(startPixel)px ..< \(endPixel)px)"
457 )
458 }
459
460 let sampleCount = endPixel - startPixel
461 let stripRect =
462 axis == .row
463 ? CGRect(x: startPixel, y: positionPixel, width: sampleCount, height: 1)
464 : CGRect(x: positionPixel, y: startPixel, width: 1, height: sampleCount)
465 // Sampling a one-pixel strip first is what makes the probe read the
466 // requested line; drawing the whole image into a thin context would
467 // average every other line into it.
468 guard let strip = image.cropping(to: stripRect) else {
469 throw HostInspectError.failure("CoreGraphics refused to crop \(describe(stripRect))")
470 }
471
472 let buffer = try rgbaPixels(
473 of: strip,
474 width: axis == .row ? sampleCount : 1,
475 height: axis == .row ? 1 : sampleCount
476 )
477 let keys = (0..<sampleCount).map { index in
478 quantize(
479 red: buffer[index * 4],
480 green: buffer[index * 4 + 1],
481 blue: buffer[index * 4 + 2]
482 )
483 }
484
485 let runs = groupRuns(keys).map { run in
486 HostColorRun(
487 start: scale.units(fromPixels: startPixel + run.start),
488 end: scale.units(fromPixels: startPixel + run.end),
489 width: scale.units(fromPixels: run.end - run.start),
490 color: hexColor(run.key)
491 )
492 }
493
494 return HostProbeResult(
495 image: describe(image, path: path, scale: scale),
496 axis: axis,
497 position: position,
498 from: scale.units(fromPixels: startPixel),
499 to: scale.units(fromPixels: endPixel),
500 runs: runs
501 )
502 }
503
504 private static func loadImage(at path: String) throws -> CGImage {
505 let url = URL(fileURLWithPath: path)
506 guard let source = CGImageSourceCreateWithURL(url as CFURL, nil) else {
507 throw HostInspectError.failure("cannot open an image at \(path)")
508 }
509 guard let image = CGImageSourceCreateImageAtIndex(source, 0, nil) else {
510 throw HostInspectError.failure("cannot decode an image at \(path)")
511 }
512 return image
513 }
514
515 private static func describe(
516 _ image: CGImage,
517 path: String,
518 scale: HostInspectScale
519 ) -> HostInspectImage {
520 HostInspectImage(
521 path: path,
522 pixelWidth: image.width,
523 pixelHeight: image.height,
524 scale: scale.pixelsPerUnit,
525 width: scale.units(fromPixels: image.width),
526 height: scale.units(fromPixels: image.height)
527 )
528 }
529
530 /// Draws the image into a tightly packed RGBA8 buffer at the requested
531 /// sampling size rather than at native resolution.
532 private static func rgbaPixels(of image: CGImage, width: Int, height: Int) throws -> [UInt8] {
533 var buffer = [UInt8](repeating: 0, count: width * height * 4)
534 let drew = buffer.withUnsafeMutableBytes { raw -> Bool in
535 guard
536 let context = CGContext(
537 data: raw.baseAddress,
538 width: width,
539 height: height,
540 bitsPerComponent: 8,
541 bytesPerRow: width * 4,
542 space: CGColorSpaceCreateDeviceRGB(),
543 bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
544 )
545 else {
546 return false
547 }
548 context.interpolationQuality = .none
549 // No flip transform here on purpose. A CGBitmapContext maps user
550 // space from the bottom-left but lays the buffer out from the top
551 // row down, so drawing an image straight in already yields a
552 // top-down buffer: buffer row 0 is the image's top row, which is
553 // the reading order the probe reports.
554 context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
555 return true
556 }
557 guard drew else {
558 throw HostInspectError.failure("cannot sample a \(width)x\(height) region")
559 }
560 return buffer
561 }
562
563 /// Five bits per channel is enough to separate adjacent UI surfaces
564 /// without splitting one surface on anti-aliasing.
565 static func quantize(red: UInt8, green: UInt8, blue: UInt8) -> Int {
566 Int(red >> quantizationShift) << 10
567 | Int(green >> quantizationShift) << 5
568 | Int(blue >> quantizationShift)
569 }
570
571 static func hexColor(_ key: Int) -> String {
572 let red = (key >> 10) & 31
573 let green = (key >> 5) & 31
574 let blue = key & 31
575 return String(format: "#%02x%02x%02x", red << 3, green << 3, blue << 3)
576 }
577
578 /// Collapses equal neighbours into half-open `[start, end)` runs.
579 static func groupRuns(_ keys: [Int]) -> [(start: Int, end: Int, key: Int)] {
580 var runs: [(start: Int, end: Int, key: Int)] = []
581 for (index, key) in keys.enumerated() {
582 if var last = runs.last, last.key == key {
583 last.end = index + 1
584 runs[runs.count - 1] = last
585 } else {
586 runs.append((start: index, end: index + 1, key: key))
587 }
588 }
589 return runs
590 }
591
592 private static func clamp(_ value: Int, lower: Int, upper: Int) -> Int {
593 min(max(value, lower), upper)
594 }
595
596 private static func describe(_ rect: CGRect) -> String {
597 "\(Int(rect.origin.x)),\(Int(rect.origin.y))"
598 + " \(Int(rect.width))x\(Int(rect.height)) px"
599 }
600
601 private static func describe(_ rect: HostInspectRect) -> String {
602 "\(rect.x),\(rect.y) \(rect.width)x\(rect.height)"
603 }
604 }
605
606 /// Parses and runs the `xcrs-host-inspect` command line.
607 public enum HostInspectCommand {
608 public static let usage = """
609 xcrs-host-inspect <command> [options]
610
611 Commands:
612 windows [--owner <substring>]
613 List on-screen windows with their screen-point bounds.
614 ocr --image <png> [--scale <n>] [--language <tag>]...
615 Recognise text and report it with coordinates.
616 crop --image <png> --rect <x,y,w,h> --out <png> [--scale <n>]
617 Write a region of an image to a new PNG.
618 probe --image <png> (--row <y> | --column <x>) [--from <a>] [--to <b>] [--scale <n>]
619 Report quantised colour runs along one line of an image.
620 devicehub-posture --device <name> --posture <closed|partiallyOpen|open>
621 Set a foldable simulator's hinge by pressing the button in its Device
622 Hub window. Needs Device Hub running and the Accessibility permission.
623 help
624 Print this text.
625
626 Coordinates are in image units. One unit is one pixel unless --scale is
627 given, in which case a unit is 1/scale pixels (a Retina screenshot is
628 --scale 2, so units are points).
629
630 Output is JSON on stdout; exit code 2 means a usage error and 1 a
631 failed operation.
632 """
633
634 public static func invoke(arguments: [String]) -> HostInspectInvocationResult {
635 do {
636 return HostInspectInvocationResult(
637 exitCode: 0,
638 standardOutput: try execute(try parse(arguments)) + "\n",
639 standardError: ""
640 )
641 } catch let error as HostInspectError {
642 switch error {
643 case .usage(let message):
644 return HostInspectInvocationResult(
645 exitCode: 2,
646 standardOutput: "",
647 standardError: "error: \(message)\n\n\(usage)\n"
648 )
649 case .failure(let message):
650 return HostInspectInvocationResult(
651 exitCode: 1,
652 standardOutput: "",
653 standardError: "error: \(message)\n"
654 )
655 }
656 } catch {
657 return HostInspectInvocationResult(
658 exitCode: 1,
659 standardOutput: "",
660 standardError: "error: \(error)\n"
661 )
662 }
663 }
664
665 enum Command: Equatable {
666 case help
667 case windows(owner: String?)
668 case devicePosture(device: String, posture: String)
669 case ocr(image: String, scale: HostInspectScale, languages: [String])
670 case crop(image: String, rect: HostInspectRect, scale: HostInspectScale, out: String)
671 case probe(
672 image: String,
673 axis: HostProbeAxis,
674 position: Double,
675 from: Double?,
676 to: Double?,
677 scale: HostInspectScale
678 )
679 }
680
681 static func parse(_ arguments: [String]) throws -> Command {
682 var scanner = ArgumentScanner(arguments: arguments)
683 guard let name = scanner.next() else {
684 throw HostInspectError.usage("a command is required")
685 }
686
687 switch name {
688 case "help", "-h", "--help":
689 try scanner.rejectRemaining()
690 return .help
691 case "windows":
692 return .windows(owner: try scanner.options().owner)
693 case "devicehub-posture":
694 let options = try scanner.options()
695 guard let device = options.device else {
696 throw HostInspectError.usage("--device is required")
697 }
698 guard let posture = options.posture else {
699 throw HostInspectError.usage("--posture is required")
700 }
701 return .devicePosture(device: device, posture: posture)
702 case "ocr":
703 let options = try scanner.options()
704 return .ocr(
705 image: try options.requiredImage(),
706 scale: options.scale,
707 languages: options.languages
708 )
709 case "crop":
710 let options = try scanner.options()
711 return .crop(
712 image: try options.requiredImage(),
713 rect: try options.requiredRect(),
714 scale: options.scale,
715 out: try options.requiredOut()
716 )
717 case "probe":
718 let options = try scanner.options()
719 let axis: HostProbeAxis
720 let position: Double
721 switch (options.row, options.column) {
722 case (let row?, nil):
723 axis = .row
724 position = row
725 case (nil, let column?):
726 axis = .column
727 position = column
728 case (nil, nil):
729 throw HostInspectError.usage("probe needs --row or --column")
730 case (_?, _?):
731 throw HostInspectError.usage("probe takes either --row or --column, not both")
732 }
733 return .probe(
734 image: try options.requiredImage(),
735 axis: axis,
736 position: position,
737 from: options.from,
738 to: options.to,
739 scale: options.scale
740 )
741 default:
742 throw HostInspectError.usage("unknown command \(name)")
743 }
744 }
745
746 private static func execute(_ command: Command) throws -> String {
747 switch command {
748 case .help:
749 return usage
750 case .windows(let owner):
751 return try encode(HostInspect.windows(owner: owner))
752 case .devicePosture(let device, let posture):
753 return try encode(HostInspect.setDeviceHubPosture(device: device, posture: posture))
754 case .ocr(let image, let scale, let languages):
755 return try encode(
756 HostInspect.recognizeText(image: image, scale: scale, languages: languages)
757 )
758 case .crop(let image, let rect, let scale, let out):
759 return try encode(
760 HostInspect.crop(image: image, rect: rect, scale: scale, out: out)
761 )
762 case .probe(let image, let axis, let position, let from, let to, let scale):
763 return try encode(
764 HostInspect.probe(
765 image: image,
766 axis: axis,
767 position: position,
768 from: from,
769 to: to,
770 scale: scale
771 )
772 )
773 }
774 }
775
776 private static func encode<T: Encodable>(_ value: T) throws -> String {
777 let encoder = JSONEncoder()
778 encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]
779 guard let text = String(data: try encoder.encode(value), encoding: .utf8) else {
780 throw HostInspectError.failure("could not render the result as UTF-8 JSON")
781 }
782 return text
783 }
784 }
785
786 private struct CommandOptions {
787 var image: String?
788 var owner: String?
789 var device: String?
790 var posture: String?
791 var out: String?
792 var rect: String?
793 var scale = HostInspectScale.pixels
794 var row: Double?
795 var column: Double?
796 var from: Double?
797 var to: Double?
798 var languages: [String] = []
799
800 func requiredImage() throws -> String {
801 guard let image else {
802 throw HostInspectError.usage("--image is required")
803 }
804 return image
805 }
806
807 func requiredOut() throws -> String {
808 guard let out else {
809 throw HostInspectError.usage("--out is required")
810 }
811 return out
812 }
813
814 func requiredRect() throws -> HostInspectRect {
815 guard let rect else {
816 throw HostInspectError.usage("--rect is required")
817 }
818 let parts = rect.split(separator: ",", omittingEmptySubsequences: false)
819 guard parts.count == 4 else {
820 throw HostInspectError.usage("--rect expects x,y,w,h, got \(rect)")
821 }
822 let values = try parts.map { part -> Double in
823 let text = String(part).trimmingCharacters(in: .whitespaces)
824 guard let value = Double(text), value.isFinite else {
825 throw HostInspectError.usage("--rect values must be numbers, got \(rect)")
826 }
827 return value
828 }
829 guard values[2] > 0, values[3] > 0 else {
830 throw HostInspectError.usage("--rect width and height must be positive, got \(rect)")
831 }
832 return HostInspectRect(x: values[0], y: values[1], width: values[2], height: values[3])
833 }
834 }
835
836 private struct ArgumentScanner {
837 private let arguments: [String]
838 private var index = 0
839
840 init(arguments: [String]) {
841 self.arguments = arguments
842 }
843
844 mutating func next() -> String? {
845 guard index < arguments.count else { return nil }
846 defer { index += 1 }
847 return arguments[index]
848 }
849
850 mutating func rejectRemaining() throws {
851 if let extra = next() {
852 throw HostInspectError.usage("unexpected argument \(extra)")
853 }
854 }
855
856 mutating func options() throws -> CommandOptions {
857 var options = CommandOptions()
858 while let argument = next() {
859 let (name, inlineValue) = ArgumentScanner.split(argument)
860 switch name {
861 case "--image":
862 options.image = try value(name: name, inline: inlineValue)
863 case "--owner":
864 options.owner = try value(name: name, inline: inlineValue)
865 case "--device":
866 options.device = try value(name: name, inline: inlineValue)
867 case "--posture":
868 options.posture = try value(name: name, inline: inlineValue)
869 case "--out":
870 options.out = try value(name: name, inline: inlineValue)
871 case "--rect":
872 options.rect = try value(name: name, inline: inlineValue)
873 case "--scale":
874 options.scale = try HostInspectScale(
875 pixelsPerUnit: try number(name: name, inline: inlineValue)
876 )
877 case "--row":
878 options.row = try number(name: name, inline: inlineValue)
879 case "--column":
880 options.column = try number(name: name, inline: inlineValue)
881 case "--from":
882 options.from = try number(name: name, inline: inlineValue)
883 case "--to":
884 options.to = try number(name: name, inline: inlineValue)
885 case "--language":
886 options.languages.append(try value(name: name, inline: inlineValue))
887 case "-h", "--help":
888 throw HostInspectError.usage("help is its own command")
889 default:
890 throw HostInspectError.usage("unknown option \(name)")
891 }
892 }
893 return options
894 }
895
896 private mutating func value(name: String, inline: String?) throws -> String {
897 if let inline { return inline }
898 guard let following = next() else {
899 throw HostInspectError.usage("\(name) needs a value")
900 }
901 return following
902 }
903
904 private mutating func number(name: String, inline: String?) throws -> Double {
905 let raw = try value(name: name, inline: inline)
906 guard let number = Double(raw), number.isFinite else {
907 throw HostInspectError.usage("\(name) expects a number, got \(raw)")
908 }
909 return number
910 }
911
912 private static func split(_ argument: String) -> (name: String, inlineValue: String?) {
913 guard let separator = argument.firstIndex(of: "=") else {
914 return (argument, nil)
915 }
916 let name = String(argument[argument.startIndex..<separator])
917 let value = String(argument[argument.index(after: separator)...])
918 return (name, value)
919 }
920 }
921
922 #else
923
924 /// Host inspection needs the macOS window server and Vision.
925 public enum HostInspectCommand {
926 public static func invoke(arguments: [String]) -> HostInspectInvocationResult {
927 HostInspectInvocationResult(
928 exitCode: 1,
929 standardOutput: "",
930 standardError: "error: xcrs-host-inspect runs on macOS only\n"
931 )
932 }
933 }
934
935 #endif