import CoreGraphics // Geometry converts between two coordinate systems. // // Cocoa (AppKit) uses a bottom-left origin on the primary screen. The Y axis // points up. NSScreen.frame uses this system. // // Accessibility (AX) and CGWindowList use a top-left origin on the primary // screen. The Y axis points down. // // The primary screen is NSScreen.screens[0]. Its height is the pivot for the // conversion. All functions are pure. The unit tests cover a primary screen // and a second screen above, below, and left of the primary screen. enum Geometry { // cocoaToAX converts a rect with a Cocoa origin to a rect with an AX origin. // primaryHeight is the height of the primary screen. static func cocoaToAX(_ rect: CGRect, primaryHeight: CGFloat) -> CGRect { let y = primaryHeight - rect.maxY return CGRect(x: rect.minX, y: y, width: rect.width, height: rect.height) } // axToCocoa converts a rect with an AX origin to a rect with a Cocoa origin. // The conversion is symmetric to cocoaToAX. static func axToCocoa(_ rect: CGRect, primaryHeight: CGFloat) -> CGRect { let y = primaryHeight - (rect.origin.y + rect.height) return CGRect(x: rect.minX, y: y, width: rect.width, height: rect.height) } // cocoaYToAXTop returns the AX top-left Y for a Cocoa rect top edge. // The Cocoa top edge is rect.maxY. The AX value is the distance from the // primary screen top. static func cocoaYToAXTop(_ cocoaMaxY: CGFloat, primaryHeight: CGFloat) -> CGFloat { return primaryHeight - cocoaMaxY } }