Created
December 25, 2024 03:50
-
-
Save abdusco/ac9d57485a08cc65f42779858d84b84f to your computer and use it in GitHub Desktop.
Which space is my cursor in
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Cocoa | |
import CoreGraphics | |
@_silgen_name("CGSMainConnectionID") | |
func CGSMainConnectionID() -> CGSConnection | |
@_silgen_name("CGSCopyManagedDisplaySpaces") | |
func CGSCopyManagedDisplaySpaces(_ connection: CGSConnection) -> CFArray | |
typealias CGSConnection = UInt32 | |
struct SpaceInfo: Codable { | |
let TotalSpaces: Int | |
let CursorIsInSpace: Int | |
} | |
struct ErrorResponse: Codable { | |
let Error: String | |
} | |
func getCursorPosition() -> CGPoint { | |
let mouseLocation = NSEvent.mouseLocation | |
let screenFrame = NSScreen.main!.frame | |
return CGPoint(x: mouseLocation.x, y: screenFrame.height - mouseLocation.y) | |
} | |
func getAllSpaces() -> [[String: Any]]? { | |
return CGSCopyManagedDisplaySpaces(CGSMainConnectionID()) as? [[String: Any]] | |
} | |
func getSpaceInfo() -> (totalSpaces: Int, currentSpace: Int)? { | |
guard let spaces = getAllSpaces(), | |
let display = spaces.first, | |
let spacesList = display["Spaces"] as? [[String: Any]], | |
let currentSpace = display["Current Space"] as? [String: Any], | |
let currentSpaceID = currentSpace["ManagedSpaceID"] as? Int else { | |
return nil | |
} | |
for (index, space) in spacesList.enumerated() { | |
if let spaceID = space["ManagedSpaceID"] as? Int, | |
spaceID == currentSpaceID { | |
return (spacesList.count, index + 1) | |
} | |
} | |
return nil | |
} | |
func main() { | |
let encoder = JSONEncoder() | |
if let (totalSpaces, currentSpace) = getSpaceInfo() { | |
let info = SpaceInfo(TotalSpaces: totalSpaces, CursorIsInSpace: currentSpace) | |
if let jsonData = try? encoder.encode(info), | |
let jsonString = String(data: jsonData, encoding: .utf8) { | |
print(jsonString) | |
} | |
} else { | |
let error = ErrorResponse(Error: "Unable to determine space information") | |
if let jsonData = try? encoder.encode(error), | |
let jsonString = String(data: jsonData, encoding: .utf8) { | |
print(jsonString) | |
} | |
} | |
} | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment