Open History to see the last commit
1import AppKit
2import CoreGraphics
3import ExpeditionCore
4
5@MainActor
6final class WindowProvider {
7 private(set) var frontWindowID: UInt32?
8 private(set) var keyboardWindowID: UInt32?
9 /// Screenshot's selection/dimming windows and its unbundled screencapture
10 /// helper are recording UI, never terrain or opaque desktop occluders.
11 static func isScreenRecorder(bundle: String?, owner: String?) -> Bool {
12 ["com.apple.screencaptureui", "com.apple.screenshot.launcher"].contains(bundle ?? "") ||
13 (bundle == nil && owner == "screencapture")
14 }
15 /// Accessibility Keyboard keeps screen-sized highlight/capture backdrops at
16 /// very high levels. Their WindowServer alpha is 1 despite transparent pixels.
17 /// Keep the real keyboard panel as an occluder; exclude only these backdrops.
18 static func isKeyboardBackdrop(bundle: String?, layer: Int, frame: CGRect, display: CGRect) -> Bool {
19 ["com.apple.inputmethod.AssistiveControl", "com.apple.KeyboardViewer"].contains(bundle ?? "") &&
20 layer >= Int(CGWindowLevelForKey(.screenSaverWindow)) && frame.insetBy(dx: -2, dy: -2).contains(display)
21 }
22 static func canClimbWindow(bundle: String?, layer: Int, frame: CGRect) -> Bool {
23 let keyboard = ["com.apple.inputmethod.AssistiveControl", "com.apple.KeyboardViewer"].contains(bundle ?? "")
24 return frame.width >= 80 && frame.height >= 60 &&
25 (layer == 0 || (keyboard && layer > 0 && layer < Int(CGWindowLevelForKey(.screenSaverWindow))))
26 }
27
28 /// Solid app UI participates in terrain; only the transparent renderer,
29 /// character hit area, invisible keyboard target and prompt stay excluded.
30 static func isAppTerrainWindow(_ window: NSWindow) -> Bool {
31 window.styleMask.contains(.titled) && !window.ignoresMouseEvents
32 && window.frame.width >= 80 && window.frame.height >= 60
33 }
34
35 /// Conservatively hide in a full-screen Space. A normally zoomed window occupies only
36 /// visibleFrame and leaves the menu bar/Dock strip, so it does not trigger this guard.
37 func isSupportedDesktop(on screen: NSScreen) -> Bool {
38 guard let front = NSWorkspace.shared.frontmostApplication,
39 front.processIdentifier != ProcessInfo.processInfo.processIdentifier,
40 let primary = NSScreen.screens.first,
41 let records = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] else { return true }
42 if Self.isScreenRecorder(bundle: front.bundleIdentifier, owner: front.localizedName) { return true }
43 for record in records {
44 guard (record[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value == front.processIdentifier,
45 (record[kCGWindowLayer as String] as? NSNumber)?.intValue == 0,
46 let dict = record[kCGWindowBounds as String] as? [String: Any],
47 let rect = CGRect(dictionaryRepresentation: dict as CFDictionary) else { continue }
48 let world = DesktopCoordinates.sceneRect(.init(x: rect.minX, y: rect.minY, width: rect.width, height: rect.height), primaryTop: primary.frame.maxY, displayOrigin: .init(x: screen.frame.minX, y: screen.frame.minY))
49 return !DesktopCoordinates.isFullScreen(window: world, display: .init(x: 0, y: 0, width: screen.frame.width, height: screen.frame.height))
50 }
51 return true
52 }
53
54 /// Reads geometry only: no window titles, images, Accessibility calls, or permission prompts.
55 func snapshot(on screen: NSScreen) -> TerrainSnapshot? {
56 guard let primary = NSScreen.screens.first,
57 let records = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] else { return nil }
58 let ownPID = ProcessInfo.processInfo.processIdentifier
59 let viewport = screen.visibleFrame.offsetBy(dx: -screen.frame.minX, dy: -screen.frame.minY)
60 let worldViewport = WorldRect(x: viewport.minX, y: viewport.minY + 2, width: viewport.width, height: max(0, viewport.height - 2))
61 var windows: [DesktopWindow] = []
62 frontWindowID = nil; keyboardWindowID = nil
63 let frontPID = NSWorkspace.shared.frontmostApplication?.processIdentifier
64 var fallbackWindowID: UInt32?
65 for record in records {
66 guard let id = (record[kCGWindowNumber as String] as? NSNumber)?.uint32Value,
67 let pid = (record[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value,
68 let layer = (record[kCGWindowLayer as String] as? NSNumber)?.intValue, layer >= 0,
69 (record[kCGWindowAlpha as String] as? NSNumber)?.doubleValue ?? 1 > 0.01,
70 let dictionary = record[kCGWindowBounds as String] as? [String: Any],
71 let frame = CGRect(dictionaryRepresentation: dictionary as CFDictionary), frame.width > 1, frame.height > 1 else { continue }
72 let converted = DesktopCoordinates.sceneRect(
73 WorldRect(x: frame.minX, y: frame.minY, width: frame.width, height: frame.height),
74 primaryTop: primary.frame.maxY,
75 displayOrigin: .init(x: screen.frame.minX, y: screen.frame.minY)
76 )
77 guard converted.intersects(worldViewport) else { continue }
78 let bundle = NSRunningApplication(processIdentifier: pid)?.bundleIdentifier
79 let ownWindow = pid == ownPID ? NSApp.windows.first(where: { $0.windowNumber == Int(id) }) : nil
80 if pid == ownPID {
81 guard let ownWindow, Self.isAppTerrainWindow(ownWindow) else { continue }
82 } else if bundle == Bundle.main.bundleIdentifier { continue }
83 if Self.isScreenRecorder(bundle: bundle, owner: record[kCGWindowOwnerName as String] as? String) { continue }
84 if Self.isKeyboardBackdrop(bundle: bundle, layer: layer,
85 frame: CGRect(x: converted.minX, y: converted.minY, width: converted.width, height: converted.height),
86 display: CGRect(origin: .zero, size: screen.frame.size)) { continue }
87 #if DEBUG
88 if ProcessInfo.processInfo.arguments.contains("--fixture-terrain"), pid != ownPID, bundle != "com.jerry.terrainfixture" { continue }
89 #endif
90 let systemOwner = bundle == "com.apple.dock" || bundle == "com.apple.WindowManager" || bundle == "com.apple.controlcenter" || bundle == "com.apple.notificationcenterui"
91 // Shell helper windows often have transparent, screen-sized backing rectangles.
92 guard !systemOwner else { continue }
93 let climbable = ownWindow != nil || Self.canClimbWindow(bundle: bundle, layer: layer, frame: frame)
94 // WindowServer does not publish the outline radius. Match our own
95 // notebook outline exactly and estimate standard AppKit windows by OS.
96 let radius: Double
97 if ownWindow is NotebookWindow { radius = Double(NotebookTheme.cornerRadius) }
98 else if #available(macOS 26.0, *) { radius = 16 }
99 else { radius = AbseilRope.cornerRadius }
100 windows.append(DesktopWindow(id: id, frame: converted, canClimb: climbable, cornerRadius: radius))
101 if climbable {
102 if ["com.apple.inputmethod.AssistiveControl", "com.apple.KeyboardViewer"].contains(bundle ?? "") {
103 if keyboardWindowID == nil { keyboardWindowID = id }
104 } else {
105 if fallbackWindowID == nil { fallbackWindowID = id }
106 if frontWindowID == nil && pid == frontPID { frontWindowID = id }
107 }
108 }
109 }
110 if frontWindowID == nil { frontWindowID = fallbackWindowID }
111 return TerrainSnapshot(windows: windows, viewport: worldViewport)
112 }
113}