Files
Lyrebird/Sources/LyrebirdCLI/ProjectScaffolder+XcodeTemplates.swift
T

606 lines
25 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// ProjectScaffolder+XcodeTemplates.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
// MARK: - Xcode template constants
extension ProjectScaffolder {
/// SPM URL Lyrebird is resolved from. Single source of truth for both
/// the generated `Package.swift` manifest and every embedded `.xcodeproj`.
public static let lyrebirdPackageURL: String = "https://realizedsound.mooo.com/josh/Lyrebird"
/// Lower bound on the Lyrebird version range — `upToNextMajorVersion`.
public static let lyrebirdMinimumVersion: String = "1.0.0"
/// Bundle identifier prefix used in `PRODUCT_BUNDLE_IDENTIFIER`. The
/// scaffolded value is `<prefix>.<name>`. Users typically rewrite this
/// to their own reverse-DNS before shipping.
public static let defaultBundleIdentifierPrefix: String = "net.realizedsound"
/// PBX `buildActionMask` — all-build-actions mask used by every build
/// phase in a vanilla pbxproj. Constant in PBX format; no semantic
/// meaning beyond "this phase participates in every build action".
static let pbxBuildActionMask: String = "2147483647"
/// AUv3 `AudioComponents` entry default `version` encoded as
/// `0x00010000` (= `1.0.0`). Standard AU component-version encoding.
static let auv3DefaultComponentVersion: Int = 65536
/// Escape an absolute filesystem path for safe embedding inside a
/// pbxproj string literal. Escapes `"` and `\\` — the only two
/// characters that would otherwise terminate or corrupt the literal.
/// Newlines + control chars in paths are not realistic on macOS so
/// not handled.
static func pbxQuoteEscape(_ path: String) -> String {
var s: String = path
s = s.replacingOccurrences(of: "\\", with: "\\\\")
s = s.replacingOccurrences(of: "\"", with: "\\\"")
return s
}
/// pbxproj snippet for the SPM package reference. Emits either an
/// `XCRemoteSwiftPackageReference` (when `lyrebirdPath == nil`) or an
/// `XCLocalSwiftPackageReference` pointing at the absolute path.
static func pbxPackageReferenceSection(lyrebirdPath: String?) -> String {
if let path: String = lyrebirdPath {
let escaped: String = pbxQuoteEscape(path)
return """
/* Begin XCLocalSwiftPackageReference section */
\t\t\(pbxRemoteSPMRef) /* XCLocalSwiftPackageReference "lyrebird" */ = {
\t\t\tisa = XCLocalSwiftPackageReference;
\t\t\trelativePath = "\(escaped)";
\t\t};
/* End XCLocalSwiftPackageReference section */
"""
} else {
return """
/* Begin XCRemoteSwiftPackageReference section */
\t\t\(pbxRemoteSPMRef) /* XCRemoteSwiftPackageReference "lyrebird" */ = {
\t\t\tisa = XCRemoteSwiftPackageReference;
\t\t\trepositoryURL = "\(lyrebirdPackageURL)";
\t\t\trequirement = {
\t\t\t\tkind = upToNextMajorVersion;
\t\t\t\tminimumVersion = \(lyrebirdMinimumVersion);
\t\t\t};
\t\t};
/* End XCRemoteSwiftPackageReference section */
"""
}
}
/// Comment label used in pbxproj for the SPM package reference.
/// Tracks whether it's a remote or local ref so the label in comments
/// matches the actual `isa = ...` value.
static func pbxPackageReferenceLabel(lyrebirdPath: String?) -> String {
lyrebirdPath == nil
? #"XCRemoteSwiftPackageReference "lyrebird""#
: #"XCLocalSwiftPackageReference "lyrebird""#
}
}
// MARK: - macos-ui-xcode template
extension ProjectScaffolder {
// MARK: Public entry point
/// Write the full `macos-ui-xcode` template tree at `projectRoot`.
///
/// Emits, in addition to the standard `Package.swift` / `Sources` /
/// `Tests` / `<name>.xcworkspace`:
/// - `<name>.xcodeproj/project.pbxproj`
/// - `<name>.xcodeproj/xcshareddata/xcschemes/<name>.xcscheme`
/// - `<name>/Info.plist`
/// - `<name>/main.swift`, `AppDelegate.swift`, `<name>Synth.swift` (under app group, not under `Sources/`)
static func writeMacOSUIXcodeFiles(
name: String,
projectRoot: String,
lyrebirdPath: String?,
fm: FileManager
) throws {
let appGroupDir: String = (projectRoot as NSString).appendingPathComponent(name)
let xcodeprojDir: String = (projectRoot as NSString).appendingPathComponent("\(name).xcodeproj")
let schemeDir: String = (xcodeprojDir as NSString)
.appendingPathComponent("xcshareddata/xcschemes")
for dir: String in [appGroupDir, xcodeprojDir, schemeDir] {
do {
try fm.createDirectory(atPath: dir,
withIntermediateDirectories: true,
attributes: nil)
} catch {
try? fm.removeItem(atPath: projectRoot)
throw Error.fileSystemError(path: dir, reason: error.localizedDescription)
}
}
let files: [(String, String)] = [
((appGroupDir as NSString).appendingPathComponent("Info.plist"),
macOSAppInfoPlist(name: name)),
((appGroupDir as NSString).appendingPathComponent("main.swift"),
macOSAppMainSwift(name: name)),
((appGroupDir as NSString).appendingPathComponent("AppDelegate.swift"),
macOSAppDelegateSwift(name: name)),
((appGroupDir as NSString).appendingPathComponent("\(name)Synth.swift"),
macOSAppSynthSwift(name: name)),
((appGroupDir as NSString).appendingPathComponent("NoteController.swift"),
macOSAppNoteControllerSwift(name: name)),
((appGroupDir as NSString).appendingPathComponent("\(name)View.swift"),
macOSAppViewSwift(name: name)),
((xcodeprojDir as NSString).appendingPathComponent("project.pbxproj"),
macOSAppPBXProj(name: name, lyrebirdPath: lyrebirdPath)),
((schemeDir as NSString).appendingPathComponent("\(name).xcscheme"),
appScheme(name: name, productExtension: "app")),
]
try writeFiles(files, fm: fm, projectRoot: projectRoot)
}
// MARK: Source files
static func macOSAppInfoPlist(name: String) -> String {
appInfoPlist(name: name, platform: .macOS)
}
static func macOSAppMainSwift(name: String) -> String {
"""
// \(name) — entry point
//
// Engine is configured here but NOT started. The UI's "Start Engine"
// button kicks the audio driver, which avoids the first-block dropout
// that happens when start() races with the first window-draw frame.
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()
"""
}
static func macOSAppDelegateSwift(name: String) -> String {
"""
import AppKit
import SwiftUI
import LyrebirdSynth
import LyrebirdUI
final class AppDelegate: NSObject, NSApplicationDelegate {
let engine: SynthesisEngine
let controller: NoteController
var window: LyrebirdWindow?
init(engine: SynthesisEngine) {
let scopeCapture = ScopeCapture(buses: [0, 1], bufferSize: 2048)
engine.scopeTap = scopeCapture
self.engine = engine
self.controller = NoteController(
engine: engine,
synth: \(name)Synth(),
scopeCapture: scopeCapture
)
}
@MainActor
func applicationDidFinishLaunching(_ notification: Notification) {
window = LyrebirdWindow(title: "\(name)", width: 360, height: 560)
window?.open {
\(name)View(controller: self.controller)
}
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
true
}
func applicationWillTerminate(_ notification: Notification) {
if controller.engineRunning { engine.stop() }
}
}
"""
}
static func macOSAppSynthSwift(name: String) -> String {
"""
import LyrebirdSynth
import LyrebirdUI
/// Live-controllable stereo sine tone.
final class \(name)Synth: SynthesizerBase {
/// Frequency in Hz. Slider range 110–1760.
@UIParam var frequency: Double = 440.0
/// Output amplitude (linear gain). Knob range 0–1.
@UIParam var amplitude: Double = 0.25
/// Stereo pan position. -1 = hard left, 0 = center, +1 = hard right.
@UIParam var pan: Double = 0.0
override func build() {
let osc = OscSin.Audio(freq: $frequency)
output(bus: 0, source: Pan2(input: osc * $amplitude, pan: $pan))
}
}
"""
}
static func macOSAppNoteControllerSwift(name: String) -> String {
"""
import Observation
import LyrebirdSynth
import LyrebirdUI
/// Owns engine + synth + scope; mediates start/stop from the UI so the
/// engine isn't kicked until user is ready (avoids first-block dropouts).
@Observable
final class NoteController {
let engine: SynthesisEngine
let synth: \(name)Synth
let scopeCapture: ScopeCapture
private(set) var engineRunning: Bool = false
private(set) var isPlaying: Bool = false
init(engine: SynthesisEngine, synth: \(name)Synth, scopeCapture: ScopeCapture) {
self.engine = engine
self.synth = synth
self.scopeCapture = scopeCapture
}
func toggleEngine() {
if engineRunning {
if isPlaying {
engine.remove(synth)
isPlaying = false
}
engine.stop()
engineRunning = false
} else {
do {
try engine.start()
engineRunning = true
} catch {
print("Engine failed to start: \\(error)")
}
}
}
func toggleNote() {
if isPlaying {
engine.remove(synth)
isPlaying = false
} else {
do {
try engine.add(synth)
isPlaying = true
} catch {
print("engine.add failed: \\(error)")
}
}
}
}
"""
}
static func macOSAppViewSwift(name: String) -> String {
"""
import SwiftUI
import LyrebirdSynth
import LyrebirdUI
struct \(name)View: View {
let controller: NoteController
var body: some View {
VStack(alignment: .leading, spacing: 20) {
HStack {
Text("Engine").font(.headline)
Spacer()
Button(controller.engineRunning ? "Stop Engine" : "Start Engine") {
controller.toggleEngine()
}
.buttonStyle(.borderedProminent)
.tint(controller.engineRunning ? .red : .green)
}
Divider()
HStack {
Text("Note").font(.headline)
Spacer()
Button(controller.isPlaying ? "Stop Note" : "Start Note") {
controller.toggleNote()
}
.buttonStyle(.bordered)
.tint(controller.isPlaying ? .red : .green)
.disabled(!controller.engineRunning)
}
ParameterSlider("Frequency",
node: controller.synth.$frequency,
range: 110.0...1760.0)
HStack(spacing: 24) {
ParameterKnob("Amplitude",
node: controller.synth.$amplitude,
range: 0.0...1.0)
ParameterKnob("Pan",
node: controller.synth.$pan,
range: -1.0...1.0)
Spacer()
}
Divider()
LyrebirdStatusView(engine: controller.engine)
Divider()
LyrebirdScopeView(capture: controller.scopeCapture)
.frame(height: 120)
}
.padding(20)
.frame(minWidth: 340)
}
}
"""
}
}
// MARK: - Shared Info.plist + Scheme
extension ProjectScaffolder {
enum AppPlatform {
case macOS
case iOS
}
/// `Info.plist` for an app bundle on macOS or iOS.
static func appInfoPlist(name: String, platform: AppPlatform) -> String {
let bundleIdSetting: String = "$(PRODUCT_BUNDLE_IDENTIFIER)"
let bundleNameSetting: String = "$(PRODUCT_NAME)"
let executableNameSetting: String = "$(EXECUTABLE_NAME)"
let minOSKey: String
let minOSValue: String
let extras: String
switch platform {
case .macOS:
minOSKey = "LSMinimumSystemVersion"
minOSValue = "$(MACOSX_DEPLOYMENT_TARGET)"
extras = """
<key>NSPrincipalClass</key>
<string>NSApplication</string>
"""
case .iOS:
minOSKey = "MinimumOSVersion"
minOSValue = "$(IPHONEOS_DEPLOYMENT_TARGET)"
extras = """
<key>UILaunchScreen</key>
<dict/>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
</array>
"""
}
return """
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleExecutable</key>
<string>\(executableNameSetting)</string>
<key>CFBundleIdentifier</key>
<string>\(bundleIdSetting)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>\(bundleNameSetting)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>\(minOSKey)</key>
<string>\(minOSValue)</string>
\(extras)
<key>NSHumanReadableCopyright</key>
<string>Copyright © \(currentYearString()) \(name). All rights reserved.</string>
</dict>
</plist>
"""
}
/// Build/Test/Launch/Profile scheme XML for a single app target.
static func appScheme(name: String, productExtension: String) -> String {
let blueprintID: String = pbxBlueprintIDApp
return """
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1600"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "\(blueprintID)"
BuildableName = "\(name).\(productExtension)"
BlueprintName = "\(name)"
ReferencedContainer = "container:\(name).xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "\(blueprintID)"
BuildableName = "\(name).\(productExtension)"
BlueprintName = "\(name)"
ReferencedContainer = "container:\(name).xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "\(blueprintID)"
BuildableName = "\(name).\(productExtension)"
BlueprintName = "\(name)"
ReferencedContainer = "container:\(name).xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
"""
}
// MARK: - PBX UUID constants
// Stable UUIDs used in every generated pbxproj. Layout chosen so the
// hex matches semantically — last byte tells the role at a glance when
// reading raw pbxproj output. Same scheme reused across all three
// xcodeproj-bearing templates; the app-target UUID is referenced from
// every scheme (`BlueprintIdentifier`).
static let pbxRootObject: String = "AABB000000000000000000A0"
static let pbxMainGroup: String = "AABB000000000000000000A1"
static let pbxProductsGroup: String = "AABB000000000000000000A2"
static let pbxAppGroup: String = "AABB000000000000000000A3"
static let pbxBlueprintIDApp: String = "AABB0000000000000000000A"
static let pbxAppProductRef: String = "AABB000000000000000000A4"
static let pbxAppBuildConfigList: String = "AABB000000000000000000A5"
static let pbxProjectBuildConfigList: String = "AABB000000000000000000A6"
static let pbxAppDebugConfig: String = "AABB000000000000000000A7"
static let pbxAppReleaseConfig: String = "AABB000000000000000000A8"
static let pbxProjectDebugConfig: String = "AABB000000000000000000A9"
static let pbxProjectReleaseConfig: String = "AABB000000000000000000AA"
static let pbxSourcesPhase: String = "AABB000000000000000000AB"
static let pbxFrameworksPhase: String = "AABB000000000000000000AC"
static let pbxResourcesPhase: String = "AABB000000000000000000AD"
static let pbxRemoteSPMRef: String = "AABB000000000000000000AE"
static let pbxLyrebirdUIProductDep: String = "AABB000000000000000000B0"
static let pbxLyrebirdUIFrameworkBuild: String = "AABB000000000000000000B2"
// App-bundle source file IDs
static let pbxMainSwiftRef: String = "AABB0000000000000000010A"
static let pbxMainSwiftBuild: String = "AABB0000000000000000010B"
static let pbxAppDelegateRef: String = "AABB0000000000000000010C"
static let pbxAppDelegateBuild: String = "AABB0000000000000000010D"
static let pbxSynthRef: String = "AABB0000000000000000010E"
static let pbxSynthBuild: String = "AABB0000000000000000010F"
static let pbxNoteControllerRef: String = "AABB0000000000000000011A"
static let pbxNoteControllerBuild: String = "AABB0000000000000000011B"
static let pbxViewRef: String = "AABB0000000000000000011C"
static let pbxViewBuild: String = "AABB0000000000000000011D"
static let pbxInfoPlistRef: String = "AABB000000000000000001A0"
// iOS app uses one fewer file (no separate AppDelegate)
static let pbxIOSAppFileRef: String = "AABB0000000000000000020A"
static let pbxIOSAppFileBuild: String = "AABB0000000000000000020B"
static let pbxIOSSynthRef: String = "AABB0000000000000000020C"
static let pbxIOSSynthBuild: String = "AABB0000000000000000020D"
// AUv3 extension target IDs (separate from the host app)
static let pbxExtBlueprint: String = "AABB0000000000000000003A"
static let pbxExtProductRef: String = "AABB000000000000000000C0"
static let pbxExtGroup: String = "AABB000000000000000000C1"
static let pbxExtBuildConfigList: String = "AABB000000000000000000C2"
static let pbxExtDebugConfig: String = "AABB000000000000000000C3"
static let pbxExtReleaseConfig: String = "AABB000000000000000000C4"
static let pbxExtSourcesPhase: String = "AABB000000000000000000C5"
static let pbxExtFrameworksPhase: String = "AABB000000000000000000C6"
static let pbxExtResourcesPhase: String = "AABB000000000000000000C7"
static let pbxExtCopyAppexPhase: String = "AABB000000000000000000C8"
static let pbxExtAppexInAppFile: String = "AABB000000000000000000C9"
static let pbxExtTargetDep: String = "AABB000000000000000000CA"
static let pbxExtContainerProxy: String = "AABB000000000000000000CB"
static let pbxExtSynthRef: String = "AABB000000000000000003A0"
static let pbxExtSynthBuild: String = "AABB000000000000000003A1"
static let pbxExtAuRef: String = "AABB000000000000000003A2"
static let pbxExtAuBuild: String = "AABB000000000000000003A3"
static let pbxExtVCRef: String = "AABB000000000000000003A4"
static let pbxExtVCBuild: String = "AABB000000000000000003A5"
static let pbxExtInfoPlistRef: String = "AABB000000000000000003A6"
static let pbxAppEntitlementsRef: String = "AABB000000000000000003A7"
static let pbxExtEntitlementsRef: String = "AABB000000000000000003A8"
// MARK: - Helpers
/// Year string for `NSHumanReadableCopyright`. Pulled out so tests can
/// reason about output stability and the year doesn't get hardcoded.
static func currentYearString() -> String {
let calendar: Calendar = Calendar(identifier: .gregorian)
let year: Int = calendar.component(.year, from: Date())
return String(year)
}
/// Atomic-write helper that cleans up `projectRoot` on first failure.
/// Mirrors the cleanup behaviour of `scaffold(name:template:in:)`.
static func writeFiles(
_ files: [(String, String)],
fm: FileManager,
projectRoot: String
) throws {
for (path, content) in files {
do {
try content.write(toFile: path, atomically: true, encoding: .utf8)
} catch {
try? fm.removeItem(atPath: projectRoot)
throw Error.fileSystemError(path: path,
reason: error.localizedDescription)
}
}
}
}