7 Commits

Author SHA1 Message Date
josh f61961b90b Consolidate 2.1.1 into 2.1.0 release notes
Fold the MIDI-CC-vs-tempo-sync note into the single 2.1.0 entry (CHANGELOG + RELEASES);
the CC guard ships as part of 2.1.0 rather than a separate 2.1.1. No code change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 10:14:42 -07:00
josh 7e39842eb2 2.1.1: ignore MIDI CC on tempo-synced parameters
A CC bound to a pedal parameter locked to a note division is now ignored while
synced — the value is tempo-derived and a CC write would be overwritten on the next
tempo change. Index-stable: ccMappableControls is unchanged (persisted bindings resolve
by position), and only the CC *write* is skipped. MIDIController.applyCC checks
Pedal.isNodeTempoSynced(_:) (node-identity match against tempoSyncableParams) and
skips the update; the binding stays intact and resumes control once set back to Free.

Test: MIDIControllerCCTests.ccIsIgnoredWhileParameterIsTempoSynced. 455 tests pass.
Docs: CHANGELOG.md, RELEASES.md, plan MIDI section updated to "implemented".

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 09:00:24 -07:00
josh 2772abdc56 Release 2.1.0: tempo-synced pedal parameters, editable BPM, control mapping badges
Tempo sync
- Lock a delay time or modulation LFO rate to a note division (whole..sixteenth,
  dotted, triplet) of the shared clock. Value is derived from the tempo and follows
  tap tempo, the stepper, the editable BPM field, and MIDI.
- Delay time: Delay, FeedbackDelay, PingPong, ReverseDelay, MultiTap (per tap).
  LFO rate (inverse mapping): Tremolo, Vibrato, Chorus, Flanger, Phaser, Modulation.
- Core types NoteDivision / TempoSync / TempoSyncableParam; Pedal.tempoSyncableParams /
  tempoSync / applyTempoSync / setSync; ShoeGaze.setBpm broadcast recomputes all pedals;
  tempoSync persisted in PedalState (lenient decode) and recomputed on load + recall.
- Observable TempoSyncRevision so the sync badge refreshes on any state-change path.

UI
- Division picker with drawn music-notation glyphs (NoteGlyphView + rasterized cache):
  noteheads, stems, flags, augmentation dot, bracketed 3 for triplets. Presented as a
  height-capped popover so it stays on-screen on iOS.
- Editable BPM text field: integer-only, live-filtered, clamped 30-300, commit on
  return / Done / blur.
- Divisions that clamp at the current tempo are disabled in the picker; an active
  clamped sync shows a warning marker.
- In-context control mapping badges (PC / CC / KEY) per pedal control, with a legend.

Delays
- Maximum delay time raised to 5 s across the delay pedals (was 1-2 s).

Docs: CHANGELOG.md, RELEASES.md, docs/plans/2.2-tempo-synced-parameters.md.
All 454 tests pass; passed lyrebird_external_review (RT-safe, main-thread param writes).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 08:47:22 -07:00
josh a33d5488c9 Add computer-keyboard control mapping
Bind letter/digit keys (with Shift/Control/Option; Command reserved for
menu shortcuts) to the same rig toggle Actions a MIDI Program-Change
footswitch drives. Keys reuse MIDIController's perform(_:) dispatch via a
new .key learn target and ingestKey(_:modifiers:).

Key capture is platform-specific: macOS installs an AppKit
NSEvent.addLocalMonitorForEvents(.keyDown) monitor (SwiftUI .onKeyPress
only delivers to the focused view); iOS uses .onKeyPress with the root
made focusable/focused, reclaiming focus when a text-field modal closes.
Both gate on the first responder not being a text field so typing is
never hijacked, filter key-repeat, and reserve Command for the menu.

MIDIMap gains keys:[KeyBinding] and a KeyModifiers OptionSet, both with
tolerant Codable decode so old rigs (no keys / no modifiers) still load
with switches/ccs intact. The mapping sheet is unified: each switch row
shows its footswitch (PC) and key bindings with per-source learn/clear,
and the sheet is retitled "MIDI / Control Mapping".

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 15:03:12 -07:00
josh 2c2ce06797 plist updates 2026-07-05 22:42:00 -07:00
josh 8b72957502 Update RELEASES.md 2026-07-05 20:48:01 +00:00
josh e051521c04 Release 2.0.0: metronome, rig mute + shortcuts, set-list ordering, per-rig persistence
- Visual metronome tempo indicator (pendulum playhead) replacing the flashing LED
- Rig Mute (Cmd-Z) hard-silence, distinct from Bypass Rig; wired to header, board menu, MIDI
- Keyboard shortcuts: Cmd-1..9 board switch, Cmd-Shift-1..0 set-list rig load, Cmd-Z mute
  (macOS native menus + iOS/iPadOS hardware keyboards)
- Rig set-list ordering: drag or Move Up/Down in the picker; order saved and archive-portable
- Persist tempo, input selection, and engine I/O with a rig (I/O applied via opt-in
  applyChannelLayout, not forced on load)
