cc3a986cde
The rig snapshot already stores inputSource + input/output channel counts and syncs them via the autosave envelope and the iCloud rig library. Make that the single source of truth instead of the parallel UserDefaults path. - RigStore.restore applies the saved channel layout (applyChannelLayout) before loadRig, while stopped at launch, so a saved live-input channel validates against the restored count instead of falling back to the test loop. The general loadRig policy (don't force layout mid-session) is unchanged. - applyInputSource and the engine-config onConfigApplied now autosave, so input and I/O changes are captured into the rig immediately. - Remove the UserDefaults keys and read/write sites: ShoeGaze.inputSelection (builder view + iOS model) and the ShoeGaze.inputChannels/outputChannels keys added earlier (EngineConfigView + both app targets build at the default layout now; RigStore.restore supplies the rig's layout). - Fresh-launch default: the seed paths set inputSource = liveInput(0) when the engine has an input channel, so a first launch listens to the instrument. A restored rig keeps its own saved input; the view's on-appear hook only requests mic access for a restored live selection (test-loop fallback on denial). Test: RigStore.restoreAppliesSavedChannelLayoutAndInput. 461 tests pass; both app targets build. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
558 lines
24 KiB
Swift
558 lines
24 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, NSMenuDelegate {
|
||
|
||
// 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: PedalType = .overdrive
|
||
|
||
// MARK: - Owned objects
|
||
|
||
private let coreDriver: CoreAudioDriver
|
||
private let engine: SynthesisEngine
|
||
private let shoeGaze: ShoeGaze
|
||
private let window: LyrebirdWindow
|
||
|
||
/// Foot-controller MIDI input. The macOS engine is never rebuilt, so this is created once and
|
||
/// started at launch.
|
||
private let midi: MIDIController
|
||
|
||
/// The rig library; constructed in `init`, resolved + loaded asynchronously after launch.
|
||
private let library: RigLibraryStore
|
||
|
||
/// Record toggle item, retained so `validateMenuItem(_:)` can flip its title + enabled state.
|
||
private var recordMenuItem: NSMenuItem?
|
||
|
||
/// Rig-mute toggle item, retained so `validateMenuItem(_:)` can flip its title + checkmark to
|
||
/// match the current mute state (which may also change from the UI, MIDI, or the tuner).
|
||
private var muteMenuItem: NSMenuItem?
|
||
|
||
/// Rig-bypass toggle item, retained so `validateMenuItem(_:)` can flip its title + checkmark to
|
||
/// match the current bypass state (which may also change from the UI or MIDI).
|
||
private var bypassMenuItem: NSMenuItem?
|
||
|
||
/// The Rigs ▸ Set List submenu, retained so its item titles can be refreshed to the current
|
||
/// library order each time it opens (via `menuNeedsUpdate(_:)`).
|
||
private var setListMenu: NSMenu?
|
||
|
||
/// The ten fixed ⌘⇧1…⌘⇧0 set-list items (tags 0…9). Their key equivalents fire whether or not
|
||
/// the menu is open; `validateMenuItem(_:)` disables slots with no rig, and `menuNeedsUpdate`
|
||
/// refreshes their titles to the rig names.
|
||
private var setListMenuItems: [NSMenuItem] = []
|
||
|
||
/// Number of set-list slots exposed as ⌘⇧1…⌘⇧0.
|
||
private static let setListSlotCount: Int = 10
|
||
|
||
/// The Help window, created lazily on first open and reused thereafter.
|
||
private var helpWindow: LyrebirdWindow?
|
||
|
||
/// Default file name offered by the archive Export panel.
|
||
private static let defaultArchiveFileName: String = "ShoeGaze Library"
|
||
|
||
// MARK: - Init
|
||
|
||
override init() {
|
||
let coreDriver: CoreAudioDriver = CoreAudioDriver()
|
||
// The engine is built with the default layout; the autosaved rig's saved I/O layout (if any)
|
||
// is applied by `RigStore.restore` below, so a multi-channel setup survives relaunch.
|
||
let engine: SynthesisEngine = SynthesisEngine(
|
||
blockSize: AppDelegate.blockSize,
|
||
sampleRate: AppDelegate.sampleRate,
|
||
numOutputChannels: AppDelegate.outputChannels,
|
||
numInputChannels: AppDelegate.inputChannels,
|
||
numAudioBuses: AppDelegate.numAudioBuses,
|
||
driver: coreDriver
|
||
)
|
||
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
|
||
self.coreDriver = coreDriver
|
||
self.engine = engine
|
||
self.shoeGaze = shoeGaze
|
||
self.midi = MIDIController(engine: engine, shoeGaze: shoeGaze)
|
||
self.window = LyrebirdWindow(
|
||
title: "ShoeGaze Builder — Lyrebird Pedalboard",
|
||
width: AppDelegate.windowWidth,
|
||
height: AppDelegate.windowHeight
|
||
)
|
||
|
||
// Stored `let`s must be set before `super.init()`. Restore the autosaved working rig (or
|
||
// seed a board) — operating on `shoeGaze`, not on `self` methods (unavailable pre-super).
|
||
if !RigStore.restore(into: shoeGaze) {
|
||
AppDelegate.seedInitialBoard(into: shoeGaze)
|
||
}
|
||
// The library constructs instantly; it resolves iCloud + loads asynchronously after launch.
|
||
self.library = RigLibraryBootstrap.makeStore()
|
||
|
||
super.init()
|
||
}
|
||
|
||
/// Seeds one board with a single pedal so the builder opens with an audible starting point.
|
||
private static func seedInitialBoard(into shoeGaze: ShoeGaze) {
|
||
// Fresh launch (no autosaved rig): default to live In 0 rather than the test-loop arpeggio,
|
||
// so the app comes up listening to the instrument. A restored rig keeps its own saved input.
|
||
if shoeGaze.engine.numInputChannels > 0 {
|
||
shoeGaze.inputSource = .liveInput(channel: 0)
|
||
}
|
||
var created: PedalBoard?
|
||
do {
|
||
let board: PedalBoard = try shoeGaze.addBoard()
|
||
created = board
|
||
try shoeGaze.appendPedal(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()
|
||
midi.start()
|
||
midi.onMapChanged = { [weak self] in
|
||
guard let self: AppDelegate = self else { return }
|
||
RigStore.save(self.shoeGaze)
|
||
}
|
||
let session: ShoeGaze = shoeGaze
|
||
let driver: CoreAudioDriver = coreDriver
|
||
let rigLibrary: RigLibraryStore = library
|
||
let midiController: MIDIController = midi
|
||
window.open {
|
||
ShoeGazeBuilderView(
|
||
shoeGaze: session,
|
||
library: rigLibrary,
|
||
hardwareSampleRate: { driver.deviceSampleRate },
|
||
midi: midiController
|
||
)
|
||
}
|
||
anchorWindowLeft()
|
||
|
||
// Resolve iCloud + load the library off the main thread, then seed from the working rig if
|
||
// it is still empty (first run).
|
||
let rigSession: ShoeGaze = shoeGaze
|
||
Task { await RigLibraryBootstrap.start(rigLibrary, seedFrom: rigSession) }
|
||
}
|
||
|
||
/// 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
|
||
}
|
||
|
||
/// Opens `.shoegaze` files handed to the app by Finder, AirDrop, "Open With", or a double-click.
|
||
///
|
||
/// Rig documents are imported into the library (they appear in the sidebar, ready to load);
|
||
/// board documents are surfaced with a note that boards are opened from a rig's board editor.
|
||
func application(_ application: NSApplication, open urls: [URL]) {
|
||
for url: URL in urls {
|
||
openShoeGazeDocument(at: url)
|
||
}
|
||
}
|
||
|
||
/// Reads and imports a single `.shoegaze` document, reporting the outcome to the user.
|
||
private func openShoeGazeDocument(at url: URL) {
|
||
// A LaunchServices-supplied URL is security-scoped; start access to read it.
|
||
let scoped: Bool = url.startAccessingSecurityScopedResource()
|
||
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
|
||
do {
|
||
let data: Data = try Data(contentsOf: url)
|
||
let document: ShoeGazeDocument = try ShoeGazeDocument.decoded(from: data)
|
||
if document.rigEntries?.isEmpty == false {
|
||
let added: Int = try library.importArchive(from: data)
|
||
presentOpenInfo(
|
||
title: added == 1 ? "Rig Imported" : "Rigs Imported",
|
||
message: added == 1
|
||
? "Added 1 rig to your library. Select it in the Rigs sidebar to load it."
|
||
: "Added \(added) rigs to your library. Select one in the Rigs sidebar to load it."
|
||
)
|
||
} else if document.boardVersion != nil {
|
||
presentOpenInfo(
|
||
title: "Board Document",
|
||
message: "This file is a single board. Open a rig, then load the board from the "
|
||
+ "board editor's Versions menu."
|
||
)
|
||
}
|
||
} catch {
|
||
presentOpenInfo(
|
||
title: "Couldn’t Open File",
|
||
message: "“\(url.lastPathComponent)” is not a readable ShoeGaze document."
|
||
)
|
||
print("[ShoeGazeBuilder] open document failed: \(error)")
|
||
}
|
||
}
|
||
|
||
/// Shows a one-button informational alert for a document-open outcome.
|
||
private func presentOpenInfo(title: String, message: String) {
|
||
let alert: NSAlert = NSAlert()
|
||
alert.messageText = title
|
||
alert.informativeText = message
|
||
alert.addButton(withTitle: "OK")
|
||
alert.runModal()
|
||
}
|
||
|
||
func applicationWillTerminate(_ notification: Notification) {
|
||
RigStore.save(shoeGaze)
|
||
// Ensure any in-flight background rig-library writes finish before exit.
|
||
library.flushPendingWrites()
|
||
engine.stop()
|
||
}
|
||
|
||
func applicationDidResignActive(_ notification: Notification) {
|
||
// Persist on every deactivation too, so state survives an unexpected exit.
|
||
RigStore.save(shoeGaze)
|
||
}
|
||
|
||
// 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
|
||
// Per-rig commands forward to the in-window builder (which owns the current-rig state and
|
||
// the naming prompts) via notifications.
|
||
addItem(to: fileMenu, title: "New Rig", action: #selector(newRigAction(_:)), key: "n")
|
||
addItem(to: fileMenu, title: "Save Rig", action: #selector(saveRigAction(_:)), key: "s")
|
||
fileMenu.addItem(NSMenuItem.separator())
|
||
// The whole-library archive: a single file holding every rig, for backup or transfer.
|
||
addItem(to: fileMenu, title: "Export Archive…", action: #selector(exportArchiveAction(_:)), key: "e")
|
||
addItem(to: fileMenu, title: "Import Archive…", action: #selector(importArchiveAction(_:)), key: "i")
|
||
|
||
// 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")
|
||
boardMenu.addItem(NSMenuItem.separator())
|
||
// ⌘Z toggles rig mute (a hard silence of all output; distinct from Bypass Rig's dry
|
||
// passthrough). Owns the ⌘Z key equivalent on macOS; the in-window view binds it on iOS.
|
||
self.muteMenuItem = addItem(
|
||
to: boardMenu,
|
||
title: "Mute Rig",
|
||
action: #selector(toggleMuteAction(_:)),
|
||
key: "z"
|
||
)
|
||
// Bypass Rig routes every board to its dry input (pedals skipped) — distinct from Mute's
|
||
// hard silence. No key equivalent: ⌘B is Add Board, and Bypass has a prominent on-screen button.
|
||
self.bypassMenuItem = addItem(
|
||
to: boardMenu,
|
||
title: "Bypass Rig",
|
||
action: #selector(toggleBypassAction(_:)),
|
||
key: ""
|
||
)
|
||
|
||
// Rigs menu — a Set List of the top ten library rigs, each on ⌘⇧1…⌘⇧0. The items are
|
||
// fixed; their titles refresh to the current library order on open, and their key
|
||
// equivalents fire whether or not the menu is showing.
|
||
let rigsMenuItem: NSMenuItem = NSMenuItem()
|
||
mainMenu.addItem(rigsMenuItem)
|
||
let rigsMenu: NSMenu = NSMenu(title: "Rigs")
|
||
rigsMenuItem.submenu = rigsMenu
|
||
let setListItem: NSMenuItem = NSMenuItem(title: "Set List", action: nil, keyEquivalent: "")
|
||
rigsMenu.addItem(setListItem)
|
||
let setListSubmenu: NSMenu = NSMenu(title: "Set List")
|
||
setListSubmenu.delegate = self
|
||
setListItem.submenu = setListSubmenu
|
||
for slot: Int in 0 ..< AppDelegate.setListSlotCount {
|
||
// Slots 0…8 → ⌘⇧1…⌘⇧9; slot 9 → ⌘⇧0 (matches the physical number row).
|
||
let key: String = slot < 9 ? "\(slot + 1)" : "0"
|
||
let item: NSMenuItem = NSMenuItem(
|
||
title: "\(slot + 1). —",
|
||
action: #selector(loadRigSlotAction(_:)),
|
||
keyEquivalent: key
|
||
)
|
||
item.keyEquivalentModifierMask = [.command, .shift]
|
||
item.target = self
|
||
item.tag = slot
|
||
setListSubmenu.addItem(item)
|
||
setListMenuItems.append(item)
|
||
}
|
||
self.setListMenu = setListSubmenu
|
||
|
||
// 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
|
||
)
|
||
|
||
// Help menu — opens the in-app guide.
|
||
let helpMenuItem: NSMenuItem = NSMenuItem()
|
||
mainMenu.addItem(helpMenuItem)
|
||
let helpMenu: NSMenu = NSMenu(title: "Help")
|
||
helpMenuItem.submenu = helpMenu
|
||
addItem(to: helpMenu, title: "ShoeGaze Help", action: #selector(showHelpAction(_:)), key: "?")
|
||
|
||
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
|
||
|
||
/// Opens (or re-opens) the Help window hosting the shared ``HelpView``.
|
||
@objc private func showHelpAction(_ sender: Any?) {
|
||
let helpWidth: CGFloat = 560
|
||
let helpHeight: CGFloat = 720
|
||
if helpWindow == nil {
|
||
helpWindow = LyrebirdWindow(title: "ShoeGaze Help", width: helpWidth, height: helpHeight)
|
||
}
|
||
helpWindow?.open {
|
||
HelpView()
|
||
}
|
||
}
|
||
|
||
@objc private func newRigAction(_ sender: Any?) {
|
||
// Forward to the builder view, which owns the current-rig state and naming prompt.
|
||
NotificationCenter.default.post(name: .shoeGazeNewRig, object: nil)
|
||
}
|
||
|
||
@objc private func saveRigAction(_ sender: Any?) {
|
||
NotificationCenter.default.post(name: .shoeGazeSaveRig, object: nil)
|
||
}
|
||
|
||
@objc private func exportArchiveAction(_ sender: Any?) {
|
||
let panel: NSSavePanel = NSSavePanel()
|
||
panel.allowedContentTypes = [.shoeGaze]
|
||
panel.nameFieldStringValue =
|
||
"\(AppDelegate.defaultArchiveFileName).\(ShoeGazeDocument.fileExtension)"
|
||
panel.canCreateDirectories = true
|
||
let rigLibrary: RigLibraryStore = library
|
||
panel.begin { response in
|
||
guard response == .OK, let url: URL = panel.url else { return }
|
||
do { try rigLibrary.exportDocumentData().write(to: url, options: .atomic) }
|
||
catch { print("[ShoeGazeBuilder] export library failed: \(error)") }
|
||
}
|
||
}
|
||
|
||
@objc private func importArchiveAction(_ sender: Any?) {
|
||
let panel: NSOpenPanel = NSOpenPanel()
|
||
// Accept the .shoegaze document plus legacy plain-JSON archives.
|
||
panel.allowedContentTypes = [.shoeGaze, .json]
|
||
panel.canChooseDirectories = false
|
||
panel.allowsMultipleSelection = false
|
||
let rigLibrary: RigLibraryStore = library
|
||
panel.begin { response in
|
||
guard response == .OK, let url: URL = panel.url else { return }
|
||
do {
|
||
let data: Data = try Data(contentsOf: url)
|
||
_ = try rigLibrary.importArchive(from: data)
|
||
} catch {
|
||
print("[ShoeGazeBuilder] import library failed: \(error)")
|
||
}
|
||
}
|
||
}
|
||
|
||
@objc private func toggleMuteAction(_ sender: Any?) {
|
||
shoeGaze.toggleRigMuted()
|
||
// Reflect the new state immediately, not only on the next menu-open validation.
|
||
muteMenuItem?.title = shoeGaze.rigMuted ? "Unmute Rig" : "Mute Rig"
|
||
muteMenuItem?.state = shoeGaze.rigMuted ? .on : .off
|
||
}
|
||
|
||
@objc private func toggleBypassAction(_ sender: Any?) {
|
||
shoeGaze.toggleRigBypassed()
|
||
bypassMenuItem?.title = shoeGaze.rigBypassed ? "Re-engage Rig" : "Bypass Rig"
|
||
bypassMenuItem?.state = shoeGaze.rigBypassed ? .on : .off
|
||
}
|
||
|
||
/// Loads the set-list rig at the sender's slot tag. Forwards to the in-window builder (which
|
||
/// owns the current-rig state, the unsaved-changes prompt, and engine lifecycle) via notification.
|
||
@objc private func loadRigSlotAction(_ sender: NSMenuItem) {
|
||
NotificationCenter.default.post(name: .shoeGazeLoadRigSlot, object: sender.tag)
|
||
}
|
||
|
||
@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"
|
||
}
|
||
|
||
// MARK: - NSMenuDelegate
|
||
|
||
/// Refreshes the Set List item titles to the current library order each time the submenu opens.
|
||
/// Key equivalents fire independently of this (see `setListMenuItems`); this is display only.
|
||
func menuNeedsUpdate(_ menu: NSMenu) {
|
||
guard menu === setListMenu else { return }
|
||
let entries: [RigEntry] = library.entries
|
||
for item: NSMenuItem in setListMenuItems {
|
||
let slot: Int = item.tag
|
||
if slot < entries.count {
|
||
item.title = "\(slot + 1). \(entries[slot].name)"
|
||
} else {
|
||
item.title = "\(slot + 1). —"
|
||
}
|
||
}
|
||
}
|
||
|
||
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
|
||
}
|
||
if menuItem == muteMenuItem {
|
||
// Mute may have changed from the UI, MIDI, or the tuner — resync title + checkmark.
|
||
menuItem.title = shoeGaze.rigMuted ? "Unmute Rig" : "Mute Rig"
|
||
menuItem.state = shoeGaze.rigMuted ? .on : .off
|
||
return true
|
||
}
|
||
if menuItem == bypassMenuItem {
|
||
// Bypass may have changed from the UI or MIDI — resync title + checkmark.
|
||
menuItem.title = shoeGaze.rigBypassed ? "Re-engage Rig" : "Bypass Rig"
|
||
menuItem.state = shoeGaze.rigBypassed ? .on : .off
|
||
return true
|
||
}
|
||
if setListMenuItems.contains(menuItem) {
|
||
// A slot is live only when the library actually holds a rig at that position.
|
||
return menuItem.tag < library.entries.count
|
||
}
|
||
return true
|
||
}
|
||
}
|
||
#endif
|