From 6688718bed340c05890a0dc8f916f70c59ce01f5 Mon Sep 17 00:00:00 2001 From: Reactorcoremeltdown Date: Mon, 16 Nov 2026 16:31:46 +0100 Subject: [PATCH] 0.39.0 (73): export and import MIDI mappings as .szm text (Android and iOS) - SIZZLE-MIDIMAP 1 format: TYPE, NAME, one parameter=CC line each - core/src/io/MidiMapIo (iOS) and io/MidiMapIo.kt (Android), tested on one shared fixture (midimap_test, MidiMapIoTest) - EXPORT / IMPORT in each device's MIDI learn panel on both platforms - Params::remove; iOS clears a mapping by removing it - ios/Makefile regenerates the Xcode project when source folders change Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 ++ .../android/sizzle/io/MidiMapIo.kt | 99 +++++++++++++++++++ .../android/sizzle/ui/AppViewModel.kt | 29 ++++++ .../sizzle/ui/toolbox/ToolboxScreen.kt | 43 +++++++- .../android/sizzle/io/MidiMapIoTest.kt | 46 +++++++++ app/src/test/resources/midimap/filter.szm | 13 +++ core/include/sizzle/Params.hpp | 2 + core/src/Params.cpp | 12 +++ core/src/io/MidiMapIo.cpp | 97 ++++++++++++++++++ core/src/io/MidiMapIo.hpp | 52 ++++++++++ core/tests/midimap_test.cpp | 52 ++++++++++ docs/DEVELOPER_HANDOVER.md | 23 +++++ ios/CHANGELOG.md | 7 ++ ios/Makefile | 13 ++- ios/app/Host/Input/InputController.swift | 3 +- .../Host/Screens/Toolbox/MidiLearnSheet.swift | 36 +++++++ ios/app/Host/SizzleSession+Files.h | 9 ++ ios/app/Host/SizzleSession+Files.mm | 40 ++++++++ versions.properties | 4 +- 19 files changed, 580 insertions(+), 8 deletions(-) create mode 100644 app/src/main/java/cc/tiredsysadmin/android/sizzle/io/MidiMapIo.kt create mode 100644 app/src/test/java/cc/tiredsysadmin/android/sizzle/io/MidiMapIoTest.kt create mode 100644 app/src/test/resources/midimap/filter.szm create mode 100644 core/src/io/MidiMapIo.cpp create mode 100644 core/src/io/MidiMapIo.hpp create mode 100644 core/tests/midimap_test.cpp diff --git a/CHANGELOG.md b/CHANGELOG.md index b4a61a3..f1b8488 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,14 @@ version in `versions.properties`; versions before 0.28.0 are described in the gi log (one commit per version). Since 0.37.0 Android and iOS share one version and one feature set; the iOS side of each version is in `ios/CHANGELOG.md`. +## 0.39.0 (versionCode 73) + +- **MIDI mappings as files:** the ⇄ MIDI panel of every toolbox device has + EXPORT and IMPORT. EXPORT shares the device's mapping (which MIDI CC drives + which parameter) as a plain-text `.szm` file; IMPORT replaces the device's + mapping with one from a file for the same kind of device, moving any CC another + parameter used. The same files work on iOS. (iOS has the same in 0.39.0.) + ## 0.38.0 (versionCode 72) - **Bluetooth LE MIDI controllers:** Settings › MIDI Sync › MIDI inputs has a diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/io/MidiMapIo.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/io/MidiMapIo.kt new file mode 100644 index 0000000..8548609 --- /dev/null +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/io/MidiMapIo.kt @@ -0,0 +1,99 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +package cc.tiredsysadmin.android.sizzle.io + +import cc.tiredsysadmin.android.sizzle.model.Project +import cc.tiredsysadmin.android.sizzle.model.ToolboxSlot + +/** + * A device's MIDI mapping as plain text (.szm), shared between Sizzle installs + * (Android and iOS read and write the same format; the C++ core's io/MidiMapIo): + * + * SIZZLE-MIDIMAP 1 + * # comments start with '#' + * TYPE=WAVETABLE + * NAME=Lead + * cutoff=74 + * resonance=71 + * + * One `parameter=CC` line per mapped parameter (CC 0..127), in the device's + * parameter order. In the song a mapping is the slot value `midicc@`. + */ +object MidiMapIo { + const val HEADER = "SIZZLE-MIDIMAP 1" + const val EXT = ".szm" + const val CC_PREFIX = "midicc@" + + data class MidiMap(val type: String, val name: String, val bindings: List>) + + /** [slot]'s mappings, in its device's parameter order. */ + fun fromSlot(slot: ToolboxSlot): MidiMap = MidiMap( + type = slot.type?.name.orEmpty(), + name = slot.name, + bindings = slot.type?.params.orEmpty().mapNotNull { spec -> + slot.string(CC_PREFIX + spec.key).toIntOrNull()?.takeIf { it in 0..127 }?.let { spec.key to it } + }, + ) + + fun save(map: MidiMap): String = buildString { + appendLine(HEADER) + appendLine("# Sizzle MIDI mapping: parameter=CC number (0-127), one per line.") + appendLine("TYPE=${map.type}") + appendLine("NAME=${map.name}") + for ((key, cc) in map.bindings) appendLine("$key=$cc") + } + + /** The mapping in [text], or null if it has no header or TYPE. Lines that aren't + * `key=CC` with CC 0..127 are skipped; a repeated key or CC keeps its first line + * (one control drives one parameter). */ + fun parse(text: String): MidiMap? { + var header = false + var type = "" + var name = "" + val bindings = ArrayList>() + val keys = HashSet() + val ccs = HashSet() + for (raw in text.lineSequence()) { + val line = raw.trim() + if (line.isEmpty() || line.startsWith("#")) continue + if (line == HEADER) { header = true; continue } + val eq = line.indexOf('=') + if (eq <= 0) continue + val key = line.substring(0, eq).trim() + val value = line.substring(eq + 1).trim() + when (key) { + "TYPE" -> type = value + "NAME" -> name = value + else -> { + val cc = value.toIntOrNull() ?: continue + if (cc !in 0..127 || key in keys || cc in ccs) continue + keys += key; ccs += cc + bindings += key to cc + } + } + } + return if (header && type.isNotEmpty()) MidiMap(type, name, bindings) else null + } + + /** Replace toolbox [slotIndex]'s mappings with [map]'s: only parameters its device + * has; a CC another parameter (of any slot) used moves to this one. Returns how + * many were applied, or -1 when [map] is for another device type. */ + fun apply(project: Project, slotIndex: Int, map: MidiMap): Int { + val target = project.toolbox.getOrNull(slotIndex) ?: return -1 + val type = target.type ?: return -1 + if (type.name != map.type) return -1 + type.params.forEach { target.values.remove(CC_PREFIX + it.key) } + var applied = 0 + for ((key, cc) in map.bindings) { + if (type.params.none { it.key == key }) continue + for (s in project.toolbox) { + s.values.entries.removeAll { it.key.startsWith(CC_PREFIX) && it.value.toIntOrNull() == cc } + } + target.set(CC_PREFIX + key, cc.toString()) + applied++ + } + + return applied + } +} diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/AppViewModel.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/AppViewModel.kt index b3281d8..2c1b948 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/AppViewModel.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/AppViewModel.kt @@ -21,6 +21,7 @@ import cc.tiredsysadmin.android.sizzle.model.Pitch import cc.tiredsysadmin.android.sizzle.model.Project import cc.tiredsysadmin.android.sizzle.model.TimeSignature import cc.tiredsysadmin.android.sizzle.model.ToolboxSlot +import cc.tiredsysadmin.android.sizzle.model.ToolboxType import kotlin.math.roundToInt import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.SharingStarted @@ -711,6 +712,34 @@ class AppViewModel( touched() } + /** [slotIndex]'s MIDI mapping as a shareable `.szm` file (in presets/.export, + * which the FileProvider serves), or null for an empty slot. */ + fun midiMapExportFile(slotIndex: Int): java.io.File? { + val slot = project.toolbox.getOrNull(slotIndex)?.takeIf { !it.isEmpty } ?: return null + val map = cc.tiredsysadmin.android.sizzle.io.MidiMapIo.fromSlot(slot) + val dir = java.io.File(appContext.filesDir, "presets/.export").apply { mkdirs() } + val base = slot.name.ifBlank { slot.type?.name ?: "device" } + .replace(Regex("[^A-Za-z0-9._ -]"), "_").trim().ifBlank { "device" } + return java.io.File(dir, "$base MIDI${cc.tiredsysadmin.android.sizzle.io.MidiMapIo.EXT}").apply { + writeText(cc.tiredsysadmin.android.sizzle.io.MidiMapIo.save(map)) + } + } + + /** Replace [slotIndex]'s MIDI mapping with the `.szm` [text]; null when done, + * else why not (for a dialog). */ + fun importMidiMap(slotIndex: Int, text: String): String? { + val io = cc.tiredsysadmin.android.sizzle.io.MidiMapIo + val map = io.parse(text) ?: return "This doesn't look like a Sizzle MIDI mapping (.szm)." + val slot = project.toolbox.getOrNull(slotIndex) ?: return "No device here." + if (slot.type?.name != map.type) { + val want = runCatching { ToolboxType.valueOf(map.type).displayName }.getOrDefault(map.type) + return "This mapping is for a $want, not a ${slot.type?.displayName ?: "empty slot"}." + } + io.apply(project, slotIndex, map) + touched() + return null + } + /** Remove the MIDI-CC binding for [slotIndex]'s [paramKey]. */ fun clearParamCc(slotIndex: Int, paramKey: String) { project.toolbox.getOrNull(slotIndex)?.values?.remove(ccKey(paramKey)) diff --git a/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/toolbox/ToolboxScreen.kt b/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/toolbox/ToolboxScreen.kt index 00fec88..42a4b0a 100644 --- a/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/toolbox/ToolboxScreen.kt +++ b/app/src/main/java/cc/tiredsysadmin/android/sizzle/ui/toolbox/ToolboxScreen.kt @@ -422,6 +422,16 @@ private fun MidiLearnPopup(vm: AppViewModel, slot: ToolboxSlot, onClose: () -> U val type = slot.type ?: return // Always disarm learn when the popup leaves the composition (closed / editor exited). DisposableEffect(slot.index) { onDispose { vm.cancelParamLearn() } } + val context = LocalContext.current + var importMessage by remember { mutableStateOf(null) } + // IMPORT: a .szm mapping for this device type replaces this slot's mappings. + val mapImporter = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> + if (uri == null) return@rememberLauncherForActivityResult + val text = runCatching { + context.contentResolver.openInputStream(uri)?.use { it.readBytes().takeIf { b -> b.size <= 1 shl 20 } } + }.getOrNull()?.toString(Charsets.UTF_8) + importMessage = if (text == null) "Couldn't read the selected file." else vm.importMidiMap(slot.index, text) + } Box( Modifier.fillMaxSize().background(c.background.copy(alpha = 0.92f)) @@ -440,9 +450,28 @@ private fun MidiLearnPopup(vm: AppViewModel, slot: ToolboxSlot, onClose: () -> U ) { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { Text("MIDI LEARN — ${slot.name}", color = c.accent, - fontFamily = FontFamily.Monospace, fontSize = 14.sp) - Text("DONE", color = c.textDim, fontFamily = FontFamily.Monospace, fontSize = 13.sp, - modifier = Modifier.pointerInput(Unit) { detectTapGestures { onClose() } }) + fontFamily = FontFamily.Monospace, fontSize = 14.sp, modifier = Modifier.weight(1f)) + Row(horizontalArrangement = Arrangement.spacedBy(14.dp)) { + // Share this device's mapping as a .szm text file / take one in. + Text("EXPORT", color = c.accent, fontFamily = FontFamily.Monospace, fontSize = 13.sp, + modifier = Modifier.pointerInput(Unit) { + detectTapGestures { + vm.midiMapExportFile(slot.index)?.let { f -> + val uri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", f) + val send = Intent(Intent.ACTION_SEND).apply { + this.type = "text/plain" + putExtra(Intent.EXTRA_STREAM, uri) + addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + } + context.startActivity(Intent.createChooser(send, "Share MIDI mapping")) + } + } + }) + Text("IMPORT", color = c.accent, fontFamily = FontFamily.Monospace, fontSize = 13.sp, + modifier = Modifier.pointerInput(Unit) { detectTapGestures { mapImporter.launch(arrayOf("*/*")) } }) + Text("DONE", color = c.textDim, fontFamily = FontFamily.Monospace, fontSize = 13.sp, + modifier = Modifier.pointerInput(Unit) { detectTapGestures { onClose() } }) + } } Text( "Tap LEARN, then move a knob/fader on your MIDI controller.", @@ -481,6 +510,14 @@ private fun MidiLearnPopup(vm: AppViewModel, slot: ToolboxSlot, onClose: () -> U } } } + importMessage?.let { msg -> + AlertDialog( + onDismissRequest = { importMessage = null }, + title = { Text("Import failed") }, + text = { Text(msg) }, + confirmButton = { TextButton(onClick = { importMessage = null }) { Text("OK") } }, + ) + } } /** diff --git a/app/src/test/java/cc/tiredsysadmin/android/sizzle/io/MidiMapIoTest.kt b/app/src/test/java/cc/tiredsysadmin/android/sizzle/io/MidiMapIoTest.kt new file mode 100644 index 0000000..daf2b73 --- /dev/null +++ b/app/src/test/java/cc/tiredsysadmin/android/sizzle/io/MidiMapIoTest.kt @@ -0,0 +1,46 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +package cc.tiredsysadmin.android.sizzle.io + +import cc.tiredsysadmin.android.sizzle.model.Project +import cc.tiredsysadmin.android.sizzle.model.ToolboxType +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Test + +/** The same expectations as core/tests/midimap_test.cpp, on the same fixture. */ +class MidiMapIoTest { + private val fixture = javaClass.getResource("/midimap/filter.szm")!!.readText() + + @Test + fun parsesTheSharedFixture() { + val map = MidiMapIo.parse(fixture) + assertNotNull(map) + assertEquals("FILTER", map!!.type) + assertEquals("Sweep", map.name) + assertEquals(listOf("cutoff" to 74, "resonance" to 71, "nosuchparam" to 20, "release" to 7), map.bindings) + assertNull(MidiMapIo.parse("TYPE=FILTER\ncutoff=1\n")) + assertNull(MidiMapIo.parse("SIZZLE-MIDIMAP 1\ncutoff=1\n")) + } + + @Test + fun appliesExportsAndRoundTrips() { + val map = MidiMapIo.parse(fixture)!! + val p = Project() + p.toolbox[2].fill(ToolboxType.FILTER) + p.toolbox[5].fill(ToolboxType.BITCRUSHER) + p.toolbox[5].set("midicc@bits", "71") + p.toolbox[2].set("midicc@warmth", "30") + assertEquals(-1, MidiMapIo.apply(p, 5, map)) + assertEquals(3, MidiMapIo.apply(p, 2, map)) + assertFalse("midicc@bits" in p.toolbox[5].values) + assertFalse("midicc@warmth" in p.toolbox[2].values) + val applied = listOf("cutoff" to 74, "resonance" to 71, "release" to 7) + val back = MidiMapIo.fromSlot(p.toolbox[2]) + assertEquals(applied, back.bindings) + assertEquals(applied, MidiMapIo.parse(MidiMapIo.save(back))!!.bindings) + } +} diff --git a/app/src/test/resources/midimap/filter.szm b/app/src/test/resources/midimap/filter.szm new file mode 100644 index 0000000..4a109d3 --- /dev/null +++ b/app/src/test/resources/midimap/filter.szm @@ -0,0 +1,13 @@ +SIZZLE-MIDIMAP 1 +# A shared fixture: core/tests/midimap_test.cpp and MidiMapIoTest.kt read it. +TYPE=FILTER +NAME=Sweep + cutoff = 74 +resonance=71 +cutoff=12 +warmth=74 +envamt=300 +nosuchparam=20 +garbage line +decay=x +release=7 diff --git a/core/include/sizzle/Params.hpp b/core/include/sizzle/Params.hpp index 2f66abe..0793a43 100644 --- a/core/include/sizzle/Params.hpp +++ b/core/include/sizzle/Params.hpp @@ -25,6 +25,8 @@ public: void fill(const DeviceSpec &spec); void set(const char *key, const char *value); void set(const char *key, float value); + /** Drop [key] (Kotlin's values.remove); the others keep their order. */ + void remove(const char *key); /** Number as Kotlin's String.toFloat would parse it, else [fallback]. */ float f(const char *key, float fallback = 0.f) const; /** The stored text (enum choice name), else [fallback]. */ diff --git a/core/src/Params.cpp b/core/src/Params.cpp index 3db853d..cc28014 100644 --- a/core/src/Params.cpp +++ b/core/src/Params.cpp @@ -4,6 +4,7 @@ #include "sizzle/Params.hpp" #include #include +#include namespace sizzle { @@ -38,6 +39,17 @@ void Params::set(const char *key, const char *value) { std::snprintf(vals_[i], kValLen, "%s", value); } +void Params::remove(const char *key) { + const int i = find(key); + if (i < 0) return; + for (int k = i; k + 1 < n_; ++k) { // keep the insertion order of the rest + std::memcpy(keys_[k], keys_[k + 1], kKeyLen); + std::memcpy(vals_[k], vals_[k + 1], kValLen); + } + --n_; + keys_[n_][0] = vals_[n_][0] = '\0'; +} + void Params::set(const char *key, float value) { // Shortest text that reads back as the same float (Kotlin stores toString()). char buf[kValLen]; diff --git a/core/src/io/MidiMapIo.cpp b/core/src/io/MidiMapIo.cpp new file mode 100644 index 0000000..51ed2ab --- /dev/null +++ b/core/src/io/MidiMapIo.cpp @@ -0,0 +1,97 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +#include "io/MidiMapIo.hpp" + +#include + +#include "io/KotlinText.hpp" +#include "sizzle/Specs.hpp" + +namespace sizzle::io { + +namespace { + +std::string ccKey(const std::string ¶m) { return std::string(MidiMapIo::CC_PREFIX) + param; } + +/// The CC [slot] maps [param] to, or -1 (Kotlin: string(key).toIntOrNull()). +int ccOf(const model::ToolboxSlot &slot, const std::string ¶m) { + int v = -1; + return kt::toIntOrNull(slot.s(ccKey(param).c_str(), ""), v) ? v : -1; +} + +} // namespace + +MidiMap MidiMapIo::fromSlot(const model::ToolboxSlot &slot) { + MidiMap m; + m.type = slot.type; + m.name = slot.name; + if (const DeviceSpec *spec = findDevice(slot.type.c_str())) { + for (int i = 0; i < spec->paramCount; ++i) { + const int cc = ccOf(slot, spec->params[i].key); + if (cc >= 0 && cc <= 127) m.bindings.emplace_back(spec->params[i].key, cc); + } + } + return m; +} + +std::string MidiMapIo::save(const MidiMap &map) { + std::string out = std::string(HEADER) + "\n"; + out += "# Sizzle MIDI mapping: parameter=CC number (0-127), one per line.\n"; + out += "TYPE=" + map.type + "\n"; + out += "NAME=" + map.name + "\n"; + for (const auto &[key, cc] : map.bindings) out += key + "=" + std::to_string(cc) + "\n"; + return out; +} + +std::optional MidiMapIo::parse(const std::string &text) { + MidiMap m; + bool header = false, typed = false; + std::set keys; + std::set ccs; + for (const std::string &raw : kt::lines(text)) { + const std::string line = kt::trim(raw); + if (line.empty() || line[0] == '#') continue; + if (line == HEADER) { header = true; continue; } + const size_t eq = line.find('='); + if (eq == std::string::npos || eq == 0) continue; + const std::string key = kt::trim(line.substr(0, eq)), value = kt::trim(line.substr(eq + 1)); + if (key == "TYPE") { m.type = value; typed = !value.empty(); continue; } + if (key == "NAME") { m.name = value; continue; } + int cc = -1; + if (!kt::toIntOrNull(value, cc) || cc < 0 || cc > 127 || keys.count(key) || ccs.count(cc)) continue; + keys.insert(key); + ccs.insert(cc); + m.bindings.emplace_back(key, cc); + } + if (!header || !typed) return std::nullopt; + return m; +} + +int MidiMapIo::apply(model::Project &project, int slot, const MidiMap &map) { + if (slot < 0 || slot >= model::Project::TOOLBOX_SLOTS) return -1; + model::ToolboxSlot &target = project.toolbox[(size_t)slot]; + if (target.type != map.type) return -1; + const DeviceSpec *spec = findDevice(target.type.c_str()); + if (!spec) return -1; + for (int i = 0; i < spec->paramCount; ++i) target.values.remove(ccKey(spec->params[i].key).c_str()); + int applied = 0; + for (const auto &[key, cc] : map.bindings) { + bool known = false; + for (int i = 0; i < spec->paramCount && !known; ++i) known = key == spec->params[i].key; + if (!known) continue; + // One physical control drives one parameter: take the CC from wherever it was. + for (auto &s : project.toolbox) { + if (s.isEmpty()) continue; + const DeviceSpec *other = findDevice(s.type.c_str()); + for (int i = 0; other && i < other->paramCount; ++i) + if (ccOf(s, other->params[i].key) == cc) s.values.remove(ccKey(other->params[i].key).c_str()); + } + target.set(ccKey(key).c_str(), std::to_string(cc).c_str()); + ++applied; + } + ++target.version; + return applied; +} + +} // namespace sizzle::io diff --git a/core/src/io/MidiMapIo.hpp b/core/src/io/MidiMapIo.hpp new file mode 100644 index 0000000..6b3f23b --- /dev/null +++ b/core/src/io/MidiMapIo.hpp @@ -0,0 +1,52 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +// A device's MIDI mapping as plain text (.szm), the same format the Android app +// reads and writes (io/MidiMapIo.kt): +// +// SIZZLE-MIDIMAP 1 +// # comments start with '#' +// TYPE=WAVETABLE +// NAME=Lead +// cutoff=74 +// resonance=71 +// +// One `parameter=CC` line per mapped parameter (CC 0..127), in the device's +// parameter order. In the song a mapping is the slot value `midicc@`. + +#pragma once + +#include +#include +#include +#include + +#include "sizzle/Model.hpp" + +namespace sizzle::io { + +struct MidiMap { + std::string type; // ToolboxType name + std::string name; // the slot's name when exported (informational) + std::vector> bindings; // parameter key, CC +}; + +class MidiMapIo { +public: + static constexpr const char *HEADER = "SIZZLE-MIDIMAP 1"; + static constexpr const char *CC_PREFIX = "midicc@"; + + /** [slot]'s mappings, in its device's parameter order. */ + static MidiMap fromSlot(const model::ToolboxSlot &slot); + static std::string save(const MidiMap &map); + /** The mapping in [text], or nothing if it has no header or TYPE. Lines that + * aren't `key=CC` with CC 0..127 are skipped; a repeated key or CC keeps its + * first line (one control drives one parameter). */ + static std::optional parse(const std::string &text); + /** Replace toolbox [slot]'s mappings with [map]'s: only parameters its device + * has; a CC another parameter (of any slot) used moves to this one. Returns + * how many were applied, or -1 when [map] is for another device type. */ + static int apply(model::Project &project, int slot, const MidiMap &map); +}; + +} // namespace sizzle::io diff --git a/core/tests/midimap_test.cpp b/core/tests/midimap_test.cpp new file mode 100644 index 0000000..892fb21 --- /dev/null +++ b/core/tests/midimap_test.cpp @@ -0,0 +1,52 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +// io::MidiMapIo against the fixture the Android test reads too +// (argv[1]: app/src/test/resources/midimap/filter.szm). + +#include "io/MidiMapIo.hpp" +#include "io/ProjectIo.hpp" + +#include +#include +#include + +using namespace sizzle; + +static int failures = 0; +#define CHECK(c) do { if (!(c)) { std::printf("FAIL %s:%d %s\n", __FILE__, __LINE__, #c); ++failures; } } while (0) + +int main(int argc, char **argv) { + if (argc < 2) { std::printf("usage: midimap_test \n"); return 2; } + std::ifstream f(argv[1]); + std::stringstream ss; + ss << f.rdbuf(); + const auto map = io::MidiMapIo::parse(ss.str()); + CHECK(map && map->type == "FILTER" && map->name == "Sweep"); + // Repeated key, repeated CC, CC out of range and junk lines are skipped. + const std::vector> want = {{"cutoff", 74}, {"resonance", 71}, {"nosuchparam", 20}, {"release", 7}}; + CHECK(map && map->bindings == want); + CHECK(!io::MidiMapIo::parse("TYPE=FILTER\ncutoff=1\n")); // no header + CHECK(!io::MidiMapIo::parse("SIZZLE-MIDIMAP 1\ncutoff=1\n")); // no type + + model::Project p; + p.toolbox[2].fill("FILTER"); + p.toolbox[5].fill("BITCRUSHER"); + p.toolbox[5].set("midicc@bits", "71"); // CC 71 moves to the filter + p.toolbox[2].set("midicc@warmth", "30"); // replaced by the import + CHECK(io::MidiMapIo::apply(p, 5, *map) == -1); // another device + CHECK(io::MidiMapIo::apply(p, 2, *map) == 3); // nosuchparam skipped + CHECK(!p.toolbox[5].values.has("midicc@bits")); + CHECK(!p.toolbox[2].values.has("midicc@warmth")); + const io::MidiMap back = io::MidiMapIo::fromSlot(p.toolbox[2]); + const std::vector> applied = {{"cutoff", 74}, {"resonance", 71}, {"release", 7}}; + CHECK(back.bindings == applied && back.type == "FILTER"); + // Round trip, and the mapping survives the song file. + CHECK(io::MidiMapIo::parse(io::MidiMapIo::save(back))->bindings == applied); + model::Project q; + io::ProjectIo::loadInto(q, io::ProjectIo::save(p)); + CHECK(io::MidiMapIo::fromSlot(q.toolbox[2]).bindings == applied); + + std::printf(failures ? "midimap_test: %d failure(s)\n" : "midimap_test: ok\n", failures); + return failures ? 1 : 0; +} diff --git a/docs/DEVELOPER_HANDOVER.md b/docs/DEVELOPER_HANDOVER.md index 9b52494..db905fb 100644 --- a/docs/DEVELOPER_HANDOVER.md +++ b/docs/DEVELOPER_HANDOVER.md @@ -776,6 +776,29 @@ attack=0.01 ``` Copy/paste from the Toolbox parameter editor uses this exact text. +### MIDI mapping (`MidiMapIo`, `.szm`, 0.39.0) + +One device's parameter → MIDI CC mapping, exported and imported from the ⇄ MIDI +panel. Written and read by `io/MidiMapIo.kt` (Android) and +`core/src/io/MidiMapIo` (iOS); both tests read the same fixture, +`app/src/test/resources/midimap/filter.szm`. +``` +SIZZLE-MIDIMAP 1 +# comments start with '#' +TYPE=FILTER +NAME=Sweep +cutoff=74 +resonance=71 +``` +The header and `TYPE` (a `ToolboxType` name) are required; `NAME` is the slot's +name, for information. Then one `parameter=CC` line per mapping (CC 0..127), in +the device's parameter order. Reading skips anything else, and a repeated +parameter or CC keeps its first line. Importing needs the same `TYPE` and +replaces the slot's mappings. Parameters the device doesn't have are skipped, +and a CC that another parameter (in any slot) used moves to the imported one, +because one control drives one parameter. In the song, a mapping is the slot +value `midicc@`. + ### Interchange `.sng` (`SngFormat`) The desktop sizzletracker format, read the way the desktop reader does it: `block ` (names may contain spaces; the trailing diff --git a/ios/CHANGELOG.md b/ios/CHANGELOG.md index 9ad3038..6802c51 100644 --- a/ios/CHANGELOG.md +++ b/ios/CHANGELOG.md @@ -5,6 +5,13 @@ Sizzle for iOS/iPadOS (`cc.tiredsysadmin.ios.sizzle`). One entry per version in is shared with Android, continuing Android's numbering, and both apps ship the same features; the Android side of each version is in `../CHANGELOG.md`. +## 0.39.0 (build 73) + +- MIDI mappings as files: EXPORT / IMPORT in each device's ⇄ MIDI sheet share a + device's CC mapping as a plain-text `.szm` file (the same files as Android). + Clearing a mapping now removes it from the song instead of leaving it empty. + (Android has the same in 0.39.0.) + ## 0.38.0 (build 72) - Bluetooth LE MIDI controllers: Setup › MIDI Sync › Bluetooth MIDI › Find diff --git a/ios/Makefile b/ios/Makefile index bbb4f8e..793ea27 100644 --- a/ios/Makefile +++ b/ios/Makefile @@ -82,6 +82,10 @@ build/core/host_test: $(CORE_SRC) $(CORE_HDR) ../core/tests/host_test.cpp mkdir -p build/core $(CXX) $(CXXFLAGS) -o $@ $(CORE_SRC) ../core/tests/host_test.cpp +build/core/midimap_test: $(CORE_SRC) $(CORE_HDR) ../core/tests/midimap_test.cpp + mkdir -p build/core + $(CXX) $(CXXFLAGS) -o $@ $(CORE_SRC) ../core/tests/midimap_test.cpp + build/core/midi_test: ../core/include/sizzle/Midi.hpp ../core/tests/midi_test.cpp mkdir -p build/core $(CXX) $(CXXFLAGS) -o $@ ../core/tests/midi_test.cpp @@ -98,7 +102,7 @@ zip-test: build/core/zip_test build/core/zip_test build/core/java.zip build/core/ours.zip unzip -tq build/core/ours.zip -core-test: build/core/golden_test build/core/sampler_test build/core/engine_test build/core/io_test build/core/midi_test build/core/host_test zip-test +core-test: build/core/golden_test build/core/sampler_test build/core/engine_test build/core/io_test build/core/midi_test build/core/host_test build/core/midimap_test zip-test @test -f $(GOLDEN)/input.f32 || $(MAKE) --no-print-directory golden build/core/golden_test $(GOLDEN) $(TYPES) build/core/sampler_test @@ -106,6 +110,7 @@ core-test: build/core/golden_test build/core/sampler_test build/core/engine_test build/core/io_test $(GOLDEN)/songs ../app/src/test/resources/mikroseq build/core/midi_test build/core/host_test $(GOLDEN)/songs + build/core/midimap_test ../app/src/test/resources/midimap/filter.szm # ------------------------------------------------------------------ app AU_SRC := app/FX/SizzleDeviceAU.mm app/FX/SizzleEffectAU.mm app/FX/SizzleInstrumentAU.mm app/FX/SizzleDeviceAU+Sources.mm @@ -158,8 +163,12 @@ app/FX/Info.plist app/FX/Components.gen.h: app/components.txt tools/gen_componen python3 tools/gen_components.py app/components.txt app/FX/Info.plist app/FX/Components.gen.h project: $(PROJECT)/project.pbxproj -$(PROJECT)/project.pbxproj: app/project.yml app/FX/Info.plist +# The folders too: a directory's time changes when a file is added or removed, and +# the generated project lists every source file. +SRC_DIRS := $(shell find app ../core/src ../core/include -type d -not -path '*.xcodeproj*') +$(PROJECT)/project.pbxproj: app/project.yml app/FX/Info.plist $(SRC_DIRS) cd app && xcodegen generate --spec project.yml --quiet + touch $@ # Device: build without signing, then ad-hoc sign inside-out (extension first) with # each target's entitlements. TrollStore re-signs at install and keeps them. diff --git a/ios/app/Host/Input/InputController.swift b/ios/app/Host/Input/InputController.swift index d6822bf..e00d380 100644 --- a/ios/app/Host/Input/InputController.swift +++ b/ios/app/Host/Input/InputController.swift @@ -158,7 +158,7 @@ final class InputController: ObservableObject { func paramCc(slot: Int, key: String) -> Int? { Int(session.value(ofSlot: slot, key: Self.ccPrefix + key)) } - func clearParamCc(slot: Int, key: String) { session.setValue("", ofSlot: slot, key: Self.ccPrefix + key) } + func clearParamCc(slot: Int, key: String) { session.removeValue(ofSlot: slot, key: Self.ccPrefix + key) } private func onRaw(_ source: InputSource, _ code: Int, _ value: Float, _ modifier: Int) { if let key = paramLearnKey { @@ -187,6 +187,7 @@ final class InputController: ObservableObject { clearParamCc(slot: s, key: spec.key) } } + // (Same rule as MidiMapIo.apply: one control drives one parameter.) session.setValue(String(cc), ofSlot: slot, key: Self.ccPrefix + key) } diff --git a/ios/app/Host/Screens/Toolbox/MidiLearnSheet.swift b/ios/app/Host/Screens/Toolbox/MidiLearnSheet.swift index 7ae45b3..06f2cdd 100644 --- a/ios/app/Host/Screens/Toolbox/MidiLearnSheet.swift +++ b/ios/app/Host/Screens/Toolbox/MidiLearnSheet.swift @@ -6,12 +6,15 @@ import SwiftUI /// Android's MidiLearnPopup: every parameter of the slot with its MIDI CC. LEARN, /// then move a knob or fader on a MIDI controller; ✕ removes the binding. The /// bindings are saved in the song (`midicc@` slot values), as on Android. +/// EXPORT shares them as a .szm text file; IMPORT takes one for this device type. struct MidiLearnSheet: View { let slot: Int let type: String @ObservedObject private var input = InputController.shared @ObservedObject private var watch = MixSongWatch.shared @Environment(\.dismiss) private var dismiss + @State private var importing = false + @State private var importError: String? var body: some View { let session = SizzleSession.shared @@ -19,6 +22,12 @@ struct MidiLearnSheet: View { HStack { Text("MIDI LEARN — \(session.name(ofSlot: slot))").font(Theme.mono(14)).foregroundColor(Theme.accent) Spacer() + Text("EXPORT").font(Theme.mono(13)).foregroundColor(Theme.accent) + .contentShape(Rectangle()).onTapGesture(perform: export) + .padding(.trailing, 14) + Text("IMPORT").font(Theme.mono(13)).foregroundColor(Theme.accent) + .contentShape(Rectangle()).onTapGesture { importing = true } + .padding(.trailing, 14) Text("DONE").font(Theme.mono(13)).foregroundColor(Theme.dim) .contentShape(Rectangle()).onTapGesture { dismiss() } } @@ -46,5 +55,32 @@ struct MidiLearnSheet: View { .background(Theme.surface.ignoresSafeArea()) .preferredColorScheme(.dark) .onDisappear { input.cancelParamLearn() } + // The completion needs nothing but the URL (iOS 15 resets the binding first). + .fileImporter(isPresented: $importing, allowedContentTypes: [.item]) { result in + guard case .success(let url) = result else { return } + do { + let data = try SetupFiles.readData(url, limit: 1 << 20) + guard let text = String(data: data, encoding: .utf8) else { throw SetupFileError.notText } + try SizzleSession.shared.importMidiMapText(text, intoSlot: slot) + } catch { + importError = error.localizedDescription + } + } + .alert("Import failed", isPresented: Binding(get: { importError != nil }, set: { if !$0 { importError = nil } }), + actions: { Button("OK") { importError = nil } }, message: { Text(importError ?? "") }) + } + + /// The mapping as " MIDI.szm", through the share sheet. + private func export() { + let session = SizzleSession.shared + guard let text = session.midiMapText(ofSlot: slot) else { return } + let name = session.name(ofSlot: slot).trimmingCharacters(in: .whitespaces) + let base = SetupFiles.fileStem(name.isEmpty ? type : name) + " MIDI" + do { + let url = try SetupFiles.export(Data(text.utf8), name: base, ext: "szm") + ShareSheet.present(url) { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) } + } catch { + importError = error.localizedDescription + } } } diff --git a/ios/app/Host/SizzleSession+Files.h b/ios/app/Host/SizzleSession+Files.h index 3a60f5f..283edb9 100644 --- a/ios/app/Host/SizzleSession+Files.h +++ b/ios/app/Host/SizzleSession+Files.h @@ -19,6 +19,15 @@ NS_ASSUME_NONNULL_BEGIN /// True for a ZIP archive (bundle or backup) rather than text. + (BOOL)isZipData:(NSData *)data; +/// Toolbox [slot]'s MIDI mapping as .szm text (io/MidiMapIo: TYPE, NAME, one +/// `parameter=CC` line each), or nil for an empty slot. +- (nullable NSString *)midiMapTextOfSlot:(NSInteger)slot; +/// Replace [slot]'s MIDI mapping with the .szm [text] (a CC another parameter used +/// moves here). NO with [error] set when it isn't a mapping or is for another device. +- (BOOL)importMidiMapText:(NSString *)text intoSlot:(NSInteger)slot error:(NSError **)error; +/// Remove setting [key] from [slot] (a cleared MIDI mapping). +- (void)removeValueOfSlot:(NSInteger)slot key:(NSString *)key; + /// Everything Sizzle keeps: Documents/songs, themes, presets and samples, the /// autosaved song, and [settings] as settings.txt. The open song is autosaved first. - (nullable NSData *)backupDataWithSettings:(NSString *)settings; diff --git a/ios/app/Host/SizzleSession+Files.mm b/ios/app/Host/SizzleSession+Files.mm index 2474f1d..c3db004 100644 --- a/ios/app/Host/SizzleSession+Files.mm +++ b/ios/app/Host/SizzleSession+Files.mm @@ -9,7 +9,9 @@ #include #include +#include "io/MidiMapIo.hpp" #include "io/Zip.hpp" +#include "sizzle/Specs.hpp" using namespace sizzle; namespace zip = sizzle::io::zip; @@ -138,6 +140,44 @@ NSString *const kSettings = @"settings.txt"; return [self importProjectText:text error:error]; } +#pragma mark - MIDI mappings + +- (nullable NSString *)midiMapTextOfSlot:(NSInteger)slot { + if (slot < 0 || slot >= 16) return nil; + __block std::string text; + [self read:^(const model::Project &p, const engine::Engine &) { + const auto &s = p.toolbox[(size_t)slot]; + if (!s.isEmpty()) text = io::MidiMapIo::save(io::MidiMapIo::fromSlot(s)); + }]; + return text.empty() ? nil : @(text.c_str()); +} + +- (BOOL)importMidiMapText:(NSString *)text intoSlot:(NSInteger)slot error:(NSError **)error { + const auto map = io::MidiMapIo::parse(text.UTF8String ?: ""); + if (!map) { + if (error) *error = filesError(@"This doesn't look like a Sizzle MIDI mapping (.szm)."); + return NO; + } + __block int applied = -1; + [self edit:^(model::Project &p, engine::Engine &) { applied = io::MidiMapIo::apply(p, (int)slot, *map); }]; + if (applied < 0 && error) { + const DeviceSpec *want = findDevice(map->type.c_str()); + const DeviceSpec *have = findDevice([self typeOfSlot:slot].UTF8String); + *error = filesError([NSString stringWithFormat:@"This mapping is for a %s, not a %s.", + want ? want->displayName : map->type.c_str(), have ? have->displayName : "empty slot"]); + } + return applied >= 0; +} + +- (void)removeValueOfSlot:(NSInteger)slot key:(NSString *)key { + if (slot < 0 || slot >= 16) return; + std::string k = key.UTF8String ?: ""; + [self edit:^(model::Project &p, engine::Engine &) { + p.toolbox[(size_t)slot].values.remove(k.c_str()); + ++p.toolbox[(size_t)slot].version; + }]; +} + #pragma mark - backups - (nullable NSData *)backupDataWithSettings:(NSString *)settings { diff --git a/versions.properties b/versions.properties index 7907523..8512eca 100644 --- a/versions.properties +++ b/versions.properties @@ -12,8 +12,8 @@ # or polish. versionCode is monotonic and bumps by 1 on every release, # because F-Droid and the Android package manager order installs by it alone. -versionName = 0.38.0 -versionCode = 72 +versionName = 0.39.0 +versionCode = 73 # Namespace for every platform: cc.tiredsysadmin..sizzle. Android: # cc.tiredsysadmin.android.sizzle (app/), iOS/iPadOS: cc.tiredsysadmin.ios.sizzle