- Fix archive import colliding set-list positions with existing rigs
- Remove ShoeGazeDemo / ShoeGazeiOSDemo apps and projects; keep the two Builder apps
- Bump marketing version to 2.0.0 on both Builder projects; pin Lyrebird 1.2.3
- Add CHANGELOG.md

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-05 12:30:45 -07:00
88 changed files with 3699 additions and 2248 deletions
+133
View File
@@ -0,0 +1,133 @@
# Changelog
All notable changes to ShoeGaze are recorded here. The format follows
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
[semantic versioning](https://semver.org/spec/v2.0.0.html).
## [2.1.0] — 2026-07-10
Tempo comes to the pedals. Delay times and modulation rates can lock to a note
division of the live tempo — a quarter-note delay, a dotted-eighth, an eighth-triplet
LFO — shown with real music-notation glyphs and following the tempo as it changes.
Delays reach further, the BPM is directly editable, and every mappable control shows
its MIDI / key binding right on the pedal.
### Added
- **Tempo-synced pedal parameters.** Lock a delay time or a modulation rate to a note
division — whole down to sixteenth, including dotted and triplet values — and it is
derived from the shared tempo, following tap tempo, the stepper, the BPM field, and
MIDI. Delay time on Delay, Feedback Delay, Ping-Pong, Reverse Delay, and each of
Multi-Tap's three taps; LFO rate on Tremolo, Vibrato, Chorus, Flanger, Phaser, and
Modulation. A MIDI CC bound to a synced parameter is ignored while it stays synced
(the tempo drives the value) and resumes control once the parameter is set to Free.
- **Note-value glyphs.** The division picker uses drawn music-notation glyphs —
noteheads, stems, flags, an augmentation dot for dotted values, and a bracketed "3"
over triplets — instead of text labels.
- **Editable BPM.** The tempo readout is now a text field: type a tempo directly
(integer only, clamped to 30–300 BPM). The stepper and tap tempo still work, and a
synced pedal follows a typed change immediately.
- **In-context control mapping.** Each pedal draws a small badge on every mappable
control showing its binding source — Program Change footswitch (PC), Control Change
expression (CC), or letter Key (KEY) — with a legend above the board. Completes the
computer-keyboard control mapping.
### Changed
- **Longer delays.** Maximum delay time raised to 5 seconds across the delay pedals
(previously 1–2 s), so tempo-synced values at slow tempos (whole and half notes) fit.
- Note divisions that would exceed a parameter's range at the current tempo are shown
disabled in the picker, and an active sync that has to clamp shows a warning marker.
### Compatibility
Additive: rigs saved before this release load unchanged (every parameter defaults to
"free"), and 2.1 rigs still open in older builds — the tempo-sync state is simply
ignored there.
## [2.0.0] — 2026-07-05
Major release. Performance-focused: a visual metronome, a real rig mute with
keyboard control, and rigs that remember their tempo, input, and I/O — plus a
saveable set-list order for hands-free switching between rigs live. The version
jumps to 2.0.0 to align ShoeGaze's numbering with the wider project family.
### Added
- **Visual metronome tempo indicator.** A horizontal playhead sweeps wall-to-wall
once per beat with pendulum easing (it slows into each beat so you can anticipate
it), fades toward center, and flashes a glow on the downbeat. Replaces the single
flashing LED.
- **Rig Mute (⌘Z).** A hard gate that silences the entire rig output — distinct from
Bypass Rig, which passes your dry signal through. Reachable from the header, the
per-board volume row, the macOS Board menu, and MIDI.
- **Keyboard shortcuts** (macOS native menus + iOS/iPadOS hardware keyboards):
- `⌘1`–`⌘9` — switch to / solo boards 1–9.
- `⌘⇧1`–`⌘⇧9` and `⌘⇧0` — load set-list rigs 1–10 in library order.
- `⌘Z` — toggle rig mute.
All are listed in the in-app Help.
- **macOS menus.** Board ▸ Mute Rig and Board ▸ Bypass Rig (with live state), and a
Rigs ▸ Set List submenu whose ten slots map to `⌘⇧1`–`⌘⇧0` and track the current
library order.
- **Set-list ordering.** Reorder rigs in the picker by dragging a row or via each
rig's Move Up / Move Down menu. The order is saved and travels with an exported
archive; the top ten map to the `⌘⇧` shortcuts.
- **Per-rig persistence.** A saved rig now also stores its tempo (BPM + enabled
state) and input selection. Engine input/output channel counts are saved too, and
applied on demand via `applyChannelLayout(from:)` rather than forced on every load.
### Changed
- The header "Mute rig" toggle — which actually only set the tuner-mutes-rig
preference — is now a real rig-mute button. The tuner preference is relabeled
**"Mute while tuning"**.
- The rig library now honors a manual set-list order instead of sorting by name/date.
New rigs append to the end; renaming a rig keeps its position.
### Fixed
- Importing a rig archive into a non-empty library no longer collides set-list
positions with existing rigs — imported rigs append in archive order.
### Removed
- The **ShoeGazeDemo** (macOS) and **ShoeGazeiOSDemo** (iOS) minimal-player apps and
their Xcode projects. Only the full **ShoeGazeBuilder** (macOS) and
**ShoeGazeBuilderiOS** (iPad) apps remain.
### Compatibility
- Despite the major-version bump, rig persistence is backward-compatible: the new
tempo / input / I/O / set-list fields are additive and optional. Rigs saved by
earlier versions load unchanged (missing fields are ignored), and rigs saved by
2.0.0 still open in older builds (the new keys are ignored there). The 2.0.0 bump
reflects the scope of new features and version alignment, not a format break.
## [1.5.0] — 2026-07-04
- Looper pedal, iPad/iOS layout rework, Lyrebird 1.2.3.
## [1.4.0] — 2026-07-01
- Maintenance and refinements.
## [1.3.0] — 2026-06-28
- Rig / board sharing via the `.shoegaze` document type.
## [1.2.0] — 2026-06-28
- Ten new pedals, iCloud rig library, builder UI rework.
## [1.1.1] — 2026-06-26
- Info-button placement and region-lane drag-drop fix.
## [1.1.0] — 2026-06-26
- Refinements over the initial release.
## [1.0.0] — 2026-06-24
- Initial ShoeGaze release.
@@ -163,7 +163,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 7;
CURRENT_PROJECT_VERSION = 8;
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 = 1.5;
MARKETING_VERSION = 2.0.0;
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 = 7;
CURRENT_PROJECT_VERSION = 8;
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 = 1.5;
MARKETING_VERSION = 2.0.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
+118 -1
View File
@@ -20,7 +20,7 @@ import LyrebirdShoeGazeUI
/// The engine is **not** started automatically; the user clicks Start in the builder's toolbar.
/// On termination the engine is stopped to release Core Audio resources cleanly.
@MainActor
final class AppDelegate: NSObject, NSApplicationDelegate {
final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
// MARK: - Engine configuration constants
@@ -65,6 +65,26 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
/// Record toggle item, retained so `validateMenuItem(_:)` can flip its title + enabled state.
private var recordMenuItem: NSMenuItem?
/// Rig-mute toggle item, retained so `validateMenuItem(_:)` can flip its title + checkmark to
/// match the current mute state (which may also change from the UI, MIDI, or the tuner).
private var muteMenuItem: NSMenuItem?
/// Rig-bypass toggle item, retained so `validateMenuItem(_:)` can flip its title + checkmark to
/// match the current bypass state (which may also change from the UI or MIDI).
private var bypassMenuItem: NSMenuItem?
/// The Rigs ▸ Set List submenu, retained so its item titles can be refreshed to the current
/// library order each time it opens (via `menuNeedsUpdate(_:)`).
private var setListMenu: NSMenu?
/// The ten fixed ⌘⇧1…⌘⇧0 set-list items (tags 0…9). Their key equivalents fire whether or not
/// the menu is open; `validateMenuItem(_:)` disables slots with no rig, and `menuNeedsUpdate`
/// refreshes their titles to the rig names.
private var setListMenuItems: [NSMenuItem] = []
/// Number of set-list slots exposed as ⌘⇧1…⌘⇧0.
private static let setListSlotCount: Int = 10
/// The Help window, created lazily on first open and reused thereafter.
private var helpWindow: LyrebirdWindow?
@@ -283,6 +303,51 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
// Engine start/stop lives in the in-window EngineConfigView (with sample-rate/channel
// config and the mismatch alert), so the Board menu only adds boards.
addItem(to: boardMenu, title: "Add Board", action: #selector(addBoardAction(_:)), key: "b")
boardMenu.addItem(NSMenuItem.separator())
// ⌘Z toggles rig mute (a hard silence of all output; distinct from Bypass Rig's dry
// passthrough). Owns the ⌘Z key equivalent on macOS; the in-window view binds it on iOS.
self.muteMenuItem = addItem(
to: boardMenu,
title: "Mute Rig",
action: #selector(toggleMuteAction(_:)),
key: "z"
)
// Bypass Rig routes every board to its dry input (pedals skipped) — distinct from Mute's
// hard silence. No key equivalent: ⌘B is Add Board, and Bypass has a prominent on-screen button.
self.bypassMenuItem = addItem(
to: boardMenu,
title: "Bypass Rig",
action: #selector(toggleBypassAction(_:)),
key: ""
)
// Rigs menu — a Set List of the top ten library rigs, each on ⌘⇧1…⌘⇧0. The items are
// fixed; their titles refresh to the current library order on open, and their key
// equivalents fire whether or not the menu is showing.
let rigsMenuItem: NSMenuItem = NSMenuItem()
mainMenu.addItem(rigsMenuItem)
let rigsMenu: NSMenu = NSMenu(title: "Rigs")
rigsMenuItem.submenu = rigsMenu
let setListItem: NSMenuItem = NSMenuItem(title: "Set List", action: nil, keyEquivalent: "")
rigsMenu.addItem(setListItem)
let setListSubmenu: NSMenu = NSMenu(title: "Set List")
setListSubmenu.delegate = self
setListItem.submenu = setListSubmenu
for slot: Int in 0 ..< AppDelegate.setListSlotCount {
// Slots 0…8 → ⌘⇧1…⌘⇧9; slot 9 → ⌘⇧0 (matches the physical number row).
let key: String = slot < 9 ? "\(slot + 1)" : "0"
let item: NSMenuItem = NSMenuItem(
title: "\(slot + 1). —",
action: #selector(loadRigSlotAction(_:)),
keyEquivalent: key
)
item.keyEquivalentModifierMask = [.command, .shift]
item.target = self
item.tag = slot
setListSubmenu.addItem(item)
setListMenuItems.append(item)
}
self.setListMenu = setListSubmenu
// Record menu — choose an output folder, then toggle recording.
let recordMenuItem: NSMenuItem = NSMenuItem()
@@ -382,6 +447,25 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
}
}
@objc private func toggleMuteAction(_ sender: Any?) {
shoeGaze.toggleRigMuted()
// Reflect the new state immediately, not only on the next menu-open validation.
muteMenuItem?.title = shoeGaze.rigMuted ? "Unmute Rig" : "Mute Rig"
muteMenuItem?.state = shoeGaze.rigMuted ? .on : .off
}
@objc private func toggleBypassAction(_ sender: Any?) {
shoeGaze.toggleRigBypassed()
bypassMenuItem?.title = shoeGaze.rigBypassed ? "Re-engage Rig" : "Bypass Rig"
bypassMenuItem?.state = shoeGaze.rigBypassed ? .on : .off
}
/// Loads the set-list rig at the sender's slot tag. Forwards to the in-window builder (which
/// owns the current-rig state, the unsaved-changes prompt, and engine lifecycle) via notification.
@objc private func loadRigSlotAction(_ sender: NSMenuItem) {
NotificationCenter.default.post(name: .shoeGazeLoadRigSlot, object: sender.tag)
}
@objc private func addBoardAction(_ sender: Any?) {
var created: PedalBoard?
do {
@@ -421,12 +505,45 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
recordMenuItem?.title = shoeGaze.isRecording ? "Stop Recording" : "Start Recording"
}
// MARK: - NSMenuDelegate
/// Refreshes the Set List item titles to the current library order each time the submenu opens.
/// Key equivalents fire independently of this (see `setListMenuItems`); this is display only.
func menuNeedsUpdate(_ menu: NSMenu) {
guard menu === setListMenu else { return }
let entries: [RigEntry] = library.entries
for item: NSMenuItem in setListMenuItems {
let slot: Int = item.tag
if slot < entries.count {
item.title = "\(slot + 1). \(entries[slot].name)"
} else {
item.title = "\(slot + 1). —"
}
}
}
func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
if menuItem == recordMenuItem {
menuItem.title = shoeGaze.isRecording ? "Stop Recording" : "Start Recording"
// Can always stop; can only start once a folder has been chosen.
return shoeGaze.isRecording || shoeGaze.recordingFolder != nil
}
if menuItem == muteMenuItem {
// Mute may have changed from the UI, MIDI, or the tuner — resync title + checkmark.
menuItem.title = shoeGaze.rigMuted ? "Unmute Rig" : "Mute Rig"
menuItem.state = shoeGaze.rigMuted ? .on : .off
return true
}
if menuItem == bypassMenuItem {
// Bypass may have changed from the UI or MIDI — resync title + checkmark.
menuItem.title = shoeGaze.rigBypassed ? "Re-engage Rig" : "Bypass Rig"
menuItem.state = shoeGaze.rigBypassed ? .on : .off
return true
}
if setListMenuItems.contains(menuItem) {
// A slot is live only when the library actually holds a rig at that position.
return menuItem.tag < library.entries.count
}
return true
}
}
+21 -21
View File
@@ -2,6 +2,21 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeName</key>
<string>ShoeGaze Document</string>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>LSHandlerRank</key>
<string>Owner</string>
<key>LSItemContentTypes</key>
<array>
<string>net.realizedsound.shoegaze</string>
</array>
</dict>
</array>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
@@ -13,9 +28,9 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.4.0</string>
<string>2.0.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<string>7</string>
<key>LSApplicationCategoryType</key>
<string>public.app-category.music</string>
<key>LSMinimumSystemVersion</key>
@@ -40,32 +55,17 @@
<string>Any</string>
</dict>
</dict>
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeName</key>
<string>ShoeGaze Document</string>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>LSHandlerRank</key>
<string>Owner</string>
<key>LSItemContentTypes</key>
<array>
<string>net.realizedsound.shoegaze</string>
</array>
</dict>
</array>
<key>UTExportedTypeDeclarations</key>
<array>
<dict>
<key>UTTypeIdentifier</key>
<string>net.realizedsound.shoegaze</string>
<key>UTTypeDescription</key>
<string>ShoeGaze Document</string>
<key>UTTypeConformsTo</key>
<array>
<string>public.json</string>
</array>
<key>UTTypeDescription</key>
<string>ShoeGaze Document</string>
<key>UTTypeIdentifier</key>
<string>net.realizedsound.shoegaze</string>
<key>UTTypeTagSpecification</key>
<dict>
<key>public.filename-extension</key>
@@ -172,7 +172,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.7;
MARKETING_VERSION = 2.0.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilderiOS;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
@@ -201,7 +201,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.7;
MARKETING_VERSION = 2.0.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilderiOS;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
-397
View File
@@ -1,397 +0,0 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 60;
objects = {
/* Begin PBXBuildFile section */
C3B000000000000000000020 /* LyrebirdShoeGaze in Frameworks */ = {isa = PBXBuildFile; productRef = C3B00000000000000000001E /* LyrebirdShoeGaze */; };
C3B000000000000000000021 /* LyrebirdShoeGazeUI in Frameworks */ = {isa = PBXBuildFile; productRef = C3B00000000000000000001F /* LyrebirdShoeGazeUI */; };
C3B000000000000000000022 /* Lyrebird in Frameworks */ = {isa = PBXBuildFile; productRef = C3B000000000000000000023 /* Lyrebird */; };
C3B000000000000000000024 /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = C3B000000000000000000025 /* LyrebirdUI */; };
C3B000000000000000000031 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = C3B000000000000000000030 /* Assets.xcassets */; };
C3B0000000000000000000C /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3B000000000000000000007 /* main.swift */; };
C3B0000000000000000000D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3B000000000000000000008 /* AppDelegate.swift */; };
C3B0000000000000000000E /* DemoRootView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3B000000000000000000009 /* DemoRootView.swift */; };
C3B0000000000000000000F /* ShoeGazeDemoController.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3B00000000000000000000A /* ShoeGazeDemoController.swift */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
C3B000000000000000000004 /* ShoeGazeDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = ShoeGazeDemo.app; sourceTree = BUILT_PRODUCTS_DIR; };
C3B000000000000000000006 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
C3B000000000000000000007 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
C3B000000000000000000008 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
C3B000000000000000000009 /* DemoRootView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DemoRootView.swift; sourceTree = "<group>"; };
C3B00000000000000000000A /* ShoeGazeDemoController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShoeGazeDemoController.swift; sourceTree = "<group>"; };
C3B000000000000000000030 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
C3B000000000000000000012 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
C3B000000000000000000020 /* LyrebirdShoeGaze in Frameworks */,
C3B000000000000000000021 /* LyrebirdShoeGazeUI in Frameworks */,
C3B000000000000000000022 /* Lyrebird in Frameworks */,
C3B000000000000000000024 /* LyrebirdUI in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
C3B000000000000000000002 = {
isa = PBXGroup;
children = (
C3B000000000000000000005 /* ShoeGazeDemo */,
C3B000000000000000000003 /* Products */,
);
sourceTree = "<group>";
};
C3B000000000000000000003 /* Products */ = {
isa = PBXGroup;
children = (
C3B000000000000000000004 /* ShoeGazeDemo.app */,
);
name = Products;
sourceTree = "<group>";
};
C3B000000000000000000005 /* ShoeGazeDemo */ = {
isa = PBXGroup;
children = (
C3B000000000000000000007 /* main.swift */,
C3B000000000000000000008 /* AppDelegate.swift */,
C3B000000000000000000009 /* DemoRootView.swift */,
C3B00000000000000000000A /* ShoeGazeDemoController.swift */,
C3B000000000000000000030 /* Assets.xcassets */,
C3B000000000000000000006 /* Info.plist */,
);
path = ShoeGazeDemo;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
C3B000000000000000000014 /* ShoeGazeDemo */ = {
isa = PBXNativeTarget;
buildConfigurationList = C3B000000000000000000015 /* Build configuration list for PBXNativeTarget "ShoeGazeDemo" */;
buildPhases = (
C3B000000000000000000011 /* Sources */,
C3B000000000000000000012 /* Frameworks */,
C3B000000000000000000013 /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = ShoeGazeDemo;
packageProductDependencies = (
C3B00000000000000000001E /* LyrebirdShoeGaze */,
C3B00000000000000000001F /* LyrebirdShoeGazeUI */,
C3B000000000000000000023 /* Lyrebird */,
C3B000000000000000000025 /* LyrebirdUI */,
);
productName = ShoeGazeDemo;
productReference = C3B000000000000000000004 /* ShoeGazeDemo.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
C3B000000000000000000001 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1600;
LastUpgradeCheck = 2620;
TargetAttributes = {
C3B000000000000000000014 = {
CreatedOnToolsVersion = 16.0;
};
};
};
buildConfigurationList = C3B000000000000000000018 /* Build configuration list for PBXProject "ShoeGazeDemo" */;
compatibilityVersion = "Xcode 14.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = C3B000000000000000000002;
packageReferences = (
C3B00000000000000000001B /* XCLocalSwiftPackageReference ".." */,
C3B00000000000000000001C /* XCRemoteSwiftPackageReference "Lyrebird" */,
);
productRefGroup = C3B000000000000000000003 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
C3B000000000000000000014 /* ShoeGazeDemo */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
C3B000000000000000000013 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
C3B000000000000000000031 /* Assets.xcassets in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
C3B000000000000000000011 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
C3B0000000000000000000C /* main.swift in Sources */,
C3B0000000000000000000D /* AppDelegate.swift in Sources */,
C3B0000000000000000000E /* DemoRootView.swift in Sources */,
C3B0000000000000000000F /* ShoeGazeDemoController.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
C3B000000000000000000016 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGNING_REQUIRED = NO;
CODE_SIGN_ENTITLEMENTS = ShoeGazeDemo/ShoeGazeDemo.entitlements;
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = HE5VJFE9E4;
ENABLE_HARDENED_RUNTIME = YES;
INFOPLIST_FILE = ShoeGazeDemo/Info.plist;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.music";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 15.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
};
name = Debug;
};
C3B000000000000000000017 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGNING_REQUIRED = NO;
CODE_SIGN_ENTITLEMENTS = ShoeGazeDemo/ShoeGazeDemo.entitlements;
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = HE5VJFE9E4;
ENABLE_HARDENED_RUNTIME = YES;
INFOPLIST_FILE = ShoeGazeDemo/Info.plist;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.music";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 15.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
};
name = Release;
};
C3B000000000000000000019 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = macosx;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
C3B00000000000000000001A /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = macosx;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
C3B000000000000000000015 /* Build configuration list for PBXNativeTarget "ShoeGazeDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
C3B000000000000000000016 /* Debug */,
C3B000000000000000000017 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
C3B000000000000000000018 /* Build configuration list for PBXProject "ShoeGazeDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
C3B000000000000000000019 /* Debug */,
C3B00000000000000000001A /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
/* Begin XCLocalSwiftPackageReference section */
C3B00000000000000000001B /* XCLocalSwiftPackageReference ".." */ = {
isa = XCLocalSwiftPackageReference;
relativePath = ..;
};
/* End XCLocalSwiftPackageReference section */
/* Begin XCRemoteSwiftPackageReference section */
C3B00000000000000000001C /* XCRemoteSwiftPackageReference "Lyrebird" */ = {
isa = XCRemoteSwiftPackageReference;
repositoryURL = "https://realizedsound.mooo.com/josh/Lyrebird";
requirement = {
kind = upToNextMajorVersion;
minimumVersion = 1.2.0;
};
};
/* End XCRemoteSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
C3B00000000000000000001E /* LyrebirdShoeGaze */ = {
isa = XCSwiftPackageProductDependency;
package = C3B00000000000000000001B /* XCLocalSwiftPackageReference ".." */;
productName = LyrebirdShoeGaze;
};
C3B00000000000000000001F /* LyrebirdShoeGazeUI */ = {
isa = XCSwiftPackageProductDependency;
package = C3B00000000000000000001B /* XCLocalSwiftPackageReference ".." */;
productName = LyrebirdShoeGazeUI;
};
C3B000000000000000000023 /* Lyrebird */ = {
isa = XCSwiftPackageProductDependency;
package = C3B00000000000000000001C /* XCRemoteSwiftPackageReference "Lyrebird" */;
productName = Lyrebird;
};
C3B000000000000000000025 /* LyrebirdUI */ = {
isa = XCSwiftPackageProductDependency;
package = C3B00000000000000000001C /* XCRemoteSwiftPackageReference "Lyrebird" */;
productName = LyrebirdUI;
};
/* End XCSwiftPackageProductDependency section */
};
rootObject = C3B000000000000000000001 /* Project object */;
}
@@ -1,33 +0,0 @@
{
"originHash" : "cfdd71f4b32d744c862bbe26a8265d75aa9e906275b0fb1b63575b7d68be1b6a",
"pins" : [
{
"identity" : "linenoise-swift",
"kind" : "remoteSourceControl",
"location" : "https://github.com/andybest/linenoise-swift",
"state" : {
"revision" : "afc897c02b030af7333105c4fedcd843a8339238",
"version" : "0.0.3"
}
},
{
"identity" : "lyrebird",
"kind" : "remoteSourceControl",
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
"state" : {
"revision" : "032b7c39d351eba4029e8399e1ab1ee201e8bb5c",
"version" : "1.2.0"
}
},
{
"identity" : "nimble",
"kind" : "remoteSourceControl",
"location" : "https://github.com/Quick/Nimble.git",
"state" : {
"revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0",
"version" : "7.3.4"
}
}
],
"version" : 3
}
@@ -1,78 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2620"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES"
buildArchitectures = "Automatic">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "C3B000000000000000000014"
BuildableName = "ShoeGazeDemo.app"
BlueprintName = "ShoeGazeDemo"
ReferencedContainer = "container:ShoeGazeDemo.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
shouldAutocreateTestPlan = "YES">
</TestAction>
<LaunchAction
buildConfiguration = "Release"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "C3B000000000000000000014"
BuildableName = "ShoeGazeDemo.app"
BlueprintName = "ShoeGazeDemo"
ReferencedContainer = "container:ShoeGazeDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "C3B000000000000000000014"
BuildableName = "ShoeGazeDemo.app"
BlueprintName = "ShoeGazeDemo"
ReferencedContainer = "container:ShoeGazeDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
-153
View File
@@ -1,153 +0,0 @@
// AppDelegate.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import AppKit
import LyrebirdSynth
import LyrebirdUI
import LyrebirdShoeGaze
import LyrebirdShoeGazeUI
/// Application delegate for the ShoeGaze demo.
///
/// Creates a `SynthesisEngine`, a `ShoeGazeDemoController` (which builds the default
/// `.boards` showcase automatically), and opens a `LyrebirdWindow` hosting `DemoRootView`.
///
/// The engine is **not** started automatically. The user clicks Start in `DemoRootView`'s
/// toolbar (or presses Stop to halt audio). On application termination, `stop()` is called
/// to release Core Audio resources cleanly.
@MainActor
final class AppDelegate: NSObject, NSApplicationDelegate {
// MARK: - Engine configuration constants
private static let blockSize: Int = 512
private static let sampleRate: Double = 48_000.0
private static let outputChannels: Int = 2
// Built-in mics are mono; default to one input channel so live input works out of the box
// (CoreAudio can't satisfy more input channels than the device provides). Raise in the UI.
private static let inputChannels: Int = 1
private static let numAudioBuses: Int = 256
// MARK: - Window geometry constants
private static let windowWidth: CGFloat = 1_100
private static let windowHeight: CGFloat = 640
// MARK: - Owned objects
private let coreDriver: CoreAudioDriver
private let controller: ShoeGazeDemoController
private let window: LyrebirdWindow
/// The Mute menu item, retained so `validateMenuItem(_:)` can update its checkmark.
private var muteMenuItem: NSMenuItem?
// MARK: - Init
override init() {
let coreDriver: CoreAudioDriver = CoreAudioDriver()
let engine: SynthesisEngine = SynthesisEngine(
blockSize: AppDelegate.blockSize,
sampleRate: AppDelegate.sampleRate,
numOutputChannels: AppDelegate.outputChannels,
numInputChannels: AppDelegate.inputChannels,
numAudioBuses: AppDelegate.numAudioBuses,
driver: coreDriver
)
self.coreDriver = coreDriver
self.controller = ShoeGazeDemoController(engine: engine)
self.window = LyrebirdWindow(
title: "ShoeGaze — Lyrebird Guitar Pedalboard",
width: AppDelegate.windowWidth,
height: AppDelegate.windowHeight
)
super.init()
}
// MARK: - NSApplicationDelegate
func applicationDidFinishLaunching(_ notification: Notification) {
installMainMenu()
let demoController: ShoeGazeDemoController = controller
let driver: CoreAudioDriver = coreDriver
window.open {
DemoRootView(controller: demoController, hardwareSampleRate: { driver.deviceSampleRate })
}
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
true
}
func applicationWillTerminate(_ notification: Notification) {
controller.stop()
}
// MARK: - Main menu
/// Builds the app's menu bar: an application menu (About / Hide / Quit ⌘Q) and an
/// Audio menu (Mute ⌘M). Standard items route through the responder chain to
/// `NSApplication`; Mute targets this delegate.
private func installMainMenu() {
let appName: String = ProcessInfo.processInfo.processName
let mainMenu: NSMenu = NSMenu()
// Application menu.
let appMenuItem: NSMenuItem = NSMenuItem()
mainMenu.addItem(appMenuItem)
let appMenu: NSMenu = NSMenu()
appMenuItem.submenu = appMenu
appMenu.addItem(
withTitle: "About \(appName)",
action: #selector(NSApplication.orderFrontStandardAboutPanel(_:)),
keyEquivalent: ""
)
appMenu.addItem(NSMenuItem.separator())
appMenu.addItem(
withTitle: "Hide \(appName)",
action: #selector(NSApplication.hide(_:)),
keyEquivalent: "h"
)
appMenu.addItem(NSMenuItem.separator())
appMenu.addItem(
withTitle: "Quit \(appName)",
action: #selector(NSApplication.terminate(_:)),
keyEquivalent: "q"
)
// Audio menu.
let audioMenuItem: NSMenuItem = NSMenuItem()
mainMenu.addItem(audioMenuItem)
let audioMenu: NSMenu = NSMenu(title: "Audio")
audioMenuItem.submenu = audioMenu
let mute: NSMenuItem = NSMenuItem(
title: "Mute",
action: #selector(toggleMute(_:)),
keyEquivalent: "m"
)
mute.target = self
audioMenu.addItem(mute)
muteMenuItem = mute
NSApplication.shared.mainMenu = mainMenu
}
/// Toggles audio output (mute). Bound to the Audio ▸ Mute menu item (⌘M).
@objc private func toggleMute(_ sender: Any?) {
controller.toggleMute()
}
/// Shows a checkmark on the Mute item while audio is silenced (engine not running).
func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
if menuItem == muteMenuItem {
menuItem.state = controller.isRunning ? .off : .on
}
return true
}
}
#endif
@@ -1,15 +0,0 @@
{
"images" : [
{"size":"16x16","idiom":"mac","filename":"icon_16x16.png","scale":"1x"},
{"size":"16x16","idiom":"mac","filename":"icon_16x16@2x.png","scale":"2x"},
{"size":"32x32","idiom":"mac","filename":"icon_32x32.png","scale":"1x"},
{"size":"32x32","idiom":"mac","filename":"icon_32x32@2x.png","scale":"2x"},
{"size":"128x128","idiom":"mac","filename":"icon_128x128.png","scale":"1x"},
{"size":"128x128","idiom":"mac","filename":"icon_128x128@2x.png","scale":"2x"},
{"size":"256x256","idiom":"mac","filename":"icon_256x256.png","scale":"1x"},
{"size":"256x256","idiom":"mac","filename":"icon_256x256@2x.png","scale":"2x"},
{"size":"512x512","idiom":"mac","filename":"icon_512x512.png","scale":"1x"},
{"size":"512x512","idiom":"mac","filename":"icon_512x512@2x.png","scale":"2x"}
],
"info" : {"author":"xcode","version":1}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 782 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 345 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 345 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 MiB

@@ -1 +0,0 @@
{ "info" : {"author":"xcode","version":1} }
-303
View File
@@ -1,303 +0,0 @@
// DemoRootView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import SwiftUI
import LyrebirdSynth
import LyrebirdUI
import LyrebirdShoeGaze
import LyrebirdShoeGazeUI
/// Root view for the ShoeGaze demo window.
///
/// Presents a top toolbar with a mode picker, an input-source toggle, and a Start/Stop
/// transport button, followed by a content area that switches between four showcase
/// modes as the user selects them.
///
/// Because `ShoeGazeDemoController` is `@Observable`, SwiftUI re-renders this view and
/// all its children whenever `controller.mode`, `controller.shoeGaze.boards`,
/// `controller.router`, `controller.parallelSection`, or `controller.isRunning` change —
/// including after a ``ShoeGazeDemoController/rebuild()`` that replaces `shoeGaze`.
///
/// ## Mode showcases
///
/// - `.boards` → `ShoeGazeView` — two boards, eight pedals, master gain per board.
/// - `.editor` → `BoardEditorView` — board + FlowLayout pedal area + version snapshots.
/// - `.parallel` → `ParallelSectionView` — splitter, two branch rows, merger (via board).
/// - `.router` → `ChainRouterView` — dual-board chain router with splitter + master.
/// - `.stereo` → `StereoSplitSectionView` — stereo split with the four route modes.
struct DemoRootView: View {
// MARK: - Layout constants
private static let toolbarSpacing: CGFloat = 10
private static let toolbarPadding: CGFloat = 12
private static let contentPadding: CGFloat = 16
private static let windowMinWidth: CGFloat = 1_100
private static let windowMinHeight: CGFloat = 640
/// Dark stage-floor background (warm almost-black).
private static let backgroundRed: Double = 0.08
private static let backgroundGreen: Double = 0.07
private static let backgroundBlue: Double = 0.06
private static let dividerOpacity: Double = 0.15
// MARK: - Properties
private let controller: ShoeGazeDemoController
private let hardwareSampleRate: () -> Double?
/// Bumped on each transport press so the buttons re-read `controller.isRunning`
/// (which derives from the non-observable engine).
@State private var transportTick: Bool = false
// MARK: - Init
/// Creates the root demo view bound to the given controller.
///
/// - Parameters:
/// - controller: The `ShoeGazeDemoController` that owns the engine, active `ShoeGaze`
/// session, and current mode. All toolbar actions dispatch through this.
/// - hardwareSampleRate: Returns the actual hardware sample rate (or `nil`), for the engine-
/// config mismatch warning. Defaults to `nil`.
init(
controller: ShoeGazeDemoController,
hardwareSampleRate: @escaping () -> Double? = { nil }
) {
self.controller = controller
self.hardwareSampleRate = hardwareSampleRate
}
// MARK: - Body
var body: some View {
VStack(spacing: 0) {
toolbar
Divider()
.overlay(Color.white.opacity(DemoRootView.dividerOpacity))
contentArea
.padding(DemoRootView.contentPadding)
Divider()
.overlay(Color.white.opacity(DemoRootView.dividerOpacity))
ShoeGazeScopeView(shoeGaze: controller.shoeGaze)
.padding(DemoRootView.contentPadding)
}
.frame(
minWidth: DemoRootView.windowMinWidth,
minHeight: DemoRootView.windowMinHeight
)
.background(
Color(
red: DemoRootView.backgroundRed,
green: DemoRootView.backgroundGreen,
blue: DemoRootView.backgroundBlue
)
)
.alert(
"Microphone Access Needed",
isPresented: Binding(
get: { controller.microphoneAccessDenied },
set: { controller.microphoneAccessDenied = $0 }
)
) {
Button("OK", role: .cancel) { }
} message: {
Text("Live input needs microphone access. Enable it in System Settings › Privacy & "
+ "Security › Microphone, then select the input again.")
}
}
// MARK: - Toolbar
/// Top toolbar: mode picker, input-source picker, transport, and CPU meter.
private var toolbar: some View {
HStack(spacing: DemoRootView.toolbarSpacing) {
modePicker
Spacer()
inputSourcePicker
// In Boards mode the pedalboard view (`ShoeGazeView`) supplies its own
// Start/Stop, so the board starts only when its own button is pressed. The
// other modes have no in-content transport, so show it here for them.
if controller.mode != .boards {
transportButtons
}
}
.padding(DemoRootView.toolbarPadding)
}
/// Segmented picker for `DemoMode`.
///
/// The selection binding's setter delegates to `controller.select(_:)` rather than
/// writing a `@State` directly, so the controller handles the mode switch and rebuild.
private var modePicker: some View {
let modeBinding: Binding<DemoMode> = Binding(
get: { controller.mode },
set: { controller.select($0) }
)
return Picker("Mode", selection: modeBinding) {
ForEach(DemoMode.allCases) { demoMode in
Text(demoMode.title).tag(demoMode)
}
}
.pickerStyle(.segmented)
.frame(maxWidth: 380)
.foregroundStyle(Color.white)
}
/// A `Binding<Int>` mapping the input Picker tag to `InputSource`.
///
/// Tag `-1` = `.testLoop`; tags `0 ..< numInputChannels` = `.liveInput(channel:)`.
/// Setting the binding calls `controller.setInputSource(_:)`.
private var inputSourceBinding: Binding<Int> {
Binding(
get: {
switch controller.inputSource {
case .testLoop:
return -1
case .liveInput(let channel):
return channel
}
},
set: { newValue in
if newValue == -1 {
controller.setInputSource(.testLoop)
} else {
controller.setInputSource(.liveInput(channel: newValue))
}
}
)
}
/// Picker listing "Test Loop" and one option per available hardware input channel.
///
/// When `engine.numInputChannels == 0` only "Test Loop" is shown; the live options
/// are omitted so the picker never offers channels that do not exist.
private var inputSourcePicker: some View {
HStack(spacing: DemoRootView.toolbarSpacing) {
Text("Input:")
.font(.subheadline)
.foregroundStyle(Color.white.opacity(0.65))
Picker("Input", selection: inputSourceBinding) {
Text("Test Loop").tag(-1)
ForEach(Array(0..<max(0, controller.engine.numInputChannels)), id: \.self) { channel in
Text("In \(channel)").tag(channel)
}
}
.pickerStyle(.menu)
.foregroundStyle(Color.white)
}
}
/// Engine configuration + transport (sample rate, ins/outs, Start/Stop, mismatch alert).
private var transportButtons: some View {
EngineConfigView(
shoeGaze: controller.shoeGaze,
hardwareSampleRate: hardwareSampleRate,
applyConfig: { rate, inputs, outputs in
try controller.reconfigure(
sampleRate: rate,
inputChannels: inputs,
outputChannels: outputs
)
},
onConfigApplied: { transportTick.toggle() }
)
}
// MARK: - Content area
/// The main content area switches view based on the active mode.
@ViewBuilder
private var contentArea: some View {
switch controller.mode {
case .boards:
ShoeGazeView(shoeGaze: controller.shoeGaze, hardwareSampleRate: hardwareSampleRate)
case .editor:
editorContent
case .parallel:
parallelContent
case .router:
routerContent
case .stereo:
stereoContent
}
}
/// `.editor` content: `BoardEditorView` bound to the first board in the session.
///
/// Shows a placeholder when the board list is unexpectedly empty (e.g. if
/// `buildEditor()` failed silently).
@ViewBuilder
private var editorContent: some View {
if controller.shoeGaze.boards.isEmpty {
Text("No editor board available.")
.foregroundStyle(Color.white.opacity(0.55))
} else {
BoardEditorView(
shoeGaze: controller.shoeGaze,
boardIndex: 0,
versionStore: controller.versionStore
)
}
}
/// `.parallel` content: the full board view (shows pre/post-split pedals) stacked
/// above `ParallelSectionView` which exposes the splitter mode picker and branch rows.
@ViewBuilder
private var parallelContent: some View {
if let section: ParallelSection = controller.parallelSection,
!controller.shoeGaze.boards.isEmpty {
let board: PedalBoard = controller.shoeGaze.boards[0]
ScrollView(.vertical, showsIndicators: true) {
VStack(alignment: .leading, spacing: 20) {
PedalBoardView(board: board)
ParallelSectionView(section: section)
}
}
} else {
Text("Parallel section unavailable.")
.foregroundStyle(Color.white.opacity(0.55))
}
}
/// `.stereo` content: the full board view (shows the pre-split pedal) stacked above a
/// width badge and `StereoSplitSectionView` (route picker + L/R branch rows).
@ViewBuilder
private var stereoContent: some View {
if let section: StereoSplitSection = controller.stereoSection,
let board: PedalBoard = controller.shoeGaze.boards.first {
ScrollView(.vertical, showsIndicators: true) {
VStack(alignment: .leading, spacing: 20) {
HStack(spacing: 10) {
PedalBoardView(board: board)
StereoWidthBadge(width: board.width)
}
StereoSplitSectionView(section: section)
}
}
} else {
Text("Stereo split unavailable.")
.foregroundStyle(Color.white.opacity(0.55))
}
}
/// `.router` content: `ChainRouterView` bound to the live `ChainRouter`.
@ViewBuilder
private var routerContent: some View {
if let chainRouter: ChainRouter = controller.router {
ScrollView(.vertical, showsIndicators: true) {
ChainRouterView(router: chainRouter)
}
} else {
Text("Chain router unavailable.")
.foregroundStyle(Color.white.opacity(0.55))
}
}
}
#endif
-32
View File
@@ -1,32 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSApplicationCategoryType</key>
<string>public.app-category.music</string>
<key>LSMinimumSystemVersion</key>
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
<key>NSHighResolutionCapable</key>
<true/>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2026 realizedsound. All rights reserved.</string>
<key>NSMicrophoneUsageDescription</key>
<string>ShoeGazeDemo can route a hardware input channel through your pedalboard. Enable microphone access to use Live Input mode.</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
</dict>
</plist>
@@ -1,8 +0,0 @@
<?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.security.device.audio-input</key>
<true/>
</dict>
</plist>
@@ -1,371 +0,0 @@
// ShoeGazeDemoController.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Observation
import LyrebirdSynth
import LyrebirdUI
import LyrebirdShoeGaze
// MARK: - DemoMode
/// The active showcase mode displayed in the demo window.
///
/// Each case corresponds to one full-window showcase of a distinct ShoeGaze feature.
/// Switching modes tears down the current audio graph and rebuilds it fresh.
enum DemoMode: String, CaseIterable, Identifiable {
/// Two full boards, each with four pedals (Board 1: Overdrive → Delay → Reverb → Modulation;
/// Board 2: Fuzz → Tremolo → Phaser → Compressor).
case boards = "Boards"
/// A single board inside `BoardEditorView` with preset version snapshots pre-populated.
case editor = "Editor"
/// A single board with a ``ParallelSection`` (Overdrive → split → Delay|Fuzz → merge → Reverb).
case parallel = "Parallel"
/// A ``ChainRouter`` that splits one input across two independent boards (A: Overdrive + Delay;
/// B: Fuzz + Reverb) and recombines them through a shared master stage.
case router = "Router"
/// A board with a ``StereoSplitSection`` (Overdrive → splitStereo(Delay | PingPong) →
/// collectStereo) showcasing the four ``StereoRoute`` modes and stereo output.
case stereo = "Stereo"
var id: String { rawValue }
/// Short human-readable title used in the mode picker.
var title: String {
switch self {
case .boards: return "Boards"
case .editor: return "Editor"
case .parallel: return "Parallel"
case .router: return "Router"
case .stereo: return "Stereo"
}
}
}
// MARK: - ShoeGazeDemoController
/// Main-actor observable controller that owns the engine and active ShoeGaze session.
///
/// A single `ShoeGaze` instance plus optional `router` / `parallelSection` hold the
/// current showcase. Switching modes via ``select(_:)`` or changing the input source via
/// ``setInputSource(_:)`` calls ``rebuild()`` which:
///
/// 1. Stops the engine if it is running.
/// 2. Calls `shoeGaze.teardown()` to remove all nodes and release all buses.
/// 3. Replaces `shoeGaze` with a fresh instance.
/// 4. Builds the new mode-specific graph.
/// 5. Restarts the engine if it was running before the rebuild.
///
/// This guarantees the engine never holds stale references across mode switches.
@MainActor
@Observable
final class ShoeGazeDemoController {
// MARK: - Public state
/// The synthesis engine. Callers must not call `engine.start()` or `engine.stop()`
/// directly — use ``start()`` and ``stop()`` so `isRunning` stays consistent.
let engine: SynthesisEngine
/// The active ShoeGaze session. Replaced on every ``rebuild()`` call.
private(set) var shoeGaze: ShoeGaze
/// Non-nil only in `.router` mode, after ``buildRouter()`` succeeds.
private(set) var router: ChainRouter?
/// Non-nil only in `.parallel` mode, after ``buildParallel()`` succeeds.
private(set) var parallelSection: ParallelSection?
/// Non-nil only in `.stereo` mode, after ``buildStereo()`` succeeds.
private(set) var stereoSection: StereoSplitSection?
/// Stores named board snapshots for the `.editor` showcase.
let versionStore: BoardVersionStore = BoardVersionStore()
/// Currently selected showcase mode.
private(set) var mode: DemoMode = .boards
/// Current input source policy.
private(set) var inputSource: InputSource = .testLoop
/// `true` while the engine is running. Derived from the engine (the single source
/// of truth) so it stays correct regardless of which control starts/stops it.
var isRunning: Bool { engine.isRunning }
// MARK: - Init
/// Creates a controller, builds the default `.boards` showcase, and does NOT start the engine.
///
/// - Parameter engine: A pre-configured `SynthesisEngine` owned by the caller. The
/// engine must not be running when this initialiser is called.
init(engine: SynthesisEngine) {
self.engine = engine
self.shoeGaze = ShoeGaze(engine: engine, inputSource: .testLoop)
buildBoards()
}
// MARK: - Mode selection
/// Switches to the given mode if different from the current one, triggering a full rebuild.
///
/// - Parameter newMode: The showcase to activate.
func select(_ newMode: DemoMode) {
guard newMode != mode else { return }
mode = newMode
rebuild()
}
// MARK: - Input source
/// Changes the input source policy and triggers a full rebuild.
///
/// Live input requires microphone authorisation first — without it macOS feeds the AUHAL input
/// silent zeros. The request is asynchronous, so `.liveInput` is applied only once the grant
/// resolves; a denial falls back to the test loop.
///
/// - Parameter source: `.testLoop` for the built-in test signal or `.liveInput(channel:)`
/// for hardware microphone/instrument input on the given channel.
func setInputSource(_ source: InputSource) {
guard case .liveInput = source else {
applyInputSource(source)
return
}
MicrophonePermission.request { [weak self] granted in
if !granted { self?.microphoneAccessDenied = true }
self?.applyInputSource(granted ? source : .testLoop)
}
}
/// Set when live input is requested but microphone access is denied/restricted. The UI observes
/// this and presents an alert, then clears it.
var microphoneAccessDenied: Bool = false
/// Applies an input-source change and triggers a full rebuild.
private func applyInputSource(_ source: InputSource) {
inputSource = source
rebuild()
}
// MARK: - Transport
/// Starts the engine. Updates ``isRunning`` on success; prints on failure.
func start() {
do {
try engine.start()
} catch {
print("[ShoeGazeDemoController] engine.start() failed: \(error)")
}
}
/// Stops the engine and updates ``isRunning``.
func stop() {
engine.stop()
}
/// Toggles audio output on/off (mute). Muting silences output by stopping the engine;
/// unmuting restarts it. `isRunning == false` is the "muted" (silent) state.
func toggleMute() {
if isRunning {
stop()
} else {
start()
}
}
// MARK: - Engine reconfiguration
/// Applies new engine settings (while stopped) and rebuilds the current mode so the showcase
/// is reconstructed at the new sample rate / channel counts. Used by the engine-config UI.
///
/// Tears the session down BEFORE reconfiguring — changing channel counts re-partitions the bus
/// allocator, which would invalidate rig buses still allocated under the old layout.
///
/// - Throws: `SynthesisEngineConfigError` if the engine is running or a value is invalid.
func reconfigure(sampleRate: Double, inputChannels: Int, outputChannels: Int) throws {
let wasRunning: Bool = isRunning
if wasRunning { stop() }
tearDownSession()
try engine.setSampleRate(sampleRate)
try engine.setNumOutputChannels(outputChannels)
try engine.setNumInputChannels(inputChannels)
// A live-input source past the new channel count would make rebuild fail; fall back.
if case .liveInput(let channel) = inputSource, channel >= inputChannels {
inputSource = .testLoop
}
buildSession()
// `buildSession()` creates a fresh `ShoeGaze`, whose `init` installs the scope tap for the
// new channel layout — no explicit `installScopeTap()` needed here.
if wasRunning { start() }
}
// MARK: - Rebuild
/// Tears down the current session and rebuilds the active mode.
///
/// The engine is stopped before teardown and restarted afterward if it was running,
/// satisfying the remove-before-release invariant documented on `ShoeGaze.teardown()`.
private func rebuild() {
let wasRunning: Bool = isRunning
if wasRunning { stop() }
tearDownSession()
buildSession()
if wasRunning { start() }
}
/// Removes the current session's nodes and clears split/router references.
private func tearDownSession() {
shoeGaze.teardown()
router = nil
parallelSection = nil
stereoSection = nil
}
/// Creates a fresh session and builds the active mode's graph.
private func buildSession() {
shoeGaze = ShoeGaze(engine: engine, inputSource: inputSource)
switch mode {
case .boards: buildBoards()
case .editor: buildEditor()
case .parallel: buildParallel()
case .router: buildRouter()
case .stereo: buildStereo()
}
}
// MARK: - Mode builders
/// `.boards` — three full boards covering all twelve pedal types.
///
/// Board 1: Overdrive → Delay → Reverb → Modulation
/// Board 2: Fuzz → Tremolo → Phaser → Compressor
/// Board 3: Mutant → Auto-Wah → Feedback Delay → Multi-Tap Delay
private func buildBoards() {
do {
let board1: PedalBoard = try shoeGaze.addBoard()
board1.label = "Board 1"
try board1.add(OverdrivePedal())
try board1.add(DelayPedal())
try board1.add(ReverbPedal())
try board1.add(ModulationPedal())
try shoeGaze.finalizeBoard(board1)
let board2: PedalBoard = try shoeGaze.addBoard()
board2.label = "Board 2"
try board2.add(FuzzPedal())
try board2.add(TremoloPedal())
try board2.add(PhaserPedal())
try board2.add(CompressorPedal())
try shoeGaze.finalizeBoard(board2)
let board3: PedalBoard = try shoeGaze.addBoard()
board3.label = "Board 3"
try board3.add(MutantPedal())
try board3.add(AutoWahPedal())
try board3.add(FeedbackDelayPedal())
try board3.add(MultiTapDelayPedal())
try shoeGaze.finalizeBoard(board3)
} catch {
print("[ShoeGazeDemoController] buildBoards failed: \(error)")
}
}
/// `.editor` — one board inside `BoardEditorView` with two pre-captured versions.
///
/// The pre-populated version entries ("Crunch" and "Clean Shimmer") ensure the
/// Versions menu is not empty when the showcase first appears.
private func buildEditor() {
do {
let board: PedalBoard = try shoeGaze.addBoard()
board.label = "Editor Board"
try board.add(OverdrivePedal())
try board.add(FuzzPedal())
try board.add(DelayPedal())
try board.add(ReverbPedal())
try shoeGaze.finalizeBoard(board)
// Pre-populate two named snapshots so the Versions menu is immediately useful.
versionStore.capture(board, name: "Crunch")
versionStore.capture(board, name: "Clean Shimmer")
} catch {
print("[ShoeGazeDemoController] buildEditor failed: \(error)")
}
}
/// `.parallel` — Overdrive → split(Delay | Fuzz) → merge → Reverb.
///
/// Stores the `ParallelSection` in `parallelSection` so `DemoRootView` can display
/// `ParallelSectionView`.
private func buildParallel() {
do {
let board: PedalBoard = try shoeGaze.addBoard()
board.label = "Parallel Board"
try board.add(OverdrivePedal())
let section: ParallelSection = try board.split()
try section.branchA.add(DelayPedal())
try section.branchB.add(FuzzPedal())
try board.merge(section)
try board.add(ReverbPedal())
try shoeGaze.finalizeBoard(board)
parallelSection = section
} catch {
print("[ShoeGazeDemoController] buildParallel failed: \(error)")
}
}
/// `.router` — ChainRouter with two independent chains: A (Overdrive + Delay),
/// B (Fuzz + Reverb), merged through a shared master stage.
///
/// Stores the `ChainRouter` in `router` so `DemoRootView` can display
/// `ChainRouterView`.
private func buildRouter() {
do {
let r: ChainRouter = try shoeGaze.makeChainRouter()
try r.addToA(OverdrivePedal())
try r.addToA(DelayPedal())
try r.addToB(FuzzPedal())
try r.addToB(ReverbPedal())
try r.finalize()
router = r
} catch {
print("[ShoeGazeDemoController] buildRouter failed: \(error)")
}
}
/// `.stereo` — Overdrive → splitStereo(left: Delay | right: Ping-Pong) → collectStereo.
///
/// Demonstrates the stereo split mechanism: a mono signal fanned into two independently
/// authored chains that become the left and right output channels, with the four
/// ``StereoRoute`` modes (stereo / left / right / bypass) selectable live. Stores the
/// `StereoSplitSection` so `DemoRootView` can display `StereoSplitSectionView`.
private func buildStereo() {
do {
let board: PedalBoard = try shoeGaze.addBoard()
board.label = "Stereo Board"
try board.add(OverdrivePedal())
let section: StereoSplitSection = try board.splitStereo()
try section.left.add(DelayPedal())
try section.right.add(PingPongDelayPedal())
try board.collectStereo(section)
try shoeGaze.finalizeBoard(board)
stereoSection = section
} catch {
print("[ShoeGazeDemoController] buildStereo failed: \(error)")
}
}
}
#endif
-24
View File
@@ -1,24 +0,0 @@
// main.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import AppKit
// Program entry runs on the main thread; assert main-actor isolation for the
// AppKit bootstrap rather than hopping asynchronously. `AppDelegate.init` builds
// `@MainActor` synthesizers and UI.
MainActor.assumeIsolated {
let app: NSApplication = NSApplication.shared
let delegate: AppDelegate = AppDelegate()
app.setActivationPolicy(.regular)
app.delegate = delegate
app.activate(ignoringOtherApps: true)
app.run()
}
#else
// The ShoeGaze demo is a macOS AppKit application and has no iOS entry point.
print("ShoeGazeDemo runs on macOS only.")
#endif
@@ -1,387 +0,0 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 60;
objects = {
/* Begin PBXBuildFile section */
C3C000000000000000000009 /* ShoeGazeiOSDemoApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C000000000000000000007 /* ShoeGazeiOSDemoApp.swift */; };
C3C00000000000000000000A /* ShoeGazeiOSDemoAppModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C000000000000000000008 /* ShoeGazeiOSDemoAppModel.swift */; };
C3C00000000000000000000B /* LyrebirdShoeGaze in Frameworks */ = {isa = PBXBuildFile; productRef = C3C00000000000000000001A /* LyrebirdShoeGaze */; };
C3C00000000000000000000C /* LyrebirdShoeGazeUI in Frameworks */ = {isa = PBXBuildFile; productRef = C3C00000000000000000001B /* LyrebirdShoeGazeUI */; };
C3C00000000000000000000D /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = C3C00000000000000000001C /* LyrebirdUI */; };
C3C00000000000000000001D /* Lyrebird in Frameworks */ = {isa = PBXBuildFile; productRef = C3C00000000000000000001E /* Lyrebird */; };
C3C000000000000000000031 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = C3C000000000000000000030 /* Assets.xcassets */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
C3C000000000000000000004 /* ShoeGazeiOSDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = ShoeGazeiOSDemo.app; sourceTree = BUILT_PRODUCTS_DIR; };
C3C000000000000000000006 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
C3C000000000000000000007 /* ShoeGazeiOSDemoApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShoeGazeiOSDemoApp.swift; sourceTree = "<group>"; };
C3C000000000000000000008 /* ShoeGazeiOSDemoAppModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShoeGazeiOSDemoAppModel.swift; sourceTree = "<group>"; };
C3C000000000000000000030 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
C3C00000000000000000000F /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
C3C00000000000000000000B /* LyrebirdShoeGaze in Frameworks */,
C3C00000000000000000000C /* LyrebirdShoeGazeUI in Frameworks */,
C3C00000000000000000000D /* LyrebirdUI in Frameworks */,
C3C00000000000000000001D /* Lyrebird in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
C3C000000000000000000002 = {
isa = PBXGroup;
children = (
C3C000000000000000000005 /* ShoeGazeiOSDemo */,
C3C000000000000000000003 /* Products */,
);
sourceTree = "<group>";
};
C3C000000000000000000003 /* Products */ = {
isa = PBXGroup;
children = (
C3C000000000000000000004 /* ShoeGazeiOSDemo.app */,
);
name = Products;
sourceTree = "<group>";
};
C3C000000000000000000005 /* ShoeGazeiOSDemo */ = {
isa = PBXGroup;
children = (
C3C000000000000000000007 /* ShoeGazeiOSDemoApp.swift */,
C3C000000000000000000008 /* ShoeGazeiOSDemoAppModel.swift */,
C3C000000000000000000030 /* Assets.xcassets */,
C3C000000000000000000006 /* Info.plist */,
);
path = ShoeGazeiOSDemo;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
C3C000000000000000000011 /* ShoeGazeiOSDemo */ = {
isa = PBXNativeTarget;
buildConfigurationList = C3C000000000000000000012 /* Build configuration list for PBXNativeTarget "ShoeGazeiOSDemo" */;
buildPhases = (
C3C00000000000000000000E /* Sources */,
C3C00000000000000000000F /* Frameworks */,
C3C000000000000000000010 /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = ShoeGazeiOSDemo;
packageProductDependencies = (
C3C00000000000000000001A /* LyrebirdShoeGaze */,
C3C00000000000000000001B /* LyrebirdShoeGazeUI */,
C3C00000000000000000001C /* LyrebirdUI */,
C3C00000000000000000001E /* Lyrebird */,
);
productName = ShoeGazeiOSDemo;
productReference = C3C000000000000000000004 /* ShoeGazeiOSDemo.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
C3C000000000000000000001 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1600;
LastUpgradeCheck = 2620;
TargetAttributes = {
C3C000000000000000000011 = {
CreatedOnToolsVersion = 16.0;
};
};
};
buildConfigurationList = C3C000000000000000000015 /* Build configuration list for PBXProject "ShoeGazeiOSDemo" */;
compatibilityVersion = "Xcode 14.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = C3C000000000000000000002;
packageReferences = (
C3C000000000000000000018 /* XCLocalSwiftPackageReference ".." */,
C3C000000000000000000019 /* XCRemoteSwiftPackageReference "Lyrebird" */,
);
productRefGroup = C3C000000000000000000003 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
C3C000000000000000000011 /* ShoeGazeiOSDemo */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
C3C000000000000000000010 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
C3C000000000000000000031 /* Assets.xcassets in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
C3C00000000000000000000E /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
C3C000000000000000000009 /* ShoeGazeiOSDemoApp.swift in Sources */,
C3C00000000000000000000A /* ShoeGazeiOSDemoAppModel.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
C3C000000000000000000013 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGNING_REQUIRED = NO;
CODE_SIGN_STYLE = Automatic;
DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = HE5VJFE9E4;
INFOPLIST_FILE = ShoeGazeiOSDemo/Info.plist;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.music";
IPHONEOS_DEPLOYMENT_TARGET = 18.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeiOSDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
SUPPORTS_MACCATALYST = NO;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 6.0;
TARGETED_DEVICE_FAMILY = 2;
};
name = Debug;
};
C3C000000000000000000014 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGNING_REQUIRED = NO;
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_TEAM = HE5VJFE9E4;
INFOPLIST_FILE = ShoeGazeiOSDemo/Info.plist;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.music";
IPHONEOS_DEPLOYMENT_TARGET = 18.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeiOSDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
SUPPORTS_MACCATALYST = NO;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 6.0;
TARGETED_DEVICE_FAMILY = 2;
};
name = Release;
};
C3C000000000000000000016 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 18.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
C3C000000000000000000017 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 18.0;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = iphoneos;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
C3C000000000000000000012 /* Build configuration list for PBXNativeTarget "ShoeGazeiOSDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
C3C000000000000000000013 /* Debug */,
C3C000000000000000000014 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
C3C000000000000000000015 /* Build configuration list for PBXProject "ShoeGazeiOSDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
C3C000000000000000000016 /* Debug */,
C3C000000000000000000017 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
/* Begin XCLocalSwiftPackageReference section */
C3C000000000000000000018 /* XCLocalSwiftPackageReference ".." */ = {
isa = XCLocalSwiftPackageReference;
relativePath = ..;
};
/* End XCLocalSwiftPackageReference section */
/* Begin XCRemoteSwiftPackageReference section */
C3C000000000000000000019 /* XCRemoteSwiftPackageReference "Lyrebird" */ = {
isa = XCRemoteSwiftPackageReference;
repositoryURL = "https://realizedsound.mooo.com/josh/Lyrebird";
requirement = {
kind = upToNextMajorVersion;
minimumVersion = 1.2.0;
};
};
/* End XCRemoteSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
C3C00000000000000000001A /* LyrebirdShoeGaze */ = {
isa = XCSwiftPackageProductDependency;
package = C3C000000000000000000018 /* XCLocalSwiftPackageReference ".." */;
productName = LyrebirdShoeGaze;
};
C3C00000000000000000001B /* LyrebirdShoeGazeUI */ = {
isa = XCSwiftPackageProductDependency;
package = C3C000000000000000000018 /* XCLocalSwiftPackageReference ".." */;
productName = LyrebirdShoeGazeUI;
};
C3C00000000000000000001C /* LyrebirdUI */ = {
isa = XCSwiftPackageProductDependency;
package = C3C000000000000000000019 /* XCRemoteSwiftPackageReference "Lyrebird" */;
productName = LyrebirdUI;
};
C3C00000000000000000001E /* Lyrebird */ = {
isa = XCSwiftPackageProductDependency;
package = C3C000000000000000000019 /* XCRemoteSwiftPackageReference "Lyrebird" */;
productName = Lyrebird;
};
/* End XCSwiftPackageProductDependency section */
};
rootObject = C3C000000000000000000001 /* Project object */;
}
@@ -1,33 +0,0 @@
{
"originHash" : "cfdd71f4b32d744c862bbe26a8265d75aa9e906275b0fb1b63575b7d68be1b6a",
"pins" : [
{
"identity" : "linenoise-swift",
"kind" : "remoteSourceControl",
"location" : "https://github.com/andybest/linenoise-swift",
"state" : {
"revision" : "afc897c02b030af7333105c4fedcd843a8339238",
"version" : "0.0.3"
}
},
{
"identity" : "lyrebird",
"kind" : "remoteSourceControl",
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
"state" : {
"revision" : "032b7c39d351eba4029e8399e1ab1ee201e8bb5c",
"version" : "1.2.0"
}
},
{
"identity" : "nimble",
"kind" : "remoteSourceControl",
"location" : "https://github.com/Quick/Nimble.git",
"state" : {
"revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0",
"version" : "7.3.4"
}
}
],
"version" : 3
}
@@ -1,78 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2620"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES"
buildArchitectures = "Automatic">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "C3C000000000000000000011"
BuildableName = "ShoeGazeiOSDemo.app"
BlueprintName = "ShoeGazeiOSDemo"
ReferencedContainer = "container:ShoeGazeiOSDemo.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
shouldAutocreateTestPlan = "YES">
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "C3C000000000000000000011"
BuildableName = "ShoeGazeiOSDemo.app"
BlueprintName = "ShoeGazeiOSDemo"
ReferencedContainer = "container:ShoeGazeiOSDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "C3C000000000000000000011"
BuildableName = "ShoeGazeiOSDemo.app"
BlueprintName = "ShoeGazeiOSDemo"
ReferencedContainer = "container:ShoeGazeiOSDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -1,6 +0,0 @@
{
"images" : [
{"filename":"icon_1024.png","idiom":"universal","platform":"ios","size":"1024x1024"}
],
"info" : {"author":"xcode","version":1}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 402 KiB

@@ -1 +0,0 @@
{ "info" : {"author":"xcode","version":1} }
-47
View File
@@ -1,47 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2026 realizedsound. All rights reserved.</string>
<key>NSMicrophoneUsageDescription</key>
<string>ShoeGazeiOSDemo can route a hardware input channel through your pedalboard. Enable microphone access to use Live Input mode.</string>
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
<false/>
</dict>
<key>UILaunchScreen</key>
<dict/>
<key>UIRequiresFullScreen</key>
<false/>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
</array>
</dict>
</plist>
@@ -1,33 +0,0 @@
// ShoeGazeiOSDemoApp.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdShoeGazeUI
/// iOS entry point for the ShoeGaze in-repo demo.
///
/// Holds the `ShoeGazeiOSDemoAppModel` as `@State` so it is created once and
/// owned for the lifetime of the app. The audio engine is **not** started
/// automatically — the user presses Start in the pedalboard (`ShoeGazeView`) to
/// begin audio. The engine is stopped when the view disappears.
@main
struct ShoeGazeiOSDemoApp: App {
@State private var model: ShoeGazeiOSDemoAppModel = ShoeGazeiOSDemoAppModel()
var body: some Scene {
WindowGroup {
NavigationStack {
ScrollView {
ShoeGazeView(shoeGaze: model.shoeGaze, hardwareSampleRate: { model.hardwareSampleRate })
.padding(.horizontal, 12)
}
.navigationTitle("ShoeGaze")
}
.onDisappear { model.stop() }
}
}
}
@@ -1,103 +0,0 @@
// ShoeGazeiOSDemoAppModel.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import AVFoundation
import Observation
import LyrebirdSynth
import LyrebirdShoeGaze
/// Observable model that owns the `SynthesisEngine` and `ShoeGaze` session for
/// the ShoeGaze iOS demo.
///
/// The engine is not started automatically — the pedalboard's Start button
/// (`ShoeGazeView`) drives `engine.start()`. `stop()` is called from `.onDisappear`
/// to release audio resources when the view goes away.
///
/// `AVAudioSession` is activated at init so the hardware sample rate is known
/// before the engine is constructed — iOS devices typically lock to 48 000 Hz
/// regardless of the preferred rate, and querying the session after activation
/// avoids pitch and timing errors.
///
/// The default board (Overdrive → Delay → Reverb → Modulation) uses `.testLoop`
/// as the input source, so no microphone permission is required to run the demo.
/// Switch to `.liveInput(channel: 0)` and set `numInputChannels: 1` in the
/// engine init to route hardware microphone or instrument input through the board.
@Observable
@MainActor
final class ShoeGazeiOSDemoAppModel {
// MARK: - Engine configuration constants
private static let blockSize: Int = 512
private static let outputChannels: Int = 2
private static let numAudioBuses: Int = 256
// MARK: - Owned objects
/// The active ShoeGaze pedalboard session.
private(set) var shoeGaze: ShoeGaze
private let engine: SynthesisEngine
private let iosDriver: iOSAudioDriver
/// The sample rate the audio session actually committed to (for the config mismatch warning).
var hardwareSampleRate: Double? { iosDriver.sessionSampleRate }
// MARK: - Init
init() {
// Activate the session before querying `sampleRate` so the hardware rate
// is reported correctly (iOS locks to 48 000 Hz on most devices).
let session: AVAudioSession = AVAudioSession.sharedInstance()
try? session.setCategory(.playAndRecord,
mode: .default,
options: [.defaultToSpeaker, .allowBluetoothHFP])
try? session.setActive(true)
let sampleRate: Double = session.sampleRate
let driver: iOSAudioDriver = iOSAudioDriver()
let eng: SynthesisEngine = SynthesisEngine(
blockSize: ShoeGazeiOSDemoAppModel.blockSize,
sampleRate: sampleRate,
numOutputChannels: ShoeGazeiOSDemoAppModel.outputChannels,
numInputChannels: 0,
numAudioBuses: ShoeGazeiOSDemoAppModel.numAudioBuses,
driver: driver
)
self.iosDriver = driver
self.engine = eng
self.shoeGaze = ShoeGaze(engine: eng)
do {
let board: PedalBoard = try shoeGaze.addBoard()
board.label = "Demo Board"
try board.add(OverdrivePedal())
try board.add(DelayPedal())
try board.add(ReverbPedal())
try board.add(ModulationPedal())
try shoeGaze.finalizeBoard(board)
} catch {
print("[ShoeGazeiOSDemo] board build failed: \(error)")
}
}
// MARK: - Transport
/// Starts the audio engine. Not called automatically — the pedalboard's Start
/// button drives `engine.start()`; this is here for callers that want to start it.
func start() {
do {
try engine.start()
} catch {
print("[ShoeGazeiOSDemo] engine.start() failed: \(error)")
}
}
/// Stops the audio engine. Call from `.onDisappear`.
func stop() {
engine.stop()
}
}
+3 -2
View File
@@ -11,8 +11,9 @@
// double-registration. The dynamic-product dance used by `LiveCompile/` is only
// required for runtime dylib hot-swap, which ShoeGaze does not do.
//
// The demo app lives at Demo/ShoeGazeDemo.xcodeproj — open ShoeGaze.xcworkspace
// in Xcode and run the ShoeGazeDemo scheme to build it.
// The apps live at Demo/ShoeGazeBuilder.xcodeproj (macOS) and
// Demo/ShoeGazeBuilderiOS.xcodeproj (iPad) — open ShoeGaze.xcworkspace in Xcode
// and run the matching scheme to build them.
import PackageDescription
let package = Package(
+1 -2
View File
@@ -105,12 +105,11 @@ struct ContentView: View {
}
```
## Demo apps
## 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
+53
View File
@@ -1,4 +1,57 @@
# Releases
## ShoeGaze 2.1.0
Tempo comes to the pedals. Delay times and LFO rates can lock to note divisions of the
live tempo — shown with real music-notation glyphs and following the tempo as it
changes — plus a directly-editable BPM, longer delays, and per-control MIDI/key mapping
badges on every pedal.
### Highlights
- **Tempo-synced parameters** — lock a delay time or a modulation rate to a note value
(whole → sixteenth, dotted, triplet); it follows tap tempo, the stepper, the BPM
field, and MIDI. Delay, Feedback Delay, Ping-Pong, Reverse, and Multi-Tap (per tap);
Tremolo, Vibrato, Chorus, Flanger, Phaser, Modulation.
- **Notation glyphs** — the picker draws real note glyphs (augmentation dot for dotted
values, a bracketed "3" over triplets) instead of text.
- **Editable BPM** — type a tempo directly (integer, 30–300); the stepper and tap still
work, and synced pedals follow immediately.
- **Longer delays** — maximum delay time raised to 5 s so slow synced values fit.
- **Control mapping badges** — every pedal shows the PC (footswitch), CC (expression),
or KEY (letter key) binding on each control, with a legend above the board.
- **CC respects tempo sync** — a CC bound to a synced parameter is ignored while synced
(the tempo drives it) and resumes control once the parameter is set back to Free.
### Compatibility
Additive persistence — older rigs load unchanged (every parameter defaults to free),
and 2.1 rigs open in older builds with the tempo-sync state ignored.
## ShoeGaze 2.0.0
Major release. Performance-focused: a visual metronome, a real rig mute with
keyboard control, and rigs that remember their tempo, input, and I/O — plus a
saveable set-list order for hands-free switching between rigs live. The version
jumps to 2.0.0 to align ShoeGaze's numbering with the wider project family.
### Highlights
- **Visual metronome** — a horizontal playhead eases wall-to-wall each beat so you
can anticipate the downbeat, replacing the old flashing LED.
- **Rig Mute (⌘Z)** — hard-silences the whole rig; distinct from Bypass Rig (dry passthrough).
- **Keyboard shortcuts** — ⌘1–⌘9 switch/solo boards, ⌘⇧1–⌘⇧0 load set-list rigs 1–10,
⌘Z mutes. macOS menus + iOS/iPadOS hardware keyboards.
- **Set lists** — reorder rigs by drag or Move Up/Down; the order saves, travels with
an exported archive, and drives the ⌘⇧ slots.
- **Per-rig memory** — tempo, input selection, and engine I/O now persist with a rig.
### Fixed
- Archive import no longer collides set-list positions with existing rigs.
### Removed
- The ShoeGazeDemo / ShoeGazeiOSDemo apps — only the ShoeGazeBuilder (macOS) and
ShoeGazeBuilderiOS (iPad) apps remain.
**Compatibility:** rig persistence is additive — older rigs load unchanged, and 2.0.0
rigs still open in older builds. The bump reflects feature scope + version alignment,
not a format break.
## 1.5.0 — 2026-07-04
-6
View File
@@ -4,12 +4,6 @@
<FileRef
location = "group:.">
</FileRef>
<FileRef
location = "group:Demo/ShoeGazeDemo.xcodeproj">
</FileRef>
<FileRef
location = "group:Demo/ShoeGazeiOSDemo.xcodeproj">
</FileRef>
<FileRef
location = "group:Demo/ShoeGazeBuilder.xcodeproj">
</FileRef>
@@ -1,5 +1,5 @@
{
"originHash" : "91598bde27d299c8e3d95f9dc660396f52cf9b8e78f90ff2652c9d34d869f572",
"originHash" : "39c6a5f1535f779ef8a83b5ea2ab6f965ee3b28ad8419b94679e422a92f75603",
"pins" : [
{
"identity" : "linenoise-swift",
@@ -15,8 +15,8 @@
"kind" : "remoteSourceControl",
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
"state" : {
"revision" : "8a2eb191a204a76735ba7eeac94e18f2e65f1b23",
"version" : "1.2.2"
"revision" : "c058493a9853695c441895a12e9f4a5dbc7295b0",
"version" : "1.2.3"
}
},
{
@@ -22,6 +22,46 @@ public enum InputSource: Equatable {
case liveInput(channel: Int)
}
// MARK: - Codable
/// Persisted so a saved rig round-trips its input selection. Encoded as a `kind` discriminator
/// plus an optional `channel`, so adding future cases stays forward-tolerant.
extension InputSource: Codable {
private enum Kind: String, Codable {
case testLoop
case liveInput
}
private enum CodingKeys: String, CodingKey {
case kind
case channel
}
public init(from decoder: Decoder) throws {
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
let kind: Kind = try container.decode(Kind.self, forKey: .kind)
switch kind {
case .testLoop:
self = .testLoop
case .liveInput:
let channel: Int = try container.decode(Int.self, forKey: .channel)
self = .liveInput(channel: channel)
}
}
public func encode(to encoder: Encoder) throws {
var container: KeyedEncodingContainer<CodingKeys> = encoder.container(keyedBy: CodingKeys.self)
switch self {
case .testLoop:
try container.encode(Kind.testLoop, forKey: .kind)
case .liveInput(let channel):
try container.encode(Kind.liveInput, forKey: .kind)
try container.encode(channel, forKey: .channel)
}
}
}
/// Validates a `.liveInput` channel against the engine and returns the engine audio-bus
/// index of that hardware input channel.
///
@@ -38,6 +38,8 @@ public final class MIDIController {
case cc(MIDIMap.CCTarget)
/// A toggle action awaiting a Program Change.
case action(MIDIMap.Action)
/// A toggle action awaiting a computer key press.
case key(MIDIMap.Action)
}
/// The control currently armed for Learn, or `nil` when not learning. Observable so the UI can
@@ -248,6 +250,14 @@ public final class MIDIController {
continue
}
guard let resolved: ResolvedCC = resolveCC(binding.target) else { continue }
// A parameter locked to a note division is driven by the tempo; a CC write would be
// overwritten on the next tempo change, so ignore it here. The binding stays intact and
// resumes control the moment the parameter is set back to Free.
if case let .pedalControl(pedalID, _, _, _) = binding.target,
let pedal: Pedal = pedal(id: pedalID),
pedal.isNodeTempoSynced(resolved.node) {
continue
}
let mapped: Double = resolved.range.lowerBound
+ norm * (resolved.range.upperBound - resolved.range.lowerBound)
resolved.node.update(mapped)
@@ -438,6 +448,89 @@ public final class MIDIController {
return nil
}
// MARK: - Key learn + apply
/// Arms MIDI Learn for a toggle action awaiting a key: the next ingested key press binds to it.
public func armKeyLearn(_ action: MIDIMap.Action) {
learnTarget = .key(action)
}
/// The key binding currently assigned to an action, or `nil` if unbound.
public func keyBinding(for action: MIDIMap.Action) -> MIDIMap.KeyBinding? {
shoeGaze?.midiMap?.keys.first { $0.action == action }
}
/// Removes any key binding assigned to an action.
public func clearKeyBinding(for action: MIDIMap.Action) {
guard let shoeGaze: ShoeGaze = shoeGaze, var map: MIDIMap = shoeGaze.midiMap else { return }
let before: Int = map.keys.count
map.keys.removeAll { $0.action == action }
guard map.keys.count != before else { return }
shoeGaze.midiMap = map
onMapChanged?()
}
/// Normalizes a raw key string to the single lowercased character used for storage and matching,
/// or `nil` when the input is not exactly one letter or digit. Restricting to alphanumerics keeps
/// non-printing keys (Return, Tab, Escape, arrows — all single `Character`s) from being learned
/// and then silently swallowed app-wide.
private func normalizedKey(_ raw: String) -> String? {
let lowered: String = raw.lowercased()
guard lowered.count == 1, let character: Character = lowered.first, character.isASCII,
character.isLetter || character.isNumber else { return nil }
return lowered
}
/// Routes a computer key press: captures a binding when armed for key Learn, otherwise performs
/// every action bound to that key + modifier combination. Returns `true` when the press was
/// consumed (learned or matched a binding) so the caller can swallow the event; `false` lets it
/// fall through.
///
/// - Parameters:
/// - rawKey: The pressed key; normalized to a single lowercased character.
/// - modifiers: The modifier keys held with the press. `a` and `⇧a` bind independently.
@discardableResult
public func ingestKey(_ rawKey: String, modifiers: MIDIMap.KeyModifiers = []) -> Bool {
guard let key: String = normalizedKey(rawKey) else { return false }
if case .key(let action) = learnTarget {
captureKey(key: key, modifiers: modifiers, action: action)
return true
}
return applyKey(key, modifiers: modifiers)
}
/// Captures a learned key binding for the armed action and clears the Learn state. One binding
/// per action — re-learning replaces it — but a single key may drive multiple actions (a scene),
/// so we do not steal by key.
private func captureKey(key: String, modifiers: MIDIMap.KeyModifiers, action: MIDIMap.Action) {
learnTarget = nil
guard let shoeGaze: ShoeGaze = shoeGaze else { return }
let binding: MIDIMap.KeyBinding = MIDIMap.KeyBinding(
key: key,
modifiers: modifiers,
action: action,
displayNameHint: hint(for: action)
)
var map: MIDIMap = shoeGaze.midiMap ?? MIDIMap.empty
map.keys.removeAll { $0.action == action }
map.keys.append(binding)
shoeGaze.midiMap = map
onMapChanged?()
}
/// Performs every action bound to a key + modifier combination. Returns `true` when at least one
/// binding matched (key and modifiers both equal).
private func applyKey(_ key: String, modifiers: MIDIMap.KeyModifiers) -> Bool {
guard let shoeGaze: ShoeGaze = shoeGaze, let map: MIDIMap = shoeGaze.midiMap else { return false }
var matched: Bool = false
for binding: MIDIMap.KeyBinding in map.keys
where binding.key == key && binding.modifiers == modifiers {
perform(binding.action)
matched = true
}
return matched
}
// MARK: - Device detection
private func refreshDevices() {
+105 -1
View File
@@ -24,6 +24,10 @@ public struct MIDIMap: Codable, Equatable, Sendable {
/// Control-Change → pedal-knob bindings (expression pedals).
public var ccs: [CCBinding]
/// Computer letter/digit key → action bindings. Same toggle ``Action`` set as ``switches`` —
/// a key press is a software footswitch — but keys never drive continuous CC targets.
public var keys: [KeyBinding]
/// An empty map (no bindings).
public static let empty: MIDIMap = MIDIMap()
@@ -32,12 +36,32 @@ public struct MIDIMap: Codable, Equatable, Sendable {
/// - Parameters:
/// - switches: Program-Change bindings. Defaults to empty.
/// - ccs: Control-Change bindings. Defaults to empty.
/// - keys: Letter-key bindings. Defaults to empty.
public init(
switches: [SwitchBinding] = [],
ccs: [CCBinding] = []
ccs: [CCBinding] = [],
keys: [KeyBinding] = []
) {
self.switches = switches
self.ccs = ccs
self.keys = keys
}
private enum CodingKeys: String, CodingKey {
case switches
case ccs
case keys
}
/// Decodes a map, tolerating an absent `keys` list so a rig saved before keyboard mapping
/// existed still decodes with its `switches` / `ccs` intact (synthesized Codable would fail
/// the whole map on the missing key, silently dropping the MIDI bindings too). `encode(to:)`
/// stays synthesized and always writes `keys` (empty when there are none).
public init(from decoder: Decoder) throws {
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
self.switches = try container.decode([SwitchBinding].self, forKey: .switches)
self.ccs = try container.decode([CCBinding].self, forKey: .ccs)
self.keys = try container.decodeIfPresent([KeyBinding].self, forKey: .keys) ?? []
}
// MARK: - Action
@@ -127,6 +151,86 @@ public struct MIDIMap: Codable, Equatable, Sendable {
}
}
// MARK: - Key modifiers
/// The modifier keys that qualify a ``KeyBinding``, so `a` and `⇧a` (and `⌃a`, `⌥a`) are
/// distinct triggers. Shift is a modifier here rather than being folded into the key's case,
/// which keeps the base key a single lowercased character on every platform. Command is
/// deliberately absent — it is reserved for the app's menu keyboard shortcuts.
public struct KeyModifiers: OptionSet, Codable, Equatable, Hashable, Sendable {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
/// The Shift key (`⇧`).
public static let shift: KeyModifiers = KeyModifiers(rawValue: 1 << 0)
/// The Control key (`⌃`).
public static let control: KeyModifiers = KeyModifiers(rawValue: 1 << 1)
/// The Option key (`⌥`).
public static let option: KeyModifiers = KeyModifiers(rawValue: 1 << 2)
}
// MARK: - Key binding
/// A computer letter/digit key bound to a toggle ``Action``. Fires on key-down when no text
/// field is focused; the same latch semantics as a footswitch (booleans flip in software,
/// `boardSolo` is exclusive). `key` is a single lowercased character; ``modifiers`` distinguish
/// `a` from `⇧a`, `⌃a`, and `⌥a`.
public struct KeyBinding: Codable, Equatable, Sendable {
/// The bound key as a single lowercased character (e.g. `"b"`, `"3"`).
public var key: String
/// The modifier keys held with ``key``. Empty for an unmodified press.
public var modifiers: KeyModifiers
/// The control to toggle.
public var action: Action
/// The resolved control's display name at learn time, for stale-binding detection.
public var displayNameHint: String?
/// Creates a key binding.
///
/// - Parameters:
/// - key: The bound key, normalized to a single lowercased character.
/// - modifiers: The qualifying modifier keys. Defaults to none.
/// - action: The toggle action to perform.
/// - displayNameHint: Resolved control name at learn time. Defaults to `nil`.
public init(
key: String,
modifiers: KeyModifiers = [],
action: Action,
displayNameHint: String? = nil
) {
self.key = key
self.modifiers = modifiers
self.action = action
self.displayNameHint = displayNameHint
}
private enum CodingKeys: String, CodingKey {
case key
case modifiers
case action
case displayNameHint
}
/// Decodes a key binding, defaulting `modifiers` to none when absent so a binding saved
/// before modifiers existed still decodes (unmodified, as it was learned). `encode(to:)`
/// stays synthesized.
public init(from decoder: Decoder) throws {
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
self.key = try container.decode(String.self, forKey: .key)
self.modifiers = try container.decodeIfPresent(KeyModifiers.self, forKey: .modifiers) ?? []
self.action = try container.decode(Action.self, forKey: .action)
self.displayNameHint = try container.decodeIfPresent(String.self, forKey: .displayNameHint)
}
}
// MARK: - CC target
/// A continuous control an expression pedal can drive — either a specific pedal control (a knob
+64
View File
@@ -73,6 +73,16 @@ open class Pedal: SynthesizerBase {
/// the engine owns the node tree, not the reverse.
public internal(set) weak var hostEngine: SynthesisEngine?
// MARK: - Tempo sync
/// Sync state per tempo-syncable parameter, keyed by ``TempoSyncableParam/key``. A missing
/// key means ``TempoSync/free``. Persisted in ``PedalState`` and restored on rig load.
public internal(set) var tempoSync: [String: TempoSync] = [:]
/// Observable signal bumped on every ``tempoSync`` change so a SwiftUI badge re-renders when the
/// sync state changes through any path (the picker, a preset load, or a lightweight recall).
public let tempoSyncRevision: TempoSyncRevision = TempoSyncRevision()
// MARK: - Identity / routing
/// Stable identity for this pedal instance, persisted in ``PedalState`` and used by MIDI
@@ -266,6 +276,60 @@ open class Pedal: SynthesizerBase {
return knobControls + sliderControls
}
// MARK: - Tempo sync
/// Parameters this pedal exposes to tempo sync (delay times, LFO rates). Empty by default —
/// override in subclasses whose time- or rate-based parameters can lock to the tempo.
///
/// Each descriptor's ``TempoSyncableParam/key`` must be unique within the pedal and stable
/// across versions (it is the persistence key). Order is the order the sync controls appear.
open var tempoSyncableParams: [TempoSyncableParam] {
[]
}
/// Recomputes and writes every parameter currently locked to a note division, from the shared
/// clock's tempo. Main-thread only — writing a `@UIParam` is the same path as a knob turn.
///
/// A no-op when no clock is injected. Free parameters are left untouched. A synced value that
/// falls outside the parameter's range (a long division past a delay's maximum time) is clamped.
/// Called by `ShoeGaze` whenever the tempo changes and whenever a parameter's sync state changes.
public func applyTempoSync() {
guard let clock: LyrebirdClock = clock else { return }
let bpm: Double = clock.bpm
guard bpm > 0 else { return }
for param: TempoSyncableParam in tempoSyncableParams {
guard case .division(let division) = tempoSync[param.key] ?? .free else { continue }
param.node.update(param.value(for: division, bpm: bpm).value)
}
}
/// Sets one parameter's sync state and immediately recomputes it. Pass ``TempoSync/free`` to
/// return the parameter to knob control (its value stays at the last synced number until the
/// knob moves it), or `.division(_:)` to lock it to a note value of the live tempo.
///
/// - Parameters:
/// - sync: The new sync state.
/// - key: The ``TempoSyncableParam/key`` of the parameter to update.
public func setSync(_ sync: TempoSync, for key: String) {
tempoSync[key] = sync
tempoSyncRevision.bump()
applyTempoSync()
}
/// Whether `node` backs a tempo-syncable parameter currently locked to a note division.
///
/// Used by MIDI to leave a synced parameter alone: its value is derived from the tempo, so a CC
/// write would be immediately overwritten on the next tempo change. Matches by node identity, so
/// it stays correct regardless of control ordering. Returns `false` for a free or non-syncable node.
public func isNodeTempoSynced(_ node: UIParamNode) -> Bool {
for param: TempoSyncableParam in tempoSyncableParams where param.node === node {
if case .division = tempoSync[param.key] ?? .free {
return true
}
}
return false
}
// MARK: - Subclass hook
/// Returns the processed (wet) mono signal for this pedal.
@@ -61,6 +61,12 @@ public final class ChorusPedal: Pedal {
private let rateRange: ClosedRange<Double> = 0.05 ... 6.0
private let depthRange: ClosedRange<Double> = 0.0005 ... 0.008
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "rate", label: "Rate", node: $rate, kind: .rate, range: rateRange),
]
}
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Rate", node: $rate, range: rateRange),
@@ -22,7 +22,7 @@ import LyrebirdUI
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
///
/// - Parameters:
/// - time: Delay time in seconds. Range `[0.01, 1.5]`. Defaults to `0.25`.
/// - time: Delay time in seconds. Range `[0.01, 5.0]`. Defaults to `0.25`.
/// - feedback: Feedback amount expressed as decay time in seconds — the time
/// for echoes to fall to `targetAmp` (−60 dB). Longer values produce more
/// repeats. Range `[0.05, 6.0]` seconds. Defaults to `1.0`.
@@ -35,7 +35,7 @@ public final class DelayPedal: Pedal {
// MARK: - Parameters
/// Delay time in seconds. Range [0.01, 1.5].
/// Delay time in seconds. Range [0.01, 5.0].
@UIParam public var time: Double = 0.25
/// Feedback decay time in seconds (time to reach −60 dB amplitude).
@@ -44,7 +44,7 @@ public final class DelayPedal: Pedal {
// MARK: - Constants
/// Maximum supported delay time in seconds. Sizes the delay line buffer at init.
private let maxDelayTime: Double = 1.5
private let maxDelayTime: Double = 5.0
/// Amplitude target for the `decayTime` calculation (−60 dB).
private let targetAmp: Double = 0.001
@@ -55,7 +55,7 @@ public final class DelayPedal: Pedal {
// MARK: - UI knobs
/// Delay-time knob range in seconds.
private let timeRange: ClosedRange<Double> = 0.01 ... 1.5
private let timeRange: ClosedRange<Double> = 0.01 ... 5.0
/// Feedback (decay-time) knob range in seconds.
private let feedbackRange: ClosedRange<Double> = 0.05 ... 6.0
@@ -86,6 +86,12 @@ public final class DelayPedal: Pedal {
]
}
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "time", label: "Time", node: $time, kind: .time, range: timeRange),
]
}
// MARK: - Effect
/// Applies a feedback delay line. Returns the pure wet (delayed) signal.
@@ -45,7 +45,7 @@ public final class FeedbackDelayPedal: Pedal {
// MARK: - Constants
/// Maximum supported delay time in seconds. Sizes the delay-line buffer at init.
private let maxDelayTime: Double = 1.5
private let maxDelayTime: Double = 5.0
/// Amplitude target for the `decayTime` calculation (−60 dB).
private let targetAmp: Double = 0.001
@@ -58,12 +58,18 @@ public final class FeedbackDelayPedal: Pedal {
// MARK: - Ranges
private let timeRange: ClosedRange<Double> = 0.02 ... 1.5
private let timeRange: ClosedRange<Double> = 0.02 ... 5.0
private let feedbackRange: ClosedRange<Double> = 0.1 ... 8.0
private let toneRange: ClosedRange<Double> = 500.0 ... 8000.0
// MARK: - Knobs
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "time", label: "Time", node: $time, kind: .time, range: timeRange),
]
}
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Time", node: $time, range: timeRange),
@@ -57,6 +57,12 @@ public final class FlangerPedal: Pedal {
// MARK: - Knobs
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "rate", label: "Rate", node: $rate, kind: .rate, range: rateRange),
]
}
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Rate", node: $rate, range: rateRange),
@@ -90,6 +90,12 @@ public final class ModulationPedal: Pedal {
)
}
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "rate", label: "Rate", node: $rate, kind: .rate, range: rateRange),
]
}
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Rate", node: $rate, range: rateRange),
@@ -58,18 +58,26 @@ public final class MultiTapDelayPedal: Pedal {
// MARK: - Constants
/// Maximum supported per-tap delay time in seconds. Sizes each delay-line buffer at init.
private let maxDelayTime: Double = 1.0
private let maxDelayTime: Double = 5.0
/// Partial wet/dry blend so the dry note and its taps coexist.
private static let defaultMix: Double = 0.4
// MARK: - Ranges
private let timeRange: ClosedRange<Double> = 0.01 ... 1.0
private let timeRange: ClosedRange<Double> = 0.01 ... 5.0
private let volRange: ClosedRange<Double> = 0.0 ... 1.0
// MARK: - Knobs
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "time1", label: "Time 1", node: $time1, kind: .time, range: timeRange),
TempoSyncableParam(key: "time2", label: "Time 2", node: $time2, kind: .time, range: timeRange),
TempoSyncableParam(key: "time3", label: "Time 3", node: $time3, kind: .time, range: timeRange),
]
}
/// Two rows of three: the three tap times, then the three tap volumes.
public override var effectKnobs: [PedalKnob] {
[
@@ -68,6 +68,12 @@ public final class PhaserPedal: Pedal {
/// Feedback knob range (all-pass feedback gain).
private let feedbackRange: ClosedRange<Double> = 0.0 ... 0.9
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "rate", label: "Rate", node: $rate, kind: .rate, range: rateRange),
]
}
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Rate", node: $rate, range: rateRange),
@@ -32,7 +32,7 @@ import LyrebirdUI
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
///
/// - Parameters:
/// - time: Delay time per tap in seconds. Range `[0.05, 1.0]`. Defaults to `0.3`.
/// - time: Delay time per tap in seconds. Range `[0.05, 5.0]`. Defaults to `0.3`.
/// - feedback: Feedback as decay time in seconds (time for echoes to fall to −60 dB).
/// Range `[0.05, 6.0]`. Defaults to `1.2`.
public final class PingPongDelayPedal: Pedal {
@@ -44,7 +44,7 @@ public final class PingPongDelayPedal: Pedal {
// MARK: - Parameters
/// Delay time per tap in seconds. Range [0.05, 1.0].
/// Delay time per tap in seconds. Range [0.05, 5.0].
@UIParam public var time: Double = 0.3
/// Feedback decay time in seconds (time to reach −60 dB amplitude). Range [0.05, 6.0].
@@ -53,7 +53,7 @@ public final class PingPongDelayPedal: Pedal {
// MARK: - Constants
/// Maximum supported delay time in seconds. Sizes both delay lines at init.
private let maxDelayTime: Double = 1.0
private let maxDelayTime: Double = 5.0
/// Amplitude target for the `decayTime` calculation (−60 dB).
private let targetAmp: Double = 0.001
@@ -67,7 +67,7 @@ public final class PingPongDelayPedal: Pedal {
// MARK: - UI knobs
/// Delay-time knob range in seconds.
private let timeRange: ClosedRange<Double> = 0.05 ... 1.0
private let timeRange: ClosedRange<Double> = 0.05 ... 5.0
/// Feedback (decay-time) knob range in seconds.
private let feedbackRange: ClosedRange<Double> = 0.05 ... 6.0
@@ -96,6 +96,12 @@ public final class PingPongDelayPedal: Pedal {
)
}
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "time", label: "Time", node: $time, kind: .time, range: timeRange),
]
}
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Time", node: $time, range: timeRange),
@@ -15,7 +15,7 @@ import LyrebirdUI
/// so the pedal's `Mix` knob sets the wet/dry blend.
///
/// ## Knobs
/// - `time`: Reverse segment length in seconds. Range `[0.05, 2.0]`.
/// - `time`: Reverse segment length in seconds. Range `[0.05, 5.0]`.
/// - `feedback`: Reverse-trail feedback. Range `[0, 0.95]`.
public final class ReverseDelayPedal: Pedal {
@@ -26,7 +26,7 @@ public final class ReverseDelayPedal: Pedal {
// MARK: - Parameters
/// Reverse segment length in seconds. Range [0.05, 2.0].
/// Reverse segment length in seconds. Range [0.05, 5.0].
@UIParam public var time: Double = 0.5
/// Reverse-trail feedback. Range [0, 0.95].
@@ -38,15 +38,21 @@ public final class ReverseDelayPedal: Pedal {
private static let defaultMix: Double = 0.5
/// Maximum segment length the buffers are allocated for, in seconds.
private let maxDelayTime: Double = 2.0
private let maxDelayTime: Double = 5.0
// MARK: - Ranges
private let timeRange: ClosedRange<Double> = 0.05 ... 2.0
private let timeRange: ClosedRange<Double> = 0.05 ... 5.0
private let feedbackRange: ClosedRange<Double> = 0.0 ... 0.95
// MARK: - Knobs
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "time", label: "Time", node: $time, kind: .time, range: timeRange),
]
}
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Time", node: $time, range: timeRange),
@@ -63,6 +63,12 @@ public final class TremoloPedal: Pedal {
/// Depth knob range (modulation fraction).
private let depthRange: ClosedRange<Double> = 0.0 ... 1.0
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "rate", label: "Rate", node: $rate, kind: .rate, range: rateRange),
]
}
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Rate", node: $rate, range: rateRange),
@@ -50,6 +50,12 @@ public final class VibratoPedal: Pedal {
// MARK: - Knobs
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "rate", label: "Rate", node: $rate, kind: .rate, range: rateRange),
]
}
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Rate", node: $rate, range: rateRange),
@@ -27,7 +27,8 @@ extension Pedal {
switchValues: switchValues,
sliderValues: sliderValues,
selectorValues: selectorValues,
bypass: bypass
bypass: bypass,
tempoSync: tempoSync.isEmpty ? nil : tempoSync
)
}
@@ -61,5 +62,9 @@ extension Pedal {
selector.node.update(value)
}
bypass = state.bypass
// Restore tempo-sync state. The synced values themselves are recomputed from the rig's
// tempo by `ShoeGaze` after the rebuild, so no clock is required here.
tempoSync = state.tempoSync ?? [:]
tempoSyncRevision.bump()
}
}
@@ -45,6 +45,11 @@ public struct PedalState: Codable, Equatable {
/// Bypass parameter value. `0.0` = engaged, `1.0` = bypassed.
public let bypass: Double
/// Tempo-sync state per syncable parameter, keyed by ``TempoSyncableParam/key``. `nil` for a
/// pedal with no synced parameters, and for presets saved before tempo sync existed — both
/// decode to "all parameters free".
public let tempoSync: [String: TempoSync]?
/// Creates a pedal state snapshot.
///
/// - Parameters:
@@ -54,6 +59,7 @@ public struct PedalState: Codable, Equatable {
/// - sliderValues: Current slider values in `Pedal.effectSliders` order. Defaults to empty.
/// - selectorValues: Current selector values in `Pedal.effectSelectors` order. Defaults to empty.
/// - bypass: Bypass parameter value (`0.0` = engaged, `1.0` = bypassed).
/// - tempoSync: Tempo-sync state per syncable parameter, or `nil` for none. Defaults to `nil`.
public init(
id: UUID = UUID(),
type: String,
@@ -61,7 +67,8 @@ public struct PedalState: Codable, Equatable {
switchValues: [Double] = [],
sliderValues: [Double] = [],
selectorValues: [Double] = [],
bypass: Double
bypass: Double,
tempoSync: [String: TempoSync]? = nil
) {
self.id = id
self.type = type
@@ -70,6 +77,7 @@ public struct PedalState: Codable, Equatable {
self.sliderValues = sliderValues
self.selectorValues = selectorValues
self.bypass = bypass
self.tempoSync = tempoSync
}
private enum CodingKeys: String, CodingKey {
@@ -80,10 +88,11 @@ public struct PedalState: Codable, Equatable {
case sliderValues
case selectorValues
case bypass
case tempoSync
}
/// Decodes a snapshot, tolerating presets saved before `switchValues` / `sliderValues` /
/// `selectorValues` existed by defaulting the missing keys to an empty array.
/// `selectorValues` / `tempoSync` existed by defaulting the missing keys.
public init(from decoder: any Decoder) throws {
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID()
@@ -93,5 +102,6 @@ public struct PedalState: Codable, Equatable {
self.sliderValues = try container.decodeIfPresent([Double].self, forKey: .sliderValues) ?? []
self.selectorValues = try container.decodeIfPresent([Double].self, forKey: .selectorValues) ?? []
self.bypass = try container.decode(Double.self, forKey: .bypass)
self.tempoSync = try container.decodeIfPresent([String: TempoSync].self, forKey: .tempoSync)
}
}
@@ -43,6 +43,14 @@ public struct RigEntry: Codable, Identifiable, Equatable {
/// The full rig snapshot — every board, segment, and pedal parameter.
public let state: ShoeGazeState
/// The rig's position in the user's manually-ordered set list, or `nil` for a rig that has
/// not been placed (a legacy entry saved before ordering existed, or one not yet reordered).
///
/// Persisted per-file and inside archive export/import, so a set-list order travels with a
/// shared or backed-up library. `RigLibraryStore` sorts placed entries by this index and
/// falls back to name/date for unplaced ones. Optional, so older files decode cleanly.
public let sortIndex: Int?
/// Creates a rig library entry.
///
/// - Parameters:
@@ -51,11 +59,13 @@ public struct RigEntry: Codable, Identifiable, Equatable {
/// - 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.
/// - sortIndex: Manual set-list position, or `nil` when unplaced. Defaults to `nil`.
public init(
id: UUID = UUID(),
name: String,
savedAt: Date = Date(),
state: ShoeGazeState
state: ShoeGazeState,
sortIndex: Int? = nil
) {
self.id = id
self.name = name
@@ -64,6 +74,16 @@ public struct RigEntry: Codable, Identifiable, Equatable {
// disk round-trip.
self.savedAt = Date(timeIntervalSince1970: savedAt.timeIntervalSince1970.rounded())
self.state = state
self.sortIndex = sortIndex
}
/// Returns a copy of this entry placed at `index` in the set list, keeping its identity,
/// name, timestamp, and state. Used by `RigLibraryStore` reordering.
///
/// - Parameter index: The new set-list position, or `nil` to unplace.
/// - Returns: A copy at the new `sortIndex`.
public func reordered(to index: Int?) -> RigEntry {
RigEntry(id: id, name: name, savedAt: savedAt, state: state, sortIndex: index)
}
/// Returns a copy of this entry with a new `name`, a fresh `id`, and `savedAt` updated to
@@ -78,7 +98,9 @@ public struct RigEntry: Codable, Identifiable, Equatable {
name: String,
date: Date = Date()
) -> RigEntry {
RigEntry(id: UUID(), name: name, savedAt: date, state: state)
// A duplicate is unplaced (`sortIndex: nil`) so the store appends it to the set list rather
// than colliding with the source's position.
RigEntry(id: UUID(), name: name, savedAt: date, state: state, sortIndex: nil)
}
/// Returns a copy of this entry with a new `name` and `savedAt` updated to `date`, keeping
@@ -93,6 +115,7 @@ public struct RigEntry: Codable, Identifiable, Equatable {
to name: String,
date: Date = Date()
) -> RigEntry {
RigEntry(id: id, name: name, savedAt: date, state: state)
// Preserve the set-list position on rename — only the name and timestamp change.
RigEntry(id: id, name: name, savedAt: date, state: state, sortIndex: sortIndex)
}
}
@@ -176,14 +176,17 @@ public final class RigLibraryStore {
/// 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 {
// Place the entry in the set list first (new rigs append; overwrites keep their position),
// so the persisted file carries a stable `sortIndex`.
let placed: RigEntry = placedForSave(entry)
// 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 data: Data = try encode(placed)
let target: URL = fileURL(for: placed)
let directory: URL = self.directory
let id: UUID = entry.id
let id: UUID = placed.id
let coordinated: Bool = isICloud
upsert(entry)
upsert(placed)
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),
@@ -198,6 +201,87 @@ public final class RigLibraryStore {
}
}
// MARK: - Reordering
/// Moves entries within the set list (SwiftUI `onMove` semantics), renumbers every entry's
/// `sortIndex` to its new dense position, and persists the changed files.
///
/// - Parameters:
/// - source: The indices being moved, into the current `entries` order.
/// - destination: The insertion offset, per SwiftUI `List.onMove`.
public func move(fromOffsets source: IndexSet, toOffset destination: Int) {
var ordered: [RigEntry] = entries
ordered.move(fromOffsets: source, toOffset: destination)
renumberAndPersist(ordered)
}
/// Moves `entry` one slot earlier in the set list. No-op if it is already first or absent.
public func moveUp(_ entry: RigEntry) {
guard let index: Int = entries.firstIndex(where: { $0.id == entry.id }), index > 0 else { return }
var ordered: [RigEntry] = entries
ordered.swapAt(index, index - 1)
renumberAndPersist(ordered)
}
/// Moves `entry` one slot later in the set list. No-op if it is already last or absent.
public func moveDown(_ entry: RigEntry) {
guard let index: Int = entries.firstIndex(where: { $0.id == entry.id }),
index < entries.count - 1 else { return }
var ordered: [RigEntry] = entries
ordered.swapAt(index, index + 1)
renumberAndPersist(ordered)
}
/// Reorders the set list to match `orderedIDs`, renumbers every entry, and persists the changes.
/// Any entry not named in `orderedIDs` is appended in its current relative order (a safety net;
/// drag reorder always passes the full id list). Used by the sidebar's drag-to-reorder.
///
/// - Parameter orderedIDs: The desired full ordering, by entry id.
public func applyOrder(_ orderedIDs: [UUID]) {
let byID: [UUID: RigEntry] = Dictionary(entries.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first })
var ordered: [RigEntry] = orderedIDs.compactMap { byID[$0] }
for entry: RigEntry in entries where !orderedIDs.contains(entry.id) {
ordered.append(entry)
}
renumberAndPersist(ordered)
}
/// Renumbers `ordered` so each entry's `sortIndex` equals its position, updates the in-memory
/// list, and writes only the files whose index actually changed.
private func renumberAndPersist(_ ordered: [RigEntry]) {
var renumbered: [RigEntry] = []
var changed: [RigEntry] = []
for (position, entry) in ordered.enumerated() {
if entry.sortIndex == position {
renumbered.append(entry)
} else {
let moved: RigEntry = entry.reordered(to: position)
renumbered.append(moved)
changed.append(moved)
}
}
entries = RigLibraryStore.sorted(renumbered)
for entry: RigEntry in changed { persistToDisk(entry) }
}
/// Writes `entry`'s JSON file on the background queue without touching the in-memory list or
/// re-sorting — the reorder path already updated `entries` in one shot.
private func persistToDisk(_ entry: RigEntry) {
guard let data: Data = try? encode(entry) else { return }
let target: URL = fileURL(for: entry)
let directory: URL = self.directory
let id: UUID = entry.id
let coordinated: Bool = isICloud
ioQueue.async {
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] reorder write failed: \(error)") }
}
}
/// Deletes `entry` from memory immediately and removes its file on the background queue.
///
/// - Parameter entry: The rig entry to remove.
@@ -328,10 +412,13 @@ public final class RigLibraryStore {
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.
// Avoid clobbering an existing rig that happens to share this id. Either way, clear the
// set-list position so the import appends after the existing entries (in archive order)
// rather than colliding with their indices — `duplicated` already unplaces; a
// non-colliding entry is explicitly unplaced via `reordered(to: nil)`.
let toSave: RigEntry = existingIDs.contains(entry.id)
? entry.duplicated(name: entry.name, date: entry.savedAt)
: entry
: entry.reordered(to: nil)
try save(toSave)
added += 1
}
@@ -549,14 +636,31 @@ public final class RigLibraryStore {
entries = RigLibraryStore.sorted(next)
}
/// Sorts entries by name (case-insensitive), then most-recently-saved first, then id for a
/// fully deterministic order.
/// Sorts entries by manual set-list position first (placed entries, ascending), then — for
/// unplaced entries or ties — by name (case-insensitive), most-recently-saved first, and id,
/// for a fully deterministic order.
private static func sorted(_ entries: [RigEntry]) -> [RigEntry] {
entries.sorted { lhs, rhs in
let lhsIndex: Int = lhs.sortIndex ?? Int.max
let rhsIndex: Int = rhs.sortIndex ?? Int.max
if lhsIndex != rhsIndex { return lhsIndex < rhsIndex }
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
}
}
/// Assigns a set-list position to an entry about to be saved so every stored rig is placed:
/// an explicit index is kept as-is; overwriting an existing rig with an unplaced snapshot
/// preserves that rig's current position; a brand-new unplaced rig appends after the last one.
private func placedForSave(_ entry: RigEntry) -> RigEntry {
if entry.sortIndex != nil { return entry }
if let existing: RigEntry = entries.first(where: { $0.id == entry.id }),
let existingIndex: Int = existing.sortIndex {
return entry.reordered(to: existingIndex)
}
let nextIndex: Int = (entries.compactMap { $0.sortIndex }.max() ?? -1) + 1
return entry.reordered(to: nextIndex)
}
}
@@ -60,6 +60,35 @@ extension ShoeGaze {
try rebuildAllBoards(from: snapshot)
}
/// Applies a rig snapshot's saved hardware channel layout (``ShoeGazeState/numInputChannels`` /
/// ``ShoeGazeState/numOutputChannels``) to the engine — a **deliberate opt-in**.
///
/// ``loadRig(from:)`` persists a rig's I/O but does not auto-apply it: forcing the engine's
/// channel layout on every load would override the user's global engine config and clobber the
/// enable-live-input flow. Call this explicitly (e.g. from the engine-config UI, or a "match rig
/// I/O" action) when you do want the rig's saved layout. Reuses ``reconfigureEngine(...)`` — so
/// it captures the current rig and rebuilds every board at the new layout.
///
/// A no-op (returns `false`) when the snapshot carries no saved counts or they already match.
///
/// - Parameter state: The rig snapshot whose channel layout should be applied.
/// - Returns: `true` if the engine was reconfigured, `false` if nothing needed to change.
/// - Throws: `SynthesisEngineConfigError.engineIsRunning` if the engine is running, or any error
/// from ``reconfigureEngine(sampleRate:inputChannels:outputChannels:)``.
@discardableResult
public func applyChannelLayout(from state: ShoeGazeState) throws -> Bool {
guard !engine.isRunning else { throw SynthesisEngineConfigError.engineIsRunning }
guard let inCount: Int = state.numInputChannels,
let outCount: Int = state.numOutputChannels else { return false }
guard inCount != engine.numInputChannels || outCount != engine.numOutputChannels else { return false }
try reconfigureEngine(
sampleRate: engine.sampleRate,
inputChannels: inCount,
outputChannels: outCount
)
return true
}
/// Default samples-per-frame captured by the scope tap.
public static let defaultScopeBufferSize: Int = 2_048
@@ -18,7 +18,15 @@ extension ShoeGaze {
/// - Returns: A `ShoeGazeState` reflecting the current rig.
public func captureState() -> ShoeGazeState {
let boardStates: [BoardState] = boards.map { $0.captureState() }
return ShoeGazeState(boards: boardStates, midiMap: midiMap)
return ShoeGazeState(
boards: boardStates,
midiMap: midiMap,
bpm: clock.bpm,
tempoEnabled: tempoEnabled,
inputSource: inputSource,
numInputChannels: engine.numInputChannels,
numOutputChannels: engine.numOutputChannels
)
}
/// Captures the current rig as a named ``RigEntry`` suitable for the rig library.
@@ -93,11 +101,45 @@ extension ShoeGaze {
throw PresetError.unsupportedVersion(state.version)
}
// Note: `state.numInputChannels` / `numOutputChannels` are persisted with the rig (see
// `captureState`) but intentionally NOT auto-applied here. Forcing the engine's channel
// layout on every load would fight the global engine config and clobber the iOS
// enable-live-input flow (rebuild engine to 1 input, then load a rig saved with 0). Apply a
// rig's saved layout deliberately via `applyChannelLayout(from:)` / the config UI instead.
// Restore the saved input source before rebuilding, since board construction reads it. A
// saved live-input channel that no longer exists on this engine falls back to the test loop
// (same guard as reconfigureEngine), so the rebuild's addBoard() can't throw on a stale
// channel. Absent (older rig) → leave the current input source untouched.
if let savedInput: InputSource = state.inputSource {
if case .liveInput(let channel) = savedInput,
channel < 0 || channel >= engine.numInputChannels {
inputSource = .testLoop
} else {
inputSource = savedInput
}
}
teardown()
try rebuildAllBoards(from: state)
// Restore the rig's MIDI bindings after the boards exist, so a MIDIController re-reading the
// map resolves against the freshly rebuilt boards.
midiMap = state.midiMap
// Tempo restore is graph-independent, so it happens after the rebuild. Absent (older rig) →
// leave the current session tempo untouched.
if let savedBpm: Double = state.bpm {
clock.bpm = savedBpm
}
if let savedTempoEnabled: Bool = state.tempoEnabled {
setTempoEnabled(savedTempoEnabled)
}
// Bring restored tempo-synced parameters in line with the loaded tempo. `setTempoEnabled`
// already re-syncs when it runs and is enabled, but an older rig with no saved
// `tempoEnabled` skips that path — recompute unconditionally so synced values are correct.
if tempoEnabled {
applyTempoSyncToAllPedals()
}
}
/// Rebuilds every board from a snapshot with all-or-nothing semantics.
@@ -310,6 +352,12 @@ extension ShoeGaze {
for (board, boardState) in zip(boards, state.boards) {
applySegmentParams(boardState.segments, to: board.orderedSegments)
}
// A recall restores each pedal's tempo-sync state but not its derived values (no clock is
// consulted in `Pedal.applyState`), so recompute them against the rig's current tempo —
// mirroring the full `loadRig(from:)` path.
if tempoEnabled {
applyTempoSyncToAllPedals()
}
}
/// Positionally applies segment parameter snapshots to live board segments, including
@@ -34,26 +34,69 @@ public struct ShoeGazeState: Codable, Equatable {
/// version bump is required for this additive field.
public let midiMap: MIDIMap?
/// The rig's tempo in BPM at save time, or `nil` for a rig saved before tempo persistence.
/// Restored onto the shared clock on load; `nil` leaves the current session tempo untouched.
public let bpm: Double?
/// Whether the tempo indicator and tempo-synced features were enabled at save time, or `nil`
/// for a rig saved before tempo persistence.
public let tempoEnabled: Bool?
/// How the board head bus was fed at save time (test loop or a live-input channel), or `nil`
/// for a rig saved before input persistence. A saved live-input channel that no longer exists
/// on the loading engine falls back to the test loop.
public let inputSource: InputSource?
/// The engine's hardware input-channel count at save time, or `nil` for a rig saved before I/O
/// persistence. Reapplied on load (when the engine is stopped and the count differs), so a rig
/// can restore its channel layout. Hardware that can't supply the count is negotiated at
/// `engine.start()`, exactly as with a manual reconfigure.
public let numInputChannels: Int?
/// The engine's hardware output-channel count at save time, or `nil` for a rig saved before I/O
/// persistence. Reapplied on load under the same conditions as ``numInputChannels``.
public let numOutputChannels: Int?
/// Creates a rig state snapshot.
///
/// - Parameters:
/// - version: Preset format version. Defaults to `presetFormatVersion`.
/// - boards: Ordered list of board state snapshots.
/// - midiMap: The rig's MIDI bindings, or `nil` when there are none. Defaults to `nil`.
/// - bpm: The rig's tempo in BPM, or `nil` to not persist a tempo. Defaults to `nil`.
/// - tempoEnabled: Whether tempo features were enabled, or `nil`. Defaults to `nil`.
/// - inputSource: The rig's input selection, or `nil` to not persist one. Defaults to `nil`.
/// - numInputChannels: The engine input-channel count, or `nil`. Defaults to `nil`.
/// - numOutputChannels: The engine output-channel count, or `nil`. Defaults to `nil`.
public init(
version: Int = presetFormatVersion,
boards: [BoardState],
midiMap: MIDIMap? = nil
midiMap: MIDIMap? = nil,
bpm: Double? = nil,
tempoEnabled: Bool? = nil,
inputSource: InputSource? = nil,
numInputChannels: Int? = nil,
numOutputChannels: Int? = nil
) {
self.version = version
self.boards = boards
self.midiMap = midiMap
self.bpm = bpm
self.tempoEnabled = tempoEnabled
self.inputSource = inputSource
self.numInputChannels = numInputChannels
self.numOutputChannels = numOutputChannels
}
private enum CodingKeys: String, CodingKey {
case version
case boards
case midiMap
case bpm
case tempoEnabled
case inputSource
case numInputChannels
case numOutputChannels
}
/// Decodes a rig snapshot, tolerating an absent, malformed, OR legacy-format `midiMap`.
@@ -79,5 +122,12 @@ public struct ShoeGazeState: Codable, Equatable {
} else {
self.midiMap = nil
}
// Additive tempo + input + I/O fields: absent in older rigs, so decode leniently to `nil`.
self.bpm = try container.decodeIfPresent(Double.self, forKey: .bpm)
self.tempoEnabled = try container.decodeIfPresent(Bool.self, forKey: .tempoEnabled)
self.inputSource = try container.decodeIfPresent(InputSource.self, forKey: .inputSource)
self.numInputChannels = try container.decodeIfPresent(Int.self, forKey: .numInputChannels)
self.numOutputChannels = try container.decodeIfPresent(Int.self, forKey: .numOutputChannels)
}
}
+26 -1
View File
@@ -139,7 +139,11 @@ public final class ShoeGaze {
/// control by forcing each ``PedalSwitch/tempoDependent`` switch to its first option.
public func setTempoEnabled(_ enabled: Bool) {
tempoEnabled = enabled
guard !enabled else { return }
guard !enabled else {
// Re-enabling: bring every tempo-synced parameter back in line with the current tempo.
applyTempoSyncToAllPedals()
return
}
for pedal: Pedal in allPedals() {
for pedalSwitch: PedalSwitch in pedal.effectSwitches where pedalSwitch.tempoDependent {
if let off: PedalSwitch.Option = pedalSwitch.options.first {
@@ -149,6 +153,27 @@ public final class ShoeGaze {
}
}
/// Sets the shared clock's tempo and recomputes every tempo-synced pedal parameter to match.
/// Route **all** BPM changes (stepper, tap tempo, MIDI) through here so synced delay times and
/// LFO rates follow the tempo. Recompute is skipped while tempo is disabled.
///
/// - Parameter bpm: The new tempo in beats per minute. A non-positive value is ignored (the
/// clock requires a positive tempo); callers that also want an upper bound clamp before calling.
public func setBpm(_ bpm: Double) {
guard bpm > 0 else { return }
clock.bpm = bpm
guard tempoEnabled else { return }
applyTempoSyncToAllPedals()
}
/// Recomputes every tempo-synced parameter on every live pedal from the current tempo.
/// `internal` so the preset-restore path (`ShoeGaze+Preset.swift`) can re-sync after a rig load.
internal func applyTempoSyncToAllPedals() {
for pedal: Pedal in allPedals() {
pedal.applyTempoSync()
}
}
// MARK: - Scope state
/// Scope tap over the hardware input + output buses, feeding the debug scope view.
@@ -0,0 +1,74 @@
// NoteDivision.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// A rhythmic note value, expressed as a fraction of a bar and measured in quarter-note beats.
///
/// Used to lock a tempo-syncable pedal parameter (a delay time, an LFO rate) to the shared
/// ``ShoeGaze/clock``. The synced period in seconds is `(60 / bpm) * beats`; a delay time uses
/// that period directly, an LFO rate uses its inverse (one cycle per division).
///
/// Cases are ordered longest-first so a stepped selector reads top-to-bottom from slow to fast.
public enum NoteDivision: String, Codable, CaseIterable, Sendable {
/// Whole note — four quarter-note beats.
case whole
/// Dotted half note — three beats.
case dottedHalf
/// Half note — two beats.
case half
/// Dotted quarter note — one and a half beats.
case dottedQuarter
/// Quarter note — one beat.
case quarter
/// Dotted eighth note — three-quarters of a beat.
case dottedEighth
/// Quarter-note triplet — two-thirds of a beat.
case quarterTriplet
/// Eighth note — half a beat.
case eighth
/// Eighth-note triplet — one-third of a beat.
case eighthTriplet
/// Sixteenth note — a quarter of a beat.
case sixteenth
/// Sixteenth-note triplet — one-sixth of a beat.
case sixteenthTriplet
/// Length of this division in quarter-note beats (a quarter note is `1`).
public var beats: Double {
switch self {
case .whole: return 4.0
case .dottedHalf: return 3.0
case .half: return 2.0
case .dottedQuarter: return 1.5
case .quarter: return 1.0
case .quarterTriplet: return 2.0 / 3.0
case .dottedEighth: return 0.75
case .eighth: return 0.5
case .eighthTriplet: return 1.0 / 3.0
case .sixteenth: return 0.25
case .sixteenthTriplet: return 1.0 / 6.0
}
}
/// Short label for a selector stop (e.g. `"1/4"`, `"1/8."`, `"1/8T"`).
public var label: String {
switch self {
case .whole: return "1/1"
case .dottedHalf: return "1/2."
case .half: return "1/2"
case .dottedQuarter: return "1/4."
case .quarter: return "1/4"
case .quarterTriplet: return "1/4T"
case .dottedEighth: return "1/8."
case .eighth: return "1/8"
case .eighthTriplet: return "1/8T"
case .sixteenth: return "1/16"
case .sixteenthTriplet: return "1/16T"
}
}
}
@@ -50,6 +50,6 @@ extension ShoeGaze {
let averageInterval: TimeInterval = intervals.reduce(0, +) / Double(intervals.count)
let secondsPerMinute: Double = 60.0
clock.bpm = secondsPerMinute / averageInterval
setBpm(secondsPerMinute / averageInterval)
}
}
@@ -0,0 +1,22 @@
// TempoSync.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Sync state of one tempo-syncable pedal parameter.
///
/// `.free` leaves the parameter at its stored absolute value (seconds or Hz), controlled by the
/// knob as usual. `.division` locks it to a ``NoteDivision`` of the shared ``ShoeGaze/clock`` —
/// the value is derived from the current tempo and rewritten whenever the tempo or the division
/// changes.
public enum TempoSync: Codable, Equatable, Sendable {
/// Absolute value, knob-controlled. The default for every parameter.
case free
/// Locked to a note division of the live tempo.
case division(NoteDivision)
}
@@ -0,0 +1,29 @@
// TempoSyncRevision.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Observation
/// An observable revision counter bumped whenever a pedal's ``Pedal/tempoSync`` state changes.
///
/// ``Pedal/tempoSync`` is a plain dictionary, not observable, so a SwiftUI view showing the sync
/// state (the note-division badge) needs a signal to re-render when the state changes through any
/// path — the knob's own picker, a preset load, or a lightweight recall. Reading ``value`` inside a
/// view body subscribes it; ``Pedal/setSync(_:for:)`` and `Pedal.applyState(_:)` bump it.
@Observable
public final class TempoSyncRevision {
/// Incremented on every ``Pedal/tempoSync`` mutation. Its magnitude is meaningless — only the
/// change matters, as an invalidation signal for observing views.
public internal(set) var value: Int = 0
/// Creates a revision counter starting at zero.
public init() {}
/// Bumps the counter, invalidating any view observing ``value``.
func bump() {
value &+= 1
}
}
@@ -0,0 +1,86 @@
// TempoSyncableParam.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdUI
/// Descriptor for one pedal parameter that can be locked to the tempo.
///
/// A ``Pedal`` publishes an array of these (via ``Pedal/tempoSyncableParams``) so the shared
/// tempo-sync machinery can recompute and rewrite each synced parameter without knowing the
/// concrete pedal type. The stable ``key`` doubles as the persistence key in ``PedalState``.
public struct TempoSyncableParam {
/// How the synced period maps onto the parameter's value.
public enum Kind {
/// A duration in seconds — the value is the synced period `T` directly (delay time).
case time
/// A frequency in Hz — the value is `1 / T` (one LFO cycle per division).
case rate
}
/// Stable identifier for this parameter within its pedal (e.g. `"time"`, `"time1"`, `"rate"`).
/// Used as the ``TempoSync`` dictionary key and the persistence key, so it must never change.
public let key: String
/// Short display label, matching the parameter's knob label.
public let label: String
/// The live parameter node the synced value is written to.
public let node: UIParamNode
/// Whether the value is a duration (`.time`) or a frequency (`.rate`, inverse of the period).
public let kind: Kind
/// Inclusive value range the parameter accepts, in its own units. A synced value outside this
/// range is clamped (a long division can exceed a delay's maximum buffered time).
public let range: ClosedRange<Double>
/// Creates a tempo-syncable parameter descriptor.
///
/// - Parameters:
/// - key: Stable identifier and persistence key. Must be unique within the pedal and stable
/// across versions.
/// - label: Short display label, matching the knob label.
/// - node: The live parameter node (`pedal.$time`, `pedal.$rate`, …).
/// - kind: `.time` for a duration, `.rate` for a frequency (inverse of the period).
/// - range: Inclusive value range in the parameter's units; the synced value is clamped to it.
public init(
key: String,
label: String,
node: UIParamNode,
kind: Kind,
range: ClosedRange<Double>
) {
self.key = key
self.label = label
self.node = node
self.kind = kind
self.range = range
}
private static let secondsPerMinute: Double = 60.0
/// The unclamped parameter value for `division` at `bpm`. For `.time` this is the note's period
/// in seconds; for `.rate` it is `1 / period` in Hz (one LFO cycle per division).
public func rawValue(for division: NoteDivision, bpm: Double) -> Double {
let period: Double = (TempoSyncableParam.secondsPerMinute / bpm) * division.beats
switch kind {
case .time:
return period
case .rate:
return period > 0 ? 1.0 / period : range.upperBound
}
}
/// The value actually written for `division` at `bpm`, plus whether it had to be clamped to the
/// parameter's range. A clamped result means the division can't be represented accurately at this
/// tempo (e.g. a whole note longer than the maximum delay time) — the UI disables/flags it.
public func value(for division: NoteDivision, bpm: Double) -> (value: Double, clamped: Bool) {
let raw: Double = rawValue(for: division, bpm: bpm)
let clampedValue: Double = min(max(raw, range.lowerBound), range.upperBound)
return (clampedValue, clampedValue != raw)
}
}
@@ -0,0 +1,251 @@
// ControlMappingStrip.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdShoeGaze
/// The rig's current control map, injected into the board view tree so each ``PedalView`` can draw
/// its own mapping strip without every call site having to thread the map through. `nil` when the
/// rig has no bindings. Set once high in the builder (`builderColumn`) from the observable
/// `ShoeGaze.midiMap`, so learning or clearing a binding updates every strip live.
private struct ControlMappingMapKey: EnvironmentKey {
static let defaultValue: MIDIMap? = nil
}
extension EnvironmentValues {
/// The rig's control map for in-context mapping badges, or `nil` when unset / empty.
var controlMappingMap: MIDIMap? {
get { self[ControlMappingMapKey.self] }
set { self[ControlMappingMapKey.self] = newValue }
}
}
/// The kind of trigger a mapping badge represents, and its colour.
enum MappingBadgeKind {
case programChange
case controlChange
case key
/// The badge fill colour (matches the mapping-sheet chip colours).
var fill: Color {
switch self {
case .programChange: return MappingBadge.pcFill
case .controlChange: return MappingBadge.ccFill
case .key: return MappingBadge.keyFill
}
}
}
/// One coloured pill — e.g. `CC11`, `PC3`, `⇧B` — marking a control's binding.
struct MappingBadge: View {
static let pcFill: Color = Color(red: 0.11, green: 0.37, blue: 0.65)
static let ccFill: Color = Color(red: 0.33, green: 0.29, blue: 0.72)
static let keyFill: Color = Color(red: 0.73, green: 0.46, blue: 0.09)
private static let fontSize: CGFloat = 9
private static let paddingH: CGFloat = 5
private static let paddingV: CGFloat = 1
private static let cornerRadius: CGFloat = 4
private let kind: MappingBadgeKind
private let text: String
/// Creates a mapping badge.
///
/// - Parameters:
/// - kind: The trigger kind (drives the fill colour).
/// - text: The badge label (e.g. `"CC11"`, `"PC3"`, `"⇧B"`).
init(kind: MappingBadgeKind, text: String) {
self.kind = kind
self.text = text
}
var body: some View {
Text(text)
.font(.system(size: MappingBadge.fontSize, weight: .medium))
.foregroundStyle(Color.white)
.padding(.horizontal, MappingBadge.paddingH)
.padding(.vertical, MappingBadge.paddingV)
.background(
RoundedRectangle(cornerRadius: MappingBadge.cornerRadius)
.fill(kind.fill)
)
}
}
/// A one-line legend keying the badge colours (`PC` footswitch, `CC` expression, `KEY` letter key),
/// shown once above the board canvas.
struct ControlMappingLegend: View {
private static let itemSpacing: CGFloat = 10
private static let pairSpacing: CGFloat = 5
private static let fontSize: CGFloat = 11
var body: some View {
HStack(spacing: ControlMappingLegend.itemSpacing) {
legendItem(kind: .programChange, badge: "PC", caption: "footswitch")
legendItem(kind: .controlChange, badge: "CC", caption: "expression")
legendItem(kind: .key, badge: "KEY", caption: "letter key")
}
.foregroundStyle(Color.white.opacity(0.55))
}
private func legendItem(kind: MappingBadgeKind, badge: String, caption: String) -> some View {
HStack(spacing: ControlMappingLegend.pairSpacing) {
MappingBadge(kind: kind, text: badge)
Text(caption)
.font(.system(size: ControlMappingLegend.fontSize))
}
}
}
/// One row of a pedal's mapping strip: a control label and the badges bound to it.
struct PedalMappingRow: Identifiable {
let id: String
let label: String
let badges: [PedalMappingBadge]
}
/// A single badge within a ``PedalMappingRow``.
struct PedalMappingBadge: Identifiable {
let id: String
let kind: MappingBadgeKind
let text: String
}
/// The per-pedal mapping strip: a compact footer listing this pedal's mapped controls and the
/// footswitch / expression / key bindings driving them. Renders nothing when the pedal has no
/// mappings, so unmapped pedals gain no height.
struct PedalMappingStrip: View {
private static let rowSpacing: CGFloat = 3
private static let labelFontSize: CGFloat = 10
private static let badgeSpacing: CGFloat = 4
private static let topPadding: CGFloat = 6
private static let dividerOpacity: Double = 0.18
private let rows: [PedalMappingRow]
/// Creates a mapping strip for a pedal against the current map.
///
/// - Parameters:
/// - pedal: The pedal whose bindings are listed.
/// - map: The rig's control map, or `nil` when there are no bindings.
init(pedal: Pedal, map: MIDIMap?) {
self.rows = PedalMappingStrip.rows(for: pedal, in: map)
}
var body: some View {
if rows.isEmpty {
EmptyView()
} else {
VStack(spacing: PedalMappingStrip.rowSpacing) {
Divider().overlay(Color.white.opacity(PedalMappingStrip.dividerOpacity))
ForEach(rows) { row in
HStack(spacing: PedalMappingStrip.badgeSpacing) {
Text(row.label)
.font(.system(size: PedalMappingStrip.labelFontSize))
.foregroundStyle(Color.white.opacity(0.6))
Spacer(minLength: 0)
ForEach(row.badges) { badge in
MappingBadge(kind: badge.kind, text: badge.text)
}
}
}
}
.padding(.top, PedalMappingStrip.topPadding)
}
}
// MARK: - Row assembly
/// Builds the strip rows for a pedal from the map: one row per mapped CC control, one for a
/// mapped bypass (footswitch + key), and one per mapped looper transport action.
static func rows(for pedal: Pedal, in map: MIDIMap?) -> [PedalMappingRow] {
guard let map: MIDIMap = map else { return [] }
let pedalID: UUID = pedal.id
var rows: [PedalMappingRow] = []
// Continuous controls driven by an expression pedal (CC).
for controlPair: (offset: Int, element: PedalControl) in pedal.ccMappableControls.enumerated() {
let target: MIDIMap.CCTarget = .pedalControl(
pedalID: pedalID, controlIndex: controlPair.offset,
pedalNameHint: nil, controlLabelHint: nil)
guard let cc: MIDIMap.CCBinding = map.ccs.first(where: { $0.target.addresses(target) })
else { continue }
rows.append(PedalMappingRow(
id: "cc-\(controlPair.offset)",
label: controlPair.element.label,
badges: [PedalMappingBadge(id: "cc", kind: .controlChange, text: "CC\(cc.controller)")]))
}
// Bypass — a footswitch and/or a key.
let bypassBadges: [PedalMappingBadge] = badges(for: .pedalBypass(pedalID: pedalID), in: map)
if bypassBadges.isEmpty == false {
rows.append(PedalMappingRow(id: "bypass", label: "Bypass", badges: bypassBadges))
}
// Looper transport actions.
if pedal is LooperPedal {
for kind: MIDIMap.PedalActionKind in loopedActionOrder {
let action: MIDIMap.Action = .pedalAction(pedalID: pedalID, kind: kind)
let actionBadges: [PedalMappingBadge] = badges(for: action, in: map)
if actionBadges.isEmpty { continue }
rows.append(PedalMappingRow(
id: "la-\(looperActionName(kind))",
label: looperActionName(kind),
badges: actionBadges))
}
}
return rows
}
/// The footswitch (PC) and key badges bound to a toggle action, in that order.
private static func badges(for action: MIDIMap.Action, in map: MIDIMap) -> [PedalMappingBadge] {
var badges: [PedalMappingBadge] = []
if let pc: MIDIMap.SwitchBinding = map.switches.first(where: { $0.action == action }) {
badges.append(PedalMappingBadge(id: "pc", kind: .programChange, text: "PC\(pc.program)"))
}
if let key: MIDIMap.KeyBinding = map.keys.first(where: { $0.action == action }) {
badges.append(PedalMappingBadge(id: "key", kind: .key, text: keyLabel(key)))
}
return badges
}
/// A key binding formatted with modifier glyphs (macOS order: control, option, shift).
private static func keyLabel(_ binding: MIDIMap.KeyBinding) -> String {
var prefix: String = ""
if binding.modifiers.contains(.control) { prefix += "⌃" }
if binding.modifiers.contains(.option) { prefix += "⌥" }
if binding.modifiers.contains(.shift) { prefix += "⇧" }
return prefix + binding.key.uppercased()
}
/// The looper transport actions in the order they appear in the mapping sheet.
private static let loopedActionOrder: [MIDIMap.PedalActionKind] = [
.looperRecordStop, .looperOverdubToggle, .looperLoopToggle, .looperStop,
.looperCueStop, .looperReverse, .looperSyncToggle, .looperReset,
.looperTrack(index: 0), .looperTrack(index: 1),
.looperTrack(index: 2), .looperTrack(index: 3),
]
/// A short user-facing name for a looper transport action.
private static func looperActionName(_ kind: MIDIMap.PedalActionKind) -> String {
switch kind {
case .looperRecordStop: return "Record"
case .looperOverdubToggle: return "Overdub"
case .looperLoopToggle: return "Loop"
case .looperStop: return "Stop"
case .looperCueStop: return "Cue Stop"
case .looperReverse: return "Reverse"
case .looperSyncToggle: return "Sync"
case .looperReset: return "Reset"
case .looperTrack(let index): return "Track \(LooperPedal.trackLabel(index))"
}
}
}
+35 -8
View File
@@ -43,6 +43,23 @@ public struct HelpView: View {
"Bypass Rig compares your sound with and without the whole pedalboard.",
]
)
topicSection(
icon: "keyboard",
title: "Keyboard Shortcuts",
intro: "With a hardware keyboard, these speed up live use.",
steps: [
"⌘1–⌘9 switch to (and solo) boards 1–9 — the fastest way to change board live.",
"⌘⇧1–⌘⇧9 and ⌘⇧0 load set-list rigs 1–10 in the order shown in the Rigs list — "
+ "build a set list by reordering rigs, then step through them hands-free.",
"⌘Z mutes and unmutes the whole rig — a hard silence of all output (distinct "
+ "from Bypass Rig, which passes your dry signal through).",
"On macOS the menu bar adds: ⌘N New Rig, ⌘S Save Rig, ⌘E Export Archive, "
+ "⌘I Import Archive, ⌘B Add Board, ⇧⌘R Start / Stop Recording, ⌘? Help, and "
+ "Rigs ▸ Set List (the ⌘⇧ rig slots).",
"The board and set-list shortcuts and ⌘Z also work on iOS / iPadOS with a "
+ "hardware keyboard attached.",
]
)
topicSection(
icon: "waveform",
title: "Choosing an Input",
@@ -64,6 +81,9 @@ public struct HelpView: View {
+ "crossfade time; each board has S (solo) and B (bypass).",
"The Rigs sidebar lists saved rigs, with New, Save, Save As, Duplicate, Rename, "
+ "Delete, and Erase All.",
"Reorder rigs into a set list by dragging a row, or via each rig's Move Up / "
+ "Move Down menu. The order is saved and travels with an exported archive; "
+ "the top ten map to ⌘⇧1–⌘⇧0.",
]
)
topicSection(
@@ -89,8 +109,9 @@ public struct HelpView: View {
"Tracks A–D: tap a dot to select the track Record overdubs into; tap a selected, "
+ "recorded track again to mute or unmute it.",
"MIDI: Record, Stop, Cue Stop, Reverse, Sync, Reset, and each Track A–D map as "
+ "footswitch (Program Change) actions in MIDI Mapping; the Crossfade / Playback / "
+ "Overdub / Feedback knobs sweep from an expression pedal like any pedal knob.",
+ "footswitch (Program Change) or key actions in MIDI / Control Mapping; the "
+ "Crossfade / Playback / Overdub / Feedback knobs sweep from an expression pedal "
+ "like any pedal knob.",
]
)
topicSection(
@@ -116,13 +137,19 @@ public struct HelpView: View {
)
topicSection(
icon: "pianokeys",
title: "MIDI Control",
intro: "Map a MIDI foot controller (e.g. a Behringer FCB1010) for hands-free control.",
title: "MIDI / Control",
intro: "Map a MIDI foot controller (e.g. a Behringer FCB1010) or your computer keyboard for "
+ "hands-free control.",
steps: [
"The keys icon in the top bar lights green when a device is connected. Tap it to open MIDI Mapping.",
"Switches (Program Change): footswitches toggle Rig Bypass, All Boards, and each board's "
+ "Solo / Audible / Bypass or a pedal's bypass. Tap Learn, then press the footswitch. "
+ "One switch can drive several actions at once — a scene.",
"The keys icon in the top bar lights green when a device is connected. Tap it to open "
+ "MIDI / Control Mapping.",
"Switches: footswitches and letter keys toggle Rig Bypass, All Boards, and each board's "
+ "Solo / Audible / Bypass or a pedal's bypass. Tap PC then press a footswitch, or Key "
+ "then press a key. One switch or key can drive several actions at once — a scene.",
"Keys fire only when you're not typing — while a text field (like a rig name) is focused, "
+ "letters go to the field, not to your mappings.",
"Hold Shift, Control, or Option while learning to bind a modified key — a and ⇧a are "
+ "separate triggers. Command is reserved for the menu shortcuts.",
"Expression (Control Change): an expression pedal sweeps any pedal knob or slider, or a "
+ "board's Level. Tap Learn, then move the pedal. Invert reverses the sweep — map one "
+ "CC to two controls and invert one for a crossfade.",
@@ -22,6 +22,7 @@ public struct MIDIMappingSheet: View {
private static let sheetMinWidth: CGFloat = 460
private static let sheetMinHeight: CGFloat = 520
private static let rowVerticalPadding: CGFloat = 2
private static let switchRowControlSpacing: CGFloat = 8
// MARK: - Inputs
@@ -49,7 +50,7 @@ public struct MIDIMappingSheet: View {
switchesSection
expressionSection
}
.navigationTitle("MIDI Mapping")
.navigationTitle("MIDI / Control Mapping")
.toolbar {
ToolbarItem(placement: .confirmationAction) {
Button("Done") {
@@ -174,30 +175,37 @@ public struct MIDIMappingSheet: View {
// MARK: - Switches (Program Change)
private var switchesSection: some View {
Section("Switches (Program Change)") {
Section("Switches (footswitch / key)") {
ForEach(switchRowModels) { row in
switchRow(row)
}
}
}
/// A switch row carries two independent trigger sources for one toggle action: a MIDI Program
/// Change (footswitch) and a computer key. Each has its own learn / clear; the detail line
/// summarises whichever are bound, or the "Listening…" prompt for the armed source.
private func switchRow(_ row: SwitchRowModel) -> some View {
let isArmed: Bool = controller.learnTarget == .action(row.action)
let binding: MIDIMap.SwitchBinding? = controller.switchBinding(for: row.action)
return HStack {
let isArmedPC: Bool = controller.learnTarget == .action(row.action)
let isArmedKey: Bool = controller.learnTarget == .key(row.action)
let pcBinding: MIDIMap.SwitchBinding? = controller.switchBinding(for: row.action)
let keyBinding: MIDIMap.KeyBinding? = controller.keyBinding(for: row.action)
let isArmed: Bool = isArmedPC || isArmedKey
return HStack(spacing: MIDIMappingSheet.switchRowControlSpacing) {
VStack(alignment: .leading, spacing: 1) {
Text(row.label)
Text(switchBindingLabel(isArmed: isArmed, binding: binding))
Text(switchBindingLabel(isArmedPC: isArmedPC, isArmedKey: isArmedKey,
pc: pcBinding, key: keyBinding))
.font(.caption)
.foregroundStyle(isArmed ? Color.orange : .secondary)
}
Spacer()
if binding != nil {
Button("Clear") { controller.clearSwitchBinding(for: row.action) }
if pcBinding != nil {
Button("Clear PC") { controller.clearSwitchBinding(for: row.action) }
.buttonStyle(.borderless)
}
Button(isArmed ? "Cancel" : "Learn") {
if isArmed {
Button(isArmedPC ? "Cancel" : "PC") {
if isArmedPC {
controller.cancelLearn()
} else {
controller.armSwitchLearn(row.action)
@@ -205,15 +213,50 @@ public struct MIDIMappingSheet: View {
}
.buttonStyle(.bordered)
.tint(.orange)
if keyBinding != nil {
Button("Clear Key") { controller.clearKeyBinding(for: row.action) }
.buttonStyle(.borderless)
}
Button(isArmedKey ? "Cancel" : "Key") {
if isArmedKey {
controller.cancelLearn()
} else {
controller.armKeyLearn(row.action)
}
}
.buttonStyle(.bordered)
.tint(.orange)
}
.padding(.vertical, MIDIMappingSheet.rowVerticalPadding)
}
private func switchBindingLabel(isArmed: Bool, binding: MIDIMap.SwitchBinding?) -> String {
if isArmed { return "Listening — press a footswitch…" }
guard let binding: MIDIMap.SwitchBinding = binding else { return "Unassigned" }
let channelText: String = binding.channel.map { " · ch \($0 + 1)" } ?? ""
return "PC \(binding.program)\(channelText)"
private func switchBindingLabel(
isArmedPC: Bool,
isArmedKey: Bool,
pc: MIDIMap.SwitchBinding?,
key: MIDIMap.KeyBinding?
) -> String {
if isArmedPC { return "Listening — press a footswitch…" }
if isArmedKey { return "Listening — press a key…" }
var parts: [String] = []
if let pc: MIDIMap.SwitchBinding = pc {
let channelText: String = pc.channel.map { " · ch \($0 + 1)" } ?? ""
parts.append("PC \(pc.program)\(channelText)")
}
if let key: MIDIMap.KeyBinding = key {
parts.append("Key \(keyLabel(key))")
}
return parts.isEmpty ? "Unassigned" : parts.joined(separator: " · ")
}
/// A key binding formatted with its modifier glyphs, e.g. `A`, `⇧A`, `⌃A` (macOS modifier order:
/// control, option, shift).
private func keyLabel(_ binding: MIDIMap.KeyBinding) -> String {
var prefix: String = ""
if binding.modifiers.contains(.control) { prefix += "⌃" }
if binding.modifiers.contains(.option) { prefix += "⌥" }
if binding.modifiers.contains(.shift) { prefix += "⇧" }
return prefix + binding.key.uppercased()
}
// MARK: - Expression (CC)
@@ -0,0 +1,244 @@
// NoteGlyphView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdShoeGaze
// MARK: - Notation spec
/// The notation elements that make up one ``NoteDivision`` glyph. Derived purely from the division;
/// consumed by ``NoteGlyphView`` to draw the note.
private struct NoteGlyphSpec {
/// `true` for a solid notehead (quarter and shorter), `false` for an open ring (whole, half).
let filledHead: Bool
/// `true` when the note has a vertical stem (everything except the whole note).
let hasStem: Bool
/// Number of flags on the stem (`0` = quarter/half, `1` = eighth, `2` = sixteenth).
let flags: Int
/// `true` for a dotted value — adds an augmentation dot right of the head.
let dotted: Bool
/// `true` for a triplet — adds a bracket with a "3" above the note.
let triplet: Bool
init(_ division: NoteDivision) {
switch division {
case .whole:
self.init(filledHead: false, hasStem: false, flags: 0, dotted: false, triplet: false)
case .dottedHalf:
self.init(filledHead: false, hasStem: true, flags: 0, dotted: true, triplet: false)
case .half:
self.init(filledHead: false, hasStem: true, flags: 0, dotted: false, triplet: false)
case .dottedQuarter:
self.init(filledHead: true, hasStem: true, flags: 0, dotted: true, triplet: false)
case .quarter:
self.init(filledHead: true, hasStem: true, flags: 0, dotted: false, triplet: false)
case .dottedEighth:
self.init(filledHead: true, hasStem: true, flags: 1, dotted: true, triplet: false)
case .quarterTriplet:
self.init(filledHead: true, hasStem: true, flags: 0, dotted: false, triplet: true)
case .eighth:
self.init(filledHead: true, hasStem: true, flags: 1, dotted: false, triplet: false)
case .eighthTriplet:
self.init(filledHead: true, hasStem: true, flags: 1, dotted: false, triplet: true)
case .sixteenth:
self.init(filledHead: true, hasStem: true, flags: 2, dotted: false, triplet: false)
case .sixteenthTriplet:
self.init(filledHead: true, hasStem: true, flags: 2, dotted: false, triplet: true)
}
}
private init(filledHead: Bool, hasStem: Bool, flags: Int, dotted: Bool, triplet: Bool) {
self.filledHead = filledHead
self.hasStem = hasStem
self.flags = flags
self.dotted = dotted
self.triplet = triplet
}
}
// MARK: - NoteGlyphView
/// Draws a single music-notation glyph for a ``NoteDivision`` — notehead, stem, flags, an
/// augmentation dot for dotted values, and a bracketed "3" for triplets — with `Canvas`.
///
/// Drawn in solid black so the rasterized image can be used as a **template** in a menu (only the
/// alpha channel matters; the system tints it to the menu's foreground colour). See
/// ``NoteGlyphImageCache``.
struct NoteGlyphView: View {
// Logical drawing box. The note sits in the lower portion; the triplet bracket uses the top,
// which is left clear on every glyph so the note baseline stays consistent across the menu.
private static let boxWidth: CGFloat = 18
private static let boxHeight: CGFloat = 26
// Notehead.
private static let headCenterX: CGFloat = 6.5
private static let headCenterY: CGFloat = 19.0
private static let headRadiusX: CGFloat = 4.3
private static let headRadiusY: CGFloat = 3.0
private static let wholeHeadRadiusX: CGFloat = 5.0
private static let openHeadLineWidth: CGFloat = 1.5
// Stem.
private static let stemLineWidth: CGFloat = 1.3
private static let stemTopY: CGFloat = 8.0
// Flags.
private static let flagLineWidth: CGFloat = 1.5
private static let flagSpread: CGFloat = 5.5
private static let flagDrop: CGFloat = 6.0
private static let flagGap: CGFloat = 3.5
// Augmentation dot — pushed clear of the notehead's right edge.
private static let dotRadius: CGFloat = 1.5
private static let dotGap: CGFloat = 3.8
// Triplet bracket + numeral. The "3" is centred in the bracket gap; `bracketTopY` leaves room
// above it so the numeral is never clipped by the raster bounds.
private static let bracketTopY: CGFloat = 4.0
private static let bracketTickHeight: CGFloat = 2.0
private static let bracketInsetX: CGFloat = 1.5
private static let bracketLineWidth: CGFloat = 1.0
private static let bracketNumberGap: CGFloat = 3.0
private static let bracketNumberSize: CGFloat = 6.0
let division: NoteDivision
var body: some View {
Canvas { context, size in
let scaleX: CGFloat = size.width / NoteGlyphView.boxWidth
let scaleY: CGFloat = size.height / NoteGlyphView.boxHeight
let s: CGFloat = min(scaleX, scaleY)
context.scaleBy(x: s, y: s)
draw(NoteGlyphSpec(division), in: &context)
}
.frame(width: NoteGlyphView.boxWidth, height: NoteGlyphView.boxHeight)
}
private func draw(_ spec: NoteGlyphSpec, in context: inout GraphicsContext) {
let ink: GraphicsContext.Shading = .color(.black)
// Stem — draw before the head so the head overlaps its lower end cleanly.
let stemX: CGFloat = NoteGlyphView.headCenterX + NoteGlyphView.headRadiusX - 0.3
if spec.hasStem {
var stem: Path = Path()
stem.move(to: CGPoint(x: stemX, y: NoteGlyphView.headCenterY))
stem.addLine(to: CGPoint(x: stemX, y: NoteGlyphView.stemTopY))
context.stroke(stem, with: ink, lineWidth: NoteGlyphView.stemLineWidth)
}
// Flags — hooks off the top of the stem, one per flag, stacked downward.
for flagIndex: Int in 0 ..< spec.flags {
let startY: CGFloat = NoteGlyphView.stemTopY + CGFloat(flagIndex) * NoteGlyphView.flagGap
var flag: Path = Path()
flag.move(to: CGPoint(x: stemX, y: startY))
flag.addQuadCurve(
to: CGPoint(x: stemX + NoteGlyphView.flagSpread, y: startY + NoteGlyphView.flagDrop),
control: CGPoint(x: stemX + NoteGlyphView.flagSpread, y: startY)
)
context.stroke(flag, with: ink, lineWidth: NoteGlyphView.flagLineWidth)
}
// Notehead.
let headRadiusX: CGFloat = spec.hasStem ? NoteGlyphView.headRadiusX : NoteGlyphView.wholeHeadRadiusX
let headRect: CGRect = CGRect(
x: NoteGlyphView.headCenterX - headRadiusX,
y: NoteGlyphView.headCenterY - NoteGlyphView.headRadiusY,
width: headRadiusX * 2,
height: NoteGlyphView.headRadiusY * 2
)
let headPath: Path = Path(ellipseIn: headRect)
if spec.filledHead {
context.fill(headPath, with: ink)
} else {
context.stroke(headPath, with: ink, lineWidth: NoteGlyphView.openHeadLineWidth)
}
// Augmentation dot, right of the head.
if spec.dotted {
let dotX: CGFloat = NoteGlyphView.headCenterX + headRadiusX + NoteGlyphView.dotGap
let dotRect: CGRect = CGRect(
x: dotX - NoteGlyphView.dotRadius,
y: NoteGlyphView.headCenterY - NoteGlyphView.dotRadius,
width: NoteGlyphView.dotRadius * 2,
height: NoteGlyphView.dotRadius * 2
)
context.fill(Path(ellipseIn: dotRect), with: ink)
}
// Triplet bracket with a centred "3".
if spec.triplet {
drawTripletBracket(in: &context, ink: ink)
}
}
private func drawTripletBracket(in context: inout GraphicsContext, ink: GraphicsContext.Shading) {
let leftX: CGFloat = NoteGlyphView.bracketInsetX
let rightX: CGFloat = NoteGlyphView.boxWidth - NoteGlyphView.bracketInsetX
let midX: CGFloat = (leftX + rightX) / 2
let topY: CGFloat = NoteGlyphView.bracketTopY
let tickBottomY: CGFloat = topY + NoteGlyphView.bracketTickHeight
let gap: CGFloat = NoteGlyphView.bracketNumberGap
var bracket: Path = Path()
// Left tick down, then horizontal to the number gap.
bracket.move(to: CGPoint(x: leftX, y: tickBottomY))
bracket.addLine(to: CGPoint(x: leftX, y: topY))
bracket.addLine(to: CGPoint(x: midX - gap, y: topY))
// Right side: horizontal from the gap out to the right tick, then down.
bracket.move(to: CGPoint(x: midX + gap, y: topY))
bracket.addLine(to: CGPoint(x: rightX, y: topY))
bracket.addLine(to: CGPoint(x: rightX, y: tickBottomY))
context.stroke(bracket, with: ink, lineWidth: NoteGlyphView.bracketLineWidth)
let numeral: GraphicsContext.ResolvedText = context.resolve(
Text("3")
.font(.system(size: NoteGlyphView.bracketNumberSize, weight: .semibold, design: .rounded))
.foregroundColor(.black)
)
context.draw(numeral, at: CGPoint(x: midX, y: topY), anchor: .center)
}
}
// MARK: - Rasterization cache
/// Renders each ``NoteDivision`` glyph to a template `Image` once and caches it, so the tempo-sync
/// menu can show notation icons without re-rasterizing on every render. Template images tint to the
/// menu's foreground colour automatically.
@MainActor
enum NoteGlyphImageCache {
private static let renderScale: CGFloat = 3.0
private static var cache: [NoteDivision: Image] = [:]
/// The cached notation glyph for `division`, rendered on first request.
static func image(for division: NoteDivision) -> Image {
if let existing: Image = cache[division] {
return existing
}
let rendered: Image = render(division)
cache[division] = rendered
return rendered
}
private static func render(_ division: NoteDivision) -> Image {
let renderer: ImageRenderer = ImageRenderer(content: NoteGlyphView(division: division))
renderer.scale = renderScale
#if os(macOS)
if let nsImage = renderer.nsImage {
nsImage.isTemplate = true
return Image(nsImage: nsImage)
}
#else
if let uiImage = renderer.uiImage {
return Image(uiImage: uiImage.withRenderingMode(.alwaysTemplate))
}
#endif
// Fallback to the division's text label if rasterization ever fails.
return Image(systemName: "music.note")
}
}
+215 -4
View File
@@ -180,6 +180,189 @@ struct FootswitchButton: View {
}
}
// MARK: - Tempo-sync knob
/// A knob that can be locked to a note division of the live tempo.
///
/// When free, it is an ordinary ``ParameterKnob``. A compact menu below the dial lets the user
/// pick `Free` or a ``NoteDivision``; once a division is chosen the knob is driven by the tempo
/// (its dial shows the derived value but is disabled, since the number is computed). The menu is
/// shown only while tempo is enabled — the enclosing view gates on `shoeGazeTempoEnabled`.
struct TempoSyncKnobView: View {
private static let cellSpacing: CGFloat = 4
private static let syncedDialOpacity: Double = 0.55
private static let menuFontSize: CGFloat = 10
private static let labelGlyphSpacing: CGFloat = 3
private static let warningIconSize: CGFloat = 8
/// Height of the glyph in the collapsed menu button, and of the whole menu row, so the row is the
/// same height whether it shows the "Free" text or a note glyph — the pedal card never grows.
private static let labelGlyphHeight: CGFloat = 18
private static let menuRowHeight: CGFloat = 20
private static let freeKey: String = "free"
// Division-picker popover: a height-capped scroll list the system keeps on-screen (it flips
// above the button near the bottom edge) rather than a native menu that can run off-screen.
private static let pickerMaxHeight: CGFloat = 260
private static let pickerGlyphHeight: CGFloat = 22
private static let pickerRowSpacing: CGFloat = 2
private static let pickerPadding: CGFloat = 8
private static let pickerRowMinWidth: CGFloat = 84
private static let checkmarkFontSize: CGFloat = 11
let pedal: Pedal
let knob: PedalKnob
let param: TempoSyncableParam
/// Presentation flag for the division-picker popover.
@State private var showDivisionPicker: Bool = false
var body: some View {
// Observe the pedal's sync-revision so the badge refreshes when `tempoSync` changes through
// any path — this view's picker, a preset load, or a lightweight recall.
let _ = pedal.tempoSyncRevision.value
let currentKey: String = keyForCurrentSync()
let isSynced: Bool = currentKey != TempoSyncKnobView.freeKey
let currentBpm: Double? = pedal.clock?.bpm
// Reading the live parameter value subscribes this view to Observation, so a tempo change
// (which rewrites the node via `applyTempoSync`) re-renders the clamp warning without polling.
let liveValue: Double = param.node.value
let activeDivision: NoteDivision? = NoteDivision(rawValue: currentKey)
let activeClamped: Bool = {
_ = liveValue
guard isSynced, let bpm: Double = currentBpm, let division: NoteDivision = activeDivision else {
return false
}
return param.value(for: division, bpm: bpm).clamped
}()
VStack(spacing: TempoSyncKnobView.cellSpacing) {
ParameterKnob(knob.label, node: knob.node, range: knob.range)
.foregroundStyle(Color.white)
.disabled(isSynced)
.opacity(isSynced ? TempoSyncKnobView.syncedDialOpacity : 1.0)
Button {
showDivisionPicker = true
} label: {
HStack(spacing: TempoSyncKnobView.labelGlyphSpacing) {
if isSynced, let division: NoteDivision = activeDivision {
NoteGlyphImageCache.image(for: division)
.resizable()
.scaledToFit()
.frame(height: TempoSyncKnobView.labelGlyphHeight)
.accessibilityLabel(Text(labelForKey(currentKey)))
} else {
Text("Free")
.font(.system(size: TempoSyncKnobView.menuFontSize, weight: .semibold, design: .rounded))
}
if activeClamped {
Image(systemName: "exclamationmark.triangle.fill")
.font(.system(size: TempoSyncKnobView.warningIconSize))
}
Image(systemName: "chevron.down")
.font(.system(size: TempoSyncKnobView.warningIconSize))
.opacity(0.6)
}
.frame(height: TempoSyncKnobView.menuRowHeight)
.foregroundStyle(activeClamped ? Color.orange : Color.white.opacity(isSynced ? 1.0 : 0.65))
}
.buttonStyle(.plain)
.fixedSize()
.help(activeClamped
? "This note can't be represented at the current tempo — \(knob.label) is clamped to its limit."
: "Sync \(knob.label) to the tempo, or set it freely")
.popover(isPresented: $showDivisionPicker) {
divisionPicker
.presentationCompactAdaptation(.popover)
}
}
}
/// Height-capped, scrollable list of `Free` + every note division. Presented as a popover so the
/// system keeps it on-screen (flipping above the button near the bottom edge) and it scrolls when
/// taller than ``pickerMaxHeight`` — unlike a native menu, which ran off the bottom on iOS.
private var divisionPicker: some View {
let currentBpm: Double? = pedal.clock?.bpm
let currentKey: String = keyForCurrentSync()
return ScrollView {
VStack(alignment: .leading, spacing: TempoSyncKnobView.pickerRowSpacing) {
pickerRow(
key: TempoSyncKnobView.freeKey,
glyph: nil,
disabled: false,
selected: currentKey == TempoSyncKnobView.freeKey
)
ForEach(NoteDivision.allCases, id: \.self) { division in
// A division whose value clamps at the current tempo (e.g. a note longer than the
// maximum delay time) can't be represented accurately, so it is shown but disabled.
let unavailable: Bool = currentBpm.map { param.value(for: division, bpm: $0).clamped } ?? false
pickerRow(
key: division.rawValue,
glyph: division,
disabled: unavailable,
selected: currentKey == division.rawValue
)
}
}
.padding(TempoSyncKnobView.pickerPadding)
}
.frame(maxHeight: TempoSyncKnobView.pickerMaxHeight)
}
/// One selectable row in ``divisionPicker`` — a note glyph (or "Free" text), a trailing checkmark
/// when it is the current selection, and a disabled state for divisions that clamp at this tempo.
@ViewBuilder
private func pickerRow(key: String, glyph: NoteDivision?, disabled: Bool, selected: Bool) -> some View {
Button {
select(key)
showDivisionPicker = false
} label: {
HStack(spacing: TempoSyncKnobView.labelGlyphSpacing) {
if let glyph: NoteDivision = glyph {
NoteGlyphImageCache.image(for: glyph)
.resizable()
.scaledToFit()
.frame(height: TempoSyncKnobView.pickerGlyphHeight)
} else {
Text("Free")
.font(.system(size: TempoSyncKnobView.menuFontSize, weight: .semibold, design: .rounded))
}
Spacer(minLength: TempoSyncKnobView.labelGlyphSpacing)
if selected {
Image(systemName: "checkmark")
.font(.system(size: TempoSyncKnobView.checkmarkFontSize, weight: .semibold))
}
}
.frame(minWidth: TempoSyncKnobView.pickerRowMinWidth, alignment: .leading)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.disabled(disabled)
.accessibilityLabel(Text(glyph?.label ?? "Free"))
}
private func keyForCurrentSync() -> String {
if case .division(let division) = pedal.tempoSync[param.key] ?? .free {
return division.rawValue
}
return TempoSyncKnobView.freeKey
}
private func labelForKey(_ key: String) -> String {
key == TempoSyncKnobView.freeKey ? "Free" : (NoteDivision(rawValue: key)?.label ?? key)
}
private func select(_ key: String) {
// `setSync` bumps `pedal.tempoSyncRevision`, which this view observes — no local flag needed.
if key == TempoSyncKnobView.freeKey {
pedal.setSync(.free, for: param.key)
} else if let division: NoteDivision = NoteDivision(rawValue: key) {
pedal.setSync(.division(division), for: param.key)
}
}
}
// MARK: - PedalView
/// A stompbox-style enclosure view that renders all controls for a single `Pedal`.
@@ -266,6 +449,13 @@ public struct PedalView: View {
/// Presentation flag for the pedal info panel (description + control ranges).
@State private var showInfo: Bool = false
/// The rig's control map, injected by the builder so the pedal can draw a mapping strip. `nil`
/// when the rig has no bindings (or in contexts that don't set it) — the strip renders nothing.
@Environment(\.controlMappingMap) private var controlMappingMap: MIDIMap?
/// Mirrors ``ShoeGaze/tempoEnabled`` so tempo-sync knob affordances hide when tempo is off.
@Environment(\.shoeGazeTempoEnabled) private var tempoEnabled: Bool
// MARK: - Init
/// Creates a stompbox pedal view for the given pedal.
@@ -355,6 +545,7 @@ public struct PedalView: View {
sliderBank(sliders)
Spacer(minLength: 0)
bottomControls
PedalMappingStrip(pedal: pedal, map: controlMappingMap)
}
}
@@ -389,6 +580,7 @@ public struct PedalView: View {
.id(ObjectIdentifier(pedal))
}
Spacer(minLength: 0)
PedalMappingStrip(pedal: pedal, map: controlMappingMap)
}
}
@@ -522,12 +714,12 @@ public struct PedalView: View {
let rowItemSpacing: CGFloat = row.count >= columns
? PedalView.knobSpacing
: PedalView.knobRowItemSpacing
HStack(spacing: rowItemSpacing) {
// Top-align so every dial pins to the row's top edge — a tempo-sync cell grows taller
// below the dial (glyph menu, warning) without dragging its neighbours' dials down.
HStack(alignment: .top, 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)
knobCell(knobPair.element)
}
Spacer(minLength: 0)
}
@@ -535,6 +727,25 @@ public struct PedalView: View {
}
}
/// Renders one effect knob — a tempo-sync knob when the parameter is syncable and tempo is
/// enabled, otherwise a plain ``ParameterKnob``. Syncable knobs are matched by node identity
/// against `pedal.tempoSyncableParams`.
@ViewBuilder
private func knobCell(_ knob: PedalKnob) -> some View {
if tempoEnabled, let param: TempoSyncableParam = syncableParam(for: knob) {
TempoSyncKnobView(pedal: pedal, knob: knob, param: param)
} else {
ParameterKnob(knob.label, node: knob.node, range: knob.range)
.foregroundStyle(Color.white)
}
}
/// The tempo-syncable descriptor whose parameter node backs `knob`, or `nil` if the knob is
/// not syncable. Matched by `UIParamNode` identity so it is robust to label changes.
private func syncableParam(for knob: PedalKnob) -> TempoSyncableParam? {
pedal.tempoSyncableParams.first { $0.node === knob.node }
}
/// Row of stepped selector knobs drawn from `pedal.effectSelectors`, beneath the knob grid.
/// Renders nothing when the pedal publishes no selectors.
@ViewBuilder
@@ -16,4 +16,8 @@ public extension Notification.Name {
/// Create a new, named, empty rig and make it current.
static let shoeGazeNewRig: Notification.Name = Notification.Name("net.realizedsound.shoegaze.newRig")
/// Load the set-list rig at a zero-based slot index (0…9, mapped to ⌘⇧1…⌘⇧0 on macOS). The
/// slot index is posted as the notification's `object` (an `NSNumber`/`Int`).
static let shoeGazeLoadRigSlot: Notification.Name = Notification.Name("net.realizedsound.shoegaze.loadRigSlot")
}
@@ -149,7 +149,20 @@ struct RigLibrarySidebarView: View {
.contentShape(Rectangle())
}
.buttonStyle(.plain)
// Drag the row onto another to reorder; dropping inserts it just before the target. Works
// on macOS (mouse drag) and iPad (long-press drag); taps still select.
.draggable(entry.id.uuidString)
.dropDestination(for: String.self) { droppedIDs, _ in
guard let first: String = droppedIDs.first else { return false }
moveDragged(first, onto: entry)
return true
}
.contextMenu {
Button("Move Up") { store.moveUp(entry) }
.disabled(isFirst(entry))
Button("Move Down") { store.moveDown(entry) }
.disabled(isLast(entry))
Divider()
Button("Rename…") { onRename(entry) }
Button("Duplicate…") { onDuplicate(entry) }
// Encoding a fully-concrete RigEntry to JSON does not fail in practice; on the
@@ -167,6 +180,28 @@ struct RigLibrarySidebarView: View {
}
}
// MARK: - Reorder helpers
private func isFirst(_ entry: RigEntry) -> Bool {
store.entries.first?.id == entry.id
}
private func isLast(_ entry: RigEntry) -> Bool {
store.entries.last?.id == entry.id
}
/// Moves the dragged entry (by id string) to sit just before `target` in the set list.
private func moveDragged(_ draggedIDString: String, onto target: RigEntry) {
guard let draggedID: UUID = UUID(uuidString: draggedIDString), draggedID != target.id else { return }
var order: [UUID] = store.entries.map(\.id)
guard let from: Int = order.firstIndex(of: draggedID) else { return }
order.remove(at: from)
// Target's index in the post-removal array; inserting there drops the dragged row before it.
guard let to: Int = order.firstIndex(of: target.id) else { return }
order.insert(draggedID, at: to)
store.applyOrder(order)
}
// MARK: - Action bar
private var actionBar: some View {
@@ -65,6 +65,9 @@ public struct ShoeGazeBuilderView: View {
private static let maxCrossfadeSeconds: Double = 10.0
/// Highest board reachable via a ⌘-number switch shortcut.
private static let maxBoardShortcuts: Int = 9
/// The number of set-list rigs reachable by ⌘⇧1…⌘⇧0 (the top ten).
private static let maxRigShortcuts: Int = 10
/// 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.
@@ -182,6 +185,16 @@ public struct ShoeGazeBuilderView: View {
@State private var showRecordingFolderImporter: Bool = false
#endif
#if os(macOS)
/// The AppKit local key-down monitor that routes bare letter/digit keys to `midi.ingestKey`,
/// or `nil` when not installed. Stored so it can be removed on disappear.
@State private var keyMonitor: Any?
#else
/// Whether the builder root holds keyboard focus, so `.onKeyPress` delivers hardware-keyboard
/// presses to the key bindings. Held `true` except while a text field is being edited.
@FocusState private var keyboardFocused: Bool
#endif
// MARK: - Init
/// Creates a builder view.
@@ -229,7 +242,10 @@ public struct ShoeGazeBuilderView: View {
}
public var body: some View {
// The builder body is split across `layoutChrome` → `presentationChrome` → `body` because the
// full modifier chain (layout + lifecycle + every sheet / dialog / alert + key capture) is too
// large for the Swift expression type-checker as a single expression.
private var layoutChrome: some View {
rootContent
.padding(ShoeGazeBuilderView.outerPadding)
// A large min width is a macOS window sizing hint; on iPad it would force content wider than
@@ -265,12 +281,26 @@ public struct ShoeGazeBuilderView: View {
restoreInputSelection()
syncIdleTimer()
maybeWarnICloudUnavailable()
#if os(macOS)
installKeyMonitor()
#else
keyboardFocused = true
#endif
}
.onDisappear {
releaseIdleTimer()
#if os(macOS)
removeKeyMonitor()
#endif
}
.onDisappear { releaseIdleTimer() }
.onChange(of: transportTick) { syncIdleTimer() }
.onChange(of: library.isLoaded) {
maybeWarnICloudUnavailable()
}
}
private var presentationChrome: some View {
layoutChrome
.background(boardsSheetAnchor)
.background(rigExportAnchor)
.background(rigImportAnchor)
@@ -311,6 +341,11 @@ public struct ShoeGazeBuilderView: View {
.onReceive(NotificationCenter.default.publisher(for: .shoeGazeNewRig)) { _ in
promptNewRig()
}
.onReceive(NotificationCenter.default.publisher(for: .shoeGazeLoadRigSlot)) { note in
if let index: Int = note.object as? Int {
loadRigSlot(index)
}
}
.confirmationDialog(
"Clear all boards?",
isPresented: $showClearDialog,
@@ -359,6 +394,136 @@ public struct ShoeGazeBuilderView: View {
.overlay(alignment: .top) { midiLearnBanner }
}
public var body: some View {
presentationChrome
// Letter/digit keys drive bound rig actions. macOS uses an AppKit key monitor (installed in
// onAppear) because SwiftUI's `.onKeyPress` only delivers to the focused view, and the builder
// root is rarely the focused view. iOS routes hardware-keyboard presses through `.onKeyPress`,
// which requires the root to be focusable AND focused — so the root claims focus on appear and
// reclaims it whenever a modal that stole focus (a text-field sheet) closes. A focused
// `TextField` still wins while open, so typing is never hijacked.
#if !os(macOS)
.modifier(KeyboardCaptureModifier(
keyboardFocused: $keyboardFocused,
modalOpen: anyFocusStealingModalOpen,
onKeyPress: handleKeyPress
))
#endif
}
#if !os(macOS)
/// Whether any modal that can take keyboard focus from the builder root is currently open. When
/// it closes, the root reclaims focus so hardware-keyboard bindings keep firing. Text-field-
/// bearing sheets (rig rename, board editor) are the ones that matter, but covering the main
/// content sheets keeps focus robust across all of them.
private var anyFocusStealingModalOpen: Bool {
showMIDISheet || showHelpSheet || showRigsSheet || showPaletteSheet
|| showSettingsSheet || showBoardsSheet || namePrompt != nil
}
#endif
#if !os(macOS)
/// Routes a bare key press to the MIDI controller's key bindings, ignoring modified presses so
/// `⌘`-shortcuts still work. Returns `.handled` when a binding consumed the key, else `.ignored`.
/// A focused text field consumes keys first via the responder chain, so this only fires when the
/// user is not typing.
private func handleKeyPress(_ keyPress: KeyPress) -> KeyPress.Result {
guard let midi: MIDIController = midi else { return .ignored }
// Command chords belong to the menu shortcuts; shift / control / option qualify the binding.
guard keyPress.modifiers.contains(.command) == false else { return .ignored }
var modifiers: MIDIMap.KeyModifiers = []
if keyPress.modifiers.contains(.shift) { modifiers.insert(.shift) }
if keyPress.modifiers.contains(.control) { modifiers.insert(.control) }
if keyPress.modifiers.contains(.option) { modifiers.insert(.option) }
// `key.character` is the unshifted base key, so shift stays represented in `modifiers` only.
let base: String = String(keyPress.key.character)
return midi.ingestKey(base, modifiers: modifiers) ? .handled : .ignored
}
#endif
#if !os(macOS)
/// The iOS/iPadOS key-capture modifiers, factored into a `ViewModifier` so the (large) builder
/// body stays under the Swift expression type-checker's complexity limit. Makes the root
/// focusable and focused so `.onKeyPress` receives hardware-keyboard presses, and reclaims focus
/// whenever a focus-stealing modal closes.
private struct KeyboardCaptureModifier: ViewModifier {
@FocusState.Binding var keyboardFocused: Bool
let modalOpen: Bool
let onKeyPress: (KeyPress) -> KeyPress.Result
func body(content: Content) -> some View {
content
.focusable()
.focusEffectDisabled()
.focused($keyboardFocused)
.onKeyPress(phases: .down) { keyPress in onKeyPress(keyPress) }
.onChange(of: modalOpen) { _, isOpen in
if isOpen == false { keyboardFocused = true }
}
}
}
#endif
#if os(macOS)
/// Installs an AppKit local key-down monitor that routes bare letter/digit keys to the MIDI
/// controller's key bindings. Unlike SwiftUI `.onKeyPress`, a local monitor sees every key-down
/// regardless of which view holds SwiftUI focus, so mapped keys fire even when the board — not a
/// text field — is what the user is looking at. Keys are swallowed only when a binding consumes
/// them; text entry and menu shortcuts pass through untouched.
private func installKeyMonitor() {
guard keyMonitor == nil else { return }
keyMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in
let flags: NSEvent.ModifierFlags = event.modifierFlags
// Command chords belong to the menu keyboard shortcuts; key-repeat would toggle
// repeatedly while a key is held. Filter both before touching any binding.
//
// Derive the base key with *no* modifiers applied, not `charactersIgnoringModifiers`
// (which still bakes in Shift — `⇧2` → `"@"` — and mangles Control into a C0 code). This
// matches the iOS path's `keyPress.key.character`, so the same physical chord stores the
// same base key on both platforms and a rig stays portable across an iCloud sync.
guard flags.contains(.command) == false,
event.isARepeat == false,
let characters: String = event.characters(byApplyingModifiers: []) else { return event }
let modifiers: MIDIMap.KeyModifiers = ShoeGazeBuilderView.keyModifiers(from: flags)
// Local monitors are delivered on the main thread; hop the actor with only Sendable
// values (NSEvent itself is not Sendable and must not cross the boundary).
let consumed: Bool = MainActor.assumeIsolated { routeMonitoredKey(characters, modifiers) }
return consumed ? nil : event
}
}
/// Maps AppKit modifier flags to the persisted ``MIDIMap/KeyModifiers`` set (shift / control /
/// option; command is reserved for menu shortcuts and never reaches here).
private static func keyModifiers(from flags: NSEvent.ModifierFlags) -> MIDIMap.KeyModifiers {
var modifiers: MIDIMap.KeyModifiers = []
if flags.contains(.shift) { modifiers.insert(.shift) }
if flags.contains(.control) { modifiers.insert(.control) }
if flags.contains(.option) { modifiers.insert(.option) }
return modifiers
}
/// Applies a monitored key press to the MIDI controller's key bindings, returning `true` when a
/// binding consumed it. A field editor holding first responder means the user is typing, so the
/// key is let through untouched — a rig-name or board-label edit is never hijacked into a toggle.
@MainActor
private func routeMonitoredKey(_ characters: String, _ modifiers: MIDIMap.KeyModifiers) -> Bool {
guard let midi: MIDIController = midi else { return false }
if let responder: NSResponder = NSApp.keyWindow?.firstResponder, responder is NSText {
return false
}
return midi.ingestKey(characters, modifiers: modifiers)
}
/// Removes the local key-down monitor installed by ``installKeyMonitor()``.
private func removeKeyMonitor() {
if let monitor: Any = keyMonitor {
NSEvent.removeMonitor(monitor)
keyMonitor = nil
}
}
#endif
/// Hosts the compact rig-library sheet on its own node.
private var rigsSheetAnchor: some View {
Color.clear
@@ -405,8 +570,8 @@ public struct ShoeGazeBuilderView: View {
/// A banner shown while a control is armed for MIDI Learn, prompting the user to move it.
@ViewBuilder
private var midiLearnBanner: some View {
if let midi: MIDIController = midi, midi.learnTarget != nil {
Text("MIDI Learn — press a footswitch or move an expression pedal to assign it")
if let midi: MIDIController = midi, let target: MIDIController.LearnTarget = midi.learnTarget {
Text(midiLearnBannerText(for: target))
.font(.callout.weight(.semibold))
.foregroundStyle(Color.black)
.padding(.horizontal, 14)
@@ -416,6 +581,18 @@ public struct ShoeGazeBuilderView: View {
}
}
/// Banner copy tailored to what the armed Learn target is waiting for.
private func midiLearnBannerText(for target: MIDIController.LearnTarget) -> String {
switch target {
case .key:
return "Learn — press a key to assign it"
case .action:
return "Learn — press a footswitch to assign it"
case .cc:
return "Learn — move an expression pedal to assign it"
}
}
/// 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 {
@@ -487,10 +664,14 @@ public struct ShoeGazeBuilderView: View {
topSection
}
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
ControlMappingLegend()
boardArea
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
.environment(\.shoeGazeTempoEnabled, shoeGaze.tempoEnabled)
// Feed the rig's control map into the board tree so each pedal can draw its mapping strip.
// Reading `shoeGaze.midiMap` here (observable) refreshes every strip when a binding changes.
.environment(\.controlMappingMap, shoeGaze.midiMap)
}
// MARK: - Compact layout (iPhone / narrow iPad)
@@ -578,14 +759,7 @@ public struct ShoeGazeBuilderView: View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
rigBypassButton
// fixedSize stops the switch Toggle from expanding to fill the row (which pushed
// the following controls far to the right, under the scope).
Toggle("Mute rig", isOn: Binding(
get: { shoeGaze.tunerMutesRig },
set: { shoeGaze.tunerMutesRig = $0 }
))
.toggleStyle(.switch)
.fixedSize()
rigMuteButton
helpButton
if let midi: MIDIController = midi {
MIDIIndicatorView(controller: midi) { showMIDISheet = true }
@@ -942,6 +1116,7 @@ public struct ShoeGazeBuilderView: View {
}
helpButton
rigBypassButton
rigMuteButton
EngineConfigView(
shoeGaze: shoeGaze,
hardwareSampleRate: hardwareSampleRate,
@@ -951,12 +1126,13 @@ public struct ShoeGazeBuilderView: View {
.frame(height: TempoView.enabledHeight)
HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
// Mute-rig-while-tuning toggle sits to the left of the input selector.
Toggle("Mute rig", isOn: Binding(
// Whether engaging the tuner silences the rig; sits left of the input selector.
Toggle("Mute while tuning", isOn: Binding(
get: { shoeGaze.tunerMutesRig },
set: { shoeGaze.tunerMutesRig = $0 }
))
.toggleStyle(.switch)
.fixedSize()
Text("Input:")
.font(.subheadline)
@@ -1010,6 +1186,22 @@ public struct ShoeGazeBuilderView: View {
.help("Bypass the entire rig — every board passes your dry input straight through")
}
/// Global rig mute — a hard gate to silence the whole output (distinct from Bypass, which
/// passes the dry signal through). Lit when engaged. A live performance panic/silence control.
private var rigMuteButton: some View {
let muted: Bool = shoeGaze.rigMuted
return Button {
shoeGaze.toggleRigMuted()
} label: {
Label(muted ? "Rig Muted" : "Mute Rig",
systemImage: muted ? "speaker.slash.fill" : "speaker.wave.2.fill")
.font(.subheadline)
}
.buttonStyle(.bordered)
.tint(muted ? .red : .gray)
.help("Mute the entire rig output — silences all sound")
}
// MARK: - Board area
private var boardArea: some View {
@@ -1213,19 +1405,40 @@ public struct ShoeGazeBuilderView: View {
// 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.
/// edit target, plus ⌘M to toggle the rig mute. 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) }
// Titles are invisible (the ZStack is opacity 0) but feed the iPadOS ⌘-hold
// discoverability HUD, so the shortcut reads as a named command there.
Button("Switch to Board \(index + 1)") { switchToBoard(index) }
.keyboardShortcut(KeyEquivalent(Character("\(index + 1)")), modifiers: .command)
}
// ⌘Z toggles rig mute on iOS/iPadOS hardware keyboards. On macOS the Board menu item
// owns the ⌘Z equivalent, so it is not also bound here (a double-bound event is ambiguous).
#if !os(macOS)
Button("Mute / Unmute Rig") { shoeGaze.toggleRigMuted() }
.keyboardShortcut("z", modifiers: .command)
// ⌘⇧1…⌘⇧9 + ⌘⇧0 load set-list rigs 1…10. macOS binds these via the Rigs ▸ Set List menu
// instead, so they are not also bound here.
ForEach(0 ..< ShoeGazeBuilderView.maxRigShortcuts, id: \.self) { slot in
Button("Load Set List Rig \(slot + 1)") { loadRigSlot(slot) }
.keyboardShortcut(ShoeGazeBuilderView.rigSlotKey(slot), modifiers: [.command, .shift])
}
#endif
}
.opacity(0)
.frame(width: 0, height: 0)
.accessibilityHidden(true)
}
/// The key equivalent for set-list slot `slot` (0-based): slots 0…8 map to `1`…`9`, slot 9 to
/// `0` — matching the ⌘⇧1…⌘⇧0 physical row.
private static func rigSlotKey(_ slot: Int) -> KeyEquivalent {
KeyEquivalent(Character(slot < 9 ? "\(slot + 1)" : "0"))
}
/// 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 }
@@ -1315,6 +1528,16 @@ public struct ShoeGazeBuilderView: View {
transportTick.toggle()
}
/// Loads the set-list rig at zero-based `index` (the library's manual order), if one exists.
/// Backs the ⌘⇧1…⌘⇧0 shortcuts and the macOS Rigs ▸ Set List menu. Routes through
/// ``requestLoad(_:)`` so the unsaved-changes prompt and no-op-if-current behaviour apply.
///
/// - Parameter index: Zero-based slot index (0…9).
private func loadRigSlot(_ index: Int) {
guard index >= 0, index < library.entries.count else { return }
requestLoad(library.entries[index])
}
/// 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) {
+162 -20
View File
@@ -19,13 +19,37 @@ public struct TempoView: View {
// MARK: - Constants
private static let pollIntervalNanoseconds: UInt64 = 33_333_333 // ~30 Hz
/// Fraction of each beat the LED stays lit — a short flash, not a 50% duty-cycle blink.
private static let flashDutyCycle: Double = 0.15
private static let minBpm: Double = 30.0
private static let maxBpm: Double = 300.0
private static let bpmStep: Double = 1.0
private static let ledDiameter: CGFloat = 14
/// Width of the editable BPM text field — fits three digits at the readout font.
private static let bpmFieldWidth: CGFloat = 44
private static let bpmFontSize: CGFloat = 18
/// Maximum digits accepted in the BPM field (max 300 BPM is three digits).
private static let bpmMaxDigits: Int = 3
private static let rowSpacing: CGFloat = 10
// Metronome track: a dot swings wall-to-wall once per beat, pausing at each wall (the beat)
// so the eye can anticipate the hit. Pendulum easing comes for free from the cosine map.
private static let trackWidth: CGFloat = 150
private static let trackHeight: CGFloat = 16
private static let trackCornerRadius: CGFloat = 4
private static let trackBrightness: Double = 0.14
private static let trackBorderOpacity: Double = 0.35
private static let trackBorderWidth: CGFloat = 1
/// Vertical playhead sweeping horizontally across the track (Looper-style), full track height.
private static let lineWidth: CGFloat = 3
/// Playhead opacity floor at mid-swing; ramps to full at the walls so it fades as it travels
/// toward center and re-brightens into each beat.
private static let lineMinOpacity: Double = 0.25
/// Curve on the wall-proximity → brightness map; > 1 dims harder through the middle.
private static let brightnessFadeCurve: Double = 1.6
/// Soft glow drawn behind the playhead; its opacity peaks at the turnaround (on the beat).
private static let glowWidth: CGFloat = 16
private static let glowMaxOpacity: Double = 0.7
/// End-wall tick marks sit on the beat positions.
private static let wallTickWidth: CGFloat = 2
private static let wallTickOpacity: Double = 0.4
/// Fixed row height = the enabled (BPM/TAP-visible) height, so toggling doesn't shift layout.
static let enabledHeight: CGFloat = 34
@@ -34,7 +58,13 @@ public struct TempoView: View {
private let shoeGaze: ShoeGaze
@State private var displayedBpm: Double
@State private var ledOn: Bool = false
/// Continuous beat position, polled from the clock; drives the metronome dot.
@State private var beat: Double = 0.0
/// The editable BPM text. Kept in sync with `displayedBpm` while the field isn't focused; on
/// commit it is validated (integer only), clamped to `[minBpm, maxBpm]`, and applied.
@State private var bpmText: String
@FocusState private var bpmFieldFocused: Bool
// MARK: - Init
@@ -42,6 +72,7 @@ public struct TempoView: View {
public init(shoeGaze: ShoeGaze) {
self.shoeGaze = shoeGaze
self._displayedBpm = State(initialValue: shoeGaze.clock.bpm)
self._bpmText = State(initialValue: String(Int(shoeGaze.clock.bpm.rounded())))
}
// MARK: - Body
@@ -57,19 +88,13 @@ public struct TempoView: View {
.help("Show the tempo indicator and enable tempo-synced controls")
if shoeGaze.tempoEnabled {
led
Text("\(Int(displayedBpm.rounded())) BPM")
.font(.system(size: 18, weight: .semibold, design: .rounded))
.foregroundStyle(Color.white)
metronome
bpmField
Stepper(
"",
value: Binding(
get: { displayedBpm },
set: { newValue in
let clamped: Double = min(max(newValue, TempoView.minBpm), TempoView.maxBpm)
shoeGaze.clock.bpm = clamped
displayedBpm = clamped
}
set: { newValue in applyBpm(newValue) }
),
in: TempoView.minBpm ... TempoView.maxBpm,
step: TempoView.bpmStep
@@ -84,21 +109,138 @@ public struct TempoView: View {
.frame(height: TempoView.enabledHeight)
.task(id: shoeGaze.tempoEnabled) {
while shoeGaze.tempoEnabled && !Task.isCancelled {
let beat: Double = shoeGaze.clock.currentBeat
let phase: Double = beat - beat.rounded(.down)
ledOn = phase < TempoView.flashDutyCycle
beat = shoeGaze.clock.currentBeat
displayedBpm = shoeGaze.clock.bpm
// Don't overwrite the field mid-edit — only reflect external tempo changes when the
// field isn't focused (tap tempo, stepper, MIDI, rig load).
if !bpmFieldFocused {
bpmText = String(Int(displayedBpm.rounded()))
}
try? await Task.sleep(nanoseconds: TempoView.pollIntervalNanoseconds)
}
}
}
// MARK: - BPM field
/// Editable BPM readout. Accepts integer input, validated and clamped on commit (Return, or the
/// keyboard's Done, or focus loss). Non-numeric or empty input reverts to the current tempo.
private var bpmField: some View {
HStack(spacing: TempoView.rowSpacing / 2) {
TextField("", text: $bpmText)
.textFieldStyle(.plain)
.multilineTextAlignment(.trailing)
.font(.system(size: TempoView.bpmFontSize, weight: .semibold, design: .rounded))
.foregroundStyle(Color.white)
.frame(width: TempoView.bpmFieldWidth)
.fixedSize()
.focused($bpmFieldFocused)
.onSubmit { commitBpm() }
#if os(iOS)
.keyboardType(.numberPad)
.toolbar {
ToolbarItemGroup(placement: .keyboard) {
Spacer()
Button("Done") { bpmFieldFocused = false }
}
}
#endif
Text("BPM")
.font(.system(size: TempoView.bpmFontSize, weight: .semibold, design: .rounded))
.foregroundStyle(Color.white)
}
.onChange(of: bpmText) { _, newValue in
// Reject non-numeric input as it is typed, and cap at three digits (max 300 BPM).
let filtered: String = String(newValue.filter { $0.isNumber }.prefix(TempoView.bpmMaxDigits))
if filtered != newValue {
bpmText = filtered
}
}
.onChange(of: bpmFieldFocused) { _, focused in
// Commit when focus leaves the field (tap away / Done), the counterpart to onSubmit.
if !focused {
commitBpm()
}
}
}
/// Validates and applies the typed BPM: integers only, clamped to `[minBpm, maxBpm]`. Non-numeric
/// or empty input reverts the field to the current tempo without changing it.
private func commitBpm() {
let digits: String = bpmText.filter { $0.isNumber }
if let value: Int = Int(digits) {
applyBpm(Double(value))
} else {
bpmText = String(Int(displayedBpm.rounded()))
}
}
/// Clamps `bpm` to the allowed range, applies it to the session, and syncs the field text.
private func applyBpm(_ bpm: Double) {
let clamped: Double = min(max(bpm, TempoView.minBpm), TempoView.maxBpm)
shoeGaze.setBpm(clamped)
displayedBpm = clamped
bpmText = String(Int(clamped.rounded()))
}
// MARK: - Subviews
private var led: some View {
Circle()
.fill(ledOn ? Color.red : Color.red.opacity(0.15))
.frame(width: TempoView.ledDiameter, height: TempoView.ledDiameter)
/// Horizontal pendulum: the dot maps `beat` through a cosine so it eases to a stop at each
/// wall (an integer beat) and moves fastest at mid-swing — the wall pauses give the eye a
/// runway to anticipate the beat. `x01 = (1 − cos(π·swing)) / 2`, `swing = beat mod 2`, puts
/// the left wall on even beats and the right wall on odd beats (one wall hit per beat).
private var metronome: some View {
// Reduce beat mod 2 before the cosine so precision holds over a long session.
let swing: Double = beat.truncatingRemainder(dividingBy: 2)
let x01: Double = (1 - cos(.pi * swing)) / 2
// Proximity to a wall in [0, 1]: 1 at a wall (on the beat), 0 at mid-swing. The curve dims
// harder through the middle so the playhead visibly fades as it travels toward center.
let wallGlow: Double = pow(1 - 2 * min(x01, 1 - x01), TempoView.brightnessFadeCurve)
return ZStack(alignment: .leading) {
RoundedRectangle(cornerRadius: TempoView.trackCornerRadius)
.fill(Color(white: TempoView.trackBrightness))
.overlay(
RoundedRectangle(cornerRadius: TempoView.trackCornerRadius)
.strokeBorder(
Color.white.opacity(TempoView.trackBorderOpacity),
lineWidth: TempoView.trackBorderWidth
)
)
// Beat-position tick marks flush against each end wall.
.overlay(alignment: .leading) { wallTick }
.overlay(alignment: .trailing) { wallTick }
playhead(x01: x01, wallGlow: wallGlow)
}
.frame(width: TempoView.trackWidth, height: TempoView.trackHeight)
.clipShape(RoundedRectangle(cornerRadius: TempoView.trackCornerRadius))
}
private var wallTick: some View {
Rectangle()
.fill(Color.white.opacity(TempoView.wallTickOpacity))
.frame(width: TempoView.wallTickWidth)
}
private func playhead(x01: Double, wallGlow: Double) -> some View {
// Travel spans the track minus the line's own width so the playhead kisses each wall.
let travel: CGFloat = TempoView.trackWidth - TempoView.lineWidth
let x: CGFloat = CGFloat(x01) * travel
let lineOpacity: Double = TempoView.lineMinOpacity + (1 - TempoView.lineMinOpacity) * wallGlow
// Center glow + line share a leading-aligned box; offset positions the line's leading edge.
return ZStack {
Rectangle()
.fill(Color.red.opacity(TempoView.glowMaxOpacity * wallGlow))
.frame(width: TempoView.glowWidth, height: TempoView.trackHeight)
.blur(radius: TempoView.glowWidth / 3)
Rectangle()
.fill(Color.red.opacity(lineOpacity))
.frame(width: TempoView.lineWidth, height: TempoView.trackHeight)
}
.frame(width: TempoView.lineWidth, height: TempoView.trackHeight, alignment: .center)
.offset(x: x)
}
private var tapArea: some View {
@@ -181,6 +181,42 @@ struct MIDIControllerCCTests {
}
}
@Test func ccIsIgnoredWhileParameterIsTempoSynced() throws {
// A CC bound to a parameter that is locked to a note division must be ignored — the value is
// tempo-derived and a CC write would be overwritten on the next tempo change. The binding
// stays intact and resumes control once the parameter is set back to Free.
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 128)
defer { try? FileManager.default.removeItem(at: url) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
sg.clock.bpm = 120.0
let board: PedalBoard = try sg.addBoard()
let delay: DelayPedal = DelayPedal()
try board.add(delay)
try sg.finalizeBoard(board)
let controller: MIDIController = MIDIController(engine: engine, shoeGaze: sg)
withExtendedLifetime(sg) {
// Bind CC 21 to Time (control 0 on a Delay pedal).
controller.armCCLearn(pedalControl(delay.id, 0))
controller.ingestForTesting(.controlChange(channel: 0, controller: 21, value: 0))
// Lock Time to a quarter note — 0.5 s at 120 BPM.
delay.setSync(.division(.quarter), for: "time")
let syncedValue: Double = delay.$time.value
#expect(abs(syncedValue - 0.5) < 1e-9)
// A CC while synced must not move the value.
controller.ingestForTesting(.controlChange(channel: 0, controller: 21, value: 127))
#expect(abs(delay.$time.value - syncedValue) < 1e-9, "CC must not drive a tempo-synced parameter")
// Back to Free — the same binding drives the control again.
delay.setSync(.free, for: "time")
let timeMax: Double = delay.ccMappableControls[0].range.upperBound
controller.ingestForTesting(.controlChange(channel: 0, controller: 21, value: 127))
#expect(abs(delay.$time.value - timeMax) < 1e-9, "CC resumes control once the parameter is Free")
}
}
@Test func unboundCCIsIgnored() throws {
let (controller, sg, board, url): (MIDIController, ShoeGaze, PedalBoard, URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
@@ -0,0 +1,201 @@
// MIDIControllerKeyTests.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("MIDIController key bindings")
struct MIDIControllerKeyTests {
/// Builds an engine + a one-board rig (a single Volume pedal) + a controller.
private func makeRig() throws -> (MIDIController, ShoeGaze, URL) {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256)
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
board.label = "Board 1"
try board.add(VolumePedal())
try sg.finalizeBoard(board)
let controller: MIDIController = MIDIController(engine: engine, shoeGaze: sg)
return (controller, sg, url)
}
@Test func learnCapturesKeyAndFiresCallback() throws {
let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
var changed: Bool = false
controller.onMapChanged = { changed = true }
controller.armKeyLearn(.rigBypass)
let consumed: Bool = controller.ingestKey("b")
#expect(consumed, "the learn press is consumed")
#expect(controller.learnTarget == nil)
#expect(changed)
#expect(controller.keyBinding(for: .rigBypass)?.key == "b")
#expect(sg.midiMap?.keys.count == 1)
#expect(sg.rigBypassed == false, "learn must not toggle")
}
}
@Test func keyLatchesOnEachPress() throws {
let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armKeyLearn(.rigBypass)
_ = controller.ingestKey("b") // learn only
#expect(sg.rigBypassed == false)
#expect(controller.ingestKey("b"))
#expect(sg.rigBypassed == true, "first press engages")
#expect(controller.ingestKey("b"))
#expect(sg.rigBypassed == false, "second press releases")
}
}
@Test func caseInsensitiveMatch() throws {
let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armKeyLearn(.rigBypass)
_ = controller.ingestKey("b")
#expect(controller.ingestKey("B"), "an uppercase press matches a lowercase binding")
#expect(sg.rigBypassed == true)
}
}
@Test func shiftDistinguishesTwoBindingsOnTheSameKey() throws {
let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armKeyLearn(.rigBypass)
_ = controller.ingestKey("b", modifiers: [])
controller.armKeyLearn(.rigMute)
_ = controller.ingestKey("b", modifiers: [.shift])
#expect(sg.midiMap?.keys.count == 2, "b and ⇧b are independent bindings")
#expect(controller.ingestKey("b", modifiers: []))
#expect(sg.rigBypassed == true, "unmodified b drives bypass")
#expect(sg.rigMuted == false, "unmodified b must not fire the ⇧b binding")
#expect(controller.ingestKey("b", modifiers: [.shift]))
#expect(sg.rigMuted == true, "⇧b drives mute")
#expect(sg.rigBypassed == true, "⇧b must not re-fire the plain-b binding")
}
}
@Test func modifierMismatchIsNotConsumed() throws {
let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armKeyLearn(.rigBypass)
_ = controller.ingestKey("b", modifiers: [.shift]) // learn ⇧b
#expect(controller.ingestKey("b", modifiers: []) == false, "plain b does not match ⇧b")
#expect(controller.ingestKey("b", modifiers: [.control]) == false, "⌃b does not match ⇧b")
#expect(sg.rigBypassed == false)
#expect(controller.ingestKey("b", modifiers: [.shift]), "⇧b matches")
#expect(sg.rigBypassed == true)
}
}
@Test func unboundKeyIsNotConsumed() throws {
let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armKeyLearn(.rigBypass)
_ = controller.ingestKey("b")
#expect(controller.ingestKey("z") == false, "an unbound key falls through")
#expect(sg.rigBypassed == false)
}
}
@Test func digitKeyBinds() throws {
let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armKeyLearn(.rigBypass)
_ = controller.ingestKey("3")
#expect(controller.keyBinding(for: .rigBypass)?.key == "3")
#expect(controller.ingestKey("3"))
#expect(sg.rigBypassed == true)
}
}
@Test func nonAlphanumericKeyRejected() throws {
let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armKeyLearn(.rigBypass)
// Return, Tab, and Escape are single Characters but not letters/digits — they must not be
// learnable, or binding one would silently swallow it everywhere in the app.
#expect(controller.ingestKey("\r") == false)
#expect(controller.ingestKey("\t") == false)
#expect(controller.ingestKey("\u{1B}") == false)
#expect(controller.ingestKey(" ") == false)
#expect(controller.learnTarget != nil, "a rejected press leaves learn armed")
#expect(sg.midiMap?.keys.isEmpty ?? true)
}
}
@Test func multiCharacterInputRejected() throws {
let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armKeyLearn(.rigBypass)
#expect(controller.ingestKey("ab") == false, "a multi-character press is ignored")
#expect(controller.learnTarget != nil, "an ignored press leaves learn armed")
#expect(sg.midiMap?.keys.isEmpty ?? true)
}
}
@Test func keyBindingSurvivesSaveLoadAndStillFires() throws {
let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
let preset: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".json")
defer { try? FileManager.default.removeItem(at: preset) }
controller.armKeyLearn(.rigBypass)
_ = controller.ingestKey("b")
try sg.saveRig(to: preset)
try sg.loadRig(from: preset)
#expect(sg.midiMap?.keys.first?.key == "b", "the key binding survives a file round-trip")
#expect(controller.ingestKey("b"), "the restored binding still fires")
#expect(sg.rigBypassed == true)
withExtendedLifetime(sg) { }
}
@Test func clearRemovesBinding() throws {
let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armKeyLearn(.rigBypass)
_ = controller.ingestKey("b")
#expect(controller.keyBinding(for: .rigBypass) != nil)
controller.clearKeyBinding(for: .rigBypass)
#expect(controller.keyBinding(for: .rigBypass) == nil)
#expect(controller.ingestKey("b") == false, "a cleared key no longer fires")
#expect(sg.rigBypassed == false)
}
}
}
@@ -44,6 +44,16 @@ struct MIDIMapCodableTests {
channel: 0,
target: .boardLevel(boardID: Self.boardID, boardLabelHint: "Board 1")
),
],
keys: [
MIDIMap.KeyBinding(key: "b", action: .rigBypass, displayNameHint: "Rig"),
MIDIMap.KeyBinding(key: "b", modifiers: [.shift], action: .rigMute),
MIDIMap.KeyBinding(
key: "r",
modifiers: [.control, .option],
action: .pedalAction(pedalID: Self.looperID, kind: .looperRecordStop),
displayNameHint: "Looper"
),
]
)
}
@@ -79,4 +89,43 @@ struct MIDIMapCodableTests {
let decoded: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data)
#expect(decoded.midiMap == nil, "legacy rig JSON should decode with a nil midiMap")
}
@Test func keyBindingsSurviveArchiveDocumentRoundTrip() throws {
// The `.shoegaze` archive / share path wraps a RigEntry → ShoeGazeState → MIDIMap. Verify a
// key binding survives a full document encode/decode, not just a bare MIDIMap round-trip.
let state: ShoeGazeState = ShoeGazeState(boards: [], midiMap: sampleMap())
let entry: RigEntry = RigEntry(name: "Keys", state: state)
let document: ShoeGazeDocument = ShoeGazeDocument(rig: entry)
let data: Data = try document.data()
let decoded: ShoeGazeDocument = try ShoeGazeDocument.decoded(from: data)
let restored: MIDIMap? = decoded.rigEntries?.first?.state.midiMap
#expect(restored?.keys == sampleMap().keys)
}
@Test func keyBindingWithoutModifiersDecodesUnmodified() throws {
// A key binding saved before modifiers existed has a `key` + `action` but no `modifiers`.
// It must decode as an unmodified binding, not fail and drop the map.
let json: String = #"""
{"switches":[],"ccs":[],"keys":[{"key":"b","action":{"rigBypass":{}}}]}
"""#
let data: Data = Data(json.utf8)
let decoded: MIDIMap = try JSONDecoder().decode(MIDIMap.self, from: data)
#expect(decoded.keys.count == 1)
#expect(decoded.keys.first?.key == "b")
#expect(decoded.keys.first?.modifiers == [])
}
@Test func mapWithoutKeysDecodesWithEmptyKeysNotDropped() throws {
// A rig saved before keyboard mapping existed has a midiMap with switches/ccs but no `keys`.
// It must decode with keys == [] AND keep its switch/cc bindings (a missing-key failure that
// fell through to the malformed path would silently drop the whole map).
let json: String = #"""
{"version":1,"boards":[],"midiMap":{"switches":[{"program":3,"action":{"rigBypass":{}}}],"ccs":[]}}
"""#
let data: Data = Data(json.utf8)
let decoded: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data)
#expect(decoded.midiMap?.keys == [], "absent keys should decode to an empty array")
#expect(decoded.midiMap?.switches.count == 1, "switch bindings must survive the missing keys")
#expect(decoded.midiMap?.switches.first?.program == 3)
}
}
@@ -0,0 +1,52 @@
// NoteDivisionTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable import LyrebirdShoeGaze
@Suite("NoteDivision")
struct NoteDivisionTests {
private let tolerance: Double = 1e-9
@Test func beatsMatchMusicalValues() {
#expect(NoteDivision.whole.beats == 4.0)
#expect(NoteDivision.dottedHalf.beats == 3.0)
#expect(NoteDivision.half.beats == 2.0)
#expect(NoteDivision.dottedQuarter.beats == 1.5)
#expect(NoteDivision.quarter.beats == 1.0)
#expect(abs(NoteDivision.quarterTriplet.beats - 2.0 / 3.0) < tolerance)
#expect(NoteDivision.dottedEighth.beats == 0.75)
#expect(NoteDivision.eighth.beats == 0.5)
#expect(abs(NoteDivision.eighthTriplet.beats - 1.0 / 3.0) < tolerance)
#expect(NoteDivision.sixteenth.beats == 0.25)
#expect(abs(NoteDivision.sixteenthTriplet.beats - 1.0 / 6.0) < tolerance)
}
@Test func dottedIsHalfAgainThePlainValue() {
#expect(NoteDivision.dottedQuarter.beats == NoteDivision.quarter.beats * 1.5)
#expect(NoteDivision.dottedEighth.beats == NoteDivision.eighth.beats * 1.5)
}
@Test func casesAreOrderedSlowToFast() {
let beats: [Double] = NoteDivision.allCases.map { $0.beats }
#expect(beats == beats.sorted(by: >), "cases must be ordered longest (slowest) first")
}
@Test func labelsAreUnique() {
let labels: [String] = NoteDivision.allCases.map { $0.label }
#expect(Set(labels).count == labels.count)
}
@Test func codableRoundTrips() throws {
for division: NoteDivision in NoteDivision.allCases {
let data: Data = try JSONEncoder().encode(division)
let decoded: NoteDivision = try JSONDecoder().decode(NoteDivision.self, from: data)
#expect(decoded == division)
}
}
}
@@ -0,0 +1,87 @@
// PedalMappingStripTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@testable import LyrebirdShoeGazeUI
@MainActor
@Suite("Pedal mapping strip")
struct PedalMappingStripTests {
/// Builds an engine + a one-board rig with a single Volume pedal, returning the pedal.
private func makePedal() throws -> (Pedal, ShoeGaze, URL) {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256)
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
try board.add(VolumePedal())
try sg.finalizeBoard(board)
guard let pedal: Pedal = board.pedals.first else {
throw ShoeGazeTestError.noPedal
}
return (pedal, sg, url)
}
private enum ShoeGazeTestError: Error { case noPedal }
@Test func emptyMapYieldsNoRows() throws {
let (pedal, sg, url): (Pedal, ShoeGaze, URL) = try makePedal()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
#expect(PedalMappingStrip.rows(for: pedal, in: nil).isEmpty)
#expect(PedalMappingStrip.rows(for: pedal, in: .empty).isEmpty)
}
}
@Test func ccAndBypassRowsBuiltFromMap() throws {
let (pedal, sg, url): (Pedal, ShoeGaze, URL) = try makePedal()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
#expect(pedal.ccMappableControls.isEmpty == false, "Volume exposes a CC-mappable control")
let controlLabel: String = pedal.ccMappableControls[0].label
let map: MIDIMap = MIDIMap(
switches: [MIDIMap.SwitchBinding(program: 4, action: .pedalBypass(pedalID: pedal.id))],
ccs: [MIDIMap.CCBinding(
controller: 11,
target: .pedalControl(
pedalID: pedal.id, controlIndex: 0,
pedalNameHint: nil, controlLabelHint: nil))],
keys: [MIDIMap.KeyBinding(key: "b", modifiers: [.shift],
action: .pedalBypass(pedalID: pedal.id))]
)
let rows: [PedalMappingRow] = PedalMappingStrip.rows(for: pedal, in: map)
#expect(rows.count == 2, "one CC control row + one bypass row")
let ccRow: PedalMappingRow? = rows.first { $0.label == controlLabel }
#expect(ccRow?.badges.map(\.text) == ["CC11"])
let bypassRow: PedalMappingRow? = rows.first { $0.label == "Bypass" }
#expect(bypassRow?.badges.map(\.text) == ["PC4", "⇧B"], "footswitch then key, shift glyph")
}
}
@Test func unmappedControlsProduceNoRows() throws {
let (pedal, sg, url): (Pedal, ShoeGaze, URL) = try makePedal()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
// A map that only binds a DIFFERENT pedal's control must not surface rows for this pedal.
let otherID: UUID = UUID()
let map: MIDIMap = MIDIMap(
ccs: [MIDIMap.CCBinding(
controller: 5,
target: .pedalControl(
pedalID: otherID, controlIndex: 0,
pedalNameHint: nil, controlLabelHint: nil))]
)
#expect(PedalMappingStrip.rows(for: pedal, in: map).isEmpty)
}
}
}
@@ -316,6 +316,138 @@ struct PresetTests {
#expect(abs(driveValue - 12.0) < 1e-9, "drive knob value should be 12.0, got \(driveValue)")
}
// MARK: - Tempo & input persistence
@Test func tempoAndInputSettingsRoundTripThroughFile() throws {
let (sg, _, url): (ShoeGaze, SynthesisEngine, URL) = try makeTwoBoardRig()
defer { try? FileManager.default.removeItem(at: url) }
let presetURL: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".json")
defer { try? FileManager.default.removeItem(at: presetURL) }
// Save a distinctive tempo + disabled tempo features (input stays on the test loop).
let savedBpm: Double = 132.0
sg.clock.bpm = savedBpm
sg.setTempoEnabled(false)
try sg.saveRig(to: presetURL)
// Drift the live values away from what was saved, then confirm the reload restores them.
sg.clock.bpm = 90.0
sg.setTempoEnabled(true)
try sg.loadRig(from: presetURL)
#expect(abs(sg.clock.bpm - savedBpm) < 1e-9, "bpm should restore to \(savedBpm)")
#expect(sg.tempoEnabled == false, "tempoEnabled should restore to false")
#expect(sg.inputSource == .testLoop, "input source should restore to test loop")
}
@Test func liveInputSourcePersistsAndFallsBackWhenChannelMissing() throws {
// Engine WITH an input channel: a live-input rig round-trips its source.
let (engineIn, urlIn): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.1,
numInputChannels: 1,
numAudioBuses: 128
)
defer { try? FileManager.default.removeItem(at: urlIn) }
let sgIn: ShoeGaze = ShoeGaze(engine: engineIn, inputSource: .liveInput(channel: 0))
let board: PedalBoard = try sgIn.addBoard()
try board.add(OverdrivePedal())
try sgIn.finalizeBoard(board)
let state: ShoeGazeState = sgIn.captureState()
#expect(state.inputSource == .liveInput(channel: 0), "capture should record the live input")
// Reload into the same input-capable engine: source preserved.
try sgIn.loadRig(from: state)
#expect(sgIn.inputSource == .liveInput(channel: 0), "live input should round-trip")
// loadRig does NOT auto-apply the saved channel layout, so loading into an engine with no
// input channels falls back to the test loop rather than clobbering the engine's config.
let (engineNoIn, urlNoIn): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.1,
numInputChannels: 0,
numAudioBuses: 128
)
defer { try? FileManager.default.removeItem(at: urlNoIn) }
let sgNoIn: ShoeGaze = ShoeGaze(engine: engineNoIn)
try sgNoIn.loadRig(from: state)
#expect(engineNoIn.numInputChannels == 0, "loadRig must not reconfigure the engine's I/O")
#expect(sgNoIn.inputSource == .testLoop, "missing channel should fall back to test loop")
}
@Test func channelCountsPersistButLoadDoesNotReconfigure() throws {
// Capture a rig on an engine with 1 input / 2 output channels: the counts are recorded and
// survive a JSON round-trip.
let (engineA, urlA): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.1,
numOutputChannels: 2,
numInputChannels: 1,
numAudioBuses: 128
)
defer { try? FileManager.default.removeItem(at: urlA) }
let sgA: ShoeGaze = ShoeGaze(engine: engineA)
let boardA: PedalBoard = try sgA.addBoard()
try boardA.add(OverdrivePedal())
try sgA.finalizeBoard(boardA)
let state: ShoeGazeState = sgA.captureState()
#expect(state.numInputChannels == 1)
#expect(state.numOutputChannels == 2)
let decoded: ShoeGazeState = try JSONDecoder().decode(
ShoeGazeState.self, from: JSONEncoder().encode(state)
)
#expect(decoded.numInputChannels == 1)
#expect(decoded.numOutputChannels == 2)
// Loading the rig must NOT reconfigure the destination engine's channel layout.
let (engineB, urlB): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.1,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 128
)
defer { try? FileManager.default.removeItem(at: urlB) }
let sgB: ShoeGaze = ShoeGaze(engine: engineB)
try sgB.loadRig(from: state)
#expect(engineB.numInputChannels == 0, "loadRig must leave engine I/O untouched")
}
@Test func applyChannelLayoutReconfiguresEngineToSavedCounts() throws {
// The deliberate opt-in DOES reconfigure the engine to a rig's saved channel layout.
let (engineA, urlA): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.1,
numOutputChannels: 2,
numInputChannels: 1,
numAudioBuses: 128
)
defer { try? FileManager.default.removeItem(at: urlA) }
let sgA: ShoeGaze = ShoeGaze(engine: engineA)
let boardA: PedalBoard = try sgA.addBoard()
try boardA.add(OverdrivePedal())
try sgA.finalizeBoard(boardA)
let state: ShoeGazeState = sgA.captureState()
let (engineB, urlB): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.1,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 128
)
defer { try? FileManager.default.removeItem(at: urlB) }
let sgB: ShoeGaze = ShoeGaze(engine: engineB)
try sgB.loadRig(from: state)
#expect(engineB.numInputChannels == 0, "load alone leaves I/O untouched")
let changed: Bool = try sgB.applyChannelLayout(from: state)
#expect(changed, "applyChannelLayout should report a change")
#expect(engineB.numInputChannels == 1, "opt-in apply reconfigures to the saved input count")
#expect(engineB.numOutputChannels == 2)
// Idempotent: applying again with matching counts is a no-op.
let changedAgain: Bool = try sgB.applyChannelLayout(from: state)
#expect(!changedAgain, "no reconfigure when counts already match")
}
// MARK: - Save / Load via temp file
@Test func saveRigAndLoadRigRestoresKnobValues() throws {
@@ -202,4 +202,138 @@ struct RigLibraryStoreTests {
#expect(store.entries.isEmpty)
store.flushPendingWrites()
}
// MARK: - Set-list ordering
@Test func newSavesAppendToSetListInSaveOrder() async throws {
let (store, dir): (RigLibraryStore, URL) = await makeStore()
defer { try? FileManager.default.removeItem(at: dir) }
// Save in reverse-alphabetical order; the set list keeps SAVE order, not name order.
try store.save(makeEntry("Zebra"))
try store.save(makeEntry("Alpha"))
#expect(store.entries.map(\.name) == ["Zebra", "Alpha"])
#expect(store.entries.map(\.sortIndex) == [0, 1])
store.flushPendingWrites()
}
@Test func moveUpMoveDownReorderAndPersistAcrossReload() 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"))
// A,B,C → move C up → A,C,B → move A down → C,A,B
guard let entryC: RigEntry = store.entries.first(where: { $0.name == "C" }) else {
Issue.record("missing C"); return
}
store.moveUp(entryC)
#expect(store.entries.map(\.name) == ["A", "C", "B"])
guard let entryA: RigEntry = store.entries.first(where: { $0.name == "A" }) else {
Issue.record("missing A"); return
}
store.moveDown(entryA)
#expect(store.entries.map(\.name) == ["C", "A", "B"])
#expect(store.entries.map(\.sortIndex) == [0, 1, 2])
// Order survives a fresh store over the same directory.
store.flushPendingWrites()
let reopened: RigLibraryStore = RigLibraryStore(directory: dir, isICloud: false)
await reopened.start()
#expect(reopened.entries.map(\.name) == ["C", "A", "B"])
}
@Test func moveFromOffsetsReordersAndRenumbers() 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"))
// SwiftUI List.onMove semantics: move the first row to the end.
store.move(fromOffsets: IndexSet(integer: 0), toOffset: 3)
#expect(store.entries.map(\.name) == ["B", "C", "A"])
#expect(store.entries.map(\.sortIndex) == [0, 1, 2])
store.flushPendingWrites()
}
@Test func applyOrderReordersAndRenumbers() 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"))
let byName: [String: UUID] = Dictionary(uniqueKeysWithValues: store.entries.map { ($0.name, $0.id) })
store.applyOrder([byName["C"], byName["A"], byName["B"]].compactMap { $0 })
#expect(store.entries.map(\.name) == ["C", "A", "B"])
#expect(store.entries.map(\.sortIndex) == [0, 1, 2])
store.flushPendingWrites()
}
@Test func renamePreservesSetListPosition() 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"))
let byName: [String: UUID] = Dictionary(uniqueKeysWithValues: store.entries.map { ($0.name, $0.id) })
store.applyOrder([byName["C"], byName["A"], byName["B"]].compactMap { $0 })
// Renaming the middle rig keeps its slot rather than re-sorting by the new name.
guard let entryA: RigEntry = store.entries.first(where: { $0.name == "A" }) else {
Issue.record("missing A"); return
}
_ = try store.rename(entryA, to: "Zzz")
#expect(store.entries.map(\.name) == ["C", "Zzz", "B"])
store.flushPendingWrites()
}
@Test func exportedArchiveCarriesSetListOrder() 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"))
let byName: [String: UUID] = Dictionary(uniqueKeysWithValues: store.entries.map { ($0.name, $0.id) })
store.applyOrder([byName["C"], byName["A"], byName["B"]].compactMap { $0 })
let archiveData: Data = try store.exportArchiveData()
// A fresh store importing the archive sees the same set-list order.
let (other, otherDir): (RigLibraryStore, URL) = await makeStore()
defer { try? FileManager.default.removeItem(at: otherDir) }
_ = try other.importArchive(from: archiveData)
#expect(other.entries.map(\.name) == ["C", "A", "B"])
store.flushPendingWrites()
other.flushPendingWrites()
}
@Test func importAppendsAfterExistingRigsWithoutInterleaving() async throws {
// Source archive with its own set-list order.
let (source, srcDir): (RigLibraryStore, URL) = await makeStore()
defer { try? FileManager.default.removeItem(at: srcDir) }
try source.save(makeEntry("Import1"))
try source.save(makeEntry("Import2"))
let archiveData: Data = try source.exportArchiveData()
// Destination already holds two placed rigs; the import must land AFTER them (append),
// not interleave by name/date on a colliding sortIndex.
let (dest, destDir): (RigLibraryStore, URL) = await makeStore()
defer { try? FileManager.default.removeItem(at: destDir) }
try dest.save(makeEntry("Existing1"))
try dest.save(makeEntry("Existing2"))
_ = try dest.importArchive(from: archiveData)
#expect(dest.entries.map(\.name) == ["Existing1", "Existing2", "Import1", "Import2"])
#expect(dest.entries.map(\.sortIndex) == [0, 1, 2, 3])
source.flushPendingWrites()
dest.flushPendingWrites()
}
}
@@ -0,0 +1,194 @@
// TempoSyncTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
@testable import LyrebirdShoeGaze
@MainActor
@Suite("Tempo sync")
struct TempoSyncTests {
/// A rig with a single `DelayPedal` on a finalized board, so the pedal has a real clock and
/// engine injected by `board.add(_:)`. Returns the session (kept alive for its clock), the
/// temp render URL, and the pedal.
private func makeRigWithDelay(bpm: Double = 120.0) throws -> (ShoeGaze, URL, DelayPedal) {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1)
let sg: ShoeGaze = ShoeGaze(engine: engine)
sg.clock.bpm = bpm
let board: PedalBoard = try sg.addBoard()
let delay: DelayPedal = DelayPedal()
try board.add(delay)
try sg.finalizeBoard(board)
return (sg, url, delay)
}
private let tolerance: Double = 1e-6
@Test func timeDivisionDerivesSecondsFromTempo() throws {
// `sg` owns the clock (the pedal holds it weakly), so it must outlive the assertions.
let (sg, url, delay): (ShoeGaze, URL, DelayPedal) = try makeRigWithDelay(bpm: 120.0)
defer { try? FileManager.default.removeItem(at: url) }
defer { withExtendedLifetime(sg) {} }
// 120 BPM → 0.5 s per beat. Eighth = 0.5 beat → 0.25 s.
delay.setSync(.division(.eighth), for: "time")
#expect(abs(delay.$time.value - 0.25) < tolerance)
// Quarter = 1 beat → 0.5 s.
delay.setSync(.division(.quarter), for: "time")
#expect(abs(delay.$time.value - 0.5) < tolerance)
}
@Test func freeParameterIsLeftUntouched() throws {
let (sg, url, delay): (ShoeGaze, URL, DelayPedal) = try makeRigWithDelay()
defer { try? FileManager.default.removeItem(at: url) }
defer { withExtendedLifetime(sg) {} }
let original: Double = delay.$time.value
delay.applyTempoSync() // nothing is synced → value unchanged
#expect(delay.$time.value == original)
}
@Test func longDivisionClampsToParameterRange() throws {
let (sg, url, delay): (ShoeGaze, URL, DelayPedal) = try makeRigWithDelay(bpm: 40.0)
defer { try? FileManager.default.removeItem(at: url) }
defer { withExtendedLifetime(sg) {} }
// Whole note at 40 BPM = 4 beats × 1.5 s = 6.0 s, past the Delay's 5.0 s maximum.
delay.setSync(.division(.whole), for: "time")
#expect(abs(delay.$time.value - 5.0) < tolerance, "synced value must clamp to the time range")
}
@Test func valueReportsWhenADivisionClamps() throws {
let delay: DelayPedal = DelayPedal()
let param: TempoSyncableParam = try #require(delay.tempoSyncableParams.first)
// Fits within [0.01, 5.0]: quarter @ 120 BPM = 0.5 s, not clamped.
let quarter: (value: Double, clamped: Bool) = param.value(for: .quarter, bpm: 120.0)
#expect(abs(quarter.value - 0.5) < tolerance)
#expect(!quarter.clamped)
// Whole @ 40 BPM = 6.0 s, past the 5.0 s max → clamped and flagged.
let whole: (value: Double, clamped: Bool) = param.value(for: .whole, bpm: 40.0)
#expect(abs(whole.value - 5.0) < tolerance)
#expect(whole.clamped)
}
@Test func setBpmBroadcastsToSyncedParameters() throws {
let (sg, url, delay): (ShoeGaze, URL, DelayPedal) = try makeRigWithDelay(bpm: 120.0)
defer { try? FileManager.default.removeItem(at: url) }
delay.setSync(.division(.quarter), for: "time")
#expect(abs(delay.$time.value - 0.5) < tolerance) // quarter @ 120 BPM
// Halving the tempo doubles a beat's length → quarter now 1.0 s.
sg.setBpm(60.0)
#expect(abs(delay.$time.value - 1.0) < tolerance, "setBpm must recompute synced parameters")
}
@Test func rateParameterUsesInverseOfPeriod() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1)
defer { try? FileManager.default.removeItem(at: url) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
sg.clock.bpm = 120.0
let board: PedalBoard = try sg.addBoard()
let tremolo: TremoloPedal = TremoloPedal()
try board.add(tremolo)
try sg.finalizeBoard(board)
defer { withExtendedLifetime(sg) {} }
// 120 BPM → 0.5 s per beat. A quarter-note LFO = one cycle per 0.5 s → 2 Hz.
tremolo.setSync(.division(.quarter), for: "rate")
#expect(abs(tremolo.$rate.value - 2.0) < tolerance)
// Eighth = 0.25 s period → 4 Hz.
tremolo.setSync(.division(.eighth), for: "rate")
#expect(abs(tremolo.$rate.value - 4.0) < tolerance)
}
@Test func multiTapSyncsEachTapIndependently() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1)
defer { try? FileManager.default.removeItem(at: url) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
sg.clock.bpm = 120.0
let board: PedalBoard = try sg.addBoard()
let multiTap: MultiTapDelayPedal = MultiTapDelayPedal()
try board.add(multiTap)
try sg.finalizeBoard(board)
defer { withExtendedLifetime(sg) {} }
let freeTime3: Double = multiTap.$time3.value
multiTap.setSync(.division(.quarter), for: "time1") // 0.5 s
multiTap.setSync(.division(.eighth), for: "time2") // 0.25 s
#expect(abs(multiTap.$time1.value - 0.5) < tolerance)
#expect(abs(multiTap.$time2.value - 0.25) < tolerance)
#expect(multiTap.$time3.value == freeTime3, "an unsynced tap is left free")
}
@Test func lightweightRecallRecomputesSyncedValuesAtCurrentTempo() throws {
let (sg, url, delay): (ShoeGaze, URL, DelayPedal) = try makeRigWithDelay(bpm: 120.0)
defer { try? FileManager.default.removeItem(at: url) }
defer { withExtendedLifetime(sg) {} }
delay.setSync(.division(.quarter), for: "time")
#expect(abs(delay.$time.value - 0.5) < tolerance) // quarter @ 120 BPM
// Capture at 120 BPM (time = 0.5 s), then change tempo so a recall must recompute.
let snapshot: ShoeGazeState = sg.captureState()
sg.setBpm(60.0)
#expect(abs(delay.$time.value - 1.0) < tolerance) // quarter @ 60 BPM
// Recall the 120-BPM snapshot onto the (now 60-BPM) rig. The restored division must be
// recomputed against the current tempo — 1.0 s — not left at the captured 0.5 s.
sg.applyState(snapshot)
#expect(delay.tempoSync["time"] == .division(.quarter))
#expect(abs(delay.$time.value - 1.0) < tolerance, "recall must recompute synced values at the current tempo")
}
@Test func syncStatePersistsThroughCaptureAndApply() throws {
let delay: DelayPedal = DelayPedal()
delay.setSync(.division(.dottedEighth), for: "time")
let data: Data = try JSONEncoder().encode(delay.captureState())
let restored: PedalState = try JSONDecoder().decode(PedalState.self, from: data)
let rebuilt: DelayPedal = DelayPedal()
rebuilt.applyState(restored)
#expect(rebuilt.tempoSync["time"] == .division(.dottedEighth))
}
@Test func presetWithoutTempoSyncDecodesToFree() throws {
// A rig saved before tempo sync has no `tempoSync` key — it must decode to "all free".
let legacy: String = """
{"type":"Delay","knobValues":[0.25,1.0,0.35,1.0],"bypass":0.0}
"""
let state: PedalState = try JSONDecoder().decode(PedalState.self, from: Data(legacy.utf8))
#expect(state.tempoSync == nil)
let delay: DelayPedal = DelayPedal()
delay.applyState(state)
#expect(delay.tempoSync.isEmpty, "a legacy preset leaves every parameter free")
}
@Test func disablingTempoStopsRecompute() throws {
let (sg, url, delay): (ShoeGaze, URL, DelayPedal) = try makeRigWithDelay(bpm: 120.0)
defer { try? FileManager.default.removeItem(at: url) }
delay.setSync(.division(.quarter), for: "time")
let syncedValue: Double = delay.$time.value // 0.5 s
sg.setTempoEnabled(false)
sg.setBpm(60.0) // tempo disabled → no recompute
#expect(delay.$time.value == syncedValue, "a disabled tempo must not drive synced parameters")
// Re-enabling re-syncs to the current (60 BPM) tempo → quarter = 1.0 s.
sg.setTempoEnabled(true)
#expect(abs(delay.$time.value - 1.0) < tolerance)
}
}
@@ -0,0 +1,99 @@
# Keyboard control mapping + unified mapping sheet
Bind computer letter keys to the same rig actions MIDI footswitches drive, and rework the
MIDI mapping sheet so each rig action shows **all** of its trigger sources (footswitch,
expression pedal, letter key) on one row.
## Goals
- A letter key (e.g. `b`) can toggle rig bypass / mute, a board solo/bypass, a pedal bypass,
a looper transport action, the tuner, or tap tempo — exactly the toggle actions a
Program-Change footswitch already drives.
- Keys fire **only** when no text field is focused (rig rename, board label). Typing a rig
name must never trip a bypass.
- One mapping sheet row per action, showing its PC chip, KEY chip, and per-source learn.
- Keys persist with the rig (travel in `ShoeGazeState`), like MIDI bindings.
- macOS + iOS hardware keyboard.
## Non-goals
- Keys driving continuous CC targets (knobs / levels). Keys are momentary → toggle actions
only. CC rows in the sheet are unchanged.
- `⌘`-modified bindings. Shift / Control / Option qualify a key binding (`a` vs `⇧a` vs `⌃a`),
but Command is reserved for the existing menu `⌘`-shortcuts and is never bindable.
## Design
Reuse the existing controller. `MIDIController` already owns the shared `perform(_:)` action
dispatch, the `learnTarget` state, the weak `shoeGaze`, and `onMapChanged`. Key learn and key
apply reuse all of it — a separate controller would duplicate that. Key **event capture** is
the only platform piece and lives in the UI module (SwiftUI `.onKeyPress`), per the module
layering rule; the controller exposes a pure `ingestKey` entry point that the UI calls.
### Model — `MIDIMap`
Add a third binding list beside `switches` / `ccs`:
```swift
public var keys: [KeyBinding]
public struct KeyBinding: Codable, Equatable, Sendable {
public var key: String // single lowercased character
public var action: Action
public var displayNameHint: String?
}
```
`MIDIMap` gains a custom `init(from:)` that decodes `keys` with `decodeIfPresent ?? []`, so a
rig saved before this feature (a `midiMap` with `switches`/`ccs` but no `keys`) still decodes
— without it, synthesized Codable would fail the whole map and `ShoeGazeState` would silently
drop existing MIDI bindings. `encode(to:)` stays synthesized.
### Controller — `MIDIController`
- `LearnTarget` gains `.key(MIDIMap.Action)`.
- `armKeyLearn(_ action:)`, `keyBinding(for:)`, `clearKeyBinding(for:)` — mirror the switch API.
- `ingestKey(_ key: String) -> Bool` — if armed for key learn, capture + clear learn; else run
every action bound to that key via the shared `perform(_:)`. Returns `true` when the key was
consumed (learned or matched a binding) so the UI can swallow the event; `false` lets the key
fall through. Normalizes to a single lowercased letter/digit (non-printing keys rejected).
`ingestKey` is `public` (no DEBUG gate needed — unlike MIDI messages there is no background-queue
hop to bypass, so tests call it directly).
### UI capture — `ShoeGazeBuilderView`
Attach a focus-gated `.onKeyPress(phases: .down)` on the builder root. Handler:
- Ignores repeats (hold = one toggle) and anything with command/control/option modifiers.
- Extracts the single character, calls `controller.ingestKey`.
- Returns `.handled` when consumed, else `.ignored`.
Focus gate: a focused `TextField` consumes keys first via the responder chain, so a root
`.onKeyPress` never sees them while the user types. Sheets (rig rename, board editor) present
their own text fields and take focus. No extra `@FocusState` plumbing needed for v1.
### UI sheet — `MIDIMappingSheet`
Switch rows gain a KEY chip (showing the bound letter, or nothing) and a keyboard-learn button
beside the existing footswitch learn. Armed key-learn shows "Listening — press a key…". CC rows
unchanged. Learn buttons: piano icon = MIDI learn, keyboard icon = key learn.
## Files
| File | Change |
|---|---|
| `Sources/LyrebirdShoeGaze/MIDI/MIDIMap.swift` | `KeyBinding` type, `keys` array, custom `init(from:)`. |
| `Sources/LyrebirdShoeGaze/MIDI/MIDIController.swift` | `.key` learn target, key learn/apply API, `ingestKey`. |
| `Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift` | focus-gated `.onKeyPress` root modifier. |
| `Sources/LyrebirdShoeGazeUI/MIDIMappingSheet.swift` | KEY chip + keyboard-learn on switch rows. |
| `Tests/LyrebirdShoeGazeTests/MIDIMapCodableTests.swift` | `keys` round-trip + old-rig (no `keys`) decode. |
| `Tests/LyrebirdShoeGazeTests/MIDIControllerKeyTests.swift` | key learn / apply / clear / latch. |
## Test plan
- `MIDIMap` with `keys` encodes + decodes equal; a `midiMap` JSON lacking `keys` decodes with
`keys == []` and its `switches`/`ccs` intact.
- `armKeyLearn` + `ingestKey("b")` captures a `KeyBinding`, clears learn, fires `onMapChanged`,
does not perform the action on the learn press.
- A subsequent `ingestKey("b")` latches the action (e.g. rig bypass on/off).
- `ingestKey` returns `false` for an unbound key; `clearKeyBinding` removes it.
- Case/whitespace normalization: `ingestKey("B")` matches a binding learned as `b`.
+221
View File
@@ -0,0 +1,221 @@
# Tempo-synced pedal parameters
Let a time- or rate-based pedal parameter be locked to a **note division of the live
tempo** (quarter, dotted-eighth, eighth-triplet, …) instead of an absolute value. A delay
time set to "quarter note" tracks the shared clock; change BPM (stepper, tap, MIDI) and the
echo follows. Setting stays "free" (absolute seconds / Hz, as today) unless the user opts a
param into sync.
## Goals
- Any delay **time** param can be marked as a note division; its seconds are derived from
`clock.bpm`.
- Any modulation **rate** param (LFO Hz) can be marked as a note division; its frequency is
the inverse of the synced period (a "quarter-note" LFO = one cycle per quarter note).
- MultiTapDelay's three tap times each sync independently to their own division.
- Sync state travels with the rig (persists in `PedalState`), decoded leniently so older
rigs still load.
- Gated on the existing `tempoEnabled` flag — when tempo is off, sync affordances hide and
synced params fall back to their stored absolute value.
- macOS + iOS.
## Non-goals
- Sample-accurate tempo-ramp tracking (Option B, a clock-backed core Generator). BPM here
changes only at discrete events — stepper, tap, MIDI — so a recompute-on-change ("Push")
model loses nothing. The state format is designed so a Pull generator can back it later
without a migration.
- Syncing envelope- or expression-driven params (AutoWah, Mutant, Wah) — no fixed rate.
- Syncing Rotary `speed` — bimodal slow/fast horn, not a free rate.
- Auto-extending delay buffers to fit long divisions. Buffers are sized at init; a division
whose period exceeds a param's range is **clamped** to the range.
## Which params
**Time family** (synced value = period `T`):
| Pedal | param(s) |
|---|---|
| DelayPedal | `time` |
| FeedbackDelayPedal | `time` |
| PingPongDelayPedal | `time` |
| ReverseDelayPedal | `time` |
| MultiTapDelayPedal | `time1`, `time2`, `time3` |
**Rate family** (synced value = `1/T`, Hz):
| Pedal | param |
|---|---|
| TremoloPedal | `rate` |
| VibratoPedal | `rate` |
| ChorusPedal | `rate` |
| FlangerPedal | `rate` |
| PhaserPedal | `rate` |
| ModulationPedal | `rate` |
## Design
Approach: **Push / recompute-on-change**. When a param is synced, its `@UIParam` value is
recomputed and written whenever BPM or the chosen division changes. Generators are untouched
— they keep reading `$time` / `$rate` exactly as now. Writing a `@UIParam` from the main
thread is identical to a knob turn, so there is no RT concern.
Synced period, given beats-per-division `d` and tempo `bpm`:
```
T = (60 / bpm) * d // seconds
value = kind == .rate ? 1 / T : T
value = min(max(value, range.lowerBound), range.upperBound) // clamp
```
### Core types — new files in `Sources/LyrebirdShoeGaze/Tempo/`
One public type per file (repo rule).
`NoteDivision.swift`:
```swift
public enum NoteDivision: String, Codable, CaseIterable, Sendable {
case whole, dottedHalf, half, dottedQuarter, quarter, quarterTriplet
case dottedEighth, eighth, eighthTriplet, sixteenth, sixteenthTriplet
/// Beats (quarter-note = 1) this division spans.
public var beats: Double { ... } // whole = 4, quarter = 1, eighth = 0.5,
// dottedEighth = 0.75, eighthTriplet = 1/3, ...
public var label: String { ... } // "1/4", "1/8.", "1/8T", ...
}
```
`TempoSync.swift`:
```swift
public enum TempoSync: Codable, Equatable, Sendable {
case free
case division(NoteDivision)
}
```
`TempoSyncableParam.swift` — descriptor a pedal publishes, one per syncable param:
```swift
public struct TempoSyncableParam {
public enum Kind { case time, rate } // rate ⇒ inverse (Hz = 1/T)
public let key: String // stable id, persistence key (e.g. "time", "time1")
public let label: String
public let node: UIParamNode
public let kind: Kind
public let range: ClosedRange<Double>
}
```
### `Pedal` base additions
```swift
/// Params this pedal exposes to tempo sync. Empty for pedals that can't sync.
open var tempoSyncableParams: [TempoSyncableParam] { [] }
/// Per-param sync state, keyed by TempoSyncableParam.key. Default .free.
public internal(set) var tempoSync: [String: TempoSync] = [:]
/// Recompute + write every synced param from the current clock BPM. Main-thread only.
public func applyTempoSync() { ... } // no-op when no clock, or tempo disabled
/// Set one param's sync state and immediately recompute it.
public func setSync(_ sync: TempoSync, for key: String) { ... }
```
`applyTempoSync()` iterates `tempoSyncableParams`, looks up each key's state, and for a
`.division` writes the clamped `T` (or `1/T`). `.free` leaves the param at its stored value.
Each candidate pedal overrides `tempoSyncableParams` — e.g. DelayPedal:
```swift
public override var tempoSyncableParams: [TempoSyncableParam] {
[TempoSyncableParam(key: "time", label: "Time", node: $time, kind: .time, range: timeRange)]
}
```
### `ShoeGaze` broadcast — the Push trigger
BPM is currently mutated in three places that set `clock.bpm` directly (TempoView stepper,
`tapTempo()`, MIDI). Funnel them through one entry point:
```swift
public func setBpm(_ bpm: Double) {
clock.bpm = bpm
board.forEachPedal { $0.applyTempoSync() }
}
```
- `TempoView` stepper `set:` → `shoeGaze.setBpm(clamped)` (was `clock.bpm = clamped`).
- `tapTempo()` → compute then `setBpm(...)` (was `clock.bpm = ...`).
- MIDI tempo path → `setBpm`.
- Rig load (BPM restored from `ShoeGazeState`) → call `applyTempoSync()` across the board
after the clock is set, so restored synced params match the loaded tempo.
- `setTempoEnabled(false)` → params keep their last absolute value (no recompute); re-enable
→ `applyTempoSync()`.
(If `board.forEachPedal` doesn't exist, add a thin iterator over the board's pedals.)
### Persistence — `PedalState`
Add one field, decoded leniently (same pattern the tempo/BPM fields already use):
```swift
public let tempoSync: [String: TempoSync]? // param key → sync state; nil for old rigs
```
Custom `init(from:)` decodes with `decodeIfPresent`; absent ⇒ `nil` ⇒ all params `.free`.
`Pedal+Preset` captures `pedal.tempoSync` on save and restores it on load, then calls
`applyTempoSync()` so values line up with the rig's restored BPM.
### UI — `PedalView`
For each param that appears in `tempoSyncableParams`:
- Show a small **Sync** toggle beside/under the knob.
- Sync **off** → render the existing `PedalKnob` rotary, unchanged.
- Sync **on** → replace the rotary with a `PedalSelectorKnob` (already exists: a knob that
snaps to labelled stops) bound to the `NoteDivision` list; changing it calls
`pedal.setSync(.division(sel), for: key)`.
- Gate the whole affordance on the `shoeGazeTempoEnabled` environment flag — when tempo is
off, only the plain knob shows.
### MIDI — implemented (inert while synced)
A synced param's value is derived, so a CC bound to it would be overwritten on the next
tempo/division change. Rather than drop `.division`-synced params from `ccMappableControls` —
which is addressed by a *stable index* (persisted CC bindings resolve by position), so filtering it
live would shift indices and break existing bindings — the exclusion is **index-stable**: the slot
stays, and the CC *write* is skipped while the target parameter is division-synced.
`MIDIController.applyCC` checks `Pedal.isNodeTempoSynced(_:)` (node-identity match against
`tempoSyncableParams`) and ignores the incoming CC for a synced control; the binding stays intact and
resumes control the moment the parameter is set back to Free. Learning/binding a CC to a synced
param is still allowed — the tempo simply wins while synced.
## Testing
One `@Suite` per file (repo rule):
- `NoteDivisionTests` — `beats` values (whole = 4, quarter = 1, dottedEighth = 0.75,
eighthTriplet ≈ 0.3333, …) and `label`s.
- `TempoSyncTests` — `applyTempoSync` for a `.time` param (period), a `.rate` param
(inverse), and range-clamp (whole note @ 60 BPM = 4 s clamps to Delay's 1.5 s max).
- `ShoeGazeTempoBroadcastTests` — `setBpm` recomputes a synced param across the board;
changing division recomputes; `.free` params untouched.
- `PedalStatePersistenceTests` (extend existing) — `tempoSync` round-trips; a rig saved
without the field decodes to all-`.free`.
## Build order
Vertical slice first to validate the whole path end to end, then fan out:
1. Core types (`NoteDivision`, `TempoSync`, `TempoSyncableParam`).
2. `Pedal` hooks (`tempoSyncableParams`, `tempoSync`, `applyTempoSync`, `setSync`).
3. `ShoeGaze.setBpm` broadcast + reroute the three BPM writers + rig-load hook.
4. **DelayPedal** override + its `PedalView` sync UI.
5. Tests for 1–4.
6. Persistence (`PedalState.tempoSync`, `Pedal+Preset`).
7. Fan out to the remaining delays, then the modulation (rate) pedals, then MultiTap's
three taps.
8. `lyrebird_external_review` (ShoeGaze is out-of-tree) before merge.
+4 -6
View File
@@ -197,10 +197,8 @@ are the case names — renames are a format break. Wideners and stereo-native pe
(`OctaveUpSplitterPedal` "Octave Splitter", `PingPongDelayPedal` "Ping-Pong") are registered in
`PedalRegistry`. Unknown pedal types are skipped on load, including inside branches.
The macOS Demo app has a `.stereo` mode (`ShoeGazeDemoController.buildStereo()` +
`DemoRootView.stereoContent`): Overdrive → `splitStereo(Delay | Ping-Pong)` → `collectStereo`,
with the four route modes selectable live.
The Builder app composes stereo chains directly from the palette — e.g. Overdrive →
`splitStereo(Delay | Ping-Pong)` → `collectStereo`, with the four route modes selectable live.
Deferred (follow-up): an iOS demo showcase (the iOS demo app has no mode switcher); rendering
the board's `orderedSegments` directly in a generic board view (today the UI composes pedal
rows and section views separately).
Deferred (follow-up): rendering the board's `orderedSegments` directly in a generic board view
(today the UI composes pedal rows and section views separately).