Ariver
2026-06-13 343237725f65445bab306e3fe4cdbd10949d4d4b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
import AppKit
import ApplicationServices
import CoreGraphics
import Foundation
 
struct WindowRecord {
    let ownerName: String
    let name: String
    let layer: Int
    let pid: Int
    let isOnscreen: Bool
    let bounds: CGRect
    let axBounds: CGRect?
 
    var verificationBounds: CGRect {
        axBounds ?? bounds
    }
}
 
struct ScreenRecord {
    let frame: CGRect
    let visibleFrame: CGRect
    let cgFrame: CGRect
}
 
enum QAError: Error, CustomStringConvertible {
    case windowListUnavailable
    case forbiddenAlignerWindows([WindowRecord])
    case unexpectedOverlayCount(count: Int, expected: Int)
    case tooManyAllowedWindows(title: String, count: Int, maximum: Int)
    case unexpectedWindowCount(title: String, count: Int, expected: Int)
    case invalidOverlayLayer(title: String, layer: Int, maximumExclusive: Int)
    case mouseOutsideScreens(location: CGPoint)
    case overlayNotOnMouseScreen(title: String, bounds: CGRect, mouseLocation: CGPoint, expectedBounds: CGRect, screenFrame: CGRect)
    case overlayDoesNotUseScreenFrame(title: String, bounds: CGRect, expectedBounds: CGRect, screenFrame: CGRect, visibleFrame: CGRect)
 
    var description: String {
        switch self {
        case .windowListUnavailable:
            return "CGWindowListCopyWindowInfo returned no data."
        case .forbiddenAlignerWindows(let windows):
            let details = windows.map {
                "- owner=\($0.ownerName) pid=\($0.pid) layer=\($0.layer) bounds=\(formatRect($0.bounds)) axBounds=\(formatOptionalRect($0.axBounds)) title=\"\($0.name)\""
            }.joined(separator: "\n")
            return "Unexpected Aligner windows found in Round0:\n\(details)"
        case .unexpectedOverlayCount(let count, let expected):
            return "Unexpected Aligner overlay count: found \(count), expected \(expected)."
        case .tooManyAllowedWindows(let title, let count, let maximum):
            return "Too many allowed Aligner windows titled \"\(title)\": found \(count), maximum \(maximum)."
        case .unexpectedWindowCount(let title, let count, let expected):
            return "Unexpected Aligner window count for \"\(title)\": found \(count), expected \(expected)."
        case .invalidOverlayLayer(let title, let layer, let maximumExclusive):
            return "Invalid overlay layer for \"\(title)\": found \(layer), expected below \(maximumExclusive)."
        case .mouseOutsideScreens(let location):
            return "Mouse is outside all NSScreen frames: \(formatPoint(location))."
        case .overlayNotOnMouseScreen(let title, let bounds, let mouseLocation, let expectedBounds, let screenFrame):
            return "Overlay \"\(title)\" is not on the mouse screen. bounds=\(formatRect(bounds)) expectedCGWindowBounds=\(formatRect(expectedBounds)) mouse=\(formatPoint(mouseLocation)) screen.frame=\(formatRect(screenFrame))."
        case .overlayDoesNotUseScreenFrame(let title, let bounds, let expectedBounds, let screenFrame, let visibleFrame):
            return "Overlay \"\(title)\" does not use full screen.frame. bounds=\(formatRect(bounds)) expectedCGWindowBounds=\(formatRect(expectedBounds)) screen.frame=\(formatRect(screenFrame)) visibleFrame=\(formatRect(visibleFrame))."
        }
    }
}
 
struct QAOptions {
    let expectDebugOverlay: Bool
    let expectDebugSettingsChild: Bool
    let expectPermissions: Bool
    let expectNoPermissions: Bool
    let expectNoDebugOverlay: Bool
    let expectNoDebugSettingsChild: Bool
    let expectRound1PerformancePoC: Bool
    let expectNoRound1PerformancePoC: Bool
    let expectQuickSwitch: Bool
    let expectNoQuickSwitch: Bool
    let expectSingleAlignerOverlay: Bool
    let expectOverlayOnMouseScreen: Bool
    let expectOverlayUsesScreenFrame: Bool
 
