Added support for coloring Rekordbox hotcues

This commit is contained in:
patben8 committed 2026-10-01 10:54:14 +02:00
1 parent 9be2c029b2
commit 08c53e1150
19 files changed
+337 -45

No files matched your search

@@ -287,6 +287,9 @@ class OneLibraryAdapter:
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> TrackCues:
self._refuse("Editing cues")
def set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues:
self._refuse("Editing cues")
def delete_cue(self, track_id: str, slot: int) -> TrackCues:
self._refuse("Deleting cues")
@@ -21,13 +21,13 @@ from __future__ import annotations
from pathlib import Path
from ...core.adapter import Unsupported
from ...core.adapter import InvalidCommand, Unsupported
from ...core.capabilities import Capabilities
from ...core.model import GridMarker, PlaylistNode, Track, TrackCues
from ...core.pathmap import PathMapping, common_dir_prefix
from ...core.query import TrackIndex
from . import capabilities as caps
from . import projection
from . import palette, projection
from .store import RekordboxStore
@@ -297,6 +297,18 @@ class RekordboxAdapter:
self._store.set_cue_type(track_id, slot, cue_type)
return self._refresh_cues(track_id)
def set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues:
self._require_writable("Editing cues")
code = None
if color is not None:
code = palette.swatch_code(color)
if code is None:
raise InvalidCommand(
f"{color!r} is not one of Rekordbox's hot cue colours"
)
self._store.set_cue_color(track_id, slot, code)
return self._refresh_cues(track_id)
def delete_cue(self, track_id: str, slot: int) -> TrackCues:
self._require_writable("Deleting cues")
self._store.delete_cue(track_id, slot)
@@ -30,6 +30,7 @@ from ...core.capabilities import (
SaveCapabilities,
TrackCapabilities,
)
from . import palette
from .cue_types import WRITABLE_CUE_TYPES
# Rekordbox's addressable hot cue bank. The pads are labelled A-H; the stored
@@ -68,8 +69,10 @@ def capabilities_for(
max_memory_cues=None, # unlimited
# Both cue types write; Rekordbox has no fade/load types.
types=WRITABLE_CUE_TYPES,
# A hot cue's colour is one of rekordbox's swatches (the 15 that
# were measured, see `palette`), offered in rekordbox's own order.
color="palette",
palette=[], # TODO milestone 2: the built-in cue colour table
palette=[palette.hex_for(code) for code in palette.SWATCHES],
named=True, # djmdCue.Comment
loops="cue_type",
),
@@ -91,3 +91,28 @@ def code_for(color: str | None) -> tuple[int, tuple[int, int, int]]:
return min(d, 1 - d)
best = min((c for c in PALETTE if c != 0x2B), key=hue_gap)
return best, PALETTE[best]
#: The swatches a user can pick, in rekordbox's own order — what
#: `capabilities.cues.palette` offers. 15 of rekordbox's 16: the unmeasured
#: teal-green is left out rather than offered with a guessed RGB, and 0x2B is
#: not a swatch at all (see the module note).
SWATCHES: list[int] = [code for code in PALETTE if code != 0x2B]
def hex_for(code: int | None) -> str | None:
"""`#RRGGBB` for a stored palette code; None for uncoloured or unknown.
An unknown code (the unmeasured teal-green) projects as no colour rather
than a guessed one; it is still kept on the row, since editing a cue's
position, type or name never rewrites its colour.
"""
rgb = PALETTE.get(code) if code else None
return None if rgb is None else f"#{rgb[0]:02X}{rgb[1]:02X}{rgb[2]:02X}"
def swatch_code(color: str) -> int | None:
"""The code of an EXACT palette colour, else None — for a user's pick, which
must be a swatch, unlike `code_for`'s nearest-hue mapping for exports."""
rgb = _parse(color)
return next((code for code, value in PALETTE.items() if value == rgb), None)
@@ -8,7 +8,7 @@ from __future__ import annotations
import re
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
from . import beatgrid, timebase
from . import beatgrid, palette, timebase
from .cue_types import cue_type, role_and_slot
# Rekordbox names keys musically ("Abm", "F", "Ebm") rather than in Camelot or
@@ -100,7 +100,7 @@ def _name_of(related) -> str | None:
def to_track(row, cue_kinds=()) -> Track:
"""Project one ``DjmdContent`` row.
`cue_kinds` is this track's ``(Kind, OutMsec)`` pairs from the store's single
`cue_kinds` is this track's ``(Kind, OutMsec, ColorTableIndex)`` from the store's single
query — passed in rather than read off the row, which would be a per-track
round trip. "Is this a hot cue, and on which pad?" is `role_and_slot`, the
same definition `to_track_cues` uses, so the table's count and dots agree
@@ -118,12 +118,11 @@ def to_track(row, cue_kinds=()) -> Track:
BPM are precisely the 22 with no grid.
"""
chips: list[HotcueChip] = []
for kind, out_msec in cue_kinds:
for kind, out_msec, color_code in cue_kinds:
role, slot = role_and_slot(kind)
if role == "hotcue" and slot is not None:
# Rekordbox's colour is a palette index nobody has decoded yet (see
# `_cue_color`), so no colour is claimed and the UI uses the type's.
chips.append(HotcueChip(slot=slot, type=cue_type(out_msec), color=None))
chips.append(HotcueChip(slot=slot, type=cue_type(out_msec),
color=palette.hex_for(color_code)))
chips.sort(key=lambda chip: chip.slot)
key_name = _name_of(getattr(row, "Key", None))
wheel, mode = parse_key(key_name)
@@ -210,11 +209,6 @@ def to_track_cues(cue_rows: list, grid: tuple | None, time_offset: float = 0.0)
def _cue_color(row) -> str | None:
"""Rekordbox stores a PALETTE INDEX, not an RGB value.
The generic model carries ``#RRGGBB``, and the built-in palette that index
refers to is not yet known, so no colour is claimed rather than a wrong one
being invented. `capabilities.cues.color` already says "palette", so the UI
knows not to offer a free colour picker.
"""
return None
"""Rekordbox stores a PALETTE CODE (`ColorTableIndex`), not an RGB value;
`Color` is -1 on a coloured cue. A loop's uncoloured convention is code 0."""
return palette.hex_for(getattr(row, "ColorTableIndex", None))
+44 -20
View File
@@ -192,8 +192,9 @@ class RekordboxStore:
raise NotFound(f"No track {track_id!r}")
return row
def cue_kinds(self) -> dict[str, list[tuple[int | None, int | None]]]:
"""``{track_id: [(Kind, OutMsec), ...]}`` for every live cue, in one query.
def cue_kinds(self) -> dict[str, list[tuple[int | None, int | None, int | None]]]:
"""``{track_id: [(Kind, OutMsec, ColorTableIndex), ...]}`` for every live
cue, in one query.
Just enough per cue for the library table's count and hotcue dots,
without a per-track round trip. What a ``Kind`` means is decided in the
@@ -202,12 +203,13 @@ class RekordboxStore:
"""
t = self._tables
rows = self._db.session.execute(
select(t.DjmdCue.ContentID, t.DjmdCue.Kind, t.DjmdCue.OutMsec)
select(t.DjmdCue.ContentID, t.DjmdCue.Kind, t.DjmdCue.OutMsec,
t.DjmdCue.ColorTableIndex)
.where(t.DjmdCue.rb_local_deleted == 0)
).all()
out: dict[str, list[tuple[int | None, int | None]]] = {}
for content_id, kind, out_msec in rows:
out.setdefault(str(content_id), []).append((kind, out_msec))
out: dict[str, list[tuple[int | None, int | None, int | None]]] = {}
for content_id, kind, out_msec, color_code in rows:
out.setdefault(str(content_id), []).append((kind, out_msec, color_code))
return out
def cues(self, track_id: str) -> list:
@@ -651,13 +653,17 @@ class RekordboxStore:
) -> None:
"""Create or replace the cue in `slot`. A loop is a cue with a length.
`color_code` is a rekordbox palette code (`palette.PALETTE`); None or 0
writes the uncoloured convention, which is what every edit through the
adapter does — only the exporter passes a colour.
`color_code` is a rekordbox palette code (`palette.PALETTE`). None KEEPS
the colour of the cue already in the slot — the colour belongs to the
pad, so a rename, a type change or an Auto Hotcues Replace leaves it as
the user set it — and a new cue is uncoloured. Only `set_cue_color`
clears one.
"""
if int(slot) < 0:
raise InvalidCommand(f"Hot cue slot cannot be negative, got {slot}")
existing = self._cue_row(track_id, slot)
if color_code is None and existing is not None:
color_code = existing.ColorTableIndex or None
self._write_cue(
track_id, existing, kind=kind_for("hotcue", slot), start_sec=start_sec,
cue_type=cue_type, length_sec=length_sec, name=name, color_code=color_code,
@@ -730,26 +736,44 @@ class RekordboxStore:
cue.BeatLoopSize = beat_loop_size(beats) if beats else None
cue.ActiveLoop = 0
cue.CueMicrosec = 0
cue.Color = 255
cue.ColorTableIndex = 0
else:
cue.BeatLoopSize = None
cue.ActiveLoop = None
cue.CueMicrosec = None
cue.Color = -1
cue.ColorTableIndex = None
if color_code:
# A palette-coloured cue, as the real library stores one: the code in
# ColorTableIndex (22 = green), Color -1. How rekordbox stores a
# COLOURED LOOP is not in the reference library; the same column is
# assumed and is what the smoke test checks.
cue.ColorTableIndex = int(color_code)
cue.Color = -1
self._apply_color(cue, color_code, is_loop)
cue.Comment = name or None
self._db.flush()
self._sync_content_cue(track_id)
@staticmethod
def _apply_color(cue, color_code: int | None, is_loop: bool) -> None:
"""A row's two colour columns — the one definition of both conventions."""
if color_code:
# A palette-coloured cue, as the real library stores one: the code in
# ColorTableIndex (22 = green), Color -1. Coloured loops store the
# same; verified in Rekordbox 7 through the master.db export.
cue.ColorTableIndex = int(color_code)
cue.Color = -1
elif is_loop:
# What Rekordbox writes on the loops and auto-cues it creates.
cue.Color = 255
cue.ColorTableIndex = 0
else:
cue.Color = -1
cue.ColorTableIndex = None
def set_cue_color(self, track_id: str, slot: int, color_code: int | None) -> None:
"""Recolour the cue in `slot`; None makes it uncoloured. Touches only the
colour columns, so the position does not take a time-base round trip."""
cue = self._cue_row(track_id, slot)
if cue is None:
raise NotFound(f"No cue in slot {slot}")
self._apply_color(cue, color_code, (cue.OutMsec or 0) > 0)
self._db.flush()
self._sync_content_cue(track_id)
self._journal.record("cue", "modify", track_id, f"slot:{slot}")
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> None:
cue = self._cue_row(track_id, slot)
if cue is None:
@@ -287,6 +287,10 @@ class TraktorAdapter:
self._store.set_hotcue_type(track_id, slot, self._native_cue_type(cue_type))
return self._refresh(track_id)
def set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues:
# Traktor colours a cue by its type (capabilities.cues.color = "none").
raise Unsupported("Traktor colours cues by their type")
def delete_cue(self, track_id: str, slot: int) -> TrackCues:
with _translate():
self._store.delete_hotcue(track_id, slot)
@@ -49,7 +49,9 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
# Traktor has no memory cues — every cue occupies a bank slot.
memory_cues=False,
types=CUE_TYPES,
color="free",
# Traktor colours a cue by its TYPE; the only COLOR it stores is a
# grid marker's white companion, so there is nothing to pick.
color="none",
named=True,
# A saved loop is a cue TYPE in Traktor, not a separate bank.
loops="cue_type",
+3
View File
@@ -161,6 +161,9 @@ class LibraryAdapter(Protocol):
name: str | None = None,
) -> TrackCues: ...
def set_cue_type(self, track_id: str, slot: int, cue_type: str) -> TrackCues: ...
# `color` is "#RRGGBB" from `capabilities().cues.palette`, or None for the
# platform's uncoloured cue. Any other cue command keeps a slot's colour.
def set_cue_color(self, track_id: str, slot: int, color: str | None) -> TrackCues: ...
def delete_cue(self, track_id: str, slot: int) -> TrackCues: ...
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues: ...
+7
View File
@@ -88,6 +88,7 @@ from .schemas import (
SourceCandidate,
SourceStatus,
SetCue,
SetCueColor,
SetCueType,
SetGridLock,
Stats,
@@ -1151,6 +1152,12 @@ def edit_cue_type(body: SetCueType) -> TrackCues:
return require_adapter().set_cue_type(body.track_id, body.slot, body.type)
@app.patch("/api/tracks/cue/color", response_model=TrackCues)
def edit_cue_color(body: SetCueColor) -> TrackCues:
"""Recolour an existing cue from the platform's palette (None = uncoloured)."""
return require_adapter().set_cue_color(body.track_id, body.slot, body.color)
@app.delete("/api/tracks/cue", response_model=TrackCues)
def delete_cue(track_id: str, slot: int) -> TrackCues:
"""Remove the hotcue in a slot."""
+6
View File
@@ -146,6 +146,12 @@ class SetCueType(BaseModel):
type: CueType
class SetCueColor(BaseModel):
track_id: str
slot: int
color: str | None = None # a capabilities.cues.palette entry; None = uncoloured
class EditState(BaseModel):
dirty: bool # unsaved in-memory changes exist
library: LibraryInfo
+1
View File
@@ -320,6 +320,7 @@ COMMANDS = [
("set_playlist_entries", lambda: adapter.set_playlist_entries(node.id, [])),
("set_cue", lambda: adapter.set_cue(one.id, slot=0, start_sec=1.0, cue_type="cue")),
("set_cue_type", lambda: adapter.set_cue_type(one.id, 0, "loop")),
("set_cue_color", lambda: adapter.set_cue_color(one.id, 0, "#FF0000")),
("delete_cue", lambda: adapter.delete_cue(one.id, 0)),
("place_cues", lambda: adapter.place_cues(one.id, [])),
("add_grid_marker", lambda: adapter.add_grid_marker(one.id, 1.0)),
+85
View File
@@ -14,6 +14,7 @@ import shutil
import sys
import tempfile
import warnings
from types import SimpleNamespace
from pathlib import Path
warnings.filterwarnings("ignore")
@@ -31,6 +32,7 @@ from konduktor.adapters.rekordbox.cue_types import ( # noqa: E402
kind_for,
role_and_slot,
)
from konduktor.adapters.rekordbox import palette # noqa: E402
from konduktor.adapters.rekordbox.driver import RekordboxDriver # noqa: E402
from konduktor.adapters.rekordbox.projection import parse_key # noqa: E402
from konduktor.core import registry # noqa: E402
@@ -88,6 +90,21 @@ check("pad H is Kind 9", kind_for("hotcue", 7) == 9)
check("BeatLoopSize encodes (beats << 16) | 1", beat_loop_size(4) == 262145 and beat_loop_size(1) == 65537)
check("and decodes back", beats_in_loop(262145) == 4 and beats_in_loop(None) is None)
print("== hot cue colour palette ==")
# rekordbox has 16; the teal-green between 0x0E and 0x16 was never measured, and
# is left out rather than offered with a guessed RGB.
check("15 pickable swatches, without the observed-only red",
len(palette.SWATCHES) == 15 and 0x2B not in palette.SWATCHES)
check("a code projects as its measured RGB", palette.hex_for(0x16) == "#1AFF00")
check("uncoloured (None, or a loop's 0) projects as no colour",
palette.hex_for(None) is None and palette.hex_for(0) is None)
# The unmeasured teal-green is probably 0x12: claim nothing rather than guess.
check("an unknown code projects as no colour", palette.hex_for(0x12) is None)
check("a swatch maps back to its code, case-insensitively",
all(palette.swatch_code(palette.hex_for(c).lower()) == c for c in palette.SWATCHES))
# A user's pick must BE a swatch; nearest-hue is the exporter's rule, not an edit's.
check("a non-palette colour is not a swatch", palette.swatch_code("#123456") is None)
print("== key parsing (Rekordbox names keys musically, not in Camelot) ==")
check("Fm -> 4A", parse_key("Fm") == (4, "minor"))
check("Am -> 8A", parse_key("Am") == (8, "minor"))
@@ -303,6 +320,9 @@ with tempfile.TemporaryDirectory() as d:
# library, and the opposite of what the original plan assumed.
check("a loop is a cue type, not a separate bank", caps.cues.loops == "cue_type")
check("cue colour is a palette, not free RGB", caps.cues.color == "palette")
check("and the palette is the measured swatches",
caps.cues.palette == [palette.hex_for(c) for c in palette.SWATCHES],
str(caps.cues.palette))
check("the editable field set is advertised", bool(caps.tracks.editable_fields))
# Rekordbox has no column for these; Traktor does. Mapping them onto its
# Composer field would silently write the wrong thing.
@@ -428,6 +448,71 @@ with tempfile.TemporaryDirectory() as d:
_raises(lambda: adapter.set_cue(cue_track.id, slot=2, start_sec=-1.0,
cue_type="cue"), InvalidCommand))
print("== hot cue colours ==")
# Slot 0 holds a point cue at 1.0 s; put a loop in slot 7.
adapter.set_cue(cue_track.id, slot=7, start_sec=60.0, cue_type="loop", length_sec=1.92)
red, green = palette.hex_for(0x2A), palette.hex_for(0x16)
def slot_cue(tc, slot):
return next((c for c in tc.cues if c.slot == slot), None)
def mirror_of(slot):
import json
store = adapter._store
t = store._tables
row = store._db.session.query(t.ContentCue).filter(
t.ContentCue.ContentID == str(cue_track.id)).first()
kind = kind_for("hotcue", slot)
return next((r for r in json.loads(row.Cues) if r.get("Kind") == kind), None)
before = slot_cue(adapter.track_cues(cue_track.id), 0)
tc = adapter.set_cue_color(cue_track.id, 0, red.lower())
c0 = slot_cue(tc, 0)
check("a cue takes a palette colour", c0 is not None and c0.color == red, str(c0 and c0.color))
check("recolouring does not move it", c0 is not None and before is not None
and c0.start == before.start, f"{before and before.start} -> {c0 and c0.start}")
raw = adapter._store._cue_row(cue_track.id, 0)
check("stored as the palette code with Color -1",
raw.ColorTableIndex == 0x2A and raw.Color == -1, f"{raw.ColorTableIndex}/{raw.Color}")
m = mirror_of(0)
check("the contentCue mirror carries the colour",
m is not None and m.get("ColorTableIndex") == 0x2A and m.get("Color") == -1, str(m))
chip = next((h for h in adapter.track(cue_track.id).hotcues if h.slot == 0), None)
check("the table's hotcue dot shows it", chip is not None and chip.color == red,
str(chip))
# The colour belongs to the PAD: a rename, a move or a type change keeps it.
tc = adapter.set_cue(cue_track.id, slot=0, start_sec=3.0, cue_type="cue", name="Renamed")
check("re-setting the slot keeps its colour", slot_cue(tc, 0).color == red,
str(slot_cue(tc, 0).color))
tc = adapter.set_cue_color(cue_track.id, 7, green)
check("a loop takes a colour too", slot_cue(tc, 7).color == green)
raw = adapter._store._cue_row(cue_track.id, 7)
check("a coloured loop stores the code, not the loop's 255/0",
raw.ColorTableIndex == 0x16 and raw.Color == -1, f"{raw.ColorTableIndex}/{raw.Color}")
tc = adapter.set_cue_type(cue_track.id, 7, "cue")
check("a type change keeps the colour", slot_cue(tc, 7).color == green)
tc = adapter.place_cues(cue_track.id, [SimpleNamespace(slot=7, start=70.0, type="cue",
length=0.0, name="Drop")],
overwrite=True)
check("an Auto Hotcues Replace keeps the slot's colour", slot_cue(tc, 7).color == green)
tc = adapter.set_cue_color(cue_track.id, 0, None)
raw = adapter._store._cue_row(cue_track.id, 0)
check("Default makes it uncoloured again",
slot_cue(tc, 0).color is None and raw.ColorTableIndex is None and raw.Color == -1,
f"{raw.ColorTableIndex}/{raw.Color}")
adapter.set_cue(cue_track.id, slot=7, start_sec=60.0, cue_type="loop", length_sec=1.92)
adapter.set_cue_color(cue_track.id, 7, None)
raw = adapter._store._cue_row(cue_track.id, 7)
check("an uncoloured loop is back to Rekordbox's own 255/0",
raw.ColorTableIndex == 0 and raw.Color == 255, f"{raw.ColorTableIndex}/{raw.Color}")
adapter.delete_cue(cue_track.id, 0)
tc = adapter.set_cue(cue_track.id, slot=0, start_sec=1.0, cue_type="cue")
check("a new cue in an emptied slot starts uncoloured", slot_cue(tc, 0).color is None)
check("a colour outside the palette is refused",
_raises(lambda: adapter.set_cue_color(cue_track.id, 0, "#123456"), InvalidCommand))
check("recolouring an empty slot is NotFound",
_raises(lambda: adapter.set_cue_color(cue_track.id, 6, red), NotFound))
print("== beatgrid edits ==")
grid_track = next((t for t in adapter.tracks if t.bpm), None)
if grid_track:
+7
View File
@@ -86,6 +86,8 @@ with tempfile.TemporaryDirectory() as d:
check("8 hotcue slots", caps.cues.hotcue_slots == 8)
check("no memory cues on Traktor", caps.cues.memory_cues is False)
check("loops are a cue type, not a separate bank", caps.cues.loops == "cue_type")
# Traktor colours a cue by its type, so no colour picker may be offered.
check("no cue colours to pick", caps.cues.color == "none" and caps.cues.palette == [])
check("flexible beatgrids supported", caps.grid.flexible is True)
check("grid is lockable", caps.grid.lockable is True)
check("save facts present for the UI to compose copy from",
@@ -127,6 +129,11 @@ with tempfile.TemporaryDirectory() as d:
check("memory cues are refused on Traktor", False, "no error raised")
except Unsupported:
check("memory cues are refused on Traktor", True)
try:
adapter.set_cue_color(tid2, free, "#FF0000")
check("cue colour is refused on Traktor", False, "no error raised")
except Unsupported:
check("cue colour is refused on Traktor", True)
# grid
grid_before = len(adapter.track_cues(tid2).grid_markers)