public import CoreGraphics import Foundation public enum WindowHitTest { public static func frontmost(at point: CGPoint, windows: [DragWindow], ignoring: Set = []) -> DragWindow? { windows.first { !ignoring.contains($0.windowNumber) && $0.bounds?.contains(point) == true } } public static func blocksHover(_ windows: [DragWindow], menuBars: [CGRect] = []) -> Bool { windows.contains { window in if window.layer >= CGWindowLevelForKey(.popUpMenuWindow) { return true } guard window.layer >= CGWindowLevelForKey(.mainMenuWindow), let frame = window.bounds else { return false } let isMenuBar = menuBars.contains { abs(frame.minY - $0.minY) <= 1 && abs(frame.width - $0.width) <= 1 && frame.height <= 30 } return !isMenuBar } } } public enum DragWindowLookup { public static func windows() throws -> [DragWindow] { guard let list = CGWindowListCopyWindowInfo(.optionOnScreenOnly, kCGNullWindowID) else { throw InputError.windowListUnavailable } return try (list as NSArray).map { value in guard let fields = value as? NSDictionary, let pid = fields[kCGWindowOwnerPID] as? NSNumber, let number = fields[kCGWindowNumber] as? NSNumber, let layer = fields[kCGWindowLayer] as? NSNumber, let bounds = fields[kCGWindowBounds] as? NSDictionary, let x = bounds["X"] as? NSNumber, let y = bounds["Y"] as? NSNumber, let width = bounds["Width"] as? NSNumber, let height = bounds["Height"] as? NSNumber, let pidValue = Int32(pid.stringValue), let numberValue = UInt32(number.stringValue), let layerValue = Int32(layer.stringValue), [x, y, width, height].allSatisfy({ $0.doubleValue.isFinite }), width.doubleValue >= 0, height.doubleValue >= 0 else { throw InputError.windowListUnavailable } let alpha = (fields[kCGWindowAlpha] as? NSNumber)?.doubleValue ?? 1 guard alpha > 0 else { return nil } return DragWindow( pid: pidValue, windowNumber: numberValue, layer: layerValue, bounds: CGRect(x: x.doubleValue, y: y.doubleValue, width: width.doubleValue, height: height.doubleValue) ) }.compactMap { $0 } } @MainActor public static func window(at point: CGPoint) throws -> DragWindow? { switch WindowHitTest.nativeHit(at: point, windows: try windows()) { case .empty: return nil case .window(let window): return window case .unavailable: throw InputError.windowListUnavailable } } static func window(at point: CGPoint, records: [Record]) -> DragWindow? { records.first { $0.alpha > 0 && $0.number > 0 && $0.bounds.rect.contains(point) }.map { DragWindow(pid: $0.pid, windowNumber: $0.number, layer: Int32($0.layer), bounds: $0.bounds.rect) } } struct Record { let pid: Int32 let number: UInt32 let layer: Int let alpha: Double let bounds: Bounds } struct Bounds { let originX: Double let originY: Double let width: Double let height: Double var rect: CGRect { CGRect(x: originX, y: originY, width: width, height: height) } } }