56 lines
3.1 KiB
Swift
56 lines
3.1 KiB
Swift
import SwiftUI
|
|
import AppKit
|
|
|
|
/// Window geometry/lifecycle stays in the feature layer; Core receives only visibility.
|
|
struct PanelWindowObserver: NSViewRepresentable {
|
|
var update: (CGSize, Bool) -> Void
|
|
func makeNSView(context: Context) -> ObserverView { ObserverView(update: update) }
|
|
func updateNSView(_ view: ObserverView, context: Context) { view.update = update }
|
|
|
|
final class ObserverView: NSView {
|
|
var update: (CGSize, Bool) -> Void
|
|
private var observers: [NSObjectProtocol] = []
|
|
init(update: @escaping (CGSize, Bool) -> Void) { self.update = update; super.init(frame: .zero) }
|
|
required init?(coder: NSCoder) { fatalError() }
|
|
override func viewDidMoveToWindow() {
|
|
super.viewDidMoveToWindow()
|
|
observers.forEach(NotificationCenter.default.removeObserver)
|
|
observers = []
|
|
guard let window else { return }
|
|
for name in [NSWindow.didChangeScreenNotification, NSWindow.didResizeNotification, NSWindow.didMoveNotification, NSWindow.didBecomeKeyNotification,
|
|
NSWindow.didResignKeyNotification, NSWindow.willCloseNotification,
|
|
NSWindow.didChangeOcclusionStateNotification] {
|
|
observers.append(NotificationCenter.default.addObserver(forName: name, object: window, queue: .main) { [weak self] _ in
|
|
MainActor.assumeIsolated { self?.report() }
|
|
})
|
|
}
|
|
observers.append(NotificationCenter.default.addObserver(forName: NSApplication.didChangeScreenParametersNotification, object: nil, queue: .main) { [weak self] _ in
|
|
MainActor.assumeIsolated { self?.report() }
|
|
})
|
|
report()
|
|
}
|
|
private func report() {
|
|
guard let window else { return }
|
|
let frame = (window.screen ?? NSScreen.main)?.visibleFrame ?? NSRect(x: 0, y: 0, width: 1000, height: 760)
|
|
let chrome = CGSize(width: max(0, window.frame.width - window.contentLayoutRect.width),
|
|
height: max(0, window.frame.height - window.contentLayoutRect.height))
|
|
let size = PanelLayout.contentSize(visible: frame, chrome: chrome)
|
|
let visible = window.isVisible
|
|
DispatchQueue.main.async { [weak self, weak window] in
|
|
guard let self, let window else { return }
|
|
self.update(size, visible)
|
|
// SwiftUI can resize a MenuBarExtra after the system chose its anchor origin.
|
|
// Clamp after layout as well as on moves; keep the native status-item scene.
|
|
DispatchQueue.main.async { [weak window] in
|
|
guard let window, window.isVisible else { return }
|
|
let adjusted = PanelLayout.constrainedFrame(window.frame, visible: frame)
|
|
if abs(adjusted.minX - window.frame.minX) > 0.5 || abs(adjusted.minY - window.frame.minY) > 0.5 {
|
|
window.setFrameOrigin(adjusted.origin)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
deinit { observers.forEach(NotificationCenter.default.removeObserver) }
|
|
}
|
|
}
|