    static func parse(arguments: [String]) -> QAOptions {
        QAOptions(
            expectDebugOverlay: arguments.contains("--expect-debug-overlay"),
            expectDebugSettingsChild: arguments.contains("--expect-debug-settings-child"),
            expectPermissions: arguments.contains("--expect-permissions"),
            expectNoPermissions: arguments.contains("--expect-no-permissions"),
            expectNoDebugOverlay: arguments.contains("--expect-no-debug-overlay"),
            expectNoDebugSettingsChild: arguments.contains("--expect-no-debug-settings-child"),
            expectRound1PerformancePoC: arguments.contains("--expect-round01-performance-poc")
                || arguments.contains("--expect-round1-performance-poc"),
            expectNoRound1PerformancePoC: arguments.contains("--expect-no-round01-performance-poc")
                || arguments.contains("--expect-no-round1-performance-poc")
                || arguments.contains("--expect-no-performance-poc"),
            expectQuickSwitch: arguments.contains("--expect-quick-switch"),
            expectNoQuickSwitch: arguments.contains("--expect-no-quick-switch"),
            expectSingleAlignerOverlay: arguments.contains("--expect-single-aligner-overlay"),
            expectOverlayOnMouseScreen: arguments.contains("--expect-overlay-on-mouse-screen"),
            expectOverlayUsesScreenFrame: arguments.contains("--expect-overlay-uses-screen-frame")
        )
    }
}
 
func boolValue(_ value: Any?) -> Bool {
    switch value {
    case let number as NSNumber:
        return number.boolValue
    case let bool as Bool:
        return bool
    default:
        return false
    }
}
 
func intValue(_ value: Any?) -> Int {
    switch value {
    case let number as NSNumber:
        return number.intValue
    case let int as Int:
        return int
    default:
        return 0
    }
}
 
func doubleValue(_ value: Any?) -> Double {
    switch value {
    case let number as NSNumber:
        return number.doubleValue
    case let double as Double:
        return double
    case let int as Int:
        return Double(int)
    default:
        return 0
    }
}
 
func stringValue(_ value: Any?) -> String {
    value as? String ?? ""
}
 
func rectValue(_ value: Any?) -> CGRect {
    guard let dictionary = value as? [String: Any] else {
        return .zero
    }
 
    return CGRect(
        x: doubleValue(dictionary["X"]),
        y: doubleValue(dictionary["Y"]),
        width: doubleValue(dictionary["Width"]),
        height: doubleValue(dictionary["Height"])
    )
}
 
func formatRect(_ rect: CGRect) -> String {
    "x=\(Int(rect.origin.x)) y=\(Int(rect.origin.y)) w=\(Int(rect.size.width)) h=\(Int(rect.size.height))"
}
 
func formatOptionalRect(_ rect: CGRect?) -> String {
    guard let rect else { return "nil" }
    return formatRect(rect)
}
 
func formatPoint(_ point: CGPoint) -> String {
    "x=\(Int(point.x)) y=\(Int(point.y))"
}
 
func allWindows() throws -> [WindowRecord] {
    guard let windowInfo = CGWindowListCopyWindowInfo(
        [.optionOnScreenOnly, .excludeDesktopElements],
        kCGNullWindowID
    ) as? [[String: Any]] else {
        throw QAError.windowListUnavailable
    }
 
    return windowInfo.map { item in
        WindowRecord(
            ownerName: stringValue(item[kCGWindowOwnerName as String]),
            name: stringValue(item[kCGWindowName as String]),
            layer: intValue(item[kCGWindowLayer as String]),
            pid: intValue(item[kCGWindowOwnerPID as String]),
            isOnscreen: boolValue(item[kCGWindowIsOnscreen as String]),
            bounds: rectValue(item[kCGWindowBounds as String]),
            axBounds: axWindowBounds(
                pid: intValue(item[kCGWindowOwnerPID as String]),
                title: stringValue(item[kCGWindowName as String])
            )
        )
    }
}
 
