Files
Lyrebird/Sources/LyrebirdUI/LyrebirdWindow.swift
T
2026-06-01 18:27:40 -07:00

162 lines
5.1 KiB
Swift

// LyrebirdWindow.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import AppKit
import SwiftUI
/// LyrebirdWindow — a native macOS window hosting SwiftUI content.
///
/// Opens an `NSWindow` backed by an `NSHostingController`. Full SwiftUI is available
/// inside the content closure — mix Lyrebird controls with any standard SwiftUI views.
///
/// Works identically from the REPL and from compiled projects.
///
/// ## Usage
///
/// ```swift
/// import LyrebirdUI
///
/// let w = LyrebirdWindow(title: "My Synth", width: 400, height: 300)
/// w.open {
/// VStack {
/// ParameterSlider("Amplitude", node: synth.$amplitude, range: 0...1)
/// ParameterSlider("Frequency", node: synth.$frequency, range: 20...20000)
/// ParameterButton("Free") { engine.rootGroup.remove(synth) }
/// }
/// .padding()
/// }
///
/// // Later...
/// w.close()
/// ```
///
/// ## Threading
///
/// All methods are `@MainActor`-isolated — `NSWindow` creation and AppKit mutations must
/// happen on the main thread. Call `open` and `close` from the main thread or from a
/// `@MainActor` context. In async code, use `await MainActor.run { w.open { ... } }`.
@MainActor
public final class LyrebirdWindow {
/// Internal `NSWindowDelegate` that nils out the parent's window reference when
/// AppKit closes the window (e.g. user clicks the red close button). `NSWindow`
/// defaults to `isReleasedWhenClosed = true`, so without this bookkeeping the
/// stored Swift reference becomes a dangling pointer.
private final class Delegate: NSObject, NSWindowDelegate {
weak var owner: LyrebirdWindow?
func windowWillClose(_ notification: Notification) {
owner?.window = nil
owner?.hostingController = nil
owner?.delegate = nil
}
}
// MARK: - Configuration
/// Window title bar text.
public let title: String
/// Initial window width in points.
public let width: CGFloat
/// Initial window height in points.
public let height: CGFloat
// MARK: - Private state
private var window: NSWindow?
private var hostingController: NSHostingController<AnyView>?
private var delegate: Delegate?
// MARK: - Underlying AppKit window
/// The underlying `NSWindow`, available after `open(content:)` has been called.
/// Use sparingly — exposed for callers that need AppKit-level configuration
/// (custom origin, level, collection behavior, etc.) that the wrapper does not.
public var nsWindow: NSWindow? { window }
// MARK: - Init
/// Creates a `LyrebirdWindow` with the given display properties.
///
/// The window is not shown until `open(content:)` is called.
///
/// - Parameters:
/// - title: Text shown in the window's title bar.
/// - width: Initial window width (default 400 pt).
/// - height: Initial window height (default 300 pt).
public init(
title: String = "Lyrebird",
width: CGFloat = 400,
height: CGFloat = 300
) {
self.title = title
self.width = width
self.height = height
}
// MARK: - Open
/// Opens the window and displays the provided SwiftUI content.
///
/// If a window is already open for this instance, it is closed and replaced with a
/// new one hosting the updated content.
///
/// - Parameter content: A `@ViewBuilder` closure returning any SwiftUI `View`.
public func open<Content: View>(@ViewBuilder content: () -> Content) {
// Close any existing window before opening a new one.
closeWindow()
let controller: NSHostingController<AnyView> = NSHostingController(rootView: AnyView(content()))
let initialSize: CGSize = CGSize(width: width, height: height)
let win: NSWindow = NSWindow(
contentRect: NSRect(origin: .zero, size: initialSize),
styleMask: [.titled, .closable, .resizable, .miniaturizable],
backing: .buffered,
defer: false
)
// NSWindow defaults to releasing itself on close — that would leave the
// stored `self.window` pointing at freed memory after the user clicks the
// red close button. Keep ownership in Swift; the delegate nils the ref.
win.isReleasedWhenClosed = false
win.title = title
win.contentViewController = controller
win.center()
let del: Delegate = Delegate()
del.owner = self
win.delegate = del
win.makeKeyAndOrderFront(nil)
self.window = win
self.hostingController = controller
self.delegate = del
}
// MARK: - Close
/// Closes and releases the window.
public func close() {
closeWindow()
}
// MARK: - Private
private func closeWindow() {
// Detach delegate first so `windowWillClose` does not re-enter and nil
// refs mid-teardown.
window?.delegate = nil
window?.close()
window = nil
hostingController = nil
delegate = nil
}
}
#endif