Files
ShoeGaze/Sources/LyrebirdShoeGaze/Presets/ShoeGazeState.swift
T
josh 44e6c35550 fix(rigs): don't flag a rig dirty over input/channel differences
Switching between starter rigs prompted "save changes?" even when nothing
was edited. The unsaved-changes check compared full ShoeGazeState snapshots
(`captureState() != entry.state`), which include the live input source and
engine channel counts — and those legitimately differ from a factory rig's
saved values now that a rig switch preserves the player's current input
instead of adopting the rig's saved one.

Add ShoeGazeState.hasSameRigContent(as:) comparing only rig content (boards,
routers, MIDI map, tempo) and use it for the dirty check, so session/engine
settings no longer register as unsaved changes. Test added.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-10 16:40:35 -07:00

160 lines
7.9 KiB
Swift

// 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]?
/// 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
) {
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
}
private enum CodingKeys: String, CodingKey {
case version
case boards
case midiMap
case bpm
case tempoEnabled
case inputSource
case numInputChannels
case numOutputChannels
case routers
}
/// 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<CodingKeys> = 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)
}
/// 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
}
}