35 Commits

Author SHA1 Message Date
josh de4d650378 Merge rig-library: iCloud rig library + builder layout rework 2026-06-27 20:17:37 -07:00
josh 6e299b9d38 Rework builder layout: scope beside stacked mixer + horizontal pedal picker
Reclaim vertical space in ShoeGazeBuilderView. The top section now places
the scope + CPU meters on the left (width matched to the mixer's
Solo/Blend/All control column) and a right column that stacks the board
mixer over a horizontal pedal picker. The board canvas takes the full
width below.

- PedalPaletteView gains an `axis` parameter: `.vertical` keeps the
  full-width sidebar column; `.horizontal` lays the catalog out as a row of
  fixed-width cards for a horizontal scroller.
- Remove the old left palette sidebar and the stacked-under-palette scope.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 20:11:18 -07:00
josh 9a8e5461c0 Make rig library loads/resolve fully off-main
Move the remaining synchronous main-thread I/O off the main actor:

- RigLibraryStore now constructs instantly with a local placeholder and
  exposes an awaitable async start(): it resolves the iCloud-or-local
  location off-main (the blocking ubiquity lookup), loads entries off-main
  via the shared ioQueue (so a reload can't drop a just-saved rig), then
  sets isLoaded. reload() is async; iCloud metadata updates re-read via it.
- Seeding moves into RigLibraryBootstrap.start(_:seedFrom:), which seeds a
  "Default" rig only AFTER the (possibly iCloud) library has loaded and is
  still empty — preventing a duplicate "Default" on every synced device on
  first launch.
- Sidebar shows a Loading state until isLoaded; the builder restores the
  persisted current-rig highlight when isLoaded flips true (initialRigID
  param dropped).
- Shells construct the store synchronously and start it asynchronously
  (macOS via Task in didFinishLaunching; iOS via .task). Codec + file
  helpers are nonisolated static so background work needs no actor hop.
- Tests await store.start().

Full suite: 206 passing.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 19:50:38 -07:00
josh 849240e6e2 Make rig saves non-blocking (background disk I/O)
Save/delete/eraseAll now update the in-memory entries on the main actor
immediately and run the file write/delete — including NSFileCoordinator —
on a serial background queue, removing the UI stall the synchronous
coordinated write caused (especially on the iCloud path).

- Encoding stays synchronous so encode errors still surface to the caller;
  only the disk write is deferred (logs on failure).
- File-system helpers and coordinated I/O are now nonisolated static so the
  background queue can call them without touching actor state.
- Add flushPendingWrites() to drain the queue; called by tests asserting
  on-disk state and by both app shells at termination / background.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 19:40:02 -07:00
josh e8e134499d Add macOS New/Save Rig menu items and save-on-switch prompt
- macOS File menu gains New Rig (⌘N) and Save Rig (⌘S), which forward to
  the in-window builder via shoeGazeNewRig / shoeGazeSaveRig notifications
  so the naming prompt and current-rig highlight update correctly.
- Selecting a different rig while the current one has unsaved changes now
  prompts Save / Don't Save / Cancel (both platforms). Dirtiness is
  captureState() != the loaded entry's state; a backing-less working rig
  with boards counts as dirty.
- Generalize saveCurrentRig to take a completion (used by Save & Clear and
  by save-then-switch).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 18:04:55 -07:00
josh dc42db0c59 Add iCloud-synced rig library
Replace the single hand-saved rig file with a managed library of named
rigs persisted in app storage and synced across devices and both builder
apps via a shared iCloud container (iCloud.net.realizedsound.ShoeGazeData),
falling back to local storage when iCloud is unavailable.

Core (LyrebirdShoeGaze/Presets):
- RigEntry: named, timestamped ShoeGazeState (a whole multi-board rig).
- RigArchive: portable multi-rig JSON bundle for backup/transfer; legacy
  single-rig files import as a one-rig archive.
- RigLibraryStore (@MainActor @Observable): one JSON file per rig, with
  NSFileCoordinator writes and NSMetadataQuery live remote-change watching.
- RigLibraryLocation: iCloud-or-local directory resolver (skips the slow
  ubiquity lookup when no iCloud account is signed in).
- ShoeGaze.loadRig(from: ShoeGazeState) + captureEntry; shared filename
  sanitizer factored out of BoardVersionStore.

UI (LyrebirdShoeGazeUI):
- RigLibrarySidebarView: persistent left listing with new/save/save-as/
  duplicate/rename/delete/erase-all and archive import/export.
- RigNamePrompt; RigLibraryBootstrap one-call shell setup.
- ShoeGazeBuilderView: sidebar wired in; selecting a rig replaces the
  session; File menu / sidebar do whole-library archive import/export.

Shells/entitlements: both builder targets own+start the store and carry
the iCloud Documents entitlement; NSUbiquitousContainers exposes the rigs
in the Files app. (macOS pbxproj also carries a pre-existing 1.0->1.1.1
version bump.)

Tests: RigEntry/RigArchive round-trip + RigLibraryStore CRUD/import/export
(15 new; full suite 206 passing).

Provisioning (manual, not done here): enable the iCloud container on both
App IDs and select it in Signing & Capabilities for both targets.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 17:56:10 -07:00
josh b55df174a6 Fix dragging an existing pedal into a region lane (cross-lane move)
Drag/drop only supported add: (palette→anywhere) and same-lane reorders, so
dragging a pedal from the main chain (or another lane) into a Stereo Unzip /
Split / Parallel lane highlighted the lane but the drop was a no-op.

- New core ShoeGaze.movePedal(from:at:to:in:) moves a pedal across lanes,
  preserving its PedalState (params), with destination-index correction when the
  removal deletes a top-level segment before the target region.
- BoardFlowView routes movemain:/movebranch: payloads dropped on a lane (or the
  main chain, or another lane's card) through it via moveAcross(_:toLane:).

Tests: move a main pedal into an unzip lane (params preserved); move a pedal
that sits before the region (index-adjust path).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 20:24:32 -07:00
josh f87fc1d4b1 1.1.1: move info button to top-left; fix empty-lane drag-drop
- PedalView: the ⓘ info button now sits under the top-left corner screw instead
  of on the name plate.
- BoardFlowView: empty region lanes (Stereo Unzip / Split / Parallel) were nearly
  transparent, so their drop target had no hit area and releases landed on
  nothing. Add contentShape(Rectangle()) so the whole lane frame accepts drops.
  (Core lane append already worked — verified by existing API tests.)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 19:43:57 -07:00
josh a99c3e86ce Date the 1.1.0 release 2026-06-26 19:34:31 -07:00
josh 900b441082 Review fixes: cache pedal summaries; stop engine around Clear
- PedalRegistry.summaries caches displayName→summary once, so the picker no
  longer constructs a fresh Pedal per row on every render.
- performClear stops the engine around the remove-all + reseed and restarts it,
  avoiding a one-block bus-reuse glitch (same pattern as loadRig/setInputSource).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 19:29:06 -07:00
josh 8c701af128 Add stereo Diffuser pedal
A .widener pedal that splits the dry signal into overlapping RBJ band-pass bands
and pans each by frequency (low to left, high to right); the spread knob fans the
spectrum from mono (spread 0) to a wide diffuse image (spread 1), using linear
pan expressed purely as node arithmetic.

Registered, with PedalType.diffuser, enclosure color, palette order, summary,
and tests (non-silent stereo; L == R at spread 0; L != R at full spread).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 19:14:00 -07:00
josh 12c7dc60f7 Add RELEASES.md (1.0 baseline + 1.1 changes)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 19:08:47 -07:00
josh 0d17ed260b Persist board across restarts + Clear button with save prompt
Persistence (macOS + iOS):
- RigStore autosaves the rig (rigData JSON) to Application Support and restores
  it on launch. App models restore-or-seed at init; macOS saves on terminate +
  resignActive, iOS saves on scenePhase leaving .active. The builder also
  autosaves after structural edits (add board/pedal, load, clear).

Clear (both platforms):
- A Clear button in the builder opens a confirmation dialog: Save & Clear /
  Clear Without Saving / Cancel. Clear removes all boards and seeds one fresh
  empty board, then autosaves. Save & Clear triggers the save mechanism and only
  clears once the save completes (cancelling the save leaves the rig intact).
- The rig-save exporter is now cross-platform (was iOS-only) so Save and the
  Save & Clear flow work on macOS too; macOS keeps its File-menu Load.

Tests: RigStore save/restore round-trip across instances; restore is a no-op
with no autosave. 186 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 18:54:03 -07:00
josh f29ab609bd Add Chorus, Sustainer, Ring Modulator pedals + pedal-info UI
Pedals (each registered, with PedalType static, enclosure color, palette order,
summary, and tests):
- Chorus: true-stereo widener (two anti-phase modulated delay lines), distinct
  from the mono-summed Modulation chorus.
- Sustainer: one-knob compressor (sustain drives threshold/ratio/makeup via
  LinLin) + tone low-pass.
- Ring Modulator: dry × tunable sine carrier.

Pedal-info UI:
- Pedal.summary (open var, overridden by all 21 pedals; mandatory going forward).
- PedalRegistry.summary(for:) for the picker.
- PedalPaletteView rows show the summary as a subtitle.
- PedalView gains an ⓘ button → PedalInfoView sheet showing the description and
  the effect controls (knobs/sliders/switches) with ranges/options — excludes
  the common Mix/Level/bypass.

Tests: per-pedal build/param-change/knob-list; every built-in pedal has a
non-empty summary; info excludes common controls. 183 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 18:05:30 -07:00
josh 9bc049d8a3 Add 1.1 feature plans + ShoeGaze CLAUDE.md (mandatory pedal summary)
docs/plans: chorus (stereo), sustainer, ring modulator, and pedal-info UI.
CLAUDE.md: project conventions + a required checklist for new pedals, including
a mandatory user-facing summary used by the pedal-info UI.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 17:44:47 -07:00
josh 5040ea1518 Rename Mu-Tron pedal to Mutant (de-trademark)
Rename the user-facing 'Mu-Tron' pedal to the non-proprietary 'Mutant':
displayName, registry key, PedalType.mutant, enclosure color, palette order,
and the class (MuTronPedal -> MutantPedal) + test file. The underlying Lyrebird
MuTronIII generator (and its Mode/Sweep types) keep their names — that's the
dependency's DSP type, not user-facing.

Note: displayName doubles as the rig-save key, so rigs saved with 'Mu-Tron'
won't match on load (acceptable pre-1.0; nothing released).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-24 21:00:02 -07:00
josh 21b9123a87 Replace stringly-typed pedal API with PedalType tokens
appendPedal(type: String, to:) is replaced by appendPedal(_ kind: PedalType, to:),
where PedalType is an extensible RawRepresentable struct with static members for
the built-in pedals:

    try shoeGaze.appendPedal(.overdrive, to: board)

Discoverable/autocompleting call sites, still open for custom pedals
(PedalType("My Pedal")). rawValue == the pedal's displayName, so PedalRegistry
and the rig JSON format are unchanged — saved rigs load exactly as before.

Named PedalType (not PedalKind) to avoid colliding with Lyrebird's score-notation
PedalKind enum, which is visible when both modules are imported. The UI palette
wraps its registry-key strings as PedalType(key); demos/tests use the static
members. PedalRegistry.makePedal(type:) stays string-keyed as the serialization
boundary used by loadRig.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-24 20:34:45 -07:00
josh 24ce4564e8 Drop screenshot-instructions note from README
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-24 16:41:19 -07:00
josh b1303a25ae Add README screenshots (builder + board mixer)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-24 16:10:58 -07:00
josh 21fda7067d Expand README with project overview, pedal catalog, and screenshots
Replace the one-line description with a full README: feature list, the 18-pedal
catalog by category, requirements, products, getting-started snippets (headless
+ SwiftUI builder), demo-app guide, and a Screenshots section wired to
docs/images/ (relative paths render on the git host and in clones).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-24 14:59:04 -07:00
josh 8c601e2029 Share one global test signal across all boards
Each board previously got its own TestLoopSource, so multiple boards ran
independently-phased arpeggios and any rebuild restarted them out of sync —
audible polyrhythms. Now a single global TestLoopSource writes a shared test
bus, and each board gets a lightweight TestLoopTap (added .after the source)
copying that bus into its head bus. The shared source survives board
add/remove, so the test signal stays phase-locked and never restarts.

- ShoeGaze: globalTestSource + globalTestBus (lazy via ensureGlobalTestSource),
  per-board testLoopTaps; teardown removes taps + source and releases the bus.
- New TestLoopTap (generic bus copy, like HardwareInputPassThrough).
- ShoeGazeError.testBusUnavailable for an exhausted bus pool.
- Test: testLoop boards share the source via taps; removal leaves others intact.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-24 14:43:50 -07:00
josh 5a07a6d4b4 Add input gain stage to Compressor pedal
A pre-compression input gain knob (Input, dB, range [-12, +24], default 0)
boosts/cuts the signal before it hits the compressor, so driving the input
harder pushes more of the signal past the threshold. The dB value is converted
to a linear multiplier via Exp(dB * ln(10)/20) and applied to the dry signal.

Tests: knob list is [Input, Threshold, Ratio]; input gain changes the output.
The preset recall test now finds the Threshold knob by label, not position.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-24 12:32:32 -07:00
josh 475dd392e6 Fix iOS Load file picker not opening
Five presentation modifiers (.sheet, .alert, two .fileImporter, .fileExporter)
were stacked on the builder's root view. SwiftUI reliably drives only one
presentation per view node, so adding the Boards .sheet swallowed the iOS rig
Load importer — the Load button toggled its flag but no picker appeared. Move
each presentation onto its own Color.clear background anchor so they no longer
collide.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-24 08:07:37 -07:00
josh dff58175f1 Label delay decay knob 'Decay Time'
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 21:56:04 -07:00
josh 42268b65a1 Relabel delay Feedback knob as Decay
The Delay, Feedback Delay, and Ping-Pong knobs labelled 'Feedback' actually
drive DelayLineFeedback's decayTime (seconds to -60 dB), not a feedback gain —
the engine clamps the internal feedback coefficient below 1, so the control
can never grow/self-oscillate. Relabel to 'Decay' so the knob reads honestly.
Phaser's feedback is a real coefficient and is unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 21:40:45 -07:00
josh 2c36de5c0d Widen gap between knobs in short pedal rows
Centred one- and two-knob rows now use a wider, touch-friendly inter-knob gap;
full three-knob rows keep the tight spacing so they still fit the enclosure.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 21:29:25 -07:00
josh f19dc2c1b3 Centre pedal knob rows
Short knob rows (one or two knobs) now sit centred in the enclosure instead of
left-aligned, via symmetric spacers around each row. Shared PedalView, so it
applies on macOS and iOS.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 21:26:54 -07:00
josh 6ad813601f Review fixes: reindex activeBoardIndex; safer live-input rebuild
- moveBoard/removeBoard now keep activeBoardIndex pointing at the soloed board
  (track by identity on move; shift down or clear on remove), so the Solo
  highlight no longer lights the wrong cell after reorder or delete.
- rebuildWithLiveInput snapshots the rig before any teardown and aborts if the
  snapshot fails, instead of tearing down then seeding a fallback (no silent
  rig loss). The engine-already-has-input early return now also persists the
  live-input selection, via a shared selectLiveInputAndPersist helper.
- Test: activeBoardIndex tracks reorder and removal.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 21:22:44 -07:00
josh 652a5a76ca Default iOS builder to one input channel
Construct the iOS engine with one input channel by default so live input is
available immediately and the In: stepper reads 1. Trade-off: iOS prompts for
microphone access at the first Start even while input defaults to test loop.
The permission-gated enableLiveInput() rebuild stays in place for any future
input-less configuration.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 21:10:13 -07:00
josh 9b31be7921 Resync EngineConfigView channel/rate fields on engine rebuild
EngineConfigView seeds its pending In/Out/Rate fields from @State(initialValue:),
which runs only once. After the iOS live-input rebuild swaps in a new engine
with one input channel, the stepper kept showing In: 0 even though audio read
the input. Resync the pending fields in a .task keyed on the engine's object
identity so a rebuilt engine's actual counts are reflected.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 20:57:34 -07:00
josh 705b4ed534 iOS live input via permission-gated engine rebuild
Live input on iOS needs an input channel, but constructing the engine with one
up-front makes iOS prompt for the microphone at the first Start even in
test-loop mode. Instead the engine starts input-less (no prompt) and is rebuilt
on demand:

- ShoeGazeBuilderView gains an optional onEnableLiveInput hook. When the user
  picks live input but the engine has no input channel, the picker offers a
  "Live Input" option that calls the hook; the input binding routes there too.
  On macOS (engine already has an input channel) the hook is nil and live input
  is selected directly.
- The iOS app model implements the hook: request mic access, then on grant
  snapshot the rig (rigData), stop + teardown the engine, rebuild it with one
  input channel, restore the rig (loadRig), and select live input. The new
  ShoeGaze is published so the @Observable host view re-binds.
- Input persistence restores live on relaunch: a saved live choice with the mic
  already authorised triggers the same rebuild silently (no prompt).

Test: a rig captured on a 0-input engine restores onto a freshly built 1-input
engine and live input is then selectable.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 20:52:11 -07:00
josh 4627b3b800 Boards sheet, ⌘1–9 switching, unified player bar, input persistence
Boards sheet (BoardsSheetView): rename, drag-reorder, swipe-delete, plus
per-board enable/solo/level and a Solo/Blend + crossfade header. Opened from a
"Boards…" button in the builder; presented with medium/large detents on iOS.
Makes ShoeGaze.moveBoard public to back the reorder.

Keyboard switching: hidden ⌘1…⌘9 buttons in the builder solo (live-switch to)
the matching board and select it as the edit target.

Unified player: ShoeGazeView drops its bespoke Active picker + crossfade field
and hosts the shared BoardBarView, matching the builder.

Input persistence: the builder saves the input choice (test loop vs live
channel) to UserDefaults and restores it on appear. With no saved choice it
defaults to live input when the mic is already authorised and an input channel
exists, else stays on the test loop. The iOS builder now opens one input
channel so live input is actually available there.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 20:38:43 -07:00
josh c25d783b71 Lock iOS builder + demo to iPad-only landscape
The board bar and scope/CPU layout already flow to iOS via the shared
ShoeGazeBuilderView. Restrict both iOS apps to iPad (TARGETED_DEVICE_FAMILY=2),
landscape-only orientations, and UIRequiresFullScreen so the wide builder
layout always has the room it needs.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 17:25:16 -07:00
josh b4b2f58762 Compact board mixer bar; align scope/CPU to palette width
Shrink BoardBarView to a fixed-height single horizontal scroll group with a
tighter two-row control column, so it wraps its elements and frees vertical
canvas for the pedals. Constrain the scope and CPU-meter views to the pedal
palette width, left-aligned, so they sit under the palette column.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 17:14:04 -07:00
josh c0605d295d Add board mixer bar UI + independent per-board audibility API
Multi-board playback was all-or-one: selectBoard soloed exclusively,
selectAllBoards summed. There was no way to play an arbitrary subset, and
the builder only exposed a dropdown that picked which board to *edit*.

ShoeGaze API:
- setBoard(_:audible:crossfadeSeconds:) toggles one board's select-gain in
  place without disturbing the others (Blend mixing); clears activeBoardIndex.
- soloBoard(_:crossfadeSeconds:) — the "Solo" verb (wraps selectBoard).
- isBoardAudible(_:) reports a board's live select-gain target.

UI — BoardBarView (shared macOS/iOS):
- Horizontal board-mixer strip. Each board is a channel cell: audible LED,
  Solo button, and a master-gain fader. Tapping a cell name sets the edit
  target (independent of what's audible); context menu silences/deletes.
- Solo | Blend mode switch + an All button + a crossfade slider.
- Replaces the builder's board dropdown and Add Board button; the cell's +
  adds a board.

Tests: solo/blend/all audibility transitions and activeBoardIndex tracking;
setBoard no-op for a board owned by another manager.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 16:51:17 -07:00
88 changed files with 5627 additions and 397 deletions
+64
View File
@@ -0,0 +1,64 @@
# ShoeGaze — Claude Context
A virtual guitar-pedalboard framework built on Lyrebird. Two products:
`LyrebirdShoeGaze` (core pedal/board framework, no SwiftUI) and `LyrebirdShoeGazeUI`
(SwiftUI views). Depends on the published Lyrebird package.
## Conventions
- **MIT SPDX header** on every new `.swift` file (first 5 lines): file name, `// Lyrebird`,
blank comment, `// Copyright (c) 2026 Joshua Parmenter / realizedsound`,
`// SPDX-License-Identifier: MIT`, then a blank line.
- **Explicit type annotations** on `let`/`var` bindings, named constants for non-trivial
literals, doc comments on public init params — matches the Lyrebird house style.
- Pedals subclass `Pedal` (in `Sources/LyrebirdShoeGaze/Pedals/`), expose parameters as
`@UIParam`, and surface them via `effectKnobs` / `effectSwitches` / `effectSliders`.
- A pedal's `displayName` **is** its serialization key and its `PedalType.rawValue`, and the
`PedalRegistry.builtIn` key. Keep all three identical when adding a pedal.
## Adding a new pedal — required checklist
1. `Sources/LyrebirdShoeGaze/Pedals/<Name>Pedal.swift` — subclass `Pedal`, override `effect`
(or `wideEffect`/`stereoEffect`), `effectKnobs`/`effectSwitches`/`effectSliders`.
2. **`summary`** — override `open var summary: String` with a one-line, user-facing
description. **This is mandatory for every pedal** (see "Pedal info" below).
3. Register in `PedalRegistry.builtIn["<DisplayName>"]`.
4. Add `PedalType.<name> = PedalType("<DisplayName>")`.
5. Enclosure color case in `PedalView.enclosureColor(for:)`.
6. Add to `PedalPaletteView.preferredOrder`.
7. Tests in `Tests/LyrebirdShoeGazeTests/<Name>PedalTests.swift` — at minimum: builds +
non-silent, each effect parameter measurably changes the output, knob-list assertion,
and (if it has switches/sliders) a preset round-trip.
8. Use `PedalType` static members at call sites (`appendPedal(.overdrive, to:)`), never raw
strings, except where a string is inherently dynamic (registry / preset load).
## Pedal info (mandatory)
Every pedal participates in the pedal-info UI:
- **`summary`** (required): a short, non-proprietary, user-facing sentence describing what
the pedal does. The picker shows it as a subtitle; the pedal's ⓘ info panel shows it as
the description. A new pedal without a non-empty `summary` is incomplete — a test asserts
every registered pedal has one.
- The info panel lists the **effect controls only** (`effectKnobs` + `effectSliders` +
`effectSwitches`) with their ranges/options — never the common Mix / Level / bypass. Put
the meaningful range and a clear unit in each control's `label`/`range` so the info panel
reads well.
## dB parameters
There is no dB→linear generator for a control-rate node. To apply a dB gain to a signal,
convert in the graph: `Exp.Audio($gainDB * dbToLinExpScale)` where
`dbToLinExpScale = ln(10)/20 ≈ 0.11512925464970229` (gives `10^(dB/20)`). RBJ shelving/peaking
filters take gain in dB directly, so pass dB nodes straight through.
## Build / test
- Package: `swift build` / `swift test --no-parallel` (the multi-engine suite can hit
Lyrebird's parallel-teardown flake without `--no-parallel`).
- Apps: `Demo/ShoeGaze.xcworkspace` (macOS builder, iPad builder, demos). iOS targets are
iPad-only, landscape.
## Planned work
`docs/plans/` holds the next-version feature plans.
@@ -163,7 +163,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1;
CURRENT_PROJECT_VERSION = 4;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = HE5VJFE9E4;
@@ -176,7 +176,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 15.0;
MARKETING_VERSION = 0.9;
MARKETING_VERSION = 1.1.1;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
@@ -194,7 +194,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1;
CURRENT_PROJECT_VERSION = 4;
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = HE5VJFE9E4;
ENABLE_HARDENED_RUNTIME = YES;
@@ -206,7 +206,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 15.0;
MARKETING_VERSION = 0.9;
MARKETING_VERSION = 1.1.1;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
+67 -24
View File
@@ -46,7 +46,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
private static let heightFraction: CGFloat = 0.88
/// The default pedal the seed board comes up with, so audio is audible immediately on Start.
private static let seedPedalType: String = "Overdrive"
private static let seedPedalType: PedalType = .overdrive
// MARK: - Owned objects
@@ -55,11 +55,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
private let shoeGaze: ShoeGaze
private let window: LyrebirdWindow
/// The rig library; constructed in `init`, resolved + loaded asynchronously after launch.
private let library: RigLibraryStore
/// Record toggle item, retained so `validateMenuItem(_:)` can flip its title + enabled state.
private var recordMenuItem: NSMenuItem?
/// Default file name offered by the Save panel.
private static let defaultRigFileName: String = "ShoeGazeRig"
/// Default file name offered by the archive Export panel.
private static let defaultArchiveFileName: String = "ShoeGaze Library"
// MARK: - Init
@@ -73,26 +76,34 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
numAudioBuses: AppDelegate.numAudioBuses,
driver: coreDriver
)
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
self.coreDriver = coreDriver
self.engine = engine
self.shoeGaze = ShoeGaze(engine: engine)
self.shoeGaze = shoeGaze
self.window = LyrebirdWindow(
title: "ShoeGaze Builder — Lyrebird Pedalboard",
width: AppDelegate.windowWidth,
height: AppDelegate.windowHeight
)
super.init()
seedInitialBoard()
// Stored `let`s must be set before `super.init()`. Restore the autosaved working rig (or
// seed a board) — operating on `shoeGaze`, not on `self` methods (unavailable pre-super).
if !RigStore.restore(into: shoeGaze) {
AppDelegate.seedInitialBoard(into: shoeGaze)
}
// The library constructs instantly; it resolves iCloud + loads asynchronously after launch.
self.library = RigLibraryBootstrap.makeStore()
super.init()
}
/// Seeds one board with a single pedal so the builder opens with an audible starting point.
private func seedInitialBoard() {
private static func seedInitialBoard(into shoeGaze: ShoeGaze) {
var created: PedalBoard?
do {
let board: PedalBoard = try shoeGaze.addBoard()
created = board
try shoeGaze.appendPedal(type: AppDelegate.seedPedalType, to: board)
try shoeGaze.appendPedal(AppDelegate.seedPedalType, to: board)
} catch {
if let board: PedalBoard = created { shoeGaze.removeBoard(board) }
print("[ShoeGazeBuilder] seed board failed: \(error)")
@@ -105,10 +116,20 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
installMainMenu()
let session: ShoeGaze = shoeGaze
let driver: CoreAudioDriver = coreDriver
let rigLibrary: RigLibraryStore = library
window.open {
ShoeGazeBuilderView(shoeGaze: session, hardwareSampleRate: { driver.deviceSampleRate })
ShoeGazeBuilderView(
shoeGaze: session,
library: rigLibrary,
hardwareSampleRate: { driver.deviceSampleRate }
)
}
anchorWindowLeft()
// Resolve iCloud + load the library off the main thread, then seed from the working rig if
// it is still empty (first run).
let rigSession: ShoeGaze = shoeGaze
Task { await RigLibraryBootstrap.start(rigLibrary, seedFrom: rigSession) }
}
/// Anchors the window `leftMargin` points from the left of the visible screen and sizes it to
@@ -134,9 +155,17 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
}
func applicationWillTerminate(_ notification: Notification) {
RigStore.save(shoeGaze)
// Ensure any in-flight background rig-library writes finish before exit.
library.flushPendingWrites()
engine.stop()
}
func applicationDidResignActive(_ notification: Notification) {
// Persist on every deactivation too, so state survives an unexpected exit.
RigStore.save(shoeGaze)
}
// MARK: - Main menu
/// Builds a minimal menu bar: an application menu with About / Hide / Quit (⌘Q).
@@ -171,8 +200,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
mainMenu.addItem(fileMenuItem)
let fileMenu: NSMenu = NSMenu(title: "File")
fileMenuItem.submenu = fileMenu
addItem(to: fileMenu, title: "Save Rig…", action: #selector(saveRigAction(_:)), key: "s")
addItem(to: fileMenu, title: "Load Rig…", action: #selector(loadRigAction(_:)), key: "o")
// Per-rig commands forward to the in-window builder (which owns the current-rig state and
// the naming prompts) via notifications.
addItem(to: fileMenu, title: "New Rig", action: #selector(newRigAction(_:)), key: "n")
addItem(to: fileMenu, title: "Save Rig", action: #selector(saveRigAction(_:)), key: "s")
fileMenu.addItem(NSMenuItem.separator())
// The whole-library archive: a single file holding every rig, for backup or transfer.
addItem(to: fileMenu, title: "Export Archive…", action: #selector(exportArchiveAction(_:)), key: "e")
addItem(to: fileMenu, title: "Import Archive…", action: #selector(importArchiveAction(_:)), key: "i")
// Board menu — add board + transport.
let boardMenuItem: NSMenuItem = NSMenuItem()
@@ -221,34 +256,42 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
// MARK: - Menu actions
@objc private func newRigAction(_ sender: Any?) {
// Forward to the builder view, which owns the current-rig state and naming prompt.
NotificationCenter.default.post(name: .shoeGazeNewRig, object: nil)
}
@objc private func saveRigAction(_ sender: Any?) {
NotificationCenter.default.post(name: .shoeGazeSaveRig, object: nil)
}
@objc private func exportArchiveAction(_ sender: Any?) {
let panel: NSSavePanel = NSSavePanel()
panel.allowedContentTypes = [.json]
panel.nameFieldStringValue = "\(AppDelegate.defaultRigFileName).json"
panel.nameFieldStringValue = "\(AppDelegate.defaultArchiveFileName).json"
panel.canCreateDirectories = true
let session: ShoeGaze = shoeGaze
let rigLibrary: RigLibraryStore = library
panel.begin { response in
guard response == .OK, let url: URL = panel.url else { return }
do { try session.saveRig(to: url) }
catch { print("[ShoeGazeBuilder] saveRig failed: \(error)") }
do { try rigLibrary.exportArchiveData().write(to: url, options: .atomic) }
catch { print("[ShoeGazeBuilder] export archive failed: \(error)") }
}
}
@objc private func loadRigAction(_ sender: Any?) {
@objc private func importArchiveAction(_ sender: Any?) {
let panel: NSOpenPanel = NSOpenPanel()
panel.allowedContentTypes = [.json]
panel.canChooseDirectories = false
panel.allowsMultipleSelection = false
let session: ShoeGaze = shoeGaze
let activeEngine: SynthesisEngine = engine
let rigLibrary: RigLibraryStore = library
panel.begin { response in
guard response == .OK, let url: URL = panel.url else { return }
// loadRig rebuilds the graph; stop the engine around it and restart if it was running.
let wasRunning: Bool = activeEngine.isRunning
if wasRunning { activeEngine.stop() }
do { try session.loadRig(from: url) }
catch { print("[ShoeGazeBuilder] loadRig failed: \(error)") }
if wasRunning { try? activeEngine.start() }
do {
let data: Data = try Data(contentsOf: url)
_ = try rigLibrary.importArchive(from: data)
} catch {
print("[ShoeGazeBuilder] import archive failed: \(error)")
}
}
}
+12
View File
@@ -28,5 +28,17 @@
<string>ShoeGaze Builder can route a hardware input channel through your pedalboard. Enable microphone access to use Live Input mode.</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
<key>NSUbiquitousContainers</key>
<dict>
<key>iCloud.net.realizedsound.ShoeGazeData</key>
<dict>
<key>NSUbiquitousContainerIsDocumentScopePublic</key>
<true/>
<key>NSUbiquitousContainerName</key>
<string>ShoeGaze</string>
<key>NSUbiquitousContainerSupportedFolderLevels</key>
<string>Any</string>
</dict>
</dict>
</dict>
</plist>
@@ -4,5 +4,17 @@
<dict>
<key>com.apple.security.device.audio-input</key>
<true/>
<key>com.apple.developer.icloud-container-identifiers</key>
<array>
<string>iCloud.net.realizedsound.ShoeGazeData</string>
</array>
<key>com.apple.developer.icloud-services</key>
<array>
<string>CloudDocuments</string>
</array>
<key>com.apple.developer.ubiquity-container-identifiers</key>
<array>
<string>iCloud.net.realizedsound.ShoeGazeData</string>
</array>
</dict>
</plist>
@@ -169,13 +169,14 @@
"$(inherited)",
"@executable_path/Frameworks",
);
CODE_SIGN_ENTITLEMENTS = ShoeGazeBuilderiOS/ShoeGazeBuilderiOS.entitlements;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilderiOS;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
SUPPORTS_MACCATALYST = NO;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 6.0;
TARGETED_DEVICE_FAMILY = "1,2";
TARGETED_DEVICE_FAMILY = 2;
};
name = Debug;
};
@@ -194,13 +195,14 @@
"$(inherited)",
"@executable_path/Frameworks",
);
CODE_SIGN_ENTITLEMENTS = ShoeGazeBuilderiOS/ShoeGazeBuilderiOS.entitlements;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilderiOS;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
SUPPORTS_MACCATALYST = NO;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 6.0;
TARGETED_DEVICE_FAMILY = "1,2";
TARGETED_DEVICE_FAMILY = 2;
};
name = Release;
};
+14 -3
View File
@@ -29,18 +29,29 @@
</dict>
<key>UILaunchScreen</key>
<dict/>
<key>UIRequiresFullScreen</key>
<true/>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>NSUbiquitousContainers</key>
<dict>
<key>iCloud.net.realizedsound.ShoeGazeData</key>
<dict>
<key>NSUbiquitousContainerIsDocumentScopePublic</key>
<true/>
<key>NSUbiquitousContainerName</key>
<string>ShoeGaze</string>
<key>NSUbiquitousContainerSupportedFolderLevels</key>
<string>Any</string>
</dict>
</dict>
</dict>
</plist>
@@ -0,0 +1,18 @@
<?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>com.apple.developer.icloud-container-identifiers</key>
<array>
<string>iCloud.net.realizedsound.ShoeGazeData</string>
</array>
<key>com.apple.developer.icloud-services</key>
<array>
<string>CloudDocuments</string>
</array>
<key>com.apple.developer.ubiquity-container-identifiers</key>
<array>
<string>iCloud.net.realizedsound.ShoeGazeData</string>
</array>
</dict>
</plist>
@@ -19,18 +19,26 @@ import LyrebirdShoeGazeUI
struct ShoeGazeBuilderiOSApp: App {
@State private var model: ShoeGazeBuilderiOSAppModel = ShoeGazeBuilderiOSAppModel()
@Environment(\.scenePhase) private var scenePhase
var body: some Scene {
WindowGroup {
NavigationStack {
ShoeGazeBuilderView(
shoeGaze: model.shoeGaze,
hardwareSampleRate: { model.hardwareSampleRate }
library: model.library,
hardwareSampleRate: { model.hardwareSampleRate },
onEnableLiveInput: { model.enableLiveInput() }
)
.navigationTitle("ShoeGaze Builder")
.navigationBarTitleDisplayMode(.inline)
.task { await model.startLibrary() }
}
.onDisappear { model.stop() }
}
.onChange(of: scenePhase) { _, phase in
// Persist the rig whenever the app leaves the foreground.
if phase != .active { model.save() }
}
}
}
@@ -8,6 +8,7 @@ import AVFoundation
import Observation
import LyrebirdSynth
import LyrebirdShoeGaze
import LyrebirdShoeGazeUI
/// Observable model owning the `SynthesisEngine` and `ShoeGaze` session for the iOS builder.
///
@@ -24,23 +25,80 @@ final class ShoeGazeBuilderiOSAppModel {
private static let blockSize: Int = 512
private static let outputChannels: Int = 2
// Default to one input channel so live input is available immediately. The trade-off is
// that the iOS driver runs a `.playAndRecord` session with the RemoteIO input element
// enabled, so iOS prompts for microphone access at the first Start even while the input
// still defaults to `.testLoop`. (The permission-gated `enableLiveInput()` rebuild remains
// available for any future build that starts input-less.)
private static let inputChannels: Int = 1
private static let numAudioBuses: Int = 256
private static let seedPedalType: String = "Overdrive"
private static let seedPedalType: PedalType = .overdrive
/// UserDefaults key persisting the input selection. Must match the key written by the
/// builder view (`ShoeGazeBuilderView.inputSelectionDefaultsKey`).
private static let inputSelectionDefaultsKey: String = "ShoeGaze.inputSelection"
/// Persisted value meaning "live input, channel 0".
private static let liveInputChannelZeroTag: Int = 0
// MARK: - Owned objects
/// The active ShoeGaze builder session.
/// The active ShoeGaze builder session. Swapped out when live input is enabled (the engine
/// is rebuilt with an input channel); the `@Observable` change re-binds the hosting view.
private(set) var shoeGaze: ShoeGaze
private let engine: SynthesisEngine
private let iosDriver: iOSAudioDriver
private var engine: SynthesisEngine
private var iosDriver: iOSAudioDriver
/// The shared rig library (iCloud-or-local). Independent of the engine, so it survives the
/// live-input engine rebuild.
private(set) var library: RigLibraryStore
/// The sample rate the audio session actually committed to (for the config mismatch warning).
var hardwareSampleRate: Double? { iosDriver.sessionSampleRate }
/// Resolves iCloud + loads the library off the main thread, then seeds it from the working rig
/// on first run. Call once from the app's `.task`. Safe to call again (no-op once non-empty).
func startLibrary() async {
await RigLibraryBootstrap.start(library, seedFrom: shoeGaze)
}
// MARK: - Init
init() {
ShoeGazeBuilderiOSAppModel.configureAudioSession()
let built: (engine: SynthesisEngine, driver: iOSAudioDriver, shoeGaze: ShoeGaze) =
ShoeGazeBuilderiOSAppModel.buildEngine(inputChannels: ShoeGazeBuilderiOSAppModel.inputChannels)
let shoeGaze: ShoeGaze = built.shoeGaze
self.engine = built.engine
self.iosDriver = built.driver
self.shoeGaze = shoeGaze
// Restore the autosaved working rig if there is one; otherwise seed a default board. Operate
// on the local `shoeGaze`, not `self.shoeGaze`: self may not be touched until every stored
// property (including `library`) is initialized.
if !RigStore.restore(into: shoeGaze) {
ShoeGazeBuilderiOSAppModel.seedFallbackBoard(into: shoeGaze)
}
// Construct the library instantly; it resolves iCloud + loads asynchronously via
// startLibrary() from the app's .task.
self.library = RigLibraryBootstrap.makeStore()
}
/// Persists the current rig. Call when the app moves to the background.
func save() {
RigStore.save(shoeGaze)
// Flush any in-flight background rig-library writes while we still have time in the
// background.
library.flushPendingWrites()
}
// MARK: - Audio session / engine construction
/// Activates the play-and-record audio session once. Idempotent; safe to call before each
/// engine build. Activating the session does not by itself prompt for microphone access —
/// the prompt only fires when an input-enabled engine first starts.
private static func configureAudioSession() {
let session: AVAudioSession = AVAudioSession.sharedInstance()
do {
try session.setCategory(.playAndRecord,
@@ -48,31 +106,108 @@ final class ShoeGazeBuilderiOSAppModel {
options: [.defaultToSpeaker, .allowBluetoothHFP])
try session.setActive(true)
} catch {
// Surface the failure: the engine is built from `session.sampleRate` below, which may
// report a stale/default rate if activation failed.
print("[ShoeGazeBuilderiOS] AVAudioSession setup failed: \(error)")
}
let sampleRate: Double = session.sampleRate
}
/// Builds a fresh engine + driver + empty `ShoeGaze` with the given input-channel count.
private static func buildEngine(
inputChannels: Int
) -> (engine: SynthesisEngine, driver: iOSAudioDriver, shoeGaze: ShoeGaze) {
let sampleRate: Double = AVAudioSession.sharedInstance().sampleRate
let driver: iOSAudioDriver = iOSAudioDriver()
let eng: SynthesisEngine = SynthesisEngine(
let engine: SynthesisEngine = SynthesisEngine(
blockSize: ShoeGazeBuilderiOSAppModel.blockSize,
sampleRate: sampleRate,
numOutputChannels: ShoeGazeBuilderiOSAppModel.outputChannels,
numInputChannels: 0,
numInputChannels: inputChannels,
numAudioBuses: ShoeGazeBuilderiOSAppModel.numAudioBuses,
driver: driver
)
self.iosDriver = driver
self.engine = eng
self.shoeGaze = ShoeGaze(engine: eng)
return (engine, driver, ShoeGaze(engine: engine))
}
// MARK: - Live input
/// Enables live input on iOS: requests microphone access, then (on grant) rebuilds the
/// engine with one input channel — preserving the current rig — and selects live input.
///
/// The rebuild is required because the input-channel count is fixed at engine construction,
/// and constructing with an input channel up-front would make iOS prompt for the microphone
/// at the first Start even in test-loop mode. Gating the rebuild behind an explicit request
/// keeps the prompt where the user expects it.
func enableLiveInput() {
MicrophonePermission.request { [weak self] granted in
guard let self, granted else { return }
self.rebuildWithLiveInput()
}
}
/// Snapshots the rig, rebuilds the engine with one input channel, restores the rig, and
/// selects live input on channel 0. No-op if the engine already has an input channel.
private func rebuildWithLiveInput() {
guard engine.numInputChannels == 0 else {
// Engine already has an input channel: just select live input, no rebuild.
selectLiveInputAndPersist()
return
}
let wasRunning: Bool = engine.isRunning
// Snapshot the rig BEFORE any teardown. If this fails, abort the rebuild rather than
// tear the engine down and lose the rig — the user stays on the current engine.
let snapshot: Data
do {
snapshot = try shoeGaze.rigData()
} catch {
print("[ShoeGazeBuilderiOS] rig snapshot failed; aborting live-input rebuild: \(error)")
return
}
engine.stop()
shoeGaze.teardown()
ShoeGazeBuilderiOSAppModel.configureAudioSession()
let rebuilt: (engine: SynthesisEngine, driver: iOSAudioDriver, shoeGaze: ShoeGaze) =
ShoeGazeBuilderiOSAppModel.buildEngine(inputChannels: 1)
self.engine = rebuilt.engine
self.iosDriver = rebuilt.driver
self.shoeGaze = rebuilt.shoeGaze
do {
// Teardown already happened, so a restore failure can only recover by seeding.
try shoeGaze.loadRig(from: snapshot)
} catch {
print("[ShoeGazeBuilderiOS] rig restore after rebuild failed: \(error)")
ShoeGazeBuilderiOSAppModel.seedFallbackBoard(into: shoeGaze)
}
selectLiveInputAndPersist()
if wasRunning { try? engine.start() }
}
/// Selects live input on channel 0 and persists the choice for restore-on-relaunch.
private func selectLiveInputAndPersist() {
do {
try shoeGaze.setInputSource(.liveInput(channel: 0))
UserDefaults.standard.set(
ShoeGazeBuilderiOSAppModel.liveInputChannelZeroTag,
forKey: ShoeGazeBuilderiOSAppModel.inputSelectionDefaultsKey
)
} catch {
print("[ShoeGazeBuilderiOS] selecting live input failed: \(error)")
}
}
/// Seeds a single default board so the rig is never empty after a failed restore.
private static func seedFallbackBoard(into shoeGaze: ShoeGaze) {
do {
let board: PedalBoard = try shoeGaze.addBoard()
board.label = "Board 1"
try shoeGaze.appendPedal(type: ShoeGazeBuilderiOSAppModel.seedPedalType, to: board)
try shoeGaze.appendPedal(ShoeGazeBuilderiOSAppModel.seedPedalType, to: board)
} catch {
print("[ShoeGazeBuilderiOS] seed board failed: \(error)")
print("[ShoeGazeBuilderiOS] fallback seed board failed: \(error)")
}
}
@@ -248,7 +248,7 @@ final class ShoeGazeDemoController {
///
/// Board 1: Overdrive → Delay → Reverb → Modulation
/// Board 2: Fuzz → Tremolo → Phaser → Compressor
/// Board 3: Mu-Tron → Auto-Wah → Feedback Delay → Multi-Tap Delay
/// Board 3: Mutant → Auto-Wah → Feedback Delay → Multi-Tap Delay
private func buildBoards() {
do {
let board1: PedalBoard = try shoeGaze.addBoard()
@@ -269,7 +269,7 @@ final class ShoeGazeDemoController {
let board3: PedalBoard = try shoeGaze.addBoard()
board3.label = "Board 3"
try board3.add(MuTronPedal())
try board3.add(MutantPedal())
try board3.add(AutoWahPedal())
try board3.add(FeedbackDelayPedal())
try board3.add(MultiTapDelayPedal())
@@ -174,7 +174,7 @@
SUPPORTS_MACCATALYST = NO;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 6.0;
TARGETED_DEVICE_FAMILY = "1,2";
TARGETED_DEVICE_FAMILY = 2;
};
name = Debug;
};
@@ -198,7 +198,7 @@
SUPPORTS_MACCATALYST = NO;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 6.0;
TARGETED_DEVICE_FAMILY = "1,2";
TARGETED_DEVICE_FAMILY = 2;
};
name = Release;
};
+2 -3
View File
@@ -29,16 +29,15 @@
</dict>
<key>UILaunchScreen</key>
<dict/>
<key>UIRequiresFullScreen</key>
<true/>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
+116 -1
View File
@@ -1,3 +1,118 @@
# ShoeGaze
A package depenedent on Lyrebird for creating and storing virtual Guitar Pedal Boards
**A virtual guitar-pedalboard framework for macOS and iPadOS, built on [Lyrebird](https://realizedsound.mooo.com/josh/Lyrebird).**
ShoeGaze turns Lyrebird's real-time synthesis engine into a stompbox rig: chain modeled
guitar pedals into one or more signal-flow boards, tweak them live with knobs and switches,
mix or switch between boards, and save the whole rig to disk. Run it on a synthesized test
signal (no hardware needed) or on live guitar through an audio input.
![ShoeGaze Builder](docs/images/builder-macos.png)
## Features
- **22 modeled pedals** across drive, dynamics, EQ/filter, modulation, delay/reverb, and
pitch — see the catalog below.
- **Multi-board rigs** — build several boards and a board-mixer bar to **Solo** one (amp-channel
style) or **Blend** any subset, each with its own level and a click-free crossfade.
- **Signal-flow editor** — drag pedals in from the palette; reorder, split into parallel or
stereo lanes, and merge back to mono.
- **Rig library** — name, save, duplicate, and switch between rigs from a sidebar; synced across
your devices and both apps via iCloud, with JSON archive import/export for backup.
- **Recording** — capture your output to timestamped files.
- **Test signal or live input** — a built-in arpeggiated test loop (shared across all boards so
they stay phase-locked) or a hardware input channel.
- **SwiftUI views** — a complete stompbox UI (`LyrebirdShoeGazeUI`) or just the headless
framework (`LyrebirdShoeGaze`) to drive your own interface.
## Pedal catalog
| Category | Pedals |
|---|---|
| Drive & dynamics | Overdrive, Fuzz, Compressor, Sustainer, Limiter, Noise Gate |
| EQ & filter | Graphic EQ, Auto-Wah, Mutant, Phaser |
| Modulation | Tremolo, Modulation, Chorus, Ring Modulator, Diffuser |
| Delay & reverb | Delay, Feedback Delay, Multi-Tap Delay, Ping-Pong, Reverb |
| Pitch & octave | Octave Splitter, Bass Octaver |
Every pedal exposes its parameters as knobs/switches and round-trips through the rig save format.
## Requirements
- macOS 15+ / iPadOS 18+ (iPad, landscape)
- Swift 6.0 toolchain / Xcode 16+
- [Lyrebird](https://realizedsound.mooo.com/josh/Lyrebird) 1.2.0+
## Packages
Two library products:
- **`LyrebirdShoeGaze`** — the core pedal/board framework (no SwiftUI).
- **`LyrebirdShoeGazeUI`** — SwiftUI pedalboard views (knobs, switches, faders, board mixer).
Add the dependency in your `Package.swift`:
```swift
.package(url: "https://realizedsound.mooo.com/josh/ShoeGaze", from: "1.0.0"),
```
## Getting started
Build a board and start the engine (macOS):
```swift
import Lyrebird
import LyrebirdShoeGaze
let driver = CoreAudioDriver()
let engine = SynthesisEngine(
blockSize: 512, sampleRate: 48_000,
numOutputChannels: 2, numInputChannels: 1,
numAudioBuses: 256, driver: driver
)
let shoeGaze = ShoeGaze(engine: engine) // defaults to the test-loop signal
let board = try shoeGaze.addBoard()
try shoeGaze.appendPedal(.overdrive, to: board)
try shoeGaze.appendPedal(.delay, to: board)
try shoeGaze.finalizeBoard(board)
try engine.start()
```
Drop in the full builder UI:
```swift
import SwiftUI
import LyrebirdShoeGazeUI
struct ContentView: View {
let shoeGaze: ShoeGaze
var body: some View {
ShoeGazeBuilderView(shoeGaze: shoeGaze)
}
}
```
## Demo apps
Open `ShoeGaze.xcworkspace` in Xcode and run a scheme from `Demo/`:
- **ShoeGazeBuilder** (macOS) / **ShoeGazeBuilderiOS** (iPad) — the full palette + board builder.
- **ShoeGazeDemo** / **ShoeGazeiOSDemo** — a minimal player view.
## Screenshots
| macOS builder | Board mixer |
|---|---|
| ![Builder](docs/images/builder-macos.png) | ![Board mixer](docs/images/board-mixer.png) |
## Built on Lyrebird
ShoeGaze is a sample project for [Lyrebird](https://realizedsound.mooo.com/josh/Lyrebird), a
native Swift audio-synthesis framework. Pedals are Lyrebird `Synthesizer` graphs of `Generator`
nodes; the board/engine plumbing handles real-time-safe signal routing and scheduling.
## License
MIT — see [LICENSE](LICENSE).
+71
View File
@@ -0,0 +1,71 @@
# Releases
## 1.1.1 — 2026-06-26
### Fixes
- Pedal **ⓘ info button** moved to the top-left corner (under the corner screw),
out of the way of the name plate.
- Fixed **dragging a pedal into a Stereo Unzip / Split / Parallel lane**. Dropping a pedal
from the main chain (or another lane) into a region lane now moves it there, preserving its
parameters — previously the drop was silently ignored. Empty lanes are also fully
hit-testable now.
## 1.1.0 — 2026-06-24
### New pedals
- **Chorus** — true-stereo chorus (two anti-phase modulated delay voices), distinct from the
mono Modulation chorus.
- **Sustainer** — one-knob compressor tuned for long, even sustain, with a tone control.
- **Ring Modulator** — multiplies the signal by a tunable sine carrier for metallic / bell /
robotic tones.
- **Diffuser** — stereo widener that fans the frequency spectrum across L/R, with a `spread`
control from mono to a wide, diffuse image.
### Pedal info UI
- Every pedal now has a one-line description (`summary`).
- The pedal picker shows each pedal's description as a subtitle.
- Each pedal has an ⓘ info button opening a panel with its description and effect controls
(knobs / sliders / switches) and their value ranges — excluding the common Mix/Level/bypass.
### Board persistence
- The board(s) persist across app restarts on macOS and iPadOS — the rig is autosaved to
Application Support and restored on launch (falls back to a default board if none).
- New **Clear** button removes all boards; it first prompts **Save & Clear / Clear Without
Saving / Cancel**, and "Save & Clear" only clears once the save completes.
- Rig save is now available in-view on macOS too (previously File-menu only).
### Developer notes
- Added `docs/plans/` (feature plans) and a project `CLAUDE.md` (conventions + a required
checklist for new pedals, including a mandatory `summary`).
---
## 1.0.0 — 2026-06-24
First stable release: a virtual guitar-pedalboard framework built on Lyrebird, for macOS and
iPadOS, in two products — `LyrebirdShoeGaze` (core) and `LyrebirdShoeGazeUI` (SwiftUI).
### Pedals (18)
Overdrive, Fuzz, Compressor (with input gain), Limiter, Noise Gate, Graphic EQ, Auto-Wah,
Mutant, Phaser, Tremolo, Modulation, Delay, Feedback Delay, Multi-Tap Delay, Ping-Pong, Reverb,
Octave Splitter, Bass Octaver. Delay-family "decay" controls are labelled **Decay Time**.
### Boards & mixing
- Multiple boards with a board-mixer bar: **Solo** one (amp-channel style) or **Blend** any
subset, each with its own level and a click-free crossfade.
- A board-manager sheet (rename, drag-reorder, swipe-delete) and ⌘1–9 board switching.
- Signal-flow editor: add pedals from the palette; parallel and stereo-split lanes; merge to mono.
- One shared, phase-locked test signal across all boards (no per-board polyrhythm).
### Audio I/O
- Test-loop signal or live hardware input.
- macOS and iPadOS (iPad-only, landscape). iOS live input via a permission-gated engine rebuild;
the last input choice is remembered.
### Files & capture
- Save / load rigs as JSON.
- Record output to timestamped files.
### API
- Type-safe `PedalType` tokens for the board-edit API (`appendPedal(.overdrive, to:)`); the rig
JSON format is keyed on pedal display names.
@@ -0,0 +1,49 @@
// TestLoopTap.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// Internal synthesizer that copies the shared global test-loop bus to a board head bus.
///
/// In `.testLoop` mode every board reads the **same** global ``TestLoopSource`` (so all boards
/// stay phase-locked instead of each running an independently-phased arpeggio). A `TestLoopTap`
/// per board reads the global test bus at `inputBusIndex` and writes it to the board's head bus
/// at `outputBusIndex`, so the first pedal still reads from a board-owned bus.
///
/// Added `.after(_:)` the global source so it evaluates once the source has written the test bus
/// for the current block.
///
/// - Note: Must be removed from the engine before the board's `teardown()` releases the head bus.
final class TestLoopTap: SynthesizerBase {
// MARK: - Routing
/// Index of the shared global test-loop bus to read from.
private let inputBusIndex: Int
/// Index of the board head bus to write to.
private let outputBusIndex: Int
// MARK: - Init
/// Creates a tap that copies `inputBusIndex` (the global test bus) to `outputBusIndex`
/// (a board head bus).
///
/// - Parameters:
/// - inputBusIndex: Shared global test-loop bus index to read from.
/// - outputBusIndex: Board head bus index to write to.
init(inputBusIndex: Int, outputBusIndex: Int) {
self.inputBusIndex = inputBusIndex
self.outputBusIndex = outputBusIndex
super.init()
}
// MARK: - Build
override func build() {
output(bus: outputBusIndex, source: input(bus: inputBusIndex))
}
}
+11
View File
@@ -128,6 +128,17 @@ open class Pedal: SynthesizerBase {
self.mix = initialMix
}
// MARK: - Description
/// One-line, user-facing description of what this pedal does.
///
/// Shown as a subtitle in the pedal picker and as the body of the pedal's info panel.
/// **Every pedal must override this** with a short, non-proprietary sentence — the empty
/// default is a placeholder only (a test asserts every registered pedal sets it).
open var summary: String {
""
}
// MARK: - UI knob descriptors
/// Effect-specific knobs for this pedal, listed before the common knobs in the UI.
+79
View File
@@ -0,0 +1,79 @@
// PedalType.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// A type-safe identifier for a pedal type, used by the board-edit API instead of a raw string.
///
/// `PedalType` is an extensible token (the `RawRepresentable` struct pattern, à la
/// `Notification.Name`): the built-in pedals are exposed as static members for discoverable,
/// autocompleting call sites —
///
/// ```swift
/// try shoeGaze.appendPedal(.overdrive, to: board)
/// ```
///
/// — while staying open for custom pedals, since any `PedalType("My Pedal")` is valid and a
/// third party can add their own static members in an extension.
///
/// `rawValue` is the pedal's `displayName`, which is exactly what the rig save format stores
/// (`PedalState.type`) and what ``PedalRegistry`` keys on. `PedalType` therefore changes only the
/// authoring call site — the JSON format and load path are unchanged.
///
/// > Note: named `PedalType` rather than `PedalKind` to avoid colliding with Lyrebird's
/// > score-notation `PedalKind` enum, which is visible whenever both modules are imported.
public struct PedalType: RawRepresentable, Hashable, Sendable {
/// The pedal's `displayName`; the key used by ``PedalRegistry`` and stored in saved rigs.
public let rawValue: String
/// Creates a type from a raw `displayName` string.
public init(rawValue: String) {
self.rawValue = rawValue
}
/// Creates a type from a raw `displayName` string.
public init(_ rawValue: String) {
self.rawValue = rawValue
}
}
// MARK: - Built-in pedals
public extension PedalType {
// Drive & dynamics
static let overdrive = PedalType("Overdrive")
static let fuzz = PedalType("Fuzz")
static let compressor = PedalType("Compressor")
static let limiter = PedalType("Limiter")
static let noiseGate = PedalType("Noise Gate")
// EQ & filter
static let graphicEQ = PedalType("Graphic EQ")
static let autoWah = PedalType("Auto-Wah")
static let mutant = PedalType("Mutant")
static let phaser = PedalType("Phaser")
// Modulation
static let tremolo = PedalType("Tremolo")
static let modulation = PedalType("Modulation")
static let chorus = PedalType("Chorus")
static let ringModulator = PedalType("Ring Modulator")
static let diffuser = PedalType("Diffuser")
// Dynamics (additional)
static let sustainer = PedalType("Sustainer")
// Delay & reverb
static let delay = PedalType("Delay")
static let feedbackDelay = PedalType("Feedback Delay")
static let multiTapDelay = PedalType("Multi-Tap Delay")
static let pingPong = PedalType("Ping-Pong")
static let reverb = PedalType("Reverb")
// Pitch & octave
static let octaveSplitter = PedalType("Octave Splitter")
static let bassOctaver = PedalType("Bass Octaver")
}
@@ -9,7 +9,7 @@ import LyrebirdUI
/// Amplitude-tracked auto-wah pedal built from discrete tracking + filter stages.
///
/// Unlike `MuTronPedal` (which wraps the single fused `MuTronIII` generator), this pedal
/// Unlike `MutantPedal` (which wraps the single fused `MuTronIII` generator), this pedal
/// wires the envelope path explicitly: an `AmplitudeFollower` tracks the dry signal level,
/// the envelope is scaled by `sensitivity` and clamped to `[0, 1]`, then mapped through an
/// exponential `LinExp` curve to a cutoff frequency that sweeps a resonant `SVF` bandpass.
@@ -27,6 +27,11 @@ import LyrebirdUI
/// - `range`: Upper cutoff in Hz reached at full envelope. Sets the sweep span over `freqLo`.
public final class AutoWahPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Touch-sensitive wah that sweeps a resonant filter from your playing dynamics."
}
// MARK: - Parameters
/// Envelope drive into the cutoff sweep. Higher values open the filter on quieter input.
@@ -35,6 +35,11 @@ import LyrebirdUI
/// - `mode` (two-state): `0` = Flip-flop (authentic OC-2), `1` = Tracking (pitch-tracked).
public final class BassOctaverPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Adds a sub-octave below your note for bass-like weight."
}
// MARK: - Parameters
/// −1 octave voice level in `[0, 1]`.
@@ -0,0 +1,129 @@
// ChorusPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// True-stereo chorus pedal.
///
/// Two modulated delay lines, fed the same dry signal but driven by sine LFOs 180° apart,
/// produce a wide left/right shimmer. Unlike `ModulationPedal` (which sums Lyrebird's
/// `Chorus` to mono), this pedal is a ``PedalChannelKind/widener`` — it keeps the two voices
/// on separate channels for genuine stereo width.
///
/// Signal path (per channel, inside `wideEffect(_:)`):
/// ```
/// dry → DelayLine(delay: base ± depth·sin(rate)) → wet L / wet R
/// ```
///
/// The wet/dry blend and bypass are handled by the `Pedal` base class.
///
/// ## Parameters
///
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
///
/// - Parameters:
/// - rate: LFO rate in Hz. Range `[0.05, 6]`. Defaults to `0.8`.
/// - depth: Delay-sweep depth in seconds (half-swing around the base delay). Range
/// `[0.0005, 0.008]`. Defaults to `0.003`.
public final class ChorusPedal: Pedal {
// MARK: - Parameters
/// LFO rate in Hz. Range [0.05, 6].
@UIParam public var rate: Double = 0.8
/// Delay-sweep depth in seconds. Range [0.0005, 0.008].
@UIParam public var depth: Double = 0.003
// MARK: - Constants
/// Default wet/dry blend — chorus sits under the dry signal.
private static let defaultMix: Double = 0.5
/// Base delay around which the LFO sweeps, in seconds.
private let baseDelayTime: Double = 0.012
/// Maximum delay the lines are allocated for, in seconds. Covers `baseDelayTime + max depth`.
private let maxDelayTime: Double = 0.03
/// LFO phase for the left voice, in cycles.
private let leftPhase: Double = 0.0
/// LFO phase for the right voice, in cycles — a half cycle (180°) opposite the left.
private let rightPhase: Double = 0.5
// MARK: - UI knobs
private let rateRange: ClosedRange<Double> = 0.05 ... 6.0
private let depthRange: ClosedRange<Double> = 0.0005 ... 0.008
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Rate", node: $rate, range: rateRange),
PedalKnob(label: "Depth", node: $depth, range: depthRange),
]
}
// MARK: - Channel topology
public override var channelKind: PedalChannelKind { .widener }
// MARK: - Init
/// Creates a stereo chorus pedal.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(
inputBus: Int = 0,
outputBus: Int = 0
) {
super.init(
name: "Chorus",
inputBus: inputBus,
outputBus: outputBus,
initialMix: ChorusPedal.defaultMix
)
}
public override var summary: String {
"Lush stereo chorus: two detuned voices panned wide for shimmer and depth."
}
// MARK: - Effect
/// Builds one modulated delay line per channel, with the two LFOs in anti-phase.
///
/// - Parameter dry: Dry mono input signal.
/// - Returns: The left and right wet voices.
public override func wideEffect(
_ dry: any ValidGeneratorInput
) -> (left: any ValidGeneratorInput, right: any ValidGeneratorInput) {
(voice(dry, phase: leftPhase), voice(dry, phase: rightPhase))
}
/// One chorus voice: a delay line whose time is swept by a sine LFO around `baseDelayTime`.
private func voice(
_ dry: any ValidGeneratorInput,
phase: Double
) -> any ValidGeneratorInput {
let sweep: OscSin.Audio = OscSin.Audio(
freq: $rate,
phase: phase,
mul: $depth,
add: baseDelayTime
)
return DelayLine(
input: dry,
maxDelay: maxDelayTime,
delay: sweep,
sampleRate: sampleRate,
interpolation: .linear
)
}
}
@@ -11,11 +11,13 @@ import LyrebirdUI
///
/// Signal chain (inside `effect(_:)`):
/// ```
/// dry → Compressor.Audio(threshold:, ratio:, attack:, release:, makeupGain:) → mono out
/// dry → × inputGain → Compressor.Audio(threshold:, ratio:, attack:, release:, makeupGain:) → mono out
/// ```
///
/// Attack, release, knee, and makeup gain are fixed at musically sensible defaults.
/// Knobs expose the two most-musical parameters: threshold and ratio.
/// An input gain stage boosts (or cuts) the signal *before* compression, so driving the
/// input harder pushes more of the signal past the threshold. Attack, release, knee, and
/// makeup gain are fixed at musically sensible defaults; knobs expose input gain, threshold,
/// and ratio.
///
/// The wet/dry mix and bypass switching are handled by the `Pedal` base class.
///
@@ -24,14 +26,24 @@ import LyrebirdUI
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
///
/// - Parameters:
/// - inputGain: Pre-compression input gain in dB. `0` = unity. Range `[-12, 24]`.
/// Defaults to `0.0`.
/// - threshold: Gain-reduction threshold in dB. Signals above this level are
/// compressed. Range `[-40, 0]` dB. Defaults to `-12.0`.
/// - ratio: Compression ratio `≥ 1.0`. `1.0` = bypass, `4.0` = 4:1 compression.
/// Range `[1, 20]`. Defaults to `4.0`.
public final class CompressorPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Feed-forward compressor that evens out dynamics, with a pre-gain input stage."
}
// MARK: - Parameters
/// Pre-compression input gain in dB. Range [-12, 24]. `0` = unity.
@UIParam public var inputGain: Double = 0.0
/// Compression threshold in dB. Range [-40, 0].
@UIParam public var threshold: Double = -12.0
@@ -43,6 +55,10 @@ public final class CompressorPedal: Pedal {
/// Default wet/dry blend — fully wet; the compressor is inserted in-line.
private static let defaultMix: Double = 1.0
/// dB → natural-exponent scale, `ln(10) / 20`. `exp(dB · scale) == 10^(dB/20)`, the
/// linear amplitude multiplier for a dB gain. Applied to the input-gain stage.
private let dbToLinExpScale: Double = 0.115_129_254_649_702_28
/// Attack time constant in seconds — time to reach full gain reduction on a transient.
private let attackTime: Double = 0.01
@@ -57,6 +73,9 @@ public final class CompressorPedal: Pedal {
// MARK: - UI knobs
/// Input-gain knob range in dB.
private let inputGainRange: ClosedRange<Double> = -12.0 ... 24.0
/// Threshold knob range in dB.
private let thresholdRange: ClosedRange<Double> = -40.0 ... 0.0
@@ -65,6 +84,7 @@ public final class CompressorPedal: Pedal {
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Input", node: $inputGain, range: inputGainRange),
PedalKnob(label: "Threshold", node: $threshold, range: thresholdRange),
PedalKnob(label: "Ratio", node: $ratio, range: ratioRange),
]
@@ -91,15 +111,18 @@ public final class CompressorPedal: Pedal {
// MARK: - Effect
/// Applies feed-forward dynamic range compression.
/// Boosts the input by `inputGain` dB, then applies feed-forward dynamic range compression.
///
/// Output is mono.
///
/// - Parameter dry: Dry mono input signal.
/// - Returns: Compressed mono output.
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
Compressor.Audio(
in: dry,
// Convert the input-gain dB to a linear multiplier (10^(dB/20)) and apply before compression.
let inputGainLinear: Exp.Audio = Exp.Audio($inputGain * dbToLinExpScale)
let boosted: any ValidGeneratorInput = dry * inputGainLinear
return Compressor.Audio(
in: boosted,
threshold: $threshold,
ratio: $ratio,
attack: attackTime,
@@ -28,6 +28,11 @@ import LyrebirdUI
/// repeats. Range `[0.05, 6.0]` seconds. Defaults to `1.0`.
public final class DelayPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Echo delay with adjustable time and decay, from slapback to long repeats."
}
// MARK: - Parameters
/// Delay time in seconds. Range [0.01, 1.5].
@@ -77,7 +82,7 @@ public final class DelayPedal: Pedal {
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Time", node: $time, range: timeRange),
PedalKnob(label: "Feedback", node: $feedback, range: feedbackRange),
PedalKnob(label: "Decay Time", node: $feedback, range: feedbackRange),
]
}
@@ -0,0 +1,130 @@
// DiffuserPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Stereo diffuser pedal: fans the frequency spectrum across the left and right channels.
///
/// A `.widener` pedal. The dry signal is split into overlapping frequency bands; each band is
/// panned by its centre frequency — lows toward the left, highs toward the right — and the
/// `spread` knob sets how far the bands fan out. At `spread = 0` every band sits centre (a mono
/// collapse); at `spread = 1` the spectrum is splayed hard across the stereo field, giving a
/// wide, diffuse image without time smearing.
///
/// Signal path (inside `wideEffect(_:)`), per band `k` at position `pos_k ∈ [-1, 1]`:
/// ```
/// dry → RBJBandPass(freq_k) → ×gainL_k → Σ → left
/// → ×gainR_k → Σ → right
/// gainL_k = 0.5 − 0.5·pos_k·spread, gainR_k = 0.5 + 0.5·pos_k·spread (linear pan)
/// ```
///
/// The wet/dry blend and bypass are handled by the `Pedal` base class.
///
/// ## Parameters
///
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
///
/// - Parameters:
/// - spread: Stereo spectral spread. `0` = centred (mono), `1` = fully fanned L↔R.
/// Range `[0, 1]`. Defaults to `0.6`.
public final class DiffuserPedal: Pedal {
// MARK: - Parameters
/// Stereo spectral spread in [0, 1]. `0` = mono, `1` = full fan.
@UIParam public var spread: Double = 0.6
// MARK: - Constants
private static let defaultMix: Double = 1.0
/// Centre pan gain (each band's gain when `spread == 0` or it sits dead-centre).
private let centerGain: Double = 0.5
/// RBJ band-pass width in octaves — wide enough that adjacent bands overlap and recombine.
private let bandwidthOctaves: Double = 1.5
/// The frequency bands and their base stereo positions (low = left, high = right).
/// `position ∈ [-1, 1]`; multiplied by `spread` to place the band.
private let bands: [(freq: Double, position: Double)] = [
(150.0, -1.0),
(400.0, -0.5),
(1000.0, 0.0),
(2500.0, 0.5),
(6000.0, 1.0),
]
// MARK: - UI knobs
private let spreadRange: ClosedRange<Double> = 0.0 ... 1.0
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Spread", node: $spread, range: spreadRange),
]
}
// MARK: - Channel topology
public override var channelKind: PedalChannelKind { .widener }
// MARK: - Init
/// Creates a stereo diffuser pedal.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(
inputBus: Int = 0,
outputBus: Int = 0
) {
super.init(
name: "Diffuser",
inputBus: inputBus,
outputBus: outputBus,
initialMix: DiffuserPedal.defaultMix
)
}
public override var summary: String {
"Stereo diffuser that fans the frequency spectrum across the left and right channels."
}
// MARK: - Effect
/// Splits the dry signal into frequency bands and pans each across the field by `spread`.
///
/// - Parameter dry: Dry mono input signal.
/// - Returns: The left and right diffused signals.
public override func wideEffect(
_ dry: any ValidGeneratorInput
) -> (left: any ValidGeneratorInput, right: any ValidGeneratorInput) {
var left: (any ValidGeneratorInput)?
var right: (any ValidGeneratorInput)?
for band: (freq: Double, position: Double) in bands {
let bandPass: RBJBandPass.Audio = RBJBandPass.Audio(
input: dry,
freq: band.freq,
bandwidth: bandwidthOctaves
)
// Linear pan, fully expressible as node arithmetic (no per-sample trig):
// gainL = centerGain − (0.5·position)·spread
// gainR = centerGain + (0.5·position)·spread
let halfPosition: Double = centerGain * band.position
let gainL: any ValidGeneratorInput = ($spread * (-halfPosition)) + centerGain
let gainR: any ValidGeneratorInput = ($spread * halfPosition) + centerGain
let leftContribution: any ValidGeneratorInput = bandPass * gainL
let rightContribution: any ValidGeneratorInput = bandPass * gainR
left = left.map { $0 + leftContribution } ?? leftContribution
right = right.map { $0 + rightContribution } ?? rightContribution
}
return (left ?? dry, right ?? dry)
}
}
@@ -26,6 +26,11 @@ import LyrebirdUI
/// - `tone`: Lowpass cutoff in Hz applied to the wet signal; lower darkens the echoes.
public final class FeedbackDelayPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Feedback delay with a tone-shaped repeat for dub-style echoes."
}
// MARK: - Parameters
/// Delay time between repeats, in seconds.
@@ -62,7 +67,7 @@ public final class FeedbackDelayPedal: Pedal {
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Time", node: $time, range: timeRange),
PedalKnob(label: "Feedback", node: $feedback, range: feedbackRange),
PedalKnob(label: "Decay Time", node: $feedback, range: feedbackRange),
PedalKnob(label: "Tone", node: $tone, range: toneRange),
]
}
@@ -36,6 +36,11 @@ import LyrebirdUI
/// Range `[200, 8000]` Hz. Defaults to `3500.0`.
public final class FuzzPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Thick, saturated fuzz for aggressive, sustaining distortion."
}
// MARK: - Parameters
/// Pre-gain drive into the saturator. Range [1, 60]; higher = more fuzz.
@@ -39,6 +39,11 @@ import LyrebirdUI
/// Defaults to `0.0`.
public final class GraphicEQPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Five-band graphic EQ with per-band faders and a master output level."
}
// MARK: - Parameters
/// Low-shelf gain in dB. Range [-12, 12].
@@ -31,6 +31,11 @@ import LyrebirdUI
/// never exceeds this absolute value. Range `[0.1, 1.0]`. Defaults to `0.95`.
public final class LimiterPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Brick-wall limiter with an input boost to push level safely to the ceiling."
}
// MARK: - Parameters
/// Pre-limit input gain (linear multiplier). Range [1, 12].
@@ -32,6 +32,11 @@ import LyrebirdUI
/// Smaller values (0.001–0.01) produce classic chorus width. Defaults to `0.002`.
public final class ModulationPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Classic mono chorus for subtle thickening and shimmer."
}
// MARK: - Parameters
/// Chorus LFO rate in Hz. Range [0.1, 10].
@@ -28,6 +28,11 @@ import LyrebirdUI
/// - `vol1`, `vol2`, `vol3`: Linear output level of each tap in `[0, 1]`.
public final class MultiTapDelayPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Multi-tap delay producing rhythmic patterns of echoes."
}
// MARK: - Tap times
/// Tap 1 delay time, in seconds.
@@ -1,4 +1,4 @@
// MuTronPedal.swift
// MutantPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
@@ -7,7 +7,7 @@
import LyrebirdSynth
import LyrebirdUI
/// Envelope-following filter pedal modeled on the Musitronics Mu-Tron III.
/// Envelope-following auto-wah / funk-filter pedal.
///
/// Wraps the Lyrebird `MuTronIII` generator. The input amplitude drives an exponential
/// cutoff sweep through a resonant Chamberlin state-variable filter. Because `MuTronIII`
@@ -24,7 +24,12 @@ import LyrebirdUI
/// ## Switches
/// - `direction` (two-state): `0` = Down (louder closes the filter), `1` = Up (louder opens it).
/// - `mode` (three-state): `0` = lowpass, `1` = bandpass (classic vowel wah), `2` = highpass.
public final class MuTronPedal: Pedal {
public final class MutantPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Envelope-following auto-wah / funk filter that opens with your picking."
}
// MARK: - Parameters
@@ -107,10 +112,10 @@ public final class MuTronPedal: Pedal {
public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(
name: "Mu-Tron",
name: "Mutant",
inputBus: inputBus,
outputBus: outputBus,
initialMix: MuTronPedal.defaultMix
initialMix: MutantPedal.defaultMix
)
}
@@ -37,6 +37,11 @@ import LyrebirdUI
/// mute, `1` = no gating. Range `[0, 1]`. Defaults to `0.0`.
public final class NoiseGatePedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Noise gate that silences hiss and hum below a tunable threshold."
}
// MARK: - Parameters
/// Gate close threshold (linear amplitude). Range [0, 0.2].
@@ -31,6 +31,11 @@ import LyrebirdUI
/// - tone: Octave-channel low-pass cutoff in Hz. Range `[500, 8000]`. Defaults to `4000.0`.
public final class OctaveUpSplitterPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Splits a clean octave-up voice alongside your dry signal in stereo."
}
// MARK: - Parameters
/// Pre-gain into the octave-channel saturator. Range [1, 40]; higher = thicker octave fuzz.
@@ -27,6 +27,11 @@ import LyrebirdUI
/// Range `(0, 20000]`. Defaults to `4000.0`.
public final class OverdrivePedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Warm soft-clip overdrive with a tone control, from gentle grit to singing sustain."
}
// MARK: - Parameters
/// Saturation drive amount. Range [1, 20]; higher = more clipping.
@@ -30,6 +30,11 @@ import LyrebirdUI
/// Range `[0.0, 0.9]`. Defaults to `0.5`.
public final class PhaserPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Sweeping phase shifter for swirling, watery motion."
}
// MARK: - Parameters
/// LFO sweep rate in Hz. Range [0.05, 5.0].
@@ -37,6 +37,11 @@ import LyrebirdUI
/// Range `[0.05, 6.0]`. Defaults to `1.2`.
public final class PingPongDelayPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Stereo ping-pong delay bouncing echoes between left and right."
}
// MARK: - Parameters
/// Delay time per tap in seconds. Range [0.05, 1.0].
@@ -94,7 +99,7 @@ public final class PingPongDelayPedal: Pedal {
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Time", node: $time, range: timeRange),
PedalKnob(label: "Feedback", node: $feedback, range: feedbackRange),
PedalKnob(label: "Decay Time", node: $feedback, range: feedbackRange),
]
}
@@ -31,6 +31,11 @@ import LyrebirdUI
/// shorter tails. Defaults to `0.5`.
public final class ReverbPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Reverb adding space and ambience, from small rooms to vast halls."
}
// MARK: - Parameters
/// Room size in [0, 1]. Larger = longer reverb tail.
@@ -0,0 +1,84 @@
// RingModulatorPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Ring modulator pedal.
///
/// Multiplies the input by a tunable sine carrier, producing sum-and-difference sidebands —
/// metallic, bell-like, and robotic tones. Below ~30 Hz the carrier reads as tremolo-style
/// amplitude modulation; in the audio range it becomes classic ring modulation.
///
/// Signal path (inside `effect(_:)`):
/// ```
/// dry × OscSin(frequency) → wet
/// ```
///
/// The wet/dry blend and bypass are handled by the `Pedal` base class.
///
/// ## Parameters
///
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
///
/// - Parameters:
/// - frequency: Carrier frequency in Hz. Range `[20, 2000]`. Defaults to `220.0`.
public final class RingModulatorPedal: Pedal {
// MARK: - Parameters
/// Carrier frequency in Hz. Range [20, 2000].
@UIParam public var frequency: Double = 220.0
// MARK: - Constants
/// Default wet/dry blend — ring mod is harsh, so keep the dry signal present.
private static let defaultMix: Double = 0.5
// MARK: - UI knobs
private let frequencyRange: ClosedRange<Double> = 20.0 ... 2000.0
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Frequency", node: $frequency, range: frequencyRange),
]
}
// MARK: - Init
/// Creates a ring modulator pedal.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(
inputBus: Int = 0,
outputBus: Int = 0
) {
super.init(
name: "Ring Modulator",
inputBus: inputBus,
outputBus: outputBus,
initialMix: RingModulatorPedal.defaultMix
)
}
public override var summary: String {
"Multiplies your signal by a tunable carrier for metallic, bell-like, and robotic tones."
}
// MARK: - Effect
/// Multiplies the dry signal by the sine carrier.
///
/// - Parameter dry: Dry mono input signal.
/// - Returns: The ring-modulated wet signal.
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
let carrier: OscSin.Audio = OscSin.Audio(freq: $frequency)
return dry * carrier
}
}
@@ -0,0 +1,144 @@
// SustainerPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Sustainer pedal: a one-knob compressor tuned for long, even sustain.
///
/// A single `sustain` control drives a feed-forward compressor harder as it climbs — lowering
/// the threshold, raising the ratio, and adding makeup gain together — so notes bloom and hold
/// without the user juggling threshold/ratio (that's what the `Compressor` pedal is for). A
/// `tone` low-pass rounds off the squashed top end.
///
/// Signal path (inside `effect(_:)`):
/// ```
/// dry → Compressor(threshold↓, ratio↑, makeup↑ with sustain) → RBJLowPass(tone) → wet
/// ```
///
/// The wet/dry blend and bypass are handled by the `Pedal` base class.
///
/// ## Parameters
///
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
///
/// - Parameters:
/// - sustain: Amount of sustain/compression. `0` = gentle, `10` = maximum squash and hold.
/// Range `[0, 10]`. Defaults to `5.0`.
/// - tone: Output low-pass cutoff in Hz. Range `[800, 8000]`. Defaults to `6000.0`.
public final class SustainerPedal: Pedal {
// MARK: - Parameters
/// Sustain amount in [0, 10]. Higher = more compression, makeup, and hold.
@UIParam public var sustain: Double = 5.0
/// Output low-pass cutoff in Hz. Range [800, 8000].
@UIParam public var tone: Double = 6000.0
// MARK: - Constants
private static let defaultMix: Double = 1.0
/// Compressor envelope times, in seconds — fast attack to catch picks, slow release to hold.
private let attackTime: Double = 0.005
private let releaseTime: Double = 0.4
/// Hard knee for a defined, punchy sustain.
private let kneeWidth: Double = 0.0
/// Butterworth tone low-pass (no resonant peak).
private let toneQ: Double = 0.707
/// `sustain` knob span, mapped to the compressor settings below.
private let sustainMin: Double = 0.0
private let sustainMax: Double = 10.0
/// Threshold in dB at min / max sustain (lower threshold = more of the signal compressed).
private let thresholdAtMin: Double = -6.0
private let thresholdAtMax: Double = -36.0
/// Compression ratio at min / max sustain.
private let ratioAtMin: Double = 2.0
private let ratioAtMax: Double = 10.0
/// Makeup gain in dB at min / max sustain (compensates for the added gain reduction).
private let makeupAtMin: Double = 0.0
private let makeupAtMax: Double = 18.0
// MARK: - UI knobs
private let sustainRange: ClosedRange<Double> = 0.0 ... 10.0
private let toneRange: ClosedRange<Double> = 800.0 ... 8000.0
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Sustain", node: $sustain, range: sustainRange),
PedalKnob(label: "Tone", node: $tone, range: toneRange),
]
}
// MARK: - Init
/// Creates a sustainer pedal.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(
inputBus: Int = 0,
outputBus: Int = 0
) {
super.init(
name: "Sustainer",
inputBus: inputBus,
outputBus: outputBus,
initialMix: SustainerPedal.defaultMix
)
}
public override var summary: String {
"Compressor tuned for long, even sustain — one knob to make notes bloom and hold."
}
// MARK: - Effect
/// Drives a compressor from the single `sustain` knob, then rolls off the top with `tone`.
///
/// - Parameter dry: Dry mono input signal.
/// - Returns: The sustained, tone-shaped wet signal.
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
let threshold: LinLin.Audio = mapSustain(to: thresholdAtMin, thresholdAtMax)
let ratio: LinLin.Audio = mapSustain(to: ratioAtMin, ratioAtMax)
let makeup: LinLin.Audio = mapSustain(to: makeupAtMin, makeupAtMax)
let compressed: Compressor.Audio = Compressor.Audio(
in: dry,
threshold: threshold,
ratio: ratio,
attack: attackTime,
release: releaseTime,
kneeWidth: kneeWidth,
makeupGain: makeup
)
return RBJLowPass.Audio(
input: compressed,
freq: $tone,
q: toneQ
)
}
/// Maps the `sustain` knob `[sustainMin, sustainMax]` to `[outLo, outHi]`.
private func mapSustain(to outLo: Double, _ outHi: Double) -> LinLin.Audio {
LinLin.Audio(
$sustain,
inLo: sustainMin,
inHi: sustainMax,
outLo: outLo,
outHi: outHi
)
}
}
@@ -31,6 +31,11 @@ import LyrebirdUI
/// Defaults to `0.7`.
public final class TremoloPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Rhythmic volume modulation, from a gentle throb to choppy stutter."
}
// MARK: - Parameters
/// LFO rate in Hz. Range [0.5, 12].
@@ -98,7 +98,7 @@ public final class BoardVersionStore {
_ version: BoardVersion,
in directory: URL
) throws {
let sanitized: String = sanitizeFilename(version.name)
let sanitized: String = sanitizePresetFilename(version.name, maxLength: maxNameLength)
let filename: String = "\(sanitized)-\(version.id.uuidString).json"
let fileURL: URL = directory.appendingPathComponent(filename)
do {
@@ -134,7 +134,7 @@ public final class BoardVersionStore {
attributes: nil
)
let sanitized: String = sanitizeFilename(version.name)
let sanitized: String = sanitizePresetFilename(version.name, maxLength: maxNameLength)
let filename: String = "\(sanitized)-\(version.id.uuidString).json"
let fileURL: URL = directory.appendingPathComponent(filename)
@@ -236,53 +236,4 @@ public final class BoardVersionStore {
/// Maximum UTF-8 byte length for the sanitised name prefix before the `-<uuid>.json`
/// suffix is appended, so the full filename stays well under the 255-byte component limit.
private let maxNameLength: Int = 200
/// Sanitises a string so it is safe as a file-system component on HFS+ and APFS.
///
/// - Replaces `/`, `\`, `:`, NUL (`\0`), and all whitespace characters with underscores.
/// - Replaces a leading `.` (which would produce hidden-file or `.`/`..` names) with an
/// underscore.
/// - Trims leading and trailing underscores that resulted from whitespace or separator
/// substitution (cosmetic only — the result is always safe even before trimming).
/// - Caps the UTF-8 byte length of the result at `maxNameLength` so the full filename
/// (`<name>-<uuid>.json`, 54 extra bytes) cannot exceed the 255-byte component limit.
/// - Returns `"unnamed"` when the input is empty, all-whitespace, or reduces entirely
/// to separator characters after substitution.
private func sanitizeFilename(_ name: String) -> String {
let replacementCharacter: Character = "_"
let forbiddenCharacters: Set<Character> = ["/", "\\", ":", "\0"]
var sanitized: String = name.map { character -> Character in
if character.isWhitespace || forbiddenCharacters.contains(character) {
return replacementCharacter
}
return character
}.reduce(into: "") { $0.append($1) }
// Replace a leading dot so the filename is never `.`, `..`, or a hidden file.
if sanitized.first == "." {
sanitized.replaceSubrange(sanitized.startIndex...sanitized.startIndex, with: "_")
}
// Trim whitespace-replacement underscores at both ends (cosmetic).
sanitized = sanitized.trimmingCharacters(in: CharacterSet(charactersIn: "_"))
// Treat all-empty or all-separator results as unnamed.
guard !sanitized.isEmpty else { return "unnamed" }
// Cap to maxNameLength UTF-8 bytes so the full filename stays within 255 bytes.
if sanitized.utf8.count > maxNameLength {
var truncated: String = ""
var byteCount: Int = 0
for scalar: Unicode.Scalar in sanitized.unicodeScalars {
let encodedLength: Int = UTF8.width(scalar)
guard byteCount + encodedLength <= maxNameLength else { break }
truncated.unicodeScalars.append(scalar)
byteCount += encodedLength
}
sanitized = truncated
}
return sanitized.isEmpty ? "unnamed" : sanitized
}
}
@@ -14,7 +14,7 @@
/// To register custom pedal types, extend `builtIn` by building your own dictionary
/// and merging it before calling `loadRig`. The built-in registry covers the factory
/// pedals: Overdrive, Delay, Reverb, Modulation, Fuzz, Tremolo, Phaser, Compressor,
/// Mu-Tron, Auto-Wah, Feedback Delay, Multi-Tap Delay, Octave Splitter, and Ping-Pong.
/// Mutant, Auto-Wah, Feedback Delay, Multi-Tap Delay, Octave Splitter, and Ping-Pong.
///
/// > Note: A saved rig captures each board's *linear* pedal chain only (see `BoardState`).
/// > When a registered widener (e.g. Octave Splitter) or stereo-native pedal (e.g.
@@ -39,7 +39,7 @@ public enum PedalRegistry {
"Tremolo": { TremoloPedal() },
"Phaser": { PhaserPedal() },
"Compressor": { CompressorPedal() },
"Mu-Tron": { MuTronPedal() },
"Mutant": { MutantPedal() },
"Auto-Wah": { AutoWahPedal() },
"Feedback Delay": { FeedbackDelayPedal() },
"Multi-Tap Delay": { MultiTapDelayPedal() },
@@ -49,6 +49,10 @@ public enum PedalRegistry {
"Limiter": { LimiterPedal() },
"Noise Gate": { NoiseGatePedal() },
"Graphic EQ": { GraphicEQPedal() },
"Chorus": { ChorusPedal() },
"Sustainer": { SustainerPedal() },
"Ring Modulator": { RingModulatorPedal() },
"Diffuser": { DiffuserPedal() },
]
/// Returns a new `Pedal` instance for the given type string, or `nil` if the type
@@ -65,4 +69,25 @@ public enum PedalRegistry {
guard let constructor: @MainActor () -> Pedal = builtIn[type] else { return nil }
return constructor()
}
/// Cached `displayName → summary` map for all built-in pedals, built once by instantiating
/// each pedal a single time (no `build()` / engine work). Lets the picker look up
/// descriptions per row without reconstructing a pedal on every render.
@MainActor
public static let summaries: [String: String] = {
var map: [String: String] = [:]
for type: String in builtIn.keys {
map[type] = makePedal(type: type)?.summary ?? ""
}
return map
}()
/// Returns the `summary` description for a built-in pedal type, or `""` if unknown.
///
/// - Parameter type: The `displayName` of the pedal.
/// - Returns: The pedal's one-line `summary`, or `""` for unknown types.
@MainActor
public static func summary(for type: String) -> String {
summaries[type] ?? ""
}
}
@@ -0,0 +1,65 @@
// PresetFilename.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Sanitises a user-supplied name so it is safe as a file-system component on HFS+ and APFS.
///
/// Shared by the preset stores (`BoardVersionStore`, `RigLibraryStore`) so every on-disk preset
/// filename follows one scheme: `<sanitized-name>-<uuid>.json`.
///
/// - Replaces `/`, `\`, `:`, NUL (`\0`), and all whitespace with underscores.
/// - Replaces a leading `.` (which would produce a hidden file or `.`/`..`) with an underscore.
/// - Trims leading and trailing underscores that resulted from the substitutions (cosmetic).
/// - Caps the UTF-8 byte length of the result at `maxLength` so the full filename
/// (`<name>-<uuid>.json`, 54 extra bytes) stays within the 255-byte component limit.
/// - Returns `"unnamed"` when the input is empty, all-whitespace, or reduces entirely to
/// separator characters after substitution.
///
/// - Parameters:
/// - name: The raw, user-supplied name.
/// - maxLength: Maximum UTF-8 byte length of the sanitised prefix. Defaults to `200`.
/// - Returns: A file-system-safe name, never empty.
func sanitizePresetFilename(
_ name: String,
maxLength: Int = 200
) -> String {
let replacementCharacter: Character = "_"
let forbiddenCharacters: Set<Character> = ["/", "\\", ":", "\0"]
var sanitized: String = name.map { character -> Character in
if character.isWhitespace || forbiddenCharacters.contains(character) {
return replacementCharacter
}
return character
}.reduce(into: "") { $0.append($1) }
// Replace a leading dot so the filename is never `.`, `..`, or a hidden file.
if sanitized.first == "." {
sanitized.replaceSubrange(sanitized.startIndex...sanitized.startIndex, with: "_")
}
// Trim whitespace-replacement underscores at both ends (cosmetic).
sanitized = sanitized.trimmingCharacters(in: CharacterSet(charactersIn: "_"))
// Treat all-empty or all-separator results as unnamed.
guard !sanitized.isEmpty else { return "unnamed" }
// Cap to maxLength UTF-8 bytes so the full filename stays within 255 bytes.
if sanitized.utf8.count > maxLength {
var truncated: String = ""
var byteCount: Int = 0
for scalar: Unicode.Scalar in sanitized.unicodeScalars {
let encodedLength: Int = UTF8.width(scalar)
guard byteCount + encodedLength <= maxLength else { break }
truncated.unicodeScalars.append(scalar)
byteCount += encodedLength
}
sanitized = truncated
}
return sanitized.isEmpty ? "unnamed" : sanitized
}
@@ -0,0 +1,44 @@
// RigArchive.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Format version written into every exported ``RigArchive``.
///
/// Increment when the archive schema changes in a way that requires migration on load.
public let rigArchiveFormatVersion: Int = 1
/// A portable bundle of one or more ``RigEntry`` rigs in a single JSON document.
///
/// `RigArchive` is the hand-editable, shareable file format used by the library's
/// **Export Archive** / **Import Archive** actions — the way to back up or move an entire
/// collection of rigs as one file. It is the multi-rig successor to the old single-rig file
/// save/load: a legacy single-rig file (a bare ``ShoeGazeState``) is still importable and is
/// treated as a one-rig archive (see `RigLibraryStore.importArchive`).
///
/// The document is written pretty-printed with sorted keys, so it stays readable and editable by
/// hand. `Date` values inside each ``RigEntry`` are encoded as `secondsSince1970`.
public struct RigArchive: Codable, Equatable {
/// Archive format version. Written as `rigArchiveFormatVersion` at export time.
public let version: Int
/// The rigs contained in this archive, in listing order.
public let rigs: [RigEntry]
/// Creates a rig archive.
///
/// - Parameters:
/// - version: Archive format version. Defaults to `rigArchiveFormatVersion`.
/// - rigs: The rigs to bundle.
public init(
version: Int = rigArchiveFormatVersion,
rigs: [RigEntry]
) {
self.version = version
self.rigs = rigs
}
}
@@ -0,0 +1,98 @@
// RigEntry.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// A named, timestamped rig in the user's library.
///
/// `RigEntry` is the unit stored and retrieved by `RigLibraryStore`. Each entry pairs a complete
/// ``ShoeGazeState`` snapshot (every board and its pedals) with a human-readable `name`
/// (e.g. `"Ambient Wash"`) and a `savedAt` timestamp. It is the rig-level analogue of
/// `BoardVersion`, which captures a single board.
///
/// `RigEntry` is `Codable` so it round-trips through the per-rig JSON files written by
/// `RigLibraryStore` and through the bundled ``RigArchive`` export. It is `Identifiable`
/// (via `UUID`) for direct use in SwiftUI `List` / `ForEach`, and `Equatable` for round-trip tests.
///
/// ## Typical usage
///
/// ```swift
/// let entry = shoeGaze.captureEntry(name: "Ambient Wash")
/// try store.save(entry)
/// // later …
/// try shoeGaze.loadRig(from: entry.state)
/// ```
public struct RigEntry: Codable, Identifiable, Equatable {
/// Stable unique identifier for this entry. Also seeds the on-disk filename.
public let id: UUID
/// Human-readable name (e.g. `"Ambient Wash"`, `"Live Set A"`).
public let name: String
/// Date and time at which this entry was last saved, at **whole-second precision**.
///
/// Rounded to the nearest second at init so it survives a JSON `secondsSince1970`
/// round-trip exactly — otherwise the fractional `Double` text form loses precision and
/// breaks `Equatable` after a `RigLibraryStore` write/load cycle.
public let savedAt: Date
/// The full rig snapshot — every board, segment, and pedal parameter.
public let state: ShoeGazeState
/// Creates a rig library entry.
///
/// - Parameters:
/// - id: Stable unique identifier. Defaults to a newly generated `UUID()`.
/// - name: Human-readable name for this rig.
/// - savedAt: Save timestamp. Defaults to `Date()` (now). Rounded to the nearest
/// whole second so persistence round-trips are lossless.
/// - state: The ``ShoeGazeState`` rig snapshot to store.
public init(
id: UUID = UUID(),
name: String,
savedAt: Date = Date(),
state: ShoeGazeState
) {
self.id = id
self.name = name
// Round to whole seconds: a fractional Date loses precision through the JSON
// `secondsSince1970` Double text form, which would break `Equatable` after a
// disk round-trip.
self.savedAt = Date(timeIntervalSince1970: savedAt.timeIntervalSince1970.rounded())
self.state = state
}
/// Returns a copy of this entry with a new `name`, a fresh `id`, and `savedAt` updated to
/// `date`. Used by the library's "duplicate" action so a copied rig becomes an independent
/// entry rather than overwriting the original's file.
///
/// - Parameters:
/// - name: The new entry's name.
/// - date: The new save timestamp. Defaults to `Date()` (now).
/// - Returns: A new `RigEntry` carrying the same `state` under a new identity.
public func duplicated(
name: String,
date: Date = Date()
) -> RigEntry {
RigEntry(id: UUID(), name: name, savedAt: date, state: state)
}
/// Returns a copy of this entry with a new `name` and `savedAt` updated to `date`, keeping
/// the same `id`. Used by the library's "rename" action so the entry's identity and file
/// association are preserved.
///
/// - Parameters:
/// - name: The new name.
/// - date: The new save timestamp. Defaults to `Date()` (now).
/// - Returns: A new `RigEntry` with the same `id` and `state` under the new name.
public func renamed(
to name: String,
date: Date = Date()
) -> RigEntry {
RigEntry(id: id, name: name, savedAt: date, state: state)
}
}
@@ -0,0 +1,96 @@
// RigLibraryLocation.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Resolves where the rig library lives on disk: the shared iCloud container when available,
/// otherwise a local Application Support folder.
///
/// Both the macOS and iOS builder apps declare the **same** iCloud container
/// (``containerIdentifier``) in their entitlements — even though their bundle identifiers differ —
/// so a single rig library is shared across a user's devices and across both apps. When iCloud is
/// unavailable (not signed in, entitlement missing, or running in a context without provisioning)
/// the library falls back to a local folder and simply does not sync.
public enum RigLibraryLocation {
/// The shared iCloud container identifier. Both builder targets must list this exact value in
/// `com.apple.developer.icloud-container-identifiers` / `ubiquity-container-identifiers`, and
/// the container must be enabled on both App IDs in the developer account.
public static let containerIdentifier: String = "iCloud.net.realizedsound.ShoeGazeData"
/// Subfolder (inside the container's `Documents/` or inside Application Support) holding the
/// per-rig JSON files.
private static let rigsFolderName: String = "Rigs"
/// Local Application Support namespace, matching `BoardVersionStore.defaultDirectory()`.
private static let localFolderName: String = "LyrebirdShoeGaze"
/// iCloud documents subfolder. Storing rigs under `Documents/` (rather than the container root)
/// makes them eligible to appear in the Files app when `NSUbiquitousContainers` is configured.
private static let documentsFolderName: String = "Documents"
/// A resolved library directory and whether it is backed by iCloud.
public struct Resolved: Equatable {
/// The directory holding per-rig JSON files (created if needed).
public let directory: URL
/// `true` when `directory` is inside the iCloud ubiquity container (sync active);
/// `false` for the local Application Support fallback.
public let isICloud: Bool
}
/// Resolves the rig library directory, preferring iCloud.
///
/// - Important: When an iCloud account is signed in,
/// `FileManager.url(forUbiquityContainerIdentifier:)` performs **blocking** I/O that can be
/// slow on its first call. Prefer calling this **once at app startup, off the main thread**.
/// When no iCloud account is present, the cheap `ubiquityIdentityToken` check short-circuits
/// straight to the local fallback without the blocking call. The created directory is returned
/// ready to use.
///
/// - Parameter containerIdentifier: The ubiquity container to use. Defaults to
/// ``containerIdentifier``.
/// - Returns: The resolved directory and whether iCloud backing is active.
public static func resolve(
containerIdentifier identifier: String = containerIdentifier
) -> Resolved {
let fileManager: FileManager = FileManager.default
// No iCloud account signed in → skip the potentially-slow container lookup entirely.
guard fileManager.ubiquityIdentityToken != nil else {
return Resolved(directory: localDirectory(), isICloud: false)
}
if let container: URL = fileManager.url(forUbiquityContainerIdentifier: identifier) {
let directory: URL = container
.appendingPathComponent(documentsFolderName, isDirectory: true)
.appendingPathComponent(rigsFolderName, isDirectory: true)
try? fileManager.createDirectory(at: directory, withIntermediateDirectories: true)
return Resolved(directory: directory, isICloud: true)
}
return Resolved(directory: localDirectory(), isICloud: false)
}
/// The local (non-iCloud) rig library directory, created if needed.
///
/// Falls back to a folder in the system temporary directory if Application Support cannot be
/// resolved. Used as the iCloud-unavailable fallback and directly by tests.
///
/// - Returns: A local `URL` for the rigs directory.
public static func localDirectory() -> URL {
let fileManager: FileManager = FileManager.default
let base: URL = (try? fileManager.url(
for: .applicationSupportDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true
)) ?? fileManager.temporaryDirectory
let directory: URL = base
.appendingPathComponent(localFolderName, isDirectory: true)
.appendingPathComponent(rigsFolderName, isDirectory: true)
try? fileManager.createDirectory(at: directory, withIntermediateDirectories: true)
return directory
}
}
@@ -0,0 +1,549 @@
// RigLibraryStore.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Observation
/// The user's library of saved rigs, persisted as one JSON file per rig and (when available)
/// synced across devices and apps through a shared iCloud container.
///
/// `RigLibraryStore` is `@Observable`, so SwiftUI views refresh automatically as `entries`
/// changes — whether the change came from a local edit or from a remote iCloud update. All
/// mutations run on the main actor.
///
/// ## Storage model
///
/// Each ``RigEntry`` is written as a separate pretty-printed JSON file named
/// `<sanitized-name>-<id>.json` (see ``sanitizePresetFilename(_:maxLength:)``) inside the
/// directory resolved by ``RigLibraryLocation``. One file per rig keeps iCloud merges
/// conflict-free at rig granularity: editing rig A never rewrites rig B's file.
///
/// When the directory is an iCloud ubiquity container, reads and writes are wrapped in
/// `NSFileCoordinator`, and an `NSMetadataQuery` watches for remote changes so a rig saved on one
/// device appears on another without relaunching. Call ``start()`` once after construction to load
/// the current contents and begin watching.
///
/// ## Typical usage
///
/// ```swift
/// // Off the main thread at launch (the ubiquity lookup blocks):
/// let resolved = RigLibraryLocation.resolve()
/// // Back on the main actor:
/// let store = RigLibraryStore(resolved: resolved)
/// store.start()
/// // …
/// try store.save(shoeGaze.captureEntry(name: "Ambient Wash"))
/// ```
@MainActor
@Observable
public final class RigLibraryStore {
// MARK: - State
/// All known rigs, sorted by name (case-insensitive), then most-recently-saved first.
public private(set) var entries: [RigEntry] = []
/// `true` when the library is backed by the iCloud container (changes sync); `false` for the
/// local-only fallback. Resolved during ``start()`` for an auto-resolving store.
public private(set) var isICloud: Bool
/// The directory holding the per-rig JSON files. May be repointed from local to iCloud during
/// ``start()`` for an auto-resolving store (before any writes, so no migration is needed).
public private(set) var directory: URL
/// `false` until the first load completes. Views can show a loading state and callers should
/// wait for this (or `await start()`) before deciding whether the library is empty — otherwise a
/// first-launch seed would race a not-yet-loaded iCloud library.
public private(set) var isLoaded: Bool = false
// MARK: - Private
/// Live query over the iCloud documents scope; `nil` when local-only or not yet started.
@ObservationIgnored private var metadataQuery: NSMetadataQuery?
/// Retained NotificationCenter tokens for the metadata-query observers.
@ObservationIgnored private var observerTokens: [NSObjectProtocol] = []
/// Serial queue for all disk writes/deletes. Mutations update the in-memory `entries` on the
/// main actor immediately (so the UI never blocks on disk or iCloud coordination), then hand the
/// file work here. Serial ordering keeps a rename's delete-then-write — and any save/delete on
/// the same file — in submission order.
@ObservationIgnored private let ioQueue: DispatchQueue =
DispatchQueue(label: "net.realizedsound.shoegaze.riglibrary.io", qos: .utility)
/// File extension of a stored rig.
private nonisolated static let fileExtension: String = "json"
/// When `true`, ``start()`` resolves the iCloud-or-local location off the main thread and
/// repoints `directory`/`isICloud` before loading. `false` for the explicit test initializer.
private let autoResolve: Bool
// MARK: - Init
/// Creates a store rooted at an explicit directory. Used directly by tests with a temporary
/// directory; `start()` will not re-resolve the location.
///
/// - Parameters:
/// - directory: The directory holding per-rig JSON files. Created if it does not exist.
/// - isICloud: Whether `directory` is an iCloud ubiquity container (enables coordination and
/// remote-change watching).
public init(
directory: URL,
isICloud: Bool
) {
self.directory = directory
self.isICloud = isICloud
self.autoResolve = false
try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
}
/// Creates an auto-resolving store. Constructed instantly with a local placeholder directory;
/// ``start()`` resolves the real iCloud-or-local location off the main thread before loading.
public init() {
self.directory = RigLibraryLocation.localDirectory()
self.isICloud = false
self.autoResolve = true
}
// MARK: - Lifecycle
/// Resolves the location (off the main thread, for an auto-resolving store), loads the current
/// library contents (off the main thread), and — when iCloud-backed — begins watching for
/// remote changes. Awaitable so callers can seed/highlight only once the real library state is
/// known. Safe to call once after construction.
public func start() async {
if autoResolve {
let resolved: RigLibraryLocation.Resolved = await RigLibraryStore.resolveOffMain()
directory = resolved.directory
isICloud = resolved.isICloud
try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
}
if isICloud {
startMetadataQuery()
}
await reload()
isLoaded = true
}
/// Re-reads the library directory off the main thread and republishes `entries`. Ordered after
/// any queued background writes (shares `ioQueue`), so a save followed by a reload never drops
/// the just-saved rig.
public func reload() async {
let dir: URL = directory
let coordinated: Bool = isICloud
let loaded: [RigEntry] = await withCheckedContinuation { continuation in
ioQueue.async {
continuation.resume(returning: RigLibraryStore.loadEntries(in: dir, coordinated: coordinated))
}
}
entries = RigLibraryStore.sorted(loaded)
}
/// Resolves the iCloud-or-local location on a background queue so the blocking ubiquity lookup
/// never runs on the main thread.
private static func resolveOffMain() async -> RigLibraryLocation.Resolved {
await withCheckedContinuation { continuation in
DispatchQueue.global(qos: .userInitiated).async {
continuation.resume(returning: RigLibraryLocation.resolve())
}
}
}
/// Stops watching for remote changes and removes observers. Call when tearing the store down;
/// the store otherwise lives for the app's lifetime.
public func stop() {
metadataQuery?.stop()
metadataQuery = nil
for token: NSObjectProtocol in observerTokens {
NotificationCenter.default.removeObserver(token)
}
observerTokens.removeAll()
}
// MARK: - Mutations
/// Saves `entry`, writing its JSON file and updating `entries` in memory.
///
/// If an entry with the same `id` already exists, its file and in-memory record are replaced
/// (the on-disk filename also updates if the name changed). Use this both to add a brand-new
/// rig and to overwrite an existing one (`shoeGaze.captureEntry(name:id:)`).
///
/// - Parameter entry: The rig entry to persist.
/// - Throws: `JSONEncoder` errors (encoding happens synchronously). The actual file write runs
/// asynchronously on a background queue and only logs on failure — call
/// ``flushPendingWrites()`` to wait for it (e.g. in tests or at app termination).
public func save(_ entry: RigEntry) throws {
// Encode synchronously (cheap, CPU) so an encoding failure is surfaced to the caller; then
// update the in-memory list immediately and push the disk write to the background queue.
let data: Data = try encode(entry)
let target: URL = fileURL(for: entry)
let directory: URL = self.directory
let id: UUID = entry.id
let coordinated: Bool = isICloud
upsert(entry)
ioQueue.async {
// Remove any prior file for this id first (a rename changes the name-prefixed filename).
if let stale: URL = RigLibraryStore.existingFileURL(for: id, in: directory),
stale.standardizedFileURL != target.standardizedFileURL {
try? RigLibraryStore.removeFile(at: stale, coordinated: coordinated)
}
do {
try RigLibraryStore.writeData(data, to: target, coordinated: coordinated)
} catch {
print("[RigLibraryStore] save write failed: \(error)")
}
}
}
/// Deletes `entry` from memory immediately and removes its file on the background queue.
///
/// - Parameter entry: The rig entry to remove.
/// - Throws: Never throws today; remains `throws` for API stability. File-removal errors are
/// logged on the background queue.
public func delete(_ entry: RigEntry) throws {
entries.removeAll { $0.id == entry.id }
let directory: URL = self.directory
let id: UUID = entry.id
let coordinated: Bool = isICloud
ioQueue.async {
if let url: URL = RigLibraryStore.existingFileURL(for: id, in: directory) {
do { try RigLibraryStore.removeFile(at: url, coordinated: coordinated) }
catch { print("[RigLibraryStore] delete failed: \(error)") }
}
}
}
/// Clears the library in memory immediately and removes every rig file on the background queue.
///
/// - Throws: Never throws today; remains `throws` for API stability. Per-file removal errors are
/// logged on the background queue.
public func eraseAll() throws {
entries.removeAll()
let directory: URL = self.directory
let coordinated: Bool = isICloud
ioQueue.async {
for url: URL in RigLibraryStore.rigFileURLs(in: directory) {
do { try RigLibraryStore.removeFile(at: url, coordinated: coordinated) }
catch { print("[RigLibraryStore] eraseAll: removing \(url.lastPathComponent) failed: \(error)") }
}
}
}
/// Blocks until all queued background writes/deletes have completed.
///
/// Primarily for tests (assert on-disk state right after a mutation) and app termination (ensure
/// the last save reaches disk before exit). Avoid calling on the main thread during normal use —
/// that would reintroduce the very stall this design removes.
public func flushPendingWrites() {
ioQueue.sync { }
}
/// Duplicates `entry` under `newName` as an independent entry with a fresh `id`, persists it,
/// and returns it.
///
/// - Parameters:
/// - entry: The rig to copy.
/// - newName: The copy's name.
/// - Returns: The newly created entry.
/// - Throws: Any error from ``save(_:)``.
@discardableResult
public func duplicate(
_ entry: RigEntry,
newName: String
) throws -> RigEntry {
let copy: RigEntry = entry.duplicated(name: newName)
try save(copy)
return copy
}
/// Renames `entry` to `newName`, keeping its `id`, and returns the updated entry.
///
/// - Parameters:
/// - entry: The rig to rename.
/// - newName: The new name.
/// - Returns: The renamed entry.
/// - Throws: Any error from ``save(_:)``.
@discardableResult
public func rename(
_ entry: RigEntry,
to newName: String
) throws -> RigEntry {
let renamed: RigEntry = entry.renamed(to: newName)
try save(renamed)
return renamed
}
// MARK: - Archive import / export
/// Encodes the entire library as a single ``RigArchive`` JSON document for export.
///
/// - Returns: Pretty-printed archive bytes suitable for a `fileExporter` / `NSSavePanel`.
/// - Throws: `JSONEncoder` errors.
public func exportArchiveData() throws -> Data {
let archive: RigArchive = RigArchive(rigs: entries)
return try RigLibraryStore.makeEncoder().encode(archive)
}
/// Imports rigs from archive `data`, saving each into the library, and returns how many were
/// added.
///
/// Accepts either a ``RigArchive`` (the multi-rig export format) or a legacy single-rig file
/// (a bare ``ShoeGazeState``), which is imported as one entry named `legacyRigName`. Imported
/// entries whose `id` already exists in the library are given a fresh `id` so an import never
/// silently overwrites an existing rig.
///
/// - Parameters:
/// - data: Archive or legacy-rig JSON bytes.
/// - legacyRigName: Name to use when importing a legacy single-rig file. Defaults to
/// `"Imported Rig"`.
/// - Returns: The number of rigs added to the library.
/// - Throws: `JSONDecoder` errors when `data` is neither an archive nor a legacy rig, or any
/// error from ``save(_:)``.
@discardableResult
public func importArchive(
from data: Data,
legacyRigName: String = "Imported Rig"
) throws -> Int {
let imported: [RigEntry] = try decodeImportable(data, legacyRigName: legacyRigName)
let existingIDs: Set<UUID> = Set(entries.map(\.id))
var added: Int = 0
for entry: RigEntry in imported {
// Avoid clobbering an existing rig that happens to share this id.
let toSave: RigEntry = existingIDs.contains(entry.id)
? entry.duplicated(name: entry.name, date: entry.savedAt)
: entry
try save(toSave)
added += 1
}
return added
}
// MARK: - Loading from disk
/// Rescans the directory and rebuilds `entries`. Files that cannot be read or decoded are
/// skipped so one bad file never blocks the rest. Not-yet-downloaded iCloud placeholders (which
/// are hidden `*.icloud` files) are naturally ignored and picked up on a later metadata update.
private nonisolated static func loadEntries(in directory: URL, coordinated: Bool) -> [RigEntry] {
var loaded: [RigEntry] = []
let decoder: JSONDecoder = makeDecoder()
for url: URL in rigFileURLs(in: directory) {
guard let data: Data = try? readData(at: url, coordinated: coordinated) else { continue }
guard let entry: RigEntry = try? decoder.decode(RigEntry.self, from: data) else { continue }
loaded.append(entry)
}
return loaded
}
// MARK: - iCloud metadata query
/// Starts the live query over the iCloud documents scope and wires update handlers.
private func startMetadataQuery() {
guard metadataQuery == nil else { return }
let query: NSMetadataQuery = NSMetadataQuery()
query.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope]
query.predicate = NSPredicate(
format: "%K LIKE %@",
NSMetadataItemFSNameKey,
"*.\(RigLibraryStore.fileExtension)"
)
let center: NotificationCenter = NotificationCenter.default
let handler: @Sendable (Notification) -> Void = { [weak self] _ in
// queue: .main delivers on the main thread; we are a main-actor type.
MainActor.assumeIsolated { self?.handleMetadataUpdate() }
}
observerTokens.append(center.addObserver(
forName: .NSMetadataQueryDidFinishGathering, object: query, queue: .main, using: handler
))
observerTokens.append(center.addObserver(
forName: .NSMetadataQueryDidUpdate, object: query, queue: .main, using: handler
))
metadataQuery = query
query.start()
}
/// Handles a metadata-query result: triggers downloads for any rig files not yet present
/// locally, then rescans the directory for whatever is now readable.
private func handleMetadataUpdate() {
guard let query: NSMetadataQuery = metadataQuery else { return }
query.disableUpdates()
defer { query.enableUpdates() }
let fileManager: FileManager = FileManager.default
for index: Int in 0..<query.resultCount {
guard let item: NSMetadataItem = query.result(at: index) as? NSMetadataItem,
let url: URL = item.value(forAttribute: NSMetadataItemURLKey) as? URL,
RigLibraryStore.isInLibrary(url, directory: directory) else { continue }
let status: String? =
item.value(forAttribute: NSMetadataUbiquitousItemDownloadingStatusKey) as? String
if status != NSMetadataUbiquitousItemDownloadingStatusCurrent {
try? fileManager.startDownloadingUbiquitousItem(at: url)
}
}
// Re-read off the main thread; the in-memory list republishes when it completes.
Task { await self.reload() }
}
// MARK: - File helpers
/// The write URL for `entry`: `<sanitized-name>-<id>.json` inside the library directory.
private func fileURL(for entry: RigEntry) -> URL {
let sanitized: String = sanitizePresetFilename(entry.name)
let filename: String = "\(sanitized)-\(entry.id.uuidString).\(RigLibraryStore.fileExtension)"
return directory.appendingPathComponent(filename)
}
/// Finds the existing file for `id` by matching the `-<uuid>.json` suffix, so renames (which
/// change the name prefix) are still located. `nil` if no file is present. `static` so the
/// background I/O queue can call it without touching actor state.
private nonisolated static func existingFileURL(for id: UUID, in directory: URL) -> URL? {
let suffix: String = "-\(id.uuidString).\(fileExtension)"
return rigFileURLs(in: directory).first { $0.lastPathComponent.hasSuffix(suffix) }
}
/// All `*.json` files currently in `directory` (hidden iCloud placeholders excluded).
private nonisolated static func rigFileURLs(in directory: URL) -> [URL] {
let contents: [URL] = (try? FileManager.default.contentsOfDirectory(
at: directory,
includingPropertiesForKeys: nil,
options: .skipsHiddenFiles
)) ?? []
return contents.filter { $0.pathExtension == fileExtension }
}
/// Whether `url` is a rig file directly inside `directory`.
private nonisolated static func isInLibrary(_ url: URL, directory: URL) -> Bool {
url.deletingLastPathComponent().standardizedFileURL == directory.standardizedFileURL
&& url.pathExtension == fileExtension
}
// MARK: - Coordinated I/O (background-queue safe)
/// Writes `data` to `url`, coordinating the write through `NSFileCoordinator` when iCloud-backed.
private nonisolated static func writeData(_ data: Data, to url: URL, coordinated: Bool) throws {
guard coordinated else {
try data.write(to: url, options: .atomic)
return
}
try coordinateWriting(url, options: .forReplacing) { target in
try data.write(to: target, options: .atomic)
}
}
/// Reads the contents of `url`, coordinating the read when iCloud-backed.
private nonisolated static func readData(at url: URL, coordinated: Bool) throws -> Data {
guard coordinated else {
return try Data(contentsOf: url)
}
var result: Data = Data()
try coordinateReading(url, options: .withoutChanges) { target in
result = try Data(contentsOf: target)
}
return result
}
/// Removes `url`, coordinating the delete when iCloud-backed.
private nonisolated static func removeFile(at url: URL, coordinated: Bool) throws {
guard coordinated else {
try FileManager.default.removeItem(at: url)
return
}
try coordinateWriting(url, options: .forDeleting) { target in
try FileManager.default.removeItem(at: target)
}
}
/// Runs `body` inside an `NSFileCoordinator` write block, surfacing both the coordinator's error
/// and any error thrown by `body`.
private nonisolated static func coordinateWriting(
_ url: URL,
options: NSFileCoordinator.WritingOptions,
_ body: (URL) throws -> Void
) throws {
let coordinator: NSFileCoordinator = NSFileCoordinator()
var coordinatorError: NSError?
var thrown: Error?
coordinator.coordinate(writingItemAt: url, options: options, error: &coordinatorError) { target in
do { try body(target) } catch { thrown = error }
}
if let coordinatorError: NSError = coordinatorError { throw coordinatorError }
if let thrown: Error = thrown { throw thrown }
}
/// Runs `body` inside an `NSFileCoordinator` read block.
private nonisolated static func coordinateReading(
_ url: URL,
options: NSFileCoordinator.ReadingOptions,
_ body: (URL) throws -> Void
) throws {
let coordinator: NSFileCoordinator = NSFileCoordinator()
var coordinatorError: NSError?
var thrown: Error?
coordinator.coordinate(readingItemAt: url, options: options, error: &coordinatorError) { target in
do { try body(target) } catch { thrown = error }
}
if let coordinatorError: NSError = coordinatorError { throw coordinatorError }
if let thrown: Error = thrown { throw thrown }
}
// MARK: - Codec
/// Encodes a single entry as a per-rig file would store it.
private func encode(_ entry: RigEntry) throws -> Data {
try RigLibraryStore.makeEncoder().encode(entry)
}
/// A JSON encoder configured for human-readable, round-trip-stable preset files.
private nonisolated static func makeEncoder() -> JSONEncoder {
let encoder: JSONEncoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
encoder.dateEncodingStrategy = .secondsSince1970
return encoder
}
/// A JSON decoder matching ``makeEncoder()``.
private nonisolated static func makeDecoder() -> JSONDecoder {
let decoder: JSONDecoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
return decoder
}
/// Decodes import bytes as a ``RigArchive`` first, falling back to a legacy single-rig
/// ``ShoeGazeState``.
private func decodeImportable(
_ data: Data,
legacyRigName: String
) throws -> [RigEntry] {
let decoder: JSONDecoder = RigLibraryStore.makeDecoder()
if let archive: RigArchive = try? decoder.decode(RigArchive.self, from: data) {
return archive.rigs
}
// A legacy single-rig file is a bare ShoeGazeState (no `rigs` array). Decode and wrap.
let state: ShoeGazeState = try decoder.decode(ShoeGazeState.self, from: data)
return [RigEntry(name: legacyRigName, state: state)]
}
// MARK: - In-memory helpers
/// Inserts or replaces `entry` in `entries` by `id`, keeping the list sorted.
private func upsert(_ entry: RigEntry) {
var next: [RigEntry] = entries.filter { $0.id != entry.id }
next.append(entry)
entries = RigLibraryStore.sorted(next)
}
/// Sorts entries by name (case-insensitive), then most-recently-saved first, then id for a
/// fully deterministic order.
private static func sorted(_ entries: [RigEntry]) -> [RigEntry] {
entries.sorted { lhs, rhs in
let byName: ComparisonResult = lhs.name.localizedCaseInsensitiveCompare(rhs.name)
if byName != .orderedSame { return byName == .orderedAscending }
if lhs.savedAt != rhs.savedAt { return lhs.savedAt > rhs.savedAt }
return lhs.id.uuidString < rhs.id.uuidString
}
}
}
@@ -0,0 +1,72 @@
// RigStore.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Autosaves the current rig to disk and restores it on launch, so a board survives app restarts.
///
/// Writes the same JSON produced by `ShoeGaze.rigData()` to a fixed file in the user's
/// Application Support directory. Callers save on app background/terminate (and after notable
/// edits) and restore once at startup, before seeding any default board.
@MainActor
public enum RigStore {
private static let folderName: String = "ShoeGaze"
private static let fileName: String = "autosave-rig.json"
/// Location of the autosave file, creating the containing folder if needed. `nil` if the
/// Application Support directory can't be resolved.
public static var autosaveURL: URL? {
let fileManager: FileManager = FileManager.default
guard let base: URL = try? fileManager.url(
for: .applicationSupportDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true
) else { return nil }
let dir: URL = base.appendingPathComponent(folderName, isDirectory: true)
try? fileManager.createDirectory(at: dir, withIntermediateDirectories: true)
return dir.appendingPathComponent(fileName)
}
/// Writes the rig's current state to the autosave file. Returns `false` on any failure.
@discardableResult
public static func save(_ shoeGaze: ShoeGaze) -> Bool {
guard let url: URL = autosaveURL else { return false }
do {
let data: Data = try shoeGaze.rigData()
try data.write(to: url, options: .atomic)
return true
} catch {
print("[RigStore] autosave failed: \(error)")
return false
}
}
/// Restores a previously autosaved rig into `shoeGaze`, which should have no boards yet.
///
/// - Returns: `true` if an autosave existed and produced at least one board; `false` if there
/// was nothing to restore or the load failed (in which case the caller should seed a default).
@discardableResult
public static func restore(into shoeGaze: ShoeGaze) -> Bool {
guard let url: URL = autosaveURL,
FileManager.default.fileExists(atPath: url.path) else { return false }
do {
let data: Data = try Data(contentsOf: url)
try shoeGaze.loadRig(from: data)
return !shoeGaze.boards.isEmpty
} catch {
print("[RigStore] restore failed: \(error)")
return false
}
}
/// Deletes the autosave file (e.g. after the user clears the board without saving).
public static func clear() {
guard let url: URL = autosaveURL else { return }
try? FileManager.default.removeItem(at: url)
}
}
@@ -21,7 +21,8 @@ extension ShoeGaze {
/// running engine with at most one block of glitch (see ``rebuildBoard(_:from:)``).
///
/// - Parameters:
/// - type: The pedal's `displayName`, e.g. `"Overdrive"`. Must be a key in `PedalRegistry.builtIn`.
/// - kind: The pedal type, e.g. ``PedalType/overdrive``. Its `rawValue` must be a key in
/// `PedalRegistry.builtIn`.
/// - board: The board to edit. Must have been returned by `addBoard()` on this instance.
/// - lane: Where to append. Defaults to ``PedalLane/main``.
/// - Returns: The rebuilt board occupying the same slot in `boards`.
@@ -29,10 +30,11 @@ extension ShoeGaze {
/// any error from ``rebuildBoard(_:from:)``.
@discardableResult
public func appendPedal(
type: String,
_ kind: PedalType,
to board: PedalBoard,
lane: PedalLane = .main
) throws -> PedalBoard {
let type: String = kind.rawValue
guard PedalRegistry.builtIn[type] != nil else {
throw ShoeGazeError.unknownPedalType(type)
}
@@ -115,6 +117,83 @@ extension ShoeGaze {
return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments))
}
/// Moves a pedal from one lane to another (e.g. the main chain into a stereo-unzip lane, or
/// between branches), preserving its parameter values. The moved pedal is appended to the end
/// of the destination lane.
///
/// - Parameters:
/// - sourceLane: The lane the pedal currently lives in.
/// - sourceIndex: The pedal's index within `sourceLane`.
/// - destinationLane: The lane to move the pedal into.
/// - board: The board to edit.
/// - Returns: The rebuilt board occupying the same slot in `boards`.
/// - Throws: `ShoeGazeError.pedalIndexOutOfRange`, `.notABranchRegion`, or any rebuild error.
@discardableResult
public func movePedal(
from sourceLane: PedalLane,
at sourceIndex: Int,
to destinationLane: PedalLane,
in board: PedalBoard
) throws -> PedalBoard {
var segments: [BoardSegmentState] = board.captureState().segments
// 1. Remove the pedal from its source lane, capturing its full state. Removing a main
// pedal deletes a top-level segment; record where so the destination region index can
// be corrected if it sat after the removal.
let moved: PedalState
var removedTopLevelIndex: Int?
switch sourceLane {
case .main:
let positions: [Int] = linearPedalSegmentIndices(segments)
guard sourceIndex >= 0, sourceIndex < positions.count else {
throw ShoeGazeError.pedalIndexOutOfRange(index: sourceIndex, count: positions.count)
}
let absolute: Int = positions[sourceIndex]
guard case .pedal(let state) = segments[absolute] else {
throw ShoeGazeError.pedalIndexOutOfRange(index: sourceIndex, count: positions.count)
}
moved = state
segments.remove(at: absolute)
removedTopLevelIndex = absolute
case .left, .right:
var captured: PedalState?
try mutateBranch(&segments, lane: sourceLane) { branch in
guard sourceIndex >= 0, sourceIndex < branch.count else {
throw ShoeGazeError.pedalIndexOutOfRange(index: sourceIndex, count: branch.count)
}
captured = branch.remove(at: sourceIndex)
}
guard let capturedState: PedalState = captured else {
throw ShoeGazeError.pedalIndexOutOfRange(index: sourceIndex, count: 0)
}
moved = capturedState
}
// 2. Correct the destination region index if a top-level segment before it was removed.
var destination: PedalLane = destinationLane
if let region: Int = destinationLane.regionIndex,
let removed: Int = removedTopLevelIndex, removed < region {
destination = destinationLane.isLeftBranch ? .left(region: region - 1) : .right(region: region - 1)
}
// 3. Append the moved pedal to the destination lane.
switch destination {
case .main:
let positions: [Int] = linearPedalSegmentIndices(segments)
if let lastPedal: Int = positions.last {
segments.insert(.pedal(moved), at: lastPedal + 1)
} else {
segments.append(.pedal(moved))
}
case .left, .right:
try mutateBranch(&segments, lane: destination) { branch in
branch.append(moved)
}
}
return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments))
}
// MARK: - Branch regions
/// Appends an empty stereo split region (two independently authored L/R lanes) to the board.
@@ -21,6 +21,23 @@ extension ShoeGaze {
return ShoeGazeState(boards: boardStates)
}
/// Captures the current rig as a named ``RigEntry`` suitable for the rig library.
///
/// Wraps ``captureState()`` with a name, a fresh `id`, and a `savedAt` timestamp. The engine
/// graph is not modified; this is a read-only operation.
///
/// - Parameters:
/// - name: Human-readable name for the entry (e.g. `"Ambient Wash"`).
/// - id: Stable identifier. Defaults to a newly generated `UUID()`; pass an existing entry's
/// `id` to overwrite that entry in place.
/// - Returns: A ``RigEntry`` reflecting the current rig.
public func captureEntry(
name: String,
id: UUID = UUID()
) -> RigEntry {
RigEntry(id: id, name: name, state: captureState())
}
// MARK: - Save / Load
/// Saves the current rig to a JSON file at `url`.
@@ -58,6 +75,20 @@ extension ShoeGaze {
public func loadRig(from data: Data) throws {
let decoder: JSONDecoder = JSONDecoder()
let state: ShoeGazeState = try decoder.decode(ShoeGazeState.self, from: data)
try loadRig(from: state)
}
/// Rebuilds the engine graph from an already-decoded ``ShoeGazeState``.
///
/// Shared core of the `Data` / `URL` loaders, and the entry point the rig library uses to
/// recall a stored ``RigEntry`` (`loadRig(from: entry.state)`) without re-encoding. Rejects a
/// snapshot whose `version` exceeds `presetFormatVersion`, tears down the current rig, then
/// rebuilds every board with the all-or-nothing semantics of ``rebuildAllBoards(from:)``.
///
/// - Important: Call with the engine **stopped**, as with ``loadRig(from:)``.
/// - Parameter state: The rig snapshot to restore.
/// - Throws: `PresetError.unsupportedVersion` for a too-new snapshot, or any board-build error.
public func loadRig(from state: ShoeGazeState) throws {
guard state.version <= presetFormatVersion else {
throw PresetError.unsupportedVersion(state.version)
}
+147 -22
View File
@@ -34,9 +34,10 @@ import LyrebirdUI
///
/// ## Input routing
///
/// When `inputSource == .testLoop`, a `TestLoopSource` is added to the engine
/// **before** the first pedal on each board (plain `engine.add` places it at the
/// head of `mainGroup`, so it evaluates first).
/// When `inputSource == .testLoop`, a **single** shared `TestLoopSource` writes a global
/// test bus, and each board gets a `TestLoopTap` (added `.after(_:)` the source) copying that
/// bus into the board's head bus. One shared source keeps every board phase-locked and survives
/// board add/remove, so the arpeggio never restarts into a polyrhythm.
///
/// When `inputSource == .liveInput(channel:)`, a `HardwareInputPassThrough` synthesizer
/// copies hardware input `channel` (engine bus `numOutputChannels + channel`) to the
@@ -96,7 +97,14 @@ public final class ShoeGaze {
// MARK: - Private
private var testLoopSources: [TestLoopSource] = []
/// The single shared test-loop source feeding every board in `.testLoop` mode, and the bus
/// it writes. One global source keeps all boards phase-locked (no per-board polyrhythm) and
/// survives board add/remove so its arpeggio never restarts. `nil` outside `.testLoop` mode.
private var globalTestSource: TestLoopSource?
private var globalTestBus: AudioBus?
/// Per-board taps copying the global test bus into each board's head bus.
private var testLoopTaps: [TestLoopTap] = []
private var inputPassThroughs: [HardwareInputPassThrough] = []
private var outputMasters: [BoardOutputMaster] = []
@@ -149,16 +157,19 @@ public final class ShoeGaze {
// Route the input source to the board head bus.
switch inputSource {
case .testLoop:
let source: TestLoopSource = TestLoopSource(
targetBus: board.headBus.index,
sampleRate: engine.sampleRate
// All boards share one global test source so they stay phase-locked. Each board
// gets a tap copying the shared test bus into its head bus, added `.after(_:)` the
// source so it sees the source's output for the current block.
let (source, testBus): (TestLoopSource, AudioBus) = try ensureGlobalTestSource()
let tap: TestLoopTap = TestLoopTap(
inputBusIndex: testBus.index,
outputBusIndex: board.headBus.index
)
// Plain add → head of mainGroup (evaluates before any pedal).
try engine.add(source)
testLoopSources.append(source)
// Record the source as the head input node so PedalBoard.add(_:) can chain
// the first pedal after it automatically (without needing an explicit `after:`).
board.headInputNode = source
try engine.add(tap, position: NodePosition.after(source))
testLoopTaps.append(tap)
// Record the tap as the head input node so PedalBoard.add(_:) can chain the first
// pedal after it automatically (without needing an explicit `after:`).
board.headInputNode = tap
case .liveInput(let channel):
// Hardware input channel `channel` lives at bus numOutputChannels + channel.
@@ -181,6 +192,36 @@ public final class ShoeGaze {
return board
}
/// Lazily creates the single shared test-loop source and its bus, returning both.
///
/// Created once per `.testLoop` session and reused by every board's tap, so the arpeggio
/// phase is continuous across board add/remove (no per-board polyrhythm). Torn down by
/// ``teardown()`` (and thus by ``setInputSource(_:)`` when leaving test-loop mode).
///
/// The source and bus are committed to `globalTestSource` / `globalTestBus` only after the
/// engine add succeeds — if `engine.add` throws, the freshly allocated bus is released so it
/// is never orphaned.
private func ensureGlobalTestSource() throws -> (source: TestLoopSource, bus: AudioBus) {
if let source: TestLoopSource = globalTestSource, let bus: AudioBus = globalTestBus {
return (source, bus)
}
let testBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let source: TestLoopSource = TestLoopSource(
targetBus: testBus.index,
sampleRate: engine.sampleRate
)
do {
// Plain add → head of mainGroup (evaluates before its taps and any pedal).
try engine.add(source)
} catch {
engine.busAllocator.releaseAudioBus(testBus)
throw error
}
globalTestBus = testBus
globalTestSource = source
return (source, testBus)
}
/// Connects the output master for a previously prepared board and adds it to the engine.
///
/// Call this after all pedals have been added to the board via `board.add(_:)`.
@@ -261,6 +302,52 @@ public final class ShoeGaze {
activeBoardIndex = nil
}
/// Solos `board` exclusively — identical to ``selectBoard(_:crossfadeSeconds:)``.
///
/// Provided as the "Solo" verb alongside ``setBoard(_:audible:crossfadeSeconds:)`` so
/// callers can express *make only this board audible* without conflating it with the
/// independent per-board enable used by Blend-style mixing.
///
/// - Parameters:
/// - board: The board to solo. No-op if not managed by this instance.
/// - crossfadeSeconds: Crossfade duration in seconds (`0` = instant).
public func soloBoard(_ board: PedalBoard, crossfadeSeconds: Double) {
selectBoard(board, crossfadeSeconds: crossfadeSeconds)
}
/// Sets a single board audible or silent **without** disturbing the others.
///
/// Unlike ``selectBoard(_:crossfadeSeconds:)`` (which is exclusive), this toggles one
/// board's select-gain in place, so arbitrary subsets of boards can play at once — the
/// "Blend" mixing model. Because the audible set is no longer a single soloed board,
/// ``activeBoardIndex`` is cleared to `nil`.
///
/// - Parameters:
/// - board: The board to enable or silence. No-op if not managed by this instance.
/// - audible: `true` to fade the board in, `false` to fade it out.
/// - crossfadeSeconds: Crossfade duration in seconds (`0` = instant).
public func setBoard(_ board: PedalBoard, audible: Bool, crossfadeSeconds: Double) {
guard boards.contains(where: { $0 === board }) else { return }
board.crossfadeTimeNode?.update(crossfadeSeconds)
board.selectGainNode?.update(audible ? 1.0 : 0.0)
activeBoardIndex = nil
}
/// Whether `board`'s output is currently audible (its select-gain target is on).
///
/// Reads the live select-gain target, so it reflects the latest
/// ``selectBoard(_:crossfadeSeconds:)`` / ``setBoard(_:audible:crossfadeSeconds:)`` /
/// ``selectAllBoards(crossfadeSeconds:)`` call (the value the crossfade is ramping
/// toward), independent of where the crossfade currently sits.
///
/// - Parameter board: A board managed by this instance.
/// - Returns: `true` when the board's select-gain target is on; `false` when silenced
/// or when the board has no output master yet.
public func isBoardAudible(_ board: PedalBoard) -> Bool {
let selectGainOnThreshold: Double = 0.5
return (board.selectGainNode?.value ?? 0.0) > selectGainOnThreshold
}
/// Removes a single board and its associated input source and output master from
/// the engine, then releases the board's buses. The other boards are unaffected.
///
@@ -287,10 +374,12 @@ public final class ShoeGaze {
outputMasters.removeAll { $0 === master }
}
// Remove the board's input source (writer of the head bus).
if let testLoop: TestLoopSource = board.headInputNode as? TestLoopSource {
engine.remove(testLoop)
testLoopSources.removeAll { $0 === testLoop }
// Remove the board's input node (writer of the head bus). In `.testLoop` mode this is a
// tap; the shared global source is left running so the remaining boards keep their
// phase-locked test signal.
if let tap: TestLoopTap = board.headInputNode as? TestLoopTap {
engine.remove(tap)
testLoopTaps.removeAll { $0 === tap }
} else if let passThrough: HardwareInputPassThrough = board.headInputNode as? HardwareInputPassThrough {
engine.remove(passThrough)
inputPassThroughs.removeAll { $0 === passThrough }
@@ -299,6 +388,16 @@ public final class ShoeGaze {
// Remove the pedals and release the board's buses.
board.teardown()
boards.remove(at: index)
// Keep the soloed-board index valid: clear it if the soloed board was removed,
// otherwise shift it down when a board before it was removed.
if let active: Int = activeBoardIndex {
if active == index {
activeBoardIndex = nil
} else if active > index {
activeBoardIndex = active - 1
}
}
}
// MARK: - Chain router
@@ -321,6 +420,13 @@ public final class ShoeGaze {
/// try engine.start()
/// ```
///
/// > Note: In `.testLoop` mode a `ChainRouter` allocates **its own** test source (shared by
/// > the router's two boards via the splitter, so those two stay phase-locked to each other).
/// > That source is independent of the global test source used by ``addBoard()``-created
/// > boards, so a router's boards are *not* phase-locked to the main board list. Routers are
/// > a separate multi-board path (not used by the standard builder UI); unifying them onto the
/// > global source is intentionally out of scope here.
///
/// - Returns: A ``ChainRouter`` with both boards ready to receive pedals.
/// - Throws:
/// - `ShoeGazeError.liveInputRequiresInputChannels` when `inputSource == .liveInput`
@@ -339,18 +445,26 @@ public final class ShoeGaze {
/// Moves `board` to `targetIndex` within `boards`, locating it by identity.
///
/// This is an internal helper that mutates `boards` directly — valid only because
/// `ShoeGaze` is `@MainActor` (no concurrent access). The method is `internal` rather than
/// `public` so callers outside the ShoeGaze module cannot disrupt board ordering.
/// `ShoeGaze` is `@MainActor` (no concurrent access). Reordering only permutes the
/// `boards` array; it does not touch the engine graph, so it is safe to call while the
/// engine is running.
///
/// - Parameters:
/// - board: The `PedalBoard` to reposition. No-op if not found in `boards`.
/// - index: The desired destination index. Clamped to `boards.count` after removal
/// so it is always a valid insertion point.
internal func moveBoard(_ board: PedalBoard, to index: Int) {
public func moveBoard(_ board: PedalBoard, to index: Int) {
guard let sourceIndex: Int = boards.firstIndex(where: { $0 === board }) else { return }
// Track the soloed board by identity so its index follows the reorder.
let soloedBoard: PedalBoard? = activeBoardIndex.flatMap { idx in
idx < boards.count ? boards[idx] : nil
}
let removed: PedalBoard = boards.remove(at: sourceIndex)
let destination: Int = min(index, boards.count)
boards.insert(removed, at: destination)
if let soloedBoard {
activeBoardIndex = boards.firstIndex(where: { $0 === soloedBoard })
}
}
// MARK: - Teardown
@@ -376,10 +490,21 @@ public final class ShoeGaze {
// Step 1: Remove all engine nodes that write to board buses.
// Order within this step does not matter; all must finish before bus release.
for source: TestLoopSource in testLoopSources {
for tap: TestLoopTap in testLoopTaps {
engine.remove(tap)
}
testLoopTaps.removeAll()
// Remove the shared global test source and release its bus (after its taps are removed,
// preserving remove-before-release ordering).
if let source: TestLoopSource = globalTestSource {
engine.remove(source)
}
testLoopSources.removeAll()
globalTestSource = nil
if let testBus: AudioBus = globalTestBus {
engine.busAllocator.releaseAudioBus(testBus)
}
globalTestBus = nil
for passThrough: HardwareInputPassThrough in inputPassThroughs {
engine.remove(passThrough)
+2 -2
View File
@@ -48,8 +48,8 @@ public enum ShoeGazeError: Error, LocalizedError, Equatable, Sendable {
/// Narrow the chain with `mergeToMono()` before adding another widener.
case stereoWidthExceeded
/// Thrown by the linear pedal-edit API (`appendPedal(type:to:)`) when `type` is not a
/// known pedal in `PedalRegistry.builtIn`. The associated value is the requested type string.
/// Thrown by the linear pedal-edit API (`appendPedal(_:to:)`) when the kind's `rawValue` is
/// not a known pedal in `PedalRegistry.builtIn`. The associated value is the requested type string.
case unknownPedalType(String)
/// Thrown by `removePedal(at:from:)` / `movePedal(from:to:in:)` when a linear pedal index is
@@ -0,0 +1,310 @@
// BoardBarView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdUI
import LyrebirdShoeGaze
/// A horizontal board-mixer strip for switching between, or blending, multiple `PedalBoard`s.
///
/// Each board is a channel cell with an audible LED, a Solo button, and a level fader (the
/// board's master gain). A leading **Solo / Blend** mode switch chooses the interaction:
///
/// - **Solo** — tapping a cell's LED makes that board the only audible one
/// (``ShoeGaze/soloBoard(_:crossfadeSeconds:)``); the **All** button returns to the
/// summed state (``ShoeGaze/selectAllBoards(crossfadeSeconds:)``). Amp-channel feel.
/// - **Blend** — tapping a cell's LED toggles that board in or out of the mix
/// independently (``ShoeGaze/setBoard(_:audible:crossfadeSeconds:)``), so any subset can
/// play at once — the default summed behaviour, now controllable per board.
///
/// Tapping a cell's **name** selects it as the edit target (`editingBoardIndex`), which is
/// independent of what is audible — you can audition one board while editing another. A
/// cell's context menu deletes the board.
///
/// The same view serves macOS and iOS; on iOS the cell row scrolls horizontally and the
/// context-menu delete is reached by long-press.
public struct BoardBarView: View {
// MARK: - Play mode
/// How a cell's LED tap maps to board audibility.
private enum PlayMode: Hashable {
/// Tapping a board solos it exclusively.
case solo
/// Tapping a board toggles it independently in/out of the mix.
case blend
}
// MARK: - Layout constants
private static let barSpacing: CGFloat = 10
private static let barHeight: CGFloat = 92
private static let cellSpacing: CGFloat = 8
private static let cellWidth: CGFloat = 104
private static let cellInnerSpacing: CGFloat = 5
private static let cellPadding: CGFloat = 7
private static let cellCornerRadius: CGFloat = 8
private static let controlColumnWidth: CGFloat = 188
private static let modePickerWidth: CGFloat = 104
private static let crossfadeSliderMinWidth: CGFloat = 64
private static let ledDiameter: CGFloat = 12
private static let ledGlowRadius: CGFloat = 6
private static let ledGlowOpacity: Double = 0.75
private static let ledDimBrightness: Double = 0.16
private static let ledRimOpacity: Double = 0.30
private static let soloButtonSize: CGFloat = 22
private static let editingBorderWidth: CGFloat = 2
private static let idleBorderOpacity: Double = 0.18
private static let cellBackgroundBrightness: Double = 0.14
private static let labelOpacity: Double = 0.65
private static let nameFontSize: CGFloat = 12
private static let maxCrossfadeSeconds: Double = 10.0
private static let crossfadeStep: Double = 0.1
private static let addButtonSize: CGFloat = 30
// MARK: - Properties
private let shoeGaze: ShoeGaze
@Binding private var editingBoardIndex: Int
@Binding private var crossfadeSeconds: Double
private let onAddBoard: () -> Void
@State private var mode: PlayMode = .solo
// MARK: - Init
/// Creates a board-mixer bar.
///
/// - Parameters:
/// - shoeGaze: The manager whose `boards` are switched / blended.
/// - editingBoardIndex: The index of the board currently being edited (a cell's name
/// tap writes this).
/// - crossfadeSeconds: Crossfade duration applied to every board switch / toggle.
/// - onAddBoard: Called when the trailing **+** button is tapped.
public init(
shoeGaze: ShoeGaze,
editingBoardIndex: Binding<Int>,
crossfadeSeconds: Binding<Double>,
onAddBoard: @escaping () -> Void
) {
self.shoeGaze = shoeGaze
self._editingBoardIndex = editingBoardIndex
self._crossfadeSeconds = crossfadeSeconds
self.onAddBoard = onAddBoard
}
// MARK: - Body
public var body: some View {
// One horizontal scroll group so the whole bar hugs its content and stays a short,
// fixed-height band — leaving the canvas below for the pedals.
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .center, spacing: BoardBarView.barSpacing) {
controlColumn
Divider().overlay(Color.white.opacity(BoardBarView.idleBorderOpacity))
ForEach(Array(shoeGaze.boards.enumerated()), id: \.offset) { pair in
boardCell(index: pair.offset, board: pair.element)
}
addButton
}
.frame(height: BoardBarView.barHeight)
}
.frame(height: BoardBarView.barHeight)
}
// MARK: - Control column
private var controlColumn: some View {
VStack(alignment: .leading, spacing: BoardBarView.cellInnerSpacing) {
HStack(spacing: BoardBarView.cellInnerSpacing) {
Picker("Mode", selection: $mode) {
Text("Solo").tag(PlayMode.solo)
Text("Blend").tag(PlayMode.blend)
}
.pickerStyle(.segmented)
.labelsHidden()
.frame(width: BoardBarView.modePickerWidth)
Button("All") {
shoeGaze.selectAllBoards(crossfadeSeconds: clampedCrossfade)
}
.buttonStyle(.bordered)
.tint(.orange)
.help("Play all boards (summed)")
}
HStack(spacing: BoardBarView.cellInnerSpacing) {
Text("XFade")
.font(.caption2)
.foregroundStyle(Color.white.opacity(BoardBarView.labelOpacity))
Slider(
value: $crossfadeSeconds,
in: 0 ... BoardBarView.maxCrossfadeSeconds,
step: BoardBarView.crossfadeStep
)
.frame(minWidth: BoardBarView.crossfadeSliderMinWidth)
Text(String(format: "%.1fs", clampedCrossfade))
.font(.caption2)
.monospacedDigit()
.foregroundStyle(Color.white.opacity(BoardBarView.labelOpacity))
}
}
.frame(width: BoardBarView.controlColumnWidth)
}
// MARK: - Board cell
@ViewBuilder
private func boardCell(index: Int, board: PedalBoard) -> some View {
let isEditing: Bool = index == editingBoardIndex
let isAudible: Bool = shoeGaze.isBoardAudible(board)
let isSoloed: Bool = shoeGaze.activeBoardIndex == index
VStack(spacing: BoardBarView.cellInnerSpacing) {
Text(boardLabel(index: index, board: board))
.font(.system(size: BoardBarView.nameFontSize, weight: .semibold))
.foregroundStyle(Color.white)
.lineLimit(1)
.frame(maxWidth: .infinity)
.contentShape(Rectangle())
.onTapGesture { editingBoardIndex = index }
HStack(spacing: BoardBarView.cellSpacing) {
ledButton(board: board, isAudible: isAudible)
soloButton(board: board, isSoloed: isSoloed)
}
levelFader(board: board)
}
.padding(BoardBarView.cellPadding)
.frame(width: BoardBarView.cellWidth)
.background(
RoundedRectangle(cornerRadius: BoardBarView.cellCornerRadius)
.fill(Color(white: BoardBarView.cellBackgroundBrightness))
)
.overlay(
RoundedRectangle(cornerRadius: BoardBarView.cellCornerRadius)
.stroke(
isEditing ? Color.orange : Color.white.opacity(BoardBarView.idleBorderOpacity),
lineWidth: isEditing ? BoardBarView.editingBorderWidth : 1
)
)
.contextMenu {
Button("Edit This Board") { editingBoardIndex = index }
Button(isAudible ? "Silence" : "Enable") {
shoeGaze.setBoard(board, audible: !isAudible, crossfadeSeconds: clampedCrossfade)
}
Divider()
Button("Delete Board", role: .destructive) {
shoeGaze.removeBoard(board)
clampEditingIndex()
}
}
}
/// The audible LED — tap behaviour depends on the current ``PlayMode``.
private func ledButton(board: PedalBoard, isAudible: Bool) -> some View {
Button {
switch mode {
case .solo:
shoeGaze.soloBoard(board, crossfadeSeconds: clampedCrossfade)
case .blend:
shoeGaze.setBoard(board, audible: !isAudible, crossfadeSeconds: clampedCrossfade)
}
} label: {
ZStack {
if isAudible {
Circle()
.fill(Color.green.opacity(BoardBarView.ledGlowOpacity))
.frame(
width: BoardBarView.ledDiameter + BoardBarView.ledGlowRadius,
height: BoardBarView.ledDiameter + BoardBarView.ledGlowRadius
)
.blur(radius: BoardBarView.ledGlowRadius / 2)
}
Circle()
.fill(isAudible ? Color.green : Color(white: BoardBarView.ledDimBrightness))
.frame(width: BoardBarView.ledDiameter, height: BoardBarView.ledDiameter)
.overlay(
Circle().stroke(Color.white.opacity(BoardBarView.ledRimOpacity), lineWidth: 0.5)
)
}
.frame(width: BoardBarView.ledDiameter + BoardBarView.ledGlowRadius,
height: BoardBarView.ledDiameter + BoardBarView.ledGlowRadius)
}
.buttonStyle(.plain)
.help(mode == .solo ? "Solo this board" : (isAudible ? "Silence this board" : "Add this board to the mix"))
}
/// Exclusive solo button — lit when this board is the soloed one.
private func soloButton(board: PedalBoard, isSoloed: Bool) -> some View {
Button {
shoeGaze.soloBoard(board, crossfadeSeconds: clampedCrossfade)
} label: {
Text("S")
.font(.system(size: BoardBarView.nameFontSize, weight: .bold))
.foregroundStyle(isSoloed ? Color.black : Color.white)
.frame(width: BoardBarView.soloButtonSize, height: BoardBarView.soloButtonSize)
.background(
RoundedRectangle(cornerRadius: 4)
.fill(isSoloed ? Color.yellow : Color(white: BoardBarView.ledDimBrightness))
)
}
.buttonStyle(.plain)
.help("Solo this board (exclusive)")
}
/// Board master-gain fader. Hidden until the board's output master is connected.
@ViewBuilder
private func levelFader(board: PedalBoard) -> some View {
if let gainNode: UIParamNode = board.masterGainNode {
Slider(
value: Binding(
get: { gainNode.value },
set: { gainNode.update($0) }
),
in: 0.0 ... 1.0
)
.controlSize(.mini)
}
}
// MARK: - Add button
private var addButton: some View {
Button(action: onAddBoard) {
Image(systemName: "plus")
.font(.system(size: BoardBarView.nameFontSize, weight: .bold))
.foregroundStyle(Color.white)
.frame(width: BoardBarView.addButtonSize, height: BoardBarView.addButtonSize)
.background(
RoundedRectangle(cornerRadius: BoardBarView.cellCornerRadius)
.stroke(Color.white.opacity(BoardBarView.idleBorderOpacity), lineWidth: 1)
)
}
.buttonStyle(.plain)
.help("Add a board")
}
// MARK: - Helpers
/// Display label for a board, falling back to a 1-based position when unnamed.
private func boardLabel(index: Int, board: PedalBoard) -> String {
board.label.isEmpty ? "Board \(index + 1)" : board.label
}
/// `crossfadeSeconds` clamped to the supported range.
private var clampedCrossfade: Double {
min(max(crossfadeSeconds, 0.0), BoardBarView.maxCrossfadeSeconds)
}
/// Keeps the edit target valid after a delete.
private func clampEditingIndex() {
let count: Int = shoeGaze.boards.count
guard count > 0 else { editingBoardIndex = 0; return }
editingBoardIndex = min(editingBoardIndex, count - 1)
}
}
+43 -8
View File
@@ -325,6 +325,10 @@ public struct BoardFlowView: View {
}
}
.frame(minWidth: BoardFlowView.laneMinWidth, alignment: .leading)
// Make the whole lane frame hit-testable: an empty lane is mostly transparent, so without
// this the drop target has almost no area and releases land on nothing (the bug where
// dropping into an empty Stereo Unzip / Split / Parallel lane did nothing).
.contentShape(Rectangle())
.overlay { dropOutline(active: dropTarget == laneID) }
.dropDestination(for: String.self) { items, _ in
handleLaneDrop(items, lane: lane)
@@ -396,16 +400,19 @@ public struct BoardFlowView: View {
reorderMain(from: src, onto: ontoLinear)
return true
}
return false
// A branch pedal dragged back onto the main chain → cross-lane move.
return moveAcross(payload, toLane: .main)
}
private func handleLaneDrop(_ items: [String], lane: PedalLane) -> Bool {
dropTarget = nil
guard let payload: String = parse(items), let type: String = payload.afterPrefix("add:") else {
return false
guard let payload: String = parse(items) else { return false }
if let type: String = payload.afterPrefix("add:") {
append(type: type, lane: lane)
return true
}
append(type: type, lane: lane)
return true
// A pedal from the main chain or another lane dragged into this lane → cross-lane move.
return moveAcross(payload, toLane: lane)
}
private func handleBranchCardDrop(_ items: [String], lane: PedalLane, ontoIndex: Int) -> Bool {
@@ -422,7 +429,7 @@ public struct BoardFlowView: View {
append(type: type, lane: lane)
return true
}
// Reorder within the same lane only: "movebranch:<region>:<side>:<index>".
// Reorder within the same lane: "movebranch:<region>:<side>:<index>".
let parts: [Substring] = payload.split(separator: ":")
if parts.count == 4, parts[0] == "movebranch",
Int(parts[1]) == lane.regionIndex,
@@ -431,7 +438,35 @@ public struct BoardFlowView: View {
reorderBranch(from: src, onto: ontoIndex, lane: lane)
return true
}
return false
// A pedal from the main chain or a different lane dropped onto a card here → cross-lane move.
return moveAcross(payload, toLane: lane)
}
/// Moves a pedal addressed by a `movemain:`/`movebranch:` payload into `destination`,
/// preserving its parameters. Returns `false` if the payload isn't a recognised move.
private func moveAcross(_ payload: String, toLane destination: PedalLane) -> Bool {
guard let board: PedalBoard = board else { return false }
let sourceLane: PedalLane
let sourceIndex: Int
if let mainIndex: Int = payload.afterPrefix("movemain:").flatMap(Int.init) {
sourceLane = .main
sourceIndex = mainIndex
} else {
let parts: [Substring] = payload.split(separator: ":")
guard parts.count == 4, parts[0] == "movebranch",
let region: Int = Int(parts[1]), let index: Int = Int(parts[3]) else {
return false
}
sourceLane = (parts[2] == "L") ? .left(region: region) : .right(region: region)
sourceIndex = index
}
do {
_ = try shoeGaze.movePedal(from: sourceLane, at: sourceIndex, to: destination, in: board)
return true
} catch {
print("[BoardFlowView] cross-lane move failed: \(error)")
return false
}
}
// MARK: - Edit actions
@@ -443,7 +478,7 @@ public struct BoardFlowView: View {
private func append(type: String, lane: PedalLane) {
guard let board: PedalBoard = board else { return }
do { _ = try shoeGaze.appendPedal(type: type, to: board, lane: lane) }
do { _ = try shoeGaze.appendPedal(PedalType(type), to: board, lane: lane) }
catch { print("[BoardFlowView] appendPedal failed: \(error)") }
}
@@ -0,0 +1,243 @@
// BoardsSheetView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdUI
import LyrebirdShoeGaze
/// A full board manager presented as a sheet — the richer companion to the inline
/// ``BoardBarView``.
///
/// Each board is a `List` row with an audible toggle, a Solo button, a master-gain fader, an
/// inline rename field, and an "Edit" action that selects it as the builder's edit target and
/// dismisses. Rows reorder by drag (`.onMove`) and delete by swipe (`.onDelete`). A header
/// pairs the **Solo / Blend** mode switch with the crossfade slider, mirroring the board bar.
///
/// Primarily used on iOS/iPadOS (presented with `.presentationDetents`) where the inline bar
/// has no room for rename / reorder, but the view is platform-neutral.
public struct BoardsSheetView: View {
// MARK: - Play mode
private enum PlayMode: Hashable {
case solo
case blend
}
// MARK: - Layout constants
private static let rowSpacing: CGFloat = 12
private static let faderWidth: CGFloat = 120
private static let soloButtonSize: CGFloat = 28
private static let ledDiameter: CGFloat = 14
private static let ledDimBrightness: Double = 0.16
private static let ledRimOpacity: Double = 0.30
private static let maxCrossfadeSeconds: Double = 10.0
private static let crossfadeStep: Double = 0.1
private static let headerSpacing: CGFloat = 10
// MARK: - Properties
private let shoeGaze: ShoeGaze
@Binding private var editingBoardIndex: Int
@Binding private var crossfadeSeconds: Double
private let onAddBoard: () -> Void
@Environment(\.dismiss) private var dismiss
@State private var mode: PlayMode = .solo
// MARK: - Init
/// Creates a board-manager sheet.
///
/// - Parameters:
/// - shoeGaze: The manager whose `boards` are edited.
/// - editingBoardIndex: The builder's edit target; a row's "Edit" action sets this.
/// - crossfadeSeconds: Crossfade duration applied to switches / toggles.
/// - onAddBoard: Called when the **Add Board** button is tapped.
public init(
shoeGaze: ShoeGaze,
editingBoardIndex: Binding<Int>,
crossfadeSeconds: Binding<Double>,
onAddBoard: @escaping () -> Void
) {
self.shoeGaze = shoeGaze
self._editingBoardIndex = editingBoardIndex
self._crossfadeSeconds = crossfadeSeconds
self.onAddBoard = onAddBoard
}
// MARK: - Body
public var body: some View {
NavigationStack {
VStack(spacing: BoardsSheetView.headerSpacing) {
header
List {
ForEach(Array(shoeGaze.boards.enumerated()), id: \.offset) { pair in
boardRow(index: pair.offset, board: pair.element)
}
.onMove(perform: moveBoards)
.onDelete(perform: deleteBoards)
}
}
.padding(.top, BoardsSheetView.headerSpacing)
.navigationTitle("Boards")
.toolbar {
ToolbarItem(placement: .confirmationAction) {
Button("Done") { dismiss() }
}
ToolbarItem(placement: .primaryAction) {
Button {
onAddBoard()
} label: {
Label("Add Board", systemImage: "plus")
}
}
}
}
}
// MARK: - Header
private var header: some View {
HStack(spacing: BoardsSheetView.headerSpacing) {
Picker("Mode", selection: $mode) {
Text("Solo").tag(PlayMode.solo)
Text("Blend").tag(PlayMode.blend)
}
.pickerStyle(.segmented)
.frame(maxWidth: 180)
Button("All") {
shoeGaze.selectAllBoards(crossfadeSeconds: clampedCrossfade)
}
.buttonStyle(.bordered)
Spacer()
Text("XFade")
Slider(
value: $crossfadeSeconds,
in: 0 ... BoardsSheetView.maxCrossfadeSeconds,
step: BoardsSheetView.crossfadeStep
)
.frame(width: BoardsSheetView.faderWidth)
Text(String(format: "%.1fs", clampedCrossfade))
.monospacedDigit()
}
.padding(.horizontal)
}
// MARK: - Board row
@ViewBuilder
private func boardRow(index: Int, board: PedalBoard) -> some View {
let isAudible: Bool = shoeGaze.isBoardAudible(board)
let isSoloed: Bool = shoeGaze.activeBoardIndex == index
HStack(spacing: BoardsSheetView.rowSpacing) {
ledButton(board: board, isAudible: isAudible)
soloButton(board: board, isSoloed: isSoloed)
TextField(
"Board \(index + 1)",
text: Binding(
get: { board.label },
set: { board.label = $0 }
)
)
.textFieldStyle(.roundedBorder)
if let gainNode: UIParamNode = board.masterGainNode {
Slider(
value: Binding(
get: { gainNode.value },
set: { gainNode.update($0) }
),
in: 0.0 ... 1.0
)
.frame(width: BoardsSheetView.faderWidth)
}
Button("Edit") {
editingBoardIndex = index
dismiss()
}
.buttonStyle(.borderless)
}
.padding(.vertical, 4)
}
private func ledButton(board: PedalBoard, isAudible: Bool) -> some View {
Button {
switch mode {
case .solo:
shoeGaze.soloBoard(board, crossfadeSeconds: clampedCrossfade)
case .blend:
shoeGaze.setBoard(board, audible: !isAudible, crossfadeSeconds: clampedCrossfade)
}
} label: {
Circle()
.fill(isAudible ? Color.green : Color(white: BoardsSheetView.ledDimBrightness))
.frame(width: BoardsSheetView.ledDiameter, height: BoardsSheetView.ledDiameter)
.overlay(
Circle().stroke(Color.white.opacity(BoardsSheetView.ledRimOpacity), lineWidth: 0.5)
)
}
.buttonStyle(.plain)
}
private func soloButton(board: PedalBoard, isSoloed: Bool) -> some View {
Button {
shoeGaze.soloBoard(board, crossfadeSeconds: clampedCrossfade)
} label: {
Text("S")
.font(.system(size: 13, weight: .bold))
.foregroundStyle(isSoloed ? Color.black : Color.primary)
.frame(width: BoardsSheetView.soloButtonSize, height: BoardsSheetView.soloButtonSize)
.background(
RoundedRectangle(cornerRadius: 5)
.fill(isSoloed ? Color.yellow : Color.secondary.opacity(0.2))
)
}
.buttonStyle(.plain)
}
// MARK: - Mutations
/// Reorders boards, translating SwiftUI's `onMove` offsets to `ShoeGaze.moveBoard`.
private func moveBoards(from source: IndexSet, to destination: Int) {
// List drag delivers a single source row; ignore any multi-selection move so a
// dropped row can never desync `shoeGaze.boards` from the displayed order.
guard source.count == 1, let sourceIndex: Int = source.first else { return }
let board: PedalBoard = shoeGaze.boards[sourceIndex]
// SwiftUI's destination is the insertion point in the pre-move list; moveBoard
// removes first, so shift down by one when moving forward.
let target: Int = destination > sourceIndex ? destination - 1 : destination
shoeGaze.moveBoard(board, to: target)
clampEditingIndex()
}
private func deleteBoards(_ offsets: IndexSet) {
for index: Int in offsets.sorted(by: >) where index < shoeGaze.boards.count {
shoeGaze.removeBoard(shoeGaze.boards[index])
}
clampEditingIndex()
}
// MARK: - Helpers
private var clampedCrossfade: Double {
min(max(crossfadeSeconds, 0.0), BoardsSheetView.maxCrossfadeSeconds)
}
private func clampEditingIndex() {
let count: Int = shoeGaze.boards.count
guard count > 0 else { editingBoardIndex = 0; return }
editingBoardIndex = min(editingBoardIndex, count - 1)
}
}
@@ -113,6 +113,16 @@ public struct EngineConfigView: View {
} message: {
Text(alertText)
}
// Resync the pending fields whenever the engine is rebuilt out from under this view (e.g.
// the iOS live-input rebuild swaps in a new engine with a different input-channel count).
// Keyed on the engine's object identity so it re-runs on every swap; the @State initial
// values are seeded only once, so without this the stepper would keep showing the old
// engine's channel counts even though audio reads the new one.
.task(id: ObjectIdentifier(shoeGaze.engine)) {
pendingSampleRate = shoeGaze.engine.sampleRate
pendingInputs = shoeGaze.engine.numInputChannels
pendingOutputs = shoeGaze.engine.numOutputChannels
}
}
private func label(_ text: String) -> some View {
@@ -0,0 +1,129 @@
// PedalInfoView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdUI
import LyrebirdShoeGaze
/// An info panel for a single pedal: its description and the effect controls with their ranges.
///
/// Shows `pedal.summary` and lists the **effect** controls only — `effectKnobs` + `effectSliders`
/// + `effectSwitches`, each with its value range or switch positions. The common Mix / Level /
/// bypass controls are intentionally omitted (they behave the same on every pedal). Presented
/// from the pedal's ⓘ button.
public struct PedalInfoView: View {
// MARK: - Layout constants
private static let sectionSpacing: CGFloat = 16
private static let rowSpacing: CGFloat = 8
private static let labelColumnWidth: CGFloat = 110
private static let summaryOpacity: Double = 0.85
private static let valueOpacity: Double = 0.7
private static let headerOpacity: Double = 0.5
// MARK: - Properties
private let pedal: Pedal
@Environment(\.dismiss) private var dismiss
// MARK: - Init
/// Creates an info panel for `pedal`.
public init(pedal: Pedal) {
self.pedal = pedal
}
// MARK: - Body
public var body: some View {
NavigationStack {
ScrollView {
VStack(alignment: .leading, spacing: PedalInfoView.sectionSpacing) {
if !pedal.summary.isEmpty {
Text(pedal.summary)
.font(.body)
.foregroundStyle(.primary.opacity(PedalInfoView.summaryOpacity))
.fixedSize(horizontal: false, vertical: true)
}
if !controlRows.isEmpty {
VStack(alignment: .leading, spacing: PedalInfoView.rowSpacing) {
Text("CONTROLS")
.font(.caption2.weight(.semibold))
.foregroundStyle(.secondary.opacity(PedalInfoView.headerOpacity))
ForEach(Array(controlRows.enumerated()), id: \.offset) { pair in
controlRow(pair.element)
}
}
}
}
.padding()
.frame(maxWidth: .infinity, alignment: .leading)
}
.navigationTitle(pedal.displayName)
#if !os(macOS)
.navigationBarTitleDisplayMode(.inline)
#endif
.toolbar {
ToolbarItem(placement: .confirmationAction) {
Button("Done") { dismiss() }
}
}
}
}
// MARK: - Control rows
private func controlRow(_ row: ControlRow) -> some View {
HStack(alignment: .firstTextBaseline) {
Text(row.label)
.font(.callout.weight(.medium))
.frame(width: PedalInfoView.labelColumnWidth, alignment: .leading)
Text(row.value)
.font(.callout.monospacedDigit())
.foregroundStyle(.secondary.opacity(PedalInfoView.valueOpacity))
Spacer(minLength: 0)
}
}
/// One displayed control: a label and its range / options string.
private struct ControlRow {
let label: String
let value: String
}
/// Effect controls only (knobs + sliders + switches), in display order.
private var controlRows: [ControlRow] {
var rows: [ControlRow] = []
for knob: PedalKnob in pedal.effectKnobs {
rows.append(ControlRow(label: knob.label, value: PedalInfoView.rangeText(knob.range)))
}
for slider: PedalSlider in pedal.effectSliders {
rows.append(ControlRow(label: slider.label, value: PedalInfoView.rangeText(slider.range)))
}
for pedalSwitch: PedalSwitch in pedal.effectSwitches {
let options: String = pedalSwitch.options.map { $0.title }.joined(separator: " / ")
rows.append(ControlRow(label: pedalSwitch.label, value: options))
}
return rows
}
// MARK: - Formatting
/// Formats a value range as `"lo – hi"`, using integers when both bounds are whole.
private static func rangeText(_ range: ClosedRange<Double>) -> String {
"\(number(range.lowerBound)) – \(number(range.upperBound))"
}
private static func number(_ value: Double) -> String {
if value == value.rounded() {
return String(format: "%.0f", value)
}
return String(format: "%.3g", value)
}
}
@@ -11,7 +11,7 @@ import LyrebirdShoeGaze
/// options, sized to sit in a narrow left sidebar.
///
/// The pedal rows are tappable: selecting one invokes `onAdd(type)` with the pedal's
/// `displayName`, which the host wires to `ShoeGaze.appendPedal(type:to:)`. The routing cards
/// `displayName`, which the host wraps in a `PedalType` for `ShoeGaze.appendPedal(_:to:)`. The routing cards
/// (Parallel split, Stereo split, Chain router, Merge to mono) are informational only — they
/// describe the topologies the engine supports, which are built programmatically rather than via
/// linear add (see ``BoardBuilderView`` for the read-only display of existing branches).
@@ -20,7 +20,7 @@ import LyrebirdShoeGaze
///
/// ```swift
/// PedalPaletteView { type in
/// try? shoeGaze.appendPedal(type: type, to: board)
/// try? shoeGaze.appendPedal(PedalType(type), to: board)
/// }
/// ```
public struct PedalPaletteView: View {
@@ -41,13 +41,19 @@ public struct PedalPaletteView: View {
private static let routingCaptionOpacity: Double = 0.5
private static let routingCaptionFontSize: CGFloat = 10
private static let addGlyphOpacity: Double = 0.4
/// Vertical gap between a pedal row's name and its description subtitle.
private static let rowSubtitleSpacing: CGFloat = 2
/// Opacity of the pedal-row description subtitle.
private static let summaryOpacity: Double = 0.55
/// Fixed card width when laid out horizontally (the vertical layout stretches to fill instead).
private static let horizontalCardWidth: CGFloat = 150
/// Preferred display order for the built-in pedals. Any registered pedal not listed here is
/// appended afterwards (sorted) so the palette never silently drops a newly added pedal.
private static let preferredOrder: [String] = [
"Overdrive", "Compressor", "Limiter", "Noise Gate", "Fuzz",
"Graphic EQ", "Tremolo", "Phaser", "Modulation",
"Auto-Wah", "Mu-Tron", "Bass Octaver", "Octave Splitter",
"Overdrive", "Compressor", "Sustainer", "Limiter", "Noise Gate", "Fuzz",
"Graphic EQ", "Tremolo", "Phaser", "Modulation", "Chorus",
"Auto-Wah", "Mutant", "Ring Modulator", "Diffuser", "Bass Octaver", "Octave Splitter",
"Delay", "Feedback Delay", "Multi-Tap Delay", "Ping-Pong", "Reverb",
]
@@ -70,19 +76,25 @@ public struct PedalPaletteView: View {
private let onAdd: (String) -> Void
private let onRouting: (RoutingAction) -> Void
private let axis: Axis
// MARK: - Init
/// Creates a pedal palette.
///
/// - Parameters:
/// - axis: `.vertical` (default) lays the catalog out as a full-width column for a sidebar;
/// `.horizontal` lays it out as a fixed-width-card row for a horizontal scroller. The host
/// wraps the view in a `ScrollView` of the matching axis.
/// - onAdd: Invoked with a pedal's `displayName` when its row is tapped (append to main chain).
/// Rows are also `.draggable` carrying `"add:<displayName>"` for drop-onto-lane targeting.
/// - onRouting: Invoked when a routing row is tapped. Defaults to a no-op.
public init(
axis: Axis = .vertical,
onAdd: @escaping (String) -> Void,
onRouting: @escaping (RoutingAction) -> Void = { _ in }
) {
self.axis = axis
self.onAdd = onAdd
self.onRouting = onRouting
}
@@ -100,6 +112,14 @@ public struct PedalPaletteView: View {
// MARK: - Body
public var body: some View {
switch axis {
case .horizontal: horizontalBody
default: verticalBody
}
}
/// Full-width column for a left sidebar.
private var verticalBody: some View {
VStack(alignment: .leading, spacing: PedalPaletteView.sectionSpacing) {
VStack(alignment: .leading, spacing: PedalPaletteView.rowSpacing) {
sectionTitle("PEDALS")
@@ -117,6 +137,22 @@ public struct PedalPaletteView: View {
}
}
/// Fixed-width-card row for a horizontal scroller: leading PEDALS group, a divider, then the
/// ROUTING group.
private var horizontalBody: some View {
HStack(alignment: .top, spacing: PedalPaletteView.rowSpacing) {
sectionTitle("PEDALS")
ForEach(orderedPedalNames, id: \.self) { name in
pedalRow(name)
}
Divider().overlay(Color.white.opacity(PedalPaletteView.cardBorderOpacity))
sectionTitle("ROUTING")
ForEach(PedalPaletteView.routingOptions, id: \.title) { option in
routingCard(title: option.title, caption: option.caption, action: option.action)
}
}
}
// MARK: - Subviews
private func sectionTitle(_ text: String) -> some View {
@@ -128,22 +164,33 @@ public struct PedalPaletteView: View {
/// A full-width pedal row: tap appends to the main chain; drag carries `"add:<name>"` so it can
/// be dropped onto a stereo/parallel lane.
private func pedalRow(_ name: String) -> some View {
Button {
let summary: String = PedalRegistry.summary(for: name)
return Button {
onAdd(name)
} label: {
HStack(spacing: 4) {
Text(name)
.font(.callout)
.foregroundStyle(Color.white)
.lineLimit(1)
Spacer(minLength: 0)
Image(systemName: "plus")
.font(.caption2)
.foregroundStyle(Color.white.opacity(PedalPaletteView.addGlyphOpacity))
VStack(alignment: .leading, spacing: PedalPaletteView.rowSubtitleSpacing) {
HStack(spacing: 4) {
Text(name)
.font(.callout)
.foregroundStyle(Color.white)
.lineLimit(1)
Spacer(minLength: 0)
Image(systemName: "plus")
.font(.caption2)
.foregroundStyle(Color.white.opacity(PedalPaletteView.addGlyphOpacity))
}
if !summary.isEmpty {
Text(summary)
.font(.caption2)
.foregroundStyle(Color.white.opacity(PedalPaletteView.summaryOpacity))
.lineLimit(2)
.multilineTextAlignment(.leading)
.fixedSize(horizontal: false, vertical: true)
}
}
.padding(.horizontal, PedalPaletteView.cardPaddingH)
.padding(.vertical, PedalPaletteView.cardPaddingV)
.frame(maxWidth: .infinity, alignment: .leading)
.modifier(CardFrame(axis: axis, width: PedalPaletteView.horizontalCardWidth))
.background(cardBackground(brightness: PedalPaletteView.pedalCardBrightness))
}
.buttonStyle(.plain)
@@ -165,12 +212,27 @@ public struct PedalPaletteView: View {
}
.padding(.horizontal, PedalPaletteView.cardPaddingH)
.padding(.vertical, PedalPaletteView.cardPaddingV)
.frame(maxWidth: .infinity, alignment: .leading)
.modifier(CardFrame(axis: axis, width: PedalPaletteView.horizontalCardWidth))
.background(cardBackground(brightness: PedalPaletteView.routingCardBrightness))
}
.buttonStyle(.plain)
}
/// Stretches a card to fill width in a vertical column, or pins it to a fixed width in a
/// horizontal row.
private struct CardFrame: ViewModifier {
let axis: Axis
let width: CGFloat
func body(content: Content) -> some View {
switch axis {
case .horizontal:
content.frame(width: width, alignment: .leading)
default:
content.frame(maxWidth: .infinity, alignment: .leading)
}
}
}
private func cardBackground(brightness: Double) -> some View {
RoundedRectangle(cornerRadius: PedalPaletteView.cardCornerRadius)
.fill(Color(white: brightness))
+49 -8
View File
@@ -24,13 +24,17 @@ private func enclosureColor(for displayName: String) -> Color {
case "Tremolo": return Color(red: 0.20, green: 0.38, blue: 0.72) // cobalt blue
case "Phaser": return Color(red: 0.60, green: 0.22, blue: 0.62) // violet
case "Compressor": return Color(red: 0.18, green: 0.42, blue: 0.32) // forest green
case "Mu-Tron": return Color(red: 0.70, green: 0.12, blue: 0.48) // magenta / plum
case "Mutant": return Color(red: 0.70, green: 0.12, blue: 0.48) // magenta / plum
case "Auto-Wah": return Color(red: 0.80, green: 0.62, blue: 0.10) // gold
case "Feedback Delay": return Color(red: 0.48, green: 0.30, blue: 0.14) // tape sepia
case "Multi-Tap Delay": return Color(red: 0.08, green: 0.48, blue: 0.68) // cyan
case "Limiter": return Color(red: 0.62, green: 0.16, blue: 0.20) // brick red
case "Noise Gate": return Color(red: 0.24, green: 0.26, blue: 0.30) // gunmetal
case "Graphic EQ": return Color(red: 0.14, green: 0.40, blue: 0.50) // deep teal
case "Chorus": return Color(red: 0.16, green: 0.50, blue: 0.64) // aqua
case "Sustainer": return Color(red: 0.22, green: 0.46, blue: 0.30) // pine green
case "Ring Modulator": return Color(red: 0.64, green: 0.30, blue: 0.10) // burnt amber
case "Diffuser": return Color(red: 0.34, green: 0.30, blue: 0.62) // periwinkle
default: return Color(red: 0.36, green: 0.36, blue: 0.38) // steel gray
}
}
@@ -187,6 +191,9 @@ public struct PedalView: View {
private static let screwInset: CGFloat = 6
private static let knobColumnCount: Int = 3
private static let knobSpacing: CGFloat = 10
/// Horizontal gap between knobs within a row. Wider than `knobSpacing` so centred
/// rows keep a comfortable, touch-friendly gap between adjacent knobs.
private static let knobRowItemSpacing: CGFloat = 24
/// Horizontal gap between adjacent vertical faders in the slider bank.
private static let sliderBankSpacing: CGFloat = 4
/// Approximate per-fader footprint (matches `VerticalParameterSlider.controlWidth`),
@@ -209,6 +216,11 @@ public struct PedalView: View {
private static let screwHalfSize: CGFloat = 4
private static let namePlateBackgroundOpacity: Double = 0.35
private static let fontSizeNamePlate: CGFloat = 13
/// Opacity of the ⓘ info button.
private static let infoButtonOpacity: Double = 0.7
/// Insets placing the ⓘ info button just under the top-left corner screw.
private static let infoButtonLeading: CGFloat = 5
private static let infoButtonTop: CGFloat = 20
private static let outerBorderLineWidth: CGFloat = 1.5
private static let innerHighlightLineWidth: CGFloat = 1
private static let innerHighlightPadding: CGFloat = 1
@@ -218,6 +230,9 @@ public struct PedalView: View {
private let pedal: Pedal
/// Presentation flag for the pedal info panel (description + control ranges).
@State private var showInfo: Bool = false
// MARK: - Init
/// Creates a stompbox pedal view for the given pedal.
@@ -271,6 +286,11 @@ public struct PedalView: View {
// Corner screws — overlaid at the four corners
screwCorners
// Info button, tucked just under the top-left corner screw.
infoButton
.padding(.leading, PedalView.infoButtonLeading)
.padding(.top, PedalView.infoButtonTop)
}
.frame(width: enclosureWidth(for: sliders))
.shadow(
@@ -279,6 +299,10 @@ public struct PedalView: View {
x: PedalView.shadowXOffset,
y: PedalView.shadowYOffset
)
.sheet(isPresented: $showInfo) {
PedalInfoView(pedal: pedal)
.presentationDetents([.medium, .large])
}
}
// MARK: - Subviews
@@ -294,6 +318,19 @@ public struct PedalView: View {
.clipShape(RoundedRectangle(cornerRadius: PedalView.namePlateCornerRadius))
}
/// Info button tucked just under the top-left corner screw.
private var infoButton: some View {
Button {
showInfo = true
} label: {
Image(systemName: "info.circle")
.font(.system(size: PedalView.fontSizeNamePlate))
.foregroundStyle(Color.white.opacity(PedalView.infoButtonOpacity))
}
.buttonStyle(.plain)
.help("About this pedal")
}
/// Grid of the effect knobs, in rows of up to `knobColumnCount`.
///
/// The trailing `Mix` and `Level` knobs (the last two entries of `pedal.knobs`) are
@@ -313,18 +350,22 @@ public struct PedalView: View {
return VStack(spacing: PedalView.knobSpacing) {
ForEach(Array(rows.enumerated()), id: \.offset) { rowPair in
let row: [PedalKnob] = rowPair.element
HStack(spacing: PedalView.knobSpacing) {
// Centre each row: a short row (one or two knobs) sits centred in the
// enclosure rather than left-aligned. Symmetric spacers also centre a full
// three-knob row, so every row stays horizontally centred.
// A full three-knob row keeps the tight spacing so it fits the enclosure;
// shorter centred rows use a wider, touch-friendly gap.
let rowItemSpacing: CGFloat = row.count >= PedalView.knobColumnCount
? PedalView.knobSpacing
: PedalView.knobRowItemSpacing
HStack(spacing: rowItemSpacing) {
Spacer(minLength: 0)
ForEach(Array(row.enumerated()), id: \.offset) { knobPair in
let knob: PedalKnob = knobPair.element
ParameterKnob(knob.label, node: knob.node, range: knob.range)
.foregroundStyle(Color.white)
}
// Pad short rows so knobs stay aligned in their columns.
if row.count < PedalView.knobColumnCount {
ForEach(0 ..< (PedalView.knobColumnCount - row.count), id: \.self) { _ in
Spacer()
}
}
Spacer(minLength: 0)
}
}
}
@@ -0,0 +1,54 @@
// RigLibraryBootstrap.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdShoeGaze
/// Setup of the rig library for an app shell, split so nothing blocks the launch path.
///
/// ``makeStore()`` returns an auto-resolving store instantly (safe to construct in a synchronous
/// initializer and hand to the UI). ``start(_:seedFrom:seedName:)`` then does the blocking work —
/// resolving the iCloud-or-local location and the initial load — off the main thread, and seeds the
/// library from the current working rig **only after** the real (possibly iCloud) contents are
/// known, so a first launch can't create a duplicate "Default" rig on every synced device.
@MainActor
public enum RigLibraryBootstrap {
/// Creates an auto-resolving store. Construct this synchronously at launch; call
/// ``start(_:seedFrom:seedName:)`` afterwards (e.g. from a SwiftUI `.task` or a `Task`).
public static func makeStore() -> RigLibraryStore {
RigLibraryStore()
}
/// Resolves + loads `store` off the main thread, then seeds it from `shoeGaze` if it is still
/// empty after loading (first run). Idempotent enough to call once at launch.
///
/// - Parameters:
/// - store: The store from ``makeStore()``.
/// - shoeGaze: The session whose current rig seeds the library when it is first empty.
/// - seedName: Name for the seeded first rig. Defaults to `"Default"`.
public static func start(
_ store: RigLibraryStore,
seedFrom shoeGaze: ShoeGaze,
seedName: String = "Default"
) async {
await store.start()
// Seed only after the (possibly iCloud) library has loaded: an empty library here means a
// genuine first run, not a not-yet-synced one.
guard store.entries.isEmpty, !shoeGaze.boards.isEmpty else { return }
let entry: RigEntry = shoeGaze.captureEntry(name: seedName)
do {
try store.save(entry)
UserDefaults.standard.set(
entry.id.uuidString,
forKey: ShoeGazeBuilderView.currentRigDefaultsKey
)
} catch {
print("[RigLibraryBootstrap] seeding library failed: \(error)")
}
}
}
@@ -0,0 +1,19 @@
// RigLibraryCommands.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Notifications the macOS app shell posts from its menu bar so the in-window
/// ``ShoeGazeBuilderView`` — which owns the current-rig state — performs the action with the
/// correct UI (naming prompts, highlight updates). iOS has no menu bar and simply never posts them.
public extension Notification.Name {
/// Save the current rig to the library (overwrites the loaded entry, or prompts for a name).
static let shoeGazeSaveRig: Notification.Name = Notification.Name("net.realizedsound.shoegaze.saveRig")
/// Create a new, named, empty rig and make it current.
static let shoeGazeNewRig: Notification.Name = Notification.Name("net.realizedsound.shoegaze.newRig")
}
@@ -0,0 +1,167 @@
// RigLibrarySidebarView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdShoeGaze
/// The rig library: a persistent left-hand listing of every saved rig, with controls to start a
/// new rig, save / save-as, duplicate, rename, delete, erase all, and import / export an archive.
///
/// Selecting a rig replaces the current working session (the host stops the engine, rebuilds the
/// graph, and restarts). This view is purely presentational — every action is delegated to the
/// host (`ShoeGazeBuilderView`) via closures so engine lifecycle and naming prompts stay in one
/// place.
struct RigLibrarySidebarView: View {
// MARK: - Layout constants
private static let width: CGFloat = 200
private static let rowSpacing: CGFloat = 4
private static let rowPadding: CGFloat = 8
private static let rowCorner: CGFloat = 6
private static let selectedOpacity: Double = 0.22
private static let subtitleOpacity: Double = 0.5
private static let headerOpacity: Double = 0.65
private static let emptyOpacity: Double = 0.4
// MARK: - Inputs
let store: RigLibraryStore
/// The library entry currently loaded into the session, or `nil` for an unsaved/new rig.
@Binding var currentRigID: UUID?
let onSelect: (RigEntry) -> Void
let onNew: () -> Void
let onSave: () -> Void
let onSaveAs: () -> Void
let onDuplicate: (RigEntry) -> Void
let onRename: (RigEntry) -> Void
let onDelete: (RigEntry) -> Void
let onEraseAll: () -> Void
let onImportArchive: () -> Void
let onExportArchive: () -> Void
private static let timestampFormat: Date.FormatStyle =
Date.FormatStyle(date: .abbreviated, time: .shortened)
// MARK: - Body
var body: some View {
VStack(alignment: .leading, spacing: RigLibrarySidebarView.rowSpacing) {
header
Divider().overlay(Color.white.opacity(0.12))
rigList
Divider().overlay(Color.white.opacity(0.12))
actionBar
}
.frame(width: RigLibrarySidebarView.width)
}
// MARK: - Header
private var header: some View {
HStack(spacing: 6) {
Text("Rigs")
.font(.headline)
.foregroundStyle(Color.white)
Spacer()
// Cloud icon when the library is iCloud-backed; a slash when local-only.
Image(systemName: store.isICloud ? "icloud" : "icloud.slash")
.font(.caption)
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.headerOpacity))
.help(store.isICloud
? "Synced with iCloud across your devices"
: "iCloud unavailable — rigs are stored on this device only")
}
}
// MARK: - List
private var rigList: some View {
ScrollView(.vertical, showsIndicators: true) {
LazyVStack(alignment: .leading, spacing: RigLibrarySidebarView.rowSpacing) {
if !store.isLoaded {
HStack(spacing: 6) {
ProgressView().controlSize(.small)
Text("Loading…")
.font(.caption)
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity))
}
.padding(.vertical, RigLibrarySidebarView.rowPadding)
} else if store.entries.isEmpty {
Text("No saved rigs yet.\nTap New or Save to add one.")
.font(.caption)
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity))
.padding(.vertical, RigLibrarySidebarView.rowPadding)
}
ForEach(store.entries) { entry in
rigRow(entry)
}
}
}
.frame(maxHeight: .infinity)
}
private func rigRow(_ entry: RigEntry) -> some View {
let isSelected: Bool = entry.id == currentRigID
return Button {
onSelect(entry)
} label: {
VStack(alignment: .leading, spacing: 2) {
Text(entry.name)
.font(.subheadline)
.foregroundStyle(Color.white)
.lineLimit(1)
Text(entry.savedAt.formatted(RigLibrarySidebarView.timestampFormat))
.font(.caption2)
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.subtitleOpacity))
.lineLimit(1)
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(RigLibrarySidebarView.rowPadding)
.background(
RoundedRectangle(cornerRadius: RigLibrarySidebarView.rowCorner)
.fill(Color.orange.opacity(isSelected ? RigLibrarySidebarView.selectedOpacity : 0))
)
}
.buttonStyle(.plain)
.contextMenu {
Button("Rename…") { onRename(entry) }
Button("Duplicate…") { onDuplicate(entry) }
Divider()
Button("Delete", role: .destructive) { onDelete(entry) }
}
}
// MARK: - Action bar
private var actionBar: some View {
HStack(spacing: 6) {
Button { onNew() } label: { Image(systemName: "plus") }
.help("New rig")
Button { onSave() } label: { Image(systemName: "square.and.arrow.down") }
.help("Save the current rig")
Button { onSaveAs() } label: { Image(systemName: "doc.on.doc") }
.help("Save the current rig as a new entry")
Spacer()
Menu {
Button("Import Archive…") { onImportArchive() }
Button("Export Archive…") { onExportArchive() }
Divider()
Button("Erase All Rigs…", role: .destructive) { onEraseAll() }
} label: {
Image(systemName: "ellipsis.circle")
}
.menuStyle(.borderlessButton)
.fixedSize()
.help("Archive and library options")
}
.buttonStyle(.bordered)
.tint(.orange)
.padding(.top, 2)
}
}
@@ -0,0 +1,71 @@
// RigNamePrompt.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
/// A request to prompt the user for a rig name (New, Save As, Rename, Duplicate).
///
/// Presented via the ``SwiftUI/View/rigNamePrompt(_:)`` modifier. Setting a non-`nil` value shows a
/// text-entry alert seeded with `initialText`; committing a non-empty, trimmed name invokes
/// `onCommit`. Cancelling dismisses without calling `onCommit`.
struct RigNamePrompt: Identifiable {
let id: UUID = UUID()
/// Alert title, e.g. `"Save Rig As"`.
let title: String
/// Text the field is pre-filled with (e.g. the existing name for a rename).
let initialText: String
/// Confirm-button label, e.g. `"Save"` or `"Rename"`.
let confirmLabel: String
/// Invoked with the trimmed, non-empty name when the user confirms.
let onCommit: (String) -> Void
}
private struct RigNamePromptModifier: ViewModifier {
@Binding var prompt: RigNamePrompt?
@State private var text: String = ""
func body(content: Content) -> some View {
content
.onChange(of: prompt?.id) {
// Seed the field whenever a new prompt is presented.
text = prompt?.initialText ?? ""
}
.alert(
prompt?.title ?? "",
isPresented: isPresented,
presenting: prompt
) { active in
TextField("Name", text: $text)
Button(active.confirmLabel) {
let trimmed: String = text.trimmingCharacters(in: .whitespacesAndNewlines)
if !trimmed.isEmpty { active.onCommit(trimmed) }
}
Button("Cancel", role: .cancel) { }
}
}
private var isPresented: Binding<Bool> {
Binding(
get: { prompt != nil },
set: { presented in if !presented { prompt = nil } }
)
}
}
extension View {
/// Presents a rig-name entry alert driven by `prompt`. Set the binding to a ``RigNamePrompt``
/// to show it; it clears itself on dismiss.
func rigNamePrompt(_ prompt: Binding<RigNamePrompt?>) -> some View {
modifier(RigNamePromptModifier(prompt: prompt))
}
}
@@ -43,34 +43,90 @@ public struct ShoeGazeBuilderView: View {
private static let minWidth: CGFloat = 720
private static let minHeight: CGFloat = 460
private static let sidebarWidth: CGFloat = 168
/// Width of the scope/CPU block in the bottom strip — matches `BoardBarView`'s Solo/Blend/All
/// control column so the scope aligns under it.
private static let scopeWidth: CGFloat = 188
private static let columnSpacing: CGFloat = 14
private static let backgroundRed: Double = 0.08
private static let backgroundGreen: Double = 0.07
private static let backgroundBlue: Double = 0.06
private static let testLoopTag: Int = -1
private static let defaultRigFileName: String = "ShoeGazeRig"
/// UserDefaults key persisting the last input selection (`-1` = test loop, `>= 0` = channel).
private static let inputSelectionDefaultsKey: String = "ShoeGaze.inputSelection"
/// UserDefaults key persisting the loaded rig's id (its `uuidString`) so the same rig can be
/// highlighted on the next launch. Read by the app shells to seed `initialRigID`.
public static let currentRigDefaultsKey: String = "ShoeGaze.currentRigID"
/// Maximum crossfade duration honoured by board-switch keyboard shortcuts.
private static let maxCrossfadeSeconds: Double = 10.0
/// Highest board reachable via a ⌘-number switch shortcut.
private static let maxBoardShortcuts: Int = 9
/// Default filename offered when exporting the whole library as an archive.
private static let defaultArchiveFileName: String = "ShoeGaze Library"
/// Extra width reserved for the rig-library sidebar on top of the builder's minimum width.
private static let librarySidebarReserve: CGFloat = 216
private static let recordDotSize: CGFloat = 9
private static let folderLabelOpacity: Double = 0.55
// MARK: - Properties
private let shoeGaze: ShoeGaze
private let library: RigLibraryStore
private let hardwareSampleRate: () -> Double?
/// Host hook to enable live input when the current engine has no input channel (iOS).
/// The host requests microphone access and rebuilds the engine with one input channel,
/// preserving the rig, then swaps in a new `ShoeGaze`. `nil` on platforms (macOS) whose
/// engine already exposes an input channel, where live input is selected directly.
private let onEnableLiveInput: (() -> Void)?
/// Index of the board currently being edited.
@State private var selectedBoardIndex: Int = 0
/// Crossfade duration (seconds) applied to board switches in the board bar.
@State private var crossfadeSeconds: Double = 0.3
/// Bumped on transport/edit actions to force a re-read of `engine.isRunning`.
@State private var transportTick: Bool = false
/// Shown when live input is selected but microphone access is denied/restricted.
@State private var showMicDeniedAlert: Bool = false
#if !os(macOS)
/// iOS file-dialog presentation flags + the document to export. (macOS uses the File menu.)
@State private var showImporter: Bool = false
/// Guards the one-time input-source restore in `.onAppear`.
@State private var didRestoreInput: Bool = false
/// Presentation flag for the board-manager sheet (rename / reorder / delete).
@State private var showBoardsSheet: Bool = false
/// Confirmation dialog for the Clear action.
@State private var showClearDialog: Bool = false
/// The library entry currently loaded into the session, or `nil` for an unsaved/new rig. Drives
/// the sidebar highlight and decides whether Save overwrites or prompts for a name.
@State private var currentRigID: UUID?
/// Guards the one-time `currentRigID` seed from `initialRigID` on appear.
@State private var didRestoreRig: Bool = false
/// Drives the shared rig-name entry alert (New / Save As / Rename / Duplicate).
@State private var namePrompt: RigNamePrompt?
/// Confirmation dialog for the "Erase All Rigs" library action.
@State private var showEraseAllDialog: Bool = false
/// Save-before-switch prompt: the rig the user asked to switch to while the current rig has
/// unsaved changes, and the flag presenting the dialog.
@State private var pendingSwitchEntry: RigEntry?
@State private var showSwitchSaveDialog: Bool = false
/// Archive export state. Cross-platform: backs the sidebar's Export Archive and the
/// "Save & Clear" flow is separate (it saves to the library, not a file).
@State private var showExporter: Bool = false
@State private var exportDocument: RigFileDocument = RigFileDocument(data: Data())
/// Archive import state (cross-platform).
@State private var showImporter: Bool = false
#if !os(macOS)
/// iOS recording-folder picker presentation flag. (macOS uses the Record menu.)
@State private var showRecordingFolderImporter: Bool = false
#endif
@@ -84,35 +140,39 @@ public struct ShoeGazeBuilderView: View {
/// create at least one board before presenting this view.
/// - hardwareSampleRate: Returns the actual hardware/session sample rate (or `nil`), used by
/// the engine-config Start to warn on a mismatch. Defaults to `nil`.
/// - onEnableLiveInput: Host hook invoked when the user requests live input but the engine
/// has no input channel (iOS). The host should request microphone access, rebuild the
/// engine with one input channel (preserving the rig), and select live input. Defaults to
/// `nil` — on macOS the engine already has an input channel, so live input is selected
/// directly without a rebuild.
/// - library: The rig library store. The host should `start()` it (e.g. via
/// `RigLibraryBootstrap`); the view shows a loading state until then and highlights the
/// persisted current rig once the library has loaded.
public init(
shoeGaze: ShoeGaze,
hardwareSampleRate: @escaping () -> Double? = { nil }
library: RigLibraryStore,
hardwareSampleRate: @escaping () -> Double? = { nil },
onEnableLiveInput: (() -> Void)? = nil
) {
self.shoeGaze = shoeGaze
self.library = library
self.hardwareSampleRate = hardwareSampleRate
self.onEnableLiveInput = onEnableLiveInput
}
// MARK: - Body
public var body: some View {
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.sectionSpacing) {
transportRow
ioRow
#if !os(macOS)
recordingRow
#endif
HStack(alignment: .top, spacing: ShoeGazeBuilderView.columnSpacing) {
rigSidebar
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
HStack(alignment: .top, spacing: ShoeGazeBuilderView.columnSpacing) {
paletteSidebar
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
boardArea
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
ShoeGazeScopeView(shoeGaze: shoeGaze)
LyrebirdStatusView(engine: shoeGaze.engine)
builderColumn
}
.padding(ShoeGazeBuilderView.outerPadding)
.frame(minWidth: ShoeGazeBuilderView.minWidth, minHeight: ShoeGazeBuilderView.minHeight)
.frame(
minWidth: ShoeGazeBuilderView.minWidth + ShoeGazeBuilderView.librarySidebarReserve,
minHeight: ShoeGazeBuilderView.minHeight
)
.background(
Color(
red: ShoeGazeBuilderView.backgroundRed,
@@ -120,6 +180,67 @@ public struct ShoeGazeBuilderView: View {
blue: ShoeGazeBuilderView.backgroundBlue
)
)
.background(boardSwitchShortcuts)
.onAppear {
restoreInputSelection()
restoreCurrentRig()
}
.onChange(of: library.isLoaded) { restoreCurrentRig() }
.onChange(of: currentRigID) { persistCurrentRigID() }
.background(boardsSheetAnchor)
.background(rigExportAnchor)
.background(rigImportAnchor)
.rigNamePrompt($namePrompt)
.confirmationDialog(
"Erase all rigs?",
isPresented: $showEraseAllDialog,
titleVisibility: .visible
) {
Button("Erase All Rigs", role: .destructive) { eraseAllRigs() }
Button("Cancel", role: .cancel) { }
} message: {
Text("This permanently removes every saved rig from the library"
+ (library.isICloud ? " on all your devices." : "."))
}
.confirmationDialog(
"Save changes to the current rig?",
isPresented: $showSwitchSaveDialog,
titleVisibility: .visible,
presenting: pendingSwitchEntry
) { target in
Button("Save") {
pendingSwitchEntry = nil
saveCurrentRig(then: { loadEntry(target) })
}
Button("Don't Save", role: .destructive) {
pendingSwitchEntry = nil
loadEntry(target)
}
Button("Cancel", role: .cancel) { pendingSwitchEntry = nil }
} message: { target in
Text("Switching to \"\(target.name)\" will discard unsaved changes to the current rig.")
}
.onReceive(NotificationCenter.default.publisher(for: .shoeGazeSaveRig)) { _ in
saveCurrentRig()
}
.onReceive(NotificationCenter.default.publisher(for: .shoeGazeNewRig)) { _ in
promptNewRig()
}
.confirmationDialog(
"Clear all boards?",
isPresented: $showClearDialog,
titleVisibility: .visible
) {
Button("Save & Clear") {
saveCurrentRig(then: { performClear() })
}
Button("Clear Without Saving", role: .destructive) {
performClear()
}
Button("Cancel", role: .cancel) { }
} message: {
Text("This removes every pedal and board. Save your current setup first?")
}
.alert("Microphone Access Needed", isPresented: $showMicDeniedAlert) {
Button("OK", role: .cancel) { }
} message: {
@@ -127,25 +248,139 @@ public struct ShoeGazeBuilderView: View {
+ "Security › Microphone, then select the input again.")
}
#if !os(macOS)
.fileImporter(isPresented: $showImporter, allowedContentTypes: [.json]) { result in
handleImport(result)
}
.fileImporter(isPresented: $showRecordingFolderImporter, allowedContentTypes: [.folder]) { result in
handleRecordingFolderImport(result)
}
.fileExporter(
isPresented: $showExporter,
document: exportDocument,
contentType: .json,
defaultFilename: ShoeGazeBuilderView.defaultRigFileName
) { result in
if case .failure(let error) = result {
print("[ShoeGazeBuilderView] export failed: \(error)")
}
}
.background(recordingFolderImportAnchor)
#endif
}
/// The rig library listing on the far left: every saved rig plus new/save/duplicate/rename/
/// delete/erase and archive import/export. Selecting a rig replaces the current session.
private var rigSidebar: some View {
RigLibrarySidebarView(
store: library,
currentRigID: $currentRigID,
onSelect: { entry in requestLoad(entry) },
onNew: { promptNewRig() },
onSave: { saveCurrentRig() },
onSaveAs: { promptSaveAs() },
onDuplicate: { entry in promptDuplicate(entry) },
onRename: { entry in promptRename(entry) },
onDelete: { entry in deleteEntry(entry) },
onEraseAll: { showEraseAllDialog = true },
onImportArchive: { showImporter = true },
onExportArchive: { exportArchiveAction() }
)
}
/// The main builder column: transport, IO, the scope-plus-mixer/picker top section, then the
/// board canvas.
private var builderColumn: some View {
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.sectionSpacing) {
transportRow
ioRow
#if !os(macOS)
recordingRow
#endif
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
topSection
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
boardArea
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
}
/// Top section: the scope + CPU meters on the left (sized to align with the mixer's
/// Solo/Blend/All control column), and a right column stacking the board mixer over the
/// horizontal pedal picker.
private var topSection: some View {
HStack(alignment: .top, spacing: ShoeGazeBuilderView.columnSpacing) {
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.rowSpacing) {
ShoeGazeScopeView(shoeGaze: shoeGaze)
LyrebirdStatusView(engine: shoeGaze.engine)
}
.frame(width: ShoeGazeBuilderView.scopeWidth, alignment: .leading)
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.sectionSpacing) {
BoardBarView(
shoeGaze: shoeGaze,
editingBoardIndex: $selectedBoardIndex,
crossfadeSeconds: $crossfadeSeconds,
onAddBoard: { addBoard() }
)
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
pedalPickerRow
}
.frame(maxWidth: .infinity, alignment: .leading)
}
.fixedSize(horizontal: false, vertical: true)
}
/// A compact horizontal pedal-picker strip (sits below the board mixer in the top section).
private var pedalPickerRow: some View {
ScrollView(.horizontal, showsIndicators: true) {
PedalPaletteView(
axis: .horizontal,
onAdd: { type in addPedal(type: type) },
onRouting: { action in performRouting(action) }
)
.padding(.bottom, 2)
}
.fixedSize(horizontal: false, vertical: true)
}
// MARK: - Presentation anchors
/// Hosts the board-manager sheet on its own node so it does not collide with the file
/// importers / exporter (one presentation per view node).
private var boardsSheetAnchor: some View {
Color.clear
.sheet(isPresented: $showBoardsSheet) {
BoardsSheetView(
shoeGaze: shoeGaze,
editingBoardIndex: $selectedBoardIndex,
crossfadeSeconds: $crossfadeSeconds,
onAddBoard: { addBoard() }
)
.presentationDetents([.medium, .large])
}
}
/// Hosts the archive-export (`.json`) exporter on its own node. Writes the whole library as one
/// ``RigArchive`` file for backup or transfer.
private var rigExportAnchor: some View {
Color.clear
.fileExporter(
isPresented: $showExporter,
document: exportDocument,
contentType: .json,
defaultFilename: ShoeGazeBuilderView.defaultArchiveFileName
) { result in
if case .failure(let error) = result {
print("[ShoeGazeBuilderView] archive export failed: \(error)")
}
}
}
/// Hosts the archive-import (`.json`) importer on its own node (cross-platform). Accepts a
/// ``RigArchive`` or a legacy single-rig file; imported rigs are added to the library.
private var rigImportAnchor: some View {
Color.clear
.fileImporter(isPresented: $showImporter, allowedContentTypes: [.json]) { result in
handleArchiveImport(result)
}
}
#if !os(macOS)
/// Hosts the recording-folder importer on its own node.
private var recordingFolderImportAnchor: some View {
Color.clear
.fileImporter(isPresented: $showRecordingFolderImporter, allowedContentTypes: [.folder]) { result in
handleRecordingFolderImport(result)
}
}
#endif
// MARK: - Transport row
private var transportRow: some View {
@@ -184,56 +419,31 @@ public struct ShoeGazeBuilderView: View {
.foregroundStyle(Color.white.opacity(ShoeGazeBuilderView.labelOpacity))
Picker("Input", selection: inputBinding) {
Text("Test Loop").tag(ShoeGazeBuilderView.testLoopTag)
ForEach(Array(0..<max(0, shoeGaze.engine.numInputChannels)), id: \.self) { channel in
Text("In \(channel)").tag(channel)
if shoeGaze.engine.numInputChannels > 0 {
ForEach(Array(0..<shoeGaze.engine.numInputChannels), id: \.self) { channel in
Text("In \(channel)").tag(channel)
}
} else if onEnableLiveInput != nil {
// No input channel yet: offer live input; selecting it asks the host to
// request mic access and rebuild the engine with one (channel 0).
Text("Live Input").tag(0)
}
}
.pickerStyle(.menu)
.foregroundStyle(Color.white)
Text("Board:")
.font(.subheadline)
.foregroundStyle(Color.white.opacity(ShoeGazeBuilderView.labelOpacity))
Picker("Board", selection: $selectedBoardIndex) {
ForEach(Array(shoeGaze.boards.enumerated()), id: \.offset) { pair in
let label: String = pair.element.label.isEmpty
? "Board \(pair.offset + 1)"
: pair.element.label
Text(label).tag(pair.offset)
}
}
.pickerStyle(.menu)
.foregroundStyle(Color.white)
Button("Add Board") { addBoard() }
Button("Boards…") { showBoardsSheet = true }
.buttonStyle(.bordered).tint(.orange)
.help("Rename, reorder, or delete boards")
Button("Clear") { showClearDialog = true }
.buttonStyle(.bordered).tint(.red)
.help("Remove all boards in the current rig (with the option to save first)")
Spacer()
// On macOS, Save/Load live in the app's File menu (see the app shell's AppDelegate);
// on iOS they stay in-view, driven by fileExporter/fileImporter.
#if !os(macOS)
Button("Save…") { saveAction() }
.buttonStyle(.bordered).tint(.blue)
Button("Load…") { loadAction() }
.buttonStyle(.bordered).tint(.blue)
#endif
}
}
// MARK: - Palette sidebar
private var paletteSidebar: some View {
ScrollView(.vertical, showsIndicators: true) {
PedalPaletteView(
onAdd: { type in addPedal(type: type) },
onRouting: { action in performRouting(action) }
)
.padding(.trailing, 2)
}
.frame(width: ShoeGazeBuilderView.sidebarWidth)
}
// MARK: - Board area
private var boardArea: some View {
@@ -280,10 +490,15 @@ public struct ShoeGazeBuilderView: View {
}
},
set: { newValue in
let source: InputSource = newValue == ShoeGazeBuilderView.testLoopTag
? .testLoop
: .liveInput(channel: newValue)
switchInput(to: source)
if newValue == ShoeGazeBuilderView.testLoopTag {
switchInput(to: .testLoop)
} else if newValue < shoeGaze.engine.numInputChannels {
switchInput(to: .liveInput(channel: newValue))
} else if let onEnableLiveInput {
// Requested a channel the current engine doesn't have (iOS, 0 channels):
// hand off to the host to grant mic + rebuild with an input channel.
onEnableLiveInput()
}
}
)
}
@@ -294,7 +509,8 @@ public struct ShoeGazeBuilderView: View {
guard !shoeGaze.boards.isEmpty else { return }
let board: PedalBoard = shoeGaze.boards[clampedBoardIndex]
do {
_ = try shoeGaze.appendPedal(type: type, to: board)
_ = try shoeGaze.appendPedal(PedalType(type), to: board)
autosave()
} catch {
print("[ShoeGazeBuilderView] appendPedal failed: \(error)")
}
@@ -307,12 +523,45 @@ public struct ShoeGazeBuilderView: View {
created = board
try shoeGaze.finalizeBoard(board)
selectedBoardIndex = shoeGaze.boards.count - 1
autosave()
} catch {
if let board: PedalBoard = created { shoeGaze.removeBoard(board) }
print("[ShoeGazeBuilderView] addBoard failed: \(error)")
}
}
/// Persists the current rig to the autosave file. Called after structural edits so state
/// survives a restart even without an explicit Save; the app shells also save on background.
private func autosave() {
RigStore.save(shoeGaze)
}
/// Removes every board, then seeds one fresh empty board so the builder is never boardless.
/// Resets the edit target and autosaves the cleared state.
private func performClear() {
// Stop around the rebuild so removing every board and immediately re-adding a fresh one
// can't reuse a bus a just-removed master is still draining (one-block glitch).
let wasRunning: Bool = shoeGaze.engine.isRunning
if wasRunning { shoeGaze.engine.stop() }
// Snapshot before removing — removeBoard mutates shoeGaze.boards.
for board: PedalBoard in Array(shoeGaze.boards) {
shoeGaze.removeBoard(board)
}
do {
let board: PedalBoard = try shoeGaze.addBoard()
board.label = "Board 1"
try shoeGaze.finalizeBoard(board)
} catch {
print("[ShoeGazeBuilderView] clear failed to seed a fresh board: \(error)")
}
selectedBoardIndex = 0
if wasRunning { try? shoeGaze.engine.start() }
autosave()
transportTick.toggle()
}
/// Switches input source, stopping/restarting the engine around the graph rebuild.
///
/// Live input requires microphone authorisation first — without it macOS feeds the AUHAL
@@ -335,6 +584,7 @@ public struct ShoeGazeBuilderView: View {
if wasRunning { shoeGaze.engine.stop() }
do {
try shoeGaze.setInputSource(source)
persistInputSelection(source)
} catch {
print("[ShoeGazeBuilderView] setInputSource failed: \(error)")
}
@@ -344,11 +594,73 @@ public struct ShoeGazeBuilderView: View {
transportTick.toggle()
}
// MARK: - Save / Load (iOS)
// MARK: - Input persistence
// On macOS, Save/Load are driven from the app's File menu (the app shell owns the
// NSSavePanel/NSOpenPanel and calls `shoeGaze.saveRig`/`loadRig` directly). On iOS they are
// in-view, presenting `fileExporter`/`fileImporter`.
/// Saves the current input choice so it is restored on the next launch.
private func persistInputSelection(_ source: InputSource) {
let value: Int
switch source {
case .testLoop:
value = ShoeGazeBuilderView.testLoopTag
case .liveInput(let channel):
value = channel
}
UserDefaults.standard.set(value, forKey: ShoeGazeBuilderView.inputSelectionDefaultsKey)
}
/// Restores the saved input choice once on appear. With no saved choice, defaults to live
/// input when the microphone is already authorised and the engine has an input channel —
/// otherwise stays on the test loop. A saved live channel that no longer fits the engine, or
/// a since-revoked permission, falls back to the test loop via `switchInput(to:)`.
private func restoreInputSelection() {
guard !didRestoreInput else { return }
didRestoreInput = true
let defaults: UserDefaults = UserDefaults.standard
if defaults.object(forKey: ShoeGazeBuilderView.inputSelectionDefaultsKey) != nil {
let stored: Int = defaults.integer(forKey: ShoeGazeBuilderView.inputSelectionDefaultsKey)
if stored >= 0, stored < shoeGaze.engine.numInputChannels {
switchInput(to: .liveInput(channel: stored))
} else if stored >= 0, shoeGaze.engine.numInputChannels == 0,
MicrophonePermission.isAuthorized, let onEnableLiveInput {
// iOS: a live choice was saved and the mic is already authorised — rebuild the
// engine with an input channel silently (no prompt, since access is granted).
onEnableLiveInput()
}
// A test-loop choice (or live with no host hook / no permission) leaves the test loop.
} else if MicrophonePermission.isAuthorized, shoeGaze.engine.numInputChannels > 0 {
// First launch with no saved choice but mic already granted → default to live input.
switchInput(to: .liveInput(channel: 0))
}
}
// MARK: - Board-switch shortcuts
/// Hidden ⌘1…⌘9 buttons that solo (live-switch to) the matching board and select it as the
/// edit target. Kept at zero opacity so the shortcuts stay active without showing chrome.
private var boardSwitchShortcuts: some View {
ZStack {
ForEach(0 ..< min(ShoeGazeBuilderView.maxBoardShortcuts, shoeGaze.boards.count), id: \.self) { index in
Button("") { switchToBoard(index) }
.keyboardShortcut(KeyEquivalent(Character("\(index + 1)")), modifiers: .command)
}
}
.opacity(0)
.frame(width: 0, height: 0)
.accessibilityHidden(true)
}
/// Solos board `index` (a live amp-channel-style switch) and makes it the edit target.
private func switchToBoard(_ index: Int) {
guard index < shoeGaze.boards.count else { return }
selectedBoardIndex = index
let seconds: Double = min(max(crossfadeSeconds, 0.0), ShoeGazeBuilderView.maxCrossfadeSeconds)
shoeGaze.soloBoard(shoeGaze.boards[index], crossfadeSeconds: seconds)
}
// MARK: - Recording (iOS)
// Recording controls are iOS in-view (macOS uses the Record menu).
#if !os(macOS)
/// iOS recording controls: choose an output folder, then start/stop recording.
private var recordingRow: some View {
@@ -393,45 +705,241 @@ public struct ShoeGazeBuilderView: View {
print("[ShoeGazeBuilderView] recording folder pick failed: \(error)")
}
}
#endif
private func saveAction() {
do {
exportDocument = RigFileDocument(data: try shoeGaze.rigData())
showExporter = true
} catch {
print("[ShoeGazeBuilderView] rigData failed: \(error)")
// MARK: - Rig library
/// Highlights the persisted current rig once the library has loaded. Runs once; only sets the
/// highlight when nothing is selected yet and the saved id still exists in the library.
private func restoreCurrentRig() {
guard !didRestoreRig, library.isLoaded else { return }
didRestoreRig = true
guard currentRigID == nil,
let stored: String = UserDefaults.standard.string(
forKey: ShoeGazeBuilderView.currentRigDefaultsKey),
let id: UUID = UUID(uuidString: stored),
library.entries.contains(where: { $0.id == id }) else { return }
currentRigID = id
}
/// Persists `currentRigID` so the same rig is highlighted on the next launch.
private func persistCurrentRigID() {
let defaults: UserDefaults = UserDefaults.standard
if let id: UUID = currentRigID {
defaults.set(id.uuidString, forKey: ShoeGazeBuilderView.currentRigDefaultsKey)
} else {
defaults.removeObject(forKey: ShoeGazeBuilderView.currentRigDefaultsKey)
}
}
private func loadAction() {
showImporter = true
}
/// Loads a rig from a URL, stopping/restarting the engine around the rebuild and resetting the
/// board selection to a valid index (load replaces all boards).
private func loadRig(from url: URL) {
/// Loads a library entry into the session, replacing the current rig. Stops/restarts the engine
/// around the rebuild, resets the board selection, and records the entry as current.
private func loadEntry(_ entry: RigEntry) {
let wasRunning: Bool = shoeGaze.engine.isRunning
if wasRunning { shoeGaze.engine.stop() }
do {
try shoeGaze.loadRig(from: url)
try shoeGaze.loadRig(from: entry.state)
currentRigID = entry.id
selectedBoardIndex = 0
autosave()
} catch {
print("[ShoeGazeBuilderView] loadRig failed: \(error)")
print("[ShoeGazeBuilderView] loadEntry failed: \(error)")
}
if wasRunning { try? shoeGaze.engine.start() }
transportTick.toggle()
}
private func handleImport(_ result: Result<URL, Error>) {
switch result {
case .success(let url):
// A `.fileImporter` URL is security-scoped on iOS; access must be started to read it.
let scoped: Bool = url.startAccessingSecurityScopedResource()
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
loadRig(from: url)
case .failure(let error):
print("[ShoeGazeBuilderView] import failed: \(error)")
/// Switches to `entry`, prompting to save first when the current rig has unsaved changes.
/// No-op when `entry` is already the current rig.
private func requestLoad(_ entry: RigEntry) {
guard entry.id != currentRigID else { return }
if isCurrentRigDirty() {
pendingSwitchEntry = entry
showSwitchSaveDialog = true
} else {
loadEntry(entry)
}
}
#endif
/// Whether the working rig differs from the library entry it was loaded from. A working rig with
/// no backing entry counts as dirty when it has any boards.
private func isCurrentRigDirty() -> Bool {
guard let id: UUID = currentRigID,
let entry: RigEntry = library.entries.first(where: { $0.id == id }) else {
return !shoeGaze.boards.isEmpty
}
return shoeGaze.captureState() != entry.state
}
/// Saves the current session over the loaded library entry, or prompts for a name when no entry
/// is loaded (a new, never-saved rig).
///
/// - Parameter completion: Runs only after a successful save (e.g. clear the boards, or load the
/// rig the user was switching to). Cancelling the name prompt cancels it too — no save, no
/// follow-up.
private func saveCurrentRig(then completion: @escaping () -> Void = { }) {
guard let id: UUID = currentRigID,
let existing: RigEntry = library.entries.first(where: { $0.id == id }) else {
// No current entry — prompt for a name; the follow-up runs only on commit.
namePrompt = RigNamePrompt(
title: "Save Rig As",
initialText: currentRigName() ?? defaultNewRigName(),
confirmLabel: "Save"
) { name in
persist(shoeGaze.captureEntry(name: name), then: completion)
}
return
}
persist(shoeGaze.captureEntry(name: existing.name, id: id), then: completion)
}
/// Prompts for a name, then creates a brand-new empty rig (one empty board) and selects it.
private func promptNewRig() {
namePrompt = RigNamePrompt(
title: "New Rig",
initialText: defaultNewRigName(),
confirmLabel: "Create"
) { name in
createNewRig(named: name)
}
}
/// Prompts for a name and saves the current session as a new library entry (new id).
private func promptSaveAs() {
namePrompt = RigNamePrompt(
title: "Save Rig As",
initialText: currentRigName() ?? defaultNewRigName(),
confirmLabel: "Save"
) { name in
persist(shoeGaze.captureEntry(name: name))
}
}
/// Prompts for a name and duplicates `entry`, loading the copy as the current rig.
private func promptDuplicate(_ entry: RigEntry) {
namePrompt = RigNamePrompt(
title: "Duplicate Rig",
initialText: "\(entry.name) copy",
confirmLabel: "Duplicate"
) { name in
do {
let copy: RigEntry = try library.duplicate(entry, newName: name)
loadEntry(copy)
} catch {
print("[ShoeGazeBuilderView] duplicate failed: \(error)")
}
}
}
/// Prompts for a new name and renames `entry` in the library.
private func promptRename(_ entry: RigEntry) {
namePrompt = RigNamePrompt(
title: "Rename Rig",
initialText: entry.name,
confirmLabel: "Rename"
) { name in
do { _ = try library.rename(entry, to: name) }
catch { print("[ShoeGazeBuilderView] rename failed: \(error)") }
}
}
/// Deletes `entry` from the library. Clears the current-rig marker if it was the loaded rig.
private func deleteEntry(_ entry: RigEntry) {
do {
try library.delete(entry)
if currentRigID == entry.id { currentRigID = nil }
} catch {
print("[ShoeGazeBuilderView] delete failed: \(error)")
}
}
/// Erases the entire library and clears the current-rig marker.
private func eraseAllRigs() {
do {
try library.eraseAll()
currentRigID = nil
} catch {
print("[ShoeGazeBuilderView] eraseAll failed: \(error)")
}
}
/// Captures the current session into the whole-library archive exporter.
private func exportArchiveAction() {
do {
exportDocument = RigFileDocument(data: try library.exportArchiveData())
showExporter = true
} catch {
print("[ShoeGazeBuilderView] exportArchiveData failed: \(error)")
}
}
/// Imports an archive (or legacy single-rig file) into the library.
private func handleArchiveImport(_ result: Result<URL, Error>) {
switch result {
case .success(let url):
// A `.fileImporter` URL is security-scoped; access must be started to read it.
let scoped: Bool = url.startAccessingSecurityScopedResource()
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
do {
let data: Data = try Data(contentsOf: url)
_ = try library.importArchive(from: data)
} catch {
print("[ShoeGazeBuilderView] archive import failed: \(error)")
}
case .failure(let error):
print("[ShoeGazeBuilderView] archive import pick failed: \(error)")
}
}
/// Persists `entry`, marks it current, and runs `completion` (e.g. the "Save & Clear" clear).
private func persist(
_ entry: RigEntry,
then completion: () -> Void = { }
) {
do {
try library.save(entry)
currentRigID = entry.id
// Only run the follow-up (e.g. the "Save & Clear" clear) once the save succeeded —
// otherwise a failed save would still wipe the boards, losing the rig.
completion()
} catch {
print("[ShoeGazeBuilderView] save failed: \(error)")
}
}
/// Creates a fresh single-board rig, saves it under `name`, and makes it current.
private func createNewRig(named name: String) {
let wasRunning: Bool = shoeGaze.engine.isRunning
if wasRunning { shoeGaze.engine.stop() }
// Replace the working graph with a single empty board.
for board: PedalBoard in Array(shoeGaze.boards) {
shoeGaze.removeBoard(board)
}
do {
let board: PedalBoard = try shoeGaze.addBoard()
board.label = "Board 1"
try shoeGaze.finalizeBoard(board)
} catch {
print("[ShoeGazeBuilderView] createNewRig seed failed: \(error)")
}
selectedBoardIndex = 0
if wasRunning { try? shoeGaze.engine.start() }
transportTick.toggle()
persist(shoeGaze.captureEntry(name: name))
}
/// The name of the currently loaded library entry, if any.
private func currentRigName() -> String? {
guard let id: UUID = currentRigID else { return nil }
return library.entries.first(where: { $0.id == id })?.name
}
/// A default name for a new rig: `"Rig N"` where N avoids collisions with existing names.
private func defaultNewRigName() -> String {
let base: String = "Rig"
let existing: Set<String> = Set(library.entries.map(\.name))
var index: Int = library.entries.count + 1
while existing.contains("\(base) \(index)") { index += 1 }
return "\(base) \(index)"
}
}
+10 -72
View File
@@ -79,6 +79,10 @@ public struct ShoeGazeView: View {
/// Crossfade duration used for the next board-select transition.
@State private var crossfadeSeconds: Double = ShoeGazeView.defaultCrossfadeSeconds
/// Highlighted board in the board bar (the bar's edit-target binding). The player shows
/// every board strip, so this only drives the bar's selection outline.
@State private var selectedBoardIndex: Int = 0
/// Controls presentation of the iOS `.fileImporter` directory picker.
/// On macOS the picker is opened imperatively via `NSOpenPanel`; this flag is
/// only meaningful on iOS / non-macOS targets.
@@ -108,7 +112,12 @@ public struct ShoeGazeView: View {
recordingRow
Divider()
.overlay(Color.white.opacity(ShoeGazeView.dividerOpacity))
boardSelectRow
BoardBarView(
shoeGaze: shoeGaze,
editingBoardIndex: $selectedBoardIndex,
crossfadeSeconds: $crossfadeSeconds,
onAddBoard: { addBoard() }
)
Divider()
.overlay(Color.white.opacity(ShoeGazeView.dividerOpacity))
boardList
@@ -230,77 +239,6 @@ public struct ShoeGazeView: View {
}
}
/// A `Binding<Int>` that maps between the Picker's integer tag and `ShoeGaze` select API.
///
/// Tag `-1` represents "All boards audible" (`activeBoardIndex == nil`).
/// Tags `0 ..< boards.count` represent the soloed board at that index.
/// Setting the binding calls `selectBoard(_:crossfadeSeconds:)` or
/// `selectAllBoards(crossfadeSeconds:)` with the current `crossfadeSeconds` value.
private var boardSelectBinding: Binding<Int> {
Binding(
get: { shoeGaze.activeBoardIndex ?? -1 },
set: { newValue in
// Clamp here so a value typed into the crossfade text field (which has no
// built-in bounds) can never pass a negative or oversized lag time.
let seconds: Double = min(max(crossfadeSeconds, 0.0), ShoeGazeView.maxCrossfadeSeconds)
if newValue == -1 {
shoeGaze.selectAllBoards(crossfadeSeconds: seconds)
} else if newValue >= 0, newValue < shoeGaze.boards.count {
shoeGaze.selectBoard(shoeGaze.boards[newValue], crossfadeSeconds: seconds)
}
}
)
}
/// Board-select row: an "Active" Picker to solo a board (or hear all), a crossfade-
/// seconds text field, and a companion Stepper for convenient adjustment.
///
/// The row is always visible. When `boards.count <= 1` the Picker has only one or two
/// options, which is still useful for the "All" / single-board toggle.
private var boardSelectRow: some View {
HStack(spacing: ShoeGazeView.boardSelectSpacing) {
Text("Active:")
.font(.subheadline)
.foregroundStyle(Color.white.opacity(ShoeGazeView.labelOpacity))
Picker("Active", selection: boardSelectBinding) {
Text("All").tag(-1)
ForEach(Array(shoeGaze.boards.enumerated()), id: \.offset) { pair in
let label: String = pair.element.label.isEmpty
? "Board \(pair.offset + 1)"
: pair.element.label
Text(label).tag(pair.offset)
}
}
.pickerStyle(.menu)
.foregroundStyle(Color.white)
Spacer()
Text("Crossfade (s):")
.font(.subheadline)
.foregroundStyle(Color.white.opacity(ShoeGazeView.labelOpacity))
TextField(
"s",
value: $crossfadeSeconds,
format: .number.precision(.fractionLength(1))
)
.frame(width: ShoeGazeView.crossfadeFieldWidth)
#if os(macOS)
.textFieldStyle(.squareBorder)
#endif
Stepper(
"",
value: $crossfadeSeconds,
in: 0...ShoeGazeView.maxCrossfadeSeconds,
step: ShoeGazeView.crossfadeStepIncrement
)
.labelsHidden()
}
}
/// Vertically scrollable list of board strips.
///
/// Keyed by `\.offset` on an enumerated snapshot; see the doc-comment on
@@ -50,7 +50,7 @@ struct BoardEditAPITests {
try makeRig(pedals: ["Overdrive", "Delay"])
defer { try? FileManager.default.removeItem(at: url) }
let edited: PedalBoard = try sg.appendPedal(type: "Reverb", to: board)
let edited: PedalBoard = try sg.appendPedal(.reverb, to: board)
#expect(names(edited) == ["Overdrive", "Delay", "Reverb"])
#expect(sg.boards.count == 1, "append should not change board count")
@@ -64,7 +64,7 @@ struct BoardEditAPITests {
defer { try? FileManager.default.removeItem(at: url) }
#expect(throws: ShoeGazeError.unknownPedalType("Nope")) {
try sg.appendPedal(type: "Nope", to: board)
try sg.appendPedal(PedalType("Nope"), to: board)
}
}
@@ -135,7 +135,7 @@ struct BoardEditAPITests {
try sg.finalizeBoard(board)
// Append a linear pedal; the stereo split region must survive untouched.
let edited: PedalBoard = try sg.appendPedal(type: "Fuzz", to: board)
let edited: PedalBoard = try sg.appendPedal(.fuzz, to: board)
#expect(names(edited).contains("Fuzz"), "appended linear pedal should be present")
let after: BoardState = edited.captureState()
@@ -215,8 +215,8 @@ struct BoardEditAPITests {
var live: PedalBoard = try sg.appendStereoSplit(to: board)
// The split region is the second top-level segment (after the Overdrive pedal).
let region: Int = 1
live = try sg.appendPedal(type: "Delay", to: live, lane: .left(region: region))
live = try sg.appendPedal(type: "Reverb", to: live, lane: .right(region: region))
live = try sg.appendPedal(.delay, to: live, lane: .left(region: region))
live = try sg.appendPedal(.reverb, to: live, lane: .right(region: region))
guard let state: StereoSplitState = stereoState(live) else {
Issue.record("No stereo split segment after building one")
@@ -236,8 +236,8 @@ struct BoardEditAPITests {
defer { try? FileManager.default.removeItem(at: url) }
var live: PedalBoard = try sg.appendStereoSplit(to: board)
live = try sg.appendPedal(type: "Delay", to: live, lane: .left(region: 1))
live = try sg.appendPedal(type: "Fuzz", to: live, lane: .left(region: 1))
live = try sg.appendPedal(.delay, to: live, lane: .left(region: 1))
live = try sg.appendPedal(.fuzz, to: live, lane: .left(region: 1))
live = try sg.removePedal(at: 0, from: live, lane: .left(region: 1))
#expect(stereoState(live)?.left.map { $0.type } == ["Fuzz"], "left lane should drop Delay")
@@ -249,7 +249,7 @@ struct BoardEditAPITests {
defer { try? FileManager.default.removeItem(at: url) }
// Octave Splitter is a widener → board becomes stereo; a second split is then invalid.
let live: PedalBoard = try sg.appendPedal(type: "Octave Splitter", to: board)
let live: PedalBoard = try sg.appendPedal(.octaveSplitter, to: board)
#expect(live.width == 2, "widener should make the board stereo")
#expect(throws: ShoeGazeError.cannotSplitStereoChain) {
try sg.appendStereoSplit(to: live)
@@ -262,7 +262,7 @@ struct BoardEditAPITests {
defer { try? FileManager.default.removeItem(at: url) }
var live: PedalBoard = try sg.appendStereoSplit(to: board)
live = try sg.appendPedal(type: "Delay", to: live, lane: .left(region: 1))
live = try sg.appendPedal(.delay, to: live, lane: .left(region: 1))
#expect(stereoState(live) != nil, "split region present before removal")
live = try sg.removeSegment(at: 1, from: live)
@@ -319,8 +319,8 @@ struct BoardEditAPITests {
var live: PedalBoard = try sg.insertStereoUnzip(afterSegment: 0, in: board)
#expect(sg.isStereoUnzip(afterSegment: 0, in: live), "toggle should report unzip present")
live = try sg.appendPedal(type: "Fuzz", to: live, lane: .left(region: 1))
live = try sg.appendPedal(type: "Reverb", to: live, lane: .right(region: 1))
live = try sg.appendPedal(.fuzz, to: live, lane: .left(region: 1))
live = try sg.appendPedal(.reverb, to: live, lane: .right(region: 1))
guard let state: StereoUnzipState = unzipState(live) else {
Issue.record("No stereo unzip segment")
@@ -375,8 +375,8 @@ struct BoardEditAPITests {
defer { try? FileManager.default.removeItem(at: url) }
var live: PedalBoard = try sg.insertStereoUnzip(afterSegment: 0, in: board)
live = try sg.appendPedal(type: "Delay", to: live, lane: .left(region: 1))
live = try sg.appendPedal(type: "Reverb", to: live, lane: .right(region: 1))
live = try sg.appendPedal(.delay, to: live, lane: .left(region: 1))
live = try sg.appendPedal(.reverb, to: live, lane: .right(region: 1))
if let section: StereoSplitSection = live.stereoUnzipSections.first {
section.route = .rightOnly
}
@@ -410,8 +410,8 @@ struct BoardEditAPITests {
defer { try? FileManager.default.removeItem(at: url) }
var live: PedalBoard = try sg.appendParallelSplit(to: board)
live = try sg.appendPedal(type: "Delay", to: live, lane: .left(region: 1))
live = try sg.appendPedal(type: "Fuzz", to: live, lane: .right(region: 1))
live = try sg.appendPedal(.delay, to: live, lane: .left(region: 1))
live = try sg.appendPedal(.fuzz, to: live, lane: .right(region: 1))
var foundParallel: Bool = false
for segment: BoardSegmentState in live.captureState().segments {
@@ -528,7 +528,7 @@ struct BoardEditAPITests {
defer { try? FileManager.default.removeItem(at: url) }
var live: PedalBoard = try sg.appendStereoSplit(to: board)
live = try sg.appendPedal(type: "Delay", to: live, lane: .left(region: 1))
live = try sg.appendPedal(.delay, to: live, lane: .left(region: 1))
// Edit the branch pedal's first knob via the node path.
guard let stereo: StereoSplitSection = live.stereoSplitSections.first,
@@ -562,7 +562,7 @@ struct BoardEditAPITests {
try makeRig(pedals: ["Overdrive", "Delay"])
defer { try? FileManager.default.removeItem(at: url) }
try sg.appendPedal(type: "Reverb", to: board)
try sg.appendPedal(.reverb, to: board)
try sg.removePedal(at: 0, from: sg.boards[0]) // drop Overdrive → [Delay, Reverb]
let preset: URL = FileManager.default.temporaryDirectory
@@ -582,4 +582,54 @@ struct BoardEditAPITests {
let samples: [Float] = try render(engine2, url2)
#expect(hasNonSilentOutput(samples), "loaded edited rig should render audio")
}
// MARK: - Cross-lane move (drag a pedal into a region lane)
@Test func moveMainPedalIntoStereoUnzipLanePreservingParams() throws {
// Ping-Pong (stereo) then Overdrive on the main chain; unzip after Ping-Pong.
let (sg, engine, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Ping-Pong", "Overdrive"])
defer { try? FileManager.default.removeItem(at: url) }
var live: PedalBoard = try sg.insertStereoUnzip(afterSegment: 0, in: board)
// Tweak the live Overdrive so we can verify its params survive the move.
let overdrive: OverdrivePedal? = live.pedals.compactMap { $0 as? OverdrivePedal }.first
overdrive?.drive = 11.0
// Move the Overdrive (main linear index 1) into the unzip's left lane (region segment 1).
live = try sg.movePedal(from: .main, at: 1, to: .left(region: 1), in: live)
#expect(names(live) == ["Ping-Pong"], "Overdrive should leave the main chain")
guard let state: StereoUnzipState = unzipState(live) else {
Issue.record("No stereo unzip segment")
return
}
#expect(state.left.map { $0.type } == ["Overdrive"], "Overdrive should land in the left lane")
#expect(state.left.first?.knobValues.first == 11.0, "Drive param should survive the move")
let samples: [Float] = try render(engine, url)
#expect(hasNonSilentOutput(samples), "board renders after the cross-lane move")
}
@Test func moveMainPedalBeforeUnzipRegionAdjustsIndex() throws {
// Overdrive (mono) then Ping-Pong (stereo); unzip after Ping-Pong. Moving the Overdrive —
// which sits BEFORE the unzip region — exercises the destination-index adjustment.
let (sg, engine, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Ping-Pong"])
defer { try? FileManager.default.removeItem(at: url) }
var live: PedalBoard = try sg.insertStereoUnzip(afterSegment: 1, in: board)
// Unzip is top-level segment 2; Overdrive is main linear index 0 (top-level segment 0).
live = try sg.movePedal(from: .main, at: 0, to: .left(region: 2), in: live)
#expect(names(live) == ["Ping-Pong"], "Overdrive should leave the main chain")
guard let state: StereoUnzipState = unzipState(live) else {
Issue.record("No stereo unzip segment")
return
}
#expect(state.left.map { $0.type } == ["Overdrive"], "Overdrive should land in the left lane")
let samples: [Float] = try render(engine, url)
#expect(hasNonSilentOutput(samples), "board renders after the index-adjusted move")
}
}
@@ -0,0 +1,131 @@
// ChorusPedalTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@MainActor
@Suite("ChorusPedal")
struct ChorusPedalTests {
private func render(configure: (ChorusPedal) -> Void = { _ in }) throws -> [Float] {
let renderDuration: Double = 0.1
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration, numAudioBuses: 64)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(dstBus)
}
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
let pedal: ChorusPedal = ChorusPedal(inputBus: srcBus.index, outputBus: dstBus.index)
configure(pedal)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(source)
try engine.add(pedal, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(pedal))
try engine.start()
return readStereoCAF(url: url)
}
private func ssd(_ a: [Float], _ b: [Float]) -> Double {
let skip: Int = 2048, window: Int = 2048
guard a.count >= skip + window, b.count >= skip + window else { return 0 }
return zip(a[skip..<(skip + window)], b[skip..<(skip + window)]).reduce(0.0) { acc, pair in
let d: Double = Double(pair.0 - pair.1); return acc + d * d
}
}
@Test func buildsAndProducesNonSilentOutput() throws {
let samples: [Float] = try render()
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "ChorusPedal produced silence")
}
@Test func rateChangesOutput() throws {
let slow: [Float] = try render { $0.rate = 0.1 }
let fast: [Float] = try render { $0.rate = 5.0 }
#expect(hasNonSilentOutput(slow) && hasNonSilentOutput(fast))
#expect(ssd(slow, fast) > 0, "rate had no effect on output")
}
@Test func depthChangesOutput() throws {
let shallow: [Float] = try render { $0.depth = 0.0005 }
let deep: [Float] = try render { $0.depth = 0.008 }
#expect(ssd(shallow, deep) > 0, "depth had no effect on output")
}
@Test func leftAndRightVoicesDiffer() throws {
// The point of the widener: anti-phase LFOs make the two voices distinct. Activate the
// right channel (which a stereo board region does via PedalBoard.add) by setting
// `outputBusRight`, route each board bus to a separate hardware channel, and compare.
let renderDuration: Double = 0.1
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration, numAudioBuses: 64)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstL: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstR: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(dstL)
engine.busAllocator.releaseAudioBus(dstR)
}
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
let pedal: ChorusPedal = ChorusPedal(inputBus: srcBus.index, outputBus: dstL.index)
pedal.outputBusRight = dstR.index // emulate the stereo region a board would create
let master: StereoSplitTestMaster = StereoSplitTestMaster(left: dstL.index, right: dstR.index)
try engine.add(source)
try engine.add(pedal, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(pedal))
try engine.start()
// readStereoCAF returns interleaved [L, R, L, R, …]; even = left voice, odd = right voice.
let samples: [Float] = readStereoCAF(url: url)
let skipFrames: Int = 2048
let windowFrames: Int = 2048
guard samples.count >= 2 * (skipFrames + windowFrames) else { return }
var lefts: [Float] = []
var rights: [Float] = []
for frame: Int in skipFrames ..< (skipFrames + windowFrames) {
lefts.append(samples[2 * frame])
rights.append(samples[2 * frame + 1])
}
#expect(hasNonSilentOutput(lefts) && hasNonSilentOutput(rights), "a chorus voice was silent")
let ssdLR: Double = zip(lefts, rights).reduce(0.0) { acc, pair in
let d: Double = Double(pair.0 - pair.1); return acc + d * d
}
#expect(ssdLR > 0, "left and right chorus voices are identical — no stereo width")
}
}
/// Routes two mono board buses to hardware left (bus 0) and right (bus 1) so a stereo widener's
/// channels can be captured separately by `readStereoCAF`.
@MainActor
private final class StereoSplitTestMaster: SynthesizerBase {
private let left: Int
private let right: Int
init(left: Int, right: Int) {
self.left = left
self.right = right
super.init()
}
override func build() {
output(bus: 0, source: input(bus: left))
output(bus: 1, source: input(bus: right))
}
}
@@ -98,4 +98,64 @@ struct CompressorPedalTests {
}
#expect(ssd > 0, "ratio=1 and ratio=20 produced identical output — ratio knob has no effect")
}
@Test func exposesInputThresholdRatioKnobs() throws {
let pedal: CompressorPedal = CompressorPedal()
let labels: [String] = pedal.effectKnobs.map { $0.label }
#expect(labels == ["Input", "Threshold", "Ratio"])
}
@Test func inputGainChangesOutput() throws {
// The pre-compression input gain stage must alter the output: boosting the input
// drives more of the signal past the threshold, changing the compressed result.
let renderDuration: Double = 0.1
let numAudioBuses: Int = 64
func renderWithInputGain(_ gainDB: Double) throws -> [Float] {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(dstBus)
}
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
let pedal: CompressorPedal = CompressorPedal(
inputBus: srcBus.index,
outputBus: dstBus.index
)
pedal.inputGain = gainDB
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(source)
try engine.add(pedal, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(pedal))
try engine.start()
return readStereoCAF(url: url)
}
let unitySamples: [Float] = try renderWithInputGain(0.0)
let boostedSamples: [Float] = try renderWithInputGain(24.0)
#expect(hasNonSilentOutput(unitySamples), "0 dB input-gain render was silent")
#expect(hasNonSilentOutput(boostedSamples), "+24 dB input-gain render was silent")
let skipSamples: Int = 1024
let windowSize: Int = 2048
guard unitySamples.count >= skipSamples + windowSize,
boostedSamples.count >= skipSamples + windowSize else { return }
let unityWindow: [Float] = Array(unitySamples[skipSamples..<(skipSamples + windowSize)])
let boostedWindow: [Float] = Array(boostedSamples[skipSamples..<(skipSamples + windowSize)])
let ssd: Double = zip(unityWindow, boostedWindow).reduce(0.0) { acc, pair in
let diff: Double = Double(pair.0 - pair.1)
return acc + diff * diff
}
#expect(ssd > 0, "input gain 0 dB and +24 dB produced identical output — input gain has no effect")
}
}
@@ -0,0 +1,98 @@
// DiffuserPedalTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@MainActor
@Suite("DiffuserPedal")
struct DiffuserPedalTests {
/// Renders the diffuser as a stereo widener, returning (leftSamples, rightSamples).
private func renderStereo(spread: Double) throws -> (left: [Float], right: [Float]) {
let renderDuration: Double = 0.1
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration, numAudioBuses: 64)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstL: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstR: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(dstL)
engine.busAllocator.releaseAudioBus(dstR)
}
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
let pedal: DiffuserPedal = DiffuserPedal(inputBus: srcBus.index, outputBus: dstL.index)
pedal.outputBusRight = dstR.index
pedal.spread = spread
let master: DiffuserStereoSplitMaster = DiffuserStereoSplitMaster(left: dstL.index, right: dstR.index)
try engine.add(source)
try engine.add(pedal, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(pedal))
try engine.start()
let samples: [Float] = readStereoCAF(url: url)
let skipFrames: Int = 2048
let windowFrames: Int = 2048
var left: [Float] = []
var right: [Float] = []
guard samples.count >= 2 * (skipFrames + windowFrames) else { return ([], []) }
for frame: Int in skipFrames ..< (skipFrames + windowFrames) {
left.append(samples[2 * frame])
right.append(samples[2 * frame + 1])
}
return (left, right)
}
private func ssd(_ a: [Float], _ b: [Float]) -> Double {
zip(a, b).reduce(0.0) { acc, pair in
let d: Double = Double(pair.0 - pair.1); return acc + d * d
}
}
@Test func buildsAndProducesNonSilentOutput() throws {
let (left, right): ([Float], [Float]) = try renderStereo(spread: 0.6)
#expect(hasNonSilentOutput(left), "diffuser left channel was silent")
#expect(hasNonSilentOutput(right), "diffuser right channel was silent")
}
@Test func zeroSpreadIsMono() throws {
// At spread 0 every band sits centre → left and right are identical.
let (left, right): ([Float], [Float]) = try renderStereo(spread: 0.0)
#expect(hasNonSilentOutput(left))
#expect(ssd(left, right) == 0, "spread 0 should collapse to mono (L == R)")
}
@Test func spreadWidensTheImage() throws {
// At full spread the spectrum fans across the field → channels differ.
let (left, right): ([Float], [Float]) = try renderStereo(spread: 1.0)
#expect(ssd(left, right) > 0, "full spread should make L and R differ")
}
}
/// Routes two mono board buses to hardware left (0) and right (1) so a widener's channels can be
/// captured separately by `readStereoCAF`.
@MainActor
private final class DiffuserStereoSplitMaster: SynthesizerBase {
private let left: Int
private let right: Int
init(left: Int, right: Int) {
self.left = left
self.right = right
super.init()
}
override func build() {
output(bus: 0, source: input(bus: left))
output(bus: 1, source: input(bus: right))
}
}
@@ -97,9 +97,9 @@ struct FeedbackDelayPedalTests {
#expect(ssd > 0, "short and long feedback produced identical output")
}
@Test func exposesTimeFeedbackAndToneKnobs() throws {
@Test func exposesTimeDecayAndToneKnobs() throws {
let pedal: FeedbackDelayPedal = FeedbackDelayPedal()
let labels: [String] = pedal.effectKnobs.map { $0.label }
#expect(labels == ["Time", "Feedback", "Tone"])
#expect(labels == ["Time", "Decay Time", "Tone"])
}
}
@@ -1,4 +1,4 @@
// MuTronPedalTests.swift
// MutantPedalTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
@@ -11,8 +11,8 @@ import LyrebirdUI
@testable import LyrebirdShoeGaze
@MainActor
@Suite("MuTronPedal")
struct MuTronPedalTests {
@Suite("MutantPedal")
struct MutantPedalTests {
@Test func buildsAndProducesNonSilentOutput() throws {
let renderDuration: Double = 0.1
@@ -27,7 +27,7 @@ struct MuTronPedalTests {
}
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
let pedal: MuTronPedal = MuTronPedal(
let pedal: MutantPedal = MutantPedal(
inputBus: srcBus.index,
outputBus: dstBus.index
)
@@ -40,7 +40,7 @@ struct MuTronPedalTests {
let samples: [Float] = readStereoCAF(url: url)
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "MuTronPedal produced silence")
#expect(hasNonSilentOutput(samples), "MutantPedal produced silence")
}
@Test func filterModesProduceDifferentOutput() throws {
@@ -62,7 +62,7 @@ struct MuTronPedalTests {
}
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
let pedal: MuTronPedal = MuTronPedal(
let pedal: MutantPedal = MutantPedal(
inputBus: srcBus.index,
outputBus: dstBus.index
)
@@ -96,27 +96,27 @@ struct MuTronPedalTests {
}
@Test func presetRoundTripPreservesSwitchPositions() throws {
let pedal: MuTronPedal = MuTronPedal()
let pedal: MutantPedal = MutantPedal()
pedal.mode = 2.0 // highpass
pedal.direction = 0.0 // down
let state: PedalState = pedal.captureState()
#expect(state.switchValues == [0.0, 2.0]) // [direction, mode]
let restored: MuTronPedal = MuTronPedal()
let restored: MutantPedal = MutantPedal()
restored.applyState(state)
#expect(restored.mode == 2.0)
#expect(restored.direction == 0.0)
}
@Test func exposesSensitivityAndResonanceKnobs() throws {
let pedal: MuTronPedal = MuTronPedal()
let pedal: MutantPedal = MutantPedal()
let labels: [String] = pedal.effectKnobs.map { $0.label }
#expect(labels == ["Sensitivity", "Resonance"])
}
@Test func exposesTwoStateSweepAndThreeStateModeSwitches() throws {
let pedal: MuTronPedal = MuTronPedal()
let pedal: MutantPedal = MutantPedal()
let switches: [PedalSwitch] = pedal.effectSwitches
#expect(switches.map { $0.label } == ["Sweep", "Mode"])
// Two-state sweep (Down/Up), three-state mode (LP/BP/HP).
@@ -143,7 +143,7 @@ struct MuTronPedalTests {
}
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
let pedal: MuTronPedal = MuTronPedal(
let pedal: MutantPedal = MutantPedal(
inputBus: srcBus.index,
outputBus: dstBus.index
)
@@ -0,0 +1,43 @@
// PedalInfoTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@MainActor
@Suite("Pedal info")
struct PedalInfoTests {
@Test func everyBuiltInPedalHasASummary() throws {
for type: String in PedalRegistry.builtIn.keys {
let pedal: Pedal? = PedalRegistry.makePedal(type: type)
#expect(pedal != nil, "registry could not build \(type)")
let summary: String = pedal?.summary ?? ""
#expect(!summary.isEmpty, "\(type) has an empty summary — every pedal must set one")
}
}
@Test func registrySummaryHelperMatchesInstance() throws {
#expect(PedalRegistry.summary(for: "Overdrive") == OverdrivePedal().summary)
#expect(PedalRegistry.summary(for: "Ring Modulator") == RingModulatorPedal().summary)
#expect(PedalRegistry.summary(for: "Nope") == "")
}
@Test func effectControlsExcludeCommonControls() throws {
// The info panel lists effect controls only; the common Mix / Level / bypass live in the
// base `Pedal` and must never appear in effectKnobs/effectSliders/effectSwitches.
let pedal: GraphicEQPedal = GraphicEQPedal()
let effectLabels: [String] =
pedal.effectKnobs.map { $0.label }
+ pedal.effectSliders.map { $0.label }
+ pedal.effectSwitches.map { $0.label }
#expect(!effectLabels.contains("Mix"))
#expect(!effectLabels.contains("Level"))
}
}
@@ -423,9 +423,12 @@ struct PresetTests {
// Apply the captured state (lightweight recall — no graph rebuild).
sg.applyState(captured)
// threshold is the first effectKnob; applyState calls knob.node.update(value)
// which sets the UIParamNode. The UIParamNode.value should now reflect the restored value.
let thresholdKnobValue: Double = compressor.knobs[0].node.value
// applyState calls knob.node.update(value) on each knob; the Threshold knob's
// UIParamNode.value should now reflect the restored value. Look up by label rather
// than position so the test is robust to knob additions.
let thresholdKnobValue: Double = try #require(
compressor.knobs.first(where: { $0.label == "Threshold" })?.node.value
)
#expect(
abs(thresholdKnobValue - knownThreshold) < 1e-9,
"threshold knob should be \(knownThreshold) after applyState, got \(thresholdKnobValue)"
@@ -0,0 +1,43 @@
// RigArchiveTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable import LyrebirdShoeGaze
@Suite("RigArchive")
struct RigArchiveTests {
private func makeEntry(_ name: String) -> RigEntry {
RigEntry(name: name, state: ShoeGazeState(boards: [BoardState(label: name, segments: [])]))
}
@Test func jsonRoundTripIsLossless() throws {
let archive: RigArchive = RigArchive(rigs: [makeEntry("A"), makeEntry("B")])
let encoder: JSONEncoder = JSONEncoder()
encoder.dateEncodingStrategy = .secondsSince1970
let decoder: JSONDecoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
let data: Data = try encoder.encode(archive)
let decoded: RigArchive = try decoder.decode(RigArchive.self, from: data)
#expect(decoded == archive)
#expect(decoded.version == rigArchiveFormatVersion)
#expect(decoded.rigs.count == 2)
}
@Test func emptyArchiveRoundTrips() throws {
let archive: RigArchive = RigArchive(rigs: [])
let encoder: JSONEncoder = JSONEncoder()
encoder.dateEncodingStrategy = .secondsSince1970
let decoder: JSONDecoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
let data: Data = try encoder.encode(archive)
let decoded: RigArchive = try decoder.decode(RigArchive.self, from: data)
#expect(decoded.rigs.isEmpty)
}
}
@@ -0,0 +1,55 @@
// RigEntryTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable import LyrebirdShoeGaze
@Suite("RigEntry")
struct RigEntryTests {
/// A minimal two-board rig state for snapshotting without an engine.
private func makeState() -> ShoeGazeState {
let board: BoardState = BoardState(label: "Lead", segments: [])
let other: BoardState = BoardState(label: "Clean", segments: [])
return ShoeGazeState(boards: [board, other])
}
@Test func jsonRoundTripIsLossless() throws {
let entry: RigEntry = RigEntry(name: "Ambient Wash", state: makeState())
let encoder: JSONEncoder = JSONEncoder()
encoder.dateEncodingStrategy = .secondsSince1970
let decoder: JSONDecoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
let data: Data = try encoder.encode(entry)
let decoded: RigEntry = try decoder.decode(RigEntry.self, from: data)
#expect(decoded == entry)
}
@Test func savedAtIsRoundedToWholeSeconds() {
let fractional: Date = Date(timeIntervalSince1970: 1_700_000_000.789)
let entry: RigEntry = RigEntry(name: "x", savedAt: fractional, state: makeState())
#expect(entry.savedAt.timeIntervalSince1970 == 1_700_000_001)
}
@Test func duplicatedGetsNewIdSameState() {
let original: RigEntry = RigEntry(name: "A", state: makeState())
let copy: RigEntry = original.duplicated(name: "A copy")
#expect(copy.id != original.id)
#expect(copy.name == "A copy")
#expect(copy.state == original.state)
}
@Test func renamedKeepsIdSameState() {
let original: RigEntry = RigEntry(name: "A", state: makeState())
let renamed: RigEntry = original.renamed(to: "B")
#expect(renamed.id == original.id)
#expect(renamed.name == "B")
#expect(renamed.state == original.state)
}
}
@@ -0,0 +1,172 @@
// RigLibraryStoreTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable import LyrebirdShoeGaze
@MainActor
@Suite("RigLibraryStore")
struct RigLibraryStoreTests {
/// A fresh, unique temp directory for an isolated, local (non-iCloud) store.
private func makeTempDirectory() -> URL {
let url: URL = FileManager.default.temporaryDirectory
.appendingPathComponent("RigLibraryTests-\(UUID().uuidString)", isDirectory: true)
return url
}
private func makeStore() async -> (RigLibraryStore, URL) {
let dir: URL = makeTempDirectory()
let store: RigLibraryStore = RigLibraryStore(directory: dir, isICloud: false)
await store.start()
return (store, dir)
}
private func makeEntry(_ name: String) -> RigEntry {
RigEntry(name: name, state: ShoeGazeState(boards: [BoardState(label: name, segments: [])]))
}
@Test func saveAddsEntryAndReloadsAcrossInstances() async throws {
let (store, dir): (RigLibraryStore, URL) = await makeStore()
defer { try? FileManager.default.removeItem(at: dir) }
try store.save(makeEntry("Ambient"))
try store.save(makeEntry("Crunch"))
#expect(store.entries.count == 2)
// Sorted by name, case-insensitive.
#expect(store.entries.map(\.name) == ["Ambient", "Crunch"])
store.flushPendingWrites()
// A fresh store over the same directory sees the persisted files.
let reopened: RigLibraryStore = RigLibraryStore(directory: dir, isICloud: false)
await reopened.start()
#expect(reopened.entries.count == 2)
#expect(reopened.entries.map(\.name) == ["Ambient", "Crunch"])
}
@Test func saveSameIdReplacesInPlace() async throws {
let (store, dir): (RigLibraryStore, URL) = await makeStore()
defer { try? FileManager.default.removeItem(at: dir) }
let entry: RigEntry = makeEntry("Original")
try store.save(entry)
// Overwrite under the same id with a new name — no duplicate file should remain.
try store.save(entry.renamed(to: "Renamed"))
#expect(store.entries.count == 1)
#expect(store.entries.first?.name == "Renamed")
store.flushPendingWrites()
let files: [URL] = try FileManager.default.contentsOfDirectory(
at: dir, includingPropertiesForKeys: nil
).filter { $0.pathExtension == "json" }
#expect(files.count == 1, "rename must not leave the old-name file behind")
}
@Test func renameKeepsIdChangesName() async throws {
let (store, dir): (RigLibraryStore, URL) = await makeStore()
defer { try? FileManager.default.removeItem(at: dir) }
let entry: RigEntry = makeEntry("Before")
try store.save(entry)
let renamed: RigEntry = try store.rename(entry, to: "After")
#expect(renamed.id == entry.id)
#expect(store.entries.map(\.name) == ["After"])
store.flushPendingWrites()
}
@Test func duplicateCreatesIndependentEntry() async throws {
let (store, dir): (RigLibraryStore, URL) = await makeStore()
defer { try? FileManager.default.removeItem(at: dir) }
let entry: RigEntry = makeEntry("Base")
try store.save(entry)
let copy: RigEntry = try store.duplicate(entry, newName: "Base 2")
#expect(copy.id != entry.id)
#expect(store.entries.count == 2)
store.flushPendingWrites()
}
@Test func deleteRemovesFileAndEntry() async throws {
let (store, dir): (RigLibraryStore, URL) = await makeStore()
defer { try? FileManager.default.removeItem(at: dir) }
let entry: RigEntry = makeEntry("Doomed")
try store.save(entry)
try store.delete(entry)
#expect(store.entries.isEmpty)
store.flushPendingWrites()
let files: [URL] = try FileManager.default.contentsOfDirectory(
at: dir, includingPropertiesForKeys: nil
).filter { $0.pathExtension == "json" }
#expect(files.isEmpty)
}
@Test func eraseAllClearsLibrary() async throws {
let (store, dir): (RigLibraryStore, URL) = await makeStore()
defer { try? FileManager.default.removeItem(at: dir) }
try store.save(makeEntry("A"))
try store.save(makeEntry("B"))
try store.save(makeEntry("C"))
try store.eraseAll()
#expect(store.entries.isEmpty)
store.flushPendingWrites()
let reopened: RigLibraryStore = RigLibraryStore(directory: dir, isICloud: false)
await reopened.start()
#expect(reopened.entries.isEmpty)
}
@Test func exportThenImportRoundTrips() async throws {
let (store, dir): (RigLibraryStore, URL) = await makeStore()
defer { try? FileManager.default.removeItem(at: dir) }
try store.save(makeEntry("One"))
try store.save(makeEntry("Two"))
let archiveData: Data = try store.exportArchiveData()
// Import into a fresh, empty store.
let (other, otherDir): (RigLibraryStore, URL) = await makeStore()
defer { try? FileManager.default.removeItem(at: otherDir) }
let added: Int = try other.importArchive(from: archiveData)
#expect(added == 2)
#expect(other.entries.map(\.name) == ["One", "Two"])
store.flushPendingWrites()
other.flushPendingWrites()
}
@Test func importColludingIdGetsFreshId() async throws {
let (store, dir): (RigLibraryStore, URL) = await makeStore()
defer { try? FileManager.default.removeItem(at: dir) }
let entry: RigEntry = makeEntry("Shared")
try store.save(entry)
// An archive carrying the SAME id must not overwrite the existing rig on import.
let archive: RigArchive = RigArchive(rigs: [entry])
let data: Data = try JSONEncoder().encode(archive)
let added: Int = try store.importArchive(from: data)
#expect(added == 1)
#expect(store.entries.count == 2, "colliding id should be imported as a new entry")
store.flushPendingWrites()
}
@Test func importLegacySingleRigFile() async throws {
let (store, dir): (RigLibraryStore, URL) = await makeStore()
defer { try? FileManager.default.removeItem(at: dir) }
// A legacy file is a bare ShoeGazeState (no `rigs` array).
let legacyState: ShoeGazeState = ShoeGazeState(boards: [BoardState(label: "Legacy", segments: [])])
let data: Data = try JSONEncoder().encode(legacyState)
let added: Int = try store.importArchive(from: data, legacyRigName: "Recovered")
#expect(added == 1)
#expect(store.entries.first?.name == "Recovered")
store.flushPendingWrites()
}
}
@@ -0,0 +1,52 @@
// RigStoreTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@MainActor
@Suite("RigStore")
struct RigStoreTests {
@Test func savesAndRestoresAcrossInstances() throws {
RigStore.clear()
defer { RigStore.clear() }
// Build a rig and autosave it.
let (engineA, urlA): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 64)
defer { try? FileManager.default.removeItem(at: urlA) }
let a: ShoeGaze = ShoeGaze(engine: engineA)
let lead: PedalBoard = try a.addBoard()
lead.label = "Lead"
try a.appendPedal(.overdrive, to: lead)
try a.finalizeBoard(lead)
let clean: PedalBoard = try a.addBoard()
clean.label = "Clean"
try a.appendPedal(.graphicEQ, to: clean)
try a.finalizeBoard(clean)
#expect(RigStore.save(a))
// A fresh, boardless instance restores the autosaved rig.
let (engineB, urlB): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 64)
defer { try? FileManager.default.removeItem(at: urlB) }
let b: ShoeGaze = ShoeGaze(engine: engineB)
#expect(RigStore.restore(into: b))
#expect(b.boards.count == 2)
#expect(b.boards.first?.label == "Lead")
#expect(b.boards.last?.label == "Clean")
}
@Test func restoreReturnsFalseWhenNoAutosave() throws {
RigStore.clear()
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 64)
defer { try? FileManager.default.removeItem(at: url) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
#expect(!RigStore.restore(into: sg), "restore should report nothing to load after clear()")
}
}
@@ -0,0 +1,58 @@
// RingModulatorPedalTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@MainActor
@Suite("RingModulatorPedal")
struct RingModulatorPedalTests {
private func render(frequency: Double) throws -> [Float] {
let renderDuration: Double = 0.1
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration, numAudioBuses: 64)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(dstBus)
}
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
let pedal: RingModulatorPedal = RingModulatorPedal(inputBus: srcBus.index, outputBus: dstBus.index)
pedal.frequency = frequency
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(source)
try engine.add(pedal, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(pedal))
try engine.start()
return readStereoCAF(url: url)
}
@Test func buildsAndProducesNonSilentOutput() throws {
let samples: [Float] = try render(frequency: 220.0)
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "RingModulatorPedal produced silence")
}
@Test func frequencyChangesOutput() throws {
let low: [Float] = try render(frequency: 100.0)
let high: [Float] = try render(frequency: 800.0)
#expect(hasNonSilentOutput(low) && hasNonSilentOutput(high))
let skip: Int = 1024, window: Int = 2048
guard low.count >= skip + window, high.count >= skip + window else { return }
let ssd: Double = zip(low[skip..<(skip + window)], high[skip..<(skip + window)]).reduce(0.0) { acc, pair in
let d: Double = Double(pair.0 - pair.1); return acc + d * d
}
#expect(ssd > 0, "carrier frequency had no effect on output")
}
}
@@ -39,6 +39,236 @@ struct ShoeGazeMultiBoardTests {
#expect(shoeGaze.boards.count == 2)
}
@Test func rigSnapshotRestoresAcrossEnginesWithInputChannel() throws {
// Backs the iOS "enable live input" rebuild: a rig captured on a 0-input engine must
// restore onto a freshly built 1-input engine, and live input must then be selectable.
let renderDuration: Double = 0.05
// Source engine: no input channels (the iOS default before live input is enabled).
let (engineA, urlA): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numInputChannels: 0,
numAudioBuses: 64
)
defer { try? FileManager.default.removeItem(at: urlA) }
let shoeGazeA: ShoeGaze = ShoeGaze(engine: engineA)
let board1: PedalBoard = try shoeGazeA.addBoard()
board1.label = "Lead"
try shoeGazeA.appendPedal(.overdrive, to: board1)
try shoeGazeA.finalizeBoard(board1)
let board2: PedalBoard = try shoeGazeA.addBoard()
board2.label = "Clean"
try shoeGazeA.appendPedal(.graphicEQ, to: board2)
try shoeGazeA.finalizeBoard(board2)
let snapshot: Data = try shoeGazeA.rigData()
// Destination engine: one input channel (the rebuilt engine for live input).
let (engineB, urlB): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numInputChannels: 1,
numAudioBuses: 64
)
defer { try? FileManager.default.removeItem(at: urlB) }
let shoeGazeB: ShoeGaze = ShoeGaze(engine: engineB)
try shoeGazeB.loadRig(from: snapshot)
// The rig round-trips: same board count and labels.
#expect(shoeGazeB.boards.count == 2)
#expect(shoeGazeB.boards.first?.label == "Lead")
#expect(shoeGazeB.boards.last?.label == "Clean")
// Live input is now selectable on the rebuilt engine.
#expect(throws: Never.self) {
try shoeGazeB.setInputSource(.liveInput(channel: 0))
}
}
@Test func testLoopBoardsShareGlobalSourceViaTaps() throws {
// In .testLoop mode every board reads one shared global source through a TestLoopTap,
// rather than owning an independently-phased TestLoopSource — this is what keeps the
// boards phase-locked. Verify the head input node of each board is a tap, and that a
// board removal leaves the others (and their signal) intact.
let renderDuration: Double = 0.05
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: 64
)
defer { try? FileManager.default.removeItem(at: url) }
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
let board1: PedalBoard = try shoeGaze.addBoard()
try board1.add(OverdrivePedal())
try shoeGaze.finalizeBoard(board1)
let board2: PedalBoard = try shoeGaze.addBoard()
try board2.add(DelayPedal())
try shoeGaze.finalizeBoard(board2)
// Both boards feed from a shared tap, not their own source.
#expect(board1.headInputNode != nil)
#expect(board1.headInputNode is TestLoopTap)
#expect(board2.headInputNode is TestLoopTap)
#expect(!(board1.headInputNode is TestLoopSource))
// Removing one board does not disturb the other's input node.
shoeGaze.removeBoard(board1)
#expect(shoeGaze.boards.count == 1)
#expect(board2.headInputNode is TestLoopTap)
}
@Test func teardownReleasesGlobalTestBusForReuse() throws {
// teardown() must remove the global source AND release its bus, so a later addBoard()
// can re-allocate cleanly (guards against the global test bus being leaked).
let renderDuration: Double = 0.05
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: 16
)
defer { try? FileManager.default.removeItem(at: url) }
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
// Repeatedly build a board then tear the whole rig down. With a small bus pool, a leaked
// global test bus on each cycle would eventually exhaust the allocator and throw.
for _ in 0 ..< 8 {
let board: PedalBoard = try shoeGaze.addBoard()
try board.add(OverdrivePedal())
try shoeGaze.finalizeBoard(board)
#expect(board.headInputNode is TestLoopTap)
shoeGaze.teardown()
#expect(shoeGaze.boards.isEmpty)
}
// Still able to build after all the teardown cycles.
let finalBoard: PedalBoard = try shoeGaze.addBoard()
#expect(finalBoard.headInputNode is TestLoopTap)
}
@Test func activeBoardIndexTracksReorderAndRemoval() throws {
let renderDuration: Double = 0.05
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: 64
)
defer { try? FileManager.default.removeItem(at: url) }
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
let board1: PedalBoard = try shoeGaze.addBoard()
try board1.add(OverdrivePedal())
try shoeGaze.finalizeBoard(board1)
let board2: PedalBoard = try shoeGaze.addBoard()
try board2.add(DelayPedal())
try shoeGaze.finalizeBoard(board2)
let board3: PedalBoard = try shoeGaze.addBoard()
try board3.add(OverdrivePedal())
try shoeGaze.finalizeBoard(board3)
// Solo board3 (index 2), then move it to the front — index must follow the board.
shoeGaze.soloBoard(board3, crossfadeSeconds: 0.0)
#expect(shoeGaze.activeBoardIndex == 2)
shoeGaze.moveBoard(board3, to: 0)
#expect(shoeGaze.boards.first === board3)
#expect(shoeGaze.activeBoardIndex == 0)
// Now order is [board3, board1, board2], soloed index 0. Removing a later board
// leaves the soloed index unchanged.
shoeGaze.removeBoard(board2)
#expect(shoeGaze.activeBoardIndex == 0)
// Re-solo board1 (now index 1), then remove the earlier board3 (index 0):
// the soloed index shifts down to 0.
shoeGaze.soloBoard(board1, crossfadeSeconds: 0.0)
#expect(shoeGaze.activeBoardIndex == 1)
shoeGaze.removeBoard(board3)
#expect(shoeGaze.activeBoardIndex == 0)
// Removing the soloed board clears the index.
shoeGaze.removeBoard(board1)
#expect(shoeGaze.activeBoardIndex == nil)
}
@Test func soloBlendAndAllControlBoardAudibility() throws {
let renderDuration: Double = 0.05
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: 64
)
defer { try? FileManager.default.removeItem(at: url) }
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
let board1: PedalBoard = try shoeGaze.addBoard()
try board1.add(OverdrivePedal())
try shoeGaze.finalizeBoard(board1)
let board2: PedalBoard = try shoeGaze.addBoard()
try board2.add(DelayPedal())
try shoeGaze.finalizeBoard(board2)
let board3: PedalBoard = try shoeGaze.addBoard()
try board3.add(OverdrivePedal())
try shoeGaze.finalizeBoard(board3)
let instantCrossfade: Double = 0.0
// Default: every board audible, no solo.
#expect(shoeGaze.isBoardAudible(board1))
#expect(shoeGaze.isBoardAudible(board2))
#expect(shoeGaze.isBoardAudible(board3))
#expect(shoeGaze.activeBoardIndex == nil)
// Solo board2 — exclusive.
shoeGaze.soloBoard(board2, crossfadeSeconds: instantCrossfade)
#expect(!shoeGaze.isBoardAudible(board1))
#expect(shoeGaze.isBoardAudible(board2))
#expect(!shoeGaze.isBoardAudible(board3))
#expect(shoeGaze.activeBoardIndex == 1)
// Blend: re-enable board1 without disturbing the others, and clear the solo index.
shoeGaze.setBoard(board1, audible: true, crossfadeSeconds: instantCrossfade)
#expect(shoeGaze.isBoardAudible(board1))
#expect(shoeGaze.isBoardAudible(board2))
#expect(!shoeGaze.isBoardAudible(board3))
#expect(shoeGaze.activeBoardIndex == nil)
// Silence a single board.
shoeGaze.setBoard(board1, audible: false, crossfadeSeconds: instantCrossfade)
#expect(!shoeGaze.isBoardAudible(board1))
#expect(shoeGaze.isBoardAudible(board2))
// All back to summed.
shoeGaze.selectAllBoards(crossfadeSeconds: instantCrossfade)
#expect(shoeGaze.isBoardAudible(board1))
#expect(shoeGaze.isBoardAudible(board2))
#expect(shoeGaze.isBoardAudible(board3))
#expect(shoeGaze.activeBoardIndex == nil)
}
@Test func setBoardIgnoresUnmanagedBoard() throws {
let renderDuration: Double = 0.05
let (engineA, urlA): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration, numAudioBuses: 64)
let (engineB, urlB): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration, numAudioBuses: 64)
defer {
try? FileManager.default.removeItem(at: urlA)
try? FileManager.default.removeItem(at: urlB)
}
let shoeGazeA: ShoeGaze = ShoeGaze(engine: engineA)
let shoeGazeB: ShoeGaze = ShoeGaze(engine: engineB)
let boardA: PedalBoard = try shoeGazeA.addBoard()
try boardA.add(OverdrivePedal())
try shoeGazeA.finalizeBoard(boardA)
let boardB: PedalBoard = try shoeGazeB.addBoard()
try boardB.add(DelayPedal())
try shoeGazeB.finalizeBoard(boardB)
// Toggling a board not owned by this manager is a no-op and must not change state.
shoeGazeA.setBoard(boardB, audible: false, crossfadeSeconds: 0.0)
#expect(shoeGazeA.isBoardAudible(boardA))
#expect(shoeGazeB.isBoardAudible(boardB))
}
@Test func removeBoardLeavesOtherBoards() throws {
let renderDuration: Double = 0.05
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
@@ -0,0 +1,64 @@
// SustainerPedalTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@MainActor
@Suite("SustainerPedal")
struct SustainerPedalTests {
private func render(configure: (SustainerPedal) -> Void = { _ in }) throws -> [Float] {
let renderDuration: Double = 0.1
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration, numAudioBuses: 64)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(dstBus)
}
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
let pedal: SustainerPedal = SustainerPedal(inputBus: srcBus.index, outputBus: dstBus.index)
configure(pedal)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(source)
try engine.add(pedal, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(pedal))
try engine.start()
return readStereoCAF(url: url)
}
@Test func buildsAndProducesNonSilentOutput() throws {
let samples: [Float] = try render()
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "SustainerPedal produced silence")
}
@Test func exposesSustainAndToneKnobs() throws {
let pedal: SustainerPedal = SustainerPedal()
#expect(pedal.effectKnobs.map { $0.label } == ["Sustain", "Tone"])
}
@Test func sustainAmountChangesOutput() throws {
// Min vs max sustain drive the compressor very differently → measurably different output.
let gentle: [Float] = try render { $0.sustain = 0.0 }
let squashed: [Float] = try render { $0.sustain = 10.0 }
#expect(hasNonSilentOutput(gentle) && hasNonSilentOutput(squashed))
let skip: Int = 1024, window: Int = 2048
guard gentle.count >= skip + window, squashed.count >= skip + window else { return }
let ssd: Double = zip(gentle[skip..<(skip + window)], squashed[skip..<(skip + window)]).reduce(0.0) { acc, pair in
let d: Double = Double(pair.0 - pair.1); return acc + d * d
}
#expect(ssd > 0, "sustain knob had no effect on output")
}
}
+8
View File
@@ -0,0 +1,8 @@
# Screenshots
Place README screenshots here as PNG:
- `builder-macos.png` — the macOS builder
- `board-mixer.png` — the multi-board mixer bar
Referenced by `README.md` via relative paths.
Binary file not shown.

After

Width:  |  Height:  |  Size: 884 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

+34
View File
@@ -0,0 +1,34 @@
# 1.1 — Chorus pedal (true stereo)
## Why distinct from Modulation
`ModulationPedal` already wraps Lyrebird's `Chorus.Audio` and **sums to mono**
(`SumChannels`). The new **Chorus** keeps the signal **stereo** (a `widener` pedal) and
exposes more control — a lusher, wider voice than the mono Modulation classic. Keep both.
## Implementation
`Sources/LyrebirdShoeGaze/Pedals/ChorusPedal.swift`
- `override var channelKind: PedalChannelKind { .widener }`
- Override `wideEffect(_ dry:) -> (left:right:)` (not `effect`): build one
`Chorus.Audio(input: dry, delayTime:, depth: $depth, rate: $rate, mix: 1.0,
sampleRate: sampleRate, maxDelayTime:)` and return its two channels as L/R
(do **not** `SumChannels`).
- Knobs (`effectKnobs`): `rate` 0.05–6 Hz (def ~0.8), `depth` 0.0005–0.01 s (def ~0.003).
Wet/dry via the base `mix` (`initialMix` ~0.5).
- Constants: `delayTime` ~0.025 s, `maxDelayTime` ~0.1 s (match Modulation).
## Wiring
- `PedalRegistry.builtIn["Chorus"] = { ChorusPedal() }`
- `PedalType.chorus = PedalType("Chorus")`
- `PedalView` enclosure color case `"Chorus"`
- `PedalPaletteView.preferredOrder` — near Modulation / Phaser
- `summary` override (see info-UI plan)
## Tests (`Tests/LyrebirdShoeGazeTests/ChorusPedalTests.swift`)
- builds + non-silent
- stereo: L channel ≠ R channel (the point of the pedal)
- rate and depth each change the output
## Open question
Keep both Modulation (mono) and Chorus (stereo) — recommended. Alternative: rename
Modulation → "Vibrato". Not doing that here.
+40
View File
@@ -0,0 +1,40 @@
# 1.1 — Pedal info UI (description + control ranges)
Show a short description of each pedal in the picker, and an info button on the pedal that
opens a panel with the description and the **effect controls** (knobs / sliders / switches)
plus their value ranges — excluding the common Mix / Level / bypass controls.
## Model (core, `LyrebirdShoeGaze`)
- Add to `Pedal`: `open var summary: String { "" }` — one-line description, overridden by
every pedal. Single source of truth.
- `PedalRegistry.summary(for displayName: String) -> String` for the palette: instantiates
`builtIn[name]?()` and reads `.summary`. No `engine.add`, so `build()` never runs — only a
cheap object alloc. Cache in the palette view.
- (Optional stretch) richer rows: add `detail: String?` and/or `unit: String?` to
`PedalKnob` / `PedalSlider` / `PedalSwitch`. Not required — `range` / `options` already
carry enough to show ranges.
## Palette (`PedalPaletteView`)
- Row → `VStack(alignment: .leading)`: name (callout) + `summary` (caption2, secondary,
~2 lines). Keep the `+` glyph and `.draggable`.
## Pedal info affordance (`PedalView`)
- Small **ⓘ button** in the name-plate (top-right of the enclosure header).
- Tap → `.sheet` / `.popover` on its **own anchor node** (one presentation per node — same
pattern as the file pickers) presenting a new `PedalInfoView(pedal:)`.
## `PedalInfoView` (`LyrebirdShoeGazeUI`)
- Title = `pedal.displayName`; body = `pedal.summary`.
- Controls list from `effectKnobs` + `effectSliders` + `effectSwitches` **only** (not
`knobs`, which includes Mix/Level; not bypass):
- knob / slider → `label` + range, e.g. `"200 – 8000"` (raw range; add `unit` later).
- switch → `label` + option titles.
## Wiring
- Override `summary` on **all** pedals (short sentences).
- Going forward, every new pedal MUST set `summary` — see CLAUDE.md.
## Tests
- every entry in `PedalRegistry.builtIn` produces a pedal with non-empty `summary`.
- `PedalInfoView` (or a helper that builds its rows) lists exactly the effect controls,
not the common three.
+31
View File
@@ -0,0 +1,31 @@
# 1.1 — Ring Modulator pedal
Multiplies the signal by a tunable carrier → metallic / bell / robot sidebands (sum &
difference of input and carrier). Classic ring mod = `dry × carrier` — no dedicated
Lyrebird generator needed. (`Ring1–4` are SC math variants; `FrequencyShifter` is SSB,
a possible stretch mode.)
## Implementation
`Sources/LyrebirdShoeGaze/Pedals/RingModulatorPedal.swift`
- `effect`: `let carrier = OscSin.Audio(freq: $frequency); return dry * carrier`
- Knobs:
- **`frequency`** carrier in Hz. Range ~**20–2000** (def ~220). <~30 Hz ≈ tremolo/AM;
audio range = classic ring mod.
- wet/dry via inherited **`mix`** (`initialMix` ~0.5 — harsh, keep dry present).
- **Optional waveform switch** (`PedalSwitch`): Sine / Square carrier (square = more
sidebands, harsher) — square via `LFSquare`/`OscSquare`. If added, preset round-trip test.
- **Stretch — Mode switch (Ring / Shift):** add an SSB pitch mode wrapping Lyrebird's
`FrequencyShifter`. Base pass = Ring only; Shift is a follow-up.
## Wiring
- `PedalRegistry.builtIn["Ring Modulator"] = { RingModulatorPedal() }`
- `PedalType.ringModulator = PedalType("Ring Modulator")`
- enclosure color, palette order (group with Phaser / Mutant "filter / weird" section)
- `summary` override, e.g. *"Multiplies your signal by a tunable carrier for metallic,
bell-like, and robotic tones."*
## Tests (`Tests/LyrebirdShoeGazeTests/RingModulatorPedalTests.swift`)
- builds + non-silent
- frequency change alters output (e.g. 100 Hz vs 800 Hz windows differ)
- (if switch added) square vs sine differ; preset round-trip of the switch
+33
View File
@@ -0,0 +1,33 @@
# 1.1 — Sustainer pedal
A one-knob sustain: heavy compression + makeup gain to hold notes, distinct from the
`Compressor` pedal (which exposes threshold/ratio directly).
## Implementation
`Sources/LyrebirdShoeGaze/Pedals/SustainerPedal.swift`
- `effect`: `Compressor.Audio(in: dry, threshold:, ratio:, attack: ~0.005,
release: ~0.4, kneeWidth: 0, makeupGain:)`.
- **`sustain` knob (0–10, def ~5)** — the single perceptual control. Maps internally:
- threshold: `-6 dB → -36 dB` as sustain rises
- ratio: `2 → 10`
- makeupGain: tracks the added gain reduction (so output stays even)
Implement the map with `LinLin` on the `$sustain` node (or fold into Compressor's
`ValidGeneratorInput` params via arithmetic on `$sustain`).
- **`tone` knob (optional)** — `RBJLowPass.Audio(input:, freq: $tone, q: 0.707)` to round the squashed top end. Range ~800–8000 Hz.
- `level` (inherited) for output trim. `initialMix` = 1.0 (in-line).
- **Stretch — floor/gate:** reuse the NoiseGate idea (`AmplitudeFollower` → `Schmidt` →
`LinLin` floor → `Lag` → ×) so infinite sustain doesn't surface hiss. Optional knob
`floor`, or a fixed gentle gate. Defer if it complicates the one-knob feel.
## Wiring
- `PedalRegistry.builtIn["Sustainer"] = { SustainerPedal() }`
- `PedalType.sustainer = PedalType("Sustainer")`
- enclosure color, palette order (near Compressor / Limiter)
- `summary` override
## Tests (`Tests/LyrebirdShoeGazeTests/SustainerPedalTests.swift`)
- builds + non-silent
- sustain knob changes dynamics: low vs high sustain → measurable RMS/level difference on
a decaying input window
- knob list assertion
+79
View File
@@ -0,0 +1,79 @@
# Rig Library (iCloud-synced rigs)
Replaces the single hand-saved rig file with a managed **library of named rigs** persisted in app
storage and synced across devices and both apps via a shared iCloud container. A rig is a whole
session (`ShoeGazeState`) and may contain multiple boards.
## What shipped
**Core (`LyrebirdShoeGaze/Presets/`)**
- `RigEntry` — a named, timestamped `ShoeGazeState` (rig-level analogue of `BoardVersion`).
- `RigArchive` — a portable bundle of many `RigEntry` in one JSON file (Export/Import Archive). A
legacy single-rig file (bare `ShoeGazeState`) imports as a one-rig archive.
- `RigLibraryLocation` — resolves the library directory: shared iCloud container `Documents/Rigs/`
when available, else local Application Support (`LyrebirdShoeGaze/Rigs/`).
- `RigLibraryStore` (`@MainActor @Observable`) — one JSON file per rig
(`<sanitized-name>-<uuid>.json`); save/delete/duplicate/rename/eraseAll/import/export. iCloud
reads/writes are coordinated via `NSFileCoordinator`; remote changes are watched with
`NSMetadataQuery` so a rig saved on one device appears on another live.
- `ShoeGaze.loadRig(from: ShoeGazeState)` overload + `ShoeGaze.captureEntry(name:id:)`.
- `sanitizePresetFilename` factored out of `BoardVersionStore` and shared.
**UI (`LyrebirdShoeGazeUI/`)**
- `RigLibrarySidebarView` — persistent left listing; rows show name + timestamp, context menu
(Rename / Duplicate / Delete), bottom bar (New / Save / Save As / ⋯ → Import / Export / Erase
All), and an iCloud status glyph.
- `RigNamePrompt` — shared name-entry alert (New / Save As / Rename / Duplicate).
- `RigLibraryBootstrap` — one-call shell setup: resolve location, start the store, seed it from the
working rig on first run, resolve the launch highlight.
- `ShoeGazeBuilderView` gains the sidebar; selecting a rig **replaces** the current session
(engine stopped/restarted around the rebuild). When the current rig has unsaved changes
(`captureState()` differs from its library entry), switching first prompts **Save /
Don't Save / Cancel** (both platforms). The old single-rig Save/Load is gone; the File menu /
sidebar now do whole-library **Archive** import/export.
**Shells / entitlements**
- macOS `AppDelegate` and iOS app model own + start the store and pass it to the view; macOS File
menu = New Rig (⌘N), Save Rig (⌘S), Export/Import Archive (⌘E/⌘I). The per-rig menu items forward
to the builder view via `Notification.Name` (`shoeGazeNewRig` / `shoeGazeSaveRig`) so naming
prompts and the current-rig highlight stay in the view that owns that state.
- Both builder targets carry the iCloud entitlement for container
`iCloud.net.realizedsound.ShoeGazeData`; `NSUbiquitousContainers` exposes `Documents/Rigs` in the
Files app.
## Manual provisioning (required before iCloud sync works)
Code is in place but signing is not provisionable from here. In Xcode, for **both** builder targets
(`ShoeGazeBuilder`, `ShoeGazeBuilderiOS`), under Signing & Capabilities:
1. Confirm the **iCloud** capability is present with **iCloud Documents** checked and the container
`iCloud.net.realizedsound.ShoeGazeData` selected (entitlement files already declare it).
2. Register that container on **both** App IDs in the developer account (same Team `HE5VJFE9E4`).
3. Build signed to a device/Mac signed into iCloud to verify cross-device sync.
If iCloud is unavailable the library transparently falls back to local storage (no sync) — the app
still works; the sidebar shows the `icloud.slash` glyph.
## Notes / follow-ups
- Editing a loaded rig does not auto-save to its library entry — Save is explicit. `RigStore`
autosave still preserves unsaved working state across restarts.
### Known limitations / deferred (from pre-PR review)
- **Off-main I/O end to end.** Save/delete/erase update the in-memory `entries` on the main actor
instantly (UI never blocks) and run the file write/delete — including `NSFileCoordinator` — on a
serial background queue (`ioQueue`). Location resolution (`RigLibraryLocation.resolve()`, the
blocking ubiquity lookup) and the initial/refresh *reads* now also run off the main thread:
`RigLibraryStore` constructs instantly with a local placeholder, and `await start()` resolves the
real iCloud-or-local location, loads via `ioQueue`, then sets `isLoaded`. Reads share `ioQueue`
with writes, so a reload never drops a just-saved rig. `flushPendingWrites()` drains the queue
(tests, app termination / iOS background).
- **Loading + correct first-run seeding.** The sidebar shows a "Loading…" state until `isLoaded`.
`RigLibraryBootstrap.start(_:seedFrom:)` seeds the working rig as "Default" **only after** the
(possibly iCloud) library has loaded and is still empty — so a first launch on a device that
already has synced rigs does not create a duplicate "Default" everywhere. The builder restores the
persisted current-rig highlight once `isLoaded` flips true.
- **`eraseAll()`** clears the in-memory list even if a file deletion fails (it still throws the
first error). A re-`start()` re-scans and re-surfaces any undeleted rigs, so state self-heals.
- Possible later work: conflict UI for simultaneous multi-device edits; the async-resolve redesign
above.