Compare commits
1 Commits
1c03e39eac
...
v1.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
| ca1ee503cc |
@@ -1,288 +0,0 @@
|
|||||||
// LyrebirdScratchMenuController.swift
|
|
||||||
// Lyrebird
|
|
||||||
//
|
|
||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
||||||
// SPDX-License-Identifier: MIT
|
|
||||||
|
|
||||||
#if os(macOS)
|
|
||||||
import AppKit
|
|
||||||
import UniformTypeIdentifiers
|
|
||||||
import LyrebirdSynth
|
|
||||||
import LyrebirdLiveCompile
|
|
||||||
|
|
||||||
/// Builds and installs the macOS application menu bar for a live-coding host
|
|
||||||
/// driven by a `LyrebirdScratchModel`. Owns the action targets so menu items
|
|
||||||
/// stay wired for the lifetime of the controller.
|
|
||||||
@MainActor
|
|
||||||
public final class LyrebirdScratchMenuController: NSObject {
|
|
||||||
|
|
||||||
public let model: LyrebirdScratchModel
|
|
||||||
|
|
||||||
public init(model: LyrebirdScratchModel) {
|
|
||||||
self.model = model
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Construct the full menu bar (App / File / Edit / Run / View / Window /
|
|
||||||
/// Help) and assign it to `NSApplication.shared.mainMenu`.
|
|
||||||
public func installMainMenu(appName: String = "LyrebirdScratchDemo") {
|
|
||||||
let mainMenu: NSMenu = NSMenu()
|
|
||||||
|
|
||||||
mainMenu.addItem(appMenuItem(appName: appName))
|
|
||||||
mainMenu.addItem(fileMenuItem())
|
|
||||||
mainMenu.addItem(editMenuItem())
|
|
||||||
mainMenu.addItem(runMenuItem())
|
|
||||||
mainMenu.addItem(viewMenuItem())
|
|
||||||
mainMenu.addItem(windowMenuItem())
|
|
||||||
|
|
||||||
NSApplication.shared.mainMenu = mainMenu
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: App menu
|
|
||||||
|
|
||||||
private func appMenuItem(appName: String) -> NSMenuItem {
|
|
||||||
let item: NSMenuItem = NSMenuItem()
|
|
||||||
let menu: NSMenu = NSMenu(title: appName)
|
|
||||||
menu.addItem(NSMenuItem(title: "About \(appName)",
|
|
||||||
action: #selector(NSApplication.orderFrontStandardAboutPanel(_:)),
|
|
||||||
keyEquivalent: ""))
|
|
||||||
menu.addItem(NSMenuItem.separator())
|
|
||||||
let services: NSMenuItem = NSMenuItem(title: "Services", action: nil, keyEquivalent: "")
|
|
||||||
let servicesMenu: NSMenu = NSMenu(title: "Services")
|
|
||||||
services.submenu = servicesMenu
|
|
||||||
NSApplication.shared.servicesMenu = servicesMenu
|
|
||||||
menu.addItem(services)
|
|
||||||
menu.addItem(NSMenuItem.separator())
|
|
||||||
menu.addItem(NSMenuItem(title: "Hide \(appName)",
|
|
||||||
action: #selector(NSApplication.hide(_:)),
|
|
||||||
keyEquivalent: "h"))
|
|
||||||
let hideOthers: NSMenuItem = NSMenuItem(title: "Hide Others",
|
|
||||||
action: #selector(NSApplication.hideOtherApplications(_:)),
|
|
||||||
keyEquivalent: "h")
|
|
||||||
hideOthers.keyEquivalentModifierMask = [.command, .option]
|
|
||||||
menu.addItem(hideOthers)
|
|
||||||
menu.addItem(NSMenuItem(title: "Show All",
|
|
||||||
action: #selector(NSApplication.unhideAllApplications(_:)),
|
|
||||||
keyEquivalent: ""))
|
|
||||||
menu.addItem(NSMenuItem.separator())
|
|
||||||
menu.addItem(NSMenuItem(title: "Quit \(appName)",
|
|
||||||
action: #selector(NSApplication.terminate(_:)),
|
|
||||||
keyEquivalent: "q"))
|
|
||||||
item.submenu = menu
|
|
||||||
return item
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: File menu
|
|
||||||
|
|
||||||
private func fileMenuItem() -> NSMenuItem {
|
|
||||||
let item: NSMenuItem = NSMenuItem()
|
|
||||||
let menu: NSMenu = NSMenu(title: "File")
|
|
||||||
menu.addItem(target(NSMenuItem(title: "New",
|
|
||||||
action: #selector(newSnippet(_:)),
|
|
||||||
keyEquivalent: "n")))
|
|
||||||
menu.addItem(target(NSMenuItem(title: "Open…",
|
|
||||||
action: #selector(openSnippet(_:)),
|
|
||||||
keyEquivalent: "o")))
|
|
||||||
menu.addItem(NSMenuItem.separator())
|
|
||||||
menu.addItem(target(NSMenuItem(title: "Save",
|
|
||||||
action: #selector(saveSnippet(_:)),
|
|
||||||
keyEquivalent: "s")))
|
|
||||||
let saveAs: NSMenuItem = NSMenuItem(title: "Save As…",
|
|
||||||
action: #selector(saveSnippetAs(_:)),
|
|
||||||
keyEquivalent: "s")
|
|
||||||
saveAs.keyEquivalentModifierMask = [.command, .shift]
|
|
||||||
menu.addItem(target(saveAs))
|
|
||||||
menu.addItem(NSMenuItem.separator())
|
|
||||||
menu.addItem(NSMenuItem(title: "Close",
|
|
||||||
action: #selector(NSWindow.performClose(_:)),
|
|
||||||
keyEquivalent: "w"))
|
|
||||||
item.submenu = menu
|
|
||||||
return item
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: Edit menu — wires to the first responder so NSTextView gets it
|
|
||||||
|
|
||||||
private func editMenuItem() -> NSMenuItem {
|
|
||||||
let item: NSMenuItem = NSMenuItem()
|
|
||||||
let menu: NSMenu = NSMenu(title: "Edit")
|
|
||||||
menu.addItem(NSMenuItem(title: "Undo",
|
|
||||||
action: Selector(("undo:")),
|
|
||||||
keyEquivalent: "z"))
|
|
||||||
let redo: NSMenuItem = NSMenuItem(title: "Redo",
|
|
||||||
action: Selector(("redo:")),
|
|
||||||
keyEquivalent: "z")
|
|
||||||
redo.keyEquivalentModifierMask = [.command, .shift]
|
|
||||||
menu.addItem(redo)
|
|
||||||
menu.addItem(NSMenuItem.separator())
|
|
||||||
menu.addItem(NSMenuItem(title: "Cut",
|
|
||||||
action: #selector(NSText.cut(_:)),
|
|
||||||
keyEquivalent: "x"))
|
|
||||||
menu.addItem(NSMenuItem(title: "Copy",
|
|
||||||
action: #selector(NSText.copy(_:)),
|
|
||||||
keyEquivalent: "c"))
|
|
||||||
menu.addItem(NSMenuItem(title: "Paste",
|
|
||||||
action: #selector(NSText.paste(_:)),
|
|
||||||
keyEquivalent: "v"))
|
|
||||||
menu.addItem(NSMenuItem(title: "Select All",
|
|
||||||
action: #selector(NSText.selectAll(_:)),
|
|
||||||
keyEquivalent: "a"))
|
|
||||||
menu.addItem(NSMenuItem.separator())
|
|
||||||
let find: NSMenuItem = NSMenuItem(title: "Find…",
|
|
||||||
action: #selector(NSTextView.performFindPanelAction(_:)),
|
|
||||||
keyEquivalent: "f")
|
|
||||||
find.tag = Int(NSFindPanelAction.showFindPanel.rawValue)
|
|
||||||
menu.addItem(find)
|
|
||||||
item.submenu = menu
|
|
||||||
return item
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: Run menu
|
|
||||||
|
|
||||||
private func runMenuItem() -> NSMenuItem {
|
|
||||||
let item: NSMenuItem = NSMenuItem()
|
|
||||||
let menu: NSMenu = NSMenu(title: "Run")
|
|
||||||
menu.addItem(target(NSMenuItem(title: "Run",
|
|
||||||
action: #selector(runSnippet(_:)),
|
|
||||||
keyEquivalent: "\r")))
|
|
||||||
let runAdd: NSMenuItem = NSMenuItem(title: "Run Additive",
|
|
||||||
action: #selector(runSnippetAdditive(_:)),
|
|
||||||
keyEquivalent: "\r")
|
|
||||||
runAdd.keyEquivalentModifierMask = [.command, .shift]
|
|
||||||
menu.addItem(target(runAdd))
|
|
||||||
menu.addItem(NSMenuItem.separator())
|
|
||||||
menu.addItem(target(NSMenuItem(title: "Clear Tracked Synths",
|
|
||||||
action: #selector(clearSynths(_:)),
|
|
||||||
keyEquivalent: "k")))
|
|
||||||
item.submenu = menu
|
|
||||||
return item
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: View menu
|
|
||||||
|
|
||||||
private func viewMenuItem() -> NSMenuItem {
|
|
||||||
let item: NSMenuItem = NSMenuItem()
|
|
||||||
let menu: NSMenu = NSMenu(title: "View")
|
|
||||||
let wrap: NSMenuItem = target(NSMenuItem(title: "Wrap Lines",
|
|
||||||
action: #selector(toggleWrap(_:)),
|
|
||||||
keyEquivalent: "l"))
|
|
||||||
wrap.keyEquivalentModifierMask = [.command, .option]
|
|
||||||
menu.addItem(wrap)
|
|
||||||
menu.addItem(NSMenuItem.separator())
|
|
||||||
let inc: NSMenuItem = target(NSMenuItem(title: "Increase Font Size",
|
|
||||||
action: #selector(increaseFontSize(_:)),
|
|
||||||
keyEquivalent: "+"))
|
|
||||||
menu.addItem(inc)
|
|
||||||
menu.addItem(target(NSMenuItem(title: "Decrease Font Size",
|
|
||||||
action: #selector(decreaseFontSize(_:)),
|
|
||||||
keyEquivalent: "-")))
|
|
||||||
menu.addItem(target(NSMenuItem(title: "Reset Font Size",
|
|
||||||
action: #selector(resetFontSize(_:)),
|
|
||||||
keyEquivalent: "0")))
|
|
||||||
item.submenu = menu
|
|
||||||
return item
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: Window menu
|
|
||||||
|
|
||||||
private func windowMenuItem() -> NSMenuItem {
|
|
||||||
let item: NSMenuItem = NSMenuItem()
|
|
||||||
let menu: NSMenu = NSMenu(title: "Window")
|
|
||||||
menu.addItem(NSMenuItem(title: "Minimize",
|
|
||||||
action: #selector(NSWindow.performMiniaturize(_:)),
|
|
||||||
keyEquivalent: "m"))
|
|
||||||
menu.addItem(NSMenuItem(title: "Zoom",
|
|
||||||
action: #selector(NSWindow.performZoom(_:)),
|
|
||||||
keyEquivalent: ""))
|
|
||||||
menu.addItem(NSMenuItem.separator())
|
|
||||||
menu.addItem(NSMenuItem(title: "Bring All to Front",
|
|
||||||
action: #selector(NSApplication.arrangeInFront(_:)),
|
|
||||||
keyEquivalent: ""))
|
|
||||||
item.submenu = menu
|
|
||||||
NSApplication.shared.windowsMenu = menu
|
|
||||||
return item
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Action targets
|
|
||||||
|
|
||||||
private func target(_ item: NSMenuItem) -> NSMenuItem {
|
|
||||||
item.target = self
|
|
||||||
return item
|
|
||||||
}
|
|
||||||
|
|
||||||
@objc private func newSnippet(_ sender: Any?) {
|
|
||||||
model.text = LyrebirdScratchModel.defaultPlaceholder
|
|
||||||
}
|
|
||||||
|
|
||||||
@objc private func openSnippet(_ sender: Any?) {
|
|
||||||
let panel: NSOpenPanel = NSOpenPanel()
|
|
||||||
panel.allowedContentTypes = [.swiftSource]
|
|
||||||
panel.allowsMultipleSelection = false
|
|
||||||
panel.canChooseDirectories = false
|
|
||||||
panel.message = "Open a Lyrebird snippet"
|
|
||||||
if panel.runModal() == .OK, let url: URL = panel.url {
|
|
||||||
do {
|
|
||||||
try model.load(from: url)
|
|
||||||
} catch {
|
|
||||||
model.reportLoadError(url: url, error: error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@objc private func saveSnippet(_ sender: Any?) {
|
|
||||||
if let url: URL = model.documentURL {
|
|
||||||
do {
|
|
||||||
try model.save(to: url)
|
|
||||||
} catch {
|
|
||||||
model.reportSaveError(url: url, error: error)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
saveSnippetAs(sender)
|
|
||||||
}
|
|
||||||
|
|
||||||
@objc private func saveSnippetAs(_ sender: Any?) {
|
|
||||||
let panel: NSSavePanel = NSSavePanel()
|
|
||||||
panel.allowedContentTypes = [.swiftSource]
|
|
||||||
panel.nameFieldStringValue = model.documentURL?.lastPathComponent ?? "snippet.swift"
|
|
||||||
panel.message = "Save Lyrebird snippet"
|
|
||||||
if panel.runModal() == .OK, let url: URL = panel.url {
|
|
||||||
do {
|
|
||||||
try model.save(to: url)
|
|
||||||
} catch {
|
|
||||||
model.reportSaveError(url: url, error: error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@objc private func runSnippet(_ sender: Any?) {
|
|
||||||
Task { @MainActor in _ = await model.run(additive: false) }
|
|
||||||
}
|
|
||||||
|
|
||||||
@objc private func runSnippetAdditive(_ sender: Any?) {
|
|
||||||
Task { @MainActor in _ = await model.run(additive: true) }
|
|
||||||
}
|
|
||||||
|
|
||||||
@objc private func clearSynths(_ sender: Any?) {
|
|
||||||
model.clearTracked()
|
|
||||||
}
|
|
||||||
|
|
||||||
@objc private func toggleWrap(_ sender: Any?) {
|
|
||||||
model.toggleWrapsLines()
|
|
||||||
if let item: NSMenuItem = sender as? NSMenuItem {
|
|
||||||
item.state = model.wrapsLines ? .on : .off
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@objc private func increaseFontSize(_ sender: Any?) {
|
|
||||||
model.bumpFontSize(by: 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
@objc private func decreaseFontSize(_ sender: Any?) {
|
|
||||||
model.bumpFontSize(by: -1)
|
|
||||||
}
|
|
||||||
|
|
||||||
@objc private func resetFontSize(_ sender: Any?) {
|
|
||||||
model.resetFontSize()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#endif
|
|
||||||
@@ -1,231 +0,0 @@
|
|||||||
// LyrebirdScratchModel.swift
|
|
||||||
// Lyrebird
|
|
||||||
//
|
|
||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
||||||
// SPDX-License-Identifier: MIT
|
|
||||||
|
|
||||||
// LyrebirdUI/LiveCompile
|
|
||||||
//
|
|
||||||
// Backing model for `LyrebirdScratchView`. Owns the editable snippet text, the
|
|
||||||
// most recent compile result, and the host `LiveSession`. Pulled out of the
|
|
||||||
// view so logic can be exercised without instantiating SwiftUI.
|
|
||||||
//
|
|
||||||
// macOS only — wraps `LyrebirdLiveCompile`, which itself is macOS-only.
|
|
||||||
|
|
||||||
#if os(macOS)
|
|
||||||
import Foundation
|
|
||||||
import CoreGraphics
|
|
||||||
import LyrebirdSynth
|
|
||||||
// Re-exported so consumers that link only the `LyrebirdLiveCompileUI` product
|
|
||||||
// (e.g. the LyrebirdScratchDemo app) get the `LyrebirdLiveCompile` API
|
|
||||||
// (`LiveSession`, …) without separately linking the `LyrebirdLiveCompile`
|
|
||||||
// dynamic product — which clashes in Xcode with the static target embed.
|
|
||||||
@_exported import LyrebirdLiveCompile
|
|
||||||
|
|
||||||
/// Observable backing model for `LyrebirdScratchView`.
|
|
||||||
///
|
|
||||||
/// Drives one live-coding editor pane. `run(additive:)` awaits
|
|
||||||
/// `LiveSession.compileAndRunAsync` so the swiftc invocation runs off the main
|
|
||||||
/// actor and the editor stays responsive. ``isCompiling`` flips around the
|
|
||||||
/// await so SwiftUI can disable the Run buttons and surface a "Compiling…"
|
|
||||||
/// status while the dylib build is in flight.
|
|
||||||
@MainActor
|
|
||||||
public final class LyrebirdScratchModel: ObservableObject {
|
|
||||||
|
|
||||||
/// Default placeholder text loaded into a fresh model. Walks the user
|
|
||||||
/// through the two keyboard shortcuts and the in-snippet API surface.
|
|
||||||
/// `nonisolated` so callers in a non-main context (e.g. SwiftUI init's
|
|
||||||
/// default-argument evaluation, which is not implicitly main-actor) can
|
|
||||||
/// reference it without a Swift 6 isolation diagnostic.
|
|
||||||
public nonisolated static let defaultPlaceholder: String = """
|
|
||||||
// ⌘↩ — compile + run (removes synths from the previous run first).
|
|
||||||
// ⌘⇧↩ — additive run (keep previously played synths around).
|
|
||||||
//
|
|
||||||
// The snippet body has `context: SnippetContext` in scope.
|
|
||||||
// `context.engine` → the host `SynthesisEngine`.
|
|
||||||
// `context.play(synth)` → adds a `Synthesizer` and tracks it for cleanup.
|
|
||||||
// `context.reportMessage(_)`→ writes back to the host (useful for `print`-style probes).
|
|
||||||
|
|
||||||
class SineSynth: SynthesizerBase {
|
|
||||||
override func build() {
|
|
||||||
let sine = OscSin.Audio(freq: 440, mul: 0.15)
|
|
||||||
let stereo = Pan2(input: sine, pan: 0)
|
|
||||||
output(bus: 0, source: stereo)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let synth = SineSynth()
|
|
||||||
_ = context.play(synth)
|
|
||||||
context.reportMessage("playing 440 Hz sine — stereo, centered")
|
|
||||||
|
|
||||||
"""
|
|
||||||
|
|
||||||
/// Current editor text. View binds to this; user edits flow back here via
|
|
||||||
/// the `NSTextView` delegate inside `LyrebirdScratchView`.
|
|
||||||
@Published public var text: String
|
|
||||||
|
|
||||||
/// Parsed swiftc diagnostics from the last `run(additive:)` invocation.
|
|
||||||
/// Empty when the last run compiled cleanly or has not yet been attempted.
|
|
||||||
@Published public private(set) var diagnostics: [Diagnostic] = []
|
|
||||||
|
|
||||||
/// Single-line human-readable status line shown beneath the editor.
|
|
||||||
/// Updated by `run(additive:)` and `clearTracked()`.
|
|
||||||
@Published public private(set) var statusMessage: String = ""
|
|
||||||
|
|
||||||
/// Mirror of `session.trackedSynthCount`, refreshed after every `run` /
|
|
||||||
/// `clearTracked` call so the toolbar can show the count without polling.
|
|
||||||
@Published public private(set) var trackedSynthCount: Int
|
|
||||||
|
|
||||||
/// `true` while a `run(additive:)` invocation is awaiting the background
|
|
||||||
/// swiftc compile. View code disables Run / Run Additive buttons against
|
|
||||||
/// this so a second compile cannot stack on top of a still-running one.
|
|
||||||
@Published public private(set) var isCompiling: Bool = false
|
|
||||||
|
|
||||||
/// URL of the file the editor text was last saved to or loaded from. `nil`
|
|
||||||
/// when the editor holds unsaved scratch content. The view uses this to
|
|
||||||
/// distinguish a silent overwrite (⌘S) from a Save As… prompt.
|
|
||||||
@Published public private(set) var documentURL: URL?
|
|
||||||
|
|
||||||
/// Editor font size in points. Clamped to `[minFontSize, maxFontSize]`.
|
|
||||||
@Published public var fontSize: CGFloat = 13
|
|
||||||
|
|
||||||
/// When `true`, lines wrap at the editor's right edge instead of scrolling
|
|
||||||
/// horizontally.
|
|
||||||
@Published public var wrapsLines: Bool = true
|
|
||||||
|
|
||||||
public let session: LiveSession
|
|
||||||
|
|
||||||
public nonisolated static let minFontSize: CGFloat = 9
|
|
||||||
public nonisolated static let maxFontSize: CGFloat = 32
|
|
||||||
public nonisolated static let defaultFontSize: CGFloat = 13
|
|
||||||
|
|
||||||
public func bumpFontSize(by delta: CGFloat) {
|
|
||||||
fontSize = max(LyrebirdScratchModel.minFontSize,
|
|
||||||
min(LyrebirdScratchModel.maxFontSize, fontSize + delta))
|
|
||||||
}
|
|
||||||
|
|
||||||
public func resetFontSize() {
|
|
||||||
fontSize = LyrebirdScratchModel.defaultFontSize
|
|
||||||
}
|
|
||||||
|
|
||||||
public func toggleWrapsLines() {
|
|
||||||
wrapsLines.toggle()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// - Parameters:
|
|
||||||
/// - session: Host `LiveSession` the model forwards compile + cleanup
|
|
||||||
/// calls to. Retained for the model's lifetime.
|
|
||||||
/// - initialText: Seed text loaded into `text`. Defaults to
|
|
||||||
/// ``defaultPlaceholder``.
|
|
||||||
public init(
|
|
||||||
session: LiveSession,
|
|
||||||
initialText: String = LyrebirdScratchModel.defaultPlaceholder
|
|
||||||
) {
|
|
||||||
self.session = session
|
|
||||||
self.text = initialText
|
|
||||||
self.trackedSynthCount = session.trackedSynthCount
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Compile and execute the current `text`. Updates `diagnostics`,
|
|
||||||
/// `statusMessage`, `trackedSynthCount`, and ``isCompiling``.
|
|
||||||
///
|
|
||||||
/// Awaits `LiveSession.compileAndRunAsync`, which runs swiftc on a
|
|
||||||
/// `Task.detached`. The view's Run / Run Additive buttons bind to
|
|
||||||
/// ``isCompiling`` and stay disabled until this method returns.
|
|
||||||
///
|
|
||||||
/// - Parameter additive: When `false`, the session removes every
|
|
||||||
/// previously tracked synth before running. When `true`, prior synths
|
|
||||||
/// stay in the engine (⌘⇧↩ in the view).
|
|
||||||
/// - Returns: `true` when the snippet compiled and its entry returned
|
|
||||||
/// without throwing; `false` otherwise.
|
|
||||||
@discardableResult
|
|
||||||
public func run(additive: Bool) async -> Bool {
|
|
||||||
guard !isCompiling else { return false }
|
|
||||||
let body: String = text
|
|
||||||
diagnostics = []
|
|
||||||
statusMessage = "Compiling…"
|
|
||||||
isCompiling = true
|
|
||||||
defer {
|
|
||||||
isCompiling = false
|
|
||||||
trackedSynthCount = session.trackedSynthCount
|
|
||||||
}
|
|
||||||
do {
|
|
||||||
try await session.compileAndRunAsync(body, additive: additive)
|
|
||||||
let mode: String = additive ? "additive" : "replaced"
|
|
||||||
statusMessage = "Ran (\(mode)). Tracked synths: \(session.trackedSynthCount)."
|
|
||||||
return true
|
|
||||||
} catch let sessionError as LiveSessionError {
|
|
||||||
switch sessionError {
|
|
||||||
case .snippetCompileFailed(let diags, let underlying):
|
|
||||||
if diags.isEmpty {
|
|
||||||
diagnostics = [Diagnostic(
|
|
||||||
line: nil,
|
|
||||||
column: 0,
|
|
||||||
severity: .error,
|
|
||||||
message: "\(underlying)",
|
|
||||||
rawLine: 0
|
|
||||||
)]
|
|
||||||
statusMessage = "Compile failed — see diagnostics below."
|
|
||||||
} else {
|
|
||||||
diagnostics = diags
|
|
||||||
let plural: String = diags.count == 1 ? "" : "s"
|
|
||||||
statusMessage = "Compile failed — \(diags.count) diagnostic\(plural)."
|
|
||||||
}
|
|
||||||
case .compilerError(let underlying):
|
|
||||||
statusMessage = "Compiler error: \(underlying)"
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
} catch {
|
|
||||||
statusMessage = "Error: \(error)"
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Forward to `LiveSession.clearTracked()` and refresh `trackedSynthCount`.
|
|
||||||
public func clearTracked() {
|
|
||||||
session.clearTracked()
|
|
||||||
trackedSynthCount = session.trackedSynthCount
|
|
||||||
statusMessage = "Cleared tracked synths."
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Snippet save / load
|
|
||||||
|
|
||||||
/// Replace `text` with the UTF-8 contents at `url`, set ``documentURL``
|
|
||||||
/// for subsequent saves, and refresh the status line.
|
|
||||||
///
|
|
||||||
/// - Parameter url: File to read. Caller (view) is responsible for the
|
|
||||||
/// `NSOpenPanel` UI; this method does the IO.
|
|
||||||
public func load(from url: URL) throws {
|
|
||||||
let loaded: String = try String(contentsOf: url, encoding: .utf8)
|
|
||||||
text = loaded
|
|
||||||
documentURL = url
|
|
||||||
diagnostics = []
|
|
||||||
statusMessage = "Loaded \(url.lastPathComponent)."
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Write `text` to `url` as UTF-8, set ``documentURL``, refresh status.
|
|
||||||
///
|
|
||||||
/// - Parameter url: Destination. Overwrites if present. Caller drives the
|
|
||||||
/// `NSSavePanel` UI.
|
|
||||||
public func save(to url: URL) throws {
|
|
||||||
try text.write(to: url, atomically: true, encoding: .utf8)
|
|
||||||
documentURL = url
|
|
||||||
statusMessage = "Saved \(url.lastPathComponent)."
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Surface a load failure on the status line without throwing across the
|
|
||||||
/// view layer. Called by the view after `NSOpenPanel` returned a URL that
|
|
||||||
/// `load(from:)` rejected.
|
|
||||||
public func reportLoadError(url: URL, error: Error) {
|
|
||||||
statusMessage = "Load failed (\(url.lastPathComponent)): \(error.localizedDescription)"
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Surface a save failure on the status line without throwing across the
|
|
||||||
/// view layer. Called by the view after `NSSavePanel` returned a URL that
|
|
||||||
/// `save(to:)` rejected.
|
|
||||||
public func reportSaveError(url: URL, error: Error) {
|
|
||||||
statusMessage = "Save failed (\(url.lastPathComponent)): \(error.localizedDescription)"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#endif
|
|
||||||
@@ -1,409 +0,0 @@
|
|||||||
// LyrebirdScratchView.swift
|
|
||||||
// Lyrebird
|
|
||||||
//
|
|
||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
||||||
// SPDX-License-Identifier: MIT
|
|
||||||
|
|
||||||
// LyrebirdUI/LiveCompile
|
|
||||||
//
|
|
||||||
// `LyrebirdScratchView` — SwiftUI scratchpad editor for live-coded snippets.
|
|
||||||
// Wraps an `NSTextView` for the editor surface, drives a `LyrebirdScratchModel`
|
|
||||||
// for compile state, and surfaces parsed `Diagnostic`s in a scrollable list
|
|
||||||
// below the editor. macOS-only; iOS hosting is deferred (no swiftc on device).
|
|
||||||
|
|
||||||
#if os(macOS)
|
|
||||||
import AppKit
|
|
||||||
import SwiftUI
|
|
||||||
import UniformTypeIdentifiers
|
|
||||||
import LyrebirdSynth
|
|
||||||
import LyrebirdLiveCompile
|
|
||||||
|
|
||||||
/// SwiftUI scratchpad for live-compiled Lyrebird snippets.
|
|
||||||
///
|
|
||||||
/// Pair with a `LiveSession` that owns the audio engine, drop the view into a
|
|
||||||
/// `LyrebirdWindow`, and ⌘↩ replaces the prior run while ⌘⇧↩ adds to it.
|
|
||||||
/// Diagnostics from a failed compile are listed under the editor with the
|
|
||||||
/// user's snippet-row coordinates already mapped by `DiagnosticParser`.
|
|
||||||
///
|
|
||||||
/// - Parameters:
|
|
||||||
/// - session: Host `LiveSession` owning the `SynthesisEngine`. Forwarded
|
|
||||||
/// into the backing ``LyrebirdScratchModel``.
|
|
||||||
/// - initialText: Seed text loaded into the editor. Defaults to
|
|
||||||
/// ``LyrebirdScratchModel/defaultPlaceholder``.
|
|
||||||
///
|
|
||||||
/// ## Hosting
|
|
||||||
///
|
|
||||||
/// ```swift
|
|
||||||
/// import LyrebirdUI // LyrebirdWindow
|
|
||||||
/// import LyrebirdLiveCompile // LiveSession
|
|
||||||
/// import LyrebirdLiveCompileUI // LyrebirdScratchView
|
|
||||||
///
|
|
||||||
/// let session = LiveSession(engine: engine)
|
|
||||||
/// let win = LyrebirdWindow(title: "Lyrebird Scratch", width: 640, height: 480)
|
|
||||||
/// win.open { LyrebirdScratchView(session: session) }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ## Threading
|
|
||||||
///
|
|
||||||
/// All UI work is `@MainActor`-isolated. The Run / Run Additive buttons
|
|
||||||
/// dispatch a `Task` that awaits `LyrebirdScratchModel.run(additive:)`, which
|
|
||||||
/// itself awaits `LiveSession.compileAndRunAsync`. The swiftc subprocess runs
|
|
||||||
/// on a background `Task.detached`; the snippet entry then resumes on the
|
|
||||||
/// main actor so it can touch UI-side state. Both Run buttons disable while
|
|
||||||
/// ``LyrebirdScratchModel/isCompiling`` is `true`.
|
|
||||||
@MainActor
|
|
||||||
public struct LyrebirdScratchView: View {
|
|
||||||
|
|
||||||
@StateObject private var model: LyrebirdScratchModel
|
|
||||||
@State private var engineTick: Int = 0
|
|
||||||
private let engineRefresh = Timer.publish(every: 0.5, on: .main, in: .common).autoconnect()
|
|
||||||
|
|
||||||
/// Construct with a fresh `LyrebirdScratchModel` wrapping `session`.
|
|
||||||
///
|
|
||||||
/// - Parameters:
|
|
||||||
/// - session: Host live-coding session owning the audio engine. The view
|
|
||||||
/// does not retain a reference of its own; the wrapped model does.
|
|
||||||
/// - initialText: Seed text loaded into the editor. Defaults to the
|
|
||||||
/// onboarding placeholder explaining the two keyboard shortcuts.
|
|
||||||
public init(
|
|
||||||
session: LiveSession,
|
|
||||||
initialText: String = LyrebirdScratchModel.defaultPlaceholder
|
|
||||||
) {
|
|
||||||
_model = StateObject(wrappedValue: LyrebirdScratchModel(
|
|
||||||
session: session,
|
|
||||||
initialText: initialText
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Construct against a pre-built model. Lets tests or alternate hosts
|
|
||||||
/// inject a model with custom session, text, or pre-populated state.
|
|
||||||
public init(model: LyrebirdScratchModel) {
|
|
||||||
_model = StateObject(wrappedValue: model)
|
|
||||||
}
|
|
||||||
|
|
||||||
public var body: some View {
|
|
||||||
VStack(spacing: 0) {
|
|
||||||
engineBar
|
|
||||||
Divider()
|
|
||||||
ScratchEditor(
|
|
||||||
text: Binding(
|
|
||||||
get: { model.text },
|
|
||||||
set: { model.text = $0 }
|
|
||||||
),
|
|
||||||
fontSize: model.fontSize,
|
|
||||||
wrapsLines: model.wrapsLines
|
|
||||||
)
|
|
||||||
.frame(minHeight: editorMinHeight)
|
|
||||||
Divider()
|
|
||||||
statusBar
|
|
||||||
if !model.diagnostics.isEmpty {
|
|
||||||
Divider()
|
|
||||||
diagnosticsList
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.frame(minWidth: scratchMinWidth, minHeight: scratchMinHeight)
|
|
||||||
.onReceive(engineRefresh) { _ in engineTick &+= 1 }
|
|
||||||
}
|
|
||||||
|
|
||||||
private var engineBar: some View {
|
|
||||||
let engine: SynthesisEngine = model.session.engine
|
|
||||||
return HStack(spacing: toolbarSpacing) {
|
|
||||||
Circle()
|
|
||||||
.fill(engine.isRunning ? Color.green : Color.red)
|
|
||||||
.frame(width: engineDotSize, height: engineDotSize)
|
|
||||||
Text(engine.isRunning ? "engine running" : "engine stopped")
|
|
||||||
.font(.system(.caption, design: .monospaced))
|
|
||||||
.foregroundStyle(.secondary)
|
|
||||||
Spacer()
|
|
||||||
Text("\(Int(engine.sampleRate)) Hz · \(engine.numOutputChannels) ch · CPU \(formatCPU(engine.averageCPU))")
|
|
||||||
.font(.system(.caption, design: .monospaced))
|
|
||||||
.foregroundStyle(.secondary)
|
|
||||||
Spacer().frame(width: 8)
|
|
||||||
Text("synths: \(model.trackedSynthCount)")
|
|
||||||
.font(.system(.caption, design: .monospaced))
|
|
||||||
.foregroundStyle(.secondary)
|
|
||||||
}
|
|
||||||
.padding(.horizontal, toolbarPadding)
|
|
||||||
.padding(.vertical, 6)
|
|
||||||
.id(engineTick)
|
|
||||||
}
|
|
||||||
|
|
||||||
private func formatCPU(_ value: Double) -> String {
|
|
||||||
String(format: "%.0f%%", value * 100)
|
|
||||||
}
|
|
||||||
|
|
||||||
public func runSnippet(additive: Bool) {
|
|
||||||
Task { @MainActor in
|
|
||||||
_ = await model.run(additive: additive)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public func presentOpenPanel() {
|
|
||||||
let panel: NSOpenPanel = NSOpenPanel()
|
|
||||||
panel.allowedContentTypes = [.swiftSource]
|
|
||||||
panel.allowsMultipleSelection = false
|
|
||||||
panel.canChooseDirectories = false
|
|
||||||
panel.message = "Open a Lyrebird snippet"
|
|
||||||
if panel.runModal() == .OK, let url: URL = panel.url {
|
|
||||||
do {
|
|
||||||
try model.load(from: url)
|
|
||||||
} catch {
|
|
||||||
model.reportLoadError(url: url, error: error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public func saveOrPromptForLocation() {
|
|
||||||
if let url: URL = model.documentURL {
|
|
||||||
do {
|
|
||||||
try model.save(to: url)
|
|
||||||
} catch {
|
|
||||||
model.reportSaveError(url: url, error: error)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
presentSavePanel()
|
|
||||||
}
|
|
||||||
|
|
||||||
public func presentSavePanel() {
|
|
||||||
let panel: NSSavePanel = NSSavePanel()
|
|
||||||
panel.allowedContentTypes = [.swiftSource]
|
|
||||||
panel.nameFieldStringValue = model.documentURL?.lastPathComponent ?? "snippet.swift"
|
|
||||||
panel.message = "Save Lyrebird snippet"
|
|
||||||
if panel.runModal() == .OK, let url: URL = panel.url {
|
|
||||||
do {
|
|
||||||
try model.save(to: url)
|
|
||||||
} catch {
|
|
||||||
model.reportSaveError(url: url, error: error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private var statusBar: some View {
|
|
||||||
HStack {
|
|
||||||
Text(model.statusMessage.isEmpty ? "Ready." : model.statusMessage)
|
|
||||||
.font(.system(.caption, design: .monospaced))
|
|
||||||
.foregroundStyle(.secondary)
|
|
||||||
.lineLimit(1)
|
|
||||||
.truncationMode(.middle)
|
|
||||||
Spacer()
|
|
||||||
}
|
|
||||||
.padding(.horizontal, statusHPad)
|
|
||||||
.padding(.vertical, statusVPad)
|
|
||||||
}
|
|
||||||
|
|
||||||
private var diagnosticsList: some View {
|
|
||||||
ScrollView {
|
|
||||||
LazyVStack(alignment: .leading, spacing: diagnosticRowSpacing) {
|
|
||||||
ForEach(Array(model.diagnostics.enumerated()), id: \.offset) { _, diag in
|
|
||||||
DiagnosticRow(diagnostic: diag)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.padding(diagnosticListPadding)
|
|
||||||
}
|
|
||||||
.frame(minHeight: diagnosticsMinHeight, maxHeight: diagnosticsMaxHeight)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Layout constants — all in points. Kept private; tuned to match
|
|
||||||
// LyrebirdEngineStatusView's visual density.
|
|
||||||
private let scratchMinWidth: CGFloat = 520
|
|
||||||
private let scratchMinHeight: CGFloat = 420
|
|
||||||
private let editorMinHeight: CGFloat = 240
|
|
||||||
private let toolbarSpacing: CGFloat = 8
|
|
||||||
private let toolbarPadding: CGFloat = 8
|
|
||||||
private let toolbarDividerHeight: CGFloat = 18
|
|
||||||
private let statusHPad: CGFloat = 8
|
|
||||||
private let statusVPad: CGFloat = 4
|
|
||||||
private let diagnosticRowSpacing: CGFloat = 2
|
|
||||||
private let diagnosticListPadding: CGFloat = 8
|
|
||||||
private let diagnosticsMinHeight: CGFloat = 80
|
|
||||||
private let diagnosticsMaxHeight: CGFloat = 200
|
|
||||||
private let engineDotSize: CGFloat = 8
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One row in the diagnostics list. Renders `(line:col)`, severity, and
|
|
||||||
/// message in a compact monospaced row.
|
|
||||||
private struct DiagnosticRow: View {
|
|
||||||
|
|
||||||
let diagnostic: Diagnostic
|
|
||||||
|
|
||||||
var body: some View {
|
|
||||||
HStack(alignment: .firstTextBaseline, spacing: rowGutter) {
|
|
||||||
Text(locationString)
|
|
||||||
.font(.system(.caption, design: .monospaced))
|
|
||||||
.foregroundStyle(.secondary)
|
|
||||||
.frame(minWidth: locationColumnWidth, alignment: .leading)
|
|
||||||
Text(diagnostic.severity.rawValue)
|
|
||||||
.font(.system(.caption, design: .monospaced))
|
|
||||||
.foregroundStyle(color(for: diagnostic.severity))
|
|
||||||
.frame(minWidth: severityColumnWidth, alignment: .leading)
|
|
||||||
Text(diagnostic.message)
|
|
||||||
.font(.system(.caption, design: .monospaced))
|
|
||||||
.textSelection(.enabled)
|
|
||||||
.multilineTextAlignment(.leading)
|
|
||||||
.fixedSize(horizontal: false, vertical: true)
|
|
||||||
Spacer(minLength: 0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private var locationString: String {
|
|
||||||
if let line: Int = diagnostic.line {
|
|
||||||
return "\(line):\(diagnostic.column)"
|
|
||||||
}
|
|
||||||
return "preamble:\(diagnostic.rawLine):\(diagnostic.column)"
|
|
||||||
}
|
|
||||||
|
|
||||||
private func color(for severity: DiagnosticSeverity) -> Color {
|
|
||||||
switch severity {
|
|
||||||
case .error: return .red
|
|
||||||
case .warning: return .orange
|
|
||||||
case .note: return .secondary
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private let rowGutter: CGFloat = 8
|
|
||||||
private let locationColumnWidth: CGFloat = 80
|
|
||||||
private let severityColumnWidth: CGFloat = 56
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `NSViewRepresentable` wrapping a vanilla `NSTextView` inside an
|
|
||||||
/// `NSScrollView`. Monospaced 13 pt, plain text, no smart-quote / dash /
|
|
||||||
/// auto-correct interference — matches the editor expectations of someone
|
|
||||||
/// typing Swift code.
|
|
||||||
private struct ScratchEditor: NSViewRepresentable {
|
|
||||||
|
|
||||||
@Binding var text: String
|
|
||||||
let fontSize: CGFloat
|
|
||||||
let wrapsLines: Bool
|
|
||||||
|
|
||||||
final class Coordinator: NSObject, NSTextViewDelegate {
|
|
||||||
var parent: ScratchEditor
|
|
||||||
init(_ parent: ScratchEditor) { self.parent = parent }
|
|
||||||
|
|
||||||
func textDidChange(_ notification: Notification) {
|
|
||||||
guard let tv: NSTextView = notification.object as? NSTextView else { return }
|
|
||||||
parent.text = tv.string
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func makeCoordinator() -> Coordinator { Coordinator(self) }
|
|
||||||
|
|
||||||
func makeNSView(context: Context) -> NSScrollView {
|
|
||||||
let scroll: NSScrollView = NSTextView.scrollableTextView()
|
|
||||||
if let tv: NSTextView = scroll.documentView as? NSTextView {
|
|
||||||
configure(tv, in: scroll, with: context.coordinator)
|
|
||||||
}
|
|
||||||
return scroll
|
|
||||||
}
|
|
||||||
|
|
||||||
func updateNSView(_ scroll: NSScrollView, context: Context) {
|
|
||||||
context.coordinator.parent = self
|
|
||||||
guard let tv: NSTextView = scroll.documentView as? NSTextView else { return }
|
|
||||||
let font: NSFont = NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
|
|
||||||
let fontChanged: Bool = (tv.font?.pointSize ?? -1) != fontSize
|
|
||||||
if fontChanged {
|
|
||||||
tv.font = font
|
|
||||||
}
|
|
||||||
let paragraphStyle: NSParagraphStyle = makeParagraphStyle(for: font)
|
|
||||||
tv.defaultParagraphStyle = paragraphStyle
|
|
||||||
tv.typingAttributes = makeAttrs(font: font, paragraph: paragraphStyle)
|
|
||||||
applyWrap(to: tv, in: scroll)
|
|
||||||
if tv.string != text {
|
|
||||||
replaceText(in: tv, with: text, font: font, paragraph: paragraphStyle)
|
|
||||||
} else if fontChanged {
|
|
||||||
reapplyAttrs(to: tv, font: font, paragraph: paragraphStyle)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func makeAttrs(font: NSFont, paragraph: NSParagraphStyle) -> [NSAttributedString.Key: Any] {
|
|
||||||
[
|
|
||||||
.font: font,
|
|
||||||
.foregroundColor: NSColor.labelColor,
|
|
||||||
.paragraphStyle: paragraph,
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
private func makeParagraphStyle(for font: NSFont) -> NSParagraphStyle {
|
|
||||||
let style: NSMutableParagraphStyle = NSMutableParagraphStyle()
|
|
||||||
let spaceAdvance: CGFloat = (" " as NSString).size(withAttributes: [.font: font]).width
|
|
||||||
let tabWidth: CGFloat = spaceAdvance * tabSpaces
|
|
||||||
style.tabStops = []
|
|
||||||
style.defaultTabInterval = tabWidth
|
|
||||||
return style
|
|
||||||
}
|
|
||||||
|
|
||||||
private func replaceText(in tv: NSTextView,
|
|
||||||
with newText: String,
|
|
||||||
font: NSFont,
|
|
||||||
paragraph: NSParagraphStyle) {
|
|
||||||
let attrs: [NSAttributedString.Key : Any] = makeAttrs(font: font, paragraph: paragraph)
|
|
||||||
let attributed: NSAttributedString = NSAttributedString(string: newText, attributes: attrs)
|
|
||||||
tv.textStorage?.setAttributedString(attributed)
|
|
||||||
tv.typingAttributes = attrs
|
|
||||||
}
|
|
||||||
|
|
||||||
private func reapplyAttrs(to tv: NSTextView,
|
|
||||||
font: NSFont,
|
|
||||||
paragraph: NSParagraphStyle) {
|
|
||||||
guard let storage: NSTextStorage = tv.textStorage else { return }
|
|
||||||
let attrs: [NSAttributedString.Key : Any] = makeAttrs(font: font, paragraph: paragraph)
|
|
||||||
let range: NSRange = NSRange(location: 0, length: storage.length)
|
|
||||||
storage.setAttributes(attrs, range: range)
|
|
||||||
tv.typingAttributes = attrs
|
|
||||||
}
|
|
||||||
|
|
||||||
private func applyWrap(to tv: NSTextView, in scroll: NSScrollView) {
|
|
||||||
guard let container: NSTextContainer = tv.textContainer else { return }
|
|
||||||
if wrapsLines {
|
|
||||||
scroll.hasHorizontalScroller = false
|
|
||||||
tv.isHorizontallyResizable = false
|
|
||||||
tv.autoresizingMask = [.width]
|
|
||||||
container.widthTracksTextView = true
|
|
||||||
container.containerSize = NSSize(width: CGFloat.greatestFiniteMagnitude,
|
|
||||||
height: CGFloat.greatestFiniteMagnitude)
|
|
||||||
} else {
|
|
||||||
scroll.hasHorizontalScroller = true
|
|
||||||
tv.isHorizontallyResizable = true
|
|
||||||
tv.autoresizingMask = []
|
|
||||||
container.widthTracksTextView = false
|
|
||||||
container.containerSize = NSSize(width: CGFloat.greatestFiniteMagnitude,
|
|
||||||
height: CGFloat.greatestFiniteMagnitude)
|
|
||||||
tv.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude,
|
|
||||||
height: CGFloat.greatestFiniteMagnitude)
|
|
||||||
}
|
|
||||||
tv.needsDisplay = true
|
|
||||||
}
|
|
||||||
|
|
||||||
private func configure(_ tv: NSTextView, in scroll: NSScrollView, with coordinator: Coordinator) {
|
|
||||||
tv.delegate = coordinator
|
|
||||||
let editorFont: NSFont = NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
|
|
||||||
tv.font = editorFont
|
|
||||||
tv.isRichText = false
|
|
||||||
tv.isAutomaticQuoteSubstitutionEnabled = false
|
|
||||||
tv.isAutomaticDashSubstitutionEnabled = false
|
|
||||||
tv.isAutomaticTextReplacementEnabled = false
|
|
||||||
tv.isAutomaticSpellingCorrectionEnabled = false
|
|
||||||
tv.smartInsertDeleteEnabled = false
|
|
||||||
tv.allowsUndo = true
|
|
||||||
tv.usesFindBar = true
|
|
||||||
tv.textContainerInset = NSSize(width: editorInset, height: editorInset)
|
|
||||||
tv.drawsBackground = true
|
|
||||||
tv.backgroundColor = .textBackgroundColor
|
|
||||||
tv.textColor = .labelColor
|
|
||||||
tv.insertionPointColor = .labelColor
|
|
||||||
tv.selectedTextAttributes = [
|
|
||||||
.backgroundColor: NSColor.selectedTextBackgroundColor,
|
|
||||||
.foregroundColor: NSColor.selectedTextColor,
|
|
||||||
]
|
|
||||||
let paragraphStyle: NSParagraphStyle = makeParagraphStyle(for: editorFont)
|
|
||||||
tv.defaultParagraphStyle = paragraphStyle
|
|
||||||
tv.typingAttributes = makeAttrs(font: editorFont, paragraph: paragraphStyle)
|
|
||||||
applyWrap(to: tv, in: scroll)
|
|
||||||
replaceText(in: tv, with: text, font: editorFont, paragraph: paragraphStyle)
|
|
||||||
}
|
|
||||||
|
|
||||||
private let editorInset: CGFloat = 6
|
|
||||||
private let tabSpaces: CGFloat = 4
|
|
||||||
}
|
|
||||||
|
|
||||||
#endif
|
|
||||||
@@ -1,145 +0,0 @@
|
|||||||
// ScratchLineNumberRuler.swift
|
|
||||||
// Lyrebird
|
|
||||||
//
|
|
||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
||||||
// SPDX-License-Identifier: MIT
|
|
||||||
|
|
||||||
// LyrebirdUI/LiveCompile
|
|
||||||
//
|
|
||||||
// Vertical line-number gutter for `ScratchEditor`'s `NSTextView`. Installed as
|
|
||||||
// the scroll view's `verticalRulerView` so it tracks scroll position for free.
|
|
||||||
// Reads laid-out glyph rects from the text view's layout manager and writes one
|
|
||||||
// 1-based line label per visible line into the ruler's bounds.
|
|
||||||
|
|
||||||
#if os(macOS)
|
|
||||||
import AppKit
|
|
||||||
|
|
||||||
/// `NSRulerView` subclass rendering one right-aligned line number per laid-out
|
|
||||||
/// line of the host `NSTextView`. Tracks the text view's scroll origin via the
|
|
||||||
/// `boundsDidChangeNotification` posted by the enclosing `NSClipView` and
|
|
||||||
/// invalidates itself on every text edit and frame change.
|
|
||||||
final class ScratchLineNumberRuler: NSRulerView {
|
|
||||||
|
|
||||||
/// Re-resolved on every `draw` so the ruler picks up font / layout-manager
|
|
||||||
/// swaps the text view performs after attachment.
|
|
||||||
private weak var textView: NSTextView?
|
|
||||||
|
|
||||||
init(scrollView: NSScrollView, textView: NSTextView) {
|
|
||||||
self.textView = textView
|
|
||||||
super.init(scrollView: scrollView, orientation: .verticalRuler)
|
|
||||||
self.clientView = textView
|
|
||||||
self.ruleThickness = gutterWidth
|
|
||||||
let center: NotificationCenter = NotificationCenter.default
|
|
||||||
center.addObserver(self,
|
|
||||||
selector: #selector(invalidateForChange(_:)),
|
|
||||||
name: NSText.didChangeNotification,
|
|
||||||
object: textView)
|
|
||||||
center.addObserver(self,
|
|
||||||
selector: #selector(invalidateForChange(_:)),
|
|
||||||
name: NSView.frameDidChangeNotification,
|
|
||||||
object: textView)
|
|
||||||
let clipView: NSClipView = scrollView.contentView
|
|
||||||
clipView.postsBoundsChangedNotifications = true
|
|
||||||
center.addObserver(self,
|
|
||||||
selector: #selector(invalidateForChange(_:)),
|
|
||||||
name: NSView.boundsDidChangeNotification,
|
|
||||||
object: clipView)
|
|
||||||
}
|
|
||||||
|
|
||||||
required init(coder: NSCoder) {
|
|
||||||
fatalError("ScratchLineNumberRuler does not support NSCoder init")
|
|
||||||
}
|
|
||||||
|
|
||||||
deinit {
|
|
||||||
NotificationCenter.default.removeObserver(self)
|
|
||||||
}
|
|
||||||
|
|
||||||
@objc private func invalidateForChange(_ note: Notification) {
|
|
||||||
needsDisplay = true
|
|
||||||
}
|
|
||||||
|
|
||||||
override func drawHashMarksAndLabels(in rect: NSRect) {
|
|
||||||
guard let textView: NSTextView,
|
|
||||||
let layoutManager: NSLayoutManager = textView.layoutManager,
|
|
||||||
let textContainer: NSTextContainer = textView.textContainer else {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
gutterFillColor.setFill()
|
|
||||||
rect.fill()
|
|
||||||
gutterDividerColor.setStroke()
|
|
||||||
let dividerPath: NSBezierPath = NSBezierPath()
|
|
||||||
let dividerX: CGFloat = bounds.maxX - dividerHalfPixel
|
|
||||||
dividerPath.move(to: NSPoint(x: dividerX, y: rect.minY))
|
|
||||||
dividerPath.line(to: NSPoint(x: dividerX, y: rect.maxY))
|
|
||||||
dividerPath.lineWidth = 1
|
|
||||||
dividerPath.stroke()
|
|
||||||
|
|
||||||
let nsText: NSString = textView.string as NSString
|
|
||||||
let totalLength: Int = nsText.length
|
|
||||||
let visibleRect: NSRect = scrollView?.contentView.bounds ?? .zero
|
|
||||||
let glyphRange: NSRange = layoutManager.glyphRange(forBoundingRect: visibleRect, in: textContainer)
|
|
||||||
let charRange: NSRange = layoutManager.characterRange(forGlyphRange: glyphRange, actualGlyphRange: nil)
|
|
||||||
let inset: CGFloat = textView.textContainerInset.height
|
|
||||||
let attrs: [NSAttributedString.Key: Any] = [
|
|
||||||
.font: rulerFont,
|
|
||||||
.foregroundColor: gutterTextColor,
|
|
||||||
]
|
|
||||||
|
|
||||||
var lineIndex: Int = lineNumber(at: charRange.location, in: nsText)
|
|
||||||
var cursor: Int = charRange.location
|
|
||||||
let visibleEnd: Int = NSMaxRange(charRange)
|
|
||||||
while cursor < visibleEnd && cursor <= totalLength {
|
|
||||||
// `lineRange(for:)` advances cursor by the full line including its
|
|
||||||
// terminator, so `\r`, `\n`, and `\r\n` line endings are all
|
|
||||||
// handled by Foundation.
|
|
||||||
let probeLength: Int = (cursor == totalLength) ? 0 : 0
|
|
||||||
let lineRange: NSRange = nsText.lineRange(for: NSRange(location: cursor, length: probeLength))
|
|
||||||
let lineGlyphRange: NSRange = layoutManager.glyphRange(forCharacterRange: lineRange,
|
|
||||||
actualCharacterRange: nil)
|
|
||||||
let usedRect: NSRect = layoutManager.boundingRect(forGlyphRange: lineGlyphRange,
|
|
||||||
in: textContainer)
|
|
||||||
let yInView: CGFloat = usedRect.minY + inset - visibleRect.minY
|
|
||||||
let label: NSString = "\(lineIndex)" as NSString
|
|
||||||
let size: CGSize = label.size(withAttributes: attrs)
|
|
||||||
let drawPoint: NSPoint = NSPoint(
|
|
||||||
x: bounds.maxX - size.width - rightInset,
|
|
||||||
y: yInView + ((usedRect.height - size.height) * 0.5)
|
|
||||||
)
|
|
||||||
label.draw(at: drawPoint, withAttributes: attrs)
|
|
||||||
|
|
||||||
let advance: Int = NSMaxRange(lineRange)
|
|
||||||
if advance <= cursor { break } // defensive — empty trailing line
|
|
||||||
cursor = advance
|
|
||||||
lineIndex += 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 1-based line number of the character at `loc`. Delegates to
|
|
||||||
// `NSString.enumerateSubstrings(.byLines)` so CR, LF, and CRLF endings are
|
|
||||||
// all counted correctly. Linear in `loc`, runs once per draw on the prefix
|
|
||||||
// that precedes the first visible line.
|
|
||||||
private func lineNumber(at loc: Int, in text: NSString) -> Int {
|
|
||||||
if loc <= 0 { return 1 }
|
|
||||||
var line: Int = 1
|
|
||||||
let prefixRange: NSRange = NSRange(location: 0, length: loc)
|
|
||||||
text.enumerateSubstrings(in: prefixRange,
|
|
||||||
options: [.byLines, .substringNotRequired]) { _, _, _, _ in
|
|
||||||
line += 1
|
|
||||||
}
|
|
||||||
return line
|
|
||||||
}
|
|
||||||
|
|
||||||
private let gutterWidth: CGFloat = 40
|
|
||||||
private let rightInset: CGFloat = 6
|
|
||||||
private let dividerHalfPixel: CGFloat = 0.5 // crisp 1px divider on Retina
|
|
||||||
private let rulerFontSize: CGFloat = 11
|
|
||||||
private let gutterFillColor: NSColor = NSColor.controlBackgroundColor
|
|
||||||
private let gutterDividerColor: NSColor = NSColor.separatorColor
|
|
||||||
private let gutterTextColor: NSColor = NSColor.tertiaryLabelColor
|
|
||||||
private var rulerFont: NSFont {
|
|
||||||
NSFont.monospacedSystemFont(ofSize: rulerFontSize, weight: .regular)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#endif
|
|
||||||
@@ -1,898 +0,0 @@
|
|||||||
// ProjectScaffolder.swift
|
|
||||||
// Lyrebird
|
|
||||||
//
|
|
||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
||||||
// SPDX-License-Identifier: MIT
|
|
||||||
|
|
||||||
import Foundation
|
|
||||||
|
|
||||||
// MARK: - ProjectTemplate
|
|
||||||
|
|
||||||
/// Template style for a scaffolded Lyrebird project.
|
|
||||||
public enum ProjectTemplate: String, CaseIterable, Equatable {
|
|
||||||
/// Minimal engine setup with `CoreAudioDriver` and `RunLoop.main.run()`.
|
|
||||||
case basic = "basic"
|
|
||||||
/// Real-time demo: `SineTone` synthesizer with `@LiveParam` frequency and amplitude.
|
|
||||||
case demo = "demo"
|
|
||||||
/// GUI demo: `@UIParam` synthesizer with a `LyrebirdWindow` SwiftUI panel.
|
|
||||||
case uiDemo = "ui-demo"
|
|
||||||
/// Non-real-time render: `NRTDriver` writes a `.caf` file and exits.
|
|
||||||
case nrt = "nrt"
|
|
||||||
/// Score / MusicXML render: builds a `Score` with the DSL, exports a
|
|
||||||
/// `.musicxml` document, and renders the score offline with `NRTDriver`.
|
|
||||||
case score = "score"
|
|
||||||
/// macOS `.app` bundle wrapping an AppKit + SwiftUI host of a `@UIParam` synth.
|
|
||||||
/// Generates a full `<name>.xcodeproj` referencing Lyrebird via remote SPM dep.
|
|
||||||
case macosUIXcode = "macos-ui-xcode"
|
|
||||||
/// iOS `.app` bundle with `iOSAudioDriver` + SwiftUI UI.
|
|
||||||
/// Generates a full `<name>.xcodeproj` referencing Lyrebird via remote SPM dep.
|
|
||||||
case iosUI = "ios-ui"
|
|
||||||
/// AUv3 host `.app` + `aumu` plugin extension wrapping a Lyrebird synth.
|
|
||||||
/// Generates a full `<name>.xcodeproj` with two targets and entitlements files.
|
|
||||||
case auv3 = "auv3"
|
|
||||||
|
|
||||||
/// Case-insensitive init from a raw string. Accepts hyphen-free aliases too.
|
|
||||||
public init?(string: String) {
|
|
||||||
switch string.lowercased() {
|
|
||||||
case "basic": self = .basic
|
|
||||||
case "demo": self = .demo
|
|
||||||
case "ui-demo", "uidemo", "ui_demo": self = .uiDemo
|
|
||||||
case "nrt": self = .nrt
|
|
||||||
case "score", "score-musicxml", "scoremusicxml", "musicxml":
|
|
||||||
self = .score
|
|
||||||
case "macos-ui-xcode", "macosuixcode", "macos_ui_xcode":
|
|
||||||
self = .macosUIXcode
|
|
||||||
case "ios-ui", "iosui", "ios_ui":
|
|
||||||
self = .iosUI
|
|
||||||
case "auv3", "au-v3", "au_v3":
|
|
||||||
self = .auv3
|
|
||||||
default: return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// True when the template emits a full `.xcodeproj` skeleton in addition
|
|
||||||
/// to the Swift Package. The simpler four templates (basic/demo/ui-demo/nrt)
|
|
||||||
/// rely on Xcode's "Open Package.swift" path; these three need a real
|
|
||||||
/// `.xcodeproj` because they ship an `.app` bundle, app entitlements, or
|
|
||||||
/// (auv3) an `.appex` extension target — none of which SwiftPM can express.
|
|
||||||
public var shipsXcodeProject: Bool {
|
|
||||||
switch self {
|
|
||||||
case .basic, .demo, .uiDemo, .nrt, .score: return false
|
|
||||||
case .macosUIXcode, .iosUI, .auv3: return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - ProjectScaffolder
|
|
||||||
|
|
||||||
/// Scaffolds a new Lyrebird project as a Swift Package.
|
|
||||||
///
|
|
||||||
/// `lyrebird new <name>` creates:
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// <name>/
|
|
||||||
/// ├── Package.swift
|
|
||||||
/// ├── <name>.xcworkspace/
|
|
||||||
/// │ └── contents.xcworkspacedata (references Package.swift — open in Xcode)
|
|
||||||
/// ├── Sources/
|
|
||||||
/// │ └── <name>/
|
|
||||||
/// │ └── main.swift (+ AppDelegate.swift, <name>Synth.swift for ui-demo)
|
|
||||||
/// └── Tests/
|
|
||||||
/// └── <name>Tests/
|
|
||||||
/// └── <name>Tests.swift
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// Pass `--template demo`, `--template ui-demo`, or `--template nrt` to get richer
|
|
||||||
/// starting points.
|
|
||||||
public enum ProjectScaffolder {
|
|
||||||
|
|
||||||
// MARK: - Errors
|
|
||||||
|
|
||||||
/// Errors thrown by `ProjectScaffolder`.
|
|
||||||
public enum Error: Swift.Error, Equatable {
|
|
||||||
/// The project directory already exists.
|
|
||||||
case projectExists(name: String)
|
|
||||||
/// The project name is empty or contains characters not valid in a Swift module name.
|
|
||||||
case invalidName(name: String)
|
|
||||||
/// A file or directory could not be created.
|
|
||||||
case fileSystemError(path: String, reason: String)
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Public API
|
|
||||||
|
|
||||||
/// Absolute path to the Lyrebird checkout this CLI was *built* from, derived
|
|
||||||
/// from the compile-time source location of this file
|
|
||||||
/// (`<root>/Sources/LyrebirdCLI/ProjectScaffolder.swift`).
|
|
||||||
///
|
|
||||||
/// Used as the default SPM dependency for scaffolded projects when the caller
|
|
||||||
/// passes no explicit `--lyrebird-path`, so generated projects track the
|
|
||||||
/// current `main` API rather than the published `from:` tag — which lags
|
|
||||||
/// unreleased Score/Generator features (e.g. `Part(clef:)`,
|
|
||||||
/// `ScoreEvent.performedDuration`). This is the pre-1.0-stable policy: the
|
|
||||||
/// template source and the dependency it pins both come from one checkout, so
|
|
||||||
/// they never drift.
|
|
||||||
///
|
|
||||||
/// Returns `nil` when the derived root no longer holds the Lyrebird
|
|
||||||
/// `Package.swift` (the binary was installed away from its source tree);
|
|
||||||
/// callers then fall back to the remote versioned dependency.
|
|
||||||
static var defaultLyrebirdCheckoutPath: String? {
|
|
||||||
lyrebirdCheckoutRoot(forSourceFile: #filePath)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Testable core of ``defaultLyrebirdCheckoutPath``. Given a source file at
|
|
||||||
/// `<root>/Sources/LyrebirdCLI/<file>.swift`, walks up three directory
|
|
||||||
/// levels to `<root>` and returns it iff `<root>/Package.swift` exists and
|
|
||||||
/// names Lyrebird. Returns `nil` otherwise. Split out so the happy- and
|
|
||||||
/// nil-paths can be unit-tested with synthetic paths (the computed property
|
|
||||||
/// is hard-wired to its own `#filePath`).
|
|
||||||
static func lyrebirdCheckoutRoot(forSourceFile sourceFile: String) -> String? {
|
|
||||||
let root: URL = URL(fileURLWithPath: sourceFile)
|
|
||||||
.deletingLastPathComponent() // strip <file>.swift → Sources/LyrebirdCLI/
|
|
||||||
.deletingLastPathComponent() // → Sources/
|
|
||||||
.deletingLastPathComponent() // → <root>/
|
|
||||||
let manifest: String = root.appendingPathComponent("Package.swift").path
|
|
||||||
guard FileManager.default.fileExists(atPath: manifest) else { return nil }
|
|
||||||
// Guard against pointing at an unrelated parent Package.swift.
|
|
||||||
guard let contents: String = try? String(contentsOfFile: manifest, encoding: .utf8),
|
|
||||||
contents.contains("Lyrebird") else { return nil }
|
|
||||||
return root.path
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Scaffold a new Lyrebird project named `name` inside `parentDirectory`.
|
|
||||||
///
|
|
||||||
/// - Parameters:
|
|
||||||
/// - name: The project name. Must be a non-empty identifier valid as a Swift module name.
|
|
||||||
/// - template: Starter template style (default `.basic`).
|
|
||||||
/// - parentDirectory: Directory in which to create the project folder.
|
|
||||||
/// Defaults to the current working directory.
|
|
||||||
/// - lyrebirdPath: Absolute path to a local Lyrebird checkout to wire into
|
|
||||||
/// the generated `Package.swift` as a `path:` dependency. `nil` → use
|
|
||||||
/// the published remote package. This is a faithful passthrough: the
|
|
||||||
/// `new` CLI command resolves `nil` to ``defaultLyrebirdCheckoutPath``
|
|
||||||
/// *before* calling this (see `LyrebirdCLI.runNew`), so default
|
|
||||||
/// scaffolds track current `main`; direct library callers get the
|
|
||||||
/// documented `nil` → remote behaviour.
|
|
||||||
/// - Throws: `ProjectScaffolder.Error` on name validation failure or file system errors.
|
|
||||||
public static func scaffold(
|
|
||||||
name: String,
|
|
||||||
template: ProjectTemplate = .basic,
|
|
||||||
in parentDirectory: String = FileManager.default.currentDirectoryPath,
|
|
||||||
lyrebirdPath: String? = nil
|
|
||||||
) throws {
|
|
||||||
try validateName(name)
|
|
||||||
|
|
||||||
let projectRoot: String = (parentDirectory as NSString).appendingPathComponent(name)
|
|
||||||
let fm: FileManager = FileManager.default
|
|
||||||
|
|
||||||
guard !fm.fileExists(atPath: projectRoot) else {
|
|
||||||
throw Error.projectExists(name: name)
|
|
||||||
}
|
|
||||||
|
|
||||||
do {
|
|
||||||
try fm.createDirectory(atPath: projectRoot,
|
|
||||||
withIntermediateDirectories: true,
|
|
||||||
attributes: nil)
|
|
||||||
} catch {
|
|
||||||
throw Error.fileSystemError(path: projectRoot,
|
|
||||||
reason: error.localizedDescription)
|
|
||||||
}
|
|
||||||
|
|
||||||
if template.shipsXcodeProject {
|
|
||||||
try scaffoldXcodeProject(name: name,
|
|
||||||
template: template,
|
|
||||||
projectRoot: projectRoot,
|
|
||||||
lyrebirdPath: lyrebirdPath,
|
|
||||||
fm: fm)
|
|
||||||
} else {
|
|
||||||
try scaffoldSwiftPackage(name: name,
|
|
||||||
template: template,
|
|
||||||
projectRoot: projectRoot,
|
|
||||||
lyrebirdPath: lyrebirdPath,
|
|
||||||
fm: fm)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - SPM-only scaffold
|
|
||||||
|
|
||||||
private static func scaffoldSwiftPackage(
|
|
||||||
name: String,
|
|
||||||
template: ProjectTemplate,
|
|
||||||
projectRoot: String,
|
|
||||||
lyrebirdPath: String?,
|
|
||||||
fm: FileManager
|
|
||||||
) throws {
|
|
||||||
let sourcesDir: String = (projectRoot as NSString)
|
|
||||||
.appendingPathComponent("Sources/\(name)")
|
|
||||||
let testsDir: String = (projectRoot as NSString)
|
|
||||||
.appendingPathComponent("Tests/\(name)Tests")
|
|
||||||
let workspaceDir: String = (projectRoot as NSString)
|
|
||||||
.appendingPathComponent("\(name).xcworkspace")
|
|
||||||
|
|
||||||
for dir: String in [sourcesDir, testsDir, workspaceDir] {
|
|
||||||
do {
|
|
||||||
try fm.createDirectory(atPath: dir,
|
|
||||||
withIntermediateDirectories: true,
|
|
||||||
attributes: nil)
|
|
||||||
} catch {
|
|
||||||
try? fm.removeItem(atPath: projectRoot)
|
|
||||||
throw Error.fileSystemError(path: dir,
|
|
||||||
reason: error.localizedDescription)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var files: [(path: String, content: String)] = [
|
|
||||||
(
|
|
||||||
(projectRoot as NSString).appendingPathComponent("Package.swift"),
|
|
||||||
packageManifest(name: name, template: template, lyrebirdPath: lyrebirdPath)
|
|
||||||
),
|
|
||||||
(
|
|
||||||
(sourcesDir as NSString).appendingPathComponent("main.swift"),
|
|
||||||
mainSwift(name: name, template: template)
|
|
||||||
),
|
|
||||||
(
|
|
||||||
(testsDir as NSString).appendingPathComponent("\(name)Tests.swift"),
|
|
||||||
testsSwift(name: name)
|
|
||||||
),
|
|
||||||
(
|
|
||||||
(workspaceDir as NSString).appendingPathComponent("contents.xcworkspacedata"),
|
|
||||||
workspaceContents()
|
|
||||||
),
|
|
||||||
]
|
|
||||||
|
|
||||||
if template == .uiDemo {
|
|
||||||
files += [
|
|
||||||
(
|
|
||||||
(sourcesDir as NSString).appendingPathComponent("AppDelegate.swift"),
|
|
||||||
appDelegateSwift(name: name)
|
|
||||||
),
|
|
||||||
(
|
|
||||||
(sourcesDir as NSString).appendingPathComponent("\(name)Synth.swift"),
|
|
||||||
synthSwift(name: name)
|
|
||||||
),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
try writeFiles(files.map { ($0.path, $0.content) },
|
|
||||||
fm: fm, projectRoot: projectRoot)
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Xcode-project scaffold dispatch
|
|
||||||
|
|
||||||
private static func scaffoldXcodeProject(
|
|
||||||
name: String,
|
|
||||||
template: ProjectTemplate,
|
|
||||||
projectRoot: String,
|
|
||||||
lyrebirdPath: String?,
|
|
||||||
fm: FileManager
|
|
||||||
) throws {
|
|
||||||
// Every xcode-bearing template ships an `<name>.xcworkspace` that
|
|
||||||
// references the generated `<name>.xcodeproj`. The workspace is
|
|
||||||
// separate from the SPM-only `workspaceContents()` shape because
|
|
||||||
// there is no `Package.swift` at the project root here.
|
|
||||||
let workspaceDir: String = (projectRoot as NSString)
|
|
||||||
.appendingPathComponent("\(name).xcworkspace")
|
|
||||||
do {
|
|
||||||
try fm.createDirectory(atPath: workspaceDir,
|
|
||||||
withIntermediateDirectories: true,
|
|
||||||
attributes: nil)
|
|
||||||
} catch {
|
|
||||||
try? fm.removeItem(atPath: projectRoot)
|
|
||||||
throw Error.fileSystemError(path: workspaceDir,
|
|
||||||
reason: error.localizedDescription)
|
|
||||||
}
|
|
||||||
|
|
||||||
let workspaceFile: String = (workspaceDir as NSString)
|
|
||||||
.appendingPathComponent("contents.xcworkspacedata")
|
|
||||||
try writeFiles([(workspaceFile,
|
|
||||||
xcodeWorkspaceContents(name: name,
|
|
||||||
lyrebirdPath: lyrebirdPath))],
|
|
||||||
fm: fm, projectRoot: projectRoot)
|
|
||||||
|
|
||||||
switch template {
|
|
||||||
case .macosUIXcode:
|
|
||||||
try writeMacOSUIXcodeFiles(name: name, projectRoot: projectRoot,
|
|
||||||
lyrebirdPath: lyrebirdPath, fm: fm)
|
|
||||||
case .iosUI:
|
|
||||||
try writeIOSUIFiles(name: name, projectRoot: projectRoot,
|
|
||||||
lyrebirdPath: lyrebirdPath, fm: fm)
|
|
||||||
case .auv3:
|
|
||||||
try writeAUv3Files(name: name, projectRoot: projectRoot,
|
|
||||||
lyrebirdPath: lyrebirdPath, fm: fm)
|
|
||||||
case .basic, .demo, .uiDemo, .nrt, .score:
|
|
||||||
// Unreachable — shipsXcodeProject filters these out at dispatch.
|
|
||||||
try? fm.removeItem(atPath: projectRoot)
|
|
||||||
throw Error.fileSystemError(
|
|
||||||
path: projectRoot,
|
|
||||||
reason: "scaffoldXcodeProject called with non-Xcode template \(template.rawValue)"
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Workspace XML for xcode-bearing templates — references the generated
|
|
||||||
/// `<name>.xcodeproj`. When `lyrebirdPath` is set, the workspace also
|
|
||||||
/// references the Lyrebird `Package.swift` at that absolute path so
|
|
||||||
/// Xcode's IDE-level SPM resolver picks it up at workspace open.
|
|
||||||
/// Without this extra FileRef, opening the workspace in Xcode (vs.
|
|
||||||
/// running `xcodebuild` from the CLI) can fail with "Missing package
|
|
||||||
/// product 'LyrebirdUI'" — the IDE resolver doesn't always crawl into
|
|
||||||
/// member-project `XCLocalSwiftPackageReference` deps automatically.
|
|
||||||
public static func xcodeWorkspaceContents(
|
|
||||||
name: String,
|
|
||||||
lyrebirdPath: String? = nil
|
|
||||||
) -> String {
|
|
||||||
var refs: String = " <FileRef\n location = \"group:\(name).xcodeproj\">\n </FileRef>"
|
|
||||||
if let path: String = lyrebirdPath {
|
|
||||||
let escaped: String = pbxQuoteEscape(path)
|
|
||||||
refs += "\n <FileRef\n location = \"absolute:\(escaped)\">\n </FileRef>"
|
|
||||||
}
|
|
||||||
return """
|
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<Workspace
|
|
||||||
version = "1.0">
|
|
||||||
\(refs)
|
|
||||||
</Workspace>
|
|
||||||
"""
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Template constants
|
|
||||||
|
|
||||||
// Module-internal so extension files (Xcode-template generators) can
|
|
||||||
// reach them. Single source of truth for the engine defaults written
|
|
||||||
// into every scaffolded `main.swift` / app delegate / iOS app shell.
|
|
||||||
static let scaffoldDefaultBlockSize: Int = 512
|
|
||||||
static let scaffoldDefaultSampleRate: Int = 44100
|
|
||||||
static let scaffoldDefaultOutputChannels: Int = 2
|
|
||||||
static let scaffoldDefaultInputChannels: Int = 2
|
|
||||||
static let scaffoldDefaultNRTDuration: Double = 4.0
|
|
||||||
|
|
||||||
// MARK: - Package manifest
|
|
||||||
|
|
||||||
/// `Package.swift` content for a project using the given template.
|
|
||||||
///
|
|
||||||
/// - Parameters:
|
|
||||||
/// - name: Module / package name written into the generated manifest.
|
|
||||||
/// Must already be validated as a legal Swift identifier.
|
|
||||||
/// - template: Starter template the manifest is tailored for. Controls
|
|
||||||
/// which target/product entries appear. Defaults to `.basic`.
|
|
||||||
/// - lyrebirdPath: When non-nil, Lyrebird is declared as a local SPM
|
|
||||||
/// dependency (`.package(path: ...)`) at this absolute path. When
|
|
||||||
/// nil, falls back to the published Git URL (``lyrebirdPackageURL``).
|
|
||||||
/// Used by `lyrebird new --lyrebird-path` for users who don't yet
|
|
||||||
/// have access to the public repository.
|
|
||||||
public static func packageManifest(
|
|
||||||
name: String,
|
|
||||||
template: ProjectTemplate = .basic,
|
|
||||||
lyrebirdPath: String? = nil
|
|
||||||
) -> String {
|
|
||||||
// byName resolves only when the product name matches the package
|
|
||||||
// name (`Lyrebird`). Sibling products (`LyrebirdUI`) need the
|
|
||||||
// explicit `.product(name:package:)` form regardless of whether
|
|
||||||
// the dep is local or remote.
|
|
||||||
let targetDeps: String
|
|
||||||
switch template {
|
|
||||||
case .basic, .demo, .nrt, .score:
|
|
||||||
targetDeps = #""Lyrebird""#
|
|
||||||
case .uiDemo:
|
|
||||||
targetDeps = #""Lyrebird", .product(name: "LyrebirdUI", package: "Lyrebird")"#
|
|
||||||
case .macosUIXcode, .iosUI, .auv3:
|
|
||||||
// Xcode-bearing templates don't emit a `Package.swift` — dispatch
|
|
||||||
// never reaches this function for them. Defensive fallthrough.
|
|
||||||
targetDeps = #""Lyrebird", .product(name: "LyrebirdUI", package: "Lyrebird")"#
|
|
||||||
}
|
|
||||||
let depLine: String
|
|
||||||
if let path: String = lyrebirdPath {
|
|
||||||
// `name:` is required so byName target deps (e.g. `"Lyrebird"`)
|
|
||||||
// resolve — SPM otherwise uses the directory basename as the
|
|
||||||
// package identity, which is unlikely to match `"Lyrebird"`
|
|
||||||
// (worktree paths, renamed checkouts, etc.).
|
|
||||||
// Path escaped for safe embedding in a Swift string literal —
|
|
||||||
// same `\\` then `"` escape semantics as `pbxQuoteEscape`.
|
|
||||||
let escapedPath: String = pbxQuoteEscape(path)
|
|
||||||
depLine = #".package(name: "Lyrebird", path: "\#(escapedPath)"),"#
|
|
||||||
} else {
|
|
||||||
depLine = #".package(url: "\#(lyrebirdPackageURL)", from: "\#(lyrebirdMinimumVersion)"),"#
|
|
||||||
}
|
|
||||||
return """
|
|
||||||
// swift-tools-version: 6.0
|
|
||||||
import PackageDescription
|
|
||||||
|
|
||||||
let package = Package(
|
|
||||||
name: "\(name)",
|
|
||||||
platforms: [.macOS(.v15)],
|
|
||||||
dependencies: [
|
|
||||||
\(depLine)
|
|
||||||
],
|
|
||||||
targets: [
|
|
||||||
.executableTarget(
|
|
||||||
name: "\(name)",
|
|
||||||
dependencies: [\(targetDeps)]
|
|
||||||
),
|
|
||||||
.testTarget(
|
|
||||||
name: "\(name)Tests",
|
|
||||||
dependencies: ["\(name)"]
|
|
||||||
),
|
|
||||||
]
|
|
||||||
)
|
|
||||||
"""
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - main.swift templates
|
|
||||||
|
|
||||||
/// `main.swift` content for the given template (defaults to `.basic`).
|
|
||||||
public static func mainSwift(
|
|
||||||
name: String,
|
|
||||||
template: ProjectTemplate = .basic
|
|
||||||
) -> String {
|
|
||||||
switch template {
|
|
||||||
case .basic: return mainSwiftBasic(name: name)
|
|
||||||
case .demo: return mainSwiftDemo(name: name)
|
|
||||||
case .uiDemo: return mainSwiftUIDemo(name: name)
|
|
||||||
case .nrt: return mainSwiftNRT(name: name)
|
|
||||||
case .score: return mainSwiftScore(name: name)
|
|
||||||
case .macosUIXcode, .iosUI, .auv3:
|
|
||||||
// Xcode-bearing templates don't emit a `main.swift` under
|
|
||||||
// `Sources/<name>/`. Dispatch never reaches this function for
|
|
||||||
// them. Defensive fallthrough to the basic skeleton.
|
|
||||||
return mainSwiftBasic(name: name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: basic
|
|
||||||
|
|
||||||
private static func mainSwiftBasic(name: String) -> String {
|
|
||||||
"""
|
|
||||||
// \(name) — entry point
|
|
||||||
import Foundation
|
|
||||||
import LyrebirdSynth
|
|
||||||
|
|
||||||
// Configure the synthesis engine.
|
|
||||||
let engine = SynthesisEngine(
|
|
||||||
blockSize: \(scaffoldDefaultBlockSize),
|
|
||||||
sampleRate: \(scaffoldDefaultSampleRate),
|
|
||||||
numOutputChannels: \(scaffoldDefaultOutputChannels),
|
|
||||||
numInputChannels: \(scaffoldDefaultInputChannels),
|
|
||||||
driver: CoreAudioDriver()
|
|
||||||
)
|
|
||||||
|
|
||||||
// Add your Synthesizers here.
|
|
||||||
// try engine.add(MySynth())
|
|
||||||
|
|
||||||
do {
|
|
||||||
try engine.start()
|
|
||||||
} catch {
|
|
||||||
fatalError("Engine failed to start: \\(error)")
|
|
||||||
}
|
|
||||||
|
|
||||||
print("\(name) running — press Ctrl+C to stop")
|
|
||||||
RunLoop.main.run()
|
|
||||||
"""
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: demo
|
|
||||||
|
|
||||||
private static func mainSwiftDemo(name: String) -> String {
|
|
||||||
"""
|
|
||||||
// \(name) — real-time demo
|
|
||||||
import Foundation
|
|
||||||
import LyrebirdSynth
|
|
||||||
|
|
||||||
// MARK: - SineTone
|
|
||||||
|
|
||||||
final class SineTone: SynthesizerBase {
|
|
||||||
@LiveParam var freq: Double = 440.0
|
|
||||||
@LiveParam var amp: Double = 0.25
|
|
||||||
|
|
||||||
override func build() {
|
|
||||||
let osc = OscSin.Audio(freq: $freq)
|
|
||||||
output(bus: 0, source: Pan2(input: osc * $amp))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Main
|
|
||||||
|
|
||||||
let engine = SynthesisEngine(
|
|
||||||
blockSize: \(scaffoldDefaultBlockSize),
|
|
||||||
sampleRate: \(scaffoldDefaultSampleRate),
|
|
||||||
numOutputChannels: \(scaffoldDefaultOutputChannels),
|
|
||||||
numInputChannels: \(scaffoldDefaultInputChannels),
|
|
||||||
driver: CoreAudioDriver()
|
|
||||||
)
|
|
||||||
|
|
||||||
do {
|
|
||||||
try engine.start()
|
|
||||||
} catch {
|
|
||||||
fatalError("Engine failed to start: \\(error)")
|
|
||||||
}
|
|
||||||
|
|
||||||
let tone = SineTone()
|
|
||||||
do {
|
|
||||||
try engine.add(tone)
|
|
||||||
} catch {
|
|
||||||
fatalError("Engine.add failed: \\(error)")
|
|
||||||
}
|
|
||||||
|
|
||||||
print("\(name) running — press Ctrl+C to stop")
|
|
||||||
print("Update tone.freq or tone.amp from the REPL to change parameters.")
|
|
||||||
RunLoop.main.run()
|
|
||||||
"""
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: ui-demo (main.swift only — AppDelegate and Synth are separate files)
|
|
||||||
|
|
||||||
private static func mainSwiftUIDemo(name: String) -> String {
|
|
||||||
"""
|
|
||||||
// \(name) — GUI demo
|
|
||||||
import AppKit
|
|
||||||
import LyrebirdSynth
|
|
||||||
|
|
||||||
let engine = SynthesisEngine(
|
|
||||||
blockSize: \(scaffoldDefaultBlockSize),
|
|
||||||
sampleRate: \(scaffoldDefaultSampleRate),
|
|
||||||
numOutputChannels: \(scaffoldDefaultOutputChannels),
|
|
||||||
numInputChannels: 0,
|
|
||||||
driver: CoreAudioDriver()
|
|
||||||
)
|
|
||||||
|
|
||||||
let delegate = AppDelegate(engine: engine)
|
|
||||||
NSApplication.shared.setActivationPolicy(.regular)
|
|
||||||
NSApplication.shared.delegate = delegate
|
|
||||||
NSApplication.shared.run()
|
|
||||||
"""
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: nrt
|
|
||||||
|
|
||||||
private static func mainSwiftNRT(name: String) -> String {
|
|
||||||
"""
|
|
||||||
// \(name) — non-real-time render
|
|
||||||
import Foundation
|
|
||||||
import LyrebirdSynth
|
|
||||||
|
|
||||||
// MARK: - \(name)Synth
|
|
||||||
|
|
||||||
final class \(name)Synth: SynthesizerBase {
|
|
||||||
override func build() {
|
|
||||||
let env = EnvelopeGen.Audio(
|
|
||||||
envelope: Envelope(
|
|
||||||
levels: [0, 1, 0.6, 0],
|
|
||||||
durations: [0.02, 0.46, 0.5],
|
|
||||||
curves: [0, 0, 0]
|
|
||||||
)
|
|
||||||
)
|
|
||||||
let osc = OscSin.Audio(freq: 440.0) * env * 0.3
|
|
||||||
output(bus: 0, source: Pan2(input: osc))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Render
|
|
||||||
|
|
||||||
let outputURL = URL(fileURLWithPath: "output.caf")
|
|
||||||
let renderDuration = \(scaffoldDefaultNRTDuration)
|
|
||||||
|
|
||||||
let engine = SynthesisEngine(
|
|
||||||
blockSize: \(scaffoldDefaultBlockSize),
|
|
||||||
sampleRate: \(scaffoldDefaultSampleRate),
|
|
||||||
numOutputChannels: \(scaffoldDefaultOutputChannels),
|
|
||||||
numInputChannels: 0,
|
|
||||||
driver: NRTDriver(outputURL: outputURL, duration: renderDuration)
|
|
||||||
)
|
|
||||||
|
|
||||||
// Add synthesizers BEFORE start() — NRTDriver renders synchronously inside start().
|
|
||||||
do {
|
|
||||||
try engine.add(\(name)Synth())
|
|
||||||
} catch {
|
|
||||||
fputs("engine.add failed: \\(error)\\n", stderr)
|
|
||||||
exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
do {
|
|
||||||
try engine.start()
|
|
||||||
print("Rendered \\(renderDuration)s → \\(outputURL.path)")
|
|
||||||
} catch {
|
|
||||||
fputs("Render failed: \\(error)\\n", stderr)
|
|
||||||
exit(1)
|
|
||||||
}
|
|
||||||
"""
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: score
|
|
||||||
|
|
||||||
private static func mainSwiftScore(name: String) -> String {
|
|
||||||
"""
|
|
||||||
// \(name) — Score / MusicXML render
|
|
||||||
import Foundation
|
|
||||||
import LyrebirdSynth
|
|
||||||
|
|
||||||
// MARK: - ScoreVoice
|
|
||||||
|
|
||||||
/// One self-freeing voice per score event. The envelope's `freeNode`
|
|
||||||
/// done-action removes the synth when its note finishes, so scheduled
|
|
||||||
/// voices never accumulate during the offline render.
|
|
||||||
final class ScoreVoice: SynthesizerBase {
|
|
||||||
let freqHz: Double
|
|
||||||
let amp: Double
|
|
||||||
let durSeconds: Double
|
|
||||||
let pan: Double
|
|
||||||
|
|
||||||
init(freqHz: Double, amp: Double, durSeconds: Double, pan: Double = 0.0) {
|
|
||||||
self.freqHz = freqHz
|
|
||||||
self.amp = amp
|
|
||||||
self.durSeconds = durSeconds
|
|
||||||
self.pan = pan
|
|
||||||
super.init()
|
|
||||||
}
|
|
||||||
|
|
||||||
override func build() {
|
|
||||||
let attack = 0.01
|
|
||||||
let release = 0.06
|
|
||||||
let sustain = max(0.0, durSeconds - attack - release)
|
|
||||||
let envelope = Envelope(
|
|
||||||
levels: [0.0, 1.0, 0.8, 0.0],
|
|
||||||
durations: [attack, sustain, release],
|
|
||||||
curves: [-4.0, 0.0, -6.0]
|
|
||||||
)
|
|
||||||
let osc = OscSawtooth.Audio(freq: freqHz)
|
|
||||||
let env = EnvelopeGen.Control(envelope: envelope, doneAction: .freeNode)
|
|
||||||
output(bus: 0, source: Pan2(input: osc * env * amp, pan: pan))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Build the score
|
|
||||||
|
|
||||||
let bpm = 120.0
|
|
||||||
let secondsPerBeat = 60.0 / bpm
|
|
||||||
|
|
||||||
// Author music with the Score DSL: Note, Rest, Chord, Tuplet, dynamics,
|
|
||||||
// and articulations. Pitch spelling (letter + accidental) is preserved
|
|
||||||
// through MusicXML export. `Generate` and `PatternNotes` add algorithmic
|
|
||||||
// generation (see the "texture" part below).
|
|
||||||
//
|
|
||||||
// Further notation (see the Lyrebird ScoreSystem docs): Slur / Crescendo /
|
|
||||||
// Diminuendo spans, per-note `spanners:` (overlapping spans, glissandi /
|
|
||||||
// slides), per-note `display:` (NoteDisplay — notehead/size/hide stem or
|
|
||||||
// beam), `Section("…") { }` blocks with rehearsal marks, and a `pageLayout:`
|
|
||||||
// (PageLayout — page size, orientation, margins).
|
|
||||||
let score = Score(bpm: bpm, timeSignature: TimeSignature(4, 4)) {
|
|
||||||
Part("lead") {
|
|
||||||
// A crescendo hairpin over the opening arpeggio (notation-only).
|
|
||||||
Crescendo {
|
|
||||||
Note(.named(.c, 5), dur: .quarter, dyn: .mf, art: .staccato)
|
|
||||||
Note(.named(.e, 5), dur: .quarter, dyn: .mf, art: .staccato)
|
|
||||||
Note(.named(.g, 5), dur: .quarter, dyn: .f, art: .accent)
|
|
||||||
}
|
|
||||||
Rest(dur: .quarter)
|
|
||||||
Tuplet(3, inTimeOf: 2) {
|
|
||||||
Note(.named(.b, 5), dur: .quarter, dyn: .mp)
|
|
||||||
Note(.named(.a, 5), dur: .quarter, dyn: .mp)
|
|
||||||
Note(.named(.g, 5), dur: .quarter, dyn: .mp)
|
|
||||||
}
|
|
||||||
Chord([.named(.c, 5), .named(.e, 5), .named(.g, 5)], dur: .half, dyn: .f, art: .tenuto)
|
|
||||||
}
|
|
||||||
Part("bass", channel: 1, clef: .bass) {
|
|
||||||
Note(.named(.c, 3), dur: .whole, dyn: .mp)
|
|
||||||
Note(.named(.g, 2), dur: .half, dyn: .p)
|
|
||||||
Note(.named(.c, 3), dur: .half, dyn: .mp, art: .tenuto)
|
|
||||||
}
|
|
||||||
// Texture — algorithmic generation. `Generate` maps an index range
|
|
||||||
// through the builder; `PatternNotes` pulls from a `Pattern` source.
|
|
||||||
Part("texture", channel: 2) {
|
|
||||||
Generate(8) { i in
|
|
||||||
Note(midi: 72 + (i % 6) * 2, dur: .sixteenth, dyn: .pp, art: .staccato)
|
|
||||||
}
|
|
||||||
PatternNotes(count: 4, midi: Pattern.series(start: 60, step: 3, length: 4), dur: .eighth, dyn: .p)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Output location
|
|
||||||
|
|
||||||
// Write next to this project's source rather than the launch directory.
|
|
||||||
// `LyrebirdPaths.projectRoot()` walks up from this file to the folder
|
|
||||||
// containing Package.swift, so output lands in the project regardless of
|
|
||||||
// how the binary is launched (lyrebird run, swift run, or Xcode — whose
|
|
||||||
// working directory is DerivedData). Dev-time convenience; for a shipped
|
|
||||||
// app writing user data, use `LyrebirdPaths.documents` instead.
|
|
||||||
let outputDir = LyrebirdPaths.projectRoot() ?? LyrebirdPaths.currentWorkingDirectory
|
|
||||||
|
|
||||||
// MARK: - Export MusicXML
|
|
||||||
|
|
||||||
let xmlURL = outputDir.appendingPathComponent("score.musicxml")
|
|
||||||
do {
|
|
||||||
let xml = score.toMusicXMLString()
|
|
||||||
try xml.write(to: xmlURL, atomically: true, encoding: .utf8)
|
|
||||||
print("MusicXML written → \\(xmlURL.path)")
|
|
||||||
} catch {
|
|
||||||
fputs("MusicXML export failed: \\(error)\\n", stderr)
|
|
||||||
exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Round-trip sanity check: parse the document back in and compare counts.
|
|
||||||
do {
|
|
||||||
let restored = try Score.fromMusicXML(data: score.toMusicXMLData())
|
|
||||||
print("Round-trip events: \\(score.allEvents.count) → \\(restored.allEvents.count)")
|
|
||||||
} catch {
|
|
||||||
fputs("MusicXML round-trip failed: \\(error)\\n", stderr)
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Render the score offline
|
|
||||||
|
|
||||||
let tailSeconds = 1.5
|
|
||||||
let renderDuration = score.totalBeats * secondsPerBeat + tailSeconds
|
|
||||||
let outputURL = outputDir.appendingPathComponent("score.caf")
|
|
||||||
|
|
||||||
let engine = SynthesisEngine(
|
|
||||||
blockSize: \(scaffoldDefaultBlockSize),
|
|
||||||
sampleRate: \(scaffoldDefaultSampleRate),
|
|
||||||
numOutputChannels: \(scaffoldDefaultOutputChannels),
|
|
||||||
numInputChannels: 0,
|
|
||||||
driver: NRTDriver(outputURL: outputURL, duration: renderDuration)
|
|
||||||
)
|
|
||||||
|
|
||||||
// Schedule one voice per sounding event BEFORE start() — NRTDriver
|
|
||||||
// renders synchronously inside start().
|
|
||||||
var scheduled = 0
|
|
||||||
for event in score.allEvents {
|
|
||||||
guard !event.isRest else { continue }
|
|
||||||
guard let freqHz = event.pitch.frequency else { continue }
|
|
||||||
let pan = event.channel == 0 ? -0.4 : 0.5
|
|
||||||
let voice = ScoreVoice(
|
|
||||||
freqHz: freqHz,
|
|
||||||
amp: event.velocity * 0.35,
|
|
||||||
durSeconds: event.performedDuration * secondsPerBeat,
|
|
||||||
pan: pan
|
|
||||||
)
|
|
||||||
do {
|
|
||||||
try engine.schedule(voice, after: event.beat * secondsPerBeat)
|
|
||||||
scheduled += 1
|
|
||||||
} catch {
|
|
||||||
fputs("engine.schedule failed: \\(error)\\n", stderr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
print("Scheduled \\(scheduled) voices.")
|
|
||||||
|
|
||||||
do {
|
|
||||||
try engine.start()
|
|
||||||
print("Rendered \\(renderDuration)s → \\(outputURL.path)")
|
|
||||||
} catch {
|
|
||||||
fputs("Render failed: \\(error)\\n", stderr)
|
|
||||||
exit(1)
|
|
||||||
}
|
|
||||||
"""
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - ui-demo additional files
|
|
||||||
|
|
||||||
/// `AppDelegate.swift` content for a ui-demo project.
|
|
||||||
public static func appDelegateSwift(name: String) -> String {
|
|
||||||
"""
|
|
||||||
import AppKit
|
|
||||||
import SwiftUI
|
|
||||||
import LyrebirdSynth
|
|
||||||
import LyrebirdUI
|
|
||||||
|
|
||||||
final class AppDelegate: NSObject, NSApplicationDelegate {
|
|
||||||
let engine: SynthesisEngine
|
|
||||||
let synth: \(name)Synth
|
|
||||||
var window: LyrebirdWindow?
|
|
||||||
|
|
||||||
@MainActor
|
|
||||||
init(engine: SynthesisEngine) {
|
|
||||||
self.engine = engine
|
|
||||||
self.synth = \(name)Synth()
|
|
||||||
}
|
|
||||||
|
|
||||||
@MainActor
|
|
||||||
func applicationDidFinishLaunching(_ notification: Notification) {
|
|
||||||
do {
|
|
||||||
try engine.start()
|
|
||||||
} catch {
|
|
||||||
print("Engine.start failed: \\(error)")
|
|
||||||
NSApp.terminate(nil)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
do {
|
|
||||||
try engine.add(synth)
|
|
||||||
} catch {
|
|
||||||
print("Engine.add failed: \\(error)")
|
|
||||||
engine.stop()
|
|
||||||
NSApp.terminate(nil)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
window = LyrebirdWindow(title: "\(name)", width: 320, height: 200)
|
|
||||||
window?.open {
|
|
||||||
VStack(spacing: 16) {
|
|
||||||
ParameterSlider("Frequency", node: self.synth.$freq, range: 110...1760)
|
|
||||||
ParameterKnob("Amplitude", node: self.synth.$amp, range: 0...1)
|
|
||||||
ParameterKnob("Pan", node: self.synth.$pan, range: -1...1)
|
|
||||||
}
|
|
||||||
.padding(24)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
|
|
||||||
true
|
|
||||||
}
|
|
||||||
|
|
||||||
func applicationWillTerminate(_ notification: Notification) {
|
|
||||||
engine.stop()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
"""
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `<name>Synth.swift` content for a ui-demo project.
|
|
||||||
public static func synthSwift(name: String) -> String {
|
|
||||||
"""
|
|
||||||
import LyrebirdSynth
|
|
||||||
import LyrebirdUI
|
|
||||||
|
|
||||||
final class \(name)Synth: SynthesizerBase {
|
|
||||||
@UIParam var freq: Double = 440.0
|
|
||||||
@UIParam var amp: Double = 0.25
|
|
||||||
@UIParam var pan: Double = 0.0
|
|
||||||
|
|
||||||
override func build() {
|
|
||||||
let osc = OscSin.Audio(freq: $freq)
|
|
||||||
output(bus: 0, source: Pan2(input: osc * $amp, pan: $pan))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
"""
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Xcode workspace
|
|
||||||
|
|
||||||
/// `contents.xcworkspacedata` body. The single `FileRef` points at the
|
|
||||||
/// workspace's enclosing directory (`group:.`) — the package root that
|
|
||||||
/// holds `Package.swift` — so Xcode recognises it as a Swift package and
|
|
||||||
/// opens the full `Sources/` / `Tests/` tree with a runnable scheme.
|
|
||||||
/// (Referencing the `Package.swift` *file* instead loads a single loose
|
|
||||||
/// document with no schemes — `xcodebuild -list` reports "no schemes".)
|
|
||||||
/// Identical for every SPM template — the file lives at
|
|
||||||
/// `<name>.xcworkspace/contents.xcworkspacedata`.
|
|
||||||
public static func workspaceContents() -> String {
|
|
||||||
"""
|
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<Workspace
|
|
||||||
version = "1.0">
|
|
||||||
<FileRef
|
|
||||||
location = "group:.">
|
|
||||||
</FileRef>
|
|
||||||
</Workspace>
|
|
||||||
"""
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Tests template
|
|
||||||
|
|
||||||
/// Starter test file content (shared across all templates).
|
|
||||||
public static func testsSwift(name: String) -> String {
|
|
||||||
"""
|
|
||||||
import Testing
|
|
||||||
import LyrebirdSynth
|
|
||||||
|
|
||||||
@Suite("\(name)")
|
|
||||||
struct \(name)Tests {
|
|
||||||
|
|
||||||
@Test func engineStartsClean() throws {
|
|
||||||
let engine = SynthesisEngine(
|
|
||||||
blockSize: \(scaffoldDefaultBlockSize),
|
|
||||||
sampleRate: \(scaffoldDefaultSampleRate),
|
|
||||||
numOutputChannels: \(scaffoldDefaultOutputChannels),
|
|
||||||
numInputChannels: \(scaffoldDefaultInputChannels),
|
|
||||||
driver: OfflineDriver()
|
|
||||||
)
|
|
||||||
try engine.start()
|
|
||||||
engine.processBlock(inputSamples: [])
|
|
||||||
engine.stop()
|
|
||||||
#expect(engine.audioBuses[0].allSatisfy { $0 == 0.0 })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
"""
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Helpers
|
|
||||||
|
|
||||||
/// Validate that `name` is a non-empty Swift-compatible identifier.
|
|
||||||
static func validateName(_ name: String) throws {
|
|
||||||
try validateSwiftIdentifier(name, invalidNameError: Error.invalidName(name: name))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user