Here's how you can use normal SwiftUI code to disable "File -> New Window" when the main window is open, and enable "File -> New Window" when the main window is closed.
This code probably has some edge cases that could be polished, but it does work.
import SwiftUI
@main
struct MyApp: App {
@State var isMainWindowOpen = false
var body: some Scene {
WindowGroup {
ContentView()
.onAppear {
print("Main window appeared")
self.isMainWindowOpen = true
}
.onDisappear {
print("Main window disappeared")
self.isMainWindowOpen = false
}
}.commands {
if isMainWindowOpen {
CommandGroup(replacing: .newItem) {
Button("New Window", action: {})
.disabled(true)
// This is the same keyboard shortcut as the default New Window option.
// We're just doing this so that our disabled dummy option shows
// the same shortcut visually.
.keyboardShortcut(KeyboardShortcut("n", modifiers: [.command]))
}
} else {
// By doing nothing here, we let the default
// "File -> New Window" item display and handle input.
EmptyCommands()
}
}
}
}