Files

262 lines
14 KiB
Markdown
Raw Permalink 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.
# Xcode File Templates
Lyrebird ships a small set of Xcode file templates (`.xctemplate` bundles) for the
common code shapes — Generators, Synthesizers, and Tasks. After install, they appear
in Xcode's New File dialog (`⌘N`) under a **Lyrebird** section.
---
## Install
Two paths — both copy the same templates to
`~/Library/Developer/Xcode/Templates/File Templates/Lyrebird/`. No Xcode
restart required; Xcode rescans on next `⌘N`.
### Via the `lyrebird` CLI (preferred)
```sh
lyrebird install-templates # error if already installed
lyrebird install-templates --force # overwrite existing install
lyrebird uninstall-templates
```
The CLI bundles every `.xctemplate` as an SPM resource on the `LyrebirdCLI`
target, so the binary needs no access to the repo at install time — copy
`lyrebird` to `/usr/local/bin` and `install-templates` keeps working from
any working directory.
Both verbs are also available inside the interactive `lyrebird>` shell.
### Via shell script (repo-checkout install)
From the repo root, equivalent to the CLI:
```sh
bash scripts/install-xcode-templates.sh
bash scripts/install-xcode-templates.sh --dry-run # preview only
bash scripts/uninstall-xcode-templates.sh
```
Re-running `install-xcode-templates.sh` is idempotent (`rsync --delete`).
Both source paths read from `Sources/LyrebirdCLI/Resources/XcodeTemplates/`,
which lives there so SPM can bundle them as a target resource.
---
## Templates shipped
### Tier 1 — usable from any project that depends on Lyrebird
| Template | Generates | Use when |
|---|---|---|
| **Lyrebird Generator** | `public enum <Name>` with `_Base`, `Audio`, `Control` + `GeneratorEnum` conformance | Implementing a new signal-producing or signal-processing Generator family. |
| **Lyrebird Synthesizer** | `final class <Name>: SynthesizerBase` with `@LiveParam` slots and a stubbed `build()` body | Defining a new synth (oscillator + envelope + output) that you add to an engine via `engine.add(_:)`. |
| **Lyrebird Task** | `func make<Name>() -> LyrebirdTask` factory plus a private example Synthesizer | Scheduling a stream of events from a background thread with pause/resume/stop support. |
These templates start with `import LyrebirdSynth` (or `@_spi(LyrebirdExtensions) import
LyrebirdSynth` for the Generator template, which references the SPI-marked `MulAddSpec`)
and use only public + SPI API. They compile cleanly in any project that has Lyrebird
as a Swift Package dependency.
### Tier 1b — in-tree contributor templates
| Template | Generates | Use when |
|---|---|---|
| **Lyrebird Oscillator** | `public enum <Name>` whose `_Base` extends `OscillatorBase`; inherits `_phase` / `_freqInput` / `_freqIsGenerator` / `_mulAdd` | Adding a new oscillator family inside the Lyrebird module. Drop the file under `Sources/Lyrebird/Generators/Oscillators/`. |
| **Lyrebird Noise Generator** | `public enum <Name>` whose `_Base` extends `NoiseBase`; inherits `rngState` + `_mulAdd`; xorshift64 PRNG seeded via `lyrebirdSeedXorshift64(from:mixConstant:)` | Adding a new noise / random-source family. Drop the file under `Sources/Lyrebird/Generators/Noise/`. |
| **Lyrebird Filter** | Audio-only `final class Audio: GeneratorBase` using `runRBJBiquadBlock` with a `computeCoefficients` closure carrying the Audio EQ Cookbook formula | Adding a new RBJ biquad filter shape. Drop the file under `Sources/Lyrebird/Generators/Filters/`. |
These templates extend module-internal base classes (`OscillatorBase`, `NoiseBase`)
or call module-internal helpers (`runRBJBiquadBlock`, `lyrebirdSeedXorshift64`,
`normalizeLFPhase`, `fillRampedResult`) and are **only useful inside the Lyrebird
module**. Each generated file carries an in-tree-only banner comment at the top.
External users adding their own oscillators / noise / filters should start from
the basic **Lyrebird Generator** template and declare the relevant state (phase
accumulator, PRNG state, biquad coefficients) inline.
### Tier 2 — extended Generator + Synthesizer shapes
| Template | Generates | Use when |
|---|---|---|
| **Lyrebird Demand Generator** | `final class <Name>: DemandGenerator` with `nextValue()` / `reset()` / `isExhausted` | Defining a pure value source consumed by `Demand.Audio` / `Demand.Control` pullers — one value per trigger edge. |
| **Lyrebird Multi-Channel Generator** | `final class <Name>: GeneratorBase, AudioGenerator` with fixed `outputChannelCount`, multi-row `_result`, channel-aware mul/add | Adding a Generator whose output has 2+ channels (panners, spatial decoders, multi-bus mixers). Modeled on Pan2. |
| **Lyrebird Synthesizer (UI)** | `final class <Name>: SynthesizerBase` with `@UIParam` slots and a stubbed `build()` body | Defining a synth whose parameters bind to SwiftUI controls (`ParameterKnob`, `ParameterSlider`, `ParameterXY`). Requires the LyrebirdUI module. |
| **Lyrebird UI View** | `public struct <Name>: View` with `@Observable` controller, `ScopeCapture` + `LyrebirdScopeView`, parameter knobs, play/stop button | Building a SwiftUI front-end for a `@UIParam`-annotated synth. Requires the LyrebirdUI module. |
| **Lyrebird Generator Test Suite** | `@Suite("…") struct <Name> { @Test … }` using `makeTestEngine` / `makeSynthGraph` / `advanceBlock` helpers | Adding a Swift Testing suite for a new Generator. Drop the file into `Tests/LyrebirdTests/` — the helpers are module-internal. |
| **Lyrebird NRT Render** | `main.swift` with a `SynthesizerBase` stub and an NRTDriver that renders the duration to disk | Building a standalone executable target that produces an offline audio file. Drop the file into the `Sources/<exec-target>/` directory of an `executableTarget`. |
| **Lyrebird Score** | `func make<Name>() -> Score` building a two-part Score with the DSL (Note/Rest/Chord/Tuplet/dynamics/articulations); doc comment shows `toMusicXMLString()` / `Score.fromMusicXML()` round-trip and `allEvents` iteration | Authoring a notated score in code and exporting it to MusicXML 4.0. Drop the file anywhere in a target that links `Lyrebird`. |
The UI templates (`Synthesizer (UI)` and `UI View`) add `import LyrebirdUI` and
compile cleanly in projects with both `Lyrebird` and `LyrebirdUI` as
dependencies. The test-suite and NRT templates only compile in their respective
target kinds (`Test`, `executableTarget`) and are reported as `SKIP` in the
in-tree / external validation passes by design.
### Tier 3 — extended subsystems (MIDI / OSC / Spectral / Buffer / Process / AUv3)
| Template | Generates | Use when |
|---|---|---|
| **Lyrebird Spectral Processor** | `final class <Name>: SpectralProcessor` with a `process(spectral:engine:)` body that walks every bin in `SpectralBuffer` | Adding a custom FFT-domain transform (filter, pitch shift, cross-synthesis, freeze). Wire into `SpectralChain.Audio` as a `.mono` stage. |
| **Lyrebird MIDI Handler** | `func make<Name>(engine:clientName:) throws -> MIDI` factory with `noteOn` / `noteOff` / `controlChange` dispatch + a `midiNoteToHz` helper | Wiring CoreMIDI input to engine-level state. Handler closure runs on `lyrebird.midi` queue (not RT). |
| **Lyrebird OSC Handler** | `func make<Name>(engine:port:) throws -> OSCServer` factory with starter `/freq` / `/amp` / `/note/{on,off}` handlers + a `doubleValue(_:)` argument-coercion helper | Wiring an OSC UDP server to engine state. Handlers run on `lyrebird.osc.handlers` queue. |
| **Lyrebird Buffer Reader** | `final class <Name>: SynthesizerBase` that loads a multichannel `LyrebirdBuffer` at init and plays it via `PlayBuffer.Audio` with `nativeRateScale` SR compensation | Building a sample-playback Synthesizer (loop / one-shot / rate-modulated). |
| **Lyrebird Process** | `struct <Name>: LyrebirdProcessFactory` whose `createProcess()` returns a `LyrebirdProcess` with a 4-point envelope (attack / sustain / release / silence), `releaseNode`, async body closure, and `onRelease` / `onFinished` callbacks | Building an envelope-governed audio process (Lyrebird's equivalent of SuperCollider's `ProcMod`). |
| **Lyrebird AUv3 Source-Slot Synth** | A `SynthesizerBase` + `LyrebirdAudioUnit` pair (Synth class + `<Name>AudioUnit` AU wrapper) with `parameterMetadata()` exposing `@LiveParam` slots to the host. Includes step-by-step Info.plist + `AUViewController` integration notes. | Wrapping a Synthesizer as an Audio Unit App Extension (.appex) for Logic / GarageBand / AUM / Loopy Pro. Pair with the `Demos/LyrebirdAUv3Demo` reference project. |
All six Tier 3 templates compile in projects depending on Lyrebird as a Swift
Package and are reported as `OK (external)` by the validator. None require
LyrebirdUI.
Each template prompts for a name in Xcode's dialog. The name becomes both the file
name and the top-level identifier inside the file.
---
## Generated shapes
### Lyrebird Generator
The Generator template emits the canonical pattern matched by every built-in
Generator family in `Sources/Lyrebird/Generators/`:
```swift
public enum MyGenerator {
public class _Base: GeneratorBase {
let inputSource: any ValidGeneratorInput
let _mulAdd: MulAddSpec
public init(
_ signal: any ValidGeneratorInput,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) { ... }
}
public final class Audio: _Base, AudioGenerator {
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count)
// sample-rate processing
}
}
public final class Control: _Base, ControlGenerator {
public var previousOutputValue: Double = 0.0
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count)
// block-rate scalar + linear ramp to previousOutputValue
}
}
}
extension MyGenerator: GeneratorEnum {
public typealias AudioType = MyGenerator.Audio
public typealias ControlType = MyGenerator.Control
}
```
Fill in `_transform(_:)` (one line) and you have a working Audio + Control pair
with `mul` / `add` wiring and the sub-block ramp pattern already in place.
If you only need one rate, delete the other class plus its line in the
`GeneratorEnum` extension.
See [`writing-generators.md`](../protocols/writing-generators.md) for the full
Generator protocol contract, shared helpers, and decision rules.
### Lyrebird Synthesizer
```swift
public final class MySynth: SynthesizerBase {
@LiveParam public var frequency: Double = 440.0
@LiveParam public var amplitude: Double = 0.25
public override func build() {
let osc = OscSin.Audio(freq: $frequency)
output(bus: 0, source: osc * $amplitude)
}
}
```
Use `$paramName` (the projected value of `@LiveParam`) to pass a live-mutable
parameter as a generator input. Direct mutation (`synth.frequency = 880.0`) is
atomic and RT-safe.
See [`synthesizer.md`](../protocols/synthesizer.md) for the full Synthesizer
protocol and lifecycle.
### Lyrebird Task
```swift
public func makeMyTask() -> LyrebirdTask {
LyrebirdTask { ctx in
while true {
let note = ExampleNote()
ctx.add(note)
try ctx.wait(seconds: 0.25)
}
}
}
```
Call `task.start(engine:)` to begin, `task.pause()` / `task.resume()` to control,
`task.stop()` to exit cleanly (raises `LyrebirdRoutineError.stopped` inside the
next `wait`, which the closure handles internally).
See [`routine-task.md`](routine-task.md) for the full scheduling model.
---
## Validating templates
Templates are validated by `scripts/validate-xcode-templates.sh`. Three modes:
```sh
bash scripts/validate-xcode-templates.sh # --quick (default)
bash scripts/validate-xcode-templates.sh --full # + in-tree compile against Lyrebird
bash scripts/validate-xcode-templates.sh --external # + compile as an external SPM package
```
`--quick` runs `plutil -lint` on each `TemplateInfo.plist` and parses the
expanded `___FILEBASENAME___.swift` with `swift -frontend -parse` to confirm
the generated code is well-formed Swift.
`--full` adds an in-tree compile pass: it drops the expanded file into
`Sources/Lyrebird/Generators/Math/Probe.swift`, runs `swift build`, and removes
the file via `trap` so the working tree stays clean even on failure. This catches
template breakage from upstream API renames (e.g. `EnvGen` → `EnvelopeGen`).
`--external` adds a third pass: for every template whose body contains
`import LyrebirdSynth` (Tier 1 templates), the script creates a temporary SPM package
that depends on the local Lyrebird repo path, drops the expanded file into it,
and runs `swift build`. This proves the template works for users who consume
Lyrebird as a Swift Package dependency. In-tree-only templates (Tier 1b — no
`import LyrebirdSynth` line) are reported as `SKIP` here by design.
CI runs `--external` on every PR that touches `Xcode/Templates/` or
`Sources/Lyrebird/`.
---
## Adding a new template
1. Create `Xcode/Templates/Lyrebird/<Name>.xctemplate/` with two files:
- `TemplateInfo.plist` — kind, summary, options, allowed types
- `___FILEBASENAME___.swift` — source body with Xcode placeholders
2. Use the placeholders Xcode expands:
- `___FILEBASENAME___` — file name (preserves user's casing)
- `___FILEBASENAMEASIDENTIFIER___` — sanitized Swift identifier
- `___FILEHEADER___` — the project's standard file header comment block
- `___FULLUSERNAME___`, `___DATE___`, `___YEAR___` — author / date stamps
3. (Optional) Add a `TemplateIcon.png` (48×48) and `TemplateIcon@2x.png` (96×96)
for the Xcode dialog icon.
4. Add custom prompts in `TemplateInfo.plist > Options` if the template needs
user input beyond the file name (parameter types, channel count, etc.).
5. Run `bash scripts/validate-xcode-templates.sh --full` — must pass.
6. Add an entry to the "Templates shipped" table above.
The `TemplateInfo.plist` schema is described in Apple's Xcode docs under
"File Templates" — the same format is used by Xcode's built-in templates at
`/Applications/Xcode.app/Contents/Developer/Library/Xcode/Templates/File Templates/`.
Copy one of those as a starting point if you need an exotic option type.