Loading the pad…
+ + +diff --git a/Pipfile b/Pipfile index 3c6bb31..4ba33c1 100644 --- a/Pipfile +++ b/Pipfile @@ -16,3 +16,4 @@ python_version = "3.12" positions = "python scripts/position_movers.py" pattern = "python -m pattern_pad" midi = "python scripts/midi.py" +padeditor = "python -m padeditor" diff --git a/padeditor/__init__.py b/padeditor/__init__.py new file mode 100644 index 0000000..6f4e9ac --- /dev/null +++ b/padeditor/__init__.py @@ -0,0 +1 @@ +"""SMC-PAD preset editor.""" diff --git a/padeditor/__main__.py b/padeditor/__main__.py new file mode 100644 index 0000000..cb6f625 --- /dev/null +++ b/padeditor/__main__.py @@ -0,0 +1,33 @@ +"""python3 -m padeditor [--port 8770]""" + +from __future__ import annotations + +import argparse +import threading +import webbrowser + +from padeditor.server import make_server + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(prog="padeditor", description="SMC-PAD preset editor") + parser.add_argument("--host", default="127.0.0.1") + parser.add_argument("--port", type=int, default=8770) + parser.add_argument("--no-browser", action="store_true") + args = parser.parse_args(argv) + server = make_server(args.host, args.port) + url = f"http://{args.host}:{args.port}/" + print(f"SMC-PAD editor → {url} Ctrl+C to quit") + if not args.no_browser: + threading.Timer(0.4, webbrowser.open, args=(url,)).start() + try: + server.serve_forever() + except KeyboardInterrupt: + pass + finally: + server.server_close() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/padeditor/device.py b/padeditor/device.py new file mode 100644 index 0000000..b9ae7be --- /dev/null +++ b/padeditor/device.py @@ -0,0 +1,313 @@ +"""Read and save the SMC-PAD preset over the Private USB port. + +Writes go to the preset address, as MidiSuite sends them; the lamps follow +straight away. Save writes the bytes that differ, checks each read-back, +then sends the empty write MidiSuite's Save button sends, which keeps the +preset after a power cycle. It never sends erase. +""" + +from __future__ import annotations + +import glob +import sys +import time +from pathlib import Path + +from padeditor.preset import GLOBAL_LEN, IMAGE_LEN, changed_ranges +from padeditor.sysex import ( + CMD_READ, + MEM_GLOBAL, + MEM_PRESET, + RAM, + payload_data, + read_request, + save_request, + write_request, +) + +ROOT = Path(__file__).resolve().parents[1] +READ_CHUNK = 512 +WRITE_CHUNK = 64 + + +class PadError(RuntimeError): + pass + + +def load_rtmidi(): + for path in glob.glob(str(ROOT / ".venv" / "lib" / "python*" / "site-packages")): + if path not in sys.path: + sys.path.insert(0, path) + import rtmidi + + return rtmidi + + +def private_port(names: list[str]) -> str: + for name in names: + if "Private" in name: + return name + raise PadError( + "SMC-PAD Private port not found. Ports:\n " + "\n ".join(names or ["(none)"]) + ) + + +def master_port(names: list[str]) -> str: + for name in names: + if "Master" in name: + return name + raise PadError( + "SMC-PAD Master port not found. Ports:\n " + "\n ".join(names or ["(none)"]) + ) + + +def transact(midiout, midiin, message: list[int], timeout: float = 0.8, expect: int | None = None) -> bytes: + while True: + item = midiin.get_message() + if not item or not item[0]: + break + midiout.send_message(message) + deadline = time.time() + timeout + while time.time() < deadline: + item = midiin.get_message() + if not item or not item[0]: + time.sleep(0.004) + continue + raw = bytes(item[0]) + if raw[:1] != b"\xf0" or raw[-1:] != b"\xf7": + continue + decoded = decode_body(raw) + if expect is not None and (len(decoded) < 3 or decoded[2] != expect): + continue + return decoded + raise PadError("the pad did not answer") + + +def decode_body(raw: bytes) -> bytes: + from padeditor.sysex import decode + + return decode(raw[1:-1]) + + +class Link: + """One open Private port, input and output.""" + + def __init__(self): + rtmidi = load_rtmidi() + self.midiout = rtmidi.MidiOut(rtapi=rtmidi.API_LINUX_ALSA) + self.midiin = rtmidi.MidiIn(rtapi=rtmidi.API_LINUX_ALSA) + self.name = private_port(self.midiout.get_ports()) + index = self.midiout.get_ports().index(self.name) + self.midiin.open_port(index) + self.midiin.ignore_types(sysex=False, timing=True, active_sense=True) + self.midiout.open_port(index) + + def close(self) -> None: + self.midiout.close_port() + self.midiin.close_port() + + def read(self, address: int, size: int, memory: int = MEM_PRESET) -> bytes: + reply = transact(self.midiout, self.midiin, read_request(address, size, memory), expect=CMD_READ) + data = payload_data(reply) + return data[:size] + + def write(self, address: int, data: bytes, memory: int = MEM_PRESET) -> None: + transact(self.midiout, self.midiin, write_request(address, data, memory)) + + def __enter__(self) -> "Link": + return self + + def __exit__(self, *exc) -> None: + self.close() + + +def read_image(link: Link | None = None) -> bytes: + own = link is None + if link is None: + link = Link() + try: + got = bytearray() + while len(got) < IMAGE_LEN: + ask = min(READ_CHUNK, IMAGE_LEN - len(got)) + part = link.read(len(got), ask) + if not part: + raise PadError(f"empty read at {len(got)}") + got += part[:ask] + return bytes(got[:IMAGE_LEN]) + finally: + if own: + link.close() + + +def _port_names(kind: str) -> list[str]: + rtmidi = load_rtmidi() + probe = rtmidi.MidiOut(rtapi=rtmidi.API_LINUX_ALSA) if kind == "out" else rtmidi.MidiIn(rtapi=rtmidi.API_LINUX_ALSA) + try: + return list(probe.get_ports()) + finally: + del probe + + +def read_port_names() -> list[str]: + return _port_names("out") + + +def input_names() -> list[str]: + return _port_names("in") + + +def connected() -> str | None: + try: + return private_port(read_port_names()) + except PadError: + return None + + +def read_global(link: Link | None = None) -> bytes: + """The 12-byte settings block MidiSuite polls: tempo, swing, curve, transpose.""" + own = link is None + if link is None: + link = Link() + try: + data = link.read(0, GLOBAL_LEN, MEM_GLOBAL) + if len(data) < GLOBAL_LEN: + raise PadError(f"global block read {len(data)} bytes, expected {GLOBAL_LEN}") + return data[:GLOBAL_LEN] + 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. + + Returns how many bytes were written. An unchanged image still gets + MidiSuite's empty save, so Save always commits. The settings block, + when given and changed, is written whole, as MidiSuite does. + """ + if len(desired) != IMAGE_LEN: + raise PadError(f"preset image is {len(desired)} bytes, expected {IMAGE_LEN}") + if settings is not None and len(settings) != GLOBAL_LEN: + raise PadError(f"global block is {len(settings)} bytes, expected {GLOBAL_LEN}") + own = link is None + if link is None: + link = Link() + try: + current = read_image(link) + ranges = changed_ranges(current, desired, WRITE_CHUNK) + for address, data in ranges: + _write_checked(link, address, data) + written = sum(len(data) for _address, data in ranges) + if settings is not None and read_global(link) != settings: + link.write(0, settings, MEM_GLOBAL) + if read_global(link) != settings: + raise PadError("the pad did not keep the global settings") + written += len(settings) + _commit(link) + return written + finally: + if own: + link.close() + + +def write_colour(preset: int, index: int, rgb: tuple[int, int, int] | list[int]) -> int: + """Light one pad. The same three-byte write MidiSuite sends while its + colour picker moves. It does not commit; Save does that.""" + from padeditor.preset import colour_offset + + if len(rgb) != 3: + raise PadError("a pad colour needs red, green, and blue") + payload = bytes(int(channel) & 0xFF for channel in rgb) + offset = colour_offset(preset, index) + with Link() as link: + _write_checked(link, offset, payload) + return offset + + +def _write_checked(link: Link, address: int, data: bytes) -> None: + """Write the preset address, as MidiSuite does, then read it back.""" + link.write(address, data) + reply = transact(link.midiout, link.midiin, read_request(address, len(data))) + got = payload_data(reply) + if got[:len(data)] != data: + raise PadError( + f"read-back at {address:#x} was {got[:len(data)].hex()}, expected {data.hex()}" + ) + + +def _commit(link: Link) -> None: + reply = transact(link.midiout, link.midiin, save_request()) + if reply[:3] != b"\x00\x59\x00" or reply[6:7] != b"\x00": + raise PadError(f"the pad did not accept the save ({reply.hex()})") + + +def probe_relative(listen: float = 2.5) -> str: + """Try knob type 0x03 in RAM only, on every preset's last knob. + + Restores the original six bytes. Does not save. Returns ``relative`` + when a turn of that knob sends a step, ``absolute`` when it sends a + running value, or ``silent`` when nothing arrives. + """ + from padeditor.preset import KNOB_AT, KNOB_COUNT, KNOB_LEN, PRESET_COUNT, PRESET_LEN, RELATIVE_TYPE + + knob = KNOB_COUNT - 1 + offsets = [index * PRESET_LEN + KNOB_AT + knob * KNOB_LEN for index in range(PRESET_COUNT)] + rtmidi = load_rtmidi() + master_name = master_port(input_names()) + heard: list[tuple[int, int, int]] = [] + watched: set[tuple[int, int]] = set() + with Link() as link: + original = [link.read(offset, KNOB_LEN) for offset in offsets] + watched = {(rec[2], rec[3]) for rec in original} + try: + for offset, rec in zip(offsets, original): + link.write(RAM + offset, bytes((RELATIVE_TYPE,)) + rec[1:]) + heard = _listen_cc(rtmidi, master_name, listen) + finally: + for offset, rec in zip(offsets, original): + link.write(RAM + offset, rec) + matched = [item for item in heard if (item[0], item[1]) in watched] + return _classify(matched) + + +def _listen_cc(rtmidi, port_name: str, listen: float) -> list[tuple[int, int, int]]: + midiin = rtmidi.MidiIn(rtapi=rtmidi.API_LINUX_ALSA) + names = midiin.get_ports() + midiin.open_port(names.index(port_name)) + midiin.ignore_types(sysex=True, timing=True, active_sense=True) + found: list[tuple[int, int, int]] = [] + try: + deadline = time.time() + listen + while time.time() < deadline: + item = midiin.get_message() + if not item or not item[0]: + time.sleep(0.004) + continue + data = bytes(item[0]) + if len(data) >= 3 and (data[0] & 0xF0) == 0xB0: + found.append((data[0] & 0x0F, data[1], data[2])) + finally: + midiin.close_port() + return found + + +def _classify(messages: list[tuple[int, int, int]]) -> str: + if not messages: + return "silent" + values = [value for _channel, _cc, value in messages] + unique = set(values) + if unique <= {0, 1, 127} or unique <= {63, 64, 65} or _steps(values): + return "relative" + if len(unique) >= 4: + return "absolute" + return "silent" + + +def _steps(values: list[int]) -> bool: + """1..63 clockwise and 65..127 counter-clockwise, with no running ramp.""" + for value in values: + if value == 0 or value == 64 or value > 127: + return False + if value >= 16 and value <= 111: + return False + return True diff --git a/padeditor/preset.py b/padeditor/preset.py new file mode 100644 index 0000000..0be3f0f --- /dev/null +++ b/padeditor/preset.py @@ -0,0 +1,311 @@ +"""SMC-PAD preset image: 8 × 3539 bytes, the map MidiSuite edits.""" + +from __future__ import annotations + +IMAGE_LEN = 28312 +PRESET_LEN = 3539 +PRESET_COUNT = 8 + +BUTTON_COUNT = 5 +BUTTON_LEN = 23 +BUTTON_NAMES = ("Left", "Right", "Play", "Stop", "Record") + +KNOB_AT = 115 +KNOB_COUNT = 16 +KNOB_LEN = 6 +KNOB_BANK = 8 + +GAP_AT = 211 + +PAD_AT = 212 +PAD_LEN = 26 +PAD_COUNT = 128 +PAGE_LEN = 16 +PAGE_COUNT = 8 +RGB_AT = 4 + +# Global settings, memory type 4. Offsets are the fields MidiSuite's Glob +# panel showed against the factory block 78 00 32 04 00 00 02 00 01 01 00 00. +GLOBAL_LEN = 12 +GLOBAL_TEMPO = 0 # two bytes, little-endian +GLOBAL_SWING = 2 +GLOBAL_CURVE = 6 +GLOBAL_TRANSPOSE = 7 # signed + +# File bytes. Names are only values MidiSuite has shown for this pad's +# factory image, or a RAM probe on this pad has heard. +KNOB_TYPES = {0x00: "CC"} +BUTTON_TYPES = {0x02: "CC Push"} + +# Set after a RAM-only probe hears a relative step from type 0x03. +RELATIVE_TYPE = 0x03 +RELATIVE_CONFIRMED = False + +FULL = 0xF0 +SYSEX_ROOM = 16 # button bytes 6..21; byte 22 is the flag + + +def scale(value: int) -> int: + """Map 0–255 onto the pad's 0–240 colour range.""" + return (value * FULL + 127) // 255 + + +def knob_type_names() -> dict[int, str]: + names = dict(KNOB_TYPES) + if RELATIVE_CONFIRMED: + names[RELATIVE_TYPE] = "Relative" + return names + + +def type_catalog() -> dict[str, list[dict[str, int | str]]]: + def rows(names: dict[int, str]) -> list[dict[str, int | str]]: + return [{"value": value, "name": name} for value, name in sorted(names.items())] + + return { + "knob": rows(knob_type_names()), + "button": rows(BUTTON_TYPES), + } + + +class PresetError(ValueError): + pass + + +def _byte(value: object, label: str) -> int: + if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 255: + raise PresetError(f"{label} must be a byte") + return value + + +def _channel(value: object, label: str) -> int: + """MIDI channel 1–16 as stored, which is 0–15.""" + if isinstance(value, bool) or not isinstance(value, int) or not 1 <= value <= 16: + raise PresetError(f"{label} must be MIDI channel 1–16") + return value - 1 + + +def _hex(value: object, label: str) -> bytes: + if not isinstance(value, str) or len(value) % 2: + raise PresetError(f"{label} must be even-length hex") + try: + return bytes.fromhex(value) + except ValueError as exc: + raise PresetError(f"{label} is not hex") from exc + + +def unpack(image: bytes) -> dict: + if len(image) != IMAGE_LEN: + raise PresetError(f"preset image is {len(image)} bytes, expected {IMAGE_LEN}") + presets = [] + for index in range(PRESET_COUNT): + block = image[index * PRESET_LEN:(index + 1) * PRESET_LEN] + presets.append(_unpack_preset(block)) + return {"presets": presets, "types": type_catalog(), "relative": RELATIVE_CONFIRMED} + + +def pack(document: dict) -> bytes: + presets = document.get("presets") + if not isinstance(presets, list) or len(presets) != PRESET_COUNT: + raise PresetError(f"expected {PRESET_COUNT} presets") + out = bytearray() + for index, preset in enumerate(presets): + out += _pack_preset(preset, index) + if len(out) != IMAGE_LEN: + raise PresetError(f"packed {len(out)} bytes, expected {IMAGE_LEN}") + return bytes(out) + + +def colour_offset(preset: int, index: int) -> int: + """Where one pad's colour sits. MidiSuite writes only this address.""" + if not 0 <= preset < PRESET_COUNT: + raise PresetError(f"preset {preset + 1} is not on this controller") + if not 0 <= index < PAD_COUNT: + raise PresetError(f"pad {index + 1} is not on this controller") + return preset * PRESET_LEN + PAD_AT + index * PAD_LEN + RGB_AT + + +def unpack_global(raw: bytes) -> dict: + if len(raw) != GLOBAL_LEN: + raise PresetError(f"global block is {len(raw)} bytes, expected {GLOBAL_LEN}") + return { + "tempo": int.from_bytes(raw[GLOBAL_TEMPO:GLOBAL_TEMPO + 2], "little"), + "swing": raw[GLOBAL_SWING], + "curve": raw[GLOBAL_CURVE], + "transpose": int.from_bytes(raw[GLOBAL_TRANSPOSE:GLOBAL_TRANSPOSE + 1], "little", signed=True), + "raw": raw.hex(), + } + + +def pack_global(block: dict) -> bytes: + """The named fields over the bytes that were read, so unknown ones stay put.""" + out = bytearray(_hex(block.get("raw", ""), "global block")) + if len(out) != GLOBAL_LEN: + raise PresetError(f"global block is {len(out)} bytes, expected {GLOBAL_LEN}") + tempo = block.get("tempo") + if isinstance(tempo, bool) or not isinstance(tempo, int) or not 1 <= tempo <= 0xFFFF: + raise PresetError("tempo must be a whole number of BPM") + out[GLOBAL_TEMPO:GLOBAL_TEMPO + 2] = tempo.to_bytes(2, "little") + out[GLOBAL_SWING] = _byte(block.get("swing"), "swing") + out[GLOBAL_CURVE] = _byte(block.get("curve"), "pad curve") + transpose = block.get("transpose") + 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 + return bytes(out) + + +def changed_ranges(before: bytes, after: bytes, limit: int = 64) -> list[tuple[int, bytes]]: + """Coalesce differing bytes, then split each run into write-sized pieces.""" + if len(before) != len(after): + raise PresetError(f"cannot compare {len(before)} bytes with {len(after)}") + runs: list[tuple[int, int]] = [] + start = None + for index, (old, new) in enumerate(zip(before, after)): + if old != new: + if start is None: + start = index + elif start is not None: + runs.append((start, index)) + start = None + if start is not None: + runs.append((start, len(after))) + pieces: list[tuple[int, bytes]] = [] + for run_at, run_end in runs: + at = run_at + while at < run_end: + stop = min(run_end, at + limit) + pieces.append((at, after[at:stop])) + at = stop + return pieces + + +def _unpack_preset(block: bytes) -> dict: + buttons = [] + for index in range(BUTTON_COUNT): + rec = block[index * BUTTON_LEN:(index + 1) * BUTTON_LEN] + length = rec[5] + if length > SYSEX_ROOM: + sysex, padding = rec[6:22], b"" + else: + sysex, padding = rec[6:6 + length], rec[6 + length:22] + buttons.append({ + "name": BUTTON_NAMES[index], + "type": rec[0], + "channel": rec[1] + 1, + "number": rec[2], + "min": rec[3], + "max": rec[4], + "sysex": sysex.hex(), + "padding": padding.hex(), + "led": rec[22], + }) + knobs = [] + for index in range(KNOB_COUNT): + at = KNOB_AT + index * KNOB_LEN + rec = block[at:at + KNOB_LEN] + knobs.append({ + "type": rec[0], + "speed": rec[1], + "channel": rec[2] + 1, + "number": rec[3], + "left": rec[4], + "right": rec[5], + }) + pads = [] + for index in range(PAD_COUNT): + at = PAD_AT + index * PAD_LEN + rec = block[at:at + PAD_LEN] + pads.append({ + "channel": rec[0] + 1, + "note": rec[1], + "min": rec[2], + "max": rec[3], + "rgb": [rec[4], rec[5], rec[6]], + "led": rec[7], + "tail": rec[8:].hex(), + }) + return {"gap": block[GAP_AT], "buttons": buttons, "knobs": knobs, "pads": pads} + + +def _pack_preset(preset: dict, index: int) -> bytes: + out = bytearray(PRESET_LEN) + buttons = preset.get("buttons") + knobs = preset.get("knobs") + pads = preset.get("pads") + if not isinstance(buttons, list) or len(buttons) != BUTTON_COUNT: + raise PresetError(f"preset {index + 1} needs {BUTTON_COUNT} buttons") + if not isinstance(knobs, list) or len(knobs) != KNOB_COUNT: + raise PresetError(f"preset {index + 1} needs {KNOB_COUNT} knobs") + if not isinstance(pads, list) or len(pads) != PAD_COUNT: + raise PresetError(f"preset {index + 1} needs {PAD_COUNT} pads") + for number, button in enumerate(buttons): + out[number * BUTTON_LEN:(number + 1) * BUTTON_LEN] = _pack_button(button, index, number) + for number, knob in enumerate(knobs): + at = KNOB_AT + number * KNOB_LEN + out[at:at + KNOB_LEN] = _pack_knob(knob, index, number) + out[GAP_AT] = _byte(preset.get("gap", 0), f"preset {index + 1} gap") + for number, pad in enumerate(pads): + at = PAD_AT + number * PAD_LEN + rec = _pack_pad(pad, index, number) + room = PRESET_LEN - at + if len(rec) > room: + raise PresetError(f"preset {index + 1} pad {number + 1} does not fit") + out[at:at + len(rec)] = rec + return bytes(out) + + +def _pack_button(button: dict, preset: int, index: int) -> bytes: + label = f"preset {preset + 1} {BUTTON_NAMES[index]}" + sysex = _hex(button.get("sysex", ""), f"{label} sysex") + if len(sysex) > SYSEX_ROOM: + raise PresetError(f"{label} sysex is longer than {SYSEX_ROOM} bytes") + padding = _hex(button.get("padding", ""), f"{label} padding") + room = SYSEX_ROOM - len(sysex) + padding = padding[:room] + rec = bytearray(BUTTON_LEN) + rec[0] = _byte(button.get("type"), f"{label} type") + rec[1] = _channel(button.get("channel"), f"{label} channel") + rec[2] = _byte(button.get("number"), f"{label} number") + rec[3] = _byte(button.get("min"), f"{label} min") + rec[4] = _byte(button.get("max"), f"{label} max") + rec[5] = len(sysex) + rec[6:6 + len(sysex)] = sysex + rec[6 + len(sysex):22] = padding + bytes(room - len(padding)) + rec[22] = _byte(button.get("led"), f"{label} led") + return bytes(rec) + + +def _pack_knob(knob: dict, preset: int, index: int) -> bytes: + label = f"preset {preset + 1} knob {index + 1}" + # Any stored type byte round-trips. The editor only offers names it has seen. + return bytes(( + _byte(knob.get("type"), f"{label} type"), + _byte(knob.get("speed"), f"{label} speed"), + _channel(knob.get("channel"), f"{label} channel"), + _byte(knob.get("number"), f"{label} number"), + _byte(knob.get("left"), f"{label} left"), + _byte(knob.get("right"), f"{label} right"), + )) + + +def _pack_pad(pad: dict, preset: int, index: int) -> bytes: + label = f"preset {preset + 1} pad {index + 1}" + rgb = pad.get("rgb") + if not isinstance(rgb, list) or len(rgb) != 3: + raise PresetError(f"{label} colour needs three bytes") + tail = _hex(pad.get("tail", ""), f"{label} tail") + stored = PAD_LEN if index < PAD_COUNT - 1 else PRESET_LEN - (PAD_AT + (PAD_COUNT - 1) * PAD_LEN) + tail_room = stored - 8 + if len(tail) > tail_room: + raise PresetError(f"{label} tail is longer than {tail_room} bytes") + rec = bytearray(stored) + rec[0] = _channel(pad.get("channel"), f"{label} channel") + rec[1] = _byte(pad.get("note"), f"{label} note") + rec[2] = _byte(pad.get("min"), f"{label} min velocity") + rec[3] = _byte(pad.get("max"), f"{label} max velocity") + rec[4] = _byte(rgb[0], f"{label} red") + rec[5] = _byte(rgb[1], f"{label} green") + rec[6] = _byte(rgb[2], f"{label} blue") + rec[7] = _byte(pad.get("led"), f"{label} led") + rec[8:8 + len(tail)] = tail + return bytes(rec) diff --git a/padeditor/server.py b/padeditor/server.py new file mode 100644 index 0000000..7bed31d --- /dev/null +++ b/padeditor/server.py @@ -0,0 +1,195 @@ +"""Local editor: load the SMC-PAD preset, edit it, save it back.""" + +from __future__ import annotations + +import json +import mimetypes +import threading +import traceback +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.preset import IMAGE_LEN, PresetError, pack, pack_global, unpack, unpack_global + +STATIC_DIR = Path(__file__).parent / "static" + + +class ApiError(Exception): + def __init__(self, message: str, status: int = 400): + super().__init__(message) + self.status = status + + +class Editor: + def __init__(self): + self.lock = threading.Lock() + + def status(self) -> dict: + port = connected() + return {"connected": port is not None, "port": port} + + def load(self) -> dict: + with self.lock: + try: + with Link() as link: + document = unpack(read_image(link)) + document["global"] = unpack_global(read_global(link)) + return document + except PadError as exc: + raise ApiError(str(exc), 503) from exc + + def save(self, document: dict) -> dict: + try: + desired = pack(document) + block = document.get("global") + settings = pack_global(block) if isinstance(block, dict) else None + except PresetError as exc: + raise ApiError(str(exc)) from exc + with self.lock: + try: + written = save_image(desired, settings=settings) + except PadError as exc: + raise ApiError(str(exc), 503) from exc + if written: + message = f"Saved on the pad. {written} bytes written." + else: + message = "Saved on the pad." + return {"ok": True, "message": message, "bytes": written} + + def colour(self, body: dict) -> dict: + try: + preset = int(body["preset"]) + index = int(body["index"]) + rgb = body["rgb"] + if not isinstance(rgb, list) or len(rgb) != 3: + raise PresetError("a pad colour needs red, green, and blue") + except (KeyError, TypeError, ValueError) as exc: + raise ApiError("colour needs a preset, a pad, and an rgb colour") from exc + with self.lock: + try: + offset = write_colour(preset, index, rgb) + except PresetError as exc: + raise ApiError(str(exc)) from exc + except PadError as exc: + raise ApiError(str(exc), 503) from exc + return {"ok": True, "offset": offset} + + def imported(self, raw: bytes) -> dict: + try: + return unpack(raw) + except PresetError as exc: + raise ApiError(str(exc)) from exc + + def exported(self, document: dict) -> bytes: + try: + return pack(document) + except PresetError as exc: + raise ApiError(str(exc)) from exc + + +def make_server(host: str = "127.0.0.1", port: int = 8770) -> ThreadingHTTPServer: + editor = Editor() + handler = type("BoundHandler", (Handler,), {"editor": editor}) + server = ThreadingHTTPServer((host, port), handler) + server.editor = editor # type: ignore[attr-defined] + return server + + +class Handler(BaseHTTPRequestHandler): + editor: Editor + + def log_message(self, fmt: str, *args) -> None: + return + + def _json(self, status: int, body: dict) -> None: + raw = json.dumps(body).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(raw))) + self.send_header("Cache-Control", "no-store") + self.end_headers() + self.wfile.write(raw) + + def _bytes(self, raw: bytes, content_type: str, filename: str | None = None) -> None: + self.send_response(200) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(raw))) + self.send_header("Cache-Control", "no-store") + if filename: + self.send_header("Content-Disposition", f'attachment; filename="{filename}"') + self.end_headers() + self.wfile.write(raw) + + def _read(self) -> bytes: + n = int(self.headers.get("Content-Length") or 0) + return self.rfile.read(n) if n > 0 else b"" + + def _json_body(self) -> dict: + raw = self._read() + if not raw: + return {} + try: + body = json.loads(raw.decode("utf-8")) + except json.JSONDecodeError as exc: + raise ApiError(f"invalid JSON: {exc}") from exc + if not isinstance(body, dict): + raise ApiError("expected a JSON object") + return body + + def _static(self, rel: str) -> None: + rel = rel.lstrip("/") or "index.html" + path = (STATIC_DIR / rel).resolve() + if STATIC_DIR.resolve() not in path.parents or not path.is_file(): + self.send_error(404) + return + ctype = mimetypes.guess_type(path.name)[0] or "application/octet-stream" + if ctype.startswith("text/") or ctype.endswith(("javascript", "json")): + ctype = f"{ctype}; charset=utf-8" + self._bytes(path.read_bytes(), ctype) + + def _dispatch(self, method: str) -> None: + url = urlparse(self.path) + editor = self.editor + try: + if not url.path.startswith("/api/"): + if method != "GET": + self.send_error(405) + return + if url.path == "/favicon.ico": + self.send_response(204) + self.send_header("Content-Length", "0") + self.end_headers() + return + self._static(url.path) + return + route = (method, url.path) + if route == ("GET", "/api/status"): + self._json(200, editor.status()) + elif route == ("POST", "/api/load"): + self._json(200, editor.load()) + elif route == ("POST", "/api/save"): + 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/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/export"): + self._bytes(editor.exported(self._json_body()), "application/octet-stream", "smc-pad-preset.bin") + else: + self._json(404, {"error": f"no route {method} {url.path}"}) + except ApiError as exc: + self._json(exc.status, {"error": str(exc)}) + except Exception as exc: # noqa: BLE001 — surface anything else to the UI + traceback.print_exc() + self._json(500, {"error": f"{type(exc).__name__}: {exc}"}) + + def do_GET(self) -> None: # noqa: N802 + self._dispatch("GET") + + def do_POST(self) -> None: # noqa: N802 + self._dispatch("POST") diff --git a/padeditor/static/app.js b/padeditor/static/app.js new file mode 100644 index 0000000..a09a44e --- /dev/null +++ b/padeditor/static/app.js @@ -0,0 +1,441 @@ +const PAGE = 16; +const state = { + doc: null, + saved: null, + preset: 0, + page: 2, + bank: 0, + kind: null, + index: 0, +}; + +const $ = (id) => document.getElementById(id); + +// Colours are stored as the picker gives them, 0–255, as MidiSuite writes them. +function cssColour(rgb) { + return `rgb(${rgb.join(",")})`; +} + +function ink(rgb) { + const [r, g, b] = rgb; + return (r * 0.3 + g * 0.59 + b * 0.11) > 150 ? "#111" : "#f4f6fb"; +} + +function hexColour(rgb) { + return `#${rgb.map((part) => part.toString(16).padStart(2, "0")).join("")}`; +} + +function setStatus(text, kind) { + const node = $("status"); + node.textContent = text; + node.className = kind || ""; +} + +function dirty() { + return state.doc !== null && JSON.stringify(state.doc) !== state.saved; +} + +function preset() { + return state.doc.presets[state.preset]; +} + +function selected() { + if (!state.doc || !state.kind) return null; + const block = preset(); + if (state.kind === "pad") return block.pads[state.page * PAGE + state.index]; + if (state.kind === "knob") return block.knobs[state.bank * 8 + state.index]; + return block.buttons[state.index]; +} + +function typeChoices(kind, current) { + const known = (state.doc.types && state.doc.types[kind]) || []; + const options = known.map((item) => ({ value: item.value, name: item.name })); + if (!options.some((item) => item.value === current)) { + const hex = current.toString(16).padStart(2, "0"); + options.push({ value: current, name: `0x${hex}` }); + } + return options; +} + +async function request(url, options) { + const response = await fetch(url, options); + const type = response.headers.get("Content-Type") || ""; + if (type.includes("application/json")) { + const body = await response.json(); + if (!response.ok) throw new Error(body.error || response.statusText); + return body; + } + if (!response.ok) throw new Error(response.statusText); + return response.blob(); +} + +function mark() { + const unsaved = dirty(); + $("save").disabled = !state.doc; + $("export").disabled = !state.doc; + $("save").classList.toggle("dirty", unsaved); + return unsaved; +} + +function touch() { + if (mark()) setStatus("Not saved on the pad.", "dirty"); + else setStatus("No unsaved edits.", "ok"); +} + +function showEmpty(text, kind) { + const node = $("empty"); + node.hidden = false; + node.textContent = text; + node.className = kind || ""; + $("board").classList.remove("ready"); +} + +async function load(manual) { + if (manual && dirty() && !window.confirm("Load from the pad and drop these edits?")) return; + setStatus("Loading the pad…"); + showEmpty("Loading the pad…"); + try { + state.doc = await request("/api/load", { method: "POST" }); + state.saved = JSON.stringify(state.doc); + render(); + setStatus("Loaded from the pad.", "ok"); + } catch (error) { + setStatus(error.message, "err"); + showEmpty(error.message, "err"); + } +} + +async function save() { + if (!state.doc) return; + setStatus("Saving…"); + $("save").disabled = true; + try { + const body = await request("/api/save", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(state.doc), + }); + state.saved = JSON.stringify(state.doc); + setStatus(body.message, "ok"); + } catch (error) { + setStatus(error.message, "err"); + } + mark(); +} + +async function exportFile() { + if (!state.doc) return; + try { + const blob = await request("/api/export", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(state.doc), + }); + const url = URL.createObjectURL(blob); + const link = document.createElement("a"); + link.href = url; + link.download = "smc-pad-preset.bin"; + link.click(); + URL.revokeObjectURL(url); + } catch (error) { + setStatus(error.message, "err"); + } +} + +async function importFile(file) { + setStatus("Reading file…"); + try { + const raw = new Uint8Array(await file.arrayBuffer()); + state.doc = await request("/api/import", { + method: "POST", + headers: { "Content-Type": "application/octet-stream" }, + body: raw, + }); + render(); + setStatus("Imported. Save to pad to store it.", "dirty"); + } catch (error) { + setStatus(error.message, "err"); + } +} + +function render() { + if (!state.doc) return; + $("board").classList.add("ready"); + renderGlobal(); + renderPresets(); + renderPages(); + renderPads(); + renderKnobs(); + renderButtons(); + renderInspector(); + mark(); +} + +function renderGlobal() { + const row = $("global"); + row.replaceChildren(); + const block = state.doc.global; + if (!block) return; + const fields = [ + ["Tempo", "tempo", 1, 999], + ["Swing", "swing", 0, 255], + ["Pad curve", "curve", 0, 255], + ["Transpose", "transpose", -128, 127], + ]; + for (const [label, key, min, max] of fields) { + row.append(field(label, numberInput(block, key, min, max))); + } +} + +function renderPresets() { + const row = $("presets"); + row.replaceChildren(); + state.doc.presets.forEach((_preset, index) => { + const button = document.createElement("button"); + button.type = "button"; + button.textContent = String(index + 1); + button.classList.toggle("selected", index === state.preset); + button.addEventListener("click", () => { + state.preset = index; + render(); + }); + row.append(button); + }); +} + +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" }; + for (const page of order) { + const pads = preset().pads.slice(page * PAGE, page * PAGE + PAGE); + const option = document.createElement("option"); + option.value = String(page); + const name = names[page] || `Page ${page + 1}`; + option.textContent = `${name} · notes ${pads[0].note}–${pads[PAGE - 1].note}`; + select.append(option); + } + select.value = current || String(state.page); + state.page = Number(select.value); + const pads = preset().pads.slice(state.page * PAGE, state.page * PAGE + PAGE); + $("page-notes").textContent = `notes ${pads[0].note}–${pads[PAGE - 1].note}`; +} + +function paint(node, rgb) { + node.style.background = cssColour(rgb); + node.style.color = ink(rgb); +} + +function renderPads() { + const grid = $("pads"); + grid.replaceChildren(); + const pads = preset().pads; + for (let row = 3; row >= 0; row -= 1) { + for (let col = 0; col < 4; col += 1) { + const index = row * 4 + col; + const pad = pads[state.page * PAGE + index]; + const button = document.createElement("button"); + button.type = "button"; + button.className = "pad"; + button.textContent = String(index + 1); + paint(button, pad.rgb); + button.style.opacity = pad.led ? "" : "0.35"; + button.classList.toggle("selected", state.kind === "pad" && state.index === index); + button.addEventListener("click", () => select("pad", index)); + grid.append(button); + } + } +} + +function renderKnobs() { + const row = $("knobs"); + row.replaceChildren(); + for (let index = 0; index < 8; index += 1) { + const knob = preset().knobs[state.bank * 8 + index]; + const button = document.createElement("button"); + button.type = "button"; + button.className = "knob"; + button.textContent = String(state.bank * 8 + index + 1); + button.title = `CC ${knob.number}`; + button.classList.toggle("selected", state.kind === "knob" && state.index === index); + button.addEventListener("click", () => select("knob", index)); + row.append(button); + } +} + +function renderButtons() { + const row = $("buttons"); + row.replaceChildren(); + preset().buttons.forEach((button, index) => { + const node = document.createElement("button"); + node.type = "button"; + node.className = "btn"; + node.textContent = button.name; + node.classList.toggle("selected", state.kind === "button" && state.index === index); + node.addEventListener("click", () => select("button", index)); + row.append(node); + }); +} + +let colourTimer = 0; + +function paintColour(index, rgb) { + const edited = state.preset; + preset().pads[index].rgb = rgb.slice(); + renderPads(); + window.clearTimeout(colourTimer); + colourTimer = window.setTimeout(() => sendColour(edited, index, rgb), 180); +} + +async function sendColour(preset, index, rgb) { + try { + await request("/api/colour", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ preset, index, rgb }), + }); + } catch (error) { + setStatus(error.message, "err"); + } +} + +function select(kind, index) { + state.kind = kind; + state.index = index; + render(); +} + +function field(label, node) { + const wrap = document.createElement("label"); + wrap.className = "field"; + wrap.append(label, node); + return wrap; +} + +function numberInput(item, key, min, max) { + const input = document.createElement("input"); + input.type = "number"; + input.min = String(min); + input.max = String(max); + input.value = String(item[key]); + input.addEventListener("input", () => { + const value = Number(input.value); + if (!Number.isInteger(value) || value < min || value > max) return; + item[key] = value; + if (key === "led") renderPads(); + if (key === "note") { + const pads = preset().pads.slice(state.page * PAGE, state.page * PAGE + PAGE); + $("page-notes").textContent = `notes ${pads[0].note}–${pads[PAGE - 1].note}`; + } + touch(); + }); + return input; +} + +function renderInspector() { + const aside = $("inspector"); + const item = selected(); + aside.replaceChildren(); + const title = document.createElement("h2"); + if (!item) { + title.textContent = "Control"; + const note = document.createElement("p"); + note.className = "muted"; + note.textContent = "Pick a pad, knob, or button."; + aside.append(title, note); + return; + } + if (state.kind === "pad") title.textContent = `Pad ${state.index + 1}`; + else if (state.kind === "knob") title.textContent = `Knob ${state.bank * 8 + state.index + 1}`; + else title.textContent = item.name; + aside.append(title); + + if (state.kind !== "pad") { + const type = document.createElement("select"); + typeChoices(state.kind, item.type).forEach((option) => { + const node = document.createElement("option"); + node.value = String(option.value); + node.textContent = option.name; + node.selected = option.value === item.type; + type.append(node); + }); + type.addEventListener("change", () => { + item.type = Number(type.value); + touch(); + }); + aside.append(field(state.kind === "button" ? "Mode" : "Type", type)); + } + aside.append(field("Channel", numberInput(item, "channel", 1, 16))); + + if (state.kind === "pad") { + aside.append(field("Note", numberInput(item, "note", 0, 127))); + aside.append(field("Min velocity", numberInput(item, "min", 0, 127))); + aside.append(field("Max velocity", numberInput(item, "max", 0, 127))); + const colour = document.createElement("input"); + colour.type = "color"; + colour.value = hexColour(item.rgb); + colour.addEventListener("input", () => { + const hex = colour.value; + const rgb = [1, 3, 5].map((at) => parseInt(hex.slice(at, at + 2), 16)); + paintColour(state.page * PAGE + state.index, rgb); + touch(); + }); + aside.append(field("Colour", colour)); + aside.append(field("Led", numberInput(item, "led", 0, 255))); + } else if (state.kind === "knob") { + aside.append(field("CC", numberInput(item, "number", 0, 127))); + aside.append(field("Speed", numberInput(item, "speed", 0, 127))); + aside.append(field("Min", numberInput(item, "left", 0, 127))); + aside.append(field("Max", numberInput(item, "right", 0, 127))); + if (state.doc.relative) { + const hint = document.createElement("p"); + hint.className = "hint"; + hint.textContent = "Relative sends the left value one way and the right value the other."; + aside.append(hint); + } + } else { + aside.append(field("CC", numberInput(item, "number", 0, 127))); + aside.append(field("Value 1", numberInput(item, "min", 0, 127))); + aside.append(field("Value 2", numberInput(item, "max", 0, 127))); + aside.append(field("Led", numberInput(item, "led", 0, 255))); + const sysex = document.createElement("input"); + sysex.type = "text"; + sysex.value = item.sysex; + sysex.spellcheck = false; + sysex.addEventListener("input", () => { + const hex = sysex.value.replace(/\s+/g, "").toLowerCase(); + if (hex.length % 2 || /[^0-9a-f]/.test(hex) || hex.length > 32) return; + item.sysex = hex; + touch(); + }); + aside.append(field("SysEx", sysex)); + } + + const hint = document.createElement("p"); + hint.className = "hint"; + hint.textContent = "A pad colour lights the lamp as you pick it. Save keeps every edit after a power cycle."; + aside.append(hint); +} + +$("load").addEventListener("click", () => load(true)); +$("save").addEventListener("click", save); +$("export").addEventListener("click", exportFile); +$("import").addEventListener("change", () => { + const file = $("import").files[0]; + $("import").value = ""; + if (file) importFile(file); +}); +$("page").addEventListener("change", () => { + state.page = Number($("page").value); + state.kind = state.kind === "pad" ? null : state.kind; + render(); +}); +$("bank").addEventListener("change", () => { + state.bank = Number($("bank").value); + state.kind = state.kind === "knob" ? null : state.kind; + render(); +}); + +load(false); diff --git a/padeditor/static/index.html b/padeditor/static/index.html new file mode 100644 index 0000000..8000bcb --- /dev/null +++ b/padeditor/static/index.html @@ -0,0 +1,45 @@ + + +
+ + +Loading the pad…
+ + +