// LyrebirdWindow.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT #if os(macOS) #if canImport(SwiftUI) 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? 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(@ViewBuilder content: () -> Content) { // Close any existing window before opening a new one. closeWindow() let controller: NSHostingController = 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 #elseif os(Linux) import Foundation import SwiftOpenUI import BackendGTK4 /// LyrebirdWindow — a standalone GTK4 window hosting SwiftOpenUI content. /// /// The Linux counterpart to the macOS `NSWindow` + `NSHostingController` host. /// Opens a top-level `GtkApplicationWindow` (via /// `GTK4Backend.openStandaloneWindow`) whose child is the rendered SwiftOpenUI /// view. Same public shape as the macOS side — `init(title:width:height:)`, /// `open(content:)`, `close()` — so `presentInWindow(...)` convenience methods /// work identically on both platforms. /// /// ## Requirements /// /// A `GtkApplication` main loop must already be running — i.e. the process is /// inside `GTK4Backend().run(App)`. Opening a window from a CLI/REPL with no /// running application is a no-op (`open` leaves the window closed); use the /// declarative `App`/`WindowGroup` scene as the process entry point, then open /// further windows imperatively with `LyrebirdWindow`. /// /// ## Threading /// /// GTK is single-threaded; every method must run on the GTK main thread. Unlike /// the macOS `@MainActor` class, this is left nonisolated to match the rest of /// the Linux/GTK4 UI and the SwiftOpenUI backend, which are all confined to the /// GTK main loop rather than the Swift main actor — a nonisolated SwiftOpenUI /// `body` and `Button` action can then drive it without an actor hop. public final class LyrebirdWindow { // MARK: - Configuration /// Window title-bar text. public let title: String /// Initial window width in points. public let width: Double /// Initial window height in points. public let height: Double // MARK: - Private state private var handle: GTK4StandaloneWindowHandle? /// Bumped on every `open()`. The `onClose` closure captures the generation /// live at open time and only clears `handle` if it still matches, so a stale /// destroy signal from a previously-closed window (were it ever delivered /// asynchronously) can't null out a newer window's handle on rapid reuse. private var generation: Int = 0 // 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: Double = 400, height: Double = 300 ) { self.title = title self.width = width self.height = height } // MARK: - State /// Whether a window is currently open for this instance. public var isOpen: Bool { handle?.isOpen ?? false } // MARK: - Open /// Opens the window and displays the provided SwiftOpenUI content. /// /// If a window is already open for this instance, it is closed and replaced /// with a new one hosting the updated content. If no `GtkApplication` is /// running, this is a no-op. /// /// - Parameter content: A `@ViewBuilder` closure returning any SwiftOpenUI /// `View`. public func open(@ViewBuilder content: () -> Content) { closeWindow() generation &+= 1 let token: Int = generation // `onClose` fires on the GTK main thread when the user closes the window; // clear our handle so `isOpen` reflects it — but only if this is still the // current window (guard against a stale callback from a replaced one). handle = GTK4Backend.openStandaloneWindow( title: title, width: Int(width), height: Int(height), onClose: { [weak self] in guard let self, self.generation == token else { return } self.handle = nil }, content: content ) } // MARK: - Close /// Closes and destroys the window. public func close() { closeWindow() } // MARK: - Private private func closeWindow() { handle?.close() handle = nil } } #endif