import CoreGraphics import ParcelCore import Testing @testable import ParcelPlatform private struct FactsProbe: WindowFactsAccess { var failures: [String: AXPlatformError] = [:] var parent = "AXApplication" var children: [String?] = ["AXButton", "AXSheet"] var resizable = true var modal = true var fullScreen = false var minimized = false var childLimitExceeded = false var parentObservation: WindowParentObservation? var role = "AXWindow" var subrole = "AXStandardWindow" var title = "Document" private func read(_ key: String, _ value: Value) throws -> Value { if let failure = failures[key] { throw failure } return value } func string(_ attribute: WindowStringFact) throws -> String { switch attribute { case .role: return try read(attribute.rawValue, role) case .subrole: return try read(attribute.rawValue, subrole) case .title: return try read(attribute.rawValue, title) } } func button(_ attribute: WindowButtonFact) throws -> Bool { try read(attribute.rawValue, true) } func boolean(_ attribute: WindowBooleanFact) throws -> Bool { switch attribute { case .modal: return try read(attribute.rawValue, modal) case .fullScreen: return try read(attribute.rawValue, fullScreen) case .minimized: return try read(attribute.rawValue, minimized) } } func size(_ attribute: WindowSizeFact) throws -> Size { try read( attribute.rawValue, attribute == .minimum ? Size(width: 100, height: 80) : Size(width: 1000, height: 800)) } func sizeSettable() throws -> Bool { try read("settable", resizable) } func parentRole() throws -> String { try read("parent", parent) } func parentWindow() throws -> WindowParentObservation { try read( "parent", parentObservation ?? WindowParentObservation(hasParent: WindowParentReader.isWindowRole(parent))) } func childRoles() throws -> [String?] { if childLimitExceeded { throw NativeTabScanError.limitExceeded } return try read("children", children) } } private let context = WindowFactsContext( bundleID: "example.app", appName: "Example", activationPolicy: .accessory, isHelper: true, level: 2, layer: 3, serverSize: Size(width: 640, height: 480)) @Suite struct WindowFactsReaderTests { @Test func factsBatchContainsOnlyScalarsAndLeavesRemoteTreesForBoundedLazyReads() throws { let names = Set(WindowFactsReader.attributes) #expect( names.isDisjoint(with: [ "AXChildren", "AXTabs", "AXParent", "AXCloseButton", "AXMinimizeButton", "AXZoomButton", "AXFullScreenButton", ])) #expect(names.contains("AXPosition") && names.contains("AXSize")) } @Test func childTreeBeyondTheScanBudgetIsUnknownWithoutDiscardingOtherWindowFacts() throws { let facts = try WindowFactsReader.gather(source: FactsProbe(childLimitExceeded: true), context: context) #expect(facts.hasSheet == nil) #expect(facts.role == "AXWindow" && facts.title == "Document") #expect(facts.isResizable == true) } @Test func gathersWindowFactsAndCallerMetadata() throws { let facts = try WindowFactsReader.gather(source: FactsProbe(), context: context) #expect( facts == WindowFacts( bundleID: "example.app", appName: "Example", activationPolicy: .accessory, isHelper: true, role: "AXWindow", subrole: "AXStandardWindow", title: "Document", hasCloseButton: true, hasMinimizeButton: true, hasZoomButton: true, hasFullScreenButton: true, isResizable: true, isModal: true, hasParent: false, hasSheet: true, minimumSize: Size(width: 100, height: 80), maximumSize: Size(width: 1000, height: 800), isFullScreen: false, isMinimized: false, level: 2, layer: 3, serverSize: Size(width: 640, height: 480))) } @Test func preservesFalseAndTrueBooleanValues() throws { let source = FactsProbe(resizable: false, modal: false, fullScreen: true, minimized: true) let facts = try WindowFactsReader.gather(source: source, context: context) #expect(facts.isResizable == false) #expect(facts.isModal == false) #expect(facts.isFullScreen == true) #expect(facts.isMinimized == true) } @Test(arguments: ["AXApplication", "AXGroup", "AXWindow", "AXSheet", "AXDialog"]) func onlyWindowSheetOrDialogParentsCount(role: String) throws { let facts = try WindowFactsReader.gather(source: FactsProbe(parent: role), context: context) #expect(facts.hasParent == ["AXWindow", "AXSheet", "AXDialog"].contains(role)) } @Test func nestedDialogCarriesItsParentIdentityWithoutLosingTheDialogFrame() throws { let source = FactsProbe( children: [], modal: false, parentObservation: WindowParentObservation(hasParent: true, windowID: 7)) let frame = CGRect(x: 80, y: 120, width: 600, height: 400) let snapshot = try WindowFactsReader.gatherCreatedWindow( source: source, windowID: 42, context: WindowFactsContext(bundleID: "example.browser", activationPolicy: .regular, isHelper: false), isOnScreen: true, frame: { frame }) #expect(snapshot.parentWindowID == 7) #expect(snapshot.frame == frame) #expect(snapshot.facts.hasParent == true) #expect(WindowClassifier().classify(snapshot.facts).disposition == .float) } @Test(arguments: ["AXWindow", "AXSheet", "AXDialog"]) func parentLookupCrossesGroupsAndRecognizesWindowRoles(role: String) throws { let observation = try WindowParentReader.read( window: 1, parent: { $0 == 1 ? 2 : 3 }, containingWindow: { _ in nil }, role: { $0 == 2 ? "AXGroup" : role }, same: { $0 == $1 }, identify: { CGWindowID($0) }) #expect(observation == WindowParentObservation(hasParent: true, windowID: 3)) } @Test func containingWindowMustIdentifyADistinctWindowRatherThanTheDialogItself() throws { for owner in [1, 3] { let observation = try WindowParentReader.read( window: 1, parent: { _ in 2 }, containingWindow: { _ in owner }, role: { $0 == 2 ? "AXApplication" : "AXWindow" }, same: { $0 == $1 }, identify: { CGWindowID($0) }) #expect(observation.hasParent == (owner == 3)) #expect(observation.windowID == (owner == 3 ? 3 : nil)) } } @Test(arguments: [false, true]) func cyclicAndExcessiveAncestryStayUnknown(cyclic: Bool) throws { var reads = 0 let observation = try WindowParentReader.read( window: 1, parent: { node in reads += 1 return cyclic ? 1 : node + 1 }, containingWindow: { _ in nil }, role: { _ in "AXGroup" }, same: { $0 == $1 }, identify: { CGWindowID($0) }) #expect(observation.hasParent == nil && observation.windowID == nil) #expect(reads == (cyclic ? 1 : WindowParentReader.ancestorLimit)) } @Test func missingAncestorRolesDoNotProveTheWindowHasNoParent() throws { let observation = try WindowParentReader.read( window: 1, parent: { $0 == 1 ? 2 : 3 }, containingWindow: { _ in nil }, role: { $0 == 2 ? nil : "AXApplication" }, same: { $0 == $1 }, identify: { CGWindowID($0) }) #expect(observation.hasParent == nil && observation.windowID == nil) } @Test func anOwnerWithoutANativeIdentityStillMakesTheChildAnAuxiliary() throws { let observation = try WindowParentReader.read( window: 1, parent: { _ in 2 }, containingWindow: { _ in nil }, role: { _ in "AXWindow" }, same: { $0 == $1 }, identify: { _ in nil }) #expect(observation.hasParent == true && observation.windowID == nil) } @Test(arguments: [AXPlatformError.timedOut, .elementInvalid, .notPermitted]) func parentTraversalDoesNotHideTransportFailures(error: AXPlatformError) { #expect(throws: error) { try WindowParentReader.read( window: 1, parent: { _ throws -> Int? in throw error }, containingWindow: { _ in nil }, role: { _ in "AXWindow" }, same: { $0 == $1 }, identify: { CGWindowID($0) }) } } @Test(arguments: ["AXDialog", "AXSystemDialog", "AXFloatingWindow"]) func nativePanelSubrolesFloatWithoutTitleOrOwnerHeuristics(subrole: String) throws { let facts = try WindowFactsReader.gather( source: FactsProbe(children: [], modal: false, subrole: subrole, title: ""), context: WindowFactsContext(bundleID: "example.browser", activationPolicy: .regular, isHelper: false)) #expect(WindowClassifier().classify(facts).disposition == .float) } @Test(arguments: ["com.apple.finder", "example.browser"], ["Open", "Save", "", "文書"]) func ordinaryWindowsRemainTileableRegardlessOfOwnerOrPickerLikeTitle(bundleID: String, title: String) throws { let facts = try WindowFactsReader.gather( source: FactsProbe(children: [], modal: false, title: title), context: WindowFactsContext(bundleID: bundleID, activationPolicy: .regular, isHelper: false)) #expect(WindowClassifier().classify(facts).disposition == .tile) #expect(facts.hasParent == false) } @Test(arguments: [ ([String?](), false as Bool?), (["AXButton"], false), (["AXSheet", nil], true), (["AXButton", nil], nil), ]) func sheetPresenceKeepsUnknownChildRolesUnknown(roles: [String?], expected: Bool?) throws { let facts = try WindowFactsReader.gather(source: FactsProbe(children: roles), context: context) #expect(facts.hasSheet == expected) } private static let factKeys = [ "AXRole", "AXSubrole", "AXTitle", "AXCloseButton", "AXMinimizeButton", "AXZoomButton", "AXFullScreenButton", "settable", "AXModal", "parent", "children", "AXMinSize", "AXMaxSize", "AXFullScreen", "AXMinimized", ] private func value(for key: String, in facts: WindowFacts) -> Bool { switch key { case "AXRole": return facts.role == nil case "AXSubrole": return facts.subrole == nil case "AXTitle": return facts.title == nil case "AXCloseButton": return facts.hasCloseButton == nil case "AXMinimizeButton": return facts.hasMinimizeButton == nil case "AXZoomButton": return facts.hasZoomButton == nil case "AXFullScreenButton": return facts.hasFullScreenButton == nil case "settable": return facts.isResizable == nil case "AXModal": return facts.isModal == nil case "parent": return facts.hasParent == nil case "children": return facts.hasSheet == nil case "AXMinSize": return facts.minimumSize == nil case "AXMaxSize": return facts.maximumSize == nil case "AXFullScreen": return facts.isFullScreen == nil case "AXMinimized": return facts.isMinimized == nil default: return false } } @Test(arguments: Self.factKeys, [AXPlatformError.attributeUnsupported, .noValue]) func missingFactsRemainUnknown(key: String, error: AXPlatformError) throws { let facts = try WindowFactsReader.gather(source: FactsProbe(failures: [key: error]), context: context) #expect(value(for: key, in: facts)) #expect(facts.bundleID == context.bundleID) } @Test( arguments: Self.factKeys, [ AXPlatformError.timedOut, .messagingFailure, .notPermitted, .elementInvalid, .unexpectedValue("bad"), .other(-1), ]) func realFactErrorsPropagate(key: String, error: AXPlatformError) { #expect(throws: error) { try WindowFactsReader.gather(source: FactsProbe(failures: [key: error]), context: context) } } @Test(arguments: [false, true]) func createdPayloadKeepsVisibilityWindowScopedFactsAndTheAlreadyReadAXFrame(isOnScreen: Bool) throws { let frame = CGRect(x: 20, y: 30, width: 640, height: 480) var frameReads = 0 let created = try WindowFactsReader.gatherCreatedWindow( source: FactsProbe(), windowID: 42, context: context, isOnScreen: isOnScreen, frame: { frameReads += 1; return frame }) #expect(created.windowID == 42) #expect(created.frame == frame) #expect(created.isOnScreen == isOnScreen) #expect(created.facts == (try WindowFactsReader.gather(source: FactsProbe(), context: context))) #expect(frameReads == 1) } @Test(arguments: [AXPlatformError.noValue, .timedOut, .notPermitted, .elementInvalid]) func createdPayloadRequiresARealFrameInsteadOfInventingGeometry(error: AXPlatformError) { #expect(throws: error) { try WindowFactsReader.gatherCreatedWindow( source: FactsProbe(), windowID: 42, context: context, isOnScreen: true, frame: { throw error }) } } @Test func failedFactsDoNotContinueIntoAFrameRead() { var frameReads = 0 #expect(throws: AXPlatformError.timedOut) { try WindowFactsReader.gatherCreatedWindow( source: FactsProbe(failures: ["AXRole": .timedOut]), windowID: 42, context: context, isOnScreen: true, frame: { frameReads += 1; return .zero }) } #expect(frameReads == 0) } @Test(arguments: [0, 1, 2]) func folderAdmissionRetainsRealWindowsAroundAnUnidentifiableAXCandidate(invalidIndex: Int) throws { var candidates: [UInt32] = [42, 43] candidates.insert(0, at: invalidIndex) var identificationReads: [UInt32] = [] var failures: [AXPlatformError] = [] let identified = try AppThreadWindowLookup.identified( in: candidates, identify: { candidate in identificationReads.append(candidate) if candidate == 0 { throw AXPlatformError.other(-25201) } return candidate }, onFailure: { error in if let error = error as? AXPlatformError { failures.append(error) } }) let folderContext = WindowFactsContext( bundleID: "com.apple.finder", activationPolicy: .regular, isHelper: false, layer: 0, serverSize: Size(width: 600, height: 400)) let snapshots = try identified.map { candidate in try WindowFactsReader.gatherCreatedWindow( source: FactsProbe(children: [], modal: false), windowID: candidate.id, context: folderContext, isOnScreen: true, frame: { CGRect(x: 80, y: 108, width: 600, height: 400) }) } #expect(snapshots.map(\.windowID) == [42, 43]) #expect(identificationReads == candidates) #expect(failures == [.other(-25201)]) let classifier = WindowClassifier() for snapshot in snapshots { #expect(classifier.classify(snapshot.facts) == .init(disposition: .tile, reason: .standardWindow)) #expect(snapshot.isOnScreen) let target = CGRect(x: 16, y: 54, width: 1480, height: 854) #expect( FrameWritePlan(current: snapshot.frame, target: target).steps == [ .size(target.size), .position(target.origin), .size(target.size), ]) } } @Test(arguments: ["AXScrollArea", "AXWindow"], [AXPlatformError.other(-25201), .timedOut, .elementInvalid]) func nonWindowIdentityExemptionRequiresTheObservedRole(role: String, error: AXPlatformError) throws { var roleReads = 0 let identify = { () throws -> UInt32? in try AppThreadWindowLookup.windowID( identify: { throw error }, role: { roleReads += 1; return role }) } if role == "AXScrollArea", error == .other(-25201) { #expect(try identify() == nil) } else { #expect(throws: error) { try identify() } } #expect(roleReads == (error == .other(-25201) ? 1 : 0)) } @Test func nonWindowCandidatesDoNotHideRealWindowsOrRoleReadFailures() throws { let identity = { (value: UInt32) throws -> UInt32? in try AppThreadWindowLookup.windowID( identify: { if value == 0 { throw AXPlatformError.other(-25201) }; return value }, role: { "AXScrollArea" }) } let identified = try AppThreadWindowLookup.identified( in: [0, 42, 43], identify: identity, onFailure: { Issue.record("Unexpected identity failure: \($0)") }) #expect(identified.map(\.id) == [42, 43]) #expect( try AppThreadWindowLookup.find( in: [0, 42, 43], windowID: 43, identify: identity, onFailure: { Issue.record("Unexpected lookup failure: \($0)") }) == 43) #expect(throws: AXPlatformError.timedOut) { try AppThreadWindowLookup.windowID( identify: { throw AXPlatformError.other(-25201) }, role: { throw AXPlatformError.timedOut }) } #expect( try AppThreadWindowLookup.windowID( identify: { 42 }, role: { Issue.record("Identified windows need no extra role read"); return "AXWindow" }) == 42) } @Test func optionalFactDoesNotHideOtherErrors() { enum OtherError: Error { case failed } #expect(throws: OtherError.failed) { try optionalWindowFact { () -> Bool in throw OtherError.failed } } } }