Ariver
2026-06-11 0045898e8cd7b2d8972bb24c8ac27e514bdd8c70
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
import AppKit
import CoreGraphics
import Darwin
import Foundation
import AlignerCore
 
final class SkyLightSpaceEnumerator: SpaceEnumeratorProtocol {
    enum SkyLightError: Error, CustomStringConvertible {
        case frameworkUnavailable
        case symbolUnavailable(String)
        case managedDisplaySpacesUnavailable
 
        var description: String {
            switch self {
            case .frameworkUnavailable:
                return "SkyLight framework could not be opened."
            case .symbolUnavailable(let name):
                return "SkyLight symbol unavailable: \(name)."
            case .managedDisplaySpacesUnavailable:
                return "CGSCopyManagedDisplaySpaces returned no usable data."
            }
        }
    }
 
    private typealias CGSMainConnectionIDFunction = @convention(c) () -> UInt32
    private typealias CGSCopyManagedDisplaySpacesFunction = @convention(c) (UInt32) -> Unmanaged<CFArray>?
    private typealias CGSCopySpacesForWindowsFunction = @convention(c) (UInt32, UInt32, CFArray) -> Unmanaged<CFArray>?
    private typealias CGSCopyWindowsWithOptionsAndTagsFunction = @convention(c) (
        UInt32,
        Int,
        CFArray,
        Int,
        UnsafeMutablePointer<Int>,
        UnsafeMutablePointer<Int>
    ) -> Unmanaged<CFArray>?
 
    private let handle: UnsafeMutableRawPointer?
    private let mainConnectionID: CGSMainConnectionIDFunction
    private let copyManagedDisplaySpaces: CGSCopyManagedDisplaySpacesFunction
    private let copySpacesForWindows: CGSCopySpacesForWindowsFunction?
    private let copyWindowsWithOptionsAndTags: CGSCopyWindowsWithOptionsAndTagsFunction?
 
    init() throws {
        guard let handle = dlopen("/System/Library/PrivateFrameworks/SkyLight.framework/SkyLight", RTLD_LAZY) else {
            throw SkyLightError.frameworkUnavailable
        }
 
        self.handle = handle
        self.mainConnectionID = try Self.symbol("CGSMainConnectionID", in: handle)
        self.copyManagedDisplaySpaces = try Self.symbol("CGSCopyManagedDisplaySpaces", in: handle)
        self.copySpacesForWindows = try? Self.symbol("CGSCopySpacesForWindows", in: handle)
        self.copyWindowsWithOptionsAndTags = try? Self.symbol("CGSCopyWindowsWithOptionsAndTags", in: handle)
    }
 
    deinit {
        if let handle {
            dlclose(handle)
        }
    }
 
    func displays() throws -> [AlignerDisplay] {
        let displayRecords = try managedDisplaySpaceRecords()
 
        let physicalDisplayUUIDs = Self.physicalDisplayUUIDs()
        let records = displayRecords.flatMap { displayRecord -> [SpaceEnumerationRecord] in
            let displayUUID = stringValue(displayRecord["Display Identifier"])
            let spaceRecords = displayRecord["Spaces"] as? [[String: Any]] ?? []
 
            return spaceRecords.compactMap { spaceRecord in
                guard let id = uint64Value(spaceRecord["id64"] ?? spaceRecord["id"]) else {
                    return nil
                }
 
                return SpaceEnumerationRecord(
                    id: id,
                    cgsType: intValue(spaceRecord["type"]) ?? -1,
                    displayUUID: displayUUID
                )
            }
        }
 
        return SpaceEnumerationPolicy.normalizedDisplays(
            from: records,
            physicalDisplayUUIDs: physicalDisplayUUIDs
        )
    }
 
    func currentOverlayScreenSpaceStatesByDisplayUUID() throws -> [String: OverlayScreenSpaceState] {
        let displayRecords = try managedDisplaySpaceRecords()
        var result: [String: OverlayScreenSpaceState] = [:]
 
        for displayRecord in displayRecords {
            let displayUUID = stringValue(displayRecord["Display Identifier"])
            guard !displayUUID.isEmpty,
                  let currentSpace = displayRecord["Current Space"] as? [String: Any]
            else {
                continue
            }
 
            let isFullscreen = SpaceEnumerationPolicy.spaceType(fromCGSType: intValue(currentSpace["type"]) ?? -1) == .fullscreen
            result[displayUUID] = OverlayScreenSpaceState(
                isFullscreenSpace: isFullscreen,
                isSplitViewSpace: Self.isSplitViewSpace(currentSpace)
            )
        }
 
        return result
    }
 
    func currentSpaceIDs() throws -> Set<UInt64> {
        let displayRecords = try managedDisplaySpaceRecords()
        var result = Set<UInt64>()
 
        for displayRecord in displayRecords {
            guard let currentSpace = displayRecord["Current Space"] as? [String: Any],
                  let id = uint64Value(currentSpace["id64"] ?? currentSpace["id"])
            else {
                continue
            }
 
            result.insert(id)
        }
 
        return result
    }
 