func axWindowBounds(pid: Int, title: String) -> CGRect? {
    guard pid > 0 else { return nil }
 
    let appElement = AXUIElementCreateApplication(pid_t(pid))
    var windowsValue: CFTypeRef?
    guard AXUIElementCopyAttributeValue(
        appElement,
        kAXWindowsAttribute as CFString,
        &windowsValue
    ) == .success,
          let windows = windowsValue as? [AXUIElement]
    else {
        return nil
    }
 
    for window in windows {
        var titleValue: CFTypeRef?
        let axTitle = AXUIElementCopyAttributeValue(
            window,
            kAXTitleAttribute as CFString,
            &titleValue
        ) == .success ? titleValue as? String : nil
        guard axTitle == title else { continue }
 
        var positionValue: CFTypeRef?
        var sizeValue: CFTypeRef?
        guard AXUIElementCopyAttributeValue(
            window,
            kAXPositionAttribute as CFString,
            &positionValue
        ) == .success,
              AXUIElementCopyAttributeValue(
                window,
                kAXSizeAttribute as CFString,
                &sizeValue
              ) == .success,
              let positionValue,
              let sizeValue,
              CFGetTypeID(positionValue) == AXValueGetTypeID(),
              CFGetTypeID(sizeValue) == AXValueGetTypeID()
        else {
            return nil
        }
 
        let positionAXValue = positionValue as! AXValue
        let sizeAXValue = sizeValue as! AXValue
        var position = CGPoint.zero
        var size = CGSize.zero
        guard AXValueGetValue(positionAXValue, .cgPoint, &position),
              AXValueGetValue(sizeAXValue, .cgSize, &size)
        else {
            return nil
        }
 
        return CGRect(origin: position, size: size)
    }
 
    return nil
}
 
func screenRecords() -> [ScreenRecord] {
    let screens = NSScreen.screens
    let globalFrame = screens.map(\.frame).reduce(CGRect.null) { partialResult, frame in
        partialResult.union(frame)
    }
 
    return screens.map { screen in
        let displayID = screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? CGDirectDisplayID ?? 0
        let cgFrame = displayID == 0
            ? CGRect(
                x: screen.frame.minX,
                y: globalFrame.maxY - screen.frame.maxY,
                width: screen.frame.width,
                height: screen.frame.height
            )
            : CGDisplayBounds(displayID)
 
        return ScreenRecord(
            frame: screen.frame,
            visibleFrame: screen.visibleFrame,
            cgFrame: cgFrame
        )
    }
}
 
func mouseScreen(from screens: [ScreenRecord]) -> ScreenRecord? {
    let location = NSEvent.mouseLocation
    return screens.first { screen in
        screen.frame.contains(location)
    }
}
 
func equivalentRect(_ lhs: CGRect, _ rhs: CGRect, tolerance: CGFloat = 2) -> Bool {
    abs(lhs.origin.x - rhs.origin.x) <= tolerance
        && abs(lhs.origin.y - rhs.origin.y) <= tolerance
        && abs(lhs.size.width - rhs.size.width) <= tolerance
        && abs(lhs.size.height - rhs.size.height) <= tolerance
}
 
func equivalentWindowBounds(_ bounds: CGRect, to screen: ScreenRecord) -> Bool {
    equivalentRect(bounds, screen.cgFrame)
}
 
let permissionTitle = "Aligner Needs Permissions"
let debugOverlayTitle = "Aligner Round0 Debug Overlay"
let debugSettingsTitle = "Aligner Round0 Debug Settings"
let round1PerformancePoCTitle = "Aligner Round01 Performance PoC"
let quickSwitchTitle = "Aligner Quick Switch"
let overlayTitles = Set([debugOverlayTitle, round1PerformancePoCTitle, quickSwitchTitle])
 
