mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 18:22:53 +01:00
Implemented cross-platform track color support
This commit is contained in:
1 parent
0605dbabe6
commit
06361a851f
38 files changed
+547
-34
No files matched your search
@@ -1159,6 +1159,18 @@ Two independent apps that talk over HTTP:
|
||||
Hot / Mem toggle shows on `cues.memory_cues`, + Memory refuses past
|
||||
`cues.max_memory_cues`, and a memory cue's swatches are `cues.memory_palette`
|
||||
where `cues.memory_color` is `palette` (its own 8, not `palette`'s 16).
|
||||
**Track colour** (decided 2026-10-17, [the discussion](.claude/discussions/discuss-track-colour-2026-10-17.md)):
|
||||
shown as the Type column's icon in `Track.color_hex`; set from the context
|
||||
menu's **Colour ▸** (swatches from `tracks.colors`, + No Color, the whole
|
||||
selection, `PATCH /api/tracks/color`) — nowhere else. `Track.color` is a
|
||||
neutral NAME (`TrackColor`: pink red orange yellow green aqua blue purple),
|
||||
which is what crosses platforms; each adapter's `track_palette.py` maps its
|
||||
codes to it BY NAME, not hue: Traktor `INFO@COLOR` 1-7 = Red Orange Yellow
|
||||
Green Blue Violet(purple) Magenta(pink), measured (kit T1), no file tag;
|
||||
rekordbox `ColorID` / OneLibrary `color_id` / pdb `color_id` 1-8 = Pink…
|
||||
Purple, 0 none. Traktor's Blue LOOKS like rekordbox's Aqua but crosses as
|
||||
Blue (the name is the DJ's category); aqua arriving in Traktor becomes Blue.
|
||||
Unmeasured: what Traktor leaves after "None" (Konduktor removes the attribute).
|
||||
Carried but deliberately unused until a second adapter
|
||||
exists: `slot_labels: 'letter'`, `loops: 'separate_bank'`.
|
||||
- `lib/trackColumns.tsx` — single source of truth for the library table's
|
||||
@@ -1244,6 +1256,10 @@ serialization path.** It enforces:
|
||||
self-closed (`/>`, which Traktor never writes); a value containing
|
||||
`name='x'` once came back with a bare `"` (malformed). Both were in the
|
||||
fork's `format_traktor_layout`, fixed there (2026-10-16).
|
||||
And **track colour** (R): `set_track_color` changes one line, that
|
||||
entry's `<INFO>`, with `COLOR` last as Traktor writes it; aqua is stored as
|
||||
Blue; clearing restores the original bytes; and a Traktor 4.5 collection
|
||||
holding coloured tracks (when on the machine) renders byte-identically.
|
||||
The guard that catches serialization regressions like the lxml reformatting bug.
|
||||
- `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays
|
||||
Traktor-valid, backup-first, COLLECTION byte-identical, original untouched;
|
||||
@@ -1650,6 +1666,9 @@ frontend at `http://localhost:5173`.
|
||||
`add_entry` write BOTH, the text in the collection's majority notation
|
||||
(`TraktorStore.key_notation()`; an empty collection — an export — takes a
|
||||
Traktor-native source's own, so Traktor→Traktor keeps the user's).
|
||||
- **Track colour** = `INFO@COLOR`, 1-7 in the Color menu's order (Red …
|
||||
Magenta), the LAST attribute of `<INFO>`; collection-only (`_COLLECTION_ONLY_FIELDS`).
|
||||
See `track_palette.py`.
|
||||
- **Beatgrid = an ORDERED LIST of markers**, never a single BPM + anchor.
|
||||
Traktor stores each as a `CUE_V2 TYPE="4"` with its own `<GRID BPM>` child
|
||||
(flexible beatgrids, 3.4+); `<TEMPO BPM>` mirrors the **first marker by
|
||||
|
||||
@@ -404,6 +404,12 @@ class OneLibraryAdapter:
|
||||
self._refresh(track_id)
|
||||
return self._index.get(track_id)
|
||||
|
||||
def set_track_color(self, track_id: str, color: str | None) -> Track | None:
|
||||
self._require_writable("Setting the track colour")
|
||||
self._store.set_track_color(track_id, color)
|
||||
self._refresh(track_id)
|
||||
return self._index.get(track_id)
|
||||
|
||||
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
|
||||
self._refuse("Editing cover art")
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ from ...core.capabilities import (
|
||||
SaveCapabilities,
|
||||
TrackCapabilities,
|
||||
)
|
||||
from ..rekordbox import memory_palette, palette
|
||||
from ..rekordbox import memory_palette, palette, track_palette
|
||||
from ..rekordbox.cue_types import MAX_MEMORY_CUES, WRITABLE_CUE_TYPES
|
||||
|
||||
# Pads A-H. Unlike `djmdCue.Kind`, the ANLZ slot number is a dense 1-based index,
|
||||
@@ -87,6 +87,8 @@ def capabilities_for(
|
||||
addable=not read_only,
|
||||
removable=not read_only,
|
||||
key_writable=not read_only,
|
||||
# `content.color_id`, rekordbox's eight; the pdb row follows at Save.
|
||||
colors=[] if read_only else list(track_palette.SWATCHES),
|
||||
places_audio=True,
|
||||
# `artwork` gates EDITING, which Rekordbox does not do yet either
|
||||
# (parity). Reading works: `store.cover_art` follows
|
||||
|
||||
@@ -121,10 +121,10 @@ def rebuild(existing: bytes, session) -> bytes | None:
|
||||
# ---- tracks -----------------------------------------------------------------
|
||||
old_tracks = {pdb.row_id(pdb.TRACKS, r): r for r in pdb.table_rows(existing, pdb.TRACKS)}
|
||||
want = {}
|
||||
for (cid, title, artist, remixer, album, genre, label, rating, bpm, year, released,
|
||||
for (cid, title, artist, remixer, album, genre, label, rating, color, bpm, year, released,
|
||||
comment, *fresh) in session.execute(text(
|
||||
"SELECT content_id, title, artist_id_artist, artist_id_remixer, album_id, genre_id, "
|
||||
"label_id, rating, bpmx100, releaseYear, releaseDate, djComment, "
|
||||
"label_id, rating, color_id, bpmx100, releaseYear, releaseDate, djComment, "
|
||||
"path, fileName, fileSize, fileType, bitrate, bitDepth, samplingRate, length, "
|
||||
"analysisDataFilePath, dateAdded, key_id, image_id FROM content")):
|
||||
cid = int(cid)
|
||||
@@ -134,7 +134,8 @@ def rebuild(existing: bytes, session) -> bytes | None:
|
||||
fields, strings = _fresh_track(cid, *fresh)
|
||||
fields = {**fields, "artist_id": artist or 0, "remixer_id": remixer or 0,
|
||||
"album_id": album or 0, "genre_id": genre or 0, "label_id": label or 0,
|
||||
"rating": max(0, min(5, int(rating or 0))), "tempo": int(bpm or 0),
|
||||
"rating": max(0, min(5, int(rating or 0))), "color_id": int(color or 0),
|
||||
"tempo": int(bpm or 0),
|
||||
"year": int(year or 0)}
|
||||
strings = {**strings, "title": title or "", "comment": comment or "",
|
||||
"release_date": released or ""}
|
||||
|
||||
@@ -44,7 +44,7 @@ from pathlib import Path
|
||||
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
|
||||
from ...core.cue_colors import effective_color
|
||||
from ..rekordbox import anlz_writer as W
|
||||
from ..rekordbox import artwork, memory_palette, palette, timebase
|
||||
from ..rekordbox import artwork, memory_palette, palette, timebase, track_palette
|
||||
from ..rekordbox.cue_types import MAX_MEMORY_CUES
|
||||
from ..rekordbox.beatgrid import beats_from_markers
|
||||
from ..rekordbox.projection import render_key
|
||||
@@ -209,13 +209,13 @@ class OneLibraryExporter:
|
||||
|
||||
con.execute(
|
||||
"INSERT INTO content (content_id, title, titleForSearch, bpmx100, length, "
|
||||
"trackNo, artist_id_artist, album_id, genre_id, label_id, key_id, image_id, "
|
||||
"trackNo, artist_id_artist, album_id, genre_id, label_id, key_id, color_id, image_id, "
|
||||
"djComment, rating, releaseDate, dateAdded, path, fileName, fileSize, "
|
||||
"fileType, bitrate, bitDepth, samplingRate, isHotCueAutoLoadOn, "
|
||||
"isKuvoDeliverStatusOn, masterDbId, masterContentId, "
|
||||
"analysisDataFilePath, analysedBits, contentLink, hasModified, cueUpdateCount, "
|
||||
"analysisDataUpdateCount, informationUpdateCount) "
|
||||
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
|
||||
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
|
||||
(
|
||||
content_id, track.title, (track.title or "").lower(),
|
||||
int(round((track.bpm or 0) * 100)) or None, track.length,
|
||||
@@ -229,6 +229,7 @@ class OneLibraryExporter:
|
||||
# where the deck expects "Cm". Rendered from the parsed wheel.
|
||||
self._lookup(con, "key", lookups["key"],
|
||||
render_key(track.key_wheel, track.key_mode)),
|
||||
track_palette.id_for(track.color),
|
||||
image_id,
|
||||
track.comment, track.rating or 0, track.release_date,
|
||||
date.today().isoformat(), rel, item.destination.name, size,
|
||||
|
||||
@@ -16,6 +16,7 @@ Field conventions are read off a real rekordbox 7 export rather than guessed:
|
||||
from __future__ import annotations
|
||||
|
||||
from ...core.model import GridMarker, Track, TrackCues
|
||||
from ..rekordbox import track_palette
|
||||
from ..rekordbox.projection import parse_key
|
||||
|
||||
|
||||
@@ -106,6 +107,8 @@ def to_track(row, drive_path: str | None = None, *, stem: bool = False) -> Track
|
||||
grid_locked=False, # OneLibrary has no grid lock
|
||||
# What the FILE is, as the deck plays it — see the Rekordbox projection.
|
||||
media_kind="stem" if stem else "audio",
|
||||
color=track_palette.color_for(getattr(row, "color_id", None)),
|
||||
color_hex=track_palette.hex_for(getattr(row, "color_id", None)),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -55,7 +55,7 @@ from ...core.grid_edit import ReplaceGridCommands
|
||||
from ...core.model import CuePoint
|
||||
from ... import paths
|
||||
from . import beatgrid, cues as cue_reader, memory_cues
|
||||
from ..rekordbox import anlz_file, palette, timebase
|
||||
from ..rekordbox import anlz_file, palette, timebase, track_palette
|
||||
from ..rekordbox.cue_types import MAX_MEMORY_CUES
|
||||
from ..rekordbox import anlz_writer as W
|
||||
from ..rekordbox import beatgrid as rb_beatgrid
|
||||
@@ -566,6 +566,23 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
db.flush()
|
||||
db.session.expire(row)
|
||||
|
||||
def set_track_color(self, track_id: str, color: str | None) -> None:
|
||||
"""`content.color_id`, a 1-based id into the `color` table (see
|
||||
`track_palette`); 0 = none, as rekordbox exports an uncoloured track.
|
||||
Not a file tag; the pdb's track row follows at Save (`device_library`)."""
|
||||
new = track_palette.id_for(color)
|
||||
if color is not None and not new:
|
||||
raise InvalidCommand(f"Not a track colour: {color!r}")
|
||||
db = self._require_db()
|
||||
row = self.content(track_id)
|
||||
before = row.color_id
|
||||
if int(before or 0) == new:
|
||||
return
|
||||
row.color_id = new
|
||||
self._journal.record("track", "set", track_id, "color", before, new)
|
||||
db.flush()
|
||||
db.session.expire(row)
|
||||
|
||||
# ---- writes: playlists --------------------------------------------------
|
||||
def _playlist(self, node_id: str):
|
||||
from pyrekordbox.onelibrary import models
|
||||
@@ -1182,7 +1199,7 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
"isrc, djPlayCount, isHotCueAutoLoadOn, isKuvoDeliverStatusOn, kuvoDeliveryComment, "
|
||||
"masterDbId, masterContentId, analysisDataFilePath, analysedBits, contentLink, "
|
||||
"hasModified) VALUES (:cid, :title, NULL, '', :bpm, :length, 0, 0, :artist, :remixer, "
|
||||
":album, :genre, :label, :key, 0, :image, :comment, :rating, :year, :released, "
|
||||
":album, :genre, :label, :key, :color, :image, :comment, :rating, :year, :released, "
|
||||
":added, :created, :path, :file, :size, :type, :bitrate, :depth, :rate, '', 0, 1, 1, "
|
||||
"'', 0, :cid, :anlz, :bits, :link, 0)"), {
|
||||
"cid": cid, "title": getattr(track, "title", None) or final.stem,
|
||||
@@ -1192,6 +1209,7 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
"label": lookup("Label", track.label),
|
||||
# Rendered from the parsed wheel: a source's "10m" means nothing here.
|
||||
"key": self._key_id(track.key_wheel, track.key_mode),
|
||||
"color": track_palette.id_for(getattr(track, "color", None)),
|
||||
"image": image_id, "comment": track.comment or "",
|
||||
"rating": max(0, min(5, int(track.rating or 0))), "year": year, "released": released,
|
||||
"added": datetime.now().strftime("%Y-%m-%d"), "created": created, "path": rel,
|
||||
|
||||
@@ -260,6 +260,12 @@ class RekordboxAdapter:
|
||||
self._refresh(track_id)
|
||||
return self._index.get(track_id)
|
||||
|
||||
def set_track_color(self, track_id: str, color: str | None) -> Track | None:
|
||||
self._require_writable("Setting the track colour")
|
||||
self._store.set_track_color(track_id, color)
|
||||
self._refresh(track_id)
|
||||
return self._index.get(track_id)
|
||||
|
||||
# ---- commands: playlists ----------------------------------------------
|
||||
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
|
||||
self._require_writable("Creating playlists")
|
||||
|
||||
@@ -30,7 +30,7 @@ from ...core.capabilities import (
|
||||
SaveCapabilities,
|
||||
TrackCapabilities,
|
||||
)
|
||||
from . import memory_palette, palette
|
||||
from . import memory_palette, palette, track_palette
|
||||
from .cue_types import MAX_MEMORY_CUES, WRITABLE_CUE_TYPES
|
||||
|
||||
# Rekordbox's addressable hot cue bank. The pads are labelled A-H; the stored
|
||||
@@ -93,6 +93,8 @@ def capabilities_for(
|
||||
removable=True,
|
||||
addable=True,
|
||||
key_writable=True,
|
||||
# `djmdContent.ColorID`, rekordbox's eight (see `track_palette`).
|
||||
colors=list(track_palette.SWATCHES),
|
||||
artwork=False,
|
||||
artwork_note=None,
|
||||
),
|
||||
|
||||
@@ -41,7 +41,7 @@ from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
|
||||
from . import artwork, pdb
|
||||
from . import artwork, pdb, track_palette
|
||||
from .projection import render_key
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
@@ -138,6 +138,7 @@ class RekordboxDeviceExporter:
|
||||
"id": n, "year": year, "sample_depth": bit_depth or 0,
|
||||
"duration": min(int(track.length or 0), 0xFFFF),
|
||||
"u5": ANALYSED, "rating": max(0, min(5, int(track.rating or 0))),
|
||||
"color_id": track_palette.id_for(track.color),
|
||||
"u6": _file_type(item.destination), "u7": 3,
|
||||
},
|
||||
{
|
||||
|
||||
@@ -58,7 +58,7 @@ from sqlalchemy import text
|
||||
|
||||
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
|
||||
from ...core.cue_colors import effective_color
|
||||
from . import memory_palette, new_content, palette
|
||||
from . import memory_palette, new_content, palette, track_palette
|
||||
from . import timebase
|
||||
from .beatgrid import beats_from_markers
|
||||
from .capabilities import capabilities_for
|
||||
@@ -313,6 +313,7 @@ class RekordboxExporter:
|
||||
# export would put "10m" where Rekordbox shows "Cm".
|
||||
content.KeyID = self._lookup(db, "key", render_key(track.key_wheel, track.key_mode))
|
||||
content.ContentLink = CONTENT_LINK
|
||||
content.ColorID = str(track_palette.id_for(track.color))
|
||||
db.flush()
|
||||
return content
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ from __future__ import annotations
|
||||
|
||||
from ...core import musical_key
|
||||
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
|
||||
from . import beatgrid, memory_palette, palette, timebase
|
||||
from . import beatgrid, memory_palette, palette, timebase, track_palette
|
||||
from .cue_types import cue_type, kind_for, role_and_slot
|
||||
|
||||
# Rekordbox names keys musically ("Abm", "F", "Ebm") — but its key table also
|
||||
@@ -127,6 +127,8 @@ def to_track(row, cue_kinds=(), *, stem: bool = False) -> Track:
|
||||
# file's mix, but Konduktor's deck plays its stems, and the Type column
|
||||
# must not disagree with the deck.
|
||||
media_kind="stem" if stem else "audio",
|
||||
color=track_palette.color_for(getattr(row, "ColorID", None)),
|
||||
color_hex=track_palette.hex_for(getattr(row, "ColorID", None)),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -47,7 +47,7 @@ from ...core.adapter import (
|
||||
from ...core.edit_journal import EditJournal
|
||||
from ...core.grid_edit import ReplaceGridCommands
|
||||
from ...core.pathmap import PathMapping, stored_form
|
||||
from . import memory_palette, timebase
|
||||
from . import memory_palette, timebase, track_palette
|
||||
from .cue_types import MAX_MEMORY_CUES, beat_loop_size, kind_for, role_and_slot
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
@@ -556,6 +556,24 @@ class RekordboxStore(ReplaceGridCommands):
|
||||
self._db.flush()
|
||||
self._db.session.expire(row)
|
||||
|
||||
# ---- writes: track colour ---------------------------------------------
|
||||
def set_track_color(self, track_id: str, color: str | None) -> None:
|
||||
"""`djmdContent.ColorID`, a 1-based id into `djmdColor` (see
|
||||
`track_palette`). Cleared = "0", as on the uncoloured rows of the local
|
||||
library (a few hold NULL; both read as none)."""
|
||||
new = track_palette.id_for(color)
|
||||
if color is not None and not new:
|
||||
raise InvalidCommand(f"Not a track colour: {color!r}")
|
||||
row = self.content(track_id)
|
||||
before = row.ColorID
|
||||
if track_palette.id_for(track_palette.color_for(before)) == new:
|
||||
return
|
||||
row.ColorID = str(new)
|
||||
self._journal.record("track", "set", track_id, "color", before, row.ColorID)
|
||||
# A foreign key into djmdColor: flush + expire, as for the others.
|
||||
self._db.flush()
|
||||
self._db.session.expire(row)
|
||||
|
||||
# ---- writes: playlists ------------------------------------------------
|
||||
def _playlist(self, node_id: str):
|
||||
t = self._tables
|
||||
@@ -761,6 +779,7 @@ class RekordboxStore(ReplaceGridCommands):
|
||||
# Rekordbox's ("10m" is "Cm" here), and a row it already has is reused.
|
||||
content.KeyID = self._key_id(track.key_wheel, track.key_mode)
|
||||
content.ContentLink = new_content.CONTENT_LINK
|
||||
content.ColorID = str(track_palette.id_for(track.color))
|
||||
if stored != audio:
|
||||
# pyrekordbox reads the file where it IS; the row names it as the
|
||||
# library stores every other path (the server's mapping, inverted).
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
"""rekordbox's TRACK colours — the eight a track can be tagged with.
|
||||
|
||||
Stored as a 1-based id into the `djmdColor` table (master.db `djmdContent.ColorID`,
|
||||
a string: "0" = none) and OneLibrary's `color` table (`content.color_id`, an
|
||||
integer, 0 = none); the stick's legacy `export.pdb` track row has a `color_id`
|
||||
byte with the same numbering. Both tables list the same eight rows in the same
|
||||
order: 1 Pink, 2 Red, 3 Orange, 4 Yellow, 5 Green, 6 Aqua, 7 Blue, 8 Purple —
|
||||
one per generic `TrackColor`, so the mapping is one to one.
|
||||
|
||||
Those are the memory-cue palette's names in its order, so the display RGB is
|
||||
`memory_palette.COLOURS`' (sampled from rekordbox 7's own colour menu). Nothing
|
||||
stores the RGB — `djmdColor.ColorCode` is NULL in a real library.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from ...core.capabilities import ColorSwatch, TrackColor
|
||||
from . import memory_palette
|
||||
|
||||
#: id - 1 -> the generic colour, in rekordbox's menu order.
|
||||
_NAMES: list[TrackColor] = ["pink", "red", "orange", "yellow", "green", "aqua", "blue", "purple"]
|
||||
|
||||
#: What `capabilities.tracks.colors` offers.
|
||||
SWATCHES: list[ColorSwatch] = [
|
||||
ColorSwatch(color=name, hex=memory_palette.SWATCHES[i], label=memory_palette.COLOURS[i][0])
|
||||
for i, name in enumerate(_NAMES)
|
||||
]
|
||||
|
||||
|
||||
def _id(color_id: int | str | None) -> int:
|
||||
try:
|
||||
return int(color_id) if color_id is not None else 0
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
|
||||
|
||||
def color_for(color_id: int | str | None) -> TrackColor | None:
|
||||
"""The generic colour for a stored id; None for 0, NULL or anything unknown."""
|
||||
n = _id(color_id)
|
||||
return _NAMES[n - 1] if 1 <= n <= len(_NAMES) else None
|
||||
|
||||
|
||||
def hex_for(color_id: int | str | None) -> str | None:
|
||||
"""rekordbox's display colour for a stored id; None when uncoloured."""
|
||||
n = _id(color_id)
|
||||
return SWATCHES[n - 1].hex if 1 <= n <= len(SWATCHES) else None
|
||||
|
||||
|
||||
def id_for(color: TrackColor | str | None) -> int:
|
||||
"""The id to store for a generic colour; 0 for none (or an unknown name)."""
|
||||
return _NAMES.index(color) + 1 if color in _NAMES else 0
|
||||
@@ -218,6 +218,9 @@ class RemoteAdapter:
|
||||
def set_key(self, track_id, wheel, mode):
|
||||
return self._call("set_key", track_id=track_id, wheel=wheel, mode=mode)
|
||||
|
||||
def set_track_color(self, track_id, color):
|
||||
return self._call("set_track_color", track_id=track_id, color=color)
|
||||
|
||||
def set_cue(self, track_id, *, slot, start_sec, cue_type, length_sec=0.0, role="hotcue", name=None):
|
||||
return self._call("set_cue", track_id=track_id, slot=slot, start_sec=start_sec,
|
||||
cue_type=cue_type, length_sec=length_sec, role=role, name=name)
|
||||
|
||||
@@ -156,6 +156,12 @@ class TraktorAdapter:
|
||||
self._refresh(track_id)
|
||||
return self._index.get(track_id)
|
||||
|
||||
def set_track_color(self, track_id: str, color: str | None) -> Track | None:
|
||||
with _translate():
|
||||
self._store.set_track_color(track_id, color)
|
||||
self._refresh(track_id)
|
||||
return self._index.get(track_id)
|
||||
|
||||
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
|
||||
with _translate():
|
||||
self._store.set_track_art(track_id, data, mime)
|
||||
|
||||
@@ -19,6 +19,7 @@ from ...core.capabilities import (
|
||||
SaveCapabilities,
|
||||
TrackCapabilities,
|
||||
)
|
||||
from . import track_palette
|
||||
|
||||
_VERSION_RE = re.compile(rb'<NML\s+VERSION="(\d+)"')
|
||||
|
||||
@@ -68,6 +69,8 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
|
||||
addable=True,
|
||||
stem_convertible=True,
|
||||
key_writable=True,
|
||||
# INFO@COLOR, seven colours (measured, see `track_palette`).
|
||||
colors=list(track_palette.SWATCHES),
|
||||
# `.mp4` covers stem files (`.stem.mp4`). Traktor also reads WMA,
|
||||
# but only on Windows, and a file added on one OS must play on both.
|
||||
audio_formats=[".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a", ".mp4", ".ogg"],
|
||||
|
||||
@@ -9,7 +9,7 @@ import re
|
||||
|
||||
from ...core import musical_key
|
||||
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
|
||||
from . import beatgrid, timebase
|
||||
from . import beatgrid, timebase, track_palette
|
||||
from .cue_types import NATIVE_TO_CUE_TYPE
|
||||
|
||||
# Traktor displays keys in Open Key ("10m" / "8d") or Camelot ("8A" / "8B"),
|
||||
@@ -172,6 +172,8 @@ def to_track(e) -> Track:
|
||||
grid_marker_count=len(markers),
|
||||
grid_locked=bool(e.lock),
|
||||
media_kind="stem" if getattr(e, "stems", None) is not None else "audio",
|
||||
color=track_palette.color_for(info.color if info else None),
|
||||
color_hex=track_palette.hex_for(info.color if info else None),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -53,7 +53,7 @@ from ...core.pathmap import PathMapping, stored_form
|
||||
from ...core.relocate import PathGroup
|
||||
from ...core.stem_file import NML_STEMS_JSON, nml_stems_for
|
||||
from ...schemas import PlaylistNode
|
||||
from . import beatgrid, timebase
|
||||
from . import beatgrid, timebase, track_palette
|
||||
from .locations import os_path_to_location, resolve_path
|
||||
from ...core import musical_key
|
||||
from .projection import iso_date, musical_key_value, traktor_date, with_memory_ids
|
||||
@@ -446,7 +446,8 @@ class TraktorStore:
|
||||
EDITABLE_FIELDS = {"title", "artist", "album", "rating", "comment2"} | _INFO_FIELDS
|
||||
# Fields that live only in the collection: Traktor itself writes no file tag
|
||||
# for "Comment 2" (verified on an m4a it had just edited), so neither do we.
|
||||
_COLLECTION_ONLY_FIELDS = {"comment2"}
|
||||
# Nor for the track colour (kit T1: no audio file's mtime moved).
|
||||
_COLLECTION_ONLY_FIELDS = {"comment2", "color"}
|
||||
|
||||
def set_track_metadata(self, track_id: str, fields: dict) -> None:
|
||||
with self._lock:
|
||||
@@ -544,6 +545,27 @@ class TraktorStore:
|
||||
self._journal.record("track", "set", track_id, "key", before, entry.info.key)
|
||||
self.dirty = True
|
||||
|
||||
# ---- track colour -----------------------------------------------------
|
||||
def set_track_color(self, track_id: str, color: str | None) -> None:
|
||||
"""INFO@COLOR (see `track_palette`). Cleared = the attribute removed, as
|
||||
every never-coloured entry has it; what Traktor itself leaves after
|
||||
"None" (absent, or `COLOR="0"`) is not yet measured (kit T1 step 3)."""
|
||||
code = track_palette.code_for(color)
|
||||
if color is not None and code is None:
|
||||
raise InvalidCommand(f"Not a track colour: {color!r}")
|
||||
with self._lock:
|
||||
entry = self._entry_by_key.get(track_id)
|
||||
if entry is None:
|
||||
raise PlaylistError(f"Track not found: {track_id}")
|
||||
before = entry.info.color if entry.info is not None else None
|
||||
if before == code:
|
||||
return
|
||||
if entry.info is None:
|
||||
entry.info = Infotype()
|
||||
entry.info.color = code
|
||||
self._journal.record("track", "set", track_id, "color", before, code)
|
||||
self.dirty = True
|
||||
|
||||
# ---- adding tracks --------------------------------------------------
|
||||
def add_entry(self, track, audio_path: Path) -> str:
|
||||
"""Append a brand-new ENTRY for `audio_path` and return its track id.
|
||||
@@ -598,6 +620,7 @@ class TraktorStore:
|
||||
# attribute at all rather than a zero.
|
||||
ranking=(max(0, min(5, int(getattr(track, "rating", 0) or 0))) * 51) or None,
|
||||
playtime=getattr(track, "length", None) or None,
|
||||
color=track_palette.code_for(getattr(track, "color", None)),
|
||||
)
|
||||
album = None
|
||||
if getattr(track, "album", None):
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Traktor's TRACK colours — `INFO@COLOR`, an integer.
|
||||
|
||||
MEASURED in Traktor 4.5 (kit T1, 2026-10-17,
|
||||
`.claude/discussions/discuss-track-colour-2026-10-17.md`) by colouring one track
|
||||
per entry of the browser's Color menu, in its order: 1 Red · 2 Orange ·
|
||||
3 Yellow · 4 Green · 5 Blue · 6 Violet · 7 Magenta. Traktor keeps it in the
|
||||
collection only — it does not tag the audio file.
|
||||
|
||||
Mapped to the generic colours BY NAME (decided 2026-10-17): Violet is `purple`,
|
||||
Magenta `pink`, and Blue is `blue` even though it LOOKS like rekordbox's Aqua —
|
||||
the name is the DJ's category. Traktor has no seventh-and-a-half colour, so
|
||||
`aqua` arriving from rekordbox is stored as Blue.
|
||||
|
||||
The RGB values are DISPLAY colours only — nothing stores them. They were
|
||||
sampled from the colour dots in Traktor's own browser (a screenshot).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from ...core.capabilities import ColorSwatch, TrackColor
|
||||
|
||||
#: What `capabilities.tracks.colors` offers; code - 1 -> swatch, menu order.
|
||||
SWATCHES: list[ColorSwatch] = [
|
||||
ColorSwatch(color="red", hex="#FB413E", label="Red"),
|
||||
ColorSwatch(color="orange", hex="#F79525", label="Orange"),
|
||||
ColorSwatch(color="yellow", hex="#F9F918", label="Yellow"),
|
||||
ColorSwatch(color="green", hex="#52FA52", label="Green"),
|
||||
ColorSwatch(color="blue", hex="#1ACBFA", label="Blue"),
|
||||
ColorSwatch(color="purple", hex="#B26CFA", label="Violet"),
|
||||
ColorSwatch(color="pink", hex="#FA51EB", label="Magenta"),
|
||||
]
|
||||
|
||||
#: Generic colours Traktor has no swatch of its own for.
|
||||
_FOLDED: dict[str, int] = {"aqua": 5}
|
||||
|
||||
|
||||
def _swatch(code: int | None) -> ColorSwatch | None:
|
||||
return SWATCHES[code - 1] if isinstance(code, int) and 1 <= code <= len(SWATCHES) else None
|
||||
|
||||
|
||||
def color_for(code: int | None) -> TrackColor | None:
|
||||
"""The generic colour for a stored code; None for absent, 0 or unknown."""
|
||||
s = _swatch(code)
|
||||
return s.color if s else None
|
||||
|
||||
|
||||
def hex_for(code: int | None) -> str | None:
|
||||
"""Traktor's display colour for a stored code; None when uncoloured."""
|
||||
s = _swatch(code)
|
||||
return s.hex if s else None
|
||||
|
||||
|
||||
def code_for(color: TrackColor | str | None) -> int | None:
|
||||
"""The `INFO@COLOR` to store for a generic colour; None for none."""
|
||||
if color is None:
|
||||
return None
|
||||
for i, s in enumerate(SWATCHES, start=1):
|
||||
if s.color == color:
|
||||
return i
|
||||
return _FOLDED.get(color)
|
||||
@@ -22,7 +22,7 @@ from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Protocol, runtime_checkable
|
||||
|
||||
from .capabilities import Capabilities
|
||||
from .capabilities import Capabilities, TrackColor
|
||||
from .model import Facets, PlaylistNode, Stats, Track, TrackCues, TrackPage
|
||||
from .pathmap import PathMapping
|
||||
from .relocate import PathGroup
|
||||
@@ -296,6 +296,9 @@ class LibraryAdapter(Protocol):
|
||||
# analysis writes. Each platform renders it in its own notation (and its own
|
||||
# analysed-key field, where it has one). Gated on `tracks.key_writable`.
|
||||
def set_key(self, track_id: str, wheel: int, mode: str) -> Track | None: ...
|
||||
# The track's colour tag (None clears it), mapped onto the platform's own
|
||||
# palette by name. Gated on `tracks.colors` being non-empty.
|
||||
def set_track_color(self, track_id: str, color: TrackColor | None) -> Track | None: ...
|
||||
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None: ...
|
||||
def cover_art(self, track_id: str) -> tuple[bytes, str] | None: ...
|
||||
|
||||
|
||||
@@ -36,6 +36,20 @@ CueType = Literal["cue", "fade_in", "fade_out", "load", "loop"]
|
||||
CueRole = Literal["hotcue", "memory"]
|
||||
MediaKind = Literal["audio", "stem", "video"]
|
||||
PlaylistKind = Literal["folder", "playlist", "smart"]
|
||||
# A track's colour tag, as a platform-neutral IDENTITY — what crosses between
|
||||
# libraries. Each adapter maps its own codes to and from these BY NAME (decided
|
||||
# 2026-10-17, `.claude/discussions/discuss-track-colour-2026-10-17.md`): eight
|
||||
# names because rekordbox has eight; Traktor's seven cover all but `aqua`,
|
||||
# which it receives as its Blue.
|
||||
TrackColor = Literal["pink", "red", "orange", "yellow", "green", "aqua", "blue", "purple"]
|
||||
|
||||
|
||||
class ColorSwatch(BaseModel):
|
||||
"""One track colour a library offers, in its own menu order."""
|
||||
|
||||
color: TrackColor
|
||||
hex: str # the platform's own display colour
|
||||
label: str # the platform's own name for it ("Violet" in Traktor)
|
||||
|
||||
|
||||
class CueCapabilities(BaseModel):
|
||||
@@ -107,6 +121,9 @@ class TrackCapabilities(BaseModel):
|
||||
# Whether added files can be left where they are ("reference") rather than
|
||||
# copied. False where the library cannot see this computer's files at all.
|
||||
reference: bool = True
|
||||
# The track colours this library can store (`set_track_color`), in its own
|
||||
# menu order. Empty: the platform has no track colour.
|
||||
colors: list[ColorSwatch] = []
|
||||
|
||||
|
||||
class PlaylistCapabilities(BaseModel):
|
||||
|
||||
@@ -13,7 +13,7 @@ from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from .capabilities import CueRole, CueType, MediaKind, PlaylistKind
|
||||
from .capabilities import CueRole, CueType, MediaKind, PlaylistKind, TrackColor
|
||||
|
||||
|
||||
class HotcueChip(BaseModel):
|
||||
@@ -71,6 +71,11 @@ class Track(BaseModel):
|
||||
grid_marker_count: int = 0
|
||||
grid_locked: bool = False
|
||||
media_kind: MediaKind = "audio"
|
||||
# The track's colour tag: the neutral identity (what crosses platforms) and
|
||||
# the platform's own display colour for it, both mapped from the stored
|
||||
# code by the adapter. None = no colour.
|
||||
color: TrackColor | None = None
|
||||
color_hex: str | None = None
|
||||
|
||||
|
||||
class TrackPage(BaseModel):
|
||||
|
||||
@@ -60,6 +60,7 @@ from .schemas import (
|
||||
LibraryInfo,
|
||||
PlatformOption,
|
||||
EditTrack,
|
||||
SetTrackColor,
|
||||
Facets,
|
||||
FileTagOutcome,
|
||||
CreateExportSet,
|
||||
@@ -1320,6 +1321,17 @@ def edit_track(body: EditTrack) -> dict:
|
||||
return {"status": "updated", "id": body.track_id}
|
||||
|
||||
|
||||
@app.patch("/api/tracks/color")
|
||||
def set_track_color(body: SetTrackColor) -> dict:
|
||||
"""Set (or clear) the colour tag of every given track (in-memory; persisted
|
||||
on save). Gated on `tracks.colors`: the platform's swatches."""
|
||||
a = require_adapter()
|
||||
if not a.capabilities().tracks.colors:
|
||||
raise Unsupported("This library cannot store a track colour")
|
||||
tracks = [a.set_track_color(tid, body.color) for tid in body.track_ids]
|
||||
return {"status": "updated", "tracks": [t for t in tracks if t is not None]}
|
||||
|
||||
|
||||
@app.get("/api/tracks/art")
|
||||
def track_art(track_id: str) -> Response:
|
||||
"""Stream a track's embedded cover art (staged replacement if unsaved)."""
|
||||
|
||||
@@ -38,7 +38,8 @@ from .core.model import AutoHotcue, Track, TrackCues
|
||||
#: 1.2 — `/v1/folder/*`: the content folder browsed as a Files tree.
|
||||
#: 1.3 — memory cues: `add_memory_cue`, `rename_memory_cue`,
|
||||
#: `set_memory_cue_type`, `set_memory_cue_color`, `delete_memory_cue`.
|
||||
API_VERSION: tuple[int, int] = (1, 3)
|
||||
#: 1.4 — track colour: `set_track_color`, `Track.color` / `color_hex`.
|
||||
API_VERSION: tuple[int, int] = (1, 4)
|
||||
|
||||
#: How long a session survives without a heartbeat, and how often the holder
|
||||
#: sends one. Long enough to ride out a Wi-Fi blip or a switch to the fallback
|
||||
@@ -77,7 +78,8 @@ _READ = (
|
||||
)
|
||||
_MUTATING = (
|
||||
"create_playlist", "create_folder", "rename_playlist", "delete_playlist",
|
||||
"move_playlist", "set_playlist_entries", "remove_tracks", "set_track_metadata", "set_key", "set_cue",
|
||||
"move_playlist", "set_playlist_entries", "remove_tracks", "set_track_metadata", "set_key",
|
||||
"set_track_color", "set_cue",
|
||||
"set_cue_type", "set_cue_color", "delete_cue", "place_cues", "add_memory_cue",
|
||||
"rename_memory_cue", "set_memory_cue_type", "set_memory_cue_color", "delete_memory_cue", "add_grid_marker",
|
||||
"move_grid_marker", "set_grid_marker_bpm", "delete_grid_marker", "replace_grid",
|
||||
|
||||
@@ -5,7 +5,7 @@ from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from .core.capabilities import CueRole, CueType
|
||||
from .core.capabilities import CueRole, CueType, TrackColor
|
||||
|
||||
|
||||
class CreatePlaylist(BaseModel):
|
||||
@@ -40,6 +40,13 @@ class EditTrack(BaseModel):
|
||||
fields: dict[str, str | int | None]
|
||||
|
||||
|
||||
class SetTrackColor(BaseModel):
|
||||
"""The context menu's Colour ▸: one colour (None = No Color) for a selection."""
|
||||
|
||||
track_ids: list[str]
|
||||
color: TrackColor | None = None
|
||||
|
||||
|
||||
class FileTagOutcome(BaseModel):
|
||||
track_id: str
|
||||
file: str
|
||||
|
||||
@@ -153,7 +153,8 @@ for i, (title, artist, key) in enumerate((("One", "Artist A", (8, "minor")), ("T
|
||||
png = __import__("io").BytesIO()
|
||||
Image.new("RGB", (300, 300), (40 * i, 90, 160)).save(png, format="PNG")
|
||||
t = Track(id=f"src{i}", title=title, artist=artist, album="LP", genre="House", bpm=125.0,
|
||||
key_wheel=key[0], key_mode=key[1], length=6, rating=i + 1, filepath=str(audio))
|
||||
key_wheel=key[0], key_mode=key[1], length=6, rating=i + 1, filepath=str(audio),
|
||||
color=("purple", None, "aqua")[i])
|
||||
tracks.append(ExportTrack(track=t, destination=audio, art=(png.getvalue(), "image/png"),
|
||||
cues=TrackCues(track_id=t.id, grid_markers=[GridMarker(start=0.0, bpm=125.0)],
|
||||
cues=[CuePoint(type="cue", role="hotcue", start=1.0, length=0.0, slot=0)])))
|
||||
@@ -174,6 +175,8 @@ check("a track with no key has key 0", lib.tracks[1]["key_id"] == 0)
|
||||
check("bpm x100, rating, file type, bitmask as rekordbox writes them",
|
||||
all(t["tempo"] == 12500 and t["u6"] == 11 and t["bitmask"] == 0xC0700 and t["u5"] == 0x29 for t in lib.tracks)
|
||||
and [t["rating"] for t in lib.tracks] == [1, 2, 3])
|
||||
check("the track colour is the 1-based id (Purple 8, none 0, Aqua 6)",
|
||||
[t["color_id"] for t in lib.tracks] == [8, 0, 6], str([t["color_id"] for t in lib.tracks]))
|
||||
check("the file path is drive-relative", lib.tracks[0]["file_path"] == "/Contents/House/One.wav", lib.tracks[0]["file_path"])
|
||||
check("no computer's masterDbId is claimed", all(t["u3"] == 0 and t["u4"] == 0 for t in lib.tracks))
|
||||
tree = {p["name"]: p for p in lib.playlists}
|
||||
|
||||
@@ -66,11 +66,14 @@ chosen = [flexible, cued, plain]
|
||||
dest = Path(tempfile.mkdtemp()) / "GIG"
|
||||
dest.mkdir(parents=True)
|
||||
items = []
|
||||
# Colours by generic name: `aqua` is rekordbox's, which Traktor stores as Blue.
|
||||
COLOURS = {flexible.id: "aqua", cued.id: "pink", plain.id: None}
|
||||
for track in chosen:
|
||||
audio = dest / "Music" / "Library" / Path(track.filepath).name
|
||||
audio.parent.mkdir(parents=True, exist_ok=True)
|
||||
audio.write_bytes(b"\0" * 64)
|
||||
items.append(ExportTrack(track=track, destination=audio, cues=src.track_cues(track.id)))
|
||||
items.append(ExportTrack(track=track.model_copy(update={"color": COLOURS[track.id]}),
|
||||
destination=audio, cues=src.track_cues(track.id)))
|
||||
|
||||
payload = ExportPayload(
|
||||
name="GIG",
|
||||
@@ -126,6 +129,11 @@ check("artist survived", by_title[plain.title].artist == plain.artist)
|
||||
if plain.key:
|
||||
check("key notation is copied, not converted", by_title[plain.title].key == plain.key)
|
||||
|
||||
check("track colours cross by name: aqua -> Blue (5), pink -> Magenta (7), none -> no COLOR",
|
||||
[by_title[t.title].color for t in chosen] == ["blue", "pink", None]
|
||||
and 'COLOR="5"' in text and 'COLOR="7"' in text and text.count(' COLOR="') == 2,
|
||||
str([by_title[t.title].color for t in chosen]))
|
||||
|
||||
print("== the playlist tree ==")
|
||||
tree = {}
|
||||
|
||||
|
||||
@@ -58,13 +58,19 @@ cued = next(t for t in src.tracks
|
||||
chosen = [flexible, cued]
|
||||
|
||||
|
||||
COLOURS = ["purple", "aqua"]
|
||||
|
||||
|
||||
def build(root: Path) -> ExportPayload:
|
||||
items = []
|
||||
for i, track in enumerate(chosen):
|
||||
audio = root / ("House" if i % 2 else "Techno") / Path(track.filepath).name
|
||||
audio.parent.mkdir(parents=True, exist_ok=True)
|
||||
audio.write_bytes(b"\0" * 4096)
|
||||
items.append(ExportTrack(track=track, destination=audio,
|
||||
# A colour each, as the generic name crosses (Traktor's Violet is
|
||||
# `purple`; `aqua` is rekordbox's own, with no Traktor swatch).
|
||||
coloured = track.model_copy(update={"color": COLOURS[i % len(COLOURS)]})
|
||||
items.append(ExportTrack(track=coloured, destination=audio,
|
||||
cues=src.track_cues(track.id)))
|
||||
return ExportPayload(
|
||||
name="GIG", tracks=items,
|
||||
@@ -136,6 +142,10 @@ for platform, reopen in (
|
||||
all(abs((by_title[t.title].bpm or 0) - (t.bpm or 0)) < 0.02
|
||||
for t in chosen if t.bpm))
|
||||
|
||||
check("the track colour crossed by name",
|
||||
[by_title[t.title].color for t in chosen] == COLOURS[:len(chosen)],
|
||||
str([by_title[t.title].color for t in chosen]))
|
||||
|
||||
print(f"-- {platform}: the key was CONVERTED, not copied")
|
||||
for track in chosen:
|
||||
if not track.key:
|
||||
|
||||
@@ -438,6 +438,25 @@ check("refusing leaves nothing dirty", adapter.dirty is False)
|
||||
check("an unknown track is a NotFound, not an Unsupported",
|
||||
_raises(lambda: adapter.audio_path("no-such-track"), NotFound))
|
||||
|
||||
print("== track colour ==")
|
||||
# Goober (`fixtures/onelibrary-goober`) is a stick coloured in rekordbox:
|
||||
# `content.color_id` 1-based into the `color` table (1 Pink, 2 Red, 5 Green).
|
||||
from konduktor.adapters.rekordbox import track_palette # noqa: E402
|
||||
|
||||
_gdir = Path(tempfile.mkdtemp(prefix="konduktor-ol-colour-")) / "goober"
|
||||
shutil.copytree(FIXTURE.parent / "onelibrary-goober", _gdir)
|
||||
_goober = OneLibraryAdapter(_gdir)
|
||||
_colours = {t.title: (t.color, t.color_hex) for t in _goober.tracks}
|
||||
check("rekordbox's track colours project by name + display RGB",
|
||||
_colours.get("Nemean - Doomed") == ("red", "#E13121")
|
||||
and _colours.get("Sleepnet - Lapse") == ("green", "#65DB41")
|
||||
and _colours.get("Life Is A Loop - Grand Prix") == ("pink", "#E577EF"), str(_colours))
|
||||
check("an uncoloured track has none", _colours.get("Demo Track 2") == (None, None))
|
||||
_goober.close()
|
||||
check("the palette maps ids both ways",
|
||||
[track_palette.id_for(track_palette.color_for(i)) for i in range(9)] == list(range(9))
|
||||
and track_palette.color_for("0") is None and track_palette.color_for(9) is None)
|
||||
|
||||
print("== reads that answer rather than refuse ==")
|
||||
check("cover art is absent, not an error", adapter.cover_art(one.id) is None)
|
||||
# A drive stores everything relative to its own root, so it cannot have stale
|
||||
|
||||
@@ -442,6 +442,49 @@ check("setting 12A reuses the stick's '12A' row instead of adding 'Dbm'",
|
||||
if r2["title"] == target.title))["key_id"]) == names["12A"])
|
||||
g.close()
|
||||
|
||||
print("== track colour ==")
|
||||
# `content.color_id` (1 Pink .. 8 Purple, 0 none); the pdb track row's
|
||||
# `color_id` byte uses the same ids, and Goober's two agree on every track.
|
||||
from konduktor.adapters.rekordbox import pdb # noqa: E402
|
||||
|
||||
goober = Path(tempfile.mkdtemp(prefix="konduktor-olfid-colour-")) / "Goober"
|
||||
shutil.copytree(FIXTURE.parent / "onelibrary-goober", goober, ignore=shutil.ignore_patterns("after"))
|
||||
pdb_path = goober / "PIONEER" / "rekordbox" / "export.pdb"
|
||||
|
||||
|
||||
def pdb_colours() -> dict:
|
||||
return {pdb.row_id(pdb.TRACKS, r): pdb.track_fields(r)[0]["color_id"]
|
||||
for r in pdb.table_rows(pdb_path.read_bytes(), pdb.TRACKS)}
|
||||
|
||||
|
||||
before = dump(db_of(goober))
|
||||
check("rekordbox's own pdb carries the same colour ids as the database",
|
||||
pdb_colours() == {int(r["content_id"]): int(r["color_id"] or 0) for r in before["content"].values()},
|
||||
str(pdb_colours()))
|
||||
g = OneLibraryAdapter(goober)
|
||||
check("an editable stick offers rekordbox's eight colours",
|
||||
[s.color for s in g.capabilities().tracks.colors]
|
||||
== ["pink", "red", "orange", "yellow", "green", "aqua", "blue", "purple"])
|
||||
check("a browsed one offers none",
|
||||
OneLibraryAdapter(goober, read_only=True).capabilities().tracks.colors == [])
|
||||
g.set_track_color(next(x for x in g.tracks if x.color == "green").id, "green")
|
||||
check("setting the colour it has is not an edit", g.dirty is False)
|
||||
red = next(t for t in g.tracks if t.color == "red")
|
||||
t = g.set_track_color(red.id, "blue")
|
||||
check("the projection shows it at once", (t.color, t.color_hex) == ("blue", "#1F4EED"), str(t))
|
||||
g.save()
|
||||
changes = diff(before, dump(db_of(goober)))
|
||||
check("exactly content.color_id changes (2 = Red -> 7 = Blue)",
|
||||
len(changes) == 1 and changes[0][3] == {"color_id": (2, 7)}, describe(changes))
|
||||
cid = int(changes[0][1]) if changes else None
|
||||
check("and the pdb's track row follows", pdb_colours().get(cid) == 7, str(pdb_colours()))
|
||||
g.set_track_color(red.id, None)
|
||||
g.save()
|
||||
check("No Color stores 0, in both",
|
||||
dump(db_of(goober))["content"][changes[0][1]]["color_id"] == 0 and pdb_colours().get(cid) == 0)
|
||||
check("an unknown colour is refused", _raises(lambda: g.set_track_color(red.id, "teal"), Exception))
|
||||
g.close()
|
||||
|
||||
print()
|
||||
print("RESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -952,5 +952,29 @@ with tempfile.TemporaryDirectory() as d:
|
||||
len(dump(work)["djmdKey"]) == len(after["djmdKey"]))
|
||||
adapter.close()
|
||||
|
||||
print("== L: track colour is djmdContent.ColorID, one row + the counter ==")
|
||||
clean_copy(REAL, work)
|
||||
before = dump(work)
|
||||
adapter = RekordboxAdapter(work)
|
||||
t1 = adapter.tracks[0]
|
||||
got = adapter.set_track_color(t1.id, "aqua")
|
||||
check("the projection updates immediately", (got.color, got.color_hex) == ("aqua", "#55BBF1"), str(got))
|
||||
adapter.save()
|
||||
changes = diff(before, dump(work))
|
||||
content = [c for c in changes if c[0] == "djmdContent"]
|
||||
check("exactly the track row and the counter change",
|
||||
{t for t, _, _, _ in changes} == {"djmdContent", "agentRegistry"} and len(changes) == 2,
|
||||
describe(changes))
|
||||
check("ColorID '6' (Aqua, 1-based into djmdColor)",
|
||||
content and content[0][3].get("ColorID", (None, None))[1] == "6", str(content and content[0][3]))
|
||||
before = dump(work)
|
||||
adapter.set_track_color(t1.id, None)
|
||||
adapter.save()
|
||||
changes = diff(before, dump(work))
|
||||
check("No Color writes '0'",
|
||||
[c[3].get("ColorID", (None, None))[1] for c in changes if c[0] == "djmdContent"] == ["0"],
|
||||
describe(changes))
|
||||
adapter.close()
|
||||
|
||||
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -63,6 +63,14 @@ def _raises_playlist(fn) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _raises_any(fn) -> bool:
|
||||
try:
|
||||
fn()
|
||||
except Exception:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def tag_lines(b: bytes) -> list[str]:
|
||||
return b.replace(b"><", b">\n<").decode("utf-8", "replace").splitlines()
|
||||
|
||||
@@ -1341,5 +1349,47 @@ with tempfile.TemporaryDirectory() as d:
|
||||
reread = TraktorStore(work)._nml.collection.entry[0].info.comment
|
||||
check("…and reads back unchanged", reread == "x > y key='8A' \"z\"", repr(reread))
|
||||
|
||||
print("== R. track colour (INFO@COLOR) is localized, Traktor's shape, reversible ==")
|
||||
# Measured in Traktor 4.5 (kit T1): COLOR="1".."7" (Red..Magenta), the LAST
|
||||
# attribute of <INFO>; no file tag. Cleared = no attribute (unmeasured what
|
||||
# Traktor itself leaves after "None"; absent is what an uncoloured entry has).
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
work = Path(d) / "collection.nml"
|
||||
shutil.copy2(REAL, work)
|
||||
original = work.read_bytes()
|
||||
store = TraktorStore(work)
|
||||
entry = next(e for e in store._nml.collection.entry if e.info is not None and e.info.color is None)
|
||||
loc = entry.location
|
||||
tid = f"{loc.volume}{loc.dir}{loc.file}"
|
||||
store.set_track_color(tid, "blue")
|
||||
store.save()
|
||||
coloured = work.read_bytes()
|
||||
o_s, o_e = _entry_span_by_file(original, loc.file)
|
||||
c_s, c_e = _entry_span_by_file(coloured, loc.file)
|
||||
check("only that ENTRY changes",
|
||||
original[:o_s] + original[o_e:] == coloured[:c_s] + coloured[c_e:])
|
||||
check("in one line: its <INFO>, with COLOR last, as Traktor writes it",
|
||||
diff_count(original[o_s:o_e], coloured[c_s:c_e]) == 2 # one line: - and +
|
||||
and _re.search(rb'<INFO [^>]* COLOR="5">', coloured[c_s:c_e]) is not None)
|
||||
store = TraktorStore(work)
|
||||
store.set_track_color(tid, "aqua")
|
||||
check("aqua (rekordbox's) is stored as Traktor's Blue: a no-op", store.dirty is False)
|
||||
store.set_track_color(tid, "purple")
|
||||
check("purple is Traktor's Violet (6)",
|
||||
store._entry_by_key[tid].info.color == 6)
|
||||
store.set_track_color(tid, None)
|
||||
store.save()
|
||||
check("clearing restores the original bytes", work.read_bytes() == original)
|
||||
check("an unknown colour is refused",
|
||||
_raises_any(lambda: TraktorStore(work).set_track_color(tid, "teal")))
|
||||
|
||||
_KIT = Path.home() / "Documents/Native Instruments/Traktor 4.5.0/collection.nml"
|
||||
if _KIT.exists() and b'COLOR="' in _KIT.read_bytes():
|
||||
data = _KIT.read_bytes()
|
||||
check("a Traktor 4.5 collection with coloured tracks renders byte-identically",
|
||||
TraktorStore(_KIT)._render() == data)
|
||||
else:
|
||||
print(" [SKIP] no coloured Traktor 4.5 collection on this machine")
|
||||
|
||||
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -332,5 +332,25 @@ if gridded is not None:
|
||||
all(c.type != "grid" for c in cues.cues) and
|
||||
gridded.cue_count == len(cues.cues))
|
||||
|
||||
print("== track colour ==")
|
||||
# `INFO@COLOR` 1-7, measured in Traktor 4.5 (kit T1): Red ... Magenta, menu order.
|
||||
from konduktor.adapters.traktor import projection, track_palette # noqa: E402
|
||||
|
||||
_entry = next(e for e in adapter._store.iter_entries() if e.info is not None)
|
||||
_was = _entry.info.color
|
||||
_seen = []
|
||||
for _code in (None, 0, 1, 4, 7, 8):
|
||||
_entry.info.color = _code
|
||||
_t = projection.to_track(_entry)
|
||||
_seen.append((_t.color, _t.color_hex))
|
||||
_entry.info.color = _was
|
||||
check("Traktor's track colours project by name + display RGB (none for absent/0/unknown)",
|
||||
_seen == [(None, None), (None, None), ("red", "#FB413E"), ("green", "#52FA52"),
|
||||
("pink", "#FA51EB"), (None, None)], str(_seen))
|
||||
check("Traktor offers seven colours, Violet as purple and Magenta as pink",
|
||||
[s.color for s in adapter.capabilities().tracks.colors]
|
||||
== ["red", "orange", "yellow", "green", "blue", "purple", "pink"])
|
||||
check("aqua (rekordbox's) is stored as Traktor's Blue", track_palette.code_for("aqua") == 5)
|
||||
|
||||
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -226,6 +226,21 @@ export default function App() {
|
||||
[qc, notify, onError, writeHintText],
|
||||
)
|
||||
|
||||
// The context menu's Colour ▸ — swatches are this library's own (by hex in
|
||||
// the menu, sent as the neutral colour name), applied to the whole selection.
|
||||
const trackColors = capabilities.data?.tracks.colors ?? []
|
||||
const setTrackColor = (ids: string[], hex: string | null) => {
|
||||
const swatch = trackColors.find((s) => s.hex === hex) ?? null
|
||||
api
|
||||
.setTrackColor(ids, swatch?.color ?? null)
|
||||
.then(() => {
|
||||
invalidateTrackLists(qc)
|
||||
const what = swatch ? `Colour set to ${swatch.label}` : 'Colour cleared'
|
||||
notify('success', `${what}${ids.length > 1 ? ` on ${ids.length} tracks` : ''} — ${writeHintText}`)
|
||||
})
|
||||
.catch((e) => onError((e as Error).message))
|
||||
}
|
||||
|
||||
|
||||
// NOTE: all hooks must run on every render (Rules of Hooks). Data queries are
|
||||
// gated with `enabled: loaded` so they don't fire before a collection is open;
|
||||
@@ -1214,6 +1229,25 @@ export default function App() {
|
||||
...(canEdit && !viewingDevice && menu.ids.length === 1
|
||||
? [{ label: 'Edit Tags…', onClick: gated(() => setEditing(menu.track)) }]
|
||||
: []),
|
||||
...(canEdit && !viewingDevice && trackColors.length
|
||||
? [
|
||||
{
|
||||
label: 'Colour',
|
||||
submenu: [
|
||||
{
|
||||
swatches: trackColors.map((s) => s.hex),
|
||||
labels: trackColors.map((s) => s.label),
|
||||
noneLabel: 'No Color',
|
||||
// A multi-selection may hold several colours, so none
|
||||
// is marked ('' matches no swatch and is not "none").
|
||||
selected: menu.ids.length === 1 ? menu.track.color_hex : '',
|
||||
onPick: (hex: string | null) =>
|
||||
menuLoose.length ? void askToAdd(menuLoose) : setTrackColor(menu.ids, hex),
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(canAnalyze
|
||||
? [
|
||||
{
|
||||
|
||||
@@ -39,6 +39,10 @@ export interface Track {
|
||||
grid_marker_count: number
|
||||
grid_locked: boolean
|
||||
media_kind: MediaKind
|
||||
/** The track's colour tag — the platform-neutral identity — and the
|
||||
* library's own display colour for it; both null when uncoloured. */
|
||||
color: TrackColor | null
|
||||
color_hex: string | null
|
||||
}
|
||||
|
||||
/** One occupied hotcue slot, as the library table previews it. */
|
||||
@@ -117,6 +121,15 @@ export type Platform = string
|
||||
export type CueRole = 'hotcue' | 'memory'
|
||||
export type CueType = 'cue' | 'fade_in' | 'fade_out' | 'load' | 'loop'
|
||||
export type MediaKind = 'audio' | 'stem' | 'video'
|
||||
/** A track colour tag; each library maps its own palette onto these by name. */
|
||||
export type TrackColor = 'pink' | 'red' | 'orange' | 'yellow' | 'green' | 'aqua' | 'blue' | 'purple'
|
||||
/** One track colour a library offers, in its own menu order. */
|
||||
export interface ColorSwatch {
|
||||
color: TrackColor
|
||||
hex: string
|
||||
/** The platform's own name for it ("Violet" in Traktor). */
|
||||
label: string
|
||||
}
|
||||
export type PlaylistKind = 'folder' | 'playlist' | 'smart'
|
||||
export type TrackField =
|
||||
| 'title' | 'artist' | 'album' | 'genre' | 'label' | 'remixer'
|
||||
@@ -279,6 +292,8 @@ export interface Capabilities {
|
||||
audio_destination: 'host' | 'library'
|
||||
/** Added files can be left where they are rather than copied. */
|
||||
reference: boolean
|
||||
/** The track colours this library can store; empty = no track colour. */
|
||||
colors: ColorSwatch[]
|
||||
}
|
||||
playlists: {
|
||||
folders: boolean
|
||||
@@ -1072,6 +1087,11 @@ export const api = {
|
||||
|
||||
editTrack: (trackId: string, fields: Record<string, string | number | null>) =>
|
||||
send<{ status: string }>('PATCH', '/api/tracks', { track_id: trackId, fields }),
|
||||
setTrackColor: (trackIds: string[], color: TrackColor | null) =>
|
||||
send<{ status: string; tracks: Track[] }>('PATCH', '/api/tracks/color', {
|
||||
track_ids: trackIds,
|
||||
color,
|
||||
}),
|
||||
artUrl: (trackId: string) =>
|
||||
`${API_BASE}/api/tracks/art?track_id=${encodeURIComponent(trackId)}`,
|
||||
audioUrl: (trackId: string) =>
|
||||
|
||||
@@ -19,6 +19,10 @@ export type MenuItem =
|
||||
selected: string | null
|
||||
onPick: (color: string | null) => void
|
||||
disabled?: boolean
|
||||
/** Names for the swatches (tooltips), else the hex is shown. */
|
||||
labels?: string[]
|
||||
/** The uncoloured choice's wording; "Default" when omitted. */
|
||||
noneLabel?: string
|
||||
}
|
||||
| { separator: true }
|
||||
|
||||
@@ -259,13 +263,13 @@ function SwatchGrid({
|
||||
return (
|
||||
<div className="px-3 pb-2 pt-1" onMouseEnter={onEnter}>
|
||||
<div className="grid w-max grid-cols-8 gap-1.5">
|
||||
{item.swatches.map((color) => (
|
||||
{item.swatches.map((color, i) => (
|
||||
<button
|
||||
key={color}
|
||||
role="menuitemradio"
|
||||
aria-checked={selected === color.toUpperCase()}
|
||||
aria-label={color}
|
||||
title={color}
|
||||
aria-label={item.labels?.[i] ?? color}
|
||||
title={item.labels?.[i] ?? color}
|
||||
disabled={item.disabled}
|
||||
onClick={() => pick(color)}
|
||||
className={`h-4 w-4 rounded-full transition-transform disabled:cursor-default disabled:opacity-40 ${ring(
|
||||
@@ -289,7 +293,7 @@ function SwatchGrid({
|
||||
selected === null ? 'outline outline-2 outline-offset-1 outline-white' : ''
|
||||
}`}
|
||||
/>
|
||||
Default
|
||||
{item.noneLabel ?? 'Default'}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -169,10 +169,14 @@ export const TRACK_COLUMNS: ColumnDef<Track, any>[] = [
|
||||
id: 'type',
|
||||
header: 'Type',
|
||||
size: 64,
|
||||
cell: (c) =>
|
||||
c.getValue() === 'stem' ? (
|
||||
// The icon takes the track's colour tag, when it has one; otherwise both
|
||||
// glyphs are neutral, so colour in this column only ever means the tag.
|
||||
cell: (c) => {
|
||||
const color = c.row.original.color_hex
|
||||
const tint = color ? undefined : 'text-faint'
|
||||
return c.getValue() === 'stem' ? (
|
||||
// Stem file → stacked lines ("burger"), the usual stem glyph.
|
||||
<span title="Stem file" className="text-accent">
|
||||
<span title="Stem file" className={tint} style={color ? { color } : undefined}>
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-label="Stem">
|
||||
<rect x="3" y="6" width="18" height="2.4" rx="1.2" />
|
||||
<rect x="3" y="10.8" width="18" height="2.4" rx="1.2" />
|
||||
@@ -181,12 +185,13 @@ export const TRACK_COLUMNS: ColumnDef<Track, any>[] = [
|
||||
</span>
|
||||
) : (
|
||||
// Normal audio track → music note.
|
||||
<span title="Audio track" className="text-faint">
|
||||
<span title="Audio track" className={tint} style={color ? { color } : undefined}>
|
||||
<svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor" aria-label="Audio">
|
||||
<path d="M12 3v10.55A4 4 0 1 0 14 17V7h4V3h-6z" />
|
||||
</svg>
|
||||
</span>
|
||||
),
|
||||
)
|
||||
},
|
||||
}),
|
||||
col.accessor('album', { id: 'album', header: 'Album', size: 180, cell: editable('album') }),
|
||||
col.accessor('genre', { id: 'genre', header: 'Genre', size: 140, cell: editable('genre') }),
|
||||
|
||||
Reference in new issue
Block a user