macos: quit if we have no visible windows

This commit is contained in:
Mitchell Hashimoto
2023-03-27 10:05:29 -07:00
parent ef30ad394d
commit 41943b9a00
2 changed files with 16 additions and 0 deletions

View File

@ -120,6 +120,15 @@ class AppDelegate: NSObject, NSApplicationDelegate, ObservableObject {
}
func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
let windows = NSApplication.shared.windows
if (windows.isEmpty) { return .terminateNow }
// This probably isn't fully safe. The isEmpty check above is aspirational, it doesn't
// quit work with SwiftUI because windows are retained on close. So instead we check
// if there are any that are visible. I'm guessing this breaks under certain scenarios.
if (windows.allSatisfy { !$0.isVisible }) { return .terminateNow }
// We have some visible window, and all our windows will watch the confirmQuit.
confirmQuit = true
return .terminateLater
}

View File

@ -1,6 +1,9 @@
import SwiftUI
struct SettingsView: View {
// We need access to our app delegate to know if we're quitting or not.
@EnvironmentObject private var appDelegate: AppDelegate
var body: some View {
HStack {
Image("AppIconImage")
@ -18,6 +21,10 @@ struct SettingsView: View {
}
.padding()
.frame(minWidth: 500, maxWidth: 500, minHeight: 156, maxHeight: 156)
.onChange(of: appDelegate.confirmQuit) { value in
guard value else { return }
NSApplication.shared.reply(toApplicationShouldTerminate: true)
}
}
}