Files
ShoeGaze/Demo/ShoeGazeBuilder/AppDelegate.swift
T
2026-06-22 15:40:23 -07:00

304 lines
12 KiB
Swift

// AppDelegate.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import AppKit
import UniformTypeIdentifiers
import LyrebirdSynth
import LyrebirdUI
import LyrebirdShoeGaze
import LyrebirdShoeGazeUI
/// Application delegate for the ShoeGaze Builder.
///
/// Creates a `SynthesisEngine` and a `ShoeGaze` session seeded with one empty board, then opens a
/// `LyrebirdWindow` hosting ``ShoeGazeBuilderView`` — the interactive palette + board builder.
///
/// The engine is **not** started automatically; the user clicks Start in the builder's toolbar.
/// On termination the engine is stopped to release Core Audio resources cleanly.
@MainActor
final class AppDelegate: NSObject, NSApplicationDelegate {
// MARK: - Engine configuration constants
private static let blockSize: Int = 512
private static let sampleRate: Double = 48_000.0
private static let outputChannels: Int = 2
// Built-in mics are mono; default to one input channel so live input works out of the box.
// CoreAudio can't satisfy a request for more input channels than the device provides, which
// leaves live input silent. Users with multi-input interfaces can raise this in the UI.
private static let inputChannels: Int = 1
private static let numAudioBuses: Int = 256
// MARK: - Window geometry constants
private static let windowWidth: CGFloat = 1_400
private static let windowHeight: CGFloat = 860
/// Margin from the left edge of the screen's visible area, in points.
private static let leftMargin: CGFloat = 100
/// Margin reserved at the right edge so the window never runs off-screen.
private static let rightMargin: CGFloat = 40
/// Fraction of the visible screen height the window should occupy.
private static let heightFraction: CGFloat = 0.88
/// The default pedal the seed board comes up with, so audio is audible immediately on Start.
private static let seedPedalType: String = "Overdrive"
// MARK: - Owned objects
private let coreDriver: CoreAudioDriver
private let engine: SynthesisEngine
private let shoeGaze: ShoeGaze
private let window: LyrebirdWindow
/// Record toggle item, retained so `validateMenuItem(_:)` can flip its title + enabled state.
private var recordMenuItem: NSMenuItem?
/// Default file name offered by the Save panel.
private static let defaultRigFileName: String = "ShoeGazeRig"
// MARK: - Init
override init() {
let coreDriver: CoreAudioDriver = CoreAudioDriver()
let engine: SynthesisEngine = SynthesisEngine(
blockSize: AppDelegate.blockSize,
sampleRate: AppDelegate.sampleRate,
numOutputChannels: AppDelegate.outputChannels,
numInputChannels: AppDelegate.inputChannels,
numAudioBuses: AppDelegate.numAudioBuses,
driver: coreDriver
)
self.coreDriver = coreDriver
self.engine = engine
self.shoeGaze = ShoeGaze(engine: engine)
self.window = LyrebirdWindow(
title: "ShoeGaze Builder — Lyrebird Pedalboard",
width: AppDelegate.windowWidth,
height: AppDelegate.windowHeight
)
super.init()
seedInitialBoard()
}
/// Seeds one board with a single pedal so the builder opens with an audible starting point.
private func seedInitialBoard() {
var created: PedalBoard?
do {
let board: PedalBoard = try shoeGaze.addBoard()
created = board
try shoeGaze.appendPedal(type: AppDelegate.seedPedalType, to: board)
} catch {
if let board: PedalBoard = created { shoeGaze.removeBoard(board) }
print("[ShoeGazeBuilder] seed board failed: \(error)")
}
}
// MARK: - NSApplicationDelegate
func applicationDidFinishLaunching(_ notification: Notification) {
installMainMenu()
let session: ShoeGaze = shoeGaze
let driver: CoreAudioDriver = coreDriver
window.open {
ShoeGazeBuilderView(shoeGaze: session, hardwareSampleRate: { driver.deviceSampleRate })
}
anchorWindowLeft()
}
/// Anchors the window `leftMargin` points from the left of the visible screen and sizes it to
/// most of the visible height, so it presents large and left-aligned rather than centered.
private func anchorWindowLeft() {
guard let nsWindow: NSWindow = window.nsWindow,
let screen: NSScreen = nsWindow.screen ?? NSScreen.main else { return }
let visible: NSRect = screen.visibleFrame
let height: CGFloat = visible.height * AppDelegate.heightFraction
let maxWidth: CGFloat = visible.width - AppDelegate.leftMargin - AppDelegate.rightMargin
let width: CGFloat = min(AppDelegate.windowWidth, maxWidth)
let originX: CGFloat = visible.minX + AppDelegate.leftMargin
// Top-align: place the window's top near the top of the visible area.
let originY: CGFloat = visible.maxY - height
nsWindow.setFrame(
NSRect(x: originX, y: originY, width: width, height: height),
display: true
)
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
true
}
func applicationWillTerminate(_ notification: Notification) {
engine.stop()
}
// MARK: - Main menu
/// Builds a minimal menu bar: an application menu with About / Hide / Quit (⌘Q).
private func installMainMenu() {
let appName: String = ProcessInfo.processInfo.processName
let mainMenu: NSMenu = NSMenu()
let appMenuItem: NSMenuItem = NSMenuItem()
mainMenu.addItem(appMenuItem)
let appMenu: NSMenu = NSMenu()
appMenuItem.submenu = appMenu
appMenu.addItem(
withTitle: "About \(appName)",
action: #selector(NSApplication.orderFrontStandardAboutPanel(_:)),
keyEquivalent: ""
)
appMenu.addItem(NSMenuItem.separator())
appMenu.addItem(
withTitle: "Hide \(appName)",
action: #selector(NSApplication.hide(_:)),
keyEquivalent: "h"
)
appMenu.addItem(NSMenuItem.separator())
appMenu.addItem(
withTitle: "Quit \(appName)",
action: #selector(NSApplication.terminate(_:)),
keyEquivalent: "q"
)
// File menu — rig save / load.
let fileMenuItem: NSMenuItem = NSMenuItem()
mainMenu.addItem(fileMenuItem)
let fileMenu: NSMenu = NSMenu(title: "File")
fileMenuItem.submenu = fileMenu
addItem(to: fileMenu, title: "Save Rig…", action: #selector(saveRigAction(_:)), key: "s")
addItem(to: fileMenu, title: "Load Rig…", action: #selector(loadRigAction(_:)), key: "o")
// Board menu — add board + transport.
let boardMenuItem: NSMenuItem = NSMenuItem()
mainMenu.addItem(boardMenuItem)
let boardMenu: NSMenu = NSMenu(title: "Board")
boardMenuItem.submenu = boardMenu
// Engine start/stop lives in the in-window EngineConfigView (with sample-rate/channel
// config and the mismatch alert), so the Board menu only adds boards.
addItem(to: boardMenu, title: "Add Board", action: #selector(addBoardAction(_:)), key: "b")
// Record menu — choose an output folder, then toggle recording.
let recordMenuItem: NSMenuItem = NSMenuItem()
mainMenu.addItem(recordMenuItem)
let recordMenu: NSMenu = NSMenu(title: "Record")
recordMenuItem.submenu = recordMenu
addItem(
to: recordMenu,
title: "Choose Recording Folder…",
action: #selector(chooseRecordingFolderAction(_:)),
key: ""
)
recordMenu.addItem(NSMenuItem.separator())
self.recordMenuItem = addItem(
to: recordMenu,
title: "Start Recording",
action: #selector(toggleRecordingAction(_:)),
key: "R" // ⇧⌘R
)
NSApplication.shared.mainMenu = mainMenu
}
/// Adds a menu item targeting this delegate and returns it.
@discardableResult
private func addItem(
to menu: NSMenu,
title: String,
action: Selector,
key: String
) -> NSMenuItem {
let item: NSMenuItem = NSMenuItem(title: title, action: action, keyEquivalent: key)
item.target = self
menu.addItem(item)
return item
}
// MARK: - Menu actions
@objc private func saveRigAction(_ sender: Any?) {
let panel: NSSavePanel = NSSavePanel()
panel.allowedContentTypes = [.json]
panel.nameFieldStringValue = "\(AppDelegate.defaultRigFileName).json"
panel.canCreateDirectories = true
let session: ShoeGaze = shoeGaze
panel.begin { response in
guard response == .OK, let url: URL = panel.url else { return }
do { try session.saveRig(to: url) }
catch { print("[ShoeGazeBuilder] saveRig failed: \(error)") }
}
}
@objc private func loadRigAction(_ sender: Any?) {
let panel: NSOpenPanel = NSOpenPanel()
panel.allowedContentTypes = [.json]
panel.canChooseDirectories = false
panel.allowsMultipleSelection = false
let session: ShoeGaze = shoeGaze
let activeEngine: SynthesisEngine = engine
panel.begin { response in
guard response == .OK, let url: URL = panel.url else { return }
// loadRig rebuilds the graph; stop the engine around it and restart if it was running.
let wasRunning: Bool = activeEngine.isRunning
if wasRunning { activeEngine.stop() }
do { try session.loadRig(from: url) }
catch { print("[ShoeGazeBuilder] loadRig failed: \(error)") }
if wasRunning { try? activeEngine.start() }
}
}
@objc private func addBoardAction(_ sender: Any?) {
var created: PedalBoard?
do {
let board: PedalBoard = try shoeGaze.addBoard()
created = board
try shoeGaze.finalizeBoard(board)
} catch {
if let board: PedalBoard = created { shoeGaze.removeBoard(board) }
print("[ShoeGazeBuilder] addBoard failed: \(error)")
}
}
@objc private func chooseRecordingFolderAction(_ sender: Any?) {
let panel: NSOpenPanel = NSOpenPanel()
panel.canChooseDirectories = true
panel.canChooseFiles = false
panel.allowsMultipleSelection = false
panel.canCreateDirectories = true
panel.prompt = "Choose"
panel.message = "Select a folder for recording output"
let session: ShoeGaze = shoeGaze
panel.begin { response in
if response == .OK, let url: URL = panel.url {
session.recordingFolder = url
}
}
}
@objc private func toggleRecordingAction(_ sender: Any?) {
if shoeGaze.isRecording {
shoeGaze.stopRecording()
} else {
do { try shoeGaze.startRecording() }
catch { print("[ShoeGazeBuilder] startRecording() failed: \(error)") }
}
// Reflect the new state on the item immediately, not only on the next menu-open validation.
recordMenuItem?.title = shoeGaze.isRecording ? "Stop Recording" : "Start Recording"
}
func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
if menuItem == recordMenuItem {
menuItem.title = shoeGaze.isRecording ? "Stop Recording" : "Start Recording"
// Can always stop; can only start once a folder has been chosen.
return shoeGaze.isRecording || shoeGaze.recordingFolder != nil
}
return true
}
}
#endif