diff --git a/Sources/LyrebirdShoeGaze/Presets/ShoeGazeState.swift b/Sources/LyrebirdShoeGaze/Presets/ShoeGazeState.swift index 030397c..c597a3d 100644 --- a/Sources/LyrebirdShoeGaze/Presets/ShoeGazeState.swift +++ b/Sources/LyrebirdShoeGaze/Presets/ShoeGazeState.swift @@ -49,4 +49,22 @@ public struct ShoeGazeState: Codable, Equatable { self.boards = boards self.midiMap = midiMap } + + private enum CodingKeys: String, CodingKey { + case version + case boards + case midiMap + } + + /// Decodes a rig snapshot, tolerating an absent OR malformed `midiMap`. + /// + /// The MIDI map is decoded with `try?` so a binding format that this build can't read (e.g. an + /// autosave written by an older schema) drops just the bindings — which are re-learnable — + /// rather than throwing and losing the entire 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) + self.boards = try container.decode([BoardState].self, forKey: .boards) + self.midiMap = try? container.decodeIfPresent(MIDIMap.self, forKey: .midiMap) ?? nil + } } diff --git a/Tests/LyrebirdShoeGazeTests/MIDIMapCodableTests.swift b/Tests/LyrebirdShoeGazeTests/MIDIMapCodableTests.swift index 82eab31..c09dec6 100644 --- a/Tests/LyrebirdShoeGazeTests/MIDIMapCodableTests.swift +++ b/Tests/LyrebirdShoeGazeTests/MIDIMapCodableTests.swift @@ -50,6 +50,16 @@ struct MIDIMapCodableTests { #expect(decoded.midiMap == sampleMap()) } + @Test func malformedMidiMapDropsBindingsNotTheRig() throws { + // A midiMap in a shape this build can't read (e.g. an older binding schema) must NOT throw + // and lose the whole rig — it drops just the (re-learnable) bindings. + let json: String = #"{"version":1,"boards":[],"midiMap":{"switches":"not-an-array","ccs":42}}"# + let data: Data = Data(json.utf8) + let decoded: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data) + #expect(decoded.midiMap == nil, "an unreadable midiMap should decode to nil, not throw") + #expect(decoded.version == 1) + } + @Test func oldRigWithoutMapDecodesToNil() throws { // A rig saved before MIDI mapping existed has no `midiMap` key at all. let legacyJSON: String = #"{"version":1,"boards":[]}"#