Decode midiMap resiliently so a bad map can't drop the whole rig
Root cause of the "highlight right, wrong graph" restart: the autosave held a midiMap written by an older binding schema (CCTarget was a struct before it became an enum). Decoding threw, loadRig threw, RigStore.restore failed, and the app fell back to seeding a single default board — so the graph showed Default while the highlight (correctly) showed the loaded rig. ShoeGazeState now decodes midiMap with try?, so an unreadable/incompatible map drops just the (re-learnable) bindings while version + boards decode strictly. The rig survives. Test: a malformed midiMap decodes to nil without throwing. 324 green; both app targets build. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -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<CodingKeys> = 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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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":[]}"#
|
||||
|
||||
Reference in New Issue
Block a user