    func spaceIDsByWindowID(windowIDs: [UInt32]) -> [UInt32: [UInt64]] {
        let directSpaceIDsByWindowID = directSpaceIDsByWindowID(windowIDs: windowIDs)
        guard let orderedSpaceIDs = try? allManagedSpaceIDs(),
              !orderedSpaceIDs.isEmpty
        else {
            return directSpaceIDsByWindowID
        }
 
        let windowIDsBySpaceID = windowIDsBySpaceID(spaceIDs: orderedSpaceIDs)
        guard !windowIDsBySpaceID.isEmpty else {
            return directSpaceIDsByWindowID
        }
 
        return WindowSpaceMappingPolicy.mergedSpaceIDsByWindowID(
            requestedWindowIDs: windowIDs,
            directSpaceIDsByWindowID: directSpaceIDsByWindowID,
            windowIDsBySpaceID: windowIDsBySpaceID,
            orderedSpaceIDs: orderedSpaceIDs
        )
    }
 
    private func directSpaceIDsByWindowID(windowIDs: [UInt32]) -> [UInt32: [UInt64]] {
        guard let copySpacesForWindows else { return [:] }
 
        let connectionID = mainConnectionID()
        var result: [UInt32: [UInt64]] = [:]
 
        for windowID in windowIDs {
            let windowIDArray = [NSNumber(value: windowID)] as CFArray
            guard let unmanagedSpaces = copySpacesForWindows(connectionID, 0x7, windowIDArray) else {
                continue
            }
 
            let spaces = (unmanagedSpaces.takeRetainedValue() as? [Any] ?? [])
                .compactMap { item -> UInt64? in
                    uint64Value(item)
                }
 
            if !spaces.isEmpty {
                result[windowID] = spaces
            }
        }
 
        return result
    }
 
    private func allManagedSpaceIDs() throws -> [UInt64] {
        try managedDisplaySpaceRecords()
            .flatMap { displayRecord -> [UInt64] in
                let spaceRecords = displayRecord["Spaces"] as? [[String: Any]] ?? []
                return spaceRecords.compactMap { spaceRecord in
                    uint64Value(spaceRecord["id64"] ?? spaceRecord["id"])
                }
            }
    }
 
    private func windowIDsBySpaceID(spaceIDs: [UInt64]) -> [UInt64: [UInt32]] {
        guard let copyWindowsWithOptionsAndTags else { return [:] }
 
        let connectionID = mainConnectionID()
        let options = Self.copyWindowsOptionIncludeInvisible
        var result: [UInt64: [UInt32]] = [:]
 
        for spaceID in spaceIDs {
            let spaceIDArray = [NSNumber(value: spaceID)] as CFArray
            var setTags = 0
            var clearTags = 0
            guard let unmanagedWindows = copyWindowsWithOptionsAndTags(
                connectionID,
                0,
                spaceIDArray,
                options,
                &setTags,
                &clearTags
            ) else {
                continue
            }
 
            let windowIDs = (unmanagedWindows.takeRetainedValue() as? [Any] ?? [])
                .compactMap { item -> UInt32? in
                    uint32Value(item)
                }
 
            if !windowIDs.isEmpty {
                result[spaceID] = windowIDs
            }
        }
 
        return result
    }
 
    private static let copyWindowsOptionIncludeInvisible = (1 << 0) | (1 << 1) | (1 << 2)
 
    private static func symbol<T>(_ name: String, in handle: UnsafeMutableRawPointer) throws -> T {
        guard let rawSymbol = dlsym(handle, name) else {
            throw SkyLightError.symbolUnavailable(name)
        }
 
        return unsafeBitCast(rawSymbol, to: T.self)
    }
 
    private func managedDisplaySpaceRecords() throws -> [[String: Any]] {
        let connectionID = mainConnectionID()
        guard
            let unmanagedDisplays = copyManagedDisplaySpaces(connectionID),
            let displayRecords = unmanagedDisplays.takeRetainedValue() as? [[String: Any]]
        else {
            throw SkyLightError.managedDisplaySpacesUnavailable
        }
 
        return displayRecords
    }
 
    private static func isSplitViewSpace(_ spaceRecord: [String: Any]) -> Bool {
        guard let tileLayoutManager = spaceRecord["TileLayoutManager"] as? [String: Any] else {
            return false
        }
 
        if let tileSpaces = tileLayoutManager["TileSpaces"] as? [Any] {
            return tileSpaces.count > 1
        }
 
        return true
    }
 
    private static func physicalDisplayUUIDs() -> Set<String> {
        Set(
            NSScreen.screens.compactMap { screen in
                guard
                    let number = screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber,
                    let unmanagedUUID = CGDisplayCreateUUIDFromDisplayID(CGDirectDisplayID(number.uint32Value))
                else {
                    return nil
                }
 
                let uuid = unmanagedUUID.takeRetainedValue()
                return CFUUIDCreateString(nil, uuid) as String?
            }
        )
    }
}
 
private func stringValue(_ value: Any?) -> String {
    value as? String ?? ""
}
 
private func intValue(_ value: Any?) -> Int? {
    switch value {
    case let number as NSNumber:
        return number.intValue
    case let int as Int:
        return int
    default:
        return nil
    }
}
 
private func uint64Value(_ value: Any?) -> UInt64? {
    switch value {
    case let number as NSNumber:
        return number.uint64Value
    case let uint64 as UInt64:
        return uint64
    case let uint as UInt:
        return UInt64(uint)
    case let int as Int where int >= 0:
        return UInt64(int)
    default:
        return nil
    }
}
 
private func uint32Value(_ value: Any?) -> UInt32? {
    switch value {
    case let number as NSNumber:
        return number.uint32Value
    case let uint32 as UInt32:
        return uint32
    case let uint as UInt where uint <= UInt(UInt32.max):
        return UInt32(uint)
    case let int as Int where int >= 0 && int <= Int(UInt32.max):
        return UInt32(int)
    default:
        return nil
    }
}