import ApplicationServices import RealityDriverSupport extension DriverAXElement { func optional(_ read: () throws -> Value) throws -> Value? { do { return try read() } catch let error as DriverAXError { switch error { case .failure(_, let code) where code == AXError.attributeUnsupported.rawValue || code == AXError.noValue.rawValue: return nil default: throw error } } } func missionControlSnapshot() throws -> [DriverAXNode] { var nodes: [DriverAXNode] = [] func visit(_ element: DriverAXElement, path: [Int]) throws { guard nodes.count < 1024, path.count <= 12 else { throw DriverError("Dock AX tree exceeds snapshot bounds") } let role = try element.string(kAXRoleAttribute) let rectangle = try element.optional { try element.frame } nodes.append( try DriverAXNode( path: path, role: role, identifier: element.optional { try element.string("AXIdentifier") }, title: element.optional { try element.string(kAXTitleAttribute) }, description: element.optional { try element.string(kAXDescriptionAttribute) }, selected: element.optional { try element.boolean(kAXSelectedAttribute) }, frame: rectangle.map { DriverFrame(x: $0.minX, y: $0.minY, width: $0.width, height: $0.height) })) let children = try element.optional { try element.elements(kAXChildrenAttribute) } ?? [] for (index, child) in children.enumerated() { try visit(child, path: path + [index]) } } try visit(self, path: []) return nodes } }