From 56075b57666bf8dc4e49fa12ec39a81000bb4a05 Mon Sep 17 00:00:00 2001 From: lwouis Date: Fri, 3 Jan 2025 16:10:40 +0100 Subject: [PATCH] refactor: split private apis for clarity --- alt-tab-macos.xcodeproj/project.pbxproj | 22 +- src/api-wrappers/CGWindowID.swift | 8 +- src/api-wrappers/PrivateApis.swift | 232 ------------------ ...icationServices.HIServices.framework.swift | 34 +++ src/api-wrappers/private-apis/README.md | 9 + .../private-apis/SkyLight.framework.swift | 199 +++++++++++++++ src/experimentations/PrivateApis.swift | 2 +- src/logic/Applications.swift | 4 +- src/logic/NSScreen.swift | 2 +- src/logic/Spaces.swift | 6 +- src/ui/App.swift | 9 +- 11 files changed, 274 insertions(+), 253 deletions(-) delete mode 100644 src/api-wrappers/PrivateApis.swift create mode 100644 src/api-wrappers/private-apis/ApplicationServices.HIServices.framework.swift create mode 100644 src/api-wrappers/private-apis/README.md create mode 100644 src/api-wrappers/private-apis/SkyLight.framework.swift diff --git a/alt-tab-macos.xcodeproj/project.pbxproj b/alt-tab-macos.xcodeproj/project.pbxproj index f7b301b4..99211f1f 100644 --- a/alt-tab-macos.xcodeproj/project.pbxproj +++ b/alt-tab-macos.xcodeproj/project.pbxproj @@ -75,6 +75,7 @@ 5F706EC32BA448D8004D542D /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 5F706EC12BA448D8004D542D /* InfoPlist.strings */; }; 76D02BB22BFE7C9E0056008D /* Pods_alt_tab_macos.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C0712B3BEA2B3780398C0999 /* Pods_alt_tab_macos.framework */; }; AA974BA929B7D84C0099A29E /* PreviewPanel.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA974BA829B7D84C0099A29E /* PreviewPanel.swift */; }; + BF0C803A13C409E7F01FBCAB /* SkyLight.framework.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF0C8B94D7994AB9007F6391 /* SkyLight.framework.swift */; }; BF0C80484AA63306D0DB4DB2 /* SpacesEvents.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF0C8DF008F1EB5F23291A13 /* SpacesEvents.swift */; }; BF0C8052AE41B1B10E42BFCE /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = BF0C875C983226CB16DBD90F /* InfoPlist.strings */; }; BF0C8053A58DFB383A3E3351 /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = BF0C8E237569FA2A8FE20707 /* InfoPlist.strings */; }; @@ -158,6 +159,7 @@ BF0C8DD7EBC3BA1E86BF4BDB /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = BF0C841E403C1C6E8C65727E /* InfoPlist.strings */; }; BF0C8DF4207B0BDC2178277B /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = BF0C8FA077BB185496B4CAE8 /* Localizable.strings */; }; BF0C8E16F38203AEC71E062B /* TableView.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF0C8343C1F6FCA82552DCB7 /* TableView.swift */; }; + BF0C8E366BC25171C0A3881C /* ApplicationServices.HIServices.framework.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF0C8C5C0FF5D567BF190DE5 /* ApplicationServices.HIServices.framework.swift */; }; BF0C8E441C550291B1EC7EDA /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = BF0C8B82128C43A4315B4455 /* InfoPlist.strings */; }; BF0C8EA4654F8059F0AED40E /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = BF0C82992C31AA542EF9E638 /* InfoPlist.strings */; }; BF0C8EF58A07D9752A6392FC /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = BF0C8D928E2ABECB92738113 /* Localizable.strings */; }; @@ -229,7 +231,6 @@ D04BAAB5C4E78AE375EA7D3C /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = D04BAA56B4EEAF17F767C7FD /* Localizable.strings */; }; D04BAABE804F3769CE22BEB6 /* HyperlinkLabel.swift in Sources */ = {isa = PBXBuildFile; fileRef = D04BA49E45BFFF3D9FC60E43 /* HyperlinkLabel.swift */; }; D04BAAD77232701929AC3D74 /* blacklists@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = D04BAAA1835480F9B3CCF170 /* blacklists@2x.png */; }; - D04BAADED6FE28D42924AEBF /* PrivateApis.swift in Sources */ = {isa = PBXBuildFile; fileRef = D04BA5C401AFA55CC67C7188 /* PrivateApis.swift */; }; D04BAAF7ACC3B361FBBF52AA /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = D04BAED4D420C506DAF539F1 /* Localizable.strings */; }; D04BAB048DE698E013577C51 /* ThumbnailsPanel.swift in Sources */ = {isa = PBXBuildFile; fileRef = D04BA653BD073CB58E2CFC93 /* ThumbnailsPanel.swift */; }; D04BAB4EB890853B5B9B2C61 /* BoldLabel.swift in Sources */ = {isa = PBXBuildFile; fileRef = D04BACEE8D430B8CAAD8C4CD /* BoldLabel.swift */; }; @@ -369,6 +370,7 @@ BF0C83D645B6BB523E50670A /* hr */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.strings; name = hr; path = InfoPlist.strings; sourceTree = ""; }; BF0C83E1E5C670A8B03E3612 /* hr */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.strings; name = hr; path = Localizable.strings; sourceTree = ""; }; BF0C83EE282A5FB191918799 /* override_contexts_on_poeditor.ts */ = {isa = PBXFileReference; lastKnownFileType = file.ts; path = override_contexts_on_poeditor.ts; sourceTree = ""; }; + BF0C83EE9730BCFA41D840A9 /* README.md */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; BF0C83F32C3AB0531459F69E /* ku */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.strings; name = ku; path = InfoPlist.strings; sourceTree = ""; }; BF0C83F5F20B43C31F0AD079 /* titles-style.jpg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = "titles-style.jpg"; sourceTree = ""; }; BF0C83FC3C53FFB41A3832FD /* fa */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.strings; name = fa; path = InfoPlist.strings; sourceTree = ""; }; @@ -439,6 +441,7 @@ BF0C8B2EA9269BA0B79A525F /* sk */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.strings; name = sk; path = Localizable.strings; sourceTree = ""; }; BF0C8B5D1A9658E64F8ECB56 /* SystemScrollerStyleEvents.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SystemScrollerStyleEvents.swift; sourceTree = ""; }; BF0C8B841E890CA0D68FFD86 /* Logger.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Logger.swift; sourceTree = ""; }; + BF0C8B94D7994AB9007F6391 /* SkyLight.framework.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SkyLight.framework.swift; sourceTree = ""; }; BF0C8BA452332236D972C60E /* ATShortcut.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ATShortcut.swift; sourceTree = ""; }; BF0C8C0832C397644B035267 /* git.ts */ = {isa = PBXFileReference; lastKnownFileType = file.ts; path = git.ts; sourceTree = ""; }; BF0C8C0FF1B21F5F7CE16B79 /* print_env.sh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.script.sh; path = print_env.sh; sourceTree = ""; }; @@ -446,6 +449,7 @@ BF0C8C4F77466FB59071A71F /* sr */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.strings; name = sr; path = InfoPlist.strings; sourceTree = ""; }; BF0C8C5210ACA9FBFAE9C631 /* preferences-general.jpg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = "preferences-general.jpg"; sourceTree = ""; }; BF0C8C5B74E5DA2CC31E52F4 /* extract_l10n_strings.sh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.script.sh; path = extract_l10n_strings.sh; sourceTree = ""; }; + BF0C8C5C0FF5D567BF190DE5 /* ApplicationServices.HIServices.framework.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ApplicationServices.HIServices.framework.swift; sourceTree = ""; }; BF0C8C6995992F837A9A83A6 /* ca */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.strings; name = ca; path = InfoPlist.strings; sourceTree = ""; }; BF0C8C77273E00B019725640 /* add_missing_terms_on_poeditor.ts */ = {isa = PBXFileReference; lastKnownFileType = file.ts; path = add_missing_terms_on_poeditor.ts; sourceTree = ""; }; BF0C8CA36F8BD99BF38A45D0 /* bn */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.strings; name = bn; path = InfoPlist.strings; sourceTree = ""; }; @@ -533,7 +537,6 @@ D04BA55D1B2C8BFF61954466 /* generate_selfsigned_certificate.sh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.script.sh; path = generate_selfsigned_certificate.sh; sourceTree = ""; }; D04BA5ABFA5457A86536E2E4 /* 5 windows - 1 line.jpg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = "5 windows - 1 line.jpg"; sourceTree = ""; }; D04BA5BD11C365C19461458C /* TextField.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TextField.swift; sourceTree = ""; }; - D04BA5C401AFA55CC67C7188 /* PrivateApis.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrivateApis.swift; sourceTree = ""; }; D04BA5C8373D1480280B71A6 /* tr */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.strings; name = tr; path = InfoPlist.strings; sourceTree = ""; }; D04BA5D2FD6E26D82721C574 /* en */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.strings; name = en; path = InfoPlist.strings; sourceTree = ""; }; D04BA5D9B4EBEB9E4333AE39 /* UserDefaultsEvents.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UserDefaultsEvents.swift; sourceTree = ""; }; @@ -1001,6 +1004,16 @@ path = nb.lproj; sourceTree = ""; }; + BF0C88D101728C6798C7FC07 /* private-apis */ = { + isa = PBXGroup; + children = ( + BF0C83EE9730BCFA41D840A9 /* README.md */, + BF0C8C5C0FF5D567BF190DE5 /* ApplicationServices.HIServices.framework.swift */, + BF0C8B94D7994AB9007F6391 /* SkyLight.framework.swift */, + ); + path = "private-apis"; + sourceTree = ""; + }; BF0C88D941E1F2CD50473F45 /* nn.lproj */ = { isa = PBXGroup; children = ( @@ -1406,13 +1419,13 @@ D04BA6F823BC0EDA9AA4B80A /* AXUIElement.swift */, D04BAC34CFD42A7F6F1F01C0 /* CGWindow.swift */, D04BAD91161791D42FEC4A60 /* HelperExtensions.swift */, - D04BA5C401AFA55CC67C7188 /* PrivateApis.swift */, D04BA03200F5A8FC0CD03607 /* CGWindowID.swift */, D04BA8DB8AA7E5570DAC568A /* Sysctl.swift */, D04BA514F1C4B475B3CA6EB6 /* Bash.swift */, BF0C82E4DE5A28800F1DA6E6 /* MissionControl.swift */, BF0C8B841E890CA0D68FFD86 /* Logger.swift */, BF0C8353097840D7DB1E0E2E /* Markdown.swift */, + BF0C88D101728C6798C7FC07 /* private-apis */, ); path = "api-wrappers"; sourceTree = ""; @@ -2229,7 +2242,6 @@ D04BAFBC862BA5FE0294EA7A /* AXUIElement.swift in Sources */, D04BA73E90EFEF8247A5105D /* CGWindow.swift in Sources */, D04BA004884A273D4D2D3EF1 /* HelperExtensions.swift in Sources */, - D04BAADED6FE28D42924AEBF /* PrivateApis.swift in Sources */, D04BABED81800E18732912CC /* CGWindowID.swift in Sources */, D04BA26A691D56031FCCF00C /* Sysctl.swift in Sources */, 5F21C9E22C6E94410091F72F /* AdditionalControlsSheet.swift in Sources */, @@ -2307,6 +2319,8 @@ BF0C85DA2D285400801C514A /* Logger.swift in Sources */, BF0C89B4B17D7843C32A102E /* Markdown.swift in Sources */, BF0C8A49891371E4027E0641 /* MacroPreferences.swift in Sources */, + BF0C8E366BC25171C0A3881C /* ApplicationServices.HIServices.framework.swift in Sources */, + BF0C803A13C409E7F01FBCAB /* SkyLight.framework.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/src/api-wrappers/CGWindowID.swift b/src/api-wrappers/CGWindowID.swift index 2cd26c99..876eb385 100644 --- a/src/api-wrappers/CGWindowID.swift +++ b/src/api-wrappers/CGWindowID.swift @@ -7,18 +7,18 @@ extension CGWindowID { func level() throws -> CGWindowLevel { var level = CGWindowLevel(0) - CGSGetWindowLevel(cgsMainConnectionId, self, &level) + CGSGetWindowLevel(CGS_CONNECTION, self, &level) return level } func spaces() -> [CGSSpaceID] { - return CGSCopySpacesForWindows(cgsMainConnectionId, CGSSpaceMask.all.rawValue, [self] as CFArray) as! [CGSSpaceID] + return CGSCopySpacesForWindows(CGS_CONNECTION, CGSSpaceMask.all.rawValue, [self] as CFArray) as! [CGSSpaceID] } func screenshot() -> CGImage? { // CGSHWCaptureWindowList var windowId_ = self - let list = CGSHWCaptureWindowList(cgsMainConnectionId, &windowId_, 1, [.ignoreGlobalClipShape, .bestResolution]).takeRetainedValue() as! [CGImage] + let list = CGSHWCaptureWindowList(CGS_CONNECTION, &windowId_, 1, [.ignoreGlobalClipShape, .bestResolution]).takeRetainedValue() as! [CGImage] return list.first // // CGWindowListCreateImage // return CGWindowListCreateImage(.null, .optionIncludingWindow, self, [.boundsIgnoreFraming, .bestResolution]) @@ -35,7 +35,7 @@ extension CGWindowID { private func cgProperty(_ key: String, _ type: T.Type) -> T? { var value: AnyObject? - CGSCopyWindowProperty(cgsMainConnectionId, self, key as CFString, &value) + CGSCopyWindowProperty(CGS_CONNECTION, self, key as CFString, &value) return value as? T } } diff --git a/src/api-wrappers/PrivateApis.swift b/src/api-wrappers/PrivateApis.swift deleted file mode 100644 index 4c019dae..00000000 --- a/src/api-wrappers/PrivateApis.swift +++ /dev/null @@ -1,232 +0,0 @@ -// Private APIs are APIs that we can build the app against, but they are not supported or documented by Apple -// We can see their names as symbols in the SDK (see https://github.com/lwouis/MacOSX-SDKs) -// However their full signature is a best-effort of retro-engineering -// Very little information is available about private APIs. I tried to document them as much as possible here -// Some links: -// * Webkit repo: https://github.com/WebKit/webkit/blob/master/Source/WebCore/PAL/pal/spi/cg/CoreGraphicsSPI.h -// * Alt-tab-macos issue: https://github.com/lwouis/alt-tab-macos/pull/87#issuecomment-558624755 -// * Github repo with retro-engineered internals: https://github.com/NUIKit/CGSInternal - -import Cocoa - -typealias CGSConnectionID = UInt32 -typealias CGSSpaceID = UInt64 - -struct CGSWindowCaptureOptions: OptionSet { - let rawValue: UInt32 - static let ignoreGlobalClipShape = CGSWindowCaptureOptions(rawValue: 1 << 11) - // on a retina display, 1px is spread on 4px, so nominalResolution is 1/4 of bestResolution - static let nominalResolution = CGSWindowCaptureOptions(rawValue: 1 << 9) - static let bestResolution = CGSWindowCaptureOptions(rawValue: 1 << 8) -} - -enum SLPSMode: UInt32 { - case allWindows = 0x100 - case userGenerated = 0x200 - case noWindows = 0x400 -} - -// returns the connection to the WindowServer. This connection ID is required when calling other APIs -// * macOS 10.10+ -@_silgen_name("CGSMainConnectionID") -func CGSMainConnectionID() -> CGSConnectionID - -// returns an array of CGImage of the windows which ID is given as `windowList`. `windowList` is supposed to be an array of IDs but in my test on High Sierra, the function ignores other IDs than the first, and always returns the screenshot of the first window in the array -// * performance: the `HW` in the name seems to imply better performance, and it was observed by some contributors that it seems to be faster (see https://github.com/lwouis/alt-tab-macos/issues/45) than other methods -// * quality: medium -// * minimized windows: yes -// * windows in other spaces: yes -// * offscreen content: no -// * macOS 10.10+ -@_silgen_name("CGSHWCaptureWindowList") -func CGSHWCaptureWindowList(_ cid: CGSConnectionID, _ windowList: inout CGWindowID, _ windowCount: UInt32, _ options: CGSWindowCaptureOptions) -> Unmanaged - -// returns an array of displays (as NSDictionary) -> each having an array of spaces (as NSDictionary) at the "Spaces" key; each having a space ID (as UInt64) at the "id64" key -// * macOS 10.10+ -// /!\ only returns correct values if the user has checked the checkbox in Preferences > Mission Control > "Displays have separate Spaces" -// See this example with 2 screens (1 laptop internal + 1 external): -// * Output with "Displays have separate Spaces" checked: -// [{ -// "Current Space" = { -// ManagedSpaceID = 4; -// id64 = 4; -// type = 0; -// uuid = "6622AC87-2FD2-48E8-934D-F6EB303AC9BA"; -// }; -// "Display Identifier" = "6FBB92D9-84CE-8D20-C114-3B1052DD9529"; -// Spaces = ( -// { -// ManagedSpaceID = 4; -// id64 = 4; -// type = 0; -// uuid = "6622AC87-2FD2-48E8-934D-F6EB303AC9BA"; -// } -// ); -// }, { -// "Current Space" = { -// ManagedSpaceID = 5; -// id64 = 5; -// type = 0; -// uuid = "BE05AFA2-B253-4199-B39E-A8E77CD4851B"; -// }; -// "Display Identifier" = "BB2327F9-3D4F-FD8F-A0EA-B9745A0B818F"; -// Spaces = ( -// { -// ManagedSpaceID = 5; -// id64 = 5; -// type = 0; -// uuid = "BE05AFA2-B253-4199-B39E-A8E77CD4851B"; -// } -// ); -// }] -// * Output with "Displays have separate Spaces" unchecked: -// [{ -// "Current Space" = { -// ManagedSpaceID = 4; -// id64 = 4; -// type = 0; -// uuid = "6622AC87-2FD2-48E8-934D-F6EB303AC9BA"; -// }; -// "Display Identifier" = Main; -// Spaces = ( -// { -// ManagedSpaceID = 4; -// id64 = 4; -// type = 0; -// uuid = "6622AC87-2FD2-48E8-934D-F6EB303AC9BA"; -// } -// ); -// }] -@_silgen_name("CGSCopyManagedDisplaySpaces") -func CGSCopyManagedDisplaySpaces(_ cid: CGSConnectionID) -> CFArray - -struct CGSCopyWindowsOptions: OptionSet { - let rawValue: Int - static let invisible1 = CGSCopyWindowsOptions(rawValue: 1 << 0) - // retrieves windows when their app is assigned to All Spaces, and windows at ScreenSaver level 1000 - static let screenSaverLevel1000 = CGSCopyWindowsOptions(rawValue: 1 << 1) - static let invisible2 = CGSCopyWindowsOptions(rawValue: 1 << 2) - static let unknown1 = CGSCopyWindowsOptions(rawValue: 1 << 3) - static let unknown2 = CGSCopyWindowsOptions(rawValue: 1 << 4) - static let desktopIconWindowLevel2147483603 = CGSCopyWindowsOptions(rawValue: 1 << 5) -} - -struct CGSCopyWindowsTags: OptionSet { - let rawValue: Int - static let level0 = CGSCopyWindowsTags(rawValue: 1 << 0) - static let noTitleMaybePopups = CGSCopyWindowsTags(rawValue: 1 << 1) - static let unknown1 = CGSCopyWindowsTags(rawValue: 1 << 2) - static let mainMenuWindowAndDesktopIconWindow = CGSCopyWindowsTags(rawValue: 1 << 3) - static let unknown2 = CGSCopyWindowsTags(rawValue: 1 << 4) -} - -// returns an array of window IDs (as UInt32) for the space(s) provided as `spaces` -// the elements of the array are ordered by the z-index order of the windows in each space, with some exceptions where spaces mix -// * macOS 10.10+ -@_silgen_name("CGSCopyWindowsWithOptionsAndTags") -func CGSCopyWindowsWithOptionsAndTags(_ cid: CGSConnectionID, _ owner: Int, _ spaces: CFArray, _ options: Int, _ setTags: inout Int, _ clearTags: inout Int) -> CFArray - -// returns the current space ID on the provided display UUID -// * macOS 10.10+ -@_silgen_name("CGSManagedDisplayGetCurrentSpace") -func CGSManagedDisplayGetCurrentSpace(_ cid: CGSConnectionID, _ displayUuid: ScreenUuid) -> CGSSpaceID - -// adds the provided windows to the provided spaces -// * macOS 10.10-12.2 -@_silgen_name("CGSAddWindowsToSpaces") -func CGSAddWindowsToSpaces(_ cid: CGSConnectionID, _ windows: NSArray, _ spaces: NSArray) -> Void - -// remove the provided windows from the provided spaces -// * macOS 10.10-12.2 -@_silgen_name("CGSRemoveWindowsFromSpaces") -func CGSRemoveWindowsFromSpaces(_ cid: CGSConnectionID, _ windows: NSArray, _ spaces: NSArray) -> Void - -// focuses the front process -// * macOS 10.12+ -@_silgen_name("_SLPSSetFrontProcessWithOptions") @discardableResult -func _SLPSSetFrontProcessWithOptions(_ psn: inout ProcessSerialNumber, _ wid: CGWindowID, _ mode: SLPSMode.RawValue) -> CGError - -// sends bytes to the WindowServer -// more context: https://github.com/Hammerspoon/hammerspoon/issues/370#issuecomment-545545468 -// * macOS 10.12+ -@_silgen_name("SLPSPostEventRecordTo") @discardableResult -func SLPSPostEventRecordTo(_ psn: inout ProcessSerialNumber, _ bytes: inout UInt8) -> CGError - -// returns the CGWindowID of the provided AXUIElement -// * macOS 10.10+ -@_silgen_name("_AXUIElementGetWindow") @discardableResult -func _AXUIElementGetWindow(_ axUiElement: AXUIElement, _ wid: inout CGWindowID) -> AXError - -// returns the provided CGWindow property for the provided CGWindowID -// * macOS 10.10+ -@_silgen_name("CGSCopyWindowProperty") @discardableResult -func CGSCopyWindowProperty(_ cid: CGSConnectionID, _ wid: CGWindowID, _ property: CFString, _ value: inout CFTypeRef?) -> CGError - -enum CGSSpaceMask: Int { - case current = 5 - case other = 6 - case all = 7 -} - -// get the CGSSpaceIDs for the given windows (CGWindowIDs) -// * macOS 10.10+ -@_silgen_name("CGSCopySpacesForWindows") -func CGSCopySpacesForWindows(_ cid: CGSConnectionID, _ mask: CGSSpaceMask.RawValue, _ wids: CFArray) -> CFArray - -// returns window level (see definition in CGWindowLevel.h) of provided window -// * macOS 10.10+ -@_silgen_name("CGSGetWindowLevel") @discardableResult -func CGSGetWindowLevel(_ cid: CGSConnectionID, _ wid: CGWindowID, _ level: inout CGWindowLevel) -> CGError - -// returns status of the checkbox in System Preferences > Security & Privacy > Privacy > Screen Recording -// returns 1 if checked or 0 if unchecked; also prompts the user the first time if unchecked -// the return value will be the same during the app lifetime; it will not reflect the actual status of the checkbox -@_silgen_name("SLSRequestScreenCaptureAccess") @discardableResult -func SLSRequestScreenCaptureAccess() -> UInt8 - -// for some reason, these attributes are missing from AXAttributeConstants -let kAXFullscreenAttribute = "AXFullScreen" -let kAXStatusLabelAttribute = "AXStatusLabel" - -// for some reason, these attributes are missing from AXRoleConstants -let kAXDocumentWindowSubrole = "AXDocumentWindow" - -// mission control private notifications -enum MissionControlState: String, CaseIterable { - case showAllWindows = "AXExposeShowAllWindows" - case showFrontWindows = "AXExposeShowFrontWindows" - case showDesktop = "AXExposeShowDesktop" - case inactive = "AXExposeExit" -} - -enum CGSSymbolicHotKey: Int, CaseIterable { - case commandTab = 1 - case commandShiftTab = 2 - case commandKeyAboveTab = 6 // see keyAboveTabDependingOnInputSource -} - -// enables/disables a symbolic hotkeys. These are system shortcuts such as command+tab or Spotlight -// it is possible to find all the existing hotkey IDs by using CGSGetSymbolicHotKeyValue on the first few hundred numbers -// note: the effect of enabling/disabling persists after the app is quit -@_silgen_name("CGSSetSymbolicHotKeyEnabled") @discardableResult -func CGSSetSymbolicHotKeyEnabled(_ hotKey: CGSSymbolicHotKey.RawValue, _ isEnabled: Bool) -> CGError - -func setNativeCommandTabEnabled(_ isEnabled: Bool, _ hotkeys: [CGSSymbolicHotKey] = CGSSymbolicHotKey.allCases) { - for hotkey in hotkeys { - CGSSetSymbolicHotKeyEnabled(hotkey.rawValue, isEnabled) - } -} - -// returns info about a given psn -// * macOS 10.9-10.15 (officially removed in 10.9, but available as a private API still) -@_silgen_name("GetProcessInformation") @discardableResult -func GetProcessInformation(_ psn: inout ProcessSerialNumber, _ info: inout ProcessInfoRec) -> OSErr - -// returns the psn for a given pid -// * macOS 10.9-10.15 (officially removed in 10.9, but available as a private API still) -@_silgen_name("GetProcessForPID") @discardableResult -func GetProcessForPID(_ pid: pid_t, _ psn: inout ProcessSerialNumber) -> OSStatus - -// get the display UUID with the active menubar (other menubar are dimmed) -@_silgen_name("CGSCopyActiveMenuBarDisplayIdentifier") -func CGSCopyActiveMenuBarDisplayIdentifier(_ cid: CGSConnectionID) -> ScreenUuid diff --git a/src/api-wrappers/private-apis/ApplicationServices.HIServices.framework.swift b/src/api-wrappers/private-apis/ApplicationServices.HIServices.framework.swift new file mode 100644 index 00000000..75904be8 --- /dev/null +++ b/src/api-wrappers/private-apis/ApplicationServices.HIServices.framework.swift @@ -0,0 +1,34 @@ +/// for some reason, this attribute is missing from ApplicationServices.HIServices.AXUIElement +/// returns the CGWindowID of the provided AXUIElement +/// * macOS 10.10+ +@_silgen_name("_AXUIElementGetWindow") @discardableResult +func _AXUIElementGetWindow(_ axUiElement: AXUIElement, _ wid: inout CGWindowID) -> AXError + +/// for some reason, this constant is missing from ApplicationServices.HIServices.AXRoleConstants +let kAXDocumentWindowSubrole = "AXDocumentWindow" + +/// for some reason, these constants are missing from ApplicationServices.HIServices.AXAttributeConstants +let kAXFullscreenAttribute = "AXFullScreen" +let kAXStatusLabelAttribute = "AXStatusLabel" + +/// for some reason, these notifications are missing from ApplicationServices.HIServices.AXNotificationConstants +enum MissionControlState: String, CaseIterable { + case showAllWindows = "AXExposeShowAllWindows" + case showFrontWindows = "AXExposeShowFrontWindows" + case showDesktop = "AXExposeShowDesktop" + case inactive = "AXExposeExit" +} + +/// this function from ApplicationServices.HIServices.Processes has been deprecated and removed, with no replacement +/// returns info about a given psn +/// * macOS 10.9-10.15 (officially removed in 10.9, but available as a private API still) +@_silgen_name("GetProcessInformation") @discardableResult +func GetProcessInformation(_ psn: inout ProcessSerialNumber, _ info: inout ProcessInfoRec) -> OSErr + +/// this function from ApplicationServices.HIServices.Processes has been deprecated and removed, with no replacement +/// returns the psn for a given pid +/// * macOS 10.9-10.15 (officially removed in 10.9, but available as a private API still) +@_silgen_name("GetProcessForPID") @discardableResult +func GetProcessForPID(_ pid: pid_t, _ psn: inout ProcessSerialNumber) -> OSStatus + + diff --git a/src/api-wrappers/private-apis/README.md b/src/api-wrappers/private-apis/README.md new file mode 100644 index 00000000..68e77084 --- /dev/null +++ b/src/api-wrappers/private-apis/README.md @@ -0,0 +1,9 @@ +Private APIs are APIs that we can build the app against, but they are not supported or documented by Apple +We can see their names as symbols in the SDK (see https://github.com/lwouis/MacOSX-SDKs) +However their full signature is a best-effort of retro-engineering +Very little information is available about private APIs. I tried to document them as much as possible here + +Some links: +* Webkit repo: https://github.com/WebKit/webkit/blob/master/Source/WebCore/PAL/pal/spi/cg/CoreGraphicsSPI.h +* Alt-tab-macos issue: https://github.com/lwouis/alt-tab-macos/pull/87#issuecomment-558624755 +* Github repo with retro-engineered internals: https://github.com/NUIKit/CGSInternal diff --git a/src/api-wrappers/private-apis/SkyLight.framework.swift b/src/api-wrappers/private-apis/SkyLight.framework.swift new file mode 100644 index 00000000..6245d243 --- /dev/null +++ b/src/api-wrappers/private-apis/SkyLight.framework.swift @@ -0,0 +1,199 @@ +/* + SkyLight is the private framework in charge of interacting with the Window Server + If we link to SkyLight.framework, we can use these private functions + Location: Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/PrivateFrameworks/SkyLight.framework + */ + +let CGS_CONNECTION = CGSMainConnectionID() + +typealias CGSConnectionID = UInt32 +typealias CGSSpaceID = UInt64 + +struct CGSWindowCaptureOptions: OptionSet { + let rawValue: UInt32 + static let ignoreGlobalClipShape = CGSWindowCaptureOptions(rawValue: 1 << 11) + // on a retina display, 1px is spread on 4px, so nominalResolution is 1/4 of bestResolution + static let nominalResolution = CGSWindowCaptureOptions(rawValue: 1 << 9) + static let bestResolution = CGSWindowCaptureOptions(rawValue: 1 << 8) +} + +/// returns the connection to the WindowServer. This connection ID is required when calling other APIs +/// * macOS 10.10+ +@_silgen_name("CGSMainConnectionID") +func CGSMainConnectionID() -> CGSConnectionID + +/// returns an array of CGImage of the windows which ID is given as `windowList`. `windowList` is supposed to be an array of IDs but in my test on High Sierra, the function ignores other IDs than the first, and always returns the screenshot of the first window in the array +/// * performance: the `HW` in the name seems to imply better performance, and it was observed by some contributors that it seems to be faster (see https://github.com/lwouis/alt-tab-macos/issues/45) than other methods +/// * quality: medium +/// * minimized windows: yes +/// * windows in other spaces: yes +/// * offscreen content: no +/// * macOS 10.10+ +@_silgen_name("CGSHWCaptureWindowList") +func CGSHWCaptureWindowList(_ cid: CGSConnectionID, _ windowList: inout CGWindowID, _ windowCount: UInt32, _ options: CGSWindowCaptureOptions) -> Unmanaged + +/// returns an array of displays (as NSDictionary) -> each having an array of spaces (as NSDictionary) at the "Spaces" key; each having a space ID (as UInt64) at the "id64" key +/// * macOS 10.10+ +/// /!\ only returns correct values if the user has checked the checkbox in Preferences > Mission Control > "Displays have separate Spaces" +/// See this example with 2 screens (1 laptop internal + 1 external): +/// * Output with "Displays have separate Spaces" checked: +/// [{ +/// "Current Space" = { +/// ManagedSpaceID = 4; +/// id64 = 4; +/// type = 0; +/// uuid = "6622AC87-2FD2-48E8-934D-F6EB303AC9BA"; +/// }; +/// "Display Identifier" = "6FBB92D9-84CE-8D20-C114-3B1052DD9529"; +/// Spaces = ( +/// { +/// ManagedSpaceID = 4; +/// id64 = 4; +/// type = 0; +/// uuid = "6622AC87-2FD2-48E8-934D-F6EB303AC9BA"; +/// } +/// ); +/// }, { +/// "Current Space" = { +/// ManagedSpaceID = 5; +/// id64 = 5; +/// type = 0; +/// uuid = "BE05AFA2-B253-4199-B39E-A8E77CD4851B"; +/// }; +/// "Display Identifier" = "BB2327F9-3D4F-FD8F-A0EA-B9745A0B818F"; +/// Spaces = ( +/// { +/// ManagedSpaceID = 5; +/// id64 = 5; +/// type = 0; +/// uuid = "BE05AFA2-B253-4199-B39E-A8E77CD4851B"; +/// } +/// ); +/// }] +/// * Output with "Displays have separate Spaces" unchecked: +/// [{ +/// "Current Space" = { +/// ManagedSpaceID = 4; +/// id64 = 4; +/// type = 0; +/// uuid = "6622AC87-2FD2-48E8-934D-F6EB303AC9BA"; +/// }; +/// "Display Identifier" = Main; +/// Spaces = ( +/// { +/// ManagedSpaceID = 4; +/// id64 = 4; +/// type = 0; +/// uuid = "6622AC87-2FD2-48E8-934D-F6EB303AC9BA"; +/// } +/// ); +/// }] +@_silgen_name("CGSCopyManagedDisplaySpaces") +func CGSCopyManagedDisplaySpaces(_ cid: CGSConnectionID) -> CFArray + +struct CGSCopyWindowsOptions: OptionSet { + let rawValue: Int + static let invisible1 = CGSCopyWindowsOptions(rawValue: 1 << 0) + // retrieves windows when their app is assigned to All Spaces, and windows at ScreenSaver level 1000 + static let screenSaverLevel1000 = CGSCopyWindowsOptions(rawValue: 1 << 1) + static let invisible2 = CGSCopyWindowsOptions(rawValue: 1 << 2) + static let unknown1 = CGSCopyWindowsOptions(rawValue: 1 << 3) + static let unknown2 = CGSCopyWindowsOptions(rawValue: 1 << 4) + static let desktopIconWindowLevel2147483603 = CGSCopyWindowsOptions(rawValue: 1 << 5) +} + +struct CGSCopyWindowsTags: OptionSet { + let rawValue: Int + static let level0 = CGSCopyWindowsTags(rawValue: 1 << 0) + static let noTitleMaybePopups = CGSCopyWindowsTags(rawValue: 1 << 1) + static let unknown1 = CGSCopyWindowsTags(rawValue: 1 << 2) + static let mainMenuWindowAndDesktopIconWindow = CGSCopyWindowsTags(rawValue: 1 << 3) + static let unknown2 = CGSCopyWindowsTags(rawValue: 1 << 4) +} + +/// returns an array of window IDs (as UInt32) for the space(s) provided as `spaces` +/// the elements of the array are ordered by the z-index order of the windows in each space, with some exceptions where spaces mix +/// * macOS 10.10+ +@_silgen_name("CGSCopyWindowsWithOptionsAndTags") +func CGSCopyWindowsWithOptionsAndTags(_ cid: CGSConnectionID, _ owner: Int, _ spaces: CFArray, _ options: Int, _ setTags: inout Int, _ clearTags: inout Int) -> CFArray + +/// returns the current space ID on the provided display UUID +/// * macOS 10.10+ +@_silgen_name("CGSManagedDisplayGetCurrentSpace") +func CGSManagedDisplayGetCurrentSpace(_ cid: CGSConnectionID, _ displayUuid: ScreenUuid) -> CGSSpaceID + +/// adds the provided windows to the provided spaces +/// * macOS 10.10-12.2 +@_silgen_name("CGSAddWindowsToSpaces") +func CGSAddWindowsToSpaces(_ cid: CGSConnectionID, _ windows: NSArray, _ spaces: NSArray) -> Void + +/// remove the provided windows from the provided spaces +/// * macOS 10.10-12.2 +@_silgen_name("CGSRemoveWindowsFromSpaces") +func CGSRemoveWindowsFromSpaces(_ cid: CGSConnectionID, _ windows: NSArray, _ spaces: NSArray) -> Void + +/// returns the provided CGWindow property for the provided CGWindowID +/// * macOS 10.10+ +@_silgen_name("CGSCopyWindowProperty") @discardableResult +func CGSCopyWindowProperty(_ cid: CGSConnectionID, _ wid: CGWindowID, _ property: CFString, _ value: inout CFTypeRef?) -> CGError + +enum CGSSpaceMask: Int { + case current = 5 + case other = 6 + case all = 7 +} + +/// get the CGSSpaceIDs for the given windows (CGWindowIDs) +/// * macOS 10.10+ +@_silgen_name("CGSCopySpacesForWindows") +func CGSCopySpacesForWindows(_ cid: CGSConnectionID, _ mask: CGSSpaceMask.RawValue, _ wids: CFArray) -> CFArray + +/// returns window level (see definition in CGWindowLevel.h) of provided window +/// * macOS 10.10+ +@_silgen_name("CGSGetWindowLevel") @discardableResult +func CGSGetWindowLevel(_ cid: CGSConnectionID, _ wid: CGWindowID, _ level: inout CGWindowLevel) -> CGError + +/// returns status of the checkbox in System Preferences > Security & Privacy > Privacy > Screen Recording +/// returns 1 if checked or 0 if unchecked; also prompts the user the first time if unchecked +/// the return value will be the same during the app lifetime; it will not reflect the actual status of the checkbox +@_silgen_name("SLSRequestScreenCaptureAccess") @discardableResult +func SLSRequestScreenCaptureAccess() -> UInt8 + +enum CGSSymbolicHotKey: Int, CaseIterable { + case commandTab = 1 + case commandShiftTab = 2 + case commandKeyAboveTab = 6 // see keyAboveTabDependingOnInputSource +} + +/// enables/disables a symbolic hotkeys. These are system shortcuts such as command+tab or Spotlight +/// it is possible to find all the existing hotkey IDs by using CGSGetSymbolicHotKeyValue on the first few hundred numbers +/// note: the effect of enabling/disabling persists after the app is quit +@_silgen_name("CGSSetSymbolicHotKeyEnabled") @discardableResult +func CGSSetSymbolicHotKeyEnabled(_ hotKey: CGSSymbolicHotKey.RawValue, _ isEnabled: Bool) -> CGError + +func setNativeCommandTabEnabled(_ isEnabled: Bool, _ hotkeys: [CGSSymbolicHotKey] = CGSSymbolicHotKey.allCases) { + for hotkey in hotkeys { + CGSSetSymbolicHotKeyEnabled(hotkey.rawValue, isEnabled) + } +} + +/// get the display UUID with the active menubar (other menubar are dimmed) +@_silgen_name("CGSCopyActiveMenuBarDisplayIdentifier") +func CGSCopyActiveMenuBarDisplayIdentifier(_ cid: CGSConnectionID) -> ScreenUuid + +enum SLPSMode: UInt32 { + case allWindows = 0x100 + case userGenerated = 0x200 + case noWindows = 0x400 +} + +/// focuses the front process +/// * macOS 10.12+ +@_silgen_name("_SLPSSetFrontProcessWithOptions") @discardableResult +func _SLPSSetFrontProcessWithOptions(_ psn: inout ProcessSerialNumber, _ wid: CGWindowID, _ mode: SLPSMode.RawValue) -> CGError + +/// sends bytes to the WindowServer +/// more context: https://github.com/Hammerspoon/hammerspoon/issues/370#issuecomment-545545468 +/// * macOS 10.12+ +@_silgen_name("SLPSPostEventRecordTo") @discardableResult +func SLPSPostEventRecordTo(_ psn: inout ProcessSerialNumber, _ bytes: inout UInt8) -> CGError diff --git a/src/experimentations/PrivateApis.swift b/src/experimentations/PrivateApis.swift index 3d9dc424..67acb3e9 100644 --- a/src/experimentations/PrivateApis.swift +++ b/src/experimentations/PrivateApis.swift @@ -207,7 +207,7 @@ func psnEqual(_ psn1: ProcessSerialNumber, _ psn2: ProcessSerialNumber) -> Bool func windowIdToPsn(_ wid: CGWindowID) -> ProcessSerialNumber { var elementConnection = UInt32(0) - CGSGetWindowOwner(cgsMainConnectionId, wid, &elementConnection) + CGSGetWindowOwner(CGS_CONNECTION, wid, &elementConnection) var psn = ProcessSerialNumber() CGSGetConnectionPSN(elementConnection, &psn) return psn diff --git a/src/logic/Applications.swift b/src/logic/Applications.swift index 896e6975..455eb629 100644 --- a/src/logic/Applications.swift +++ b/src/logic/Applications.swift @@ -38,9 +38,9 @@ class Applications { let windowsOnlyOnOtherSpaces = Array(Set(windowsOnOtherSpaces).subtracting(windowsOnCurrentSpace)) if windowsOnlyOnOtherSpaces.count > 0 { // on initial launch, we use private APIs to bring windows from other spaces into the current space, observe them, then remove them from the current space - CGSAddWindowsToSpaces(cgsMainConnectionId, windowsOnlyOnOtherSpaces as NSArray, [Spaces.currentSpaceId]) + CGSAddWindowsToSpaces(CGS_CONNECTION, windowsOnlyOnOtherSpaces as NSArray, [Spaces.currentSpaceId]) Applications.manuallyUpdateWindowsFor2s() - CGSRemoveWindowsFromSpaces(cgsMainConnectionId, windowsOnlyOnOtherSpaces as NSArray, [Spaces.currentSpaceId]) + CGSRemoveWindowsFromSpaces(CGS_CONNECTION, windowsOnlyOnOtherSpaces as NSArray, [Spaces.currentSpaceId]) } } else { Applications.manuallyUpdateWindows() diff --git a/src/logic/NSScreen.swift b/src/logic/NSScreen.swift index f4107ebb..87956fea 100644 --- a/src/logic/NSScreen.swift +++ b/src/logic/NSScreen.swift @@ -71,7 +71,7 @@ extension NSScreen { // there is only 1 active menubar. Other screens will show their menubar dimmed static func withActiveMenubar() -> NSScreen? { - return NSScreen.screens.first { CGSCopyActiveMenuBarDisplayIdentifier(cgsMainConnectionId) == $0.uuid() } + return NSScreen.screens.first { CGSCopyActiveMenuBarDisplayIdentifier(CGS_CONNECTION) == $0.uuid() } } static func withMouse() -> NSScreen? { diff --git a/src/logic/Spaces.swift b/src/logic/Spaces.swift index d303ba0c..b156cb56 100644 --- a/src/logic/Spaces.swift +++ b/src/logic/Spaces.swift @@ -22,7 +22,7 @@ class Spaces { if includeInvisible { options = [options, .invisible1, .invisible2] } - return CGSCopyWindowsWithOptionsAndTags(cgsMainConnectionId, 0, spaceIds as CFArray, options.rawValue, &set_tags, &clear_tags) as! [CGWindowID] + return CGSCopyWindowsWithOptionsAndTags(CGS_CONNECTION, 0, spaceIds as CFArray, options.rawValue, &set_tags, &clear_tags) as! [CGWindowID] } static func refresh() { @@ -34,7 +34,7 @@ class Spaces { // it seems that in some rare scenarios, some of these values are nil; we wrap to avoid crashing if let mainScreen = NSScreen.main, let uuid = mainScreen.uuid() { - currentSpaceId = CGSManagedDisplayGetCurrentSpace(cgsMainConnectionId, uuid) + currentSpaceId = CGSManagedDisplayGetCurrentSpace(CGS_CONNECTION, uuid) } currentSpaceIndex = idsAndIndexes.first { (spaceId: CGSSpaceID, _) -> Bool in spaceId == currentSpaceId @@ -46,7 +46,7 @@ class Spaces { screenSpacesMap.removeAll() visibleSpaces.removeAll() var spaceIndex = SpaceIndex(1) - (CGSCopyManagedDisplaySpaces(cgsMainConnectionId) as! [NSDictionary]).forEach { (screen: NSDictionary) in + (CGSCopyManagedDisplaySpaces(CGS_CONNECTION) as! [NSDictionary]).forEach { (screen: NSDictionary) in var display = screen["Display Identifier"] as! ScreenUuid if display as String == "Main", let mainUuid = NSScreen.main?.uuid() { display = mainUuid diff --git a/src/ui/App.swift b/src/ui/App.swift index 387b8e7f..c9c90efe 100644 --- a/src/ui/App.swift +++ b/src/ui/App.swift @@ -4,13 +4,10 @@ import LetsMove import ShortcutRecorder import AppCenterCrashes -let cgsMainConnectionId = CGSMainConnectionID() - -// periphery:ignore -var activity = ProcessInfo.processInfo.beginActivity(options: .userInitiatedAllowingIdleSystemSleep, - reason: "Prevent App Nap to preserve responsiveness") - class App: AppCenterApplication { + /// periphery:ignore + static let activity = ProcessInfo.processInfo.beginActivity(options: .userInitiatedAllowingIdleSystemSleep, + reason: "Prevent App Nap to preserve responsiveness") static let name = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as! String static let id = Bundle.main.object(forInfoDictionaryKey: "CFBundleIdentifier") as! String static let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String