func run(options: QAOptions) throws {
    let windows = try allWindows()
    let alignerWindows = windows.filter { $0.ownerName == "Aligner" }
    let alignerOverlayWindows = alignerWindows.filter { overlayTitles.contains($0.name) }
    let allowedTitleMaximums = [
        permissionTitle: 1,
        debugOverlayTitle: 1,
        debugSettingsTitle: 1,
        round1PerformancePoCTitle: 1,
        quickSwitchTitle: 1
    ]
    let allowedTitles = Set(allowedTitleMaximums.keys)
    let forbiddenWindows = alignerWindows.filter { window in
        !allowedTitles.contains(window.name)
    }
 
    print("WindowLogic QA")
    print("  screens: \(NSScreen.screens.count)")
    print("  onscreen windows: \(windows.count)")
    print("  aligner windows: \(alignerWindows.count)")
 
    for window in alignerWindows {
        print("  Aligner window: pid=\(window.pid) layer=\(window.layer) bounds=\(formatRect(window.bounds)) axBounds=\(formatOptionalRect(window.axBounds)) title=\"\(window.name)\"")
    }
 
    guard forbiddenWindows.isEmpty else {
        throw QAError.forbiddenAlignerWindows(forbiddenWindows)
    }
 
    for (title, maximum) in allowedTitleMaximums {
        let count = alignerWindows.filter { $0.name == title }.count
        if count > maximum {
            throw QAError.tooManyAllowedWindows(title: title, count: count, maximum: maximum)
        }
    }
 
    try assertWindow(title: debugOverlayTitle, in: alignerWindows, expected: options.expectDebugOverlay ? 1 : nil)
    try assertWindow(title: debugSettingsTitle, in: alignerWindows, expected: options.expectDebugSettingsChild ? 1 : nil)
    try assertWindow(title: permissionTitle, in: alignerWindows, expected: options.expectPermissions ? 1 : nil)
    try assertWindow(title: round1PerformancePoCTitle, in: alignerWindows, expected: options.expectRound1PerformancePoC ? 1 : nil)
    try assertWindow(title: quickSwitchTitle, in: alignerWindows, expected: options.expectQuickSwitch ? 1 : nil)
 
    if options.expectNoDebugOverlay {
        try assertWindow(title: debugOverlayTitle, in: alignerWindows, expected: 0)
    }
    if options.expectNoDebugSettingsChild {
        try assertWindow(title: debugSettingsTitle, in: alignerWindows, expected: 0)
    }
    if options.expectNoPermissions {
        try assertWindow(title: permissionTitle, in: alignerWindows, expected: 0)
    }
    if options.expectNoRound1PerformancePoC {
        try assertWindow(title: round1PerformancePoCTitle, in: alignerWindows, expected: 0)
    }
    if options.expectNoQuickSwitch {
        try assertWindow(title: quickSwitchTitle, in: alignerWindows, expected: 0)
    }
    if options.expectSingleAlignerOverlay && alignerOverlayWindows.count != 1 {
        throw QAError.unexpectedOverlayCount(count: alignerOverlayWindows.count, expected: 1)
    }
 
    let mainMenuLayer = Int(CGWindowLevelForKey(.mainMenuWindow))
    for overlay in alignerOverlayWindows {
        if overlay.layer >= mainMenuLayer {
            throw QAError.invalidOverlayLayer(
                title: overlay.name,
                layer: overlay.layer,
                maximumExclusive: mainMenuLayer
            )
        }
    }
 
    if options.expectOverlayOnMouseScreen || options.expectOverlayUsesScreenFrame {
        let screens = screenRecords()
        let mouseLocation = NSEvent.mouseLocation
        guard let screen = mouseScreen(from: screens) else {
            throw QAError.mouseOutsideScreens(location: mouseLocation)
        }
 
        for overlay in alignerOverlayWindows {
            let bounds = overlay.verificationBounds
            if options.expectOverlayOnMouseScreen && !equivalentWindowBounds(bounds, to: screen) {
                throw QAError.overlayNotOnMouseScreen(
                    title: overlay.name,
                    bounds: bounds,
                    mouseLocation: mouseLocation,
                    expectedBounds: screen.cgFrame,
                    screenFrame: screen.frame
                )
            }
            if options.expectOverlayUsesScreenFrame && !equivalentWindowBounds(bounds, to: screen) {
                throw QAError.overlayDoesNotUseScreenFrame(
                    title: overlay.name,
                    bounds: bounds,
                    expectedBounds: screen.cgFrame,
                    screenFrame: screen.frame,
                    visibleFrame: screen.visibleFrame
                )
            }
        }
    }
 
    print("  Overlay QA check: passed")
}
 
func assertWindow(title: String, in windows: [WindowRecord], expected: Int?) throws {
    guard let expected else { return }
 
    let count = windows.filter { $0.name == title }.count
    guard count == expected else {
        throw QAError.unexpectedWindowCount(title: title, count: count, expected: expected)
    }
}
 
do {
    try run(options: QAOptions.parse(arguments: CommandLine.arguments))
} catch {
    fputs("WindowLogic QA failed: \(error)\n", stderr)
    exit(1)
}