import AppKit import ApplicationServices import CoreGraphics // WindowConstraintService keeps windows above the strip (decision D6, spec // 7.10). The service reacts to move and resize events. The service resizes a // window so the window bottom sits at the strip top edge. // // NOTE: These AX reads and writes run on the main actor. The spec wants AX // calls off the main thread. A later change can move the AX work to the serial // AX queue. The debounce and the loop protection stay the same. @MainActor final class WindowConstraintService { private let store: WindowStore private let cache: AXElementCache private let settings: Settings // stripFrame is the strip frame in Cocoa global coordinates. The // integration sets this value. limitY is the strip top edge. var stripFrame: CGRect = .zero private var limitY: CGFloat { stripFrame.maxY } // debounceWork holds the pending resize work per window. private var debounceWork: [CGWindowID: DispatchWorkItem] = [:] // ignoreUntil holds the loop-protection deadline per window. private var ignoreUntil: [CGWindowID: Date] = [:] // blacklist holds the applications that do not accept the new size. private var blacklist: Set = [] init(store: WindowStore, cache: AXElementCache, settings: Settings) { self.store = store self.cache = cache self.settings = settings } // handleMovedOrResized schedules a constraint check after a move or a // resize event. func handleMovedOrResized(windowID: CGWindowID) { schedule(windowID) } // constrainOnCreate schedules a constraint check for a new window. func constrainOnCreate(windowID: CGWindowID) { schedule(windowID) } // schedule debounces the check. The service waits 150 ms after the last // event of a window. private func schedule(_ id: CGWindowID) { debounceWork[id]?.cancel() let work = DispatchWorkItem { [weak self] in self?.constrainNow(id) } debounceWork[id] = work DispatchQueue.main.asyncAfter(deadline: .now() + 0.15, execute: work) } // constrainNow runs the constraint check for one window. private func constrainNow(_ id: CGWindowID) { debounceWork[id] = nil // Loop protection: ignore the window after an own resize. if let until = ignoreUntil[id], until > Date() { return } // Do not resize during a drag. Check the window again after the drag. if NSEvent.pressedMouseButtons != 0 { schedule(id) return } // Skip rules (spec 7.10, step 1). guard settings.constrainWindows else { return } guard let info = findWindow(id) else { return } if settings.isExcluded(info.bundleID) { return } if info.isFullScreen { return } if blacklist.contains(info.pid) { return } if StageManagerState.isOn { return } guard let element = cache.element(for: id) else { return } guard subrole(element) == (kAXStandardWindowSubrole as String) else { return } guard isSizeSettable(element) else { return } guard let currentFrame = axFrame(element) else { return } let primaryHeight = NSScreen.screens.first?.frame.height ?? 0 let cocoa = Geometry.axToCocoa(currentFrame, primaryHeight: primaryHeight) // Skip if the window is not on the strip screen (spec 7.10, step 2). guard isOnStripScreen(cocoa) else { return } // The window bottom must be below the limit (spec 7.10, step 3). guard cocoa.minY < limitY else { return } // The user moved the window down on purpose. Do nothing. if ConstraintMath.isIntentionalMoveDown(windowTopCocoa: cocoa.maxY, limitY: limitY) { return } guard let newHeight = ConstraintMath.newHeight(windowCocoa: cocoa, limitY: limitY), newHeight > 0 else { return } let requested = CGSize(width: cocoa.width, height: newHeight) // Set the loop-protection deadline before the resize. ignoreUntil[id] = Date().addingTimeInterval(0.3) setSize(element, requested) // Check the size after the set. Blacklist the application if the size // is wrong. if let after = axFrame(element), abs(after.height - requested.height) > 2 { blacklist.insert(info.pid) Log.constraint.warning("app \(info.pid) did not accept the new size; blacklist for this session") } } // isOnStripScreen returns true if the window is on the strip screen. private func isOnStripScreen(_ cocoa: CGRect) -> Bool { guard let stripScreen = NSScreen.screens.first(where: { $0.frame.intersects(stripFrame) }) else { return true } return stripScreen.frame.intersects(cocoa) } private func findWindow(_ id: CGWindowID) -> WindowInfo? { for pid in store.allPIDs() { if let window = store.windows(for: pid).first(where: { $0.id == id }) { return window } } return nil } private func subrole(_ element: AXUIElement) -> String? { var value: CFTypeRef? guard AXUIElementCopyAttributeValue(element, kAXSubroleAttribute as CFString, &value) == .success else { return nil } return value as? String } private func isSizeSettable(_ element: AXUIElement) -> Bool { var settable: DarwinBoolean = false let error = AXUIElementIsAttributeSettable(element, kAXSizeAttribute as CFString, &settable) return error == .success && settable.boolValue } // axFrame returns the window frame in AX coordinates (top-left origin). private func axFrame(_ element: AXUIElement) -> CGRect? { var positionValue: CFTypeRef? var sizeValue: CFTypeRef? guard AXUIElementCopyAttributeValue(element, kAXPositionAttribute as CFString, &positionValue) == .success, AXUIElementCopyAttributeValue(element, kAXSizeAttribute as CFString, &sizeValue) == .success, let positionValue = positionValue, let sizeValue = sizeValue, CFGetTypeID(positionValue) == AXValueGetTypeID(), CFGetTypeID(sizeValue) == AXValueGetTypeID() else { return nil } var point = CGPoint.zero var size = CGSize.zero AXValueGetValue(positionValue as! AXValue, .cgPoint, &point) AXValueGetValue(sizeValue as! AXValue, .cgSize, &size) return CGRect(origin: point, size: size) } private func setSize(_ element: AXUIElement, _ size: CGSize) { var value = size if let axValue = AXValueCreate(.cgSize, &value) { AXUIElementSetAttributeValue(element, kAXSizeAttribute as CFString, axValue) } } } // StageManagerState reads the Stage Manager state. // // UNCERTAIN: macOS has no public API for the Stage Manager state. The key // "GloballyEnabled" in the domain "com.apple.WindowManager" reports if Stage // Manager is on. This key reports the global setting, not the per-Space state. // The constraint service skips the window if this key is true. private enum StageManagerState { static var isOn: Bool { guard let defaults = UserDefaults(suiteName: "com.apple.WindowManager") else { return false } return defaults.bool(forKey: "GloballyEnabled") } }