PulseCanvas / app / Sources / PulseCanvas / AppLifecycle.swift
| 1 | import AppKit |
| 2 | |
| 3 | /// Closing the last editor or radio window ends playback and quits, even if an |
| 4 | /// auxiliary credits window remains open. Minimizing is not a close event. |
| 5 | @MainActor |
| 6 | final class AppLifecycle: NSObject, NSApplicationDelegate { |
| 7 | private let primaryWindows = NSHashTable<NSWindow>.weakObjects() |
| 8 | private weak var audio: AudioController? |
| 9 | private weak var radio: RadioController? |
| 10 | |
| 11 | override init() { |
| 12 | super.init() |
| 13 | NotificationCenter.default.addObserver(self, selector: #selector(windowWillClose(_:)), |
| 14 | name: NSWindow.willCloseNotification, object: nil) |
| 15 | } |
| 16 | |
| 17 | func attach(audio: AudioController, radio: RadioController) { |
| 18 | self.audio = audio; self.radio = radio |
| 19 | } |
| 20 | |
| 21 | func track(_ window: NSWindow?) { |
| 22 | if let window { primaryWindows.add(window) } |
| 23 | } |
| 24 | |
| 25 | func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true } |
| 26 | |
| 27 | func applicationWillTerminate(_ notification: Notification) { stopPlayback() } |
| 28 | |
| 29 | private func stopPlayback() { radio?.shutdown(); audio?.stop() } |
| 30 | |
| 31 | @objc private func windowWillClose(_ notification: Notification) { |
| 32 | guard let window = notification.object as? NSWindow, primaryWindows.contains(window) else { return } |
| 33 | primaryWindows.remove(window) |
| 34 | guard primaryWindows.allObjects.isEmpty else { return } |
| 35 | stopPlayback() |
| 36 | // Finish the native close event before terminating the SwiftUI scene host. |
| 37 | DispatchQueue.main.async { NSApplication.shared.terminate(nil) } |
| 38 | } |
| 39 | } |