// ShoeGazeState.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT /// Format version written into every saved preset file. /// /// Increment this constant when the `ShoeGazeState` schema changes in a way that /// requires migration logic on load. public let presetFormatVersion: Int = 1 /// Serialisable snapshot of an entire `ShoeGaze` rig — all boards and their pedals. /// /// Use `ShoeGaze.saveRig(to:)` to write and `ShoeGaze.loadRig(from:)` to restore. /// The `version` field allows future migrations: loaders that read a file with a /// higher `version` than `presetFormatVersion` should reject or warn, while loaders /// reading older versions may apply forward-compatibility mappings. /// /// Unknown pedal types encountered during load are silently skipped so presets made /// with custom third-party pedals degrade gracefully on systems without those pedals. public struct ShoeGazeState: Codable, Equatable { /// Preset format version. Written as `presetFormatVersion` at save time. public let version: Int /// All board snapshots in the order they were created. public let boards: [BoardState] /// The rig's MIDI foot-controller bindings, or `nil` for a rig saved without any. /// /// Optional so rigs written before MIDI mapping existed decode cleanly (the synthesized /// `init(from:)` uses `decodeIfPresent`, yielding `nil` for the missing key) — no format /// 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? /// The rig's chain routers (two-board split/blend units), or `nil` for a rig saved before router /// persistence existed. Additive: decoded with `decodeIfPresent`, so older rigs — which never had /// routers — decode cleanly to `nil` without a format-version bump. public let routers: [ChainRouterState]? /// The rig's pre-board chain — pedals that process the input once, before the board split, and /// feed every board — or `nil` for a rig saved before the pre-board stage existed. Additive: /// decoded with `decodeIfPresent`, so older rigs decode cleanly to `nil` without a format bump. public let preChain: [PedalState]? /// The rig's post-board chain — pedals that process the summed board mix, after the split, before /// the hardware output (global reverb, bus limiter, …) — or `nil` for a rig saved before the /// post-board stage existed. Additive: decoded with `decodeIfPresent`. public let postChain: [PedalState]? /// 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`. /// - routers: The rig's chain routers, or `nil` when there are none. Defaults to `nil`. public init( version: Int = presetFormatVersion, boards: [BoardState], midiMap: MIDIMap? = nil, bpm: Double? = nil, tempoEnabled: Bool? = nil, inputSource: InputSource? = nil, numInputChannels: Int? = nil, numOutputChannels: Int? = nil, routers: [ChainRouterState]? = nil, preChain: [PedalState]? = nil, postChain: [PedalState]? = 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 self.routers = routers self.preChain = preChain self.postChain = postChain } private enum CodingKeys: String, CodingKey { case version case boards case midiMap case bpm case tempoEnabled case inputSource case numInputChannels case numOutputChannels case routers case preChain case postChain } /// Decodes a rig snapshot, tolerating an absent, malformed, OR legacy-format `midiMap`. /// /// The MIDI map is decoded in three tiers: (1) the current id-based ``MIDIMap``; (2) failing /// that, the pre-UUID positional ``LegacyMIDIMap``, migrated to id-based via the boards' /// freshly-decoded ids so old rigs keep their bindings; (3) failing both (absent or unreadable), /// `nil` — dropping just the bindings, which are re-learnable, rather than losing the whole rig. /// `version` and `boards` still decode strictly. public init(from decoder: Decoder) throws { let container: KeyedDecodingContainer = try decoder.container(keyedBy: CodingKeys.self) self.version = try container.decode(Int.self, forKey: .version) let decodedBoards: [BoardState] = try container.decode([BoardState].self, forKey: .boards) self.boards = decodedBoards if !container.contains(.midiMap) { self.midiMap = nil } else if let current: MIDIMap = try? container.decode(MIDIMap.self, forKey: .midiMap) { self.midiMap = current } else if let legacy: LegacyMIDIMap = try? container.decode(LegacyMIDIMap.self, forKey: .midiMap) { // Pre-UUID positional map: convert each binding to the id now at that position. self.midiMap = legacy.migrated(boards: decodedBoards) } 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) self.routers = try container.decodeIfPresent([ChainRouterState].self, forKey: .routers) self.preChain = try container.decodeIfPresent([PedalState].self, forKey: .preChain) self.postChain = try container.decodeIfPresent([PedalState].self, forKey: .postChain) } /// Whether two snapshots describe the same **rig** — its boards, routers, MIDI map, and tempo — /// ignoring live session settings that are not part of the recalled rig: the input source and the /// engine's channel counts. /// /// Use this for unsaved-changes detection. Those session fields are deliberately not applied when /// switching rigs (see ``ShoeGaze/loadRig(from:keepingCurrentInput:)``), so a plain `==` would /// report a freshly-loaded rig as "changed" merely because the player's current input differs from /// the input the rig was saved with — producing a spurious "save changes?" prompt. public func hasSameRigContent(as other: ShoeGazeState) -> Bool { boards == other.boards && routers == other.routers && midiMap == other.midiMap && bpm == other.bpm && tempoEnabled == other.tempoEnabled && preChain == other.preChain && postChain == other.postChain } /// Returns a copy of this snapshot with its `preChain` replaced. Used by the pre-board edit path /// to force the just-mutated intended chain (rather than a re-read of the still-live pre-pedals). public func withPreChain(_ preChain: [PedalState]?) -> ShoeGazeState { ShoeGazeState( version: version, boards: boards, midiMap: midiMap, bpm: bpm, tempoEnabled: tempoEnabled, inputSource: inputSource, numInputChannels: numInputChannels, numOutputChannels: numOutputChannels, routers: routers, preChain: preChain, postChain: postChain ) } /// Returns a copy with its `postChain` replaced. Post-board edit counterpart of ``withPreChain(_:)``. public func withPostChain(_ postChain: [PedalState]?) -> ShoeGazeState { ShoeGazeState( version: version, boards: boards, midiMap: midiMap, bpm: bpm, tempoEnabled: tempoEnabled, inputSource: inputSource, numInputChannels: numInputChannels, numOutputChannels: numOutputChannels, routers: routers, preChain: preChain, postChain: postChain ) } }