diff --git a/padeditor/device.py b/padeditor/device.py index b9ae7be..6da4708 100644 --- a/padeditor/device.py +++ b/padeditor/device.py @@ -178,6 +178,27 @@ def read_global(link: Link | None = None) -> bytes: link.close() +def set_bank(bank: int, link: Link | None = None) -> int: + """Switch the pad bank the way MidiSuite does: one live byte in the + global block. It does not commit; Save keeps whatever the block holds.""" + from padeditor.preset import GLOBAL_BANK + + if bank not in (0, 1): + raise PadError("pad bank must be 0 or 1") + own = link is None + if link is None: + link = Link() + try: + link.write(GLOBAL_BANK, bytes((bank,)), MEM_GLOBAL) + got = read_global(link)[GLOBAL_BANK] + if got != bank: + raise PadError(f"the pad is on bank {got + 1}, not {bank + 1}") + return bank + finally: + if own: + link.close() + + def save_image(desired: bytes, link: Link | None = None, settings: bytes | None = None) -> int: """Write differing bytes to the preset and commit them. diff --git a/padeditor/factory.bin b/padeditor/factory.bin new file mode 100644 index 0000000..cb743c8 Binary files /dev/null and b/padeditor/factory.bin differ diff --git a/padeditor/preset.py b/padeditor/preset.py index 0be3f0f..849e274 100644 --- a/padeditor/preset.py +++ b/padeditor/preset.py @@ -31,6 +31,7 @@ GLOBAL_TEMPO = 0 # two bytes, little-endian GLOBAL_SWING = 2 GLOBAL_CURVE = 6 GLOBAL_TRANSPOSE = 7 # signed +GLOBAL_BANK = 11 # 0 is pad bank 1, 1 is pad bank 2; MidiSuite writes it to switch banks # File bytes. Names are only values MidiSuite has shown for this pad's # factory image, or a RAM probe on this pad has heard. @@ -132,6 +133,7 @@ def unpack_global(raw: bytes) -> dict: "swing": raw[GLOBAL_SWING], "curve": raw[GLOBAL_CURVE], "transpose": int.from_bytes(raw[GLOBAL_TRANSPOSE:GLOBAL_TRANSPOSE + 1], "little", signed=True), + "bank": raw[GLOBAL_BANK], "raw": raw.hex(), } @@ -151,6 +153,10 @@ def pack_global(block: dict) -> bytes: if isinstance(transpose, bool) or not isinstance(transpose, int) or not -128 <= transpose <= 127: raise PresetError("transpose must be -128 to 127") out[GLOBAL_TRANSPOSE] = transpose & 0xFF + bank = block.get("bank", out[GLOBAL_BANK]) + if isinstance(bank, bool) or bank not in (0, 1): + raise PresetError("pad bank must be 0 or 1") + out[GLOBAL_BANK] = bank return bytes(out) diff --git a/padeditor/server.py b/padeditor/server.py index 7bed31d..1550f5a 100644 --- a/padeditor/server.py +++ b/padeditor/server.py @@ -10,10 +10,13 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from urllib.parse import urlparse -from padeditor.device import Link, PadError, connected, read_global, read_image, save_image, write_colour +from padeditor.device import Link, PadError, connected, read_global, read_image, save_image, set_bank, write_colour from padeditor.preset import IMAGE_LEN, PresetError, pack, pack_global, unpack, unpack_global STATIC_DIR = Path(__file__).parent / "static" +# The image MidiSuite uploads for its factory reset, and its global block. +FACTORY_IMAGE = Path(__file__).parent / "factory.bin" +FACTORY_GLOBAL = bytes.fromhex("780032040000020001010000") class ApiError(Exception): @@ -76,12 +79,28 @@ class Editor: raise ApiError(str(exc), 503) from exc return {"ok": True, "offset": offset} + def bank(self, body: dict) -> dict: + bank = body.get("bank") + if isinstance(bank, bool) or bank not in (0, 1): + raise ApiError("bank must be 0 or 1") + with self.lock: + try: + set_bank(bank) + except PadError as exc: + raise ApiError(str(exc), 503) from exc + return {"ok": True, "bank": bank} + def imported(self, raw: bytes) -> dict: try: return unpack(raw) except PresetError as exc: raise ApiError(str(exc)) from exc + def factory(self) -> dict: + document = unpack(FACTORY_IMAGE.read_bytes()) + document["global"] = unpack_global(FACTORY_GLOBAL) + return document + def exported(self, document: dict) -> bytes: try: return pack(document) @@ -173,11 +192,15 @@ class Handler(BaseHTTPRequestHandler): self._json(200, editor.save(self._json_body())) elif route == ("POST", "/api/colour"): self._json(200, editor.colour(self._json_body())) + elif route == ("POST", "/api/bank"): + self._json(200, editor.bank(self._json_body())) elif route == ("POST", "/api/import"): raw = self._read() if len(raw) != IMAGE_LEN: raise ApiError(f"preset file is {len(raw)} bytes, expected {IMAGE_LEN}") self._json(200, editor.imported(raw)) + elif route == ("POST", "/api/factory"): + self._json(200, editor.factory()) elif route == ("POST", "/api/export"): self._bytes(editor.exported(self._json_body()), "application/octet-stream", "smc-pad-preset.bin") else: diff --git a/padeditor/static/app.js b/padeditor/static/app.js index a09a44e..66fecd5 100644 --- a/padeditor/static/app.js +++ b/padeditor/static/app.js @@ -158,6 +158,48 @@ async function importFile(file) { } } +function withBank(global, bank) { + const raw = global.raw.slice(0, 22) + bank.toString(16).padStart(2, "0") + global.raw.slice(24); + return { ...global, bank, raw }; +} + +async function switchBank(bank) { + try { + await request("/api/bank", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ bank }), + }); + const wasDirty = dirty(); + state.doc.global = withBank(state.doc.global, bank); + if (!wasDirty) { + const saved = JSON.parse(state.saved); + saved.global = withBank(saved.global, bank); + state.saved = JSON.stringify(saved); + } + state.page = bank ? 7 : 2; + $("page").value = String(state.page); + state.kind = state.kind === "pad" ? null : state.kind; + render(); + setStatus(`Pad bank ${bank + 1}.`, "ok"); + } catch (error) { + setStatus(error.message, "err"); + } +} + +async function factory() { + if (!window.confirm("Replace all eight presets with the factory settings? Nothing reaches the pad until you Save.")) return; + setStatus("Reading the factory preset…"); + try { + state.doc = await request("/api/factory", { method: "POST" }); + render(); + setStatus("Factory settings loaded. Save to pad to store them.", "dirty"); + } catch (error) { + setStatus(error.message, "err"); + } + mark(); +} + function render() { if (!state.doc) return; $("board").classList.add("ready"); @@ -185,6 +227,12 @@ function renderGlobal() { for (const [label, key, min, max] of fields) { row.append(field(label, numberInput(block, key, min, max))); } + const toggle = document.createElement("button"); + toggle.type = "button"; + toggle.textContent = `Pad bank ${block.bank + 1}`; + toggle.title = "Switch the pad's bank now, as MidiSuite does"; + toggle.addEventListener("click", () => switchBank(1 - block.bank)); + row.append(toggle); } function renderPresets() { @@ -207,8 +255,8 @@ function renderPages() { const select = $("page"); const current = select.value; select.replaceChildren(); - const order = [2, 3, 0, 1, 4, 5, 6, 7]; - const names = { 2: "Bank 1", 3: "Bank 2" }; + const order = [2, 7, 0, 1, 3, 4, 5, 6]; + const names = { 2: "Bank 1", 7: "Bank 2", 3: "Page 4 (not lit)" }; for (const page of order) { const pads = preset().pads.slice(page * PAGE, page * PAGE + PAGE); const option = document.createElement("option"); @@ -422,6 +470,7 @@ function renderInspector() { $("load").addEventListener("click", () => load(true)); $("save").addEventListener("click", save); $("export").addEventListener("click", exportFile); +$("factory").addEventListener("click", factory); $("import").addEventListener("change", () => { const file = $("import").files[0]; $("import").value = ""; diff --git a/padeditor/static/index.html b/padeditor/static/index.html index 8000bcb..cfad576 100644 --- a/padeditor/static/index.html +++ b/padeditor/static/index.html @@ -11,6 +11,7 @@

SMC-PAD

+