Files
ShoeGaze/Tests/LyrebirdShoeGazeTests/MIDIMapCodableTests.swift
T
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

132 lines
6.1 KiB
Swift

// MIDIMapCodableTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable import LyrebirdShoeGaze
@MainActor
@Suite("MIDIMap persistence")
struct MIDIMapCodableTests {
// Fixed ids so the round-trip comparison is deterministic.
private static let boardID: UUID = UUID()
private static let looperID: UUID = UUID()
private static let volumeID: UUID = UUID()
private func sampleMap() -> MIDIMap {
MIDIMap(
switches: [
MIDIMap.SwitchBinding(program: 3, channel: 0, action: .rigBypass, displayNameHint: "Rig"),
MIDIMap.SwitchBinding(program: 4, action: .boardSolo(boardID: Self.boardID), displayNameHint: "Board 2"),
MIDIMap.SwitchBinding(program: 5, action: .tunerToggle),
MIDIMap.SwitchBinding(program: 6, action: .tapTempo),
MIDIMap.SwitchBinding(
program: 7,
action: .pedalAction(pedalID: Self.looperID, kind: .looperRecordStop),
displayNameHint: "Looper"
),
],
ccs: [
MIDIMap.CCBinding(
controller: 7,
channel: 0,
target: .pedalControl(
pedalID: Self.volumeID, controlIndex: 0,
pedalNameHint: "Volume", controlLabelHint: "Position"
)
),
MIDIMap.CCBinding(
controller: 11,
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"
),
]
)
}
@Test func mapRoundTrips() throws {
let map: MIDIMap = sampleMap()
let data: Data = try JSONEncoder().encode(map)
let decoded: MIDIMap = try JSONDecoder().decode(MIDIMap.self, from: data)
#expect(decoded == map)
}
@Test func rigStateEmbedsAndRestoresMap() throws {
let state: ShoeGazeState = ShoeGazeState(boards: [], midiMap: sampleMap())
let data: Data = try JSONEncoder().encode(state)
let decoded: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data)
#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":[]}"#
let data: Data = Data(legacyJSON.utf8)
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)
}
}