Files
CrossSound-Swift/Apps/macOS/Sources/MacAppDelegate.swift
RedLintu16andClaude Opus 5.5 64ec524ba0 CrossSound for Apple platforms
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-14 13:28:34 -07:00

203 lines
9.2 KiB
Swift
Executable File

// MacAppDelegate.swift — the AppKit half of the macOS shell: installs the
// menu-bar item, gives the window its close-hides behavior, restores it on
// Dock reopen, and bridges the Kit's live services to StatusBarController.
//
// It also owns Space-to-play/pause (installSpaceToPlay below): an AppKit key
// monitor, because only AppKit can tell when Space belongs to a text field.
//
// Port of CrossSound-Flutter macos/Runner/AppDelegate.swift plus the window
// pieces of MainFlutterWindow.swift (shared window ref + windowShouldClose).
// SwiftUI owns the Window scene now, so instead of subclassing NSWindow we
// ADOPT the scene's window at launch and take its delegate — same
// interception point, different tenure.
import AppKit
import CrossSoundKit
import CrossSoundUI
import WebKit
@MainActor
final class MacAppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, MacControlRegistry {
/// The Window("CrossSound") scene's NSWindow — this port's
/// MainFlutterWindow.shared. weak: SwiftUI owns the window; orderOut keeps
/// it alive while hidden, so the ref survives close-hides.
private weak var mainWindow: NSWindow?
/// The scene's NowPlayingCenter, handed over by AppRoot.wireControlHooks
/// through MacControlSurface. weak: AppRoot's @State owns it.
private weak var nowPlaying: NowPlayingCenter?
/// The Space key monitor's token. Held for the app's lifetime, never removed.
private var spaceMonitor: Any?
func applicationWillFinishLaunching(_ notification: Notification) {
// Plant the registry slot before any scene mounts: AppRoot's .task (which
// runs wireControlHooks → registerControlServices) can only fire after
// launch completes, so the slot is always filled in time.
MacControlSurface.registry = self
}
func applicationDidFinishLaunching(_ notification: Notification) {
CSLog.shared.log("statusbar", "applicationDidFinishLaunching")
StatusBarController.shared.install()
StatusBarController.shared.onShowWindow = { [weak self] in self?.showMainWindow() }
installSpaceToPlay()
// WINDOW CAPTURE — the chosen approach: NSApp.windows from here, not a
// WindowAccessor helper view. It keeps the SwiftUI scene declaration free
// of AppKit plumbing, and with exactly one Window scene in the app (see
// CrossSoundApp: Window, not WindowGroup) there is only one window to
// find. SwiftUI may not have realized the NSWindow at this exact moment,
// hence the main-queue hop; every showMainWindow() re-adopts as the
// belt-and-braces retry if even that was too early.
// A few spaced attempts: SwiftUI may not have realized the NSWindow on
// the first main-queue turn (review finding: a single attempt could leave
// windowShouldClose unhooked until the user happens to hit Show).
for delay in [0.0, 0.25, 1.0] {
DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in
self?.adoptMainWindow()
}
}
}
/// Closing the window HIDES it (windowShouldClose below) and the app keeps
/// running in the menu bar with audio playing. Quit is explicit — menu/⌘Q.
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
false
}
/// Clicking the Dock icon with no visible window brings ours back.
func applicationShouldHandleReopen(
_ sender: NSApplication, hasVisibleWindows flag: Bool
) -> Bool {
if !flag { showMainWindow() }
return true
}
func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
true
}
// MARK: - MacControlRegistry (the Kit → menu-bar bridge)
/// AppRoot.wireControlHooks hands the scene's live NowPlayingCenter here,
/// once per scene. Two wires:
/// state — NowPlayingCenter.onState → StatusBarController.apply. onState
/// is a single closure ("last assignment wins") that nothing
/// else in the app sets, so taking it whole is safe, and this
/// port fires it on main — no hop needed (the Flutter plugin
/// made no threading promise; the old consumer hopped itself).
/// action — StatusBarController.onCommand (the original channel's command
/// strings) → NowPlayingCenter.onCommand, i.e. the exact closure
/// wireControlHooks installed around QueueController. Invoking
/// it makes a menu click take the SAME switch as the media keys,
/// including the fresh-snapshot push its defer does.
func registerControlServices(nowPlaying: NowPlayingCenter) {
self.nowPlaying = nowPlaying
nowPlaying.onState = { title, artist, isPlaying in
StatusBarController.shared.apply(title: title, artist: artist, isPlaying: isPlaying)
}
StatusBarController.shared.onCommand = { [weak nowPlaying] cmd in
// The menu never emits "playpause" anymore — StatusBarController
// resolves the toggle itself and sends explicit "play"/"pause" (the
// Flutter-era "playpause" string died unheard in the Dart handler).
let mapped: RemoteCommand?
switch cmd {
case "play": mapped = .play
case "pause": mapped = .pause
case "next": mapped = .next
case "prev": mapped = .prev
case "like": mapped = .like
default: mapped = nil
}
guard let mapped else {
CSLog.shared.log("statusbar", "unknown menu command: \(cmd)")
return
}
nowPlaying?.onCommand?(mapped)
}
CSLog.shared.log("statusbar", "control services registered")
}
// MARK: - Space to play/pause
/// Space toggles playback, like Music and Spotify — through the same
/// NowPlayingCenter.onCommand(.toggle) the media keys and the menu bar use.
///
/// An AppKit local monitor rather than a SwiftUI .keyboardShortcut(.space)
/// or a menu key equivalent: those fire before the focused view sees the
/// key, so Space would stop typing anywhere. Here the event is only taken
/// when nothing is typing — see isPlayPauseSpace.
private func installSpaceToPlay() {
spaceMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in
guard let self, self.isPlayPauseSpace(event) else { return event }
// Swallow auto-repeat without toggling: holding Space must not stutter
// play/pause/play.
if !event.isARepeat { self.nowPlaying?.onCommand?(.toggle) }
return nil
}
}
/// A bare Space (no modifiers) in one of our windows while nothing is
/// taking text input.
private func isPlayPauseSpace(_ event: NSEvent) -> Bool {
guard event.keyCode == 49, // kVK_Space
event.modifierFlags.intersection(.deviceIndependentFlagsMask)
.subtracting([.capsLock, .numericPad, .function]).isEmpty,
nowPlaying != nil, // services not wired yet: leave the key alone
let window = event.window
else { return false }
let responder = window.firstResponder
// TextField / SecureField / TextEditor: AppKit edits through an NSText
// (the window's field editor, or the NSTextView itself), and so does a
// marked IME composition.
if responder is NSText { return false }
// Web content — the SoundCloud login form lives inside a WKWebView, which
// keeps its own focus; a space typed into its fields must reach the page.
var view = responder as? NSView
while let v = view {
if v is WKWebView { return false }
view = v.superview
}
return true
}
// MARK: - Window behavior (MainFlutterWindow's job, SwiftUI-era)
/// Find the Window scene's NSWindow and take its delegate so close can be
/// intercepted. Idempotent — cheap to call from every restore path.
///
/// NOTE: assigning .delegate displaces SwiftUI's own window delegate. That
/// is the deliberate trade for the same interception point the Flutter
/// window had; nothing this app leans on (scenePhase, environment, @State)
/// has shown a dependency on it. Revisit here first if window restoration
/// or scene-phase updates ever misbehave.
private func adoptMainWindow() {
guard mainWindow == nil else { return }
// SwiftUI derives the NSWindow identifier from Window(id: "main"); the
// exact spelling varies by OS release ("main", "main-AppWindow-1", …) so
// match the prefix, and fall back to "any titled non-panel" — with a
// single Window scene that can only be ours (the status item lives in a
// borderless NSStatusBarWindow, which .titled filters out).
let window =
NSApp.windows.first { $0.identifier?.rawValue.hasPrefix("main") == true }
?? NSApp.windows.first { $0.styleMask.contains(.titled) && !($0 is NSPanel) }
guard let window else {
CSLog.shared.log("statusbar", "adoptMainWindow: no window yet")
return
}
mainWindow = window
window.delegate = self
CSLog.shared.log("statusbar", "adopted main window (\(window.identifier?.rawValue ?? "?"))")
}
private func showMainWindow() {
adoptMainWindow() // covers a launch race where the async hop found nothing
mainWindow?.makeKeyAndOrderFront(nil)
}
/// Hide instead of closing: playback continues and the menu bar item stays.
/// (MainFlutterWindow.windowShouldClose, behavior verbatim.)
func windowShouldClose(_ sender: NSWindow) -> Bool {
sender.orderOut(nil)
return false
}
}