import AppKit
import ObjectiveC
private var fullscreenHooksKey: UInt8 = 0
private final class FullscreenHooks: NSObject {
private var monitor: Any?
private let tray: Bool
private let exited: @convention(c) (Bool) -> Void
init(window: NSWindow, tray: Bool, escape: @escaping @convention(c) (Bool) -> Bool,
exited: @escaping @convention(c) (Bool) -> Void) {
self.tray = tray
self.exited = exited
super.init()
monitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak window] event in
guard let window, event.window === window, event.keyCode == 53,
event.modifierFlags.intersection([.shift, .control, .option, .command]).isEmpty,
escape(tray) else { return event }
return nil
}
NotificationCenter.default.addObserver(self, selector: #selector(didExit),
name: NSWindow.didExitFullScreenNotification, object: window)
}
@objc private func didExit(_ notification: Notification) {
exited(tray)
}
deinit {
if let monitor { NSEvent.removeMonitor(monitor) }
NotificationCenter.default.removeObserver(self)
}
}
@_cdecl("gent_fullscreen_watch")
public func gentFullscreenWatch(_ pointer: UnsafeRawPointer, _ tray: Bool,
_ escape: @escaping @convention(c) (Bool) -> Bool,
_ exited: @escaping @convention(c) (Bool) -> Void) {
let window = Unmanaged<NSWindow>.fromOpaque(pointer).takeUnretainedValue()
guard objc_getAssociatedObject(window, &fullscreenHooksKey) == nil else { return }
if !tray {
// Tao calls toggleFullScreen: on this viewer. An accessory app's window
// needs an explicit primary fullscreen role for AppKit to honor the toggle.
window.collectionBehavior = window.collectionBehavior
.subtracting([.fullScreenAuxiliary, .fullScreenNone]).union(.fullScreenPrimary)
}
let hooks = FullscreenHooks(window: window, tray: tray, escape: escape, exited: exited)
objc_setAssociatedObject(window, &fullscreenHooksKey, hooks, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
@_cdecl("gent_fullscreen_state")
public func gentFullscreenState(_ pointer: UnsafeRawPointer) -> Int32 {
let window = Unmanaged<NSWindow>.fromOpaque(pointer).takeUnretainedValue()
return window.styleMask.contains(.fullScreen) ? 1 : 0
}