Compare commits

...
15 Commits
Author SHA1 Message Date
patben8 2821ba124d Merge pull request #14 from MrPatben8/dev
Improved drag and drop import
2026-10-17 22:55:03 +02:00
patben8 f9ef38d826 Bumped version number 2026-10-17 22:54:08 +02:00
patben8 518542c7bb Improved drag to import dialog 2026-10-17 22:53:37 +02:00
patben8 bf427a628e Fixed drag and drop position accuracy 2026-10-17 22:53:37 +02:00
patben8 4340e948ac Bumped version number 2026-10-17 20:21:28 +02:00
patben8 fe63acc2a2 Merge pull request #13 from MrPatben8/dev
Implemented Cross-Platform Track Color Support
2026-10-17 20:08:02 +02:00
patben8 06361a851f Implemented cross-platform track color support 2026-10-17 19:50:56 +02:00
patben8 0605dbabe6 Improved release description and file names 2026-10-16 18:04:54 +02:00
patben8 6be99e6d7e Merge pull request #12 from MrPatben8/dev
Implemented self-updating
2026-10-16 17:39:28 +02:00
patben8 0eac972173 Implemented self-updating 2026-10-16 17:38:35 +02:00
patben8 422297d890 Merge pull request #11 from MrPatben8/dev
Implemented Memory Cue Support
2026-10-16 16:06:47 +02:00
patben8 ee48e80440 Bumped version number 2026-10-16 16:04:49 +02:00
patben8 0aeb5019ad Fixed issue with Traktor 4.5 collection round-trip 2026-10-16 15:53:52 +02:00
patben8 1f2ca18e8a Fixed issues with cross-platform memory-cue naming and coloring 2026-10-16 15:04:43 +02:00
patben8 19a604f730 Added full support for memory-cues 2026-10-16 14:50:46 +02:00
107 changed files with 3943 additions and 429 deletions

No files matched your search

+97
View File
@@ -0,0 +1,97 @@
"""Lay out one release's assets under user-facing names, plus the updater's
latest.json and the release notes' Download section.
Run by build.yml's release job:
python3 .github/scripts/release_assets.py artifacts release \\
--version 0.6.0 --tag v0.6.0-b42 --repo owner/konduktor
Finds, anywhere under `artifacts`, what `tauri build` produced: the macOS
`*.dmg` and `*.app.tar.gz` (+ `.sig`) and the Windows `*-setup.exe` (+ `.sig`).
Copies them into `release` as
Konduktor-<version>-macOS.dmg (download)
Konduktor-<version>-Windows-Setup.exe (download; the Windows updater runs it too)
Konduktor-<version>-app-updater.tar.gz (the macOS updater's package)
latest.json (the updater's manifest)
and writes `download.md`. Renaming is safe: the signatures cover contents,
not names, and latest.json is written from the final names. `latest.json`
itself keeps its name: the app asks for releases/download/<tag>/latest.json.
Fails if anything is missing: a manifest lacking a platform is refused by the
updater as a whole.
"""
import argparse
import json
import shutil
import sys
from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import quote
def find_one(root: Path, suffix: str) -> Path:
found = [p for p in root.rglob(f"*{suffix}") if p.is_file()]
if len(found) != 1:
sys.exit(f"expected exactly one *{suffix} under {root}, found {len(found)}")
return found[0]
def signature(asset: Path) -> str:
sig = asset.with_name(asset.name + ".sig")
if not sig.is_file():
sys.exit(f"missing signature {sig}")
return sig.read_text(encoding="utf-8").strip()
def lay_out(artifacts: Path, out: Path, version: str, tag: str, repo: str) -> None:
def url(name: str) -> str:
return f"https://github.com/{repo}/releases/download/{quote(tag)}/{quote(name)}"
dmg = find_one(artifacts, ".dmg")
app = find_one(artifacts, ".app.tar.gz")
setup = find_one(artifacts, "-setup.exe")
names = {
dmg: f"Konduktor-{version}-macOS.dmg",
setup: f"Konduktor-{version}-Windows-Setup.exe",
app: f"Konduktor-{version}-app-updater.tar.gz",
}
# Tauri's platform keys -> the file that platform's updater installs.
manifest = {
"version": version,
"pub_date": datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z"),
"platforms": {
"darwin-aarch64": {"signature": signature(app), "url": url(names[app])},
"windows-x86_64": {"signature": signature(setup), "url": url(names[setup])},
},
}
out.mkdir(parents=True, exist_ok=True)
for src, name in names.items():
shutil.copy2(src, out / name)
(out / "latest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
(out / "download.md").write_text(
"## Download\n"
f"- **macOS** (Apple Silicon): [{names[dmg]}]({url(names[dmg])})\n"
f"- **Windows**: [{names[setup]}]({url(names[setup])})\n",
encoding="utf-8",
)
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("artifacts", type=Path)
ap.add_argument("out", type=Path)
ap.add_argument("--version", required=True)
ap.add_argument("--tag", required=True)
ap.add_argument("--repo", required=True)
args = ap.parse_args()
lay_out(args.artifacts, args.out, args.version, args.tag, args.repo)
for p in sorted(args.out.iterdir()):
print(p.name)
if __name__ == "__main__":
main()
+37 -7
View File
@@ -86,20 +86,31 @@ jobs:
working-directory: frontend working-directory: frontend
run: npm ci run: npm ci
# createUpdaterArtifacts also signs the in-app update packages
# (Konduktor.app.tar.gz / the NSIS setup.exe) with the updater key, whose
# public half is plugins.updater.pubkey in tauri.conf.json. Losing the
# private key means installed copies can never update themselves again.
- name: Build Tauri app - name: Build Tauri app
working-directory: frontend working-directory: frontend
env:
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
run: npx tauri build run: npx tauri build
# Stage the single installer per OS into a flat folder. Uploading one # Stage the single installer per OS into a flat folder. Uploading one
# directory (not multiple bundle subpaths) keeps the artifact root at # directory (not multiple bundle subpaths) keeps the artifact root at
# ./installer, so the zip holds the bare file — no nested dmg/ or nsis/ # ./installer, so the zip holds the bare file — no nested dmg/ or nsis/
# folder. We ship the DMG on macOS and the NSIS -setup.exe on Windows # folder. We ship the DMG on macOS and the NSIS -setup.exe on Windows
# (the .msi is intentionally left out). # (the .msi is intentionally left out), plus what the in-app updater
# installs: the .app.tar.gz on macOS (the setup.exe on Windows) and the
# .sig files the release job folds into latest.json.
- name: Stage installer (macOS) - name: Stage installer (macOS)
if: runner.os == 'macOS' if: runner.os == 'macOS'
run: | run: |
mkdir -p installer mkdir -p installer
cp frontend/src-tauri/target/release/bundle/dmg/*.dmg installer/ cp frontend/src-tauri/target/release/bundle/dmg/*.dmg installer/
cp frontend/src-tauri/target/release/bundle/macos/*.app.tar.gz installer/
cp frontend/src-tauri/target/release/bundle/macos/*.app.tar.gz.sig installer/
- name: Stage installer (Windows) - name: Stage installer (Windows)
if: runner.os == 'Windows' if: runner.os == 'Windows'
@@ -107,6 +118,7 @@ jobs:
run: | run: |
New-Item -ItemType Directory -Force installer | Out-Null New-Item -ItemType Directory -Force installer | Out-Null
Copy-Item frontend/src-tauri/target/release/bundle/nsis/*-setup.exe installer/ Copy-Item frontend/src-tauri/target/release/bundle/nsis/*-setup.exe installer/
Copy-Item frontend/src-tauri/target/release/bundle/nsis/*-setup.exe.sig installer/
- name: Upload installer - name: Upload installer
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4
@@ -189,11 +201,24 @@ jobs:
pattern: konduktor-* pattern: konduktor-*
path: artifacts # → artifacts/konduktor-macOS/…, artifacts/konduktor-Windows/… path: artifacts # → artifacts/konduktor-macOS/…, artifacts/konduktor-Windows/…
# The release's files under user-facing names, the in-app updater's
# latest.json (the app reads releases/download/<tag>/latest.json) and the
# notes' Download section. The .sig files are folded into latest.json and
# not uploaded themselves.
- name: Release assets
run: |
python3 .github/scripts/release_assets.py artifacts release \
--version "${{ steps.version.outputs.version }}" \
--tag "v${{ steps.version.outputs.version }}-b${{ github.run_number }}" \
--repo "${{ github.repository }}"
# Release notes from the "Patch notes" section of the PR that merged this # Release notes from the "Patch notes" section of the PR that merged this
# commit into main (dev → main merges carry many features in one PR, so # commit into main (dev → main merges carry many features in one PR, so
# its title alone says little). Written under "What's Changed", the # its title alone says little). Written under "What's Changed", the
# heading the app's update dialog reads. No PR (a manual run, a direct # heading the app's update dialog reads. No PR (a manual run, a direct
# push) or no such section → GitHub's generated notes, as before. # push) or no such section → GitHub's generated notes, as before. The
# Download section always comes first (the action puts the body above
# generated notes); the dialog reads only "What's Changed".
- name: Patch notes from the merged PR - name: Patch notes from the merged PR
id: notes id: notes
env: env:
@@ -218,9 +243,10 @@ jobs:
section.append(line) section.append(line)
notes = "\n".join(section).strip() notes = "\n".join(section).strip()
found = bool(notes) found = bool(notes)
if found: with open("release-notes.md", "w", encoding="utf-8") as f:
with open("release-notes.md", "w", encoding="utf-8") as f: f.write(open("release/download.md", encoding="utf-8").read())
f.write("## What's Changed\n\n" + notes + "\n") if found:
f.write("\n## What's Changed\n\n" + notes + "\n")
with open(os.environ["GITHUB_OUTPUT"], "a") as out: with open(os.environ["GITHUB_OUTPUT"], "a") as out:
out.write(f"found={'true' if found else 'false'}\n") out.write(f"found={'true' if found else 'false'}\n")
print("Using the PR's patch notes." if found else "No patch notes section; using generated notes.") print("Using the PR's patch notes." if found else "No patch notes section; using generated notes.")
@@ -232,7 +258,11 @@ jobs:
tag_name: v${{ steps.version.outputs.version }}-b${{ github.run_number }} tag_name: v${{ steps.version.outputs.version }}-b${{ github.run_number }}
name: Konduktor v${{ steps.version.outputs.version }}-b${{ github.run_number }} name: Konduktor v${{ steps.version.outputs.version }}-b${{ github.run_number }}
target_commitish: ${{ github.sha }} target_commitish: ${{ github.sha }}
body_path: ${{ steps.notes.outputs.found == 'true' && 'release-notes.md' || '' }} body_path: release-notes.md
generate_release_notes: ${{ steps.notes.outputs.found != 'true' }} generate_release_notes: ${{ steps.notes.outputs.found != 'true' }}
fail_on_unmatched_files: true fail_on_unmatched_files: true
files: artifacts/**/* files: |
release/*.dmg
release/*.exe
release/*.tar.gz
release/latest.json
+8 -3
View File
@@ -88,9 +88,14 @@ cd ..
# 2) Build the app (its beforeBuildCommand runs the Vite build) # 2) Build the app (its beforeBuildCommand runs the Vite build)
cd frontend cd frontend
npx tauri build npx tauri build --config src-tauri/tauri.unsigned.conf.json
``` ```
The `--config` override skips the in-app updater packages, which are signed
with the release key that only CI holds (`TAURI_SIGNING_PRIVATE_KEY`). With
that key set in the environment, plain `npx tauri build` makes them too.
`build.ps1` picks the right one by itself.
`build_sidecar.ps1` uses `backend\.venv\Scripts\python.exe` when it exists (else `build_sidecar.ps1` uses `backend\.venv\Scripts\python.exe` when it exists (else
whatever `python` resolves to), so the venv doesn't need to be activated. It whatever `python` resolves to), so the venv doesn't need to be activated. It
replaces the whole staged folder, so no file from an older build survives. replaces the whole staged folder, so no file from an older build survives.
@@ -117,8 +122,8 @@ folder (`tauri.windows.conf.json` → `bundle.resources`), where `lib.rs` spawns
## Rebuilding after changes ## Rebuilding after changes
If you changed **backend** Python, run `.\build.ps1` (or `build_sidecar.ps1`, If you changed **backend** Python, run `.\build.ps1` (or `build_sidecar.ps1`,
then `npx tauri build`). Frontend-only changes just need then `npx tauri build` as above). Frontend-only changes just need
`.\build.ps1 -SkipSidecar` (or `npx tauri build`). `.\build.ps1 -SkipSidecar`.
## Not part of this build: the stem engine ## Not part of this build: the stem engine
+163 -26
View File
@@ -49,7 +49,10 @@ Two independent apps that talk over HTTP:
(nothing changes, the count comes back so the UI can ask and resend); (nothing changes, the count comes back so the UI can ask and resend);
`add` only where `capabilities.playlists.duplicates` — Traktor only, since `add` only where `capabilities.playlists.duplicates` — Traktor only, since
OneLibrary's `playlist_content` is keyed on (playlist, content) and OneLibrary's `playlist_content` is keyed on (playlist, content) and
rekordbox's tolerance of a repeat is unmeasured. rekordbox's tolerance of a repeat is unmeasured. An optional `index`
inserts among the CURRENT entries (a drop between a table's rows);
folder add (`playlist_index`) and device import (`into_playlist_index`)
take the same.
- `capabilities.py` — `Capabilities`: what the loaded library can persist, so - `capabilities.py` — `Capabilities`: what the loaded library can persist, so
the UI can gate controls instead of branching on the platform. the UI can gate controls instead of branching on the platform.
- `query.py` (`TrackIndex`) — all query/filter/sort/facet/stats logic, over - `query.py` (`TrackIndex`) — all query/filter/sort/facet/stats logic, over
@@ -315,8 +318,19 @@ Two independent apps that talk over HTTP:
cue at `Kind=4` lands on no pad and Rekordbox shows it as a memory cue. cue at `Kind=4` lands on no pad and Rekordbox shows it as a memory cue.
Get this wrong and cues silently move to the wrong pad or vanish from the Get this wrong and cues silently move to the wrong pad or vanish from the
bank. Point cues AND loops both write; `cue_types` owns the translation. bank. Point cues AND loops both write; `cue_types` owns the translation.
**Memory cues stay preserved-but-uneditable** (Rekordbox is the only **Memory cues are editable** (`add_memory_cue` / `rename_` /
platform with them — the two-platform promotion rule). `set_memory_cue_color` / `delete_memory_cue`, addressed by `CuePoint.id`
= `djmdCue.ID`; decided and MEASURED 2026-10-16, kit M1 in
[the discussion](.claude/discussions/discuss-memory-cues-2026-10-16.md)):
`Kind=0`, no ANLZ write, **at most 10 per track** (rekordbox stops
storing the 11th SILENTLY, so the store refuses it with a reason), and
a colour of their OWN — 8 colours (`memory_palette.py`, display RGB
sampled from rekordbox's menu), the 0-based code in **`Color`** with
`ColorTableIndex` NULL (the opposite of a hot cue), `-1` never coloured,
**255** after "No Color", and an unnamed memory LOOP has `Comment=''`.
`_sync_content_cue` writes the mirror in **ROW order** (`rowid`), as
rekordbox does — not by position. A cue on the reserved `Kind=4` is
shown as a memory cue but is not one, so it is not editable.
**Hot cue colour is writable** (`set_cue_color`, `PATCH **Hot cue colour is writable** (`set_cue_color`, `PATCH
/api/tracks/cue/color`) from `palette.SWATCHES` — all 16 of rekordbox's /api/tracks/cue/color`) from `palette.SWATCHES` — all 16 of rekordbox's
swatches, MEASURED (the teal-green, 0x13 #00FF30, came last: rekordbox swatches, MEASURED (the teal-green, 0x13 #00FF30, came last: rekordbox
@@ -392,8 +406,19 @@ Two independent apps that talk over HTTP:
A pad keeps its colour and (unless given one) its name through a move or A pad keeps its colour and (unless given one) its name through a move or
retype. An `.EXT` without `PCO2` gets both lists seeded from its `PCOB`s on retype. An `.EXT` without `PCO2` gets both lists seeded from its `PCOB`s on
the first edit — readers prefer `PCO2`, so a one-pad list would hide the rest. the first edit — readers prefer `PCO2`, so a one-pad list would hide the rest.
A track with no analysis files refuses cue/grid edits. Memory cues stay A track with no analysis files refuses cue/grid edits.
preserved-but-uneditable. **Memory cues are editable** the way rekordbox 7 edits them on a stick
(kit M2; rekordbox's own bytes are `fixtures/onelibrary-memory-edits`):
`memory_cues.py` does the list edits — ONLY the analysis files change (the
database and both pdbs keep every row); the `.DAT` `PCOB` memory list
PREPENDS a new cue and is relinked as a whole (status 0, bytes 24–27 =
prev/next list index, `anlz_writer.relinked_memory_pcpts`), the `.EXT`
`PCO2` memory list APPENDS it in rekordbox's compact 44-byte form; colour =
`PCP2` byte 28, 1-based (`memory_palette.anlz_byte`), name = the `PCP2`
comment, which grows the entry by its length; cap 10. The id is
content-derived (`cues.memory_cue_id`: stored time, kind, loop end), the
same in both lists. When rekordbox rewrites a `.DAT` it also re-sorts the
untouched hot `PCOB` ascending; Konduktor changes only the list it edits.
**`device_library.py` keeps the stick's legacy `export.pdb` in step** at **`device_library.py` keeps the stick's legacy `export.pdb` in step** at
every Save (rekordbox's own edits let its playlists drift — measured). The every Save (rekordbox's own edits let its playlists drift — measured). The
stick's own pdb is EDITED (`pdb.PdbEditor`), not regenerated: ids are stick's own pdb is EDITED (`pdb.PdbEditor`), not regenerated: ids are
@@ -933,7 +958,14 @@ Two independent apps that talk over HTTP:
20 px edge after a 250 ms dwell — any less and the first/last visible row 20 px edge after a 250 ms dwell — any less and the first/last visible row
could not be dropped on. Targets: playlist + export rows (Sidebar, could not be dropped on. Targets: playlist + export rows (Sidebar,
ExportsSection), the tree's zones, the table's reorder, and the DECK ExportsSection), the tree's zones, the table's reorder, and the DECK
(App), which loads the grabbed row paused, in its own origin. (App), which loads the grabbed row paused, in its own origin. An open
editable playlist's TABLE (and its empty / no-match state) also takes
files and Files/device rows (`TrackTable.foreignDrop`, `drag.isForeign`;
decided 2026-10-17): the add dialog opens with the playlist as target at
the insertion line — appended while sorted/filtered — and both add
dialogs offer "Also add to <playlist>" (`usePlaylistToggle`), ticked
every time, never remembered; unticked = the collection only. Wherever
a playlist is the target, the sidebar's drop included.
**Files from Finder / Explorer** (decided 2026-10-13) ride the same store **Files from Finder / Explorer** (decided 2026-10-13) ride the same store
as a `files` payload: `lib/fileDrop.ts` feeds Tauri's `onDragDropEvent` as a `files` payload: `lib/fileDrop.ts` feeds Tauri's `onDragDropEvent`
(real paths; a plain browser has none, so no file drop there) through (real paths; a plain browser has none, so no file drop there) through
@@ -1013,10 +1045,28 @@ Two independent apps that talk over HTTP:
stem engine publishes `engine-v*` releases in the same repo — and, stem engine publishes `engine-v*` releases in the same repo — and,
if its tag's **semver part** is newer than `__APP_VERSION__` — build-number if its tag's **semver part** is newer than `__APP_VERSION__` — build-number
`-b<N>` bumps don't count — shows an update dialog with the release's `-b<N>` bumps don't count — shows an update dialog with the release's
"What's Changed" bullets; Download opens the release page in the system "What's Changed" bullets; "Skip this version" persists
browser via `@tauri-apps/plugin-shell` `open` — falls back to `window.open` `skippedUpdateVersion` to userprefs via `/api/prefs`; check failures are
outside Tauri; "Skip this version" persists `skippedUpdateVersion` to silent. **In the desktop app, Update installs it** (decided 2026-10-16,
userprefs via `/api/prefs`; all failures are silent). [the discussion](.claude/discussions/discuss-self-update-2026-10-16.md)):
`update_download` (lib.rs, tauri-plugin-updater) reads THAT release's
`latest.json`, downloads with progress in the dialog, verifies the
signature and STAGES the package in app-cache; `update_restart` then
quits through the ordinary quit request, so QuitGuard asks about unsaved
edits. The package is installed in `exit_now`, only AFTER the sidecar is
killed — on macOS the running backend lazily loads native libraries from
inside the bundle being replaced, on Windows its `.exe` is locked (the
shell waits until it can open it for writing) — then the app relaunches.
Cancel in QuitGuard keeps it staged (`konduktor://update-deferred`) and the
next ordinary quit installs it without relaunching. On macOS a bundle run
from the DMG, translocated, or in a folder the user cannot write is
refused BEFORE downloading (the updater's own admin-password fallback
runs on the main thread, which the quit path may hold). Any failure shows
its reason + "Open release page" (the old Download, still the button in a
plain browser); an install that failed at exit is written to
`failed.json` and reported by the next launch (`update_take_failure`).
The updater's crate is built WITHOUT its `zip` feature — only for v1-style
zipped Windows installers, and every zip 4.x is yanked.
- **Stem playback** (decided 2026-09-30): a stem FILE always loads its four - **Stem playback** (decided 2026-09-30): a stem FILE always loads its four
stems (`trackStemsFor` / `trackStemUrl` in `api.ts`) and the deck plays stems (`trackStemsFor` / `trackStemUrl` in `api.ts`) and the deck plays
their SUM, as Traktor's stem deck does — the mix stream is never decoded, their SUM, as Traktor's stem deck does — the mix stream is never decoded,
@@ -1045,8 +1095,9 @@ Two independent apps that talk over HTTP:
persists; a toggle under the zoom buttons draws the RAW signal instead persists; a toggle under the zoom buttons draws the RAW signal instead
of bars — `lib/rawWave.ts`, below; persisted as `mainWaveRaw`) over of bars — `lib/rawWave.ts`, below; persisted as `mainWaveRaw`) over
`OverviewWaveform`, which frames the main view's visible range around the `OverviewWaveform`, which frames the main view's visible range around the
playhead (it takes `secPerView` for exactly that). **Controls**: play, CUE, `LoopControls`, then EITHER playhead (it takes `secPerView` for exactly that). **Controls**: play, CUE, `LoopControls`, then
`HotcueBar` OR — in **Grid mode** — `GridEditStrip`, then `TempoControls` (where `cues.memory_cues`) the **Hot / Mem** switch (`ModeSwitch`, the same component as BEAT / MAN), then
`HotcueBar`, `MemoryCueStrip` (Mem) OR — in **Grid mode** — `GridEditStrip`, then `TempoControls`
(±0.01 / ±0.25, ÷2 ×2, tap, lock) and the Grid toggle. The row is a (±0.01 / ±0.25, ÷2 ×2, tap, lock) and the Grid toggle. The row is a
**container** and gives way in stages instead of overlapping: each pad **container** and gives way in stages instead of overlapping: each pad
queries its own width and drops its name below 4rem (the bank never goes queries its own width and drops its name below 4rem (the bank never goes
@@ -1070,6 +1121,20 @@ Two independent apps that talk over HTTP:
and only jump the playhead when no loop is engaged. The move sets the new and only jump the playhead when no loop is engaged. The move sets the new
loop BEFORE seeking: `PlaybackEngine.seek` honours the loop in force, so loop BEFORE seeking: `PlaybackEngine.seek` honours the loop in force, so
seeking first wraps the playhead back into the old loop. seeking first wraps the playhead back into the old loop.
- **Memory cues** (decided 2026-10-16, [the discussion](.claude/discussions/discuss-memory-cues-2026-10-16.md)):
Mem mode replaces the pads with `MemoryCueStrip` — chips in TIME order,
scrolling sideways, labelled by name else `m:ss.s`, after a + Memory button
(at the snapped playhead, or the engaged loop as a memory loop;
disabled with the reason past `max_memory_cues`). **Clicking a chip is
CDJ CALL, not a trigger**: jump there and make it the CUE point (paused
stays paused), a memory loop engaging as a loop pad does (`enterCue`).
Right-click: Type (point types, where the platform has more than one —
Traktor; `set_memory_cue_type`, a loop is not retyped), Colour
(`memory_palette`), Rename… (the shared `RenameField`), Delete — no move
(rekordbox has none: a move is delete + add). An uncoloured memory cue
draws in its TYPE colour, exactly as a hot cue does (`cueColor` /
`core/cue_colors.effective_color`). Digit keys stay on hot cues. The mode
persists as `cueBankMode`.
- **Hotcue edits live on the pad's right-click menu** (type as one-click - **Hotcue edits live on the pad's right-click menu** (type as one-click
choices, a colour swatch grid + Default where `cues.color` is `palette` — choices, a colour swatch grid + Default where `cues.color` is `palette` —
`ContextMenu`'s `swatches` item, Rename…, Delete); there is no standalone `ContextMenu`'s `swatches` item, Rename…, Delete); there is no standalone
@@ -1100,9 +1165,24 @@ Two independent apps that talk over HTTP:
`cues.palette`; a `free` platform gets no picker yet), the rating scale `cues.palette`; a `free` platform gets no picker yet), the rating scale
(`tracks.rating_max`), the grid Lock button (`grid.lockable`). Per-node playlist flags (`can_rename`, `can_delete`, (`tracks.rating_max`), the grid Lock button (`grid.lockable`). Per-node playlist flags (`can_rename`, `can_delete`,
`can_add_tracks`) gate the sidebar and the context menu's "Add to" — each on its OWN flag, `can_add_tracks`) gate the sidebar and the context menu's "Add to" — each on its OWN flag,
since a platform may allow renaming but not deleting. Carried but deliberately unused until a second adapter since a platform may allow renaming but not deleting. Memory cues: the deck's
exists: `slot_labels: 'letter'`, `loops: 'separate_bank'`, and Hot / Mem toggle shows on `cues.memory_cues`, + Memory refuses past
memory-cue *editing* (one-platform features stay preserved-but-uneditable). `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 - `lib/trackColumns.tsx` — single source of truth for the library table's
columns (defs, default widths/visibility/order, the Columns-menu list, the columns (defs, default widths/visibility/order, the Columns-menu list, the
inline `InlineEdit` cell, and the `TableMeta.onEditField` augmentation). inline `InlineEdit` cell, and the `TableMeta.onEditField` augmentation).
@@ -1176,6 +1256,20 @@ serialization path.** It enforces:
moving back is byte-identical; a folder moves with its subtree and answers moving back is byte-identical; a folder moves with its subtree and answers
its new path id; into its own descendant / beside a namesake is refused with its new path id; into its own descendant / beside a namesake is refused with
nothing changed; a smart playlist moves by its path id; a no-op is not dirty. nothing changed; a smart playlist moves by its path id; a no-op is not dirty.
And **memory cues** (P): add / rename / delete change only that `<ENTRY>`'s
cue lines, in Traktor's shape (`HOTCUE="-1"`, `n.n.`), add + delete
round-trips byte for byte, new cues (hot ones too) are INSERTED by START,
and a pad + memory cue at one START project once, as the pad.
And **`>` / quotes in attribute values** (Q): Traktor leaves `>` raw, and
an empty element holding one (4.5's default "Recently added" query
`$IMPORTDATE >= MONTHS_AGO(1)`, a comment, a file name) once came back
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. The guard that catches serialization regressions like the lxml reformatting bug.
- `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays - `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays
Traktor-valid, backup-first, COLLECTION byte-identical, original untouched; Traktor-valid, backup-first, COLLECTION byte-identical, original untouched;
@@ -1276,7 +1370,13 @@ serialization path.** It enforces:
and the counter, pointing at its OWN row (found by meaning, not name); a and the counter, pointing at its OWN row (found by meaning, not name); a
missing key adds one `djmdKey` row as rekordbox creates its own — its missing key adds one `djmdKey` row as rekordbox creates its own — its
spelling, `Seq` NULL, its own USN (so through the ORM; a raw insert is spelling, `Seq` NULL, its own USN (so through the ORM; a raw insert is
left unstamped) — which the next `set_key` reuses. left unstamped) — which the next `set_key` reuses. And **memory cues** (G2):
M1's measured row shapes (point: `Color -1`, CTI NULL; loop: `255/0`,
`Comment ''`), colour in `Color` (Blue 6) with CTI NULL, No Color = 255, the
mirror in ROW order, rename touching only `Comment` (+ the USN pyrekordbox
stamps on every cue write — rekordbox's own leave it NULL, and it has
accepted ours), the 11th refused with nothing changed, delete removing the
row outright.
- `test_onelibrary_adapter.py` — the third adapter against the same contract. - `test_onelibrary_adapter.py` — the third adapter against the same contract.
Unlike the Rekordbox tests it needs **nothing installed and nothing plugged Unlike the Rekordbox tests it needs **nothing installed and nothing plugged
in**: it runs against `fixtures/onelibrary/`, a real rekordbox 7 export trimmed in**: it runs against `fixtures/onelibrary/`, a real rekordbox 7 export trimmed
@@ -1307,10 +1407,15 @@ serialization path.** It enforces:
new `PQTZ` keeps the marker where it was (rekordbox's own halving moved its new `PQTZ` keeps the marker where it was (rekordbox's own halving moved its
anchor 6 ms; within 10 ms). Then fidelity on the demo drive: nothing on the anchor 6 ms; within 10 ms). Then fidelity on the demo drive: nothing on the
drive before Save, only the touched tags change (in place, order kept), a drive before Save, only the touched tags change (in place, order kept), a
moved pad keeps colour and name, memory cues refused, swatches only, a moved pad keeps colour and name, swatches only, a
same-tempo marker collapses (a per-beat grid has no markers), another app's same-tempo marker collapses (a per-beat grid has no markers), another app's
ANLZ write refused, an `.EXT` with no `PCO2` keeps every pad, a track with no ANLZ write refused, an `.EXT` with no `PCO2` keeps every pad, a track with no
analysis files refuses. analysis files refuses. And **memory cues against rekordbox's own edits**
(`fixtures/onelibrary-memory-edits`): add a cue, add a loop, add up to 10, recolour,
comment and delete, each replayed with `memory_cues` on `before/` and equal
to `after/` tag for tag (the `.DAT` hot list compared as a set — rekordbox
re-sorts it); then through the adapter on the demo drive: palette, cap,
NotFound, nothing before Save, and Save changing only the two memory lists.
- `test_onelibrary_pdb.py` — the Device Library rebuild on Goober's own - `test_onelibrary_pdb.py` — the Device Library rebuild on Goober's own
`export.pdb`: every track row reads (rows end at their last string; stale `export.pdb`: every track row reads (rows end at their last string; stale
heap tails ignored), a no-op rebuild returns None and a no-op save leaves the heap tails ignored), a no-op rebuild returns None and a no-op save leaves the
@@ -1327,7 +1432,9 @@ serialization path.** It enforces:
and files only at Save, renumbers playlists and prunes empty folders. and files only at Save, renumbers playlists and prunes empty folders.
- `test_import.py` — the import feature end to end: a drive's tracks into a temp - `test_import.py` — the import feature end to end: a drive's tracks into a temp
copy of the real collection. Asserts the prep survives (hot cues keep their copy of the real collection. Asserts the prep survives (hot cues keep their
PAD, memory cues fill spare ones, the flexible grid crosses intact, no PAD, memory cues arrive as Traktor memory cues (`HOTCUE="-1"`; one on a
pad's START shows once, as the pad), a hot cue displaced with no spare pad
becomes a memory cue instead of being dropped, the flexible grid crosses intact, no
companion cue is invented), that the existing 8,485 entries render companion cue is invented), that the existing 8,485 entries render
byte-identically, that the job registry runs/fails/cancels, and that a byte-identically, that the job registry runs/fails/cancels, and that a
cancelled import leaves **no orphaned audio and an untouched collection**. cancelled import leaves **no orphaned audio and an untouched collection**.
@@ -1569,6 +1676,9 @@ frontend at `http://localhost:5173`.
`add_entry` write BOTH, the text in the collection's majority notation `add_entry` write BOTH, the text in the collection's majority notation
(`TraktorStore.key_notation()`; an empty collection — an export — takes a (`TraktorStore.key_notation()`; an empty collection — an export — takes a
Traktor-native source's own, so Traktor→Traktor keeps the user's). 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. - **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 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 (flexible beatgrids, 3.4+); `<TEMPO BPM>` mirrors the **first marker by
@@ -1590,6 +1700,16 @@ frontend at `http://localhost:5173`.
load-bearing: 49 uncoloured cues and 18 *loops* also sit within 1 ms of a load-bearing: 49 uncoloured cues and 18 *loops* also sit within 1 ms of a
marker and must not be dragged or deleted. `backend/konduktor/beatgrid.py` marker and must not be dragged or deleted. `backend/konduktor/beatgrid.py`
is the single shared definition of all of this. is the single shared definition of all of this.
- **Memory cues are `CUE_V2`s on no pad** (`HOTCUE="-1"`) WITHOUT a `<GRID>`
— a grid marker is also `HOTCUE="-1"`, and the `<GRID>` child is the only
test (`projection.is_memory_cue`). Measured in Traktor 4.5 (kit M3,
2026-10-16): any type, no limit, drawn on the waveform, reached with the
cue panel's ‹ ›, a name shown in the cue panel, and a Konduktor-written one
kept byte for byte. MAP puts a pad on one and leaves the memory cue at the
same START; Traktor draws ONE marker, so the projection shows the pad only.
Their id is content-derived (`m:<START>:<TYPE>:<LEN>:<n>`). Traktor keeps
`CUE_V2` sorted by START, so the store INSERTS new cues in place
(`_insert_cue`) rather than appending.
- **Playlist tree**: recurse `nml.playlists.node.subnodes.node`. A node's `.type` - **Playlist tree**: recurse `nml.playlists.node.subnodes.node`. A node's `.type`
is `FOLDER`, `PLAYLIST`, or `SMARTLIST`. Smart playlists are rule-based and is `FOLDER`, `PLAYLIST`, or `SMARTLIST`. Smart playlists are rule-based and
have no static entry list. `PlaylistNode.id` is the playlist's stable `UUID`; have no static entry list. `PlaylistNode.id` is the playlist's stable `UUID`;
@@ -1698,7 +1818,22 @@ that number and nothing else — everything derives from it:
- **CI release** — `.github/workflows/build.yml` reads it with - **CI release** — `.github/workflows/build.yml` reads it with
`jq .version frontend/package.json` and tags each push `jq .version frontend/package.json` and tags each push
`v<version>-b<run_number>` (release name `Konduktor v<version>-b<run_number>`). `v<version>-b<run_number>` (release name `Konduktor v<version>-b<run_number>`).
The `-b<N>` suffix keeps every push's tag/release unique. The `-b<N>` suffix keeps every push's tag/release unique. Each release also
carries its files under user-facing names, laid out by
`.github/scripts/release_assets.py`: `Konduktor-<v>-macOS.dmg`,
`Konduktor-<v>-Windows-Setup.exe` (also the Windows update package),
`Konduktor-<v>-app-updater.tar.gz` (the macOS update package) and the
in-app updater's `latest.json` (`version` = package.json's, each platform's
URL + signature inlined; the name is fixed — the app asks for it by name).
The notes open with a "Download" section linking the two installers, above
the PR's patch notes or GitHub's generated ones; the update dialog reads
only "What's Changed" and skips "Download" when falling back.
`bundle.createUpdaterArtifacts` signs those with the updater key: the
repo secrets `TAURI_SIGNING_PRIVATE_KEY` / `_PASSWORD`, public half in
`tauri.conf.json` `plugins.updater.pubkey`. **Losing the private key means
installed copies can never update themselves again** — it is backed up
outside the repo. A local build without it passes
`--config src-tauri/tauri.unsigned.conf.json` (`build.ps1` does so itself).
- **NOT a source**: `src-tauri/Cargo.toml` `version` is inert Rust crate metadata - **NOT a source**: `src-tauri/Cargo.toml` `version` is inert Rust crate metadata
(Tauri uses the config's `../package.json`); don't treat it as the app version. (Tauri uses the config's `../package.json`); don't treat it as the app version.
@@ -1787,9 +1922,11 @@ that number and nothing else — everything derives from it:
that swap so `SaveBar` still saves collection edits. While a device's that swap so `SaveBar` still saves collection edits. While a device's
capabilities load the fallback is read-only, never the collection's — capabilities load the fallback is read-only, never the collection's —
guessing "writable" for one frame would offer an edit bound for the wrong guessing "writable" for one frame would offer an edit bound for the wrong
library. Lossiness follows the settled rule: memory cues become hot cues in library. Lossiness follows the settled rule: memory cues stay memory cues
spare pads (earliest first), cue colour is dropped (Traktor derives it from (Traktor's `HOTCUE="-1"`; until 2026-10-16 they were promoted to spare
type). pads), a hot cue whose pad is taken moves to a spare pad, else becomes a
memory cue; cue colour is dropped (Traktor derives it from type). Into
Rekordbox / OneLibrary only the first 10 memory cues cross (rekordbox's cap).
- ✅ OneLibrary adapter — **reading and editing done**, at parity with the - ✅ OneLibrary adapter — **reading and editing done**, at parity with the
Rekordbox adapter (2026-10-01, [decisions](.claude/discussions/discuss-onelibrary-editing-2026-10-01.md)). Rekordbox adapter (2026-10-01, [decisions](.claude/discussions/discuss-onelibrary-editing-2026-10-01.md)).
A OneLibrary USB drive opens, projects, browses and searches: tracks, A OneLibrary USB drive opens, projects, browses and searches: tracks,
@@ -1798,8 +1935,7 @@ that number and nothing else — everything derives from it:
files, each rule matching rekordbox's measured edit), the `export.pdb` rebuild files, each rule matching rekordbox's measured edit), the `export.pdb` rebuild
on save, adding/removing tracks (the library places the audio), Save via a on save, adding/removing tracks (the library places the audio), Save via a
working copy, and "Open for editing…" on a Devices row — all verified in working copy, and "Open for editing…" on a Devices row — all verified in
rekordbox 7. Same gaps as Rekordbox: cover-art writing, memory-cue editing, rekordbox 7. Same gaps as Rekordbox: cover-art writing, stem conversion. All format research — including the schema, which has no
stem conversion. All format research — including the schema, which has no
public spec — is in [.claude/handoffs/onelibrary-adapter.md](.claude/handoffs/onelibrary-adapter.md). public spec — is in [.claude/handoffs/onelibrary-adapter.md](.claude/handoffs/onelibrary-adapter.md).
- 🟡 **Export/conversion** — **in progress.** Both the design AND the user flow - 🟡 **Export/conversion** — **in progress.** Both the design AND the user flow
are settled; see are settled; see
@@ -1962,7 +2098,8 @@ that number and nothing else — everything derives from it:
0x2C060E. **Parity with the OneLibrary target is done and verified in 0x2C060E. **Parity with the OneLibrary target is done and verified in
Rekordbox 7**: cue colours (palette code in `djmdCue.ColorTableIndex`, Rekordbox 7**: cue colours (palette code in `djmdCue.ColorTableIndex`,
`Color` -1 — coloured loops included), memory cues (`store.add_memory_cue`, `Color` -1 — coloured loops included), memory cues (`store.add_memory_cue`,
export-only: the adapter still refuses memory-cue edits), and artwork the same write as the adapter's memory-cue edit: colour in `Color` from the
memory palette, the first 10 per track), and artwork
(`share/PIONEER/Artwork/<uuid[:3]>/<uuid[3:]>/artwork.jpg` fit to 800 px plus (`share/PIONEER/Artwork/<uuid[:3]>/<uuid[3:]>/artwork.jpg` fit to 800 px plus
`_m` 240 / `_s` 80 letterboxed, `ImagePath` -> artwork.jpg). The exporter writes `_m` 240 / `_s` 80 letterboxed, `ImagePath` -> artwork.jpg). The exporter writes
cues through `store.set_cue`/`add_memory_cue`, which share `_write_cue` with cues through `store.set_cue`/`add_memory_cue`, which share `_write_cue` with
@@ -0,0 +1,38 @@
# Memory-cue edits rekordbox 7 made on a stick
Analysis files of six tracks on a OneLibrary test stick written by
rekordbox, before and after **rekordbox 7 itself** edited their MEMORY cues
(kit M2, 2026-10-16; the stick was backed up first and restored afterwards).
`test_onelibrary_anlz.py` replays each edit with Konduktor's helpers on
`before/` and compares the memory lists with `after/` byte for byte.
Only `PPTH`, `PQTZ`, `PCOB`, `PCO2` and `PQT2` are kept, byte for byte — the
waveforms were dropped, as in `onelibrary-goober/`. There is no database and
no audio: `exportLibrary.db` and both pdbs had NO row change for any of these
edits (memory cues on a stick live only in the analysis files).
| File | Track | Edit (one per track) |
|---|---|---|
| `black-bloc` | Justin Hawkes – Black Bloc (VIP) | memory cue ADDED at 2:11.206 |
| `formula` | RL Grime & Juelz – Formula (IMANU Remix) | 4-beat memory LOOP added at 1:20.378 |
| `lift-it` | Tian – Lift It (Hexa Remix) | 8 memory cues added (2 → 10, the cap) |
| `wtf` | Result – WTF (Phace Remix) | the memory loop at 1:53 recoloured Blue |
| `sell-my-soul` | Bensley, Justin Hawkes & Kumarion – Sell My Soul | comment "Loopy" on the memory loop at 1:18 |
| `doomed` | Nemean – Doomed | the memory loop at 2:01 DELETED |
What they show (the full write-up is in
`.claude/discussions/discuss-memory-cues-2026-10-16.md`, kit M2):
- `.DAT` `PCOB` memory list: a new entry is PREPENDED; every entry has status 0
and bytes 24–27 = previous / next index in the list (`ffff` at the ends), so
any add or delete relinks the whole list; the header i32 at offset 20 is
count − 1.
- `.EXT` `PCO2` memory list: a new entry is APPENDED in rekordbox's compact
44-byte form; the others stay byte-identical. The `.EXT`'s `PCOB` memory list
stays empty.
- When rekordbox rewrites a `.DAT` (any memory add or delete), it ALSO
re-sorts the untouched hot-cue `PCOB` into ascending pad order (an export
writes it highest pad first); the entries themselves are unchanged.
Konduktor changes only the list it edits, so the test compares that tag's
entries regardless of order.
- Colour: `PCP2` byte 28, 1-based (Blue = 7), 0 = none. Comment: UTF-16BE + NUL
at byte 44, `len_comment` at 40. Neither touches the `.DAT`.
@@ -26,7 +26,7 @@ from ...core.capabilities import Capabilities
from ...core.model import GridMarker, HotcueChip, PlaylistNode, Track, TrackCues from ...core.model import GridMarker, HotcueChip, PlaylistNode, Track, TrackCues
from ...core.pathmap import PathMapping, common_dir_prefix from ...core.pathmap import PathMapping, common_dir_prefix
from ...core.query import TrackIndex from ...core.query import TrackIndex
from ..rekordbox import palette from ..rekordbox import memory_palette, palette
from ..rekordbox.cue_types import WRITABLE_CUE_TYPES from ..rekordbox.cue_types import WRITABLE_CUE_TYPES
from ...exporter import MANIFEST_NAME from ...exporter import MANIFEST_NAME
from . import capabilities as caps from . import capabilities as caps
@@ -404,6 +404,12 @@ class OneLibraryAdapter:
self._refresh(track_id) self._refresh(track_id)
return self._index.get(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: def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
self._refuse("Editing cover art") self._refuse("Editing cover art")
@@ -457,10 +463,8 @@ class OneLibraryAdapter:
) -> TrackCues: ) -> TrackCues:
self._require_writable("Editing cues") self._require_writable("Editing cues")
if role != "hotcue": if role != "hotcue":
# Preserved-but-uneditable, exactly as in the Rekordbox adapter. # A memory cue has no slot to set; it has its own commands.
raise Unsupported( raise InvalidCommand("Memory cues are added with add_memory_cue, not set_cue")
"Memory cues are shown but cannot be edited — only hot cues are writable"
)
self._check_cue_type(cue_type) self._check_cue_type(cue_type)
self._store.set_cue(track_id, slot=slot, start_sec=start_sec, cue_type=cue_type, self._store.set_cue(track_id, slot=slot, start_sec=start_sec, cue_type=cue_type,
length_sec=length_sec, name=name) length_sec=length_sec, name=name)
@@ -494,6 +498,53 @@ class OneLibraryAdapter:
self._store.place_cues(track_id, cues, overwrite=overwrite) self._store.place_cues(track_id, cues, overwrite=overwrite)
return self._refresh_cues(track_id) return self._refresh_cues(track_id)
# ---- commands: memory cues --------------------------------------------
@staticmethod
def _memory_byte(color: str | None) -> int:
if color is None:
return 0
code = memory_palette.code_for(color)
if code is None:
raise InvalidCommand(f"{color!r} is not one of rekordbox's memory cue colours")
return memory_palette.anlz_byte(code)
def add_memory_cue(
self,
track_id: str,
*,
start_sec: float,
cue_type: str,
length_sec: float = 0.0,
name: str | None = None,
color: str | None = None,
) -> TrackCues:
self._require_writable("Editing cues")
self._check_cue_type(cue_type)
self._store.add_memory_cue(track_id, start_sec=start_sec, cue_type=cue_type,
length_sec=length_sec, name=name,
color_id=self._memory_byte(color))
return self._refresh_cues(track_id)
def rename_memory_cue(self, track_id: str, cue_id: str, name: str | None) -> TrackCues:
self._require_writable("Editing cues")
self._store.rename_memory_cue(track_id, cue_id, name)
return self._refresh_cues(track_id)
def set_memory_cue_type(self, track_id: str, cue_id: str, cue_type: str) -> TrackCues:
# rekordbox has one point type, so there is nothing to choose; a memory
# cue is a cue or a loop by its length.
raise Unsupported("rekordbox memory cues have no type to change")
def set_memory_cue_color(self, track_id: str, cue_id: str, color: str | None) -> TrackCues:
self._require_writable("Editing cues")
self._store.set_memory_cue_color(track_id, cue_id, self._memory_byte(color))
return self._refresh_cues(track_id)
def delete_memory_cue(self, track_id: str, cue_id: str) -> TrackCues:
self._require_writable("Deleting cues")
self._store.delete_memory_cue(track_id, cue_id)
return self._refresh_cues(track_id)
# ---- commands: beatgrid ----------------------------------------------- # ---- commands: beatgrid -----------------------------------------------
@staticmethod @staticmethod
def _markers_from(markers: list) -> list: def _markers_from(markers: list) -> list:
@@ -36,8 +36,8 @@ from ...core.capabilities import (
SaveCapabilities, SaveCapabilities,
TrackCapabilities, TrackCapabilities,
) )
from ..rekordbox import palette from ..rekordbox import memory_palette, palette, track_palette
from ..rekordbox.cue_types import WRITABLE_CUE_TYPES 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, # Pads A-H. Unlike `djmdCue.Kind`, the ANLZ slot number is a dense 1-based index,
# so the bank really is 1..8 (see `cues.py`). # so the bank really is 1..8 (see `cues.py`).
@@ -61,10 +61,12 @@ def capabilities_for(
editable=True, editable=True,
hotcue_slots=HOTCUE_SLOTS, hotcue_slots=HOTCUE_SLOTS,
slot_labels="letter", slot_labels="letter",
# OneLibrary carries memory cues, as Rekordbox does: projected and # Memory cues, editable as in Rekordbox — in the ANLZ files, the
# preserved, NOT editable (the two-platform rule, as in Rekordbox). # way rekordbox 7 edits them on a stick (measured, kit M2).
memory_cues=True, memory_cues=True,
max_memory_cues=None, max_memory_cues=MAX_MEMORY_CUES,
memory_color="palette",
memory_palette=list(memory_palette.SWATCHES),
types=WRITABLE_CUE_TYPES, types=WRITABLE_CUE_TYPES,
color="palette", color="palette",
palette=[palette.hex_for(code) for code in palette.SWATCHES], palette=[palette.hex_for(code) for code in palette.SWATCHES],
@@ -85,6 +87,8 @@ def capabilities_for(
addable=not read_only, addable=not read_only,
removable=not read_only, removable=not read_only,
key_writable=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, places_audio=True,
# `artwork` gates EDITING, which Rekordbox does not do yet either # `artwork` gates EDITING, which Rekordbox does not do yet either
# (parity). Reading works: `store.cover_art` follows # (parity). Reading works: `store.cover_art` follows
+24 -7
View File
@@ -37,7 +37,7 @@ from __future__ import annotations
import logging import logging
from ...core.model import CuePoint from ...core.model import CuePoint
from ..rekordbox import palette from ..rekordbox import memory_palette, palette
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@@ -112,6 +112,13 @@ def _to_cue(entry, *, with_color: bool, editable: bool = False) -> CuePoint | No
slot = None if role == "memory" else hot_cue - 1 slot = None if role == "memory" else hot_cue - 1
comment = getattr(entry, "comment", None) comment = getattr(entry, "comment", None)
if role == "memory":
# A memory cue's colour is byte 28 (`memory_palette`), not the hot-cue
# code + RGB tail, which stays zero on one.
color = (memory_palette.hex_for(memory_palette.from_anlz_byte(
int(getattr(entry, "color_id", 0) or 0))) if with_color else None)
else:
color = _color(entry) if with_color else None
return CuePoint( return CuePoint(
name=(str(comment) or None) if comment else None, name=(str(comment) or None) if comment else None,
type="loop" if length > 0 else "cue", type="loop" if length > 0 else "cue",
@@ -119,16 +126,26 @@ def _to_cue(entry, *, with_color: bool, editable: bool = False) -> CuePoint | No
start=start_ms / 1000.0, start=start_ms / 1000.0,
length=length, length=length,
slot=slot, slot=slot,
color=_color(entry) if with_color else None, color=color,
# Hot cues are editable on a drive opened for editing (the caller says # Editable on a drive opened for editing (the caller says so), memory
# so). MEMORY cues never are — preserved-but-uneditable, as in the # cues included; browsing a device is read-only.
# Rekordbox adapter (the two-platform rule). editable=editable,
editable=editable and role == "hotcue", readonly_reason=None if editable else "platform_managed",
readonly_reason=None if editable and role == "hotcue" else "platform_managed",
grid_marker=None, grid_marker=None,
id=memory_cue_id(entry) if role == "memory" else None,
) )
def memory_cue_id(entry) -> str:
"""A memory cue's `CuePoint.id`: its STORED position, kind and loop end.
Content-derived, so it is the same on every read and in both lists (`PCOB`
in the .DAT, `PCO2` in the .EXT, which order the same cues differently);
an index would not be. Two memory cues identical in all three are one cue
to `_dedupe` already, so the first match is the one meant."""
return f"m:{int(entry.time)}:{_entry_kind(getattr(entry, 'type', ENTRY_CUE))}:{int(getattr(entry, 'loop_time', NO_LOOP))}"
def _entries(anlz, tag_type: str) -> list: def _entries(anlz, tag_type: str) -> list:
"""Every entry of every `tag_type` tag in one parsed ANLZ file. """Every entry of every `tag_type` tag in one parsed ANLZ file.
@@ -121,10 +121,10 @@ def rebuild(existing: bytes, session) -> bytes | None:
# ---- tracks ----------------------------------------------------------------- # ---- tracks -----------------------------------------------------------------
old_tracks = {pdb.row_id(pdb.TRACKS, r): r for r in pdb.table_rows(existing, pdb.TRACKS)} old_tracks = {pdb.row_id(pdb.TRACKS, r): r for r in pdb.table_rows(existing, pdb.TRACKS)}
want = {} 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( comment, *fresh) in session.execute(text(
"SELECT content_id, title, artist_id_artist, artist_id_remixer, album_id, genre_id, " "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, " "path, fileName, fileSize, fileType, bitrate, bitDepth, samplingRate, length, "
"analysisDataFilePath, dateAdded, key_id, image_id FROM content")): "analysisDataFilePath, dateAdded, key_id, image_id FROM content")):
cid = int(cid) cid = int(cid)
@@ -134,7 +134,8 @@ def rebuild(existing: bytes, session) -> bytes | None:
fields, strings = _fresh_track(cid, *fresh) fields, strings = _fresh_track(cid, *fresh)
fields = {**fields, "artist_id": artist or 0, "remixer_id": remixer or 0, 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, "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)} "year": int(year or 0)}
strings = {**strings, "title": title or "", "comment": comment or "", strings = {**strings, "title": title or "", "comment": comment or "",
"release_date": released or ""} "release_date": released or ""}
+26 -10
View File
@@ -44,7 +44,8 @@ from pathlib import Path
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
from ...core.cue_colors import effective_color from ...core.cue_colors import effective_color
from ..rekordbox import anlz_writer as W from ..rekordbox import anlz_writer as W
from ..rekordbox import artwork, 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.beatgrid import beats_from_markers
from ..rekordbox.projection import render_key from ..rekordbox.projection import render_key
from .capabilities import capabilities_for from .capabilities import capabilities_for
@@ -208,13 +209,13 @@ class OneLibraryExporter:
con.execute( con.execute(
"INSERT INTO content (content_id, title, titleForSearch, bpmx100, length, " "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, " "djComment, rating, releaseDate, dateAdded, path, fileName, fileSize, "
"fileType, bitrate, bitDepth, samplingRate, isHotCueAutoLoadOn, " "fileType, bitrate, bitDepth, samplingRate, isHotCueAutoLoadOn, "
"isKuvoDeliverStatusOn, masterDbId, masterContentId, " "isKuvoDeliverStatusOn, masterDbId, masterContentId, "
"analysisDataFilePath, analysedBits, contentLink, hasModified, cueUpdateCount, " "analysisDataFilePath, analysedBits, contentLink, hasModified, cueUpdateCount, "
"analysisDataUpdateCount, informationUpdateCount) " "analysisDataUpdateCount, informationUpdateCount) "
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
( (
content_id, track.title, (track.title or "").lower(), content_id, track.title, (track.title or "").lower(),
int(round((track.bpm or 0) * 100)) or None, track.length, int(round((track.bpm or 0) * 100)) or None, track.length,
@@ -228,6 +229,7 @@ class OneLibraryExporter:
# where the deck expects "Cm". Rendered from the parsed wheel. # where the deck expects "Cm". Rendered from the parsed wheel.
self._lookup(con, "key", lookups["key"], self._lookup(con, "key", lookups["key"],
render_key(track.key_wheel, track.key_mode)), render_key(track.key_wheel, track.key_mode)),
track_palette.id_for(track.color),
image_id, image_id,
track.comment, track.rating or 0, track.release_date, track.comment, track.rating or 0, track.release_date,
date.today().isoformat(), rel, item.destination.name, size, date.today().isoformat(), rel, item.destination.name, size,
@@ -359,15 +361,29 @@ class OneLibraryExporter:
too far along. too far along.
""" """
out: list[dict] = [] out: list[dict] = []
for cue in (item.cues.cues if item.cues else []): memory = 0
for cue in sorted(item.cues.cues if item.cues else [], key=lambda c: c.start):
is_loop = cue.type == "loop" or cue.length > 0 is_loop = cue.type == "loop" or cue.length > 0
# A hot cue carries what Konduktor SHOWS — stored colour, else the is_memory = cue.role == "memory" or cue.slot is None
# type's (blue cue, green loop) — as a rekordbox palette CODE, which if is_memory:
# is what rekordbox draws from; "unset" draws its own defaults. A # rekordbox keeps 10 (earliest first; the rest are dropped, per
# memory cue keeps rekordbox's own "unset". # the lossiness rule). A memory cue's colour is PCP2 byte 28 from
code, rgb = palette.code_for(cue.color if cue.role == "memory" else effective_color(cue)) # its own 8-colour palette — what Konduktor SHOWS (stored, else
# the type's), as for a hot cue; the hot-cue code + RGB stay zero.
if memory >= MAX_MEMORY_CUES:
continue
memory += 1
code, rgb = 0, (0, 0, 0)
color_id = memory_palette.anlz_byte(memory_palette.nearest_code(effective_color(cue)))
else:
# What Konduktor SHOWS — stored colour, else the type's (blue cue,
# green loop) — as a rekordbox palette CODE, which is what
# rekordbox draws from; "unset" draws its own defaults.
code, rgb = palette.code_for(effective_color(cue))
color_id = 0
out.append({ out.append({
"hot_cue": 0 if cue.role == "memory" or cue.slot is None else cue.slot + 1, "color_id": color_id,
"hot_cue": 0 if is_memory else cue.slot + 1,
"kind": 2 if is_loop else 1, "kind": 2 if is_loop else 1,
"time_ms": int(round(timebase.to_pioneer(cue.start, off) * 1000)), "time_ms": int(round(timebase.to_pioneer(cue.start, off) * 1000)),
"loop_ms": (int(round(timebase.to_pioneer(cue.start + cue.length, off) * 1000)) "loop_ms": (int(round(timebase.to_pioneer(cue.start + cue.length, off) * 1000))
@@ -0,0 +1,102 @@
"""Memory-cue edits on a track's two analysis files, the way rekordbox 7 makes them.
Pure functions over parsed `AnlzFile`s, so they are pinned byte for byte
against rekordbox's own edits (`fixtures/onelibrary-memory-edits`, kit M2,
2026-10-16) without a drive; the store adds the drive, the time base and Save.
A stick keeps memory cues ONLY in the analysis files — the database and both
pdbs keep every row — in two lists kept in OPPOSITE orders:
* `.DAT` `PCOB` memory: a new cue is PREPENDED, and the whole list is
relinked (`anlz_writer.relinked_memory_pcpts`: status 0, prev/next
indexes) on any add or delete; header field = count − 1.
* `.EXT` `PCO2` memory: a new cue is APPENDED in the compact 44-byte form;
every other entry keeps its bytes. The `.EXT`'s own `PCOB` memory list
stays empty.
A colour is `PCP2` byte 28 and a name the `PCP2` comment; neither touches the
`.DAT`. A cue is addressed by `cues.memory_cue_id` (stored time, kind, loop
end), which is the same in both lists.
"""
from __future__ import annotations
from ..rekordbox import anlz_file
from ..rekordbox import anlz_writer as W
from .cues import memory_cue_id
DAT_ORDER = ("PPTH", "PVBR", "PQTZ", "PWAV", "PWV2", "PCOB")
EXT_ORDER = ("PPTH", "PWV3", "PCOB", "PCO2")
def entries(f: anlz_file.AnlzFile, kind: str) -> list[bytes]:
"""The raw entries of a file's `kind` (PCOB / PCO2) MEMORY list."""
i = f.find(kind, anlz_file.LIST_MEMORY)
return anlz_file.raw_entries(f.tags[i]) if i is not None else []
def count(ext: anlz_file.AnlzFile) -> int:
return len(entries(ext, "PCO2"))
def _matches(entry: bytes, cue_id: str) -> bool:
return memory_cue_id(anlz_file.decode_entry(entry)) == cue_id
def _put(dat, ext, pcob: list[bytes] | None, pco2: list[bytes] | None) -> None:
if pcob is not None:
dat.put("PCOB", W.pcob_tag(anlz_file.LIST_MEMORY, W.relinked_memory_pcpts(pcob)),
list_kind=anlz_file.LIST_MEMORY, after=DAT_ORDER)
if pco2 is not None:
ext.put("PCO2", W.pco2_tag(anlz_file.LIST_MEMORY, pco2),
list_kind=anlz_file.LIST_MEMORY, after=EXT_ORDER)
def add(dat, ext, *, kind: int, time_ms: int, loop_ms: int | None, beats: int | None,
name: str | None = None, color_id: int = 0) -> None:
"""Add one memory cue (kind 1 cue, 2 loop): prepended to the `.DAT`'s list,
appended — compact unless named — to the `.EXT`'s."""
pcp2 = W.pcp2_compact_entry(kind=kind, time_ms=time_ms, loop_ms=loop_ms,
beats=beats, color_id=color_id)
if name:
pcp2 = anlz_file.entry_with_comment(pcp2, name)
pcpt = W.pcpt_entry(hot_cue=0, kind=kind, time_ms=time_ms, loop_ms=loop_ms)
_put(dat, ext, [pcpt] + entries(dat, "PCOB"), entries(ext, "PCO2") + [pcp2])
def _index(ext, cue_id: str) -> tuple[list[bytes], int | None]:
pco2 = entries(ext, "PCO2")
return pco2, next((n for n, e in enumerate(pco2) if _matches(e, cue_id)), None)
def rename(ext, cue_id: str, name: str | None) -> bool:
"""Rename in the `.EXT` only; False if no such cue."""
pco2, i = _index(ext, cue_id)
if i is None:
return False
pco2[i] = anlz_file.entry_with_comment(pco2[i], name)
_put(None, ext, None, pco2)
return True
def recolour(ext, cue_id: str, color_id: int) -> bool:
"""Byte 28 of the cue's `PCP2` entry, nothing else; False if no such cue."""
pco2, i = _index(ext, cue_id)
if i is None:
return False
pco2[i] = anlz_file.entry_with_color_id(pco2[i], color_id)
_put(None, ext, None, pco2)
return True
def delete(dat, ext, cue_id: str) -> bool:
"""Out of both lists (the `.DAT`'s relinked); False if no such cue."""
pco2, i = _index(ext, cue_id)
if i is None:
return False
del pco2[i]
pcob = entries(dat, "PCOB")
j = next((n for n, e in enumerate(pcob) if _matches(e, cue_id)), None)
if j is not None:
del pcob[j]
_put(dat, ext, pcob if j is not None else None, pco2)
return True
@@ -16,6 +16,7 @@ Field conventions are read off a real rekordbox 7 export rather than guessed:
from __future__ import annotations from __future__ import annotations
from ...core.model import GridMarker, Track, TrackCues from ...core.model import GridMarker, Track, TrackCues
from ..rekordbox import track_palette
from ..rekordbox.projection import parse_key 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 grid_locked=False, # OneLibrary has no grid lock
# What the FILE is, as the deck plays it — see the Rekordbox projection. # What the FILE is, as the deck plays it — see the Rekordbox projection.
media_kind="stem" if stem else "audio", 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)),
) )
@@ -114,7 +117,7 @@ def to_track_cues(cues: list, grid_markers: list[GridMarker]) -> TrackCues:
`cues` are already generic — see `store.cues` for why that boundary sits `cues` are already generic — see `store.cues` for why that boundary sits
where it does — so this is the assembly point rather than a translation. where it does — so this is the assembly point rather than a translation.
Nothing here is editable: a OneLibrary drive is read-only in Konduktor, and Each cue already says whether it is editable (the store knows whether the
`capabilities.writable` says so at the library level. drive was opened for editing or is only being browsed).
""" """
return TrackCues(grid_markers=grid_markers, grid_locked=False, cues=list(cues)) return TrackCues(grid_markers=grid_markers, grid_locked=False, cues=list(cues))
+76 -3
View File
@@ -54,8 +54,9 @@ from ...core.edit_journal import EditJournal
from ...core.grid_edit import ReplaceGridCommands from ...core.grid_edit import ReplaceGridCommands
from ...core.model import CuePoint from ...core.model import CuePoint
from ... import paths from ... import paths
from . import beatgrid, cues as cue_reader 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 anlz_writer as W
from ..rekordbox import beatgrid as rb_beatgrid from ..rekordbox import beatgrid as rb_beatgrid
from .layout import DriveLayout from .layout import DriveLayout
@@ -565,6 +566,23 @@ class OneLibraryStore(ReplaceGridCommands):
db.flush() db.flush()
db.session.expire(row) 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 -------------------------------------------------- # ---- writes: playlists --------------------------------------------------
def _playlist(self, node_id: str): def _playlist(self, node_id: str):
from pyrekordbox.onelibrary import models from pyrekordbox.onelibrary import models
@@ -916,6 +934,60 @@ class OneLibraryStore(ReplaceGridCommands):
self._replace_hot(track_id, hot, None, None) self._replace_hot(track_id, hot, None, None)
self._journal.record("cue", "delete", track_id, f"slot:{slot}") self._journal.record("cue", "delete", track_id, f"slot:{slot}")
# ---- memory cues -------------------------------------------------------
# The list edits — and what rekordbox was measured doing — are in
# `memory_cues`; here: the drive, the time base, the cap and the journal.
MAX_MEMORY_CUES = MAX_MEMORY_CUES # rekordbox stops storing at 10, silently (measured)
def _memory_files(self, track_id: str):
dat, ext = self._editing(track_id)
self._ensure_pco2(dat, ext)
return dat, ext
def add_memory_cue(self, track_id: str, *, start_sec: float, cue_type: str,
length_sec: float = 0.0, name: str | None = None,
color_id: int = 0) -> None:
"""Add a memory cue (a memory loop with a length) the way rekordbox does.
`color_id` is `PCP2` byte 28 (`memory_palette.anlz_byte`), 0 = none."""
from .export import _loop_beats
if start_sec < 0:
raise InvalidCommand("A cue cannot be before the start of the track")
dat, ext = self._memory_files(track_id)
if memory_cues.count(ext) >= self.MAX_MEMORY_CUES:
raise InvalidCommand(
f"rekordbox keeps at most {self.MAX_MEMORY_CUES} memory cues per track"
)
is_loop = cue_type == "loop" and length_sec > 0
off = self._offset(track_id)
time_ms = int(round(timebase.to_pioneer(start_sec, off) * 1000))
loop_ms = int(round(timebase.to_pioneer(start_sec + length_sec, off) * 1000)) if is_loop else None
grid = self.anlz_grid(track_id)
beats = (_loop_beats(start_sec, length_sec, list(zip(grid[2], grid[1], grid[0])))
if is_loop and grid else None)
memory_cues.add(dat, ext, kind=2 if is_loop else 1, time_ms=time_ms, loop_ms=loop_ms,
beats=beats, name=name, color_id=color_id)
self._journal.record("cue", "add", track_id, "memory")
def _memory_edit(self, track_id: str, cue_id: str, op: str, edit) -> None:
dat, ext = self._memory_files(track_id)
if not edit(dat, ext):
raise NotFound(f"No memory cue {cue_id!r} on this track")
self._journal.record("cue", op, track_id, "memory")
def rename_memory_cue(self, track_id: str, cue_id: str, name: str | None) -> None:
self._memory_edit(track_id, cue_id, "modify",
lambda _d, ext: memory_cues.rename(ext, cue_id, name))
def set_memory_cue_color(self, track_id: str, cue_id: str, color_id: int) -> None:
self._memory_edit(track_id, cue_id, "modify",
lambda _d, ext: memory_cues.recolour(ext, cue_id, color_id))
def delete_memory_cue(self, track_id: str, cue_id: str) -> None:
self._memory_edit(track_id, cue_id, "delete",
lambda dat, ext: memory_cues.delete(dat, ext, cue_id))
def hot_slots(self, track_id: str) -> set[int]: def hot_slots(self, track_id: str) -> set[int]:
"""Occupied 0-based slots (pending edits included).""" """Occupied 0-based slots (pending edits included)."""
return {c.slot for c in self.cues(track_id) if c.role == "hotcue" and c.slot is not None} return {c.slot for c in self.cues(track_id) if c.role == "hotcue" and c.slot is not None}
@@ -1127,7 +1199,7 @@ class OneLibraryStore(ReplaceGridCommands):
"isrc, djPlayCount, isHotCueAutoLoadOn, isKuvoDeliverStatusOn, kuvoDeliveryComment, " "isrc, djPlayCount, isHotCueAutoLoadOn, isKuvoDeliverStatusOn, kuvoDeliveryComment, "
"masterDbId, masterContentId, analysisDataFilePath, analysedBits, contentLink, " "masterDbId, masterContentId, analysisDataFilePath, analysedBits, contentLink, "
"hasModified) VALUES (:cid, :title, NULL, '', :bpm, :length, 0, 0, :artist, :remixer, " "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, " ":added, :created, :path, :file, :size, :type, :bitrate, :depth, :rate, '', 0, 1, 1, "
"'', 0, :cid, :anlz, :bits, :link, 0)"), { "'', 0, :cid, :anlz, :bits, :link, 0)"), {
"cid": cid, "title": getattr(track, "title", None) or final.stem, "cid": cid, "title": getattr(track, "title", None) or final.stem,
@@ -1137,6 +1209,7 @@ class OneLibraryStore(ReplaceGridCommands):
"label": lookup("Label", track.label), "label": lookup("Label", track.label),
# Rendered from the parsed wheel: a source's "10m" means nothing here. # Rendered from the parsed wheel: a source's "10m" means nothing here.
"key": self._key_id(track.key_wheel, track.key_mode), "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 "", "image": image_id, "comment": track.comment or "",
"rating": max(0, min(5, int(track.rating or 0))), "year": year, "released": released, "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, "added": datetime.now().strftime("%Y-%m-%d"), "created": created, "path": rel,
+67 -13
View File
@@ -27,7 +27,7 @@ from ...core.model import GridMarker, PlaylistNode, Track, TrackCues
from ...core.pathmap import PathMapping, common_dir_prefix from ...core.pathmap import PathMapping, common_dir_prefix
from ...core.query import TrackIndex from ...core.query import TrackIndex
from . import capabilities as caps from . import capabilities as caps
from . import palette, projection, timebase from . import memory_palette, palette, projection, timebase
from ...core import add_analysis from ...core import add_analysis
from .store import RekordboxStore from .store import RekordboxStore
@@ -260,6 +260,12 @@ class RekordboxAdapter:
self._refresh(track_id) self._refresh(track_id)
return self._index.get(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 ---------------------------------------------- # ---- commands: playlists ----------------------------------------------
def create_playlist(self, name: str, parent_id: str | None = None) -> str: def create_playlist(self, name: str, parent_id: str | None = None) -> str:
self._require_writable("Creating playlists") self._require_writable("Creating playlists")
@@ -303,12 +309,8 @@ class RekordboxAdapter:
) -> TrackCues: ) -> TrackCues:
self._require_writable("Editing cues") self._require_writable("Editing cues")
if role != "hotcue": if role != "hotcue":
# Rekordbox is the ONLY platform with memory cues, so under the # A memory cue has no slot to set; it has its own commands.
# two-platform promotion rule they stay preserved-but-uneditable: raise InvalidCommand("Memory cues are added with add_memory_cue, not set_cue")
# they are projected and shown, never written.
raise Unsupported(
"Memory cues are shown but cannot be edited — only hot cues are writable"
)
self._check_cue_type(cue_type) self._check_cue_type(cue_type)
self._store.set_cue( self._store.set_cue(
track_id, slot=slot, start_sec=start_sec, cue_type=cue_type, track_id, slot=slot, start_sec=start_sec, cue_type=cue_type,
@@ -339,6 +341,53 @@ class RekordboxAdapter:
self._store.delete_cue(track_id, slot) self._store.delete_cue(track_id, slot)
return self._refresh_cues(track_id) return self._refresh_cues(track_id)
# ---- commands: memory cues --------------------------------------------
def _memory_code(self, color: str | None) -> int | None:
if color is None:
return None
code = memory_palette.code_for(color)
if code is None:
raise InvalidCommand(f"{color!r} is not one of rekordbox's memory cue colours")
return code
def add_memory_cue(
self,
track_id: str,
*,
start_sec: float,
cue_type: str,
length_sec: float = 0.0,
name: str | None = None,
color: str | None = None,
) -> TrackCues:
self._require_writable("Editing cues")
self._check_cue_type(cue_type)
self._store.add_memory_cue(
track_id, start_sec=start_sec, cue_type=cue_type, length_sec=length_sec,
name=name, color_code=self._memory_code(color),
)
return self._refresh_cues(track_id)
def rename_memory_cue(self, track_id: str, cue_id: str, name: str | None) -> TrackCues:
self._require_writable("Editing cues")
self._store.rename_memory_cue(track_id, cue_id, name)
return self._refresh_cues(track_id)
def set_memory_cue_type(self, track_id: str, cue_id: str, cue_type: str) -> TrackCues:
# rekordbox has one point type, so there is nothing to choose; a memory
# cue is a cue or a loop by its length.
raise Unsupported("rekordbox memory cues have no type to change")
def set_memory_cue_color(self, track_id: str, cue_id: str, color: str | None) -> TrackCues:
self._require_writable("Editing cues")
self._store.set_memory_cue_color(track_id, cue_id, self._memory_code(color))
return self._refresh_cues(track_id)
def delete_memory_cue(self, track_id: str, cue_id: str) -> TrackCues:
self._require_writable("Deleting cues")
self._store.delete_memory_cue(track_id, cue_id)
return self._refresh_cues(track_id)
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues: def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues:
self._require_writable("Placing cues") self._require_writable("Placing cues")
for cue in cues: for cue in cues:
@@ -521,20 +570,25 @@ class RekordboxAdapter:
def _place_imported_cues(self, track_id: str, cues) -> None: def _place_imported_cues(self, track_id: str, cues) -> None:
"""Hot cues on their own pads; memory cues — and a hot cue with no """Hot cues on their own pads; memory cues — and a hot cue with no
free pad — as memory cues. Colour as the nearest palette swatch.""" free pad — as memory cues, up to rekordbox's 10 (earliest first; the
rest are dropped, per the lossiness rule). Colour as the nearest swatch
of the palette the cue lands in: a hot cue's 16, a memory cue's 8."""
taken: set[int] = set() taken: set[int] = set()
memory = 0
for cue in sorted(cues.cues or [], key=lambda c: c.start): for cue in sorted(cues.cues or [], key=lambda c: c.start):
cue_type = "loop" if getattr(cue, "length", 0) else "cue" cue_type = "loop" if getattr(cue, "length", 0) else "cue"
code, _rgb = palette.code_for(cue.color)
common = dict(start_sec=cue.start, cue_type=cue_type, common = dict(start_sec=cue.start, cue_type=cue_type,
length_sec=getattr(cue, "length", 0.0) or 0.0, length_sec=getattr(cue, "length", 0.0) or 0.0,
name=getattr(cue, "name", None), color_code=code or None) name=getattr(cue, "name", None))
slot = cue.slot if cue.role == "hotcue" else None slot = cue.slot if cue.role == "hotcue" else None
if slot is not None and 0 <= slot < caps.HOTCUE_SLOTS and slot not in taken: if slot is not None and 0 <= slot < caps.HOTCUE_SLOTS and slot not in taken:
self._store.set_cue(track_id, slot=slot, **common) code, _rgb = palette.code_for(cue.color)
self._store.set_cue(track_id, slot=slot, color_code=code or None, **common)
taken.add(slot) taken.add(slot)
else: elif memory < self._store.MAX_MEMORY_CUES:
self._store.add_memory_cue(track_id, **common) self._store.add_memory_cue(
track_id, color_code=memory_palette.nearest_code(cue.color), **common)
memory += 1
def remove_tracks(self, track_ids: list[str]) -> int: def remove_tracks(self, track_ids: list[str]) -> int:
# What goes with a track was measured in Rekordbox 7 — see the store. # What goes with a track was measured in Rekordbox 7 — see the store.
@@ -158,6 +158,9 @@ class CueEntry:
color_green: int | None = None color_green: int | None = None
color_blue: int | None = None color_blue: int | None = None
len_entry: int = 0 len_entry: int = 0
#: `PCP2` byte 28: a MEMORY cue's colour, 1-based, 0 = none (also present
#: in the compact 44-byte form, which has no hot-cue colour tail).
color_id: int = 0
def raw_entries(tag: Tag) -> list[bytes]: def raw_entries(tag: Tag) -> list[bytes]:
@@ -197,6 +200,35 @@ def entry_with_colour(entry: bytes, code: int, rgb: tuple[int, int, int]) -> byt
return entry[:at] + bytes([code & 0xFF, *rgb]) + entry[at + 4:] return entry[:at] + bytes([code & 0xFF, *rgb]) + entry[at + 4:]
def entry_color_id(entry: bytes) -> int:
"""A `PCP2` entry's byte 28 — a MEMORY cue's colour, 1-based, 0 = none."""
return entry[28] if len(entry) > 28 and entry[:4] == b"PCP2" else 0
def entry_with_color_id(entry: bytes, value: int) -> bytes:
"""A `PCP2` entry with ONLY byte 28 changed — what rekordbox does to recolour
a memory cue (measured: that one byte, in any entry length, compact too)."""
return entry[:28] + bytes([value & 0xFF]) + entry[29:]
def entry_with_comment(entry: bytes, name: str | None) -> bytes:
"""A `PCP2` entry renamed, every other byte kept.
Measured on a memory loop (rekordbox 7, 2026-10-16): the comment goes in at
byte 44 as UTF-16BE plus a NUL, `len_comment` (byte 40) counts it, and the
entry GROWS by exactly that much — 88 -> 100 for "Loopy" — the colour tail
and padding following it unchanged. A compact 44-byte entry has no tail, so
it first takes a full entry's (4 colour bytes + 40 zeros); that case is
unmeasured."""
if len(entry) < 44:
raise AnlzError("A PCP2 entry shorter than 44 bytes has no comment field")
old_len = struct.unpack_from(">I", entry, 40)[0]
tail = entry[44 + old_len:] if len(entry) > 44 else bytes(44)
comment = (name.encode("utf-16-be") + b"\0\0") if name else b""
head = entry[:8] + struct.pack(">I", 44 + len(comment) + len(tail)) + entry[12:40]
return head + struct.pack(">I", len(comment)) + comment + tail
def entry_without_loop_beats(entry: bytes) -> bytes: def entry_without_loop_beats(entry: bytes) -> bytes:
"""A `PCP2` entry with its loop length in beats cleared to 0/0 — what """A `PCP2` entry with its loop length in beats cleared to 0/0 — what
rekordbox does to every loop when the grid changes (measured: 32/1 -> 0/0), rekordbox does to every loop when the grid changes (measured: 32/1 -> 0/0),
@@ -245,7 +277,8 @@ def _pco2(data: bytes) -> list[CueEntry]:
hot_cue, = struct.unpack_from(">I", data, off + 12) hot_cue, = struct.unpack_from(">I", data, off + 12)
kind = data[off + 16] kind = data[off + 16]
time, loop = struct.unpack_from(">II", data, off + 20) time, loop = struct.unpack_from(">II", data, off + 20)
e = CueEntry(hot_cue=hot_cue, type=kind, time=time, loop_time=loop, len_entry=n) e = CueEntry(hot_cue=hot_cue, type=kind, time=time, loop_time=loop, len_entry=n,
color_id=data[off + 28] if n > 28 else 0)
if n >= 44: if n >= 44:
e.loop_numerator, e.loop_denominator, len_comment = struct.unpack_from(">HHI", data, off + 36) e.loop_numerator, e.loop_denominator, len_comment = struct.unpack_from(">HHI", data, off + 36)
colour_at = off + 44 + len_comment colour_at = off + 44 + len_comment
@@ -315,7 +315,7 @@ def flat_preview_tags() -> list[bytes]:
def pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None, def pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
rgb: tuple[int, int, int] | None, beats: int | None, code: int = 0, rgb: tuple[int, int, int] | None, beats: int | None, code: int = 0,
comment: str | None = None) -> bytes: comment: str | None = None, color_id: int = 0) -> bytes:
"""One `PCP2` entry, byte-for-byte as rekordbox 7 writes it. """One `PCP2` entry, byte-for-byte as rekordbox 7 writes it.
Two constants in here are rekordbox's, not the documented struct's: the Two constants in here are rekordbox's, not the documented struct's: the
@@ -328,6 +328,9 @@ def pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
Konduktor's reader and pyrekordbox's agree with. No reference cue carries Konduktor's reader and pyrekordbox's agree with. No reference cue carries
one, so that detail is documented rather than measured. The entry stays the one, so that detail is documented rather than measured. The entry stays the
exported 88 bytes unless the name needs more. exported 88 bytes unless the name needs more.
`color_id` is byte 28: a MEMORY cue's colour, 1-based (`memory_palette`),
0 = none. A hot cue's colour is the code + RGB tail instead.
""" """
comment_bytes = (comment.encode("utf-16-be") + b"\0\0") if comment else b"" comment_bytes = (comment.encode("utf-16-be") + b"\0\0") if comment else b""
red, green, blue = rgb or (0, 0, 0) red, green, blue = rgb or (0, 0, 0)
@@ -336,7 +339,7 @@ def pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
">4sIIIBxHIIBB6xHHI", ">4sIIIBxHIIBB6xHHI",
b"PCP2", 16, length, hot_cue, kind, 1000, b"PCP2", 16, length, hot_cue, kind, 1000,
int(time_ms), NO_LOOP if loop_ms is None else int(loop_ms), int(time_ms), NO_LOOP if loop_ms is None else int(loop_ms),
0, 1, beats or 0, 1 if beats else 0, len(comment_bytes), color_id & 0xFF, 1, beats or 0, 1 if beats else 0, len(comment_bytes),
# The colour is the palette CODE, then RGB: rekordbox draws from the code # The colour is the palette CODE, then RGB: rekordbox draws from the code
# (`palette`); a code of 0 draws its default colour whatever the RGB says. # (`palette`); a code of 0 draws its default colour whatever the RGB says.
) + comment_bytes + struct.pack(">4B", code & 0xFF, red, green, blue) + bytes( ) + comment_bytes + struct.pack(">4B", code & 0xFF, red, green, blue) + bytes(
@@ -344,6 +347,41 @@ def pcp2_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None,
) )
#: rekordbox's COMPACT `PCP2` entry: the first 44 bytes of a full one — no
#: comment and no colour tail. What rekordbox 7 appends when it ADDS a memory cue
#: on a stick (measured 2026-10-16, `fixtures/onelibrary-memory-edits`).
PCP2_COMPACT_LEN = 44
def pcp2_compact_entry(*, kind: int, time_ms: int, loop_ms: int | None,
beats: int | None, color_id: int = 0, hot_cue: int = 0) -> bytes:
"""A compact 44-byte `PCP2` entry, byte for byte as rekordbox 7 writes one
for a memory cue it adds: the same fields as `pcp2_entry` up to
`len_comment` (0), including the `1000` and the `1` after byte 28."""
return struct.pack(
">4sIIIBxHIIBB6xHHI",
b"PCP2", 16, PCP2_COMPACT_LEN, hot_cue, kind, 1000,
int(time_ms), NO_LOOP if loop_ms is None else int(loop_ms),
color_id & 0xFF, 1, beats or 0, 1 if beats else 0, 0,
)
def relinked_memory_pcpts(entries: list[bytes]) -> list[bytes]:
"""A `PCOB` MEMORY list's entries with their link fields rewritten, as
rekordbox 7 leaves them after ANY add or delete (measured 2026-10-16,
`fixtures/onelibrary-memory-edits`): status (bytes 16-19) 0, and bytes 24-27 the
previous / next entry's INDEX IN THE LIST, 0xFFFF at either end — so every
entry changes when one is added or removed. rekordbox's exports agree on any
list of two or more; a lone exported entry is status 4, 0xFFFF/0xFFFF."""
n = len(entries)
out = []
for i, e in enumerate(entries):
prev = i - 1 if i > 0 else 0xFFFF
nxt = i + 1 if i < n - 1 else 0xFFFF
out.append(e[:16] + struct.pack(">I", 0) + e[20:24] + struct.pack(">HH", prev, nxt) + e[28:])
return out
def pcpt_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None) -> bytes: def pcpt_entry(*, hot_cue: int, kind: int, time_ms: int, loop_ms: int | None) -> bytes:
"""One `PCPT` entry, byte-for-byte as rekordbox 7 writes it. """One `PCPT` entry, byte-for-byte as rekordbox 7 writes it.
@@ -378,18 +416,25 @@ def pco2_tag(cue_type: int, entries: list[bytes]) -> bytes:
def _pcob(cue_type: int, chosen: list[dict]) -> bytes: def _pcob(cue_type: int, chosen: list[dict]) -> bytes:
return pcob_tag(cue_type, [ entries = [
pcpt_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"], pcpt_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
loop_ms=c["loop_ms"]) loop_ms=c["loop_ms"])
for c in chosen for c in chosen
]) ]
if cue_type == 0 and len(entries) > 1:
# A memory list of two or more is linked, status 0 — what rekordbox's
# own exports (two test sticks) and edits hold. A lone entry keeps the
# status 4 / 0xFFFF form the reference export pins.
entries = relinked_memory_pcpts(entries)
return pcob_tag(cue_type, entries)
def _pco2(cue_type: int, chosen: list[dict]) -> bytes: def _pco2(cue_type: int, chosen: list[dict]) -> bytes:
return pco2_tag(cue_type, [ return pco2_tag(cue_type, [
pcp2_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"], pcp2_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
loop_ms=c["loop_ms"], rgb=c.get("rgb"), beats=c.get("beats"), loop_ms=c["loop_ms"], rgb=c.get("rgb"), beats=c.get("beats"),
code=c.get("code", 0), comment=c.get("comment")) code=c.get("code", 0), comment=c.get("comment"),
color_id=c.get("color_id", 0))
for c in chosen for c in chosen
]) ])
@@ -30,8 +30,8 @@ from ...core.capabilities import (
SaveCapabilities, SaveCapabilities,
TrackCapabilities, TrackCapabilities,
) )
from . import palette from . import memory_palette, palette, track_palette
from .cue_types import WRITABLE_CUE_TYPES from .cue_types import MAX_MEMORY_CUES, WRITABLE_CUE_TYPES
# Rekordbox's addressable hot cue bank. The pads are labelled A-H; the stored # Rekordbox's addressable hot cue bank. The pads are labelled A-H; the stored
# slot number is NOT a plain letter index (see cue_types), so the adapter keeps # slot number is NOT a plain letter index (see cue_types), so the adapter keeps
@@ -55,18 +55,19 @@ def capabilities_for(
writable=not cloud_synced, writable=not cloud_synced,
readonly_cause="cloud_synced" if cloud_synced else None, readonly_cause="cloud_synced" if cloud_synced else None,
cues=CueCapabilities( cues=CueCapabilities(
# Hot cues are writable: djmdCue rows plus the contentCue JSON # Hot AND memory cues are writable: djmdCue rows plus the
# mirror, kept in step. MEMORY cues stay preserved-but-uneditable — # contentCue JSON mirror, kept in step (memory cues: measured
# Rekordbox is the only platform that has them, and the two-platform # 2026-10-16, kit M1).
# promotion rule says a one-platform concept does not become an
# editing feature.
editable=True, editable=True,
hotcue_slots=HOTCUE_SLOTS, hotcue_slots=HOTCUE_SLOTS,
slot_labels="letter", slot_labels="letter",
# Rekordbox is the only platform with memory cues, so they are
# projected and PRESERVED but not editable (two-platform rule).
memory_cues=True, memory_cues=True,
max_memory_cues=None, # unlimited # rekordbox stops storing at 10, silently; the store refuses the 11th.
max_memory_cues=MAX_MEMORY_CUES,
# A memory cue's colour is its own 8-colour palette (`Color`, not
# `ColorTableIndex`) — see `memory_palette`.
memory_color="palette",
memory_palette=list(memory_palette.SWATCHES),
# Both cue types write; Rekordbox has no fade/load types. # Both cue types write; Rekordbox has no fade/load types.
types=WRITABLE_CUE_TYPES, types=WRITABLE_CUE_TYPES,
# A hot cue's colour is one of rekordbox's 16 swatches (all # A hot cue's colour is one of rekordbox's 16 swatches (all
@@ -92,6 +93,8 @@ def capabilities_for(
removable=True, removable=True,
addable=True, addable=True,
key_writable=True, key_writable=True,
# `djmdContent.ColorID`, rekordbox's eight (see `track_palette`).
colors=list(track_palette.SWATCHES),
artwork=False, artwork=False,
artwork_note=None, artwork_note=None,
), ),
@@ -36,6 +36,10 @@ has an out-point, so a loop can sit in a hot cue slot or be a memory cue.
from __future__ import annotations from __future__ import annotations
MEMORY_KIND = 0 MEMORY_KIND = 0
#: rekordbox stores at most this many memory cues per track — on the computer
#: AND on a stick — and enforces it SILENTLY (measured 2026-10-16: MEMORY simply
#: stops storing), so Konduktor refuses the next one itself, with a reason.
MAX_MEMORY_CUES = 10
# Rekordbox has no fade-in/fade-out/load cues; those are Traktor-only. # Rekordbox has no fade-in/fade-out/load cues; those are Traktor-only.
CUE_TYPES = ["cue", "loop"] CUE_TYPES = ["cue", "loop"]
@@ -41,7 +41,7 @@ from datetime import date
from pathlib import Path from pathlib import Path
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
from . import artwork, pdb from . import artwork, pdb, track_palette
from .projection import render_key from .projection import render_key
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@@ -138,6 +138,7 @@ class RekordboxDeviceExporter:
"id": n, "year": year, "sample_depth": bit_depth or 0, "id": n, "year": year, "sample_depth": bit_depth or 0,
"duration": min(int(track.length or 0), 0xFFFF), "duration": min(int(track.length or 0), 0xFFFF),
"u5": ANALYSED, "rating": max(0, min(5, int(track.rating or 0))), "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, "u6": _file_type(item.destination), "u7": 3,
}, },
{ {
+17 -9
View File
@@ -58,7 +58,7 @@ from sqlalchemy import text
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
from ...core.cue_colors import effective_color from ...core.cue_colors import effective_color
from . import new_content, palette from . import memory_palette, new_content, palette, track_palette
from . import timebase from . import timebase
from .beatgrid import beats_from_markers from .beatgrid import beats_from_markers
from .capabilities import capabilities_for from .capabilities import capabilities_for
@@ -199,24 +199,31 @@ class RekordboxExporter:
from .adapter import RekordboxAdapter from .adapter import RekordboxAdapter
adapter = RekordboxAdapter(library) adapter = RekordboxAdapter(library)
# The store, not the adapter's commands: the adapter refuses memory cues # The store, not the adapter's commands: the adapter's set_cue takes no
# (editing them in a user's library is off-limits) and takes no colour. # colour and its memory-cue command takes only a swatch. A NEW library
# Building a NEW library is neither an edit nor lossy by choice, so the # maps any source colour to the nearest one instead — through the same
# exporter writes both — through the same `_write_cue` every edit uses. # `_write_cue` every edit uses.
store = adapter._store store = adapter._store
try: try:
for item in payload.tracks: for item in payload.tracks:
track_id = ids.get(item.source_id) track_id = ids.get(item.source_id)
if track_id is None or not item.cues: if track_id is None or not item.cues:
continue continue
for cue in item.cues.cues: memory = 0
for cue in sorted(item.cues.cues, key=lambda c: c.start):
if cue.role == "memory" or cue.slot is None: if cue.role == "memory" or cue.slot is None:
# rekordbox's own "unset" for a memory cue with no colour. # rekordbox keeps 10 (earliest first; the rest are
code, _rgb = palette.code_for(cue.color) # dropped, per the lossiness rule). Colour: what
# Konduktor SHOWS — stored, else the type's — as the
# nearest of the memory palette's 8, as for a hot cue.
if memory >= store.MAX_MEMORY_CUES:
continue
store.add_memory_cue( store.add_memory_cue(
track_id, start_sec=cue.start, cue_type=cue.type, track_id, start_sec=cue.start, cue_type=cue.type,
length_sec=cue.length, name=cue.name, color_code=code or None, length_sec=cue.length, name=cue.name,
color_code=memory_palette.nearest_code(effective_color(cue)),
) )
memory += 1
continue continue
# What Konduktor SHOWS — stored colour, else the type's (blue # What Konduktor SHOWS — stored colour, else the type's (blue
# cue, green loop) — as a palette code, which is what # cue, green loop) — as a palette code, which is what
@@ -306,6 +313,7 @@ class RekordboxExporter:
# export would put "10m" where Rekordbox shows "Cm". # export would put "10m" where Rekordbox shows "Cm".
content.KeyID = self._lookup(db, "key", render_key(track.key_wheel, track.key_mode)) content.KeyID = self._lookup(db, "key", render_key(track.key_wheel, track.key_mode))
content.ContentLink = CONTENT_LINK content.ContentLink = CONTENT_LINK
content.ColorID = str(track_palette.id_for(track.color))
db.flush() db.flush()
return content return content
@@ -0,0 +1,95 @@
"""rekordbox's MEMORY-cue colours — a palette of its own, not the hot cues'.
rekordbox 7 offers a memory cue eight colours plus "No Color" (Pink, Red,
Orange, Yellow, Green, Aqua, Blue, Purple — the same eight names as its track
colours), against sixteen swatches for a hot cue. MEASURED 2026-10-16 (kits M1 /
M2 in `.claude/discussions/discuss-memory-cues-2026-10-16.md`), by colouring
memory cues one per colour, in that order, in rekordbox itself:
* `master.db`: the code is `djmdCue.Color`, **0-based** in menu order (Pink 0
… Purple 7) and `ColorTableIndex` stays NULL — the opposite of a hot cue,
which keeps its code in `ColorTableIndex` with `Color = -1`. "No colour" is
`-1` on a cue never coloured and **255** on one set back to "No Color".
* the ANLZ `.EXT`: `PCP2` byte 28, **1-based** (Blue = 7), 0 = none. The
hot-cue colour tail after the comment stays zero on a memory cue.
The RGB values are DISPLAY colours only — nothing stores them. They were
sampled from the dots in rekordbox 7's own colour menu (a screenshot), so they
are what rekordbox shows, not what it writes.
"""
from __future__ import annotations
import colorsys
from .palette import _parse
#: code (0-based, master.db) -> display RGB, in rekordbox's menu order.
COLOURS: list[tuple[str, tuple[int, int, int]]] = [
("Pink", (0xE5, 0x77, 0xEF)),
("Red", (0xE1, 0x31, 0x21)),
("Orange", (0xEA, 0xA3, 0x49)),
("Yellow", (0xF2, 0xE2, 0x57)),
("Green", (0x65, 0xDB, 0x41)),
("Aqua", (0x55, 0xBB, 0xF1)),
("Blue", (0x1F, 0x4E, 0xED)),
("Purple", (0x8A, 0x1D, 0xED)),
]
#: `master.db`'s `Color` for a memory cue set back to "No Color" (measured);
#: a cue never coloured keeps -1. Both read as uncoloured.
CLEARED = 255
#: Below this saturation a colour is white/grey, which the palette cannot show.
_GREY = 0.2
def _hex(rgb: tuple[int, int, int]) -> str:
return f"#{rgb[0]:02X}{rgb[1]:02X}{rgb[2]:02X}"
#: The swatches a user can pick — what `capabilities.cues.memory_palette` offers.
SWATCHES: list[str] = [_hex(rgb) for _name, rgb in COLOURS]
def hex_for(code: int | None) -> str | None:
"""`#RRGGBB` for a stored 0-based code; None for -1, 255 or anything unknown."""
if code is None or not 0 <= code < len(COLOURS):
return None
return _hex(COLOURS[code][1])
def code_for(color: str | None) -> int | None:
"""The 0-based code of an EXACT swatch (a user's pick), else None."""
rgb = _parse(color) if color else None
return next((i for i, (_n, value) in enumerate(COLOURS) if value == rgb), None)
def nearest_code(color: str | None) -> int | None:
"""The swatch nearest in hue to any `#RRGGBB` — for a colour arriving from
another platform (an import, an export). None for no colour or a grey."""
exact = code_for(color)
if exact is not None:
return exact
rgb = _parse(color) if color else None
if rgb is None:
return None
h, _l, s = colorsys.rgb_to_hls(*(v / 255 for v in rgb))
if s < _GREY or max(rgb) - min(rgb) < 40:
return None
def hue_gap(i: int) -> float:
ph = colorsys.rgb_to_hls(*(v / 255 for v in COLOURS[i][1]))[0]
d = abs(ph - h)
return min(d, 1 - d)
return min(range(len(COLOURS)), key=hue_gap)
def anlz_byte(code: int | None) -> int:
"""`PCP2` byte 28 for a 0-based code: code + 1, and 0 for none."""
return 0 if code is None else code + 1
def from_anlz_byte(value: int) -> int | None:
"""The 0-based code from `PCP2` byte 28 (0 = none)."""
return value - 1 if 1 <= value <= len(COLOURS) else None
@@ -7,8 +7,8 @@ from __future__ import annotations
from ...core import musical_key from ...core import musical_key
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
from . import beatgrid, palette, timebase from . import beatgrid, memory_palette, palette, timebase, track_palette
from .cue_types import cue_type, role_and_slot from .cue_types import cue_type, kind_for, role_and_slot
# Rekordbox names keys musically ("Abm", "F", "Ebm") — but its key table also # Rekordbox names keys musically ("Abm", "F", "Ebm") — but its key table also
# holds whatever text a track's key TAG carried when it was imported, so a real # holds whatever text a track's key TAG carried when it was imported, so a real
@@ -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 # file's mix, but Konduktor's deck plays its stems, and the Type column
# must not disagree with the deck. # must not disagree with the deck.
media_kind="stem" if stem else "audio", 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)),
) )
@@ -140,10 +142,10 @@ def to_track_cues(cue_rows: list, grid: tuple | None, time_offset: float = 0.0)
`editable` says whether the adapter will accept a command on THIS cue, which `editable` says whether the adapter will accept a command on THIS cue, which
is the only thing the UI gates on. Every hot cue is editable, loops included. is the only thing the UI gates on. Every hot cue is editable, loops included.
**Memory cues are not**: Rekordbox is the only platform that has them, so So is every memory cue (`Kind` 0), addressed by its row id (`CuePoint.id`)
under the two-platform promotion rule they are shown and never written. A cue since it has no pad. A cue sitting on the reserved `Kind` 4 occupies no pad
sitting on the reserved `Kind` occupies no pad and is projected the same way, either and is SHOWN as a memory cue, because that is how Rekordbox itself
because that is how Rekordbox itself displays one. displays one — but it is not one, so it is not editable.
""" """
markers: list[GridMarker] = [] markers: list[GridMarker] = []
if grid is not None: if grid is not None:
@@ -158,7 +160,9 @@ def to_track_cues(cue_rows: list, grid: tuple | None, time_offset: float = 0.0)
length = 0.0 length = 0.0
if out_msec is not None and out_msec > 0: if out_msec is not None and out_msec > 0:
length = max(0.0, (out_msec - in_msec) / 1000.0) length = max(0.0, (out_msec - in_msec) / 1000.0)
editable = role == "hotcue" memory = role == "memory"
# Kind 4 (reserved) displays as a memory cue but is not one.
editable = not memory or getattr(c, "Kind", None) == kind_for("memory", None)
cues.append( cues.append(
CuePoint( CuePoint(
name=(getattr(c, "Comment", None) or None), name=(getattr(c, "Comment", None) or None),
@@ -169,15 +173,27 @@ def to_track_cues(cue_rows: list, grid: tuple | None, time_offset: float = 0.0)
start=timebase.from_pioneer(in_msec / 1000.0, time_offset), start=timebase.from_pioneer(in_msec / 1000.0, time_offset),
length=length, length=length,
slot=slot, slot=slot,
color=_cue_color(c), color=_memory_cue_color(c) if memory else _cue_color(c),
editable=editable, editable=editable,
readonly_reason=None if editable else "platform_managed", readonly_reason=None if editable else "platform_managed",
grid_marker=None, grid_marker=None,
# A memory cue is addressed by its row id (`CuePoint.id`).
id=str(c.ID) if memory and editable and getattr(c, "ID", None) is not None else None,
) )
) )
return TrackCues(grid_markers=markers, grid_locked=False, cues=cues) return TrackCues(grid_markers=markers, grid_locked=False, cues=cues)
def _memory_cue_color(row) -> str | None:
"""A memory cue keeps its 0-based `memory_palette` code in `Color` (-1 and
255 = none). A row Konduktor wrote before that was measured carries a
hot-cue code in `ColorTableIndex` instead; read it rather than lose it."""
colour = memory_palette.hex_for(getattr(row, "Color", None))
if colour is None and (getattr(row, "OutMsec", -1) or -1) <= 0:
colour = palette.hex_for(getattr(row, "ColorTableIndex", None))
return colour
def _cue_color(row) -> str | None: def _cue_color(row) -> str | None:
"""Rekordbox stores a PALETTE CODE (`ColorTableIndex`), not an RGB value; """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.""" `Color` is -1 on a coloured cue. A loop's uncoloured convention is code 0."""
+106 -10
View File
@@ -47,8 +47,8 @@ from ...core.adapter import (
from ...core.edit_journal import EditJournal from ...core.edit_journal import EditJournal
from ...core.grid_edit import ReplaceGridCommands from ...core.grid_edit import ReplaceGridCommands
from ...core.pathmap import PathMapping, stored_form from ...core.pathmap import PathMapping, stored_form
from . import timebase from . import memory_palette, timebase, track_palette
from .cue_types import beat_loop_size, kind_for, role_and_slot from .cue_types import MAX_MEMORY_CUES, beat_loop_size, kind_for, role_and_slot
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@@ -556,6 +556,24 @@ class RekordboxStore(ReplaceGridCommands):
self._db.flush() self._db.flush()
self._db.session.expire(row) 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 ------------------------------------------------ # ---- writes: playlists ------------------------------------------------
def _playlist(self, node_id: str): def _playlist(self, node_id: str):
t = self._tables t = self._tables
@@ -761,6 +779,7 @@ class RekordboxStore(ReplaceGridCommands):
# Rekordbox's ("10m" is "Cm" here), and a row it already has is reused. # 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.KeyID = self._key_id(track.key_wheel, track.key_mode)
content.ContentLink = new_content.CONTENT_LINK content.ContentLink = new_content.CONTENT_LINK
content.ColorID = str(track_palette.id_for(track.color))
if stored != audio: if stored != audio:
# pyrekordbox reads the file where it IS; the row names it as the # pyrekordbox reads the file where it IS; the row names it as the
# library stores every other path (the server's mapping, inverted). # library stores every other path (the server's mapping, inverted).
@@ -1147,6 +1166,25 @@ class RekordboxStore(ReplaceGridCommands):
) )
self._journal.record("cue", "add" if existing is None else "modify", track_id, f"slot:{slot}") self._journal.record("cue", "add" if existing is None else "modify", track_id, f"slot:{slot}")
MAX_MEMORY_CUES = MAX_MEMORY_CUES # see `cue_types`
def memory_cue_rows(self, track_id: str) -> list:
"""A track's memory cues (`Kind` 0), in row order."""
t = self._tables
return list(
self._db.session.query(t.DjmdCue)
.filter(t.DjmdCue.ContentID == str(track_id))
.filter(t.DjmdCue.Kind == kind_for("memory", None))
.filter(t.DjmdCue.rb_local_deleted == 0)
)
def _memory_cue_row(self, track_id: str, cue_id: str):
"""The memory cue whose `djmdCue.ID` is `cue_id` (`CuePoint.id`)."""
row = next((c for c in self.memory_cue_rows(track_id) if str(c.ID) == str(cue_id)), None)
if row is None:
raise NotFound(f"No memory cue {cue_id!r} on this track")
return row
def add_memory_cue( def add_memory_cue(
self, self,
track_id: str, track_id: str,
@@ -1156,23 +1194,59 @@ class RekordboxStore(ReplaceGridCommands):
length_sec: float = 0.0, length_sec: float = 0.0,
name: str | None = None, name: str | None = None,
color_code: int | None = None, color_code: int | None = None,
enforce_cap: bool = True,
) -> None: ) -> None:
"""Add a MEMORY cue (`Kind` 0) — for the exporter building a new library. """Add a MEMORY cue (`Kind` 0); a memory loop when `length_sec` > 0.
The adapter never calls this: editing memory cues in a user's library `color_code` is a 0-based `memory_palette` code — NOT a hot-cue palette
stays refused under the two-platform promotion rule. A new export is not code: a memory cue keeps its colour in `Color`, not `ColorTableIndex`.
an edit, and dropping the source's memory cues would lose prep. `enforce_cap` refuses the 11th (an edit); the exporter, building a
library from a source that may hold more, trims before calling.
""" """
if enforce_cap and len(self.memory_cue_rows(track_id)) >= self.MAX_MEMORY_CUES:
raise InvalidCommand(
f"rekordbox keeps at most {self.MAX_MEMORY_CUES} memory cues per track"
)
self._write_cue( self._write_cue(
track_id, None, kind=kind_for("memory", None), start_sec=start_sec, track_id, None, kind=kind_for("memory", None), start_sec=start_sec,
cue_type=cue_type, length_sec=length_sec, name=name, color_code=color_code, cue_type=cue_type, length_sec=length_sec, name=name, color_code=color_code,
) )
self._journal.record("cue", "add", track_id, "memory") self._journal.record("cue", "add", track_id, "memory")
def rename_memory_cue(self, track_id: str, cue_id: str, name: str | None) -> None:
"""A memory cue's name is rekordbox's `Comment`; only that column changes."""
cue = self._memory_cue_row(track_id, cue_id)
is_loop = (cue.OutMsec or 0) > 0
# An unnamed memory LOOP is '' (measured); an unnamed point cue NULL.
cue.Comment = name or ("" if is_loop else None)
self._db.flush()
self._sync_content_cue(track_id)
self._journal.record("cue", "modify", track_id, "memory")
def set_memory_cue_color(self, track_id: str, cue_id: str, color_code: int | None) -> None:
"""Recolour a memory cue; None = rekordbox's "No Color" (255, measured)."""
cue = self._memory_cue_row(track_id, cue_id)
self._apply_memory_color(cue, color_code, (cue.OutMsec or 0) > 0, cleared=True)
self._db.flush()
self._sync_content_cue(track_id)
self._journal.record("cue", "modify", track_id, "memory")
def delete_memory_cue(self, track_id: str, cue_id: str) -> None:
"""Delete the row outright, as rekordbox does (never `rb_local_deleted`)."""
cue = self._memory_cue_row(track_id, cue_id)
self._db.delete(cue)
self._db.flush()
self._sync_content_cue(track_id)
self._journal.record("cue", "delete", track_id, "memory")
def _write_cue(self, track_id: str, cue, *, kind: int, start_sec: float, cue_type: str, def _write_cue(self, track_id: str, cue, *, kind: int, start_sec: float, cue_type: str,
length_sec: float, name: str | None, color_code: int | None) -> None: length_sec: float, name: str | None, color_code: int | None) -> None:
"""Fill one `djmdCue` row (a new one when `cue` is None) and resync the """Fill one `djmdCue` row (a new one when `cue` is None) and resync the
`contentCue` mirror — the single definition of a cue row's fields.""" `contentCue` mirror — the single definition of a cue row's fields.
`color_code` is a hot-cue palette code on a hot cue and a 0-based
`memory_palette` code on a memory cue (`Kind` 0): the two keep their
colour in different columns."""
if start_sec < 0: if start_sec < 0:
raise InvalidCommand("A cue cannot be before the start of the track") raise InvalidCommand("A cue cannot be before the start of the track")
row = self.content(track_id) row = self.content(track_id)
@@ -1217,8 +1291,13 @@ class RekordboxStore(ReplaceGridCommands):
cue.BeatLoopSize = None cue.BeatLoopSize = None
cue.ActiveLoop = None cue.ActiveLoop = None
cue.CueMicrosec = None cue.CueMicrosec = None
self._apply_color(cue, color_code, is_loop) if kind == kind_for("memory", None):
cue.Comment = name or None self._apply_memory_color(cue, color_code, is_loop)
# Measured: an unnamed memory LOOP has Comment '', a point cue NULL.
cue.Comment = name or ("" if is_loop else None)
else:
self._apply_color(cue, color_code, is_loop)
cue.Comment = name or None
self._db.flush() self._db.flush()
self._sync_content_cue(track_id) self._sync_content_cue(track_id)
@@ -1240,6 +1319,21 @@ class RekordboxStore(ReplaceGridCommands):
cue.Color = -1 cue.Color = -1
cue.ColorTableIndex = None cue.ColorTableIndex = None
@staticmethod
def _apply_memory_color(cue, code: int | None, is_loop: bool, *, cleared: bool = False) -> None:
"""A MEMORY cue's colour columns (measured 2026-10-16, kit M1): the
0-based `memory_palette` code in `Color`, `ColorTableIndex` untouched by
colour — NULL on a point cue, 0 on a loop (rekordbox's loop marker).
Uncoloured is -1 on a new point cue, 255 on a loop and on any cue set
back to "No Color" (`cleared`)."""
cue.ColorTableIndex = 0 if is_loop else None
if code is not None:
cue.Color = int(code)
elif cleared or is_loop:
cue.Color = memory_palette.CLEARED
else:
cue.Color = -1
def set_cue_color(self, track_id: str, slot: int, color_code: int | None) -> 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 """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.""" colour columns, so the position does not take a time-base round trip."""
@@ -1308,11 +1402,13 @@ class RekordboxStore(ReplaceGridCommands):
""" """
t = self._tables t = self._tables
row = self.content(track_id) row = self.content(track_id)
# In ROW order, as rekordbox writes it (measured: a memory cue added at
# 1:55 is listed after older ones at 2:04 and 3:26), not by position.
cues = ( cues = (
self._db.session.query(t.DjmdCue) self._db.session.query(t.DjmdCue)
.filter(t.DjmdCue.ContentID == str(track_id)) .filter(t.DjmdCue.ContentID == str(track_id))
.filter(t.DjmdCue.rb_local_deleted == 0) .filter(t.DjmdCue.rb_local_deleted == 0)
.order_by(t.DjmdCue.InMsec) .order_by(text("djmdCue.rowid"))
.all() .all()
) )
fields = ( fields = (
@@ -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): def set_key(self, track_id, wheel, mode):
return self._call("set_key", track_id=track_id, wheel=wheel, mode=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): 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, 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) cue_type=cue_type, length_sec=length_sec, role=role, name=name)
@@ -234,6 +237,22 @@ class RemoteAdapter:
def place_cues(self, track_id, cues, *, overwrite=False): def place_cues(self, track_id, cues, *, overwrite=False):
return self._call("place_cues", track_id=track_id, cues=list(cues), overwrite=overwrite) return self._call("place_cues", track_id=track_id, cues=list(cues), overwrite=overwrite)
def add_memory_cue(self, track_id, *, start_sec, cue_type, length_sec=0.0, name=None, color=None):
return self._call("add_memory_cue", track_id=track_id, start_sec=start_sec,
cue_type=cue_type, length_sec=length_sec, name=name, color=color)
def rename_memory_cue(self, track_id, cue_id, name):
return self._call("rename_memory_cue", track_id=track_id, cue_id=cue_id, name=name)
def set_memory_cue_type(self, track_id, cue_id, cue_type):
return self._call("set_memory_cue_type", track_id=track_id, cue_id=cue_id, cue_type=cue_type)
def set_memory_cue_color(self, track_id, cue_id, color):
return self._call("set_memory_cue_color", track_id=track_id, cue_id=cue_id, color=color)
def delete_memory_cue(self, track_id, cue_id):
return self._call("delete_memory_cue", track_id=track_id, cue_id=cue_id)
def add_grid_marker(self, track_id, start_sec, bpm=None): def add_grid_marker(self, track_id, start_sec, bpm=None):
return self._call("add_grid_marker", track_id=track_id, start_sec=start_sec, bpm=bpm) return self._call("add_grid_marker", track_id=track_id, start_sec=start_sec, bpm=bpm)
+80 -20
View File
@@ -156,6 +156,12 @@ class TraktorAdapter:
self._refresh(track_id) self._refresh(track_id)
return self._index.get(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: def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
with _translate(): with _translate():
self._store.set_track_art(track_id, data, mime) self._store.set_track_art(track_id, data, mime)
@@ -197,10 +203,11 @@ class TraktorAdapter:
Lossiness follows the settled rule — degrade to the nearest equivalent, Lossiness follows the settled rule — degrade to the nearest equivalent,
drop only where none exists: drop only where none exists:
* **Memory cues become hot cues in spare slots.** Traktor has no * **Memory cues stay memory cues** — Traktor's cues on no pad
memory cues, and every Traktor cue occupies a slot. Filling the (HOTCUE="-1"), decided 2026-10-16 once Traktor was measured keeping
leftovers preserves the positions a DJ actually marked; when the them. They used to be promoted to spare pads.
bank is full the rest are dropped, because there is nowhere left. * **A hot cue whose pad is taken** moves to a spare pad, else becomes a
memory cue — never dropped.
* **Cue colour is dropped.** Traktor derives a cue's colour from its * **Cue colour is dropped.** Traktor derives a cue's colour from its
type, so a free RGB value has nowhere to go. type, so a free RGB value has nowhere to go.
@@ -250,29 +257,43 @@ class TraktorAdapter:
self._place_imported_cue(track_id, cue.slot, cue) self._place_imported_cue(track_id, cue.slot, cue)
taken.add(cue.slot) taken.add(cue.slot)
# Everything without a pad of its own competes for what is left: memory # A hot cue whose pad was taken (or is past the bank) moves to a spare
# cues, which Traktor has no equivalent for, and any hot cue whose pad # pad, earliest first, because muscle memory is most of what a hot cue
# was already occupied. Earliest first, so that when the bank runs out # layout is; once the bank is full it becomes a memory cue rather than
# it is the late cues that are lost rather than an arbitrary set — and # being lost. Memory cues cross as memory cues.
# a displaced hot cue is moved rather than dropped, because losing one
# silently is much worse than having it turn up on the wrong pad.
leftovers = displaced + [c for c in (cues.cues or []) if c.role != "hotcue"]
spare = (s for s in range(slots) if s not in taken) spare = (s for s in range(slots) if s not in taken)
for cue in sorted(leftovers, key=lambda c: c.start): for cue in sorted(displaced, key=lambda c: c.start):
slot = next(spare, None) slot = next(spare, None)
if slot is None: if slot is None:
break # bank full: the rest are dropped, per the lossiness rule self._place_imported_memory_cue(track_id, cue)
self._place_imported_cue(track_id, slot, cue) else:
self._place_imported_cue(track_id, slot, cue)
for cue in sorted((c for c in (cues.cues or []) if c.role != "hotcue" or c.slot is None),
key=lambda c: c.start):
self._place_imported_memory_cue(track_id, cue)
@staticmethod
def _imported_type(cue) -> str:
"""A loop stays a loop; Traktor's own point types (fade, load) survive."""
if getattr(cue, "length", 0):
return "loop"
return cue.type if cue.type in ("cue", "fade_in", "fade_out", "load") else "cue"
def _place_imported_cue(self, track_id: str, slot: int, cue) -> None: def _place_imported_cue(self, track_id: str, slot: int, cue) -> None:
cue_type = "loop" if getattr(cue, "length", 0) else "cue"
if cue_type not in CUE_TYPE_TO_NATIVE:
return
self.set_cue( self.set_cue(
track_id, track_id,
slot=slot, slot=slot,
start_sec=cue.start, start_sec=cue.start,
cue_type=cue_type, cue_type=self._imported_type(cue),
length_sec=getattr(cue, "length", 0.0) or 0.0,
name=getattr(cue, "name", None),
)
def _place_imported_memory_cue(self, track_id: str, cue) -> None:
self.add_memory_cue(
track_id,
start_sec=cue.start,
cue_type=self._imported_type(cue),
length_sec=getattr(cue, "length", 0.0) or 0.0, length_sec=getattr(cue, "length", 0.0) or 0.0,
name=getattr(cue, "name", None), name=getattr(cue, "name", None),
) )
@@ -296,8 +317,8 @@ class TraktorAdapter:
name: str | None = None, name: str | None = None,
) -> TrackCues: ) -> TrackCues:
if role != "hotcue": if role != "hotcue":
# Memory cues are a Rekordbox concept; every Traktor cue holds a slot. # A memory cue has no slot to set; it has its own commands.
raise Unsupported("Traktor cues always occupy a hotcue slot") raise InvalidCommand("Memory cues are added with add_memory_cue, not set_cue")
with _translate(): with _translate():
self._store.set_hotcue( self._store.set_hotcue(
track_id, slot, start_sec, self._native_cue_type(cue_type), length_sec, name track_id, slot, start_sec, self._native_cue_type(cue_type), length_sec, name
@@ -318,6 +339,45 @@ class TraktorAdapter:
self._store.delete_hotcue(track_id, slot) self._store.delete_hotcue(track_id, slot)
return self._refresh(track_id) return self._refresh(track_id)
# ---- memory cues: cues on no pad (HOTCUE="-1") ----------------------------
def add_memory_cue(
self,
track_id: str,
*,
start_sec: float,
cue_type: str,
length_sec: float = 0.0,
name: str | None = None,
color: str | None = None,
) -> TrackCues:
# Traktor colours a cue by its type, so a colour has nowhere to go; an
# import passes none, and the capabilities offer none.
if color is not None:
raise Unsupported("Traktor colours cues by their type")
with _translate():
self._store.add_memory_cue(
track_id, start_sec, self._native_cue_type(cue_type), length_sec, name
)
return self._refresh(track_id)
def rename_memory_cue(self, track_id: str, cue_id: str, name: str | None) -> TrackCues:
with _translate():
self._store.rename_memory_cue(track_id, cue_id, name)
return self._refresh(track_id)
def set_memory_cue_type(self, track_id: str, cue_id: str, cue_type: str) -> TrackCues:
with _translate():
self._store.set_memory_cue_type(track_id, cue_id, self._native_cue_type(cue_type))
return self._refresh(track_id)
def set_memory_cue_color(self, track_id: str, cue_id: str, color: str | None) -> TrackCues:
raise Unsupported("Traktor colours cues by their type")
def delete_memory_cue(self, track_id: str, cue_id: str) -> TrackCues:
with _translate():
self._store.delete_memory_cue(track_id, cue_id)
return self._refresh(track_id)
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues: def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues:
native = [ native = [
SimpleNamespace( SimpleNamespace(
@@ -19,6 +19,7 @@ from ...core.capabilities import (
SaveCapabilities, SaveCapabilities,
TrackCapabilities, TrackCapabilities,
) )
from . import track_palette
_VERSION_RE = re.compile(rb'<NML\s+VERSION="(\d+)"') _VERSION_RE = re.compile(rb'<NML\s+VERSION="(\d+)"')
@@ -46,8 +47,11 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
editable=True, editable=True,
hotcue_slots=8, hotcue_slots=8,
slot_labels="number", slot_labels="number",
# Traktor has no memory cues — every cue occupies a bank slot. # Memory cues are CUE_V2s on no pad (HOTCUE="-1"), any type, no
memory_cues=False, # limit (measured in Traktor 4.5, 2026-10-16). No colour: by type.
memory_cues=True,
max_memory_cues=None,
memory_color="none",
types=CUE_TYPES, types=CUE_TYPES,
# Traktor colours a cue by its TYPE; the only COLOR it stores is a # 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. # grid marker's white companion, so there is nothing to pick.
@@ -65,6 +69,8 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
addable=True, addable=True,
stem_convertible=True, stem_convertible=True,
key_writable=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, # `.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. # 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"], audio_formats=[".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a", ".mp4", ".ogg"],
@@ -9,7 +9,7 @@ import re
from ...core import musical_key from ...core import musical_key
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues 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 from .cue_types import NATIVE_TO_CUE_TYPE
# Traktor displays keys in Open Key ("10m" / "8d") or Camelot ("8A" / "8B"), # Traktor displays keys in Open Key ("10m" / "8d") or Camelot ("8A" / "8B"),
@@ -172,9 +172,48 @@ def to_track(e) -> Track:
grid_marker_count=len(markers), grid_marker_count=len(markers),
grid_locked=bool(e.lock), grid_locked=bool(e.lock),
media_kind="stem" if getattr(e, "stems", None) is not None else "audio", 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),
) )
#: Traktor's NAME for a cue nobody named.
UNNAMED = "n.n."
def is_memory_cue(c) -> bool:
"""A cue on no pad that is not a grid marker — Traktor's memory cue.
Traktor stores it as an ordinary CUE_V2 with HOTCUE="-1", any type, drawn
on the waveform and reached with the cue panel's ‹ › (measured in Traktor
4.5, 2026-10-16). A grid marker is ALSO HOTCUE="-1"; its <GRID> child is
what tells them apart — never its name or position.
"""
return getattr(c, "grid", None) is None and (c.hotcue is None or c.hotcue < 0)
def memory_cue_id(c, n: int) -> str:
"""`CuePoint.id` for a memory cue: its stored START, TYPE and LEN, plus `n`
— how many identical memory cues come before it (Traktor allows several at
one START). Content-derived, so it is the same on every read."""
return f"m:{c.start or 0.0:.6f}:{c.type}:{c.len or 0.0:.6f}:{n}"
def with_memory_ids(entry) -> list:
"""(cue, its memory id or None) for every CUE_V2 of an entry, in order."""
seen: dict[str, int] = {}
out = []
for c in entry.cue_v2 or []:
if not is_memory_cue(c):
out.append((c, None))
continue
base = memory_cue_id(c, 0)
n = seen.get(base, 0)
seen[base] = n + 1
out.append((c, memory_cue_id(c, n)))
return out
def to_track_cues(entry, offset_ms: float = 0.0) -> TrackCues: def to_track_cues(entry, offset_ms: float = 0.0) -> TrackCues:
"""Project an ENTRY's beatgrid + cues. """Project an ENTRY's beatgrid + cues.
@@ -200,20 +239,30 @@ def to_track_cues(entry, offset_ms: float = 0.0) -> TrackCues:
) )
for i, m in enumerate(markers) for i, m in enumerate(markers)
] ]
# A pad MAP put on a memory cue leaves the memory cue in place at the same
# START (measured in Traktor 4.5); Traktor draws ONE marker, so the pad
# stands for both (decided 2026-10-16).
pad_starts = {c.start for c in entry.cue_v2 or []
if getattr(c, "grid", None) is None and c.hotcue is not None and c.hotcue >= 0}
cues = [] cues = []
for c in entry.cue_v2 or []: for c, memory_id in with_memory_ids(entry):
if getattr(c, "grid", None) is not None: if getattr(c, "grid", None) is not None:
continue # a grid marker is projected as a beatgrid marker, not a cue continue # a grid marker is projected as a beatgrid marker, not a cue
if memory_id is not None and c.start in pad_starts:
continue
marker = marker_of.get(id(c)) marker = marker_of.get(id(c))
slot = c.hotcue if c.hotcue is not None and c.hotcue >= 0 else None slot = c.hotcue if c.hotcue is not None and c.hotcue >= 0 else None
cues.append( cues.append(
CuePoint( CuePoint(
name=c.name, # "n.n." is the name Traktor gives every cue the user did not
# name — a placeholder, not a name, so it crosses as none
# (it once landed in rekordbox as a comment reading "n.n.").
name=None if c.name in (None, "", UNNAMED) else c.name,
# An unknown TYPE is projected as a plain cue rather than dropped: # An unknown TYPE is projected as a plain cue rather than dropped:
# preserving a cue we cannot name beats hiding it from the user. # preserving a cue we cannot name beats hiding it from the user.
type=NATIVE_TO_CUE_TYPE.get(c.type, "cue"), type=NATIVE_TO_CUE_TYPE.get(c.type, "cue"),
# Every Traktor cue lives in the hotcue bank. # A cue on no pad (HOTCUE="-1") is a memory cue.
role="hotcue", role="hotcue" if slot is not None else "memory",
start=timebase.from_traktor_ms(c.start or 0.0, offset_ms), start=timebase.from_traktor_ms(c.start or 0.0, offset_ms),
length=(c.len or 0.0) / 1000.0, length=(c.len or 0.0) / 1000.0,
slot=slot, slot=slot,
@@ -221,6 +270,7 @@ def to_track_cues(entry, offset_ms: float = 0.0) -> TrackCues:
editable=True, editable=True,
readonly_reason=None, readonly_reason=None,
grid_marker=marker, grid_marker=marker,
id=memory_id,
) )
) )
return TrackCues( return TrackCues(
+108 -18
View File
@@ -53,10 +53,10 @@ from ...core.pathmap import PathMapping, stored_form
from ...core.relocate import PathGroup from ...core.relocate import PathGroup
from ...core.stem_file import NML_STEMS_JSON, nml_stems_for from ...core.stem_file import NML_STEMS_JSON, nml_stems_for
from ...schemas import PlaylistNode from ...schemas import PlaylistNode
from . import beatgrid, timebase from . import beatgrid, timebase, track_palette
from .locations import os_path_to_location, resolve_path from .locations import os_path_to_location, resolve_path
from ...core import musical_key from ...core import musical_key
from .projection import iso_date, musical_key_value, traktor_date from .projection import iso_date, musical_key_value, traktor_date, with_memory_ids
# Traktor's POPM frame owner: an ID3 rating is per-owner, so writing under # Traktor's POPM frame owner: an ID3 rating is per-owner, so writing under
# this email is what makes the stars show up in Traktor itself. # this email is what makes the stars show up in Traktor itself.
@@ -446,7 +446,8 @@ class TraktorStore:
EDITABLE_FIELDS = {"title", "artist", "album", "rating", "comment2"} | _INFO_FIELDS EDITABLE_FIELDS = {"title", "artist", "album", "rating", "comment2"} | _INFO_FIELDS
# Fields that live only in the collection: Traktor itself writes no file tag # 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. # 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: def set_track_metadata(self, track_id: str, fields: dict) -> None:
with self._lock: with self._lock:
@@ -544,6 +545,27 @@ class TraktorStore:
self._journal.record("track", "set", track_id, "key", before, entry.info.key) self._journal.record("track", "set", track_id, "key", before, entry.info.key)
self.dirty = True 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 -------------------------------------------------- # ---- adding tracks --------------------------------------------------
def add_entry(self, track, audio_path: Path) -> str: def add_entry(self, track, audio_path: Path) -> str:
"""Append a brand-new ENTRY for `audio_path` and return its track id. """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. # attribute at all rather than a zero.
ranking=(max(0, min(5, int(getattr(track, "rating", 0) or 0))) * 51) or None, ranking=(max(0, min(5, int(getattr(track, "rating", 0) or 0))) * 51) or None,
playtime=getattr(track, "length", None) or None, playtime=getattr(track, "length", None) or None,
color=track_palette.code_for(getattr(track, "color", None)),
) )
album = None album = None
if getattr(track, "album", None): if getattr(track, "album", None):
@@ -770,21 +793,7 @@ class TraktorStore:
if name is not None: if name is not None:
existing.name = name existing.name = name
else: else:
if entry.cue_v2 is None: self._insert_cue(entry, self._new_cue(cue_type, start_ms, len_ms, slot, name))
entry.cue_v2 = []
entry.cue_v2.append(
CueV2Type(
name=name or "n.n.", # Traktor's default name for a manual cue
displ_order=0,
type=cue_type,
start=start_ms,
len=len_ms,
repeats=-1,
hotcue=slot,
color=None,
grid=None,
)
)
# "add" only when it's a genuinely new hotcue; repositioning/retyping # "add" only when it's a genuinely new hotcue; repositioning/retyping
# an existing slot is a "modify" (keeps the net add/remove count honest). # an existing slot is a "modify" (keeps the net add/remove count honest).
self._note( self._note(
@@ -816,6 +825,87 @@ class TraktorStore:
name=getattr(spec, "name", None), name=getattr(spec, "name", None),
) )
@staticmethod
def _new_cue(cue_type: int, start_ms: float, len_ms: float, hotcue: int,
name: str | None) -> CueV2Type:
"""A CUE_V2 as Traktor writes one by hand — on a pad, or on none
(`hotcue` -1, a memory cue: the same element, measured in Traktor 4.5)."""
return CueV2Type(
name=name or "n.n.", # Traktor's default name for a manual cue
displ_order=0,
type=cue_type,
start=start_ms,
len=len_ms,
repeats=-1,
hotcue=hotcue,
color=None,
grid=None,
)
@staticmethod
def _insert_cue(entry: Entrytype, cue: CueV2Type) -> None:
"""Insert a new cue at its place BY START, after every cue at or before
it — Traktor keeps CUE_V2 sorted by START (8485/8485 reference entries,
and its own saves), so a later Traktor save moves nothing. Nothing else
moves either, unlike a re-sort of an entry another tool left unsorted."""
if entry.cue_v2 is None:
entry.cue_v2 = []
at = len(entry.cue_v2)
while at > 0 and (entry.cue_v2[at - 1].start or 0.0) > (cue.start or 0.0):
at -= 1
entry.cue_v2.insert(at, cue)
# ---- memory cues: CUE_V2 on no pad (HOTCUE="-1"), not a grid marker -----
# Measured in Traktor 4.5 (2026-10-16, kit M3): any type, no limit, drawn
# on the waveform and reached with the cue panel's ‹ ›, a name shown in the
# cue panel — and a cue written here survives Traktor's own save byte for
# byte. Addressed by `projection.memory_cue_id`.
def _memory_cue(self, entry: Entrytype, cue_id: str) -> CueV2Type:
cue = next((c for c, mid in with_memory_ids(entry) if mid == cue_id), None)
if cue is None:
raise PlaylistError(f"Memory cue {cue_id!r} not found on this track")
return cue
def add_memory_cue(self, track_id: str, start_sec: float, cue_type: int,
length_sec: float = 0.0, name: str | None = None) -> None:
if cue_type not in self.CREATABLE_TYPES:
raise PlaylistError(f"Unsupported cue type: {cue_type}")
with self._lock:
entry = self._entry_or_raise(track_id)
start_ms = timebase.to_traktor_ms(start_sec, self.time_offset_ms(entry))
len_ms = max(0.0, length_sec * 1000.0)
self._insert_cue(entry, self._new_cue(cue_type, start_ms, len_ms, -1, name))
self._note("hotcue", "add", track_id, "memory")
self.dirty = True
def rename_memory_cue(self, track_id: str, cue_id: str, name: str | None) -> None:
with self._lock:
entry = self._entry_or_raise(track_id)
self._memory_cue(entry, cue_id).name = name or "n.n."
self._note("hotcue", "modify", track_id, "memory")
self.dirty = True
def set_memory_cue_type(self, track_id: str, cue_id: str, cue_type: int) -> None:
"""A point type only, as for a hot cue: a loop is not retyped."""
if cue_type not in self.POINT_CUE_TYPES:
raise PlaylistError(f"Unsupported cue type: {cue_type}")
with self._lock:
entry = self._entry_or_raise(track_id)
cue = self._memory_cue(entry, cue_id)
if cue.type not in self.POINT_CUE_TYPES:
raise PlaylistError("A memory loop keeps its type")
cue.type = cue_type
self._note("hotcue", "modify", track_id, "memory")
self.dirty = True
def delete_memory_cue(self, track_id: str, cue_id: str) -> None:
with self._lock:
entry = self._entry_or_raise(track_id)
cue = self._memory_cue(entry, cue_id)
entry.cue_v2 = [c for c in entry.cue_v2 if c is not cue]
self._note("hotcue", "delete", track_id, "memory")
self.dirty = True
def set_hotcue_type(self, track_id: str, slot: int, cue_type: int) -> None: def set_hotcue_type(self, track_id: str, slot: int, cue_type: int) -> None:
"""Change the type of the existing hotcue in `slot` (keeps its position).""" """Change the type of the existing hotcue in `slot` (keeps its position)."""
if cue_type not in self.POINT_CUE_TYPES: if cue_type not in self.POINT_CUE_TYPES:
@@ -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)
+27 -1
View File
@@ -22,7 +22,7 @@ from dataclasses import dataclass, field
from pathlib import Path from pathlib import Path
from typing import Protocol, runtime_checkable 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 .model import Facets, PlaylistNode, Stats, Track, TrackCues, TrackPage
from .pathmap import PathMapping from .pathmap import PathMapping
from .relocate import PathGroup from .relocate import PathGroup
@@ -296,6 +296,9 @@ class LibraryAdapter(Protocol):
# analysis writes. Each platform renders it in its own notation (and its own # 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`. # 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: ... 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 set_cover_art(self, track_id: str, data: bytes, mime: str) -> None: ...
def cover_art(self, track_id: str) -> tuple[bytes, str] | None: ... def cover_art(self, track_id: str) -> tuple[bytes, str] | None: ...
@@ -318,6 +321,29 @@ class LibraryAdapter(Protocol):
def delete_cue(self, track_id: str, slot: int) -> TrackCues: ... def delete_cue(self, track_id: str, slot: int) -> TrackCues: ...
def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues: ... def place_cues(self, track_id: str, cues: list, *, overwrite: bool = False) -> TrackCues: ...
# ---- commands: memory cues --------------------------------------------
# Cues on no pad, addressed by `CuePoint.id`. Gated on `cues.memory_cues`.
# Past `cues.max_memory_cues` -> InvalidCommand; an unknown id -> NotFound;
# `color` is from `cues.memory_palette` (Unsupported where memory_color is
# "none"). There is deliberately no move: rekordbox has none either, so a
# move is a delete and an add.
def add_memory_cue(
self,
track_id: str,
*,
start_sec: float,
cue_type: str,
length_sec: float = 0.0,
name: str | None = None,
color: str | None = None,
) -> TrackCues: ...
def rename_memory_cue(self, track_id: str, cue_id: str, name: str | None) -> TrackCues: ...
# A POINT type from `cues.types` (Traktor: cue / fade in / fade out / load);
# a loop is not retyped. Unsupported where the platform has one point type.
def set_memory_cue_type(self, track_id: str, cue_id: str, cue_type: str) -> TrackCues: ...
def set_memory_cue_color(self, track_id: str, cue_id: str, color: str | None) -> TrackCues: ...
def delete_memory_cue(self, track_id: str, cue_id: str) -> TrackCues: ...
# ---- commands: beatgrid --------------------------------------------- # ---- commands: beatgrid ---------------------------------------------
def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> TrackCues: ... def add_grid_marker(self, track_id: str, start_sec: float, bpm: float | None = None) -> TrackCues: ...
def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> TrackCues: ... def move_grid_marker(self, track_id: str, index: int, start_sec: float) -> TrackCues: ...
+26 -2
View File
@@ -36,6 +36,20 @@ CueType = Literal["cue", "fade_in", "fade_out", "load", "loop"]
CueRole = Literal["hotcue", "memory"] CueRole = Literal["hotcue", "memory"]
MediaKind = Literal["audio", "stem", "video"] MediaKind = Literal["audio", "stem", "video"]
PlaylistKind = Literal["folder", "playlist", "smart"] 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): class CueCapabilities(BaseModel):
@@ -45,10 +59,17 @@ class CueCapabilities(BaseModel):
editable: bool = False editable: bool = False
hotcue_slots: int = 8 # size of the addressable bank; 0 = no bank hotcue_slots: int = 8 # size of the addressable bank; 0 = no bank
slot_labels: Literal["number", "letter"] = "number" slot_labels: Literal["number", "letter"] = "number"
# Memory cues are Rekordbox-only today, so they are modelled and PRESERVED # Cues on no pad, listed in time order and called CDJ-style (decided
# but not editable anywhere yet (the two-platform promotion rule). # 2026-10-16). Editable wherever `editable` is: every platform that has them
# can store them (Rekordbox, OneLibrary, and Traktor's HOTCUE="-1").
memory_cues: bool = False memory_cues: bool = False
# Per track; None = no limit. rekordbox stops storing at 10 WITHOUT saying
# so, so the adapter refuses the 11th itself.
max_memory_cues: int | None = None max_memory_cues: int | None = None
# A memory cue's colour is its own palette, not `palette` (rekordbox offers
# 8 colours for memory cues against 16 for hot cues).
memory_color: Literal["none", "palette"] = "none"
memory_palette: list[str] = []
types: list[CueType] = ["cue"] types: list[CueType] = ["cue"]
color: Literal["none", "free", "palette"] = "none" color: Literal["none", "free", "palette"] = "none"
palette: list[str] = [] palette: list[str] = []
@@ -100,6 +121,9 @@ class TrackCapabilities(BaseModel):
# Whether added files can be left where they are ("reference") rather than # 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. # copied. False where the library cannot see this computer's files at all.
reference: bool = True 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): class PlaylistCapabilities(BaseModel):
+2 -3
View File
@@ -25,9 +25,8 @@ MEMORY_COLOR = "#9AA1B2" # grey
def effective_color(cue: CuePoint) -> str: def effective_color(cue: CuePoint) -> str:
"""`#RRGGBB` — the stored colour, or the type's.""" """`#RRGGBB` — the stored colour, or the type's: hot and memory cues alike
(a memory cue's type colours it too, decided 2026-10-16)."""
if cue.color: if cue.color:
return cue.color.upper() return cue.color.upper()
if cue.role == "memory":
return MEMORY_COLOR
return TYPE_COLORS.get(cue.type, MEMORY_COLOR) return TYPE_COLORS.get(cue.type, MEMORY_COLOR)
+16 -12
View File
@@ -167,21 +167,23 @@ class EditJournal:
else: else:
parts.append(f"{verb} {len(names)} {noun}s") parts.append(f"{verb} {len(names)} {noun}s")
# --- hotcues: net change in count, scoped by how many tracks were touched --- # --- cues: net change in count, scoped by how many tracks were touched.
hc_add = hc_del = 0 # Memory cues (detail "memory") are counted apart from hotcues, so a
hc_tracks: set[str] = set() # session of memory-cue edits is not described as hotcue work.
counts = {kind: [0, 0, set()] for kind in ("hotcue", "memory cue")}
grid_edit: set[str] = set() grid_edit: set[str] = set()
grid_del: set[str] = set() grid_del: set[str] = set()
lock_on: set[str] = set() lock_on: set[str] = set()
lock_off: set[str] = set() lock_off: set[str] = set()
for c in self.changes: for c in self.changes:
if c.scope == "cue": if c.scope == "cue":
bucket = counts["memory cue" if c.detail == "memory" else "hotcue"]
if c.target: if c.target:
hc_tracks.add(c.target) bucket[2].add(c.target)
if c.op == "add": if c.op == "add":
hc_add += 1 bucket[0] += 1
elif c.op == "delete": elif c.op == "delete":
hc_del += 1 bucket[1] += 1
elif c.scope == "grid": elif c.scope == "grid":
# "delete" is the ONLY deletion op. Everything else — including # "delete" is the ONLY deletion op. Everything else — including
# ops added later — counts as an edit, because mis-labelling an # ops added later — counts as an edit, because mis-labelling an
@@ -190,15 +192,17 @@ class EditJournal:
elif c.scope == "lock": elif c.scope == "lock":
(lock_on if c.op == "on" else lock_off).add(c.target or "") (lock_on if c.op == "on" else lock_off).add(c.target or "")
if hc_tracks: for noun, (added, deleted, touched) in counts.items():
net = hc_add - hc_del if not touched:
scope = f" across {tracks(len(hc_tracks))}" if len(hc_tracks) > 1 else "" continue
net = added - deleted
scope = f" across {tracks(len(touched))}" if len(touched) > 1 else ""
if net > 0: if net > 0:
parts.append(f"added {net} hotcue{'' if net == 1 else 's'}{scope}") parts.append(f"added {net} {noun}{'' if net == 1 else 's'}{scope}")
elif net < 0: elif net < 0:
parts.append(f"removed {-net} hotcue{'' if -net == 1 else 's'}{scope}") parts.append(f"removed {-net} {noun}{'' if -net == 1 else 's'}{scope}")
else: # net zero but there was activity (moves / retypes / add-then-delete) else: # net zero but there was activity (moves / retypes / add-then-delete)
parts.append(f"adjusted hotcues{scope}") parts.append(f"adjusted {noun}s{scope}")
# --- beatgrids & lock: per-track counts --- # --- beatgrids & lock: per-track counts ---
if grid_edit: if grid_edit:
+12 -3
View File
@@ -13,7 +13,7 @@ from typing import Literal
from pydantic import BaseModel, ConfigDict, Field from pydantic import BaseModel, ConfigDict, Field
from .capabilities import CueRole, CueType, MediaKind, PlaylistKind from .capabilities import CueRole, CueType, MediaKind, PlaylistKind, TrackColor
class HotcueChip(BaseModel): class HotcueChip(BaseModel):
@@ -71,6 +71,11 @@ class Track(BaseModel):
grid_marker_count: int = 0 grid_marker_count: int = 0
grid_locked: bool = False grid_locked: bool = False
media_kind: MediaKind = "audio" 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): class TrackPage(BaseModel):
@@ -144,8 +149,8 @@ PlaylistNode.model_rebuild()
class CuePoint(BaseModel): class CuePoint(BaseModel):
name: str | None = None name: str | None = None
type: CueType = "cue" type: CueType = "cue"
# "memory" cues have no bank slot. Only Rekordbox has them, so they are # A "memory" cue has no bank slot: Rekordbox's / OneLibrary's memory cues,
# modelled and preserved but not yet editable anywhere. # Traktor's cues on no pad (HOTCUE="-1"). Addressed by `id`, not `slot`.
role: CueRole = "hotcue" role: CueRole = "hotcue"
start: float # seconds start: float # seconds
length: float # seconds (>0 for loops) length: float # seconds (>0 for loops)
@@ -158,6 +163,10 @@ class CuePoint(BaseModel):
# Index of the grid marker this cue mirrors, where the platform pairs them. # Index of the grid marker this cue mirrors, where the platform pairs them.
# A display hint only; None on platforms that do not. # A display hint only; None on platforms that do not.
grid_marker: int | None = None grid_marker: int | None = None
# The handle the memory-cue commands take (None on a hot cue, which is
# addressed by slot). Opaque and adapter-defined; an edit of THIS cue may
# change it, which is fine because every command returns fresh TrackCues.
id: str | None = None
class GridMarker(BaseModel): class GridMarker(BaseModel):
+6 -4
View File
@@ -317,6 +317,7 @@ def run(
folder_name: str | None = None, folder_name: str | None = None,
reference: bool = False, reference: bool = False,
into_playlist: str | None = None, into_playlist: str | None = None,
into_playlist_index: int | None = None,
) -> dict: ) -> dict:
"""Perform the import. Returns a summary dict for the job result. """Perform the import. Returns a summary dict for the job result.
@@ -332,7 +333,8 @@ def run(
`reference` adds each file WHERE IT IS instead of copying it, so there is no `reference` adds each file WHERE IT IS instead of copying it, so there is no
destination and nothing to roll back. `into_playlist` appends every planned destination and nothing to roll back. `into_playlist` appends every planned
track — the new ones and those the destination already held — to one of the track — the new ones and those the destination already held — to one of the
destination's playlists before the save, so both land in one commit. destination's playlists before the save, so both land in one commit;
`into_playlist_index` inserts them there instead (a drop between rows).
A destination that PLACES ITS OWN AUDIO (`tracks.places_audio`: a OneLibrary A destination that PLACES ITS OWN AUDIO (`tracks.places_audio`: a OneLibrary
stick) overrides both: `dest.place_audio` names each copy's target, or says stick) overrides both: `dest.place_audio` names each copy's target, or says
@@ -446,9 +448,9 @@ def run(
handle.progress(message="Adding to the playlist…") handle.progress(message="Adding to the playlist…")
current = dest.playlist_entries(into_playlist) or [] current = dest.playlist_entries(into_playlist) or []
have = set(current) have = set(current)
dest.set_playlist_entries( fresh = [i for i in all_ids if i not in have]
into_playlist, current + [i for i in all_ids if i not in have] at = len(current) if into_playlist_index is None else max(0, min(len(current), into_playlist_index))
) dest.set_playlist_entries(into_playlist, current[:at] + fresh + current[at:])
playlists_made = _rebuild_playlists( playlists_made = _rebuild_playlists(
source, dest, plan, by_source, folder_name, handle source, dest, plan, by_source, folder_name, handle
+59 -1
View File
@@ -60,6 +60,7 @@ from .schemas import (
LibraryInfo, LibraryInfo,
PlatformOption, PlatformOption,
EditTrack, EditTrack,
SetTrackColor,
Facets, Facets,
FileTagOutcome, FileTagOutcome,
CreateExportSet, CreateExportSet,
@@ -102,6 +103,10 @@ from .schemas import (
SetCue, SetCue,
SetCueColor, SetCueColor,
SetCueType, SetCueType,
AddMemoryCue,
RenameMemoryCue,
SetMemoryCueColor,
SetMemoryCueType,
SetGridLock, SetGridLock,
Stats, Stats,
Track, Track,
@@ -1304,7 +1309,8 @@ def add_entries(playlist_uuid: str, body: AddEntries) -> dict:
return {"status": "duplicates", "id": playlist_uuid, "added": 0, return {"status": "duplicates", "id": playlist_uuid, "added": 0,
"duplicates": len(dupes), "count": len(current)} "duplicates": len(dupes), "count": len(current)}
added = list(body.track_ids) if mode == "add" else [t for t in body.track_ids if t not in have] added = list(body.track_ids) if mode == "add" else [t for t in body.track_ids if t not in have]
n = a.set_playlist_entries(playlist_uuid, current + added) if added else len(current) at = len(current) if body.index is None else max(0, min(len(current), body.index))
n = a.set_playlist_entries(playlist_uuid, current[:at] + added + current[at:]) if added else len(current)
return {"status": "added", "id": playlist_uuid, "added": len(added), return {"status": "added", "id": playlist_uuid, "added": len(added),
"duplicates": len(dupes), "count": n} "duplicates": len(dupes), "count": n}
@@ -1316,6 +1322,17 @@ def edit_track(body: EditTrack) -> dict:
return {"status": "updated", "id": body.track_id} 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") @app.get("/api/tracks/art")
def track_art(track_id: str) -> Response: def track_art(track_id: str) -> Response:
"""Stream a track's embedded cover art (staged replacement if unsaved).""" """Stream a track's embedded cover art (staged replacement if unsaved)."""
@@ -1842,6 +1859,45 @@ def delete_cue(track_id: str, slot: int) -> TrackCues:
return require_adapter().delete_cue(track_id, slot) return require_adapter().delete_cue(track_id, slot)
# Memory cues — cues on no pad, addressed by CuePoint.id (gated on
# capabilities.cues.memory_cues; the adapter refuses past max_memory_cues).
@app.post("/api/tracks/memory-cue", response_model=TrackCues)
def add_memory_cue(body: AddMemoryCue) -> TrackCues:
"""Add a memory cue (a memory loop when `length` > 0)."""
return require_adapter().add_memory_cue(
body.track_id,
start_sec=body.start,
cue_type=body.type,
length_sec=body.length,
name=body.name,
color=body.color,
)
@app.patch("/api/tracks/memory-cue", response_model=TrackCues)
def rename_memory_cue(body: RenameMemoryCue) -> TrackCues:
"""Name a memory cue (rekordbox calls it the comment); None/"" clears it."""
return require_adapter().rename_memory_cue(body.track_id, body.cue_id, body.name or None)
@app.patch("/api/tracks/memory-cue/type", response_model=TrackCues)
def edit_memory_cue_type(body: SetMemoryCueType) -> TrackCues:
"""Change a memory cue's point type (keeps its position)."""
return require_adapter().set_memory_cue_type(body.track_id, body.cue_id, body.type)
@app.patch("/api/tracks/memory-cue/color", response_model=TrackCues)
def edit_memory_cue_color(body: SetMemoryCueColor) -> TrackCues:
"""Recolour a memory cue from capabilities.cues.memory_palette (None = uncoloured)."""
return require_adapter().set_memory_cue_color(body.track_id, body.cue_id, body.color)
@app.delete("/api/tracks/memory-cue", response_model=TrackCues)
def delete_memory_cue(track_id: str, cue_id: str) -> TrackCues:
"""Remove a memory cue."""
return require_adapter().delete_memory_cue(track_id, cue_id)
@app.post("/api/tracks/grid/marker", response_model=TrackCues) @app.post("/api/tracks/grid/marker", response_model=TrackCues)
def add_grid_marker(body: AddGridMarker) -> TrackCues: def add_grid_marker(body: AddGridMarker) -> TrackCues:
"""Add a beatgrid marker. Omitting `bpm` inherits the governing tempo.""" """Add a beatgrid marker. Omitting `bpm` inherits the governing tempo."""
@@ -2517,6 +2573,7 @@ def folder_add(body: FolderAddRequest) -> JobStatus:
source, dest, plan, handle, source, dest, plan, handle,
reference=in_place or body.mode == "reference", reference=in_place or body.mode == "reference",
into_playlist=body.playlist_id, into_playlist=body.playlist_id,
into_playlist_index=body.playlist_index,
) )
# Export sets are Konduktor's own data, not the library's, so they are # Export sets are Konduktor's own data, not the library's, so they are
# updated after the library has been saved rather than inside it. # updated after the library has been saved rather than inside it.
@@ -2603,6 +2660,7 @@ def start_import(body: ImportRequest) -> JobStatus:
def work(handle): def work(handle):
result = importer.run( result = importer.run(
source, dest, plan, handle, folder_name=folder_name, into_playlist=body.into_playlist, source, dest, plan, handle, folder_name=folder_name, into_playlist=body.into_playlist,
into_playlist_index=body.into_playlist_index,
) )
# As folder add: an export set is Konduktor's data, updated afterwards. # As folder add: an export set is Konduktor's data, updated afterwards.
if body.export_id is not None and library is not None: if body.export_id is not None and library is not None:
+8 -3
View File
@@ -36,7 +36,10 @@ from .core.model import AutoHotcue, Track, TrackCues
#: method, the major for anything an older client would misread. #: method, the major for anything an older client would misread.
#: 1.1 — `move_playlist` (sidebar drag and drop). #: 1.1 — `move_playlist` (sidebar drag and drop).
#: 1.2 — `/v1/folder/*`: the content folder browsed as a Files tree. #: 1.2 — `/v1/folder/*`: the content folder browsed as a Files tree.
API_VERSION: tuple[int, int] = (1, 2) #: 1.3 — memory cues: `add_memory_cue`, `rename_memory_cue`,
#: `set_memory_cue_type`, `set_memory_cue_color`, `delete_memory_cue`.
#: 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 #: 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 #: sends one. Long enough to ride out a Wi-Fi blip or a switch to the fallback
@@ -75,8 +78,10 @@ _READ = (
) )
_MUTATING = ( _MUTATING = (
"create_playlist", "create_folder", "rename_playlist", "delete_playlist", "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_cue_type", "set_cue_color", "delete_cue", "place_cues", "add_grid_marker", "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", "move_grid_marker", "set_grid_marker_bpm", "delete_grid_marker", "replace_grid",
"set_analysed_grid", "delete_grid", "set_grid_lock", "add_tracks", "set_analysed_grid", "delete_grid", "set_grid_lock", "add_tracks",
) )
+40 -1
View File
@@ -5,7 +5,7 @@ from typing import Literal
from pydantic import BaseModel, ConfigDict, Field from pydantic import BaseModel, ConfigDict, Field
from .core.capabilities import CueRole, CueType from .core.capabilities import CueRole, CueType, TrackColor
class CreatePlaylist(BaseModel): class CreatePlaylist(BaseModel):
@@ -27,6 +27,9 @@ class AddEntries(BaseModel):
# where `playlists.duplicates`, else skipped), or "ask" — change nothing and # where `playlists.duplicates`, else skipped), or "ask" — change nothing and
# report how many, so the UI can ask and send again with skip/add. # report how many, so the UI can ask and send again with skip/add.
duplicates: Literal["skip", "add", "ask"] = "skip" duplicates: Literal["skip", "add", "ask"] = "skip"
# Insert at this position among the playlist's CURRENT entries (a drop
# between rows); None appends. Clamped to the list.
index: int | None = None
class MovePlaylist(BaseModel): class MovePlaylist(BaseModel):
@@ -40,6 +43,13 @@ class EditTrack(BaseModel):
fields: dict[str, str | int | None] 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): class FileTagOutcome(BaseModel):
track_id: str track_id: str
file: str file: str
@@ -200,6 +210,33 @@ class SetCueColor(BaseModel):
color: str | None = None # a capabilities.cues.palette entry; None = uncoloured color: str | None = None # a capabilities.cues.palette entry; None = uncoloured
class AddMemoryCue(BaseModel):
track_id: str
start: float # seconds
type: CueType = "cue"
length: float = 0.0 # seconds (>0 for a memory loop)
name: str | None = None
color: str | None = None # a capabilities.cues.memory_palette entry
class RenameMemoryCue(BaseModel):
track_id: str
cue_id: str # CuePoint.id
name: str | None = None # None / "" = unnamed
class SetMemoryCueType(BaseModel):
track_id: str
cue_id: str
type: CueType # a point type from capabilities.cues.types
class SetMemoryCueColor(BaseModel):
track_id: str
cue_id: str
color: str | None = None # a capabilities.cues.memory_palette entry; None = uncoloured
class StemEngineInstall(BaseModel): class StemEngineInstall(BaseModel):
# None = this computer's default engine; "windows-x64-cuda" to take the GPU one. # None = this computer's default engine; "windows-x64-cuda" to take the GPU one.
target: str | None = None target: str | None = None
@@ -511,6 +548,7 @@ class ImportRequest(BaseModel):
# drop): every imported track — and every one the collection already # drop): every imported track — and every one the collection already
# holds — goes into it, as folder add does. # holds — goes into it, as folder add does.
into_playlist: str | None = None into_playlist: str | None = None
into_playlist_index: int | None = None # where in it (see AddEntries.index)
export_id: str | None = None export_id: str | None = None
@@ -579,6 +617,7 @@ class FolderAddRequest(BaseModel):
mode: Literal["copy", "reference"] mode: Literal["copy", "reference"]
destination: str | None = None # required for `copy` destination: str | None = None # required for `copy`
playlist_id: str | None = None playlist_id: str | None = None
playlist_index: int | None = None # where in it (see AddEntries.index)
export_id: str | None = None export_id: str | None = None
+1 -1
View File
@@ -14,5 +14,5 @@ Pillow>=11 # a Rekordbox add writes the cover's artwork files
dulwich>=0.22 # version history, beside the library dulwich>=0.22 # version history, beside the library
platformdirs>=4.0 platformdirs>=4.0
# From GitHub, NOT PyPI — see requirements.txt for why. # From GitHub, NOT PyPI — see requirements.txt for why.
traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git@39a9c15f29d6b0ea2ce61cd7d548501eea38319d traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git@d7f472aaf5be53e53921de351e948233e9c1d1e8
pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git@43137cb91f8297c768d2a8bdce5b27b2225f0a2d pyrekordbox @ git+https://github.com/dylanljones/pyrekordbox.git@43137cb91f8297c768d2a8bdce5b27b2225f0a2d
+1 -1
View File
@@ -24,7 +24,7 @@ scikit-learn>=1.5
# what it had: pyrekordbox renamed `devicelib_plus` to `onelibrary` upstream, # what it had: pyrekordbox renamed `devicelib_plus` to `onelibrary` upstream,
# every local test passed, and the released app could not export or read a # every local test passed, and the released app could not export or read a
# OneLibrary stick. Move a pin deliberately, with ./run_tests.sh. # OneLibrary stick. Move a pin deliberately, with ./run_tests.sh.
traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git@39a9c15f29d6b0ea2ce61cd7d548501eea38319d traktor-nml-utils @ git+https://github.com/MrPatben8/traktor-nml-utils.git@d7f472aaf5be53e53921de351e948233e9c1d1e8
# Rekordbox (master.db is SQLCipher-encrypted SQLite + per-track ANLZ analysis # Rekordbox (master.db is SQLCipher-encrypted SQLite + per-track ANLZ analysis
# files). Both ship prebuilt Python 3.14 wheels — no Rust/OpenSSL source build. # files). Both ship prebuilt Python 3.14 wheels — no Rust/OpenSSL source build.
# #
+4 -1
View File
@@ -153,7 +153,8 @@ for i, (title, artist, key) in enumerate((("One", "Artist A", (8, "minor")), ("T
png = __import__("io").BytesIO() png = __import__("io").BytesIO()
Image.new("RGB", (300, 300), (40 * i, 90, 160)).save(png, format="PNG") 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, 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"), 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=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)]))) 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", 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) 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]) 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("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)) 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} tree = {p["name"]: p for p in lib.playlists}
+9 -1
View File
@@ -66,11 +66,14 @@ chosen = [flexible, cued, plain]
dest = Path(tempfile.mkdtemp()) / "GIG" dest = Path(tempfile.mkdtemp()) / "GIG"
dest.mkdir(parents=True) dest.mkdir(parents=True)
items = [] 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: for track in chosen:
audio = dest / "Music" / "Library" / Path(track.filepath).name audio = dest / "Music" / "Library" / Path(track.filepath).name
audio.parent.mkdir(parents=True, exist_ok=True) audio.parent.mkdir(parents=True, exist_ok=True)
audio.write_bytes(b"\0" * 64) 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( payload = ExportPayload(
name="GIG", name="GIG",
@@ -126,6 +129,11 @@ check("artist survived", by_title[plain.title].artist == plain.artist)
if plain.key: if plain.key:
check("key notation is copied, not converted", by_title[plain.title].key == 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 ==") print("== the playlist tree ==")
tree = {} tree = {}
+48 -3
View File
@@ -58,13 +58,19 @@ cued = next(t for t in src.tracks
chosen = [flexible, cued] chosen = [flexible, cued]
COLOURS = ["purple", "aqua"]
def build(root: Path) -> ExportPayload: def build(root: Path) -> ExportPayload:
items = [] items = []
for i, track in enumerate(chosen): for i, track in enumerate(chosen):
audio = root / ("House" if i % 2 else "Techno") / Path(track.filepath).name audio = root / ("House" if i % 2 else "Techno") / Path(track.filepath).name
audio.parent.mkdir(parents=True, exist_ok=True) audio.parent.mkdir(parents=True, exist_ok=True)
audio.write_bytes(b"\0" * 4096) 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))) cues=src.track_cues(track.id)))
return ExportPayload( return ExportPayload(
name="GIG", tracks=items, 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 all(abs((by_title[t.title].bpm or 0) - (t.bpm or 0)) < 0.02
for t in chosen if t.bpm)) 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") print(f"-- {platform}: the key was CONVERTED, not copied")
for track in chosen: for track in chosen:
if not track.key: if not track.key:
@@ -236,7 +246,10 @@ def _real_cue_tags(path: Path) -> list[bytes]:
def _mask_colour(tag: bytes) -> bytes: def _mask_colour(tag: bytes) -> bytes:
"""A PCO2 tag with each entry's code + RGB (after its comment) zeroed.""" """A PCO2 tag with each entry's colours zeroed: the hot-cue code + RGB
(after its comment) and byte 28, a memory cue's colour. The fixture's
memory loop is uncoloured; Konduktor now exports one in its TYPE colour,
as it draws it (decided 2026-10-16) — pinned separately below."""
if tag[:4] != b"PCO2": if tag[:4] != b"PCO2":
return tag return tag
out, off = bytearray(tag), struct.unpack(">I", tag[4:8])[0] out, off = bytearray(tag), struct.unpack(">I", tag[4:8])[0]
@@ -244,6 +257,7 @@ def _mask_colour(tag: bytes) -> bytes:
length = struct.unpack(">I", tag[off + 8:off + 12])[0] length = struct.unpack(">I", tag[off + 8:off + 12])[0]
at = off + 44 + struct.unpack(">I", tag[off + 40:off + 44])[0] at = off + 44 + struct.unpack(">I", tag[off + 40:off + 44])[0]
out[at:at + 4] = bytes(4) out[at:at + 4] = bytes(4)
out[off + 28] = 0
off += length off += length
return bytes(out) return bytes(out)
@@ -424,6 +438,7 @@ print("\n== cue colours cross as rekordbox PALETTE CODES ==")
# rekordbox draws a hot cue from the palette code, not the RGB: an export writing # rekordbox draws a hot cue from the palette code, not the RGB: an export writing
# code 0 had every cue drawn in rekordbox's defaults (green cues, orange loops). # code 0 had every cue drawn in rekordbox's defaults (green cues, orange loops).
# The table was measured from a rekordbox 7 export of all 16 swatches. # The table was measured from a rekordbox 7 export of all 16 swatches.
from konduktor.adapters.rekordbox import anlz_file as A_ # noqa: E402
from konduktor.adapters.rekordbox import palette # noqa: E402 from konduktor.adapters.rekordbox import palette # noqa: E402
check("a measured swatch keeps its exact code and RGB", check("a measured swatch keeps its exact code and RGB",
@@ -451,6 +466,35 @@ entry = W.cue_tags([{"hot_cue": 1, "kind": 1, "time_ms": 1000, "loop_ms": None,
check("the code is packed where rekordbox 7 puts it — byte 44, before the RGB", check("the code is packed where rekordbox 7 puts it — byte 44, before the RGB",
entry[20 + 44:20 + 48] == bytes([0x16, 0x1A, 0xFF, 0x00]), entry[64:68].hex()) entry[20 + 44:20 + 48] == bytes([0x16, 0x1A, 0xFF, 0x00]), entry[64:68].hex())
# Memory cues (kit M2, 2026-10-16): colour is PCP2 byte 28 from the 8-colour
# memory palette, a list of two or more is LINKED in the .DAT, and rekordbox
# keeps 10.
from konduktor.adapters.rekordbox import memory_palette # noqa: E402
many_memory = [CuePoint(type="cue", role="memory", start=float(i), length=0.0, slot=None,
color="#E13121" if i == 0 else None) for i in range(12)]
mem_dicts = OneLibraryExporter._cue_dicts(
ExportTrack(track=cued, destination=Path("t.wav"),
cues=TrackCues(track_id="t", cues=many_memory, grid_markers=[])), [], 0.0)
check("rekordbox keeps 10 memory cues: the earliest 10 are exported",
len(mem_dicts) == 10 and [d["time_ms"] for d in mem_dicts] == [i * 1000 for i in range(10)],
[d["time_ms"] for d in mem_dicts])
check("a memory cue's colour is byte 28 from its own palette (Red = 2); no hot-cue code",
(mem_dicts[0]["color_id"], mem_dicts[0]["code"]) == (memory_palette.anlz_byte(1), 0),
(mem_dicts[0]["color_id"], mem_dicts[0]["code"]))
check("an uncoloured one exports in its type colour, as Konduktor shows it (cue -> Blue = 7)",
mem_dicts[1]["color_id"] == memory_palette.anlz_byte(6), mem_dicts[1]["color_id"])
dat_tags = W.cue_tags(mem_dicts[:3], extended=False)
mem_pcob = A_.raw_entries(A_.Tag("PCOB", dat_tags[1]))
check("a memory PCOB of two or more is linked, status 0, as rekordbox writes it",
[(e[16:20].hex(), e[24:28].hex()) for e in mem_pcob]
== [("00000000", "ffff0001"), ("00000000", "00000002"), ("00000000", "0001ffff")],
[(e[16:20].hex(), e[24:28].hex()) for e in mem_pcob])
ext_tags = W.cue_tags(mem_dicts[:1], extended=True)
pco2_mem = A_.raw_entries(A_.Tag("PCO2", ext_tags[3]))
check("and the colour lands in PCP2 byte 28",
len(pco2_mem) == 1 and pco2_mem[0][28] == memory_palette.anlz_byte(1), pco2_mem and pco2_mem[0][24:32].hex())
print("\n== artwork crosses the way rekordbox 7 writes it ==") print("\n== artwork crosses the way rekordbox 7 writes it ==")
# Measured on a rekordbox 7 export: PIONEER/Artwork/00001/{a,b}<n>{,_m}.jpg at # Measured on a rekordbox 7 export: PIONEER/Artwork/00001/{a,b}<n>{,_m}.jpg at
# 80 and 240 px (a == b byte for byte), baseline JPEG q85 4:2:0, non-square art # 80 and 240 px (a == b byte for byte), baseline JPEG q85 4:2:0, non-square art
@@ -581,7 +625,8 @@ check("four cue rows: three hot cues and a memory cue (Kind 0)",
check("a plain cue is rekordbox's light blue (code 5)", by_kind.get(1) == (0x05, -1), by_kind.get(1)) check("a plain cue is rekordbox's light blue (code 5)", by_kind.get(1) == (0x05, -1), by_kind.get(1))
check("a loop is rekordbox's green (code 22)", by_kind.get(2) == (0x16, -1), by_kind.get(2)) check("a loop is rekordbox's green (code 22)", by_kind.get(2) == (0x16, -1), by_kind.get(2))
check("the white grid cue has no swatch, so stays uncoloured", by_kind.get(3) == (None, -1), by_kind.get(3)) check("the white grid cue has no swatch, so stays uncoloured", by_kind.get(3) == (None, -1), by_kind.get(3))
check("the memory cue is written, uncoloured", by_kind.get(0) == (None, -1), by_kind.get(0)) check("an uncoloured memory cue is written in its type colour (cue -> Blue, Color 6)",
by_kind.get(0) == (None, 6), by_kind.get(0))
check("the contentCue mirror holds all four, colours included", check("the contentCue mirror holds all four, colours included",
mirror is not None and mirror[0].count('"Kind"') == 4 and '"ColorTableIndex": 22' in mirror[0].replace(":22", ": 22"), mirror is not None and mirror[0].count('"Kind"') == 4 and '"ColorTableIndex": 22' in mirror[0].replace(":22", ": 22"),
mirror and mirror[0][:200]) mirror and mirror[0][:200])
+5 -1
View File
@@ -181,7 +181,9 @@ with TestClient(main.app, raise_server_exceptions=False) as c:
three_dir = music / "Deeper" three_dir = music / "Deeper"
c.get("/api/folder/tracks", params={"path": str(three_dir)}) c.get("/api/folder/tracks", params={"path": str(three_dir)})
dest = Path(tempfile.mkdtemp()) / "Imported" dest = Path(tempfile.mkdtemp()) / "Imported"
req = {"track_ids": [str(three_dir / "three.flac")], "mode": "copy", "destination": str(dest)} # Dropped between the playlist's rows: inserted there, not appended.
req = {"track_ids": [str(three_dir / "three.flac")], "mode": "copy", "destination": str(dest),
"playlist_id": playlist, "playlist_index": 1}
p = c.post("/api/folder/add/preview", json=req).json() p = c.post("/api/folder/add/preview", json=req).json()
check("the preview sizes the copy", p["total_bytes"] > 0, str(p)) check("the preview sizes the copy", p["total_bytes"] > 0, str(p))
job = wait(c, c.post("/api/folder/add", json=req).json()) job = wait(c, c.post("/api/folder/add", json=req).json())
@@ -191,6 +193,8 @@ with TestClient(main.app, raise_server_exceptions=False) as c:
check("the entry points at the copy", a.audio_path(copied_id) == dest / "three.flac", check("the entry points at the copy", a.audio_path(copied_id) == dest / "three.flac",
str(a.audio_path(copied_id))) str(a.audio_path(copied_id)))
check("the original is untouched", (three_dir / "three.flac").is_file()) check("the original is untouched", (three_dir / "three.flac").is_file())
check("it went into the playlist AT the index", a.playlist_entries(playlist) == [added, copied_id, new],
str(a.playlist_entries(playlist)))
check("copy without a destination is refused", check("copy without a destination is refused",
c.post("/api/folder/add", json={"track_ids": [str(one)], "mode": "copy"}).status_code == 400) c.post("/api/folder/add", json={"track_ids": [str(one)], "mode": "copy"}).status_code == 400)
check("an unscanned file cannot be added", check("an unscanned file cannot be added",
+34 -14
View File
@@ -139,15 +139,29 @@ check("every hot cue keeps the pad it was on",
check("a loop stays a loop, with its length", check("a loop stays a loop, with its length",
got_by_slot[0].type == "loop" and abs(got_by_slot[0].length - 1.875) < 0.001) got_by_slot[0].type == "loop" and abs(got_by_slot[0].length - 1.875) < 0.001)
# Traktor has no memory cues, so they degrade into spare pads rather than being # Memory cues cross AS memory cues — Traktor's cues on no pad (HOTCUE="-1"),
# dropped — the settled lossiness rule. # decided 2026-10-16 once Traktor was measured keeping them. They used to be
# promoted to spare pads.
n_memory = sum(1 for c in src_cues.cues if c.role != "hotcue") n_memory = sum(1 for c in src_cues.cues if c.role != "hotcue")
check("memory cues are preserved in spare slots, not dropped", padless = [c for c in dest._store.model_entry(ids[0]).cue_v2
len(got.cues) == len(src_hot) + n_memory, f"{len(got.cues)} cues") if c.grid is None and c.hotcue == -1]
check("and they do not overwrite a hot cue", check("every memory cue is written as a memory cue (a CUE_V2 on no pad)",
len({c.slot for c in got.cues}) == len(got.cues)) len(padless) == n_memory and n_memory > 0, f"{len(padless)} of {n_memory}")
check("every imported cue occupies a real pad", check("and no extra pad is taken",
all(c.role == "hotcue" and c.slot is not None for c in got.cues)) sorted(c.slot for c in got.cues if c.role == "hotcue") == sorted(src_hot))
# The demo track's memory loop starts exactly where pad A's loop does. Traktor
# draws a pad and a memory cue at one START as ONE marker (measured), so the
# projection shows it once, as the pad (decided 2026-10-16).
pad_starts = {round(c.start, 3) for c in got.cues if c.role == "hotcue"}
got_memory = [c for c in got.cues if c.role == "memory"]
check("a memory cue is shown unless a pad sits on its START",
len(got_memory) + sum(1 for c in padless
if round((c.start - dest._store.time_offset_ms(
dest._store.model_entry(ids[0]))) / 1000, 3) in pad_starts)
== n_memory,
f"{len(got_memory)} shown, pads at {sorted(pad_starts)}")
check("a shown memory cue has no pad and an id",
all(c.slot is None and c.id for c in got_memory))
# `set_analysed_grid` would place Traktor's beat-1 companion on pad A. That both # `set_analysed_grid` would place Traktor's beat-1 companion on pad A. That both
# invents a cue the source never had and displaces the imported pad A cue — it # invents a cue the source never had and displaces the imported pad A cue — it
@@ -230,7 +244,9 @@ many = TrackCues(
grid_markers=[GridMarker(start=0.0, bpm=120.0)], grid_markers=[GridMarker(start=0.0, bpm=120.0)],
cues=[CuePoint(type="cue", role="hotcue", start=float(i), length=0.0, slot=i) cues=[CuePoint(type="cue", role="hotcue", start=float(i), length=0.0, slot=i)
for i in range(8)] for i in range(8)]
+ [CuePoint(type="cue", role="memory", start=99.0, length=0.0, slot=None)], + [CuePoint(type="cue", role="memory", start=99.0, length=0.0, slot=None),
# A pad past Traktor's bank: displaced, and with no spare pad left.
CuePoint(type="cue", role="hotcue", start=50.0, length=0.0, slot=9)],
) )
crowded_id = dest2.add_tracks([NewTrack( crowded_id = dest2.add_tracks([NewTrack(
track=Track(id="ignored", title="Crowded", bpm=120.0), track=Track(id="ignored", title="Crowded", bpm=120.0),
@@ -238,11 +254,15 @@ crowded_id = dest2.add_tracks([NewTrack(
cues=many, cues=many,
)])[0] )])[0]
crowded = dest2.track_cues(crowded_id) crowded = dest2.track_cues(crowded_id)
check("the bank is filled but not overflowed", len(crowded.cues) == 8, str(len(crowded.cues))) crowded_hot = [c for c in crowded.cues if c.role == "hotcue"]
check("the hot cues are the ones that survived", check("the bank is filled but not overflowed", len(crowded_hot) == 8, str(len(crowded_hot)))
sorted(c.slot for c in crowded.cues) == list(range(8))) check("the hot cues keep their own pads",
check("the memory cue that would not fit is dropped, not misplaced", sorted(c.slot for c in crowded_hot) == list(range(8))
all(c.start < 99.0 for c in crowded.cues)) and all(c.start == float(c.slot) for c in crowded_hot))
check("the memory cue stays a memory cue, and a displaced hot cue with no spare "
"pad becomes one — nothing is dropped",
sorted(round(c.start) for c in crowded.cues if c.role == "memory") == [50, 99],
str([(c.role, c.start) for c in crowded.cues]))
print("== the source slot ==") print("== the source slot ==")
# A source is a library read FROM, open alongside the loaded one. The whole slot # A source is a library read FROM, open alongside the loaded one. The whole slot
+23 -2
View File
@@ -317,8 +317,10 @@ memory = [c for c in cues.cues if c.role == "memory"]
check("the memory cue is preserved", len(memory) == 1) check("the memory cue is preserved", len(memory) == 1)
check("it has no slot", memory[0].slot is None) check("it has no slot", memory[0].slot is None)
check("it is the same loop, at the same place", abs(memory[0].start - (40.0 - OFF)) < 0.001) check("it is the same loop, at the same place", abs(memory[0].start - (40.0 - OFF)) < 0.001)
check("on an editable drive every hot cue is editable, no memory cue is", check("on an editable drive every cue is editable, memory cues included",
all(c.editable == (c.role == "hotcue") for c in cues.cues)) all(c.editable for c in cues.cues))
check("a memory cue is addressed by a content-derived id",
memory[0].id is not None and memory[0].id.startswith("m:"), str(memory[0].id))
_browse = OneLibraryAdapter(DRIVE, read_only=True) _browse = OneLibraryAdapter(DRIVE, read_only=True)
check("on a browsing drive no cue is editable", check("on a browsing drive no cue is editable",
all(not c.editable for c in _browse.track_cues(one.id).cues)) all(not c.editable for c in _browse.track_cues(one.id).cues))
@@ -436,6 +438,25 @@ check("refusing leaves nothing dirty", adapter.dirty is False)
check("an unknown track is a NotFound, not an Unsupported", check("an unknown track is a NotFound, not an Unsupported",
_raises(lambda: adapter.audio_path("no-such-track"), NotFound)) _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 ==") print("== reads that answer rather than refuse ==")
check("cover art is absent, not an error", adapter.cover_art(one.id) is None) 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 # A drive stores everything relative to its own root, so it cannot have stale
+125 -4
View File
@@ -131,8 +131,8 @@ dat = dat_of(a, TRACK_1)
ext = dat.with_suffix(".EXT") ext = dat.with_suffix(".EXT")
original = {p: p.read_bytes() for p in (dat, ext)} original = {p: p.read_bytes() for p in (dat, ext)}
cues = {c.slot: c for c in a.track_cues(TRACK_1).cues if c.role == "hotcue"} cues = {c.slot: c for c in a.track_cues(TRACK_1).cues if c.role == "hotcue"}
check("hot cues are editable, memory cues are not", check("hot cues and memory cues are editable on a drive opened for editing",
all(c.editable == (c.role == "hotcue") for c in a.track_cues(TRACK_1).cues)) all(c.editable for c in a.track_cues(TRACK_1).cues))
a.set_cue(TRACK_1, slot=5, start_sec=10.0, cue_type="cue", name="Drop") a.set_cue(TRACK_1, slot=5, start_sec=10.0, cue_type="cue", name="Drop")
a.set_cue_color(TRACK_1, 5, "#FF0045") a.set_cue_color(TRACK_1, 5, "#FF0045")
@@ -154,8 +154,8 @@ check("a pad can be deleted (pad D, which lives in the .EXT's PCOB)",
check("deleting an empty pad is NotFound", _raises(lambda: a.delete_cue(TRACK_1, 7), NotFound)) check("deleting an empty pad is NotFound", _raises(lambda: a.delete_cue(TRACK_1, 7), NotFound))
check("a pad beyond the bank is refused", check("a pad beyond the bank is refused",
_raises(lambda: a.set_cue(TRACK_1, slot=8, start_sec=1.0, cue_type="cue"), InvalidCommand)) _raises(lambda: a.set_cue(TRACK_1, slot=8, start_sec=1.0, cue_type="cue"), InvalidCommand))
check("memory cues are not editable", check("set_cue refuses role=memory (memory cues have their own commands)",
_raises(lambda: a.set_cue(TRACK_1, slot=0, start_sec=1.0, cue_type="cue", role="memory"), Unsupported)) _raises(lambda: a.set_cue(TRACK_1, slot=0, start_sec=1.0, cue_type="cue", role="memory"), InvalidCommand))
check("a colour must be one of rekordbox's swatches", check("a colour must be one of rekordbox's swatches",
_raises(lambda: a.set_cue_color(TRACK_1, 5, "#123456"), InvalidCommand)) _raises(lambda: a.set_cue_color(TRACK_1, 5, "#123456"), InvalidCommand))
a.place_cues(TRACK_1, [CuePoint(slot=1, start=30.0, length=0.0, type="cue"), a.place_cues(TRACK_1, [CuePoint(slot=1, start=30.0, length=0.0, type="cue"),
@@ -256,6 +256,127 @@ check("a 44-byte compact entry has no colour bytes to patch",
/ "nemean.EXT", "PCO2", A.LIST_MEMORY)))[-1], / "nemean.EXT", "PCO2", A.LIST_MEMORY)))[-1],
9, (1, 2, 3)) is None) 9, (1, 2, 3)) is None)
# ---- memory cues: rekordbox's own edits, byte for byte --------------------------
# `fixtures/onelibrary-memory-edits`: six memory-cue edits rekordbox 7 made on a stick
# (kit M2, 2026-10-16), one per track. Each is replayed with `memory_cues` — the
# code the store runs — on `before/`, and the memory lists must equal `after/`.
print("== memory cues: the same edit as rekordbox 7 made, the same bytes ==")
from konduktor.adapters.onelibrary import memory_cues as M # noqa: E402
from konduktor.adapters.onelibrary.cues import memory_cue_id # noqa: E402
MEMORY_EDITS = HERE / "fixtures" / "onelibrary-memory-edits"
def memory_edit(name: str):
return (A.parse_file(MEMORY_EDITS / "before" / f"{name}.DAT"),
A.parse_file(MEMORY_EDITS / "before" / f"{name}.EXT"))
def same_as_rekordbox(name: str, dat, ext) -> bool:
"""Both files equal rekordbox's, tag for tag — except that when rekordbox
rewrites a `.DAT` it also re-sorts the UNTOUCHED hot-cue `PCOB` into
ascending pad order (measured: same entries, pads 3-2-1 -> 1-2-3).
Konduktor changes only the list it edits, so that one tag must hold the
same entries in either order."""
want_dat = A.parse_file(MEMORY_EDITS / "after" / f"{name}.DAT")
want_ext = A.parse_file(MEMORY_EDITS / "after" / f"{name}.EXT")
if ext.to_bytes() != want_ext.to_bytes() or len(dat.tags) != len(want_dat.tags):
return False
for got, want in zip(dat.tags, want_dat.tags):
if (got.type, got.list_kind) == ("PCOB", A.LIST_HOT):
if sorted(A.raw_entries(got)) != sorted(A.raw_entries(want)):
return False
elif got.data != want.data:
return False
return dat.header[:8] == want_dat.header[:8] and len(dat.to_bytes()) == len(want_dat.to_bytes())
def id_at(ext, time_ms: int) -> str:
return next(memory_cue_id(A.decode_entry(e)) for e in M.entries(ext, "PCO2")
if A.decode_entry(e).time == time_ms)
dat, ext = memory_edit("black-bloc")
M.add(dat, ext, kind=1, time_ms=131206, loop_ms=None, beats=None)
check("add a memory cue: .DAT prepended + relinked, .EXT appended compact — both FILES "
"equal rekordbox's", same_as_rekordbox("black-bloc", dat, ext))
dat, ext = memory_edit("formula")
M.add(dat, ext, kind=2, time_ms=80378, loop_ms=81773, beats=4)
check("add a memory loop (4 beats): rekordbox's bytes", same_as_rekordbox("formula", dat, ext))
dat, ext = memory_edit("lift-it")
for t in (3353, 4733, 6112, 7491, 8871, 10250, 11629, 13009):
M.add(dat, ext, kind=1, time_ms=t, loop_ms=None, beats=None)
check("add eight, up to rekordbox's cap of 10: rekordbox's bytes",
same_as_rekordbox("lift-it", dat, ext) and M.count(ext) == 10)
dat, ext = memory_edit("wtf")
check("recolour Blue: only PCP2 byte 28 (= 7), rekordbox's bytes",
M.recolour(ext, id_at(ext, 113186), 7) and same_as_rekordbox("wtf", dat, ext))
dat, ext = memory_edit("sell-my-soul")
check("a comment grows the PCP2 entry by its length (88 -> 100): rekordbox's bytes",
M.rename(ext, id_at(ext, 78645), "Loopy") and same_as_rekordbox("sell-my-soul", dat, ext))
dat, ext = memory_edit("doomed")
check("delete: out of both lists, the survivor relinked: rekordbox's bytes",
M.delete(dat, ext, id_at(ext, 121402)) and same_as_rekordbox("doomed", dat, ext))
check("an unknown id finds nothing", not M.delete(dat, ext, "m:1:1:4294967295"))
print("== memory cues through the adapter, on the demo drive ==")
from konduktor.adapters.rekordbox import memory_palette # noqa: E402
drive = copy_of(DEMO, "Memo")
a = OneLibraryAdapter(drive)
dat = dat_of(a, TRACK_1)
ext = dat.with_suffix(".EXT")
original = {p: p.read_bytes() for p in (dat, ext)}
caps = a.capabilities().cues
check("capabilities: memory cues, cap 10, the 8-colour palette",
caps.memory_cues and caps.max_memory_cues == 10 and caps.memory_color == "palette"
and caps.memory_palette == memory_palette.SWATCHES)
before_mem = [c for c in a.track_cues(TRACK_1).cues if c.role == "memory"]
tc = a.add_memory_cue(TRACK_1, start_sec=12.0, cue_type="cue", name="Break",
color=memory_palette.SWATCHES[1])
new = [c for c in tc.cues if c.role == "memory" and c not in before_mem]
check("add_memory_cue: named, coloured (Red), editable, with an id",
len(new) == 1 and new[0].name == "Break" and new[0].color == memory_palette.SWATCHES[1]
and new[0].editable and new[0].id, str(new))
check("nothing reaches the drive before Save", all(p.read_bytes() == b for p, b in original.items()))
tc = a.rename_memory_cue(TRACK_1, new[0].id, "Breakdown")
tc = a.set_memory_cue_color(TRACK_1, new[0].id, None)
got = next(c for c in tc.cues if c.id == new[0].id)
check("rename and clear the colour", got.name == "Breakdown" and got.color is None, str(got))
check("a hot-cue swatch is not a memory colour",
_raises(lambda: a.set_memory_cue_color(TRACK_1, new[0].id, "#00FF30"), InvalidCommand))
check("an unknown id is NotFound",
_raises(lambda: a.delete_memory_cue(TRACK_1, "m:1:1:4294967295"), NotFound))
while sum(c.role == "memory" for c in a.track_cues(TRACK_1).cues) < 10:
n = sum(c.role == "memory" for c in a.track_cues(TRACK_1).cues)
a.add_memory_cue(TRACK_1, start_sec=100.0 + n, cue_type="cue")
check("the 11th is refused", _raises(lambda: a.add_memory_cue(TRACK_1, start_sec=1.0,
cue_type="cue"), InvalidCommand))
a.delete_memory_cue(TRACK_1, new[0].id)
check("delete removes it", all(c.id != new[0].id for c in a.track_cues(TRACK_1).cues))
hot_before = {c.slot: (c.start, c.color) for c in a.track_cues(TRACK_1).cues if c.role == "hotcue"}
a.save()
def changed_tags(path: Path) -> set:
now, was = tags_by_key(path), tags_by_key(original[path])
return {k for k in set(now) | set(was) if now.get(k) != was.get(k)}
check("Save: the .DAT changes only in its memory PCOB",
changed_tags(dat) == {("PCOB", A.LIST_MEMORY)}, str(changed_tags(dat)))
check("the .EXT only in its memory PCO2",
changed_tags(ext) == {("PCO2", A.LIST_MEMORY)}, str(changed_tags(ext)))
b = OneLibraryAdapter(drive)
check("reopened: the hot cues are untouched and 9 memory cues remain",
{c.slot: (c.start, c.color) for c in b.track_cues(TRACK_1).cues if c.role == "hotcue"}
== hot_before and sum(c.role == "memory" for c in b.track_cues(TRACK_1).cues) == 9)
b.close()
a.close()
print() print()
print("RESULT:", "FAILED" if failed else "ALL PASSED") print("RESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0) sys.exit(1 if failed else 0)
+43
View File
@@ -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"]) if r2["title"] == target.title))["key_id"]) == names["12A"])
g.close() 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()
print("RESULT:", "FAILED" if failed else "ALL PASSED") print("RESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0) sys.exit(1 if failed else 0)
+10
View File
@@ -191,6 +191,16 @@ check("'add' adds it again (Traktor can hold a track twice)", r["added"] == 1 an
r = client.post(f"/api/playlists/{target}/add", r = client.post(f"/api/playlists/{target}/add",
json={"track_ids": track_ids[4:5], "duplicates": "ask"}).json() json={"track_ids": track_ids[4:5], "duplicates": "ask"}).json()
check("'ask' with nothing duplicated simply adds", r["status"] == "added" and r["added"] == 1) check("'ask' with nothing duplicated simply adds", r["status"] == "added" and r["added"] == 1)
more = [t["id"] for t in client.get("/api/tracks", params={"limit": 50}).json()["items"]
if t["id"] not in track_ids][:2]
before = [t["id"] for t in client.get(f"/api/playlists/{target}/tracks").json()]
r = client.post(f"/api/playlists/{target}/add", json={"track_ids": more[:1], "index": 1}).json()
after = [t["id"] for t in client.get(f"/api/playlists/{target}/tracks").json()]
check("an index inserts there (a drop between rows)",
r["added"] == 1 and after == before[:1] + more[:1] + before[1:])
client.post(f"/api/playlists/{target}/add", json={"track_ids": more[1:2], "index": 999})
after = [t["id"] for t in client.get(f"/api/playlists/{target}/tracks").json()]
check("an index past the end appends", after[-1] == more[1])
check("capabilities say Traktor holds duplicates", check("capabilities say Traktor holds duplicates",
client.get("/api/capabilities").json()["playlists"]["duplicates"] is True) client.get("/api/capabilities").json()["playlists"]["duplicates"] is True)
+10 -7
View File
@@ -216,8 +216,9 @@ with tempfile.TemporaryDirectory() as d:
# writable hot cue with a padlock. # writable hot cue with a padlock.
check("ordinary hot cues are editable", check("ordinary hot cues are editable",
all(c.editable for c in tc.cues if c.role == "hotcue" and c.type != "loop")) all(c.editable for c in tc.cues if c.role == "hotcue" and c.type != "loop"))
check("memory cues are preserved but not editable", check("memory cues are editable and addressed by id",
all(not c.editable for c in tc.cues if c.role == "memory")) all(c.editable and c.id for c in tc.cues
if c.role == "memory" and c.readonly_reason is None))
check("loops are editable like any other hot cue", check("loops are editable like any other hot cue",
all(c.editable for c in tc.cues if c.type == "loop" and c.role == "hotcue")) all(c.editable for c in tc.cues if c.type == "loop" and c.role == "hotcue"))
check("an uneditable cue always says why", check("an uneditable cue always says why",
@@ -427,11 +428,10 @@ with tempfile.TemporaryDirectory() as d:
check("a Traktor-only cue type is Unsupported", check("a Traktor-only cue type is Unsupported",
_raises(lambda: adapter.set_cue(cue_track.id, slot=2, start_sec=1.0, _raises(lambda: adapter.set_cue(cue_track.id, slot=2, start_sec=1.0,
cue_type="fade_in"), Unsupported)) cue_type="fade_in"), Unsupported))
# Rekordbox is the ONLY platform with memory cues, so they stay # A memory cue has no slot; set_cue is for pads only.
# preserved-but-uneditable under the two-platform promotion rule. check("set_cue refuses role=memory (memory cues have their own commands)",
check("memory cues are shown but not writable",
_raises(lambda: adapter.set_cue(cue_track.id, slot=1, start_sec=1.0, _raises(lambda: adapter.set_cue(cue_track.id, slot=1, start_sec=1.0,
cue_type="cue", role="memory"), Unsupported)) cue_type="cue", role="memory"), InvalidCommand))
# Slot 0 is the FIRST pad, not an error: it is Kind=1 natively. # Slot 0 is the FIRST pad, not an error: it is Kind=1 natively.
tc = adapter.set_cue(cue_track.id, slot=0, start_sec=1.0, cue_type="cue") tc = adapter.set_cue(cue_track.id, slot=0, start_sec=1.0, cue_type="cue")
first = [c for c in tc.cues if c.slot == 0] first = [c for c in tc.cues if c.slot == 0]
@@ -511,7 +511,10 @@ with tempfile.TemporaryDirectory() as d:
_raises(lambda: adapter.set_cue_color(cue_track.id, 6, red), NotFound)) _raises(lambda: adapter.set_cue_color(cue_track.id, 6, red), NotFound))
print("== beatgrid edits ==") print("== beatgrid edits ==")
grid_track = next((t for t in adapter.tracks if t.bpm), None) # Long enough for a marker at 60 s: a grid is stored per beat, only up to
# the track's end, and the library's first BPM track became a 1 s Sampler
# WAV ("House 1"), where a marker at 60 s simply vanished.
grid_track = next((t for t in adapter.tracks if t.bpm and (t.length or 0) >= 90), None)
if grid_track: if grid_track:
check("a gridded track starts with at least one marker", check("a gridded track starts with at least one marker",
len(adapter.track_cues(grid_track.id).grid_markers) >= 1) len(adapter.track_cues(grid_track.id).grid_markers) >= 1)
+139
View File
@@ -97,6 +97,14 @@ def diff(before: dict, after: dict, ignore_columns=("updated_at", "created_at"))
return changes return changes
def _raises(fn, exc) -> bool:
try:
fn()
except exc:
return True
return False
def describe(changes) -> str: def describe(changes) -> str:
return "; ".join(f"{t}/{pk} {kind}" for t, pk, kind, _ in changes) or "(none)" return "; ".join(f"{t}/{pk} {kind}" for t, pk, kind, _ in changes) or "(none)"
@@ -446,6 +454,113 @@ with tempfile.TemporaryDirectory() as d:
f"{mirror_row['rb_cue_count']} vs {len(records)}") f"{mirror_row['rb_cue_count']} vs {len(records)}")
adapter.close() adapter.close()
# ---- G2: memory cues, as rekordbox 7 writes them (kit M1, 2026-10-16) ---
print("== G2: memory cues: row shapes, colour column, mirror order, the cap of 10 ==")
import json as _json
from konduktor.adapters.rekordbox import memory_palette as _mp
from konduktor.core.adapter import InvalidCommand as _Invalid
clean_copy(REAL, work, closing=[adapter])
adapter = RekordboxAdapter(work)
mem_track = next((t for t in adapter.tracks if t.bpm), adapter.tracks[0])
for c in [c for c in adapter.track_cues(mem_track.id).cues if c.role == "memory" and c.id]:
adapter.delete_memory_cue(mem_track.id, c.id)
adapter.save()
def memory_rows(snapshot):
return {pk: r for pk, r in snapshot["djmdCue"].items()
if r["ContentID"] == mem_track.id and r["Kind"] == 0}
before = dump(work)
adapter.add_memory_cue(mem_track.id, start_sec=60.0, cue_type="cue")
adapter.add_memory_cue(mem_track.id, start_sec=20.0, cue_type="loop", length_sec=2.0)
adapter.save()
changes = diff(before, dump(work))
check("adding memory cues changes only djmdCue, contentCue and the counter",
{t for t, _, _, _ in changes} == {"djmdCue", "contentCue", "agentRegistry"},
describe(changes))
after = dump(work)
rows = sorted(memory_rows(after).values(), key=lambda r: r["InMsec"])
point = next((r for r in rows if r["OutMsec"] == -1), None)
loop = next((r for r in rows if r["OutMsec"] > 0), None)
check("a memory point cue: Kind 0, Color -1, ColorTableIndex NULL, Comment NULL",
point is not None and (point["Color"], point["ColorTableIndex"], point["Comment"])
== (-1, None, None), str(point and (point["Color"], point["ColorTableIndex"], point["Comment"])))
check("a memory loop: Color 255, ColorTableIndex 0, Comment '', ActiveLoop 0, CueMicrosec 0",
loop is not None and (loop["Color"], loop["ColorTableIndex"], loop["Comment"],
loop["ActiveLoop"], loop["CueMicrosec"]) == (255, 0, "", 0, 0),
str(loop and (loop["Color"], loop["ColorTableIndex"], loop["Comment"])))
check("its BeatLoopSize is (beats << 16) | 1",
loop is not None and loop["BeatLoopSize"] and loop["BeatLoopSize"] & 0xFFFF == 1)
mirror = next(r for r in after["contentCue"].values() if r["ContentID"] == mem_track.id)
ids_in_mirror = [str(r["ID"]) for r in _json.loads(mirror["Cues"])]
live = [r for r in after["djmdCue"].values() if r["ContentID"] == mem_track.id]
check("the mirror lists cues in ROW order, as rekordbox does — the 20 s loop "
"added second comes after the 60 s cue",
ids_in_mirror.index(str(loop["ID"])) > ids_in_mirror.index(str(point["ID"])),
str(ids_in_mirror))
check("rb_cue_count counts memory cues too", mirror["rb_cue_count"] == len(live))
cues = {c.id: c for c in adapter.track_cues(mem_track.id).cues if c.role == "memory"}
point_id = str(point["ID"])
check("a memory cue projects with its row id, editable",
point_id in cues and cues[point_id].editable)
blue = _mp.SWATCHES[6]
adapter.set_memory_cue_color(mem_track.id, point_id, blue)
adapter.save()
row = memory_rows(dump(work))[point_id]
check("a colour is the 0-based code in Color (Blue = 6), ColorTableIndex NULL",
(row["Color"], row["ColorTableIndex"]) == (6, None),
str((row["Color"], row["ColorTableIndex"])))
check("and projects back as that swatch",
next(c.color for c in adapter.track_cues(mem_track.id).cues if c.id == point_id) == blue)
adapter.set_memory_cue_color(mem_track.id, point_id, None)
adapter.save()
row = memory_rows(dump(work))[point_id]
check("No Color writes 255, as rekordbox does after a colour is cleared",
(row["Color"], row["ColorTableIndex"]) == (255, None),
str((row["Color"], row["ColorTableIndex"])))
check("rekordbox memory cues have no type to choose",
_raises(lambda: adapter.set_memory_cue_type(mem_track.id, point_id, "load"), Exception))
check("a hot-cue swatch is not a memory colour",
_raises(lambda: adapter.set_memory_cue_color(mem_track.id, point_id, "#00FF30"), _Invalid))
before = dump(work)
adapter.rename_memory_cue(mem_track.id, point_id, "This is a comment")
adapter.save()
changes = diff(before, dump(work))
cue_change = [c for c in changes if c[0] == "djmdCue"]
# pyrekordbox's commit stamps the row's USN too, as on every hot-cue write
# (rekordbox's own edits leave a cue row's USN NULL; it has accepted ours).
check("a rename changes only that row's Comment (and its USN)",
len(cue_change) == 1 and set(cue_change[0][3]) <= {"Comment", "rb_local_usn"}
and "Comment" in cue_change[0][3],
str(cue_change and cue_change[0][3]))
while sum(1 for c in adapter.track_cues(mem_track.id).cues if c.role == "memory") < 10:
adapter.add_memory_cue(mem_track.id, start_sec=float(
1 + sum(1 for c in adapter.track_cues(mem_track.id).cues if c.role == "memory")),
cue_type="cue")
adapter.save()
before = dump(work)
check("the 11th memory cue is refused (rekordbox would drop it silently)",
_raises(lambda: adapter.add_memory_cue(mem_track.id, start_sec=99.0, cue_type="cue"),
_Invalid))
adapter.save()
check("and nothing changed", not diff(before, dump(work)))
before = dump(work)
adapter.delete_memory_cue(mem_track.id, point_id)
adapter.save()
after = dump(work)
changes = [c for c in diff(before, after) if c[0] == "djmdCue"]
check("a delete removes the row outright (not rb_local_deleted)",
len(changes) == 1 and changes[0][2] == "DELETE", describe(changes))
mirror = next(r for r in after["contentCue"].values() if r["ContentID"] == mem_track.id)
check("and its mirror entry",
point_id not in {str(r["ID"]) for r in _json.loads(mirror["Cues"])})
adapter.close()
# ---- H: a grid write touches ONE tag of ONE file --------------------- # ---- H: a grid write touches ONE tag of ONE file ---------------------
print("== H: a beatgrid write is localized to the .DAT's PQTZ tag ==") print("== H: a beatgrid write is localized to the .DAT's PQTZ tag ==")
from pyrekordbox.anlz import AnlzFile from pyrekordbox.anlz import AnlzFile
@@ -837,5 +952,29 @@ with tempfile.TemporaryDirectory() as d:
len(dump(work)["djmdKey"]) == len(after["djmdKey"])) len(dump(work)["djmdKey"]) == len(after["djmdKey"]))
adapter.close() 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") print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0) sys.exit(1 if failed else 0)
+9
View File
@@ -179,6 +179,15 @@ with tempfile.TemporaryDirectory() as d:
r = c.post("/api/tracks/cue", json={"track_id": target, "slot": 4, "start": 1.0, "type": "cue"}) r = c.post("/api/tracks/cue", json={"track_id": target, "slot": 4, "start": 1.0, "type": "cue"})
check("a hotcue goes to the server", r.status_code == 200 check("a hotcue goes to the server", r.status_code == 200
and any(cu["slot"] == 4 for cu in server_adapter.track_cues(target).model_dump()["cues"]), r.text[:200]) and any(cu["slot"] == 4 for cu in server_adapter.track_cues(target).model_dump()["cues"]), r.text[:200])
r = c.post("/api/tracks/memory-cue", json={"track_id": target, "start": 2.0, "type": "cue"})
mem = [cu for cu in server_adapter.track_cues(target).model_dump()["cues"] if cu["role"] == "memory"]
check("a memory cue goes to the server (protocol 1.3)", r.status_code == 200 and len(mem) == 1
and any(cu["id"] == mem[0]["id"] for cu in r.json()["cues"]), r.text[:200])
r = c.patch("/api/tracks/memory-cue", json={"track_id": target, "cue_id": mem[0]["id"],
"name": "Remote memo"})
check("…and is renamed there, by id", r.status_code == 200 and any(
cu["name"] == "Remote memo" for cu in server_adapter.track_cues(target).model_dump()["cues"]
if cu["role"] == "memory"), r.text[:200])
check("the state says unsaved", c.get("/api/state").json()["dirty"] is True) check("the state says unsaved", c.get("/api/state").json()["dirty"] is True)
versions = len(history.list_history(work)) versions = len(history.list_history(work))
r = c.post("/api/save").json() r = c.post("/api/save").json()
+10
View File
@@ -70,6 +70,16 @@ got = through_json("set_cue", {"track_id": "a", "slot": 2, "start_sec": 1.5, "cu
"length_sec": 4.0, "name": None}) "length_sec": 4.0, "name": None})
check("set_cue's arguments survive", got == {"track_id": "a", "slot": 2, "start_sec": 1.5, check("set_cue's arguments survive", got == {"track_id": "a", "slot": 2, "start_sec": 1.5,
"cue_type": "loop", "length_sec": 4.0, "name": None}, got) "cue_type": "loop", "length_sec": 4.0, "name": None}, got)
got = through_json("add_memory_cue", {"track_id": "a", "start_sec": 2.5, "cue_type": "loop",
"length_sec": 2.0, "name": "Break", "color": "#1F4EED"})
check("add_memory_cue's arguments survive",
got == {"track_id": "a", "start_sec": 2.5, "cue_type": "loop", "length_sec": 2.0,
"name": "Break", "color": "#1F4EED"}, got)
got = through_json("set_memory_cue_type", {"track_id": "a", "cue_id": "m:1", "cue_type": "load"})
check("set_memory_cue_type's arguments survive",
got == {"track_id": "a", "cue_id": "m:1", "cue_type": "load"}, got)
got = through_json("delete_memory_cue", {"track_id": "a", "cue_id": "m:1:1:4294967295"})
check("a memory cue id survives", got == {"track_id": "a", "cue_id": "m:1:1:4294967295"}, got)
got = through_json("replace_grid", {"track_id": "a", "markers": [(0.1, 128.0), (60.0, 130.0)]}) got = through_json("replace_grid", {"track_id": "a", "markers": [(0.1, 128.0), (60.0, 130.0)]})
check("a grid's (start, bpm) tuples survive", got["markers"] == [(0.1, 128.0), (60.0, 130.0)], got) check("a grid's (start, bpm) tuples survive", got["markers"] == [(0.1, 128.0), (60.0, 130.0)], got)
cue = AutoHotcue(slot=1, start=12.0, name="Drop") cue = AutoHotcue(slot=1, start=12.0, name="Drop")
+200
View File
@@ -55,6 +55,22 @@ def playlist_block_span(data: bytes, uuid: str):
return start, end return start, end
def _raises_playlist(fn) -> bool:
try:
fn()
except PlaylistError:
return True
return False
def _raises_any(fn) -> bool:
try:
fn()
except Exception:
return True
return False
def tag_lines(b: bytes) -> list[str]: def tag_lines(b: bytes) -> list[str]:
return b.replace(b"><", b">\n<").decode("utf-8", "replace").splitlines() return b.replace(b"><", b">\n<").decode("utf-8", "replace").splitlines()
@@ -1191,5 +1207,189 @@ with tempfile.TemporaryDirectory() as d:
check("O: moving a node onto its own place is not an edit", not fresh.dirty) check("O: moving a node onto its own place is not an edit", not fresh.dirty)
# ---- P: memory cues (CUE_V2 on no pad) are localized + reversible ------------
# Measured in Traktor 4.5 (2026-10-16): a memory cue is set_hotcue's element with
# HOTCUE="-1", and Traktor keeps a Konduktor-written one byte for byte. Cues are
# inserted in START order, as Traktor itself writes them.
print("\n== P. memory cues: add / rename / delete, localized, in START order ==")
from konduktor.adapters.traktor import projection as _proj # noqa: E402
with tempfile.TemporaryDirectory() as d:
work = Path(d) / "collection.nml"
shutil.copy2(REAL, work)
original = work.read_bytes()
store = TraktorStore(work)
entry = store._nml.collection.entry[0]
loc = entry.location
tid = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}"
off = store.time_offset_ms(entry)
store.add_memory_cue(tid, 42.5, 0)
store.add_memory_cue(tid, 30.0, 5, 2.0, "Intro loop")
store.save()
edited = work.read_bytes()
os_, oe = _entry_span_by_file(original, loc.file)
es_, ee = _entry_span_by_file(edited, loc.file)
check("everything outside the ENTRY is byte-identical",
original[:os_] + b"@@" + original[oe:] == edited[:es_] + b"@@" + edited[ee:])
added = [l for l in tag_lines(edited[es_:ee]) if l not in tag_lines(original[os_:oe])]
check("the ENTRY gains exactly the two memory cue lines",
len(added) == 2 and all('HOTCUE="-1"' in l and "<GRID" not in l for l in added),
str(added))
check("in Traktor's own shape (n.n., DISPL_ORDER 0, REPEATS -1, no COLOR)",
any('NAME="n.n." DISPL_ORDER="0" TYPE="0" START="' in l and 'REPEATS="-1"' in l
and "COLOR" not in l for l in added), str(added))
check("a memory loop carries its LEN and name",
any('NAME="Intro loop"' in l and 'TYPE="5"' in l and 'LEN="2000.000000"' in l
for l in added), str(added))
store = TraktorStore(work)
entry = store._nml.collection.entry[0]
starts = [c.start or 0.0 for c in entry.cue_v2]
check("cues stay sorted by START (inserted in place, not appended)",
starts == sorted(starts), str(starts))
tc = _proj.to_track_cues(entry, off)
memory = [c for c in tc.cues if c.role == "memory"]
check("both project as memory cues with ids, no slot",
len(memory) == 2 and all(c.slot is None and c.id for c in memory), str(memory))
check("the grid marker is still a grid marker, not a memory cue",
len(tc.grid_markers) == len([c for c in entry.cue_v2 if c.grid is not None]))
loop = next(c for c in memory if c.type == "loop")
store.rename_memory_cue(tid, loop.id, "Outro loop")
store.save()
renamed = work.read_bytes()
check("a rename changes one line", diff_count(edited, renamed) == 2,
str(diff_count(edited, renamed)))
store = TraktorStore(work)
entry = store._nml.collection.entry[0]
point = next(c for c in _proj.to_track_cues(entry, off).cues
if c.role == "memory" and c.type == "cue")
store.set_memory_cue_type(tid, point.id, 1)
store.save()
retyped = work.read_bytes()
check("a type change changes one line (TYPE 0 -> 1)",
diff_count(renamed, retyped) == 2 and b'TYPE="1" START=' in retyped,
str(diff_count(renamed, retyped)))
store = TraktorStore(work)
entry = store._nml.collection.entry[0]
for c in [c for c in _proj.to_track_cues(entry, off).cues if c.role == "memory"]:
store.delete_memory_cue(tid, c.id)
store.save()
check("add + delete round-trips to the original bytes", work.read_bytes() == original)
store = TraktorStore(work)
check("an unknown memory cue id is refused",
_raises_playlist(lambda: store.delete_memory_cue(tid, "m:1.000000:0:0.000000:0")))
# A new HOT cue is inserted in START order too (it used to be appended).
entry = store._nml.collection.entry[0]
store.set_hotcue(tid, next(s for s in range(8)
if s not in {c.hotcue for c in entry.cue_v2}), 0.001, 0)
starts = [c.start or 0.0 for c in entry.cue_v2]
check("a new hot cue is inserted by START too", starts == sorted(starts), str(starts))
# A pad MAPPED onto a memory cue: Traktor keeps both cues at one START and draws
# one marker; Konduktor shows it once, as the pad.
with tempfile.TemporaryDirectory() as d:
work = Path(d) / "collection.nml"
shutil.copy2(REAL, work)
store = TraktorStore(work)
entry = store._nml.collection.entry[0]
loc = entry.location
tid = f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}"
off = store.time_offset_ms(entry)
store.add_memory_cue(tid, 77.0, 0)
store.add_memory_cue(tid, 88.0, 0)
free = next(s for s in range(8) if s not in {c.hotcue for c in entry.cue_v2})
store.set_hotcue(tid, free, 77.0, 0)
tc = _proj.to_track_cues(entry, off)
check("a pad and a memory cue at one START show once, as the pad",
[round(c.start, 3) for c in tc.cues if c.role == "memory"] == [88.0]
and any(c.slot == free and round(c.start, 3) == 77.0 for c in tc.cues),
str([(c.role, c.slot, c.start) for c in tc.cues]))
check("both cues stay in the file",
sum(1 for c in entry.cue_v2 if c.grid is None and c.hotcue == -1) == 2)
print("== Q. '>' and quotes in attribute values round-trip (Traktor leaves '>' raw) ==")
# The real collection's queries hold no '>', so Traktor-written values with one
# are injected into a copy: Traktor 4.5's default "Recently added" smartlist,
# a '<' query (Traktor escapes it), and '>' / name='x' in a comment and a file
# name. All four once came back self-closed ("<X .../>"), which Traktor never
# writes, and a quoting step rewrote name='x' into a bare '"' (malformed XML).
import re as _re # noqa: E402
with tempfile.TemporaryDirectory() as d:
work = Path(d) / "collection.nml"
data = REAL.read_bytes()
queries = list(_re.finditer(rb'QUERY="[^"]*"', data))
swaps = [
(queries[0].group(0), b'QUERY="$IMPORTDATE >= MONTHS_AGO(1)"'),
(queries[1].group(0), b'QUERY="$RATING &lt; 3"'),
(_re.search(rb' COMMENT="[^"]*"', data).group(0), b" COMMENT=\"Classic > Move key='8A'\""),
(_re.search(rb' FILE="[^"]*"', data).group(0), b' FILE="Break Down > Build Up.wav"'),
]
for old, new in swaps:
data = data.replace(old, new, 1)
work.write_bytes(data)
store = TraktorStore(work)
out = store._render()
check("no-op render is byte-identical", out == data, f"{diff_count(data, out)} lines differ")
check("nothing is self-closed ('/>' — Traktor never writes it)", b"/>" not in out)
entry = store._nml.collection.entry[0]
tid = f"{entry.location.volume}{entry.location.dir}{entry.location.file}"
store.set_track_metadata(tid, {"comment": "x > y key='8A' \"z\""})
store.save()
saved = work.read_bytes()
check("an edited comment with '>' keeps </INFO>",
b"COMMENT=\"x > y key='8A' &quot;z&quot;\"" in saved and b"/>" not in saved)
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") print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0) sys.exit(1 if failed else 0)
+15 -4
View File
@@ -172,9 +172,16 @@ with TestClient(main.app) as c:
got = ROOT / "folder-1.m4a" got = ROOT / "folder-1.m4a"
got.write_bytes(r.content) got.write_bytes(r.content)
check("…and serves them", r.status_code == 200 and np.array_equal(decode(got), decode(stem, 2))) check("…and serves them", r.status_code == 200 and np.array_equal(decode(got), decode(stem, 2)))
kinds = {t["id"]: t["media_kind"] for t in listing.json()["tracks"]} # All three files are HELD, and a held file's row IS the collection track
check("the listing marks the stem file as a stem track and the MP3 as audio", # (decided 2026-10-10): its id and media_kind are the collection's, so the
kinds.get(str(stem)) == "stem" and kinds.get(str(plain)) == "audio", str(kinds)) # MP3 whose entry carries <STEMS> lists as a stem track. What the FILE says
# is checked on loose files below.
body = listing.json()
kinds = {t["id"]: t["media_kind"] for t in body["tracks"]}
check("held files list as their collection tracks, mapped back to the files",
body["files"].get(stem_id) == str(stem) and body["files"].get(tagged_id) == str(tagged), str(body["files"]))
check("…with the collection's media kind",
kinds.get(tagged_id) == "stem" and kinds.get(plain_id) == "audio", str(kinds))
print("== adding a stem file to the collection ==") print("== adding a stem file to the collection ==")
extra_dir = ROOT / "More" extra_dir = ROOT / "More"
@@ -182,7 +189,11 @@ with TestClient(main.app) as c:
extra = extra_dir / "Other.stem.m4a" extra = extra_dir / "Other.stem.m4a"
shutil.copy2(stem, extra) shutil.copy2(stem, extra)
extra_plain = make_mp3(extra_dir / "Other.mp3", seed=9) extra_plain = make_mp3(extra_dir / "Other.mp3", seed=9)
assert c.get("/api/folder/tracks", params={"path": str(extra_dir)}).status_code == 200 loose = c.get("/api/folder/tracks", params={"path": str(extra_dir)})
assert loose.status_code == 200
kinds = {t["id"]: t["media_kind"] for t in loose.json()["tracks"]}
check("a LOOSE stem file lists as a stem track (its box), the MP3 beside it as audio",
kinds.get(str(extra)) == "stem" and kinds.get(str(extra_plain)) == "audio", str(kinds))
pl_id = c.post("/api/playlists", json={"name": "Stem Adds"}).json()["id"] pl_id = c.post("/api/playlists", json={"name": "Stem Adds"}).json()["id"]
job = c.post("/api/folder/add", json={"track_ids": [str(extra), str(extra_plain)], job = c.post("/api/folder/add", json={"track_ids": [str(extra), str(extra_plain)],
"mode": "reference", "playlist_id": pl_id}).json() "mode": "reference", "playlist_id": pl_id}).json()
+77 -5
View File
@@ -22,13 +22,21 @@ REAL = Path(__file__).resolve().parents[1] / "collection.nml"
import traktor_nml_utils as tnu # noqa: E402 import traktor_nml_utils as tnu # noqa: E402
from konduktor.adapters.traktor.adapter import TraktorAdapter # noqa: E402 from konduktor.adapters.traktor.adapter import TraktorAdapter # noqa: E402
from konduktor.core.adapter import LibraryAdapter, Unsupported # noqa: E402 from konduktor.core.adapter import InvalidCommand, LibraryAdapter, NotFound, Unsupported # noqa: E402
from konduktor.core.model import AutoHotcue # noqa: E402 from konduktor.core.model import AutoHotcue # noqa: E402
from konduktor.core.pathmap import PathMapping # noqa: E402 from konduktor.core.pathmap import PathMapping # noqa: E402
failed = False failed = False
def _raises(fn, exc) -> bool:
try:
fn()
except exc:
return True
return False
def check(label, cond, detail=""): def check(label, cond, detail=""):
global failed global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else "")) print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
@@ -84,7 +92,9 @@ with tempfile.TemporaryDirectory() as d:
caps.writable is True and caps.readonly_cause is None) caps.writable is True and caps.readonly_cause is None)
check("version read from the NML header", caps.version == "20", str(caps.version)) check("version read from the NML header", caps.version == "20", str(caps.version))
check("8 hotcue slots", caps.cues.hotcue_slots == 8) check("8 hotcue slots", caps.cues.hotcue_slots == 8)
check("no memory cues on Traktor", caps.cues.memory_cues is False) check("memory cues: Traktor's cues on no pad, no limit, no colour",
caps.cues.memory_cues is True and caps.cues.max_memory_cues is None
and caps.cues.memory_color == "none")
check("loops are a cue type, not a separate bank", caps.cues.loops == "cue_type") 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. # 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("no cue colours to pick", caps.cues.color == "none" and caps.cues.palette == [])
@@ -142,15 +152,57 @@ with tempfile.TemporaryDirectory() as d:
next(c.type for c in adapter.track_cues(tid2).cues if c.slot == free) == "load") next(c.type for c in adapter.track_cues(tid2).cues if c.slot == free) == "load")
try: try:
adapter.set_cue(tid2, slot=free, start_sec=1.0, cue_type="cue", role="memory") adapter.set_cue(tid2, slot=free, start_sec=1.0, cue_type="cue", role="memory")
check("memory cues are refused on Traktor", False, "no error raised") check("set_cue refuses role=memory (memory cues have their own commands)", False,
except Unsupported: "no error raised")
check("memory cues are refused on Traktor", True) except InvalidCommand:
check("set_cue refuses role=memory (memory cues have their own commands)", True)
try: try:
adapter.set_cue_color(tid2, free, "#FF0000") adapter.set_cue_color(tid2, free, "#FF0000")
check("cue colour is refused on Traktor", False, "no error raised") check("cue colour is refused on Traktor", False, "no error raised")
except Unsupported: except Unsupported:
check("cue colour is refused on Traktor", True) check("cue colour is refused on Traktor", True)
# memory cues — Traktor's cues on no pad (HOTCUE="-1")
count_before = adapter.track(tid2).cue_count
tc = adapter.add_memory_cue(tid2, start_sec=33.0, cue_type="fade_in")
mem = [c for c in tc.cues if c.role == "memory"]
check("an unnamed cue (Traktor's \"n.n.\") projects with no name",
mem[0].name is None if mem else False, str(mem))
check("add_memory_cue returns fresh cues with the memory cue, by id",
len(mem) == 1 and mem[0].slot is None and mem[0].id and mem[0].type == "fade_in"
and abs(mem[0].start - 33.0) < 0.001, str(mem))
check("the hot cue bank is untouched (count and chips)",
adapter.track(tid2).hotcue_count == before + 1
and adapter.track(tid2).cue_count == count_before + 1)
tc = adapter.rename_memory_cue(tid2, mem[0].id, "Vocal in")
renamed = next(c for c in tc.cues if c.role == "memory")
check("rename_memory_cue names it", renamed.name == "Vocal in")
tc = adapter.set_memory_cue_type(tid2, renamed.id, "load")
renamed = next(c for c in tc.cues if c.role == "memory")
check("set_memory_cue_type changes its type, keeping position and name",
(renamed.type, renamed.name, round(renamed.start, 3)) == ("load", "Vocal in", 33.0),
str(renamed))
check("a memory loop is not retyped",
_raises(lambda: adapter.set_memory_cue_type(
tid2, next(c.id for c in adapter.add_memory_cue(
tid2, start_sec=40.0, cue_type="loop", length_sec=2.0).cues
if c.role == "memory" and c.type == "loop"), "cue"), InvalidCommand))
adapter.delete_memory_cue(tid2, next(c.id for c in adapter.track_cues(tid2).cues
if c.role == "memory" and c.type == "loop"))
check("a memory cue colour is refused (Traktor colours by type)",
_raises(lambda: adapter.set_memory_cue_color(tid2, renamed.id, "#FF0000"), Unsupported))
check("adding one with a colour is refused too",
_raises(lambda: adapter.add_memory_cue(tid2, start_sec=1.0, cue_type="cue",
color="#FF0000"), Unsupported))
tc = adapter.delete_memory_cue(tid2, renamed.id)
check("delete_memory_cue removes it", not any(c.role == "memory" for c in tc.cues))
check("an unknown id is NotFound",
_raises(lambda: adapter.delete_memory_cue(tid2, renamed.id), NotFound))
adapter.add_memory_cue(tid2, start_sec=34.0, cue_type="cue")
summary = adapter._store._journal.summary()
check("the history message names memory cues, apart from hotcues",
"memory cue" in summary, summary)
# grid # grid
grid_before = len(adapter.track_cues(tid2).grid_markers) grid_before = len(adapter.track_cues(tid2).grid_markers)
adapter.add_grid_marker(tid2, adapter.track_cues(tid2).grid_markers[0].start + 40.0) adapter.add_grid_marker(tid2, adapter.track_cues(tid2).grid_markers[0].start + 40.0)
@@ -280,5 +332,25 @@ if gridded is not None:
all(c.type != "grid" for c in cues.cues) and all(c.type != "grid" for c in cues.cues) and
gridded.cue_count == len(cues.cues)) 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") print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0) sys.exit(1 if failed else 0)
+6
View File
@@ -40,6 +40,12 @@ try {
& (Join-Path $Root "backend\build_sidecar.ps1") & (Join-Path $Root "backend\build_sidecar.ps1")
} }
# Updater packages are signed with the release key (CI's secret). Without
# it, build the installers alone rather than fail at the signing step.
if (-not $env:TAURI_SIGNING_PRIVATE_KEY) {
$TauriArgs = @("--config", "src-tauri/tauri.unsigned.conf.json") + $TauriArgs
}
Write-Host "" Write-Host ""
Write-Host "==> 2/2 Building the app (tauri build $TauriArgs)" Write-Host "==> 2/2 Building the app (tauri build $TauriArgs)"
Set-Location (Join-Path $Root "frontend") Set-Location (Join-Path $Root "frontend")
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "frontend", "name": "frontend",
"private": true, "private": true,
"version": "0.2.8", "version": "0.3.2",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
+412 -8
View File
@@ -86,6 +86,7 @@ dependencies = [
"tauri-build", "tauri-build",
"tauri-plugin-log", "tauri-plugin-log",
"tauri-plugin-shell", "tauri-plugin-shell",
"tauri-plugin-updater",
"tokio", "tokio",
] ]
@@ -465,6 +466,16 @@ dependencies = [
"version_check", "version_check",
] ]
[[package]]
name = "core-foundation"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]] [[package]]
name = "core-foundation" name = "core-foundation"
version = "0.10.1" version = "0.10.1"
@@ -488,7 +499,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97" checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97"
dependencies = [ dependencies = [
"bitflags 2.13.0", "bitflags 2.13.0",
"core-foundation", "core-foundation 0.10.1",
"core-graphics-types", "core-graphics-types",
"foreign-types", "foreign-types",
"libc", "libc",
@@ -501,7 +512,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb" checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb"
dependencies = [ dependencies = [
"bitflags 2.13.0", "bitflags 2.13.0",
"core-foundation", "core-foundation 0.10.1",
"libc", "libc",
] ]
@@ -905,6 +916,16 @@ dependencies = [
"rustc_version", "rustc_version",
] ]
[[package]]
name = "filetime"
version = "0.2.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"
dependencies = [
"cfg-if",
"libc",
]
[[package]] [[package]]
name = "find-msvc-tools" name = "find-msvc-tools"
version = "0.1.9" version = "0.1.9"
@@ -1439,6 +1460,21 @@ dependencies = [
"want", "want",
] ]
[[package]]
name = "hyper-rustls"
version = "0.27.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53"
dependencies = [
"http",
"hyper",
"hyper-util",
"rustls",
"tokio",
"tokio-rustls",
"tower-service",
]
[[package]] [[package]]
name = "hyper-util" name = "hyper-util"
version = "0.1.20" version = "0.1.20"
@@ -1457,9 +1493,11 @@ dependencies = [
"percent-encoding", "percent-encoding",
"pin-project-lite", "pin-project-lite",
"socket2", "socket2",
"system-configuration",
"tokio", "tokio",
"tower-service", "tower-service",
"tracing", "tracing",
"windows-registry",
] ]
[[package]] [[package]]
@@ -1707,6 +1745,36 @@ dependencies = [
"windows-sys 0.45.0", "windows-sys 0.45.0",
] ]
[[package]]
name = "jni"
version = "0.22.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498"
dependencies = [
"cfg-if",
"combine",
"jni-macros",
"jni-sys 0.4.1",
"log",
"simd_cesu8",
"thiserror 2.0.18",
"walkdir",
"windows-link 0.2.1",
]
[[package]]
name = "jni-macros"
version = "0.22.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3"
dependencies = [
"proc-macro2",
"quote",
"rustc_version",
"simd_cesu8",
"syn 2.0.118",
]
[[package]] [[package]]
name = "jni-sys" name = "jni-sys"
version = "0.3.1" version = "0.3.1"
@@ -1837,6 +1905,12 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]] [[package]]
name = "litemap" name = "litemap"
version = "0.8.2" version = "0.8.2"
@@ -1893,6 +1967,12 @@ version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
[[package]]
name = "minisign-verify"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22f9645cb765ea72b8111f36c522475d2daa0d22c957a9826437e97534bc4e9e"
[[package]] [[package]]
name = "miniz_oxide" name = "miniz_oxide"
version = "0.8.9" version = "0.8.9"
@@ -2134,6 +2214,7 @@ checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
dependencies = [ dependencies = [
"bitflags 2.13.0", "bitflags 2.13.0",
"block2", "block2",
"libc",
"objc2", "objc2",
"objc2-core-foundation", "objc2-core-foundation",
] ]
@@ -2149,6 +2230,18 @@ dependencies = [
"objc2-core-foundation", "objc2-core-foundation",
] ]
[[package]]
name = "objc2-osa-kit"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f112d1746737b0da274ef79a23aac283376f335f4095a083a267a082f21db0c0"
dependencies = [
"bitflags 2.13.0",
"objc2",
"objc2-app-kit",
"objc2-foundation",
]
[[package]] [[package]]
name = "objc2-quartz-core" name = "objc2-quartz-core"
version = "0.3.2" version = "0.3.2"
@@ -2223,6 +2316,12 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "openssl-probe"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
[[package]] [[package]]
name = "option-ext" name = "option-ext"
version = "0.2.0" version = "0.2.0"
@@ -2239,6 +2338,20 @@ dependencies = [
"windows-sys 0.61.2", "windows-sys 0.61.2",
] ]
[[package]]
name = "osakit"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "732c71caeaa72c065bb69d7ea08717bd3f4863a4f451402fc9513e29dbd5261b"
dependencies = [
"objc2",
"objc2-foundation",
"objc2-osa-kit",
"serde",
"serde_json",
"thiserror 2.0.18",
]
[[package]] [[package]]
name = "pango" name = "pango"
version = "0.18.3" version = "0.18.3"
@@ -2673,15 +2786,20 @@ dependencies = [
"http-body", "http-body",
"http-body-util", "http-body-util",
"hyper", "hyper",
"hyper-rustls",
"hyper-util", "hyper-util",
"js-sys", "js-sys",
"log", "log",
"percent-encoding", "percent-encoding",
"pin-project-lite", "pin-project-lite",
"rustls",
"rustls-pki-types",
"rustls-platform-verifier",
"serde", "serde",
"serde_json", "serde_json",
"sync_wrapper", "sync_wrapper",
"tokio", "tokio",
"tokio-rustls",
"tokio-util", "tokio-util",
"tower", "tower",
"tower-http", "tower-http",
@@ -2693,6 +2811,20 @@ dependencies = [
"web-sys", "web-sys",
] ]
[[package]]
name = "ring"
version = "0.17.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
dependencies = [
"cc",
"cfg-if",
"getrandom 0.2.17",
"libc",
"untrusted",
"windows-sys 0.52.0",
]
[[package]] [[package]]
name = "rkyv" name = "rkyv"
version = "0.7.46" version = "0.7.46"
@@ -2754,6 +2886,92 @@ dependencies = [
"semver", "semver",
] ]
[[package]]
name = "rustix"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"
dependencies = [
"bitflags 2.13.0",
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.61.2",
]
[[package]]
name = "rustls"
version = "0.23.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
dependencies = [
"once_cell",
"ring",
"rustls-pki-types",
"rustls-webpki",
"subtle",
"zeroize",
]
[[package]]
name = "rustls-native-certs"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4"
dependencies = [
"openssl-probe",
"rustls-pki-types",
"schannel",
"security-framework",
]
[[package]]
name = "rustls-pki-types"
version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
dependencies = [
"zeroize",
]
[[package]]
name = "rustls-platform-verifier"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98"
dependencies = [
"core-foundation 0.10.1",
"core-foundation-sys",
"jni 0.22.4",
"log",
"once_cell",
"rustls",
"rustls-native-certs",
"rustls-platform-verifier-android",
"rustls-webpki",
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.61.2",
]
[[package]]
name = "rustls-platform-verifier-android"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f"
[[package]]
name = "rustls-webpki"
version = "0.103.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
dependencies = [
"ring",
"rustls-pki-types",
"untrusted",
]
[[package]] [[package]]
name = "rustversion" name = "rustversion"
version = "1.0.22" version = "1.0.22"
@@ -2769,6 +2987,15 @@ dependencies = [
"winapi-util", "winapi-util",
] ]
[[package]]
name = "schannel"
version = "0.1.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939"
dependencies = [
"windows-sys 0.61.2",
]
[[package]] [[package]]
name = "schemars" name = "schemars"
version = "0.8.22" version = "0.8.22"
@@ -2832,6 +3059,29 @@ version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b" checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b"
[[package]]
name = "security-framework"
version = "3.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
dependencies = [
"bitflags 2.13.0",
"core-foundation 0.10.1",
"core-foundation-sys",
"libc",
"security-framework-sys",
]
[[package]]
name = "security-framework-sys"
version = "2.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]] [[package]]
name = "selectors" name = "selectors"
version = "0.36.1" version = "0.36.1"
@@ -3084,6 +3334,16 @@ version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214" checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214"
[[package]]
name = "simd_cesu8"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520"
dependencies = [
"rustc_version",
"simdutf8",
]
[[package]] [[package]]
name = "simdutf8" name = "simdutf8"
version = "0.1.5" version = "0.1.5"
@@ -3202,6 +3462,12 @@ version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]] [[package]]
name = "swift-rs" name = "swift-rs"
version = "1.0.7" version = "1.0.7"
@@ -3255,6 +3521,27 @@ dependencies = [
"syn 2.0.118", "syn 2.0.118",
] ]
[[package]]
name = "system-configuration"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b"
dependencies = [
"bitflags 2.13.0",
"core-foundation 0.9.4",
"system-configuration-sys",
]
[[package]]
name = "system-configuration-sys"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]] [[package]]
name = "system-deps" name = "system-deps"
version = "6.2.2" version = "6.2.2"
@@ -3276,7 +3563,7 @@ checksum = "d1c93047acf68669466a34690ac58cca7010bd1b201e1ec86f1fd0a75d3dd4a9"
dependencies = [ dependencies = [
"bitflags 2.13.0", "bitflags 2.13.0",
"block2", "block2",
"core-foundation", "core-foundation 0.10.1",
"core-graphics", "core-graphics",
"crossbeam-channel", "crossbeam-channel",
"dbus", "dbus",
@@ -3286,7 +3573,7 @@ dependencies = [
"gdkwayland-sys", "gdkwayland-sys",
"gdkx11-sys", "gdkx11-sys",
"gtk", "gtk",
"jni", "jni 0.21.1",
"libc", "libc",
"log", "log",
"ndk", "ndk",
@@ -3325,6 +3612,17 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
[[package]]
name = "tar"
version = "0.4.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"
dependencies = [
"filetime",
"libc",
"xattr",
]
[[package]] [[package]]
name = "target-lexicon" name = "target-lexicon"
version = "0.12.16" version = "0.12.16"
@@ -3348,7 +3646,7 @@ dependencies = [
"gtk", "gtk",
"heck 0.5.0", "heck 0.5.0",
"http", "http",
"jni", "jni 0.21.1",
"libc", "libc",
"log", "log",
"mime", "mime",
@@ -3503,6 +3801,38 @@ dependencies = [
"tokio", "tokio",
] ]
[[package]]
name = "tauri-plugin-updater"
version = "2.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a5cad8ed5948d988e1018ecd31e27cacedbf72ce3fb972940c3e4bf51639e4b"
dependencies = [
"base64 0.22.1",
"dirs",
"flate2",
"futures-util",
"http",
"infer",
"log",
"minisign-verify",
"osakit",
"percent-encoding",
"reqwest",
"rustls",
"semver",
"serde",
"serde_json",
"tar",
"tauri",
"tauri-plugin",
"tempfile",
"thiserror 2.0.18",
"time",
"tokio",
"url",
"windows-sys 0.60.2",
]
[[package]] [[package]]
name = "tauri-runtime" name = "tauri-runtime"
version = "2.11.3" version = "2.11.3"
@@ -3513,7 +3843,7 @@ dependencies = [
"dpi", "dpi",
"gtk", "gtk",
"http", "http",
"jni", "jni 0.21.1",
"objc2", "objc2",
"objc2-ui-kit", "objc2-ui-kit",
"objc2-web-kit", "objc2-web-kit",
@@ -3536,7 +3866,7 @@ checksum = "4e6fac707727b7a2f48e4ded90976324267371073edbb415ffb73bb0458d203f"
dependencies = [ dependencies = [
"gtk", "gtk",
"http", "http",
"jni", "jni 0.21.1",
"log", "log",
"objc2", "objc2",
"objc2-app-kit", "objc2-app-kit",
@@ -3603,6 +3933,19 @@ dependencies = [
"toml 1.1.2+spec-1.1.0", "toml 1.1.2+spec-1.1.0",
] ]
[[package]]
name = "tempfile"
version = "3.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.4.3",
"once_cell",
"rustix",
"windows-sys 0.61.2",
]
[[package]] [[package]]
name = "tendril" name = "tendril"
version = "0.5.0" version = "0.5.0"
@@ -3724,6 +4067,16 @@ dependencies = [
"windows-sys 0.61.2", "windows-sys 0.61.2",
] ]
[[package]]
name = "tokio-rustls"
version = "0.26.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db"
dependencies = [
"rustls",
"tokio",
]
[[package]] [[package]]
name = "tokio-util" name = "tokio-util"
version = "0.7.18" version = "0.7.18"
@@ -4014,6 +4367,12 @@ version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
[[package]]
name = "untrusted"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]] [[package]]
name = "url" name = "url"
version = "2.5.8" version = "2.5.8"
@@ -4275,6 +4634,15 @@ dependencies = [
"system-deps", "system-deps",
] ]
[[package]]
name = "webpki-root-certs"
version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b"
dependencies = [
"rustls-pki-types",
]
[[package]] [[package]]
name = "webview2-com" name = "webview2-com"
version = "0.38.2" version = "0.38.2"
@@ -4460,6 +4828,17 @@ dependencies = [
"windows-link 0.1.3", "windows-link 0.1.3",
] ]
[[package]]
name = "windows-registry"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720"
dependencies = [
"windows-link 0.2.1",
"windows-result 0.4.1",
"windows-strings 0.5.1",
]
[[package]] [[package]]
name = "windows-result" name = "windows-result"
version = "0.3.4" version = "0.3.4"
@@ -4505,6 +4884,15 @@ dependencies = [
"windows-targets 0.42.2", "windows-targets 0.42.2",
] ]
[[package]]
name = "windows-sys"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
"windows-targets 0.52.6",
]
[[package]] [[package]]
name = "windows-sys" name = "windows-sys"
version = "0.59.0" version = "0.59.0"
@@ -4800,7 +5188,7 @@ dependencies = [
"gtk", "gtk",
"http", "http",
"javascriptcore-rs", "javascriptcore-rs",
"jni", "jni 0.21.1",
"libc", "libc",
"ndk", "ndk",
"objc2", "objc2",
@@ -4856,6 +5244,16 @@ dependencies = [
"pkg-config", "pkg-config",
] ]
[[package]]
name = "xattr"
version = "1.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
dependencies = [
"libc",
"rustix",
]
[[package]] [[package]]
name = "yoke" name = "yoke"
version = "0.8.3" version = "0.8.3"
@@ -4920,6 +5318,12 @@ dependencies = [
"synstructure", "synstructure",
] ]
[[package]]
name = "zeroize"
version = "1.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
[[package]] [[package]]
name = "zerotrie" name = "zerotrie"
version = "0.2.4" version = "0.2.4"
+4
View File
@@ -28,3 +28,7 @@ tauri = { version = "2.11.3", features = [] }
tauri-plugin-log = "2" tauri-plugin-log = "2"
tauri-plugin-shell = "2" # spawn the Python backend sidecar tauri-plugin-shell = "2" # spawn the Python backend sidecar
tokio = { version = "1", features = ["time"] } # timeout on the port handshake tokio = { version = "1", features = ["time"] } # timeout on the port handshake
# One-click update (UpdateDialog.tsx). No `zip` feature: it only unpacks
# v1-style zipped Windows installers (we ship the bare NSIS setup.exe), and
# every zip 4.x it would need is yanked.
tauri-plugin-updater = { version = "2.12", default-features = false, features = ["rustls-tls", "system-proxy"] }
+241 -17
View File
@@ -26,16 +26,30 @@
// it — so it is killed only once the app really exits. If the webview does not // it — so it is killed only once the app really exits. If the webview does not
// acknowledge within ~2 s (hung, or not loaded yet), the app quits anyway: a // acknowledge within ~2 s (hung, or not loaded yet), the app quits anyway: a
// broken page must never make the app unquittable. // broken page must never make the app unquittable.
//
// UPDATING rides on that same handshake (UpdateDialog.tsx). The page finds the
// release (its own GitHub check); `update_download` fetches THAT release's
// `latest.json`, downloads + verifies the package with tauri-plugin-updater and
// STAGES it on disk; `update_restart` then asks to quit like Cmd+Q does. The
// package is installed only in `exit_now`, after the sidecar is dead: on macOS
// the sidecar lazily loads native libraries from inside the bundle being
// replaced, and on Windows its .exe in the install folder is locked while it
// runs. Cancel in the Save / Discard prompt keeps the update staged, so the
// next ordinary quit installs it (without relaunching). A failed install is
// written to `failed.json` for the next launch's dialog to report.
use std::collections::VecDeque; use std::collections::VecDeque;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Mutex; use std::sync::Mutex;
use std::time::Duration; use std::time::{Duration, Instant};
use serde::Serialize; use serde::Serialize;
use tauri::ipc::Channel;
use tauri::window::Color; use tauri::window::Color;
use tauri::{AppHandle, Emitter, Manager, RunEvent, WebviewUrl, WebviewWindowBuilder, WindowEvent}; use tauri::{AppHandle, Emitter, Manager, RunEvent, WebviewUrl, WebviewWindowBuilder, WindowEvent};
use tauri_plugin_shell::process::{CommandChild, CommandEvent}; use tauri_plugin_shell::process::{CommandChild, CommandEvent};
use tauri_plugin_shell::ShellExt; use tauri_plugin_shell::ShellExt;
use tauri_plugin_updater::{Update, UpdaterExt};
/// Holds the running sidecar child so we can terminate it on exit. /// Holds the running sidecar child so we can terminate it on exit.
struct Sidecar(Mutex<Option<CommandChild>>); struct Sidecar(Mutex<Option<CommandChild>>);
@@ -67,15 +81,105 @@ struct Quit {
acked: AtomicBool, acked: AtomicBool,
} }
/// A downloaded, verified update waiting for the app to exit.
struct StagedUpdate {
update: Update,
/// The package on disk (~150 MB: not worth holding in memory all session).
path: PathBuf,
/// Relaunch once installed: set by `update_restart`, cleared by Cancel.
relaunch: bool,
}
struct Staged(Mutex<Option<StagedUpdate>>);
/// Download progress for the update dialog.
#[derive(Clone, Serialize)]
struct UpdateProgress {
downloaded: u64,
total: Option<u64>,
}
/// An install that failed at exit, reported by the next launch.
#[derive(Serialize, serde::Deserialize)]
struct UpdateFailure {
version: String,
error: String,
}
const REPO: &str = "MrPatben8/konduktor";
/// The frozen backend's executable, in the bundled `sidecar/` folder (staged
/// into src-tauri/binaries/ by backend/build_sidecar.*).
fn sidecar_exe(app: &AppHandle) -> Result<PathBuf, String> {
let exe = if cfg!(windows) { "konduktor-sidecar.exe" } else { "konduktor-sidecar" };
let dir = app.path().resource_dir().map_err(|e| e.to_string())?;
Ok(dir.join("sidecar").join(exe))
}
fn kill_sidecar(app: &AppHandle) { fn kill_sidecar(app: &AppHandle) {
if let Some(child) = app.state::<Sidecar>().0.lock().unwrap().take() { if let Some(child) = app.state::<Sidecar>().0.lock().unwrap().take() {
let _ = child.kill(); let _ = child.kill();
} }
} }
/// Windows only: `kill` asks the OS to end the process and returns at once,
/// and the installer must not find the sidecar's .exe still locked. Opening a
/// running executable for writing is refused, so poll that (up to ~5 s).
fn wait_for_sidecar_exit(app: &AppHandle) {
if !cfg!(windows) {
return;
}
let Ok(exe) = sidecar_exe(app) else { return };
let deadline = Instant::now() + Duration::from_secs(5);
while Instant::now() < deadline {
if std::fs::OpenOptions::new().write(true).open(&exe).is_ok() {
return;
}
std::thread::sleep(Duration::from_millis(100));
}
}
fn update_dir(app: &AppHandle) -> Option<PathBuf> {
app.path().app_cache_dir().ok().map(|dir| dir.join("update"))
}
/// Install a staged update, if any. Runs at exit with the sidecar already dead.
/// On Windows a successful install never returns (the updater starts the
/// installer and exits the process); on macOS the new bundle is in place and
/// a requested relaunch starts it.
fn install_staged(app: &AppHandle) {
let Some(staged) = app.state::<Staged>().0.lock().unwrap().take() else { return };
let StagedUpdate { update, path, relaunch } = staged;
let version = update.version.clone();
wait_for_sidecar_exit(app);
// Not re-verified: `download` checked the signature before staging, and
// whoever could alter the app's cache folder could alter the app itself.
let result = std::fs::read(&path).map_err(|e| e.to_string()).and_then(|bytes| {
update.restart_after_install(relaunch).install(bytes).map_err(|e| e.to_string())
});
let _ = std::fs::remove_file(&path);
match result {
Ok(()) if relaunch => app.restart(),
Ok(()) => {}
Err(error) => {
log::error!("update to {version} failed to install: {error}");
if let Some(dir) = update_dir(app) {
let failure = UpdateFailure { version, error };
if let Ok(json) = serde_json::to_vec(&failure) {
let _ = std::fs::write(dir.join("failed.json"), json);
}
}
if relaunch {
app.restart(); // back into the version that is still installed
}
}
}
}
fn exit_now(app: &AppHandle) { fn exit_now(app: &AppHandle) {
app.state::<Quit>().allowed.store(true, Ordering::SeqCst); app.state::<Quit>().allowed.store(true, Ordering::SeqCst);
kill_sidecar(app); kill_sidecar(app);
install_staged(app);
app.exit(0); app.exit(0);
} }
@@ -121,20 +225,12 @@ fn start_backend(app: &AppHandle) {
let gen = app.state::<Backend>().generation.fetch_add(1, Ordering::SeqCst) + 1; let gen = app.state::<Backend>().generation.fetch_add(1, Ordering::SeqCst) + 1;
set_status(app, gen, BackendStatus::Starting); set_status(app, gen, BackendStatus::Starting);
// The frozen backend lives in the bundled `sidecar/` folder (staged into let spawned = sidecar_exe(app).and_then(|program| {
// src-tauri/binaries/ by backend/build_sidecar.*). app.shell()
let exe = if cfg!(windows) { "konduktor-sidecar.exe" } else { "konduktor-sidecar" }; .command(&program)
let spawned = app .spawn()
.path() .map_err(|e| format!("{}: {e}", program.display()))
.resource_dir() });
.map_err(|e| e.to_string())
.and_then(|dir| {
let program = dir.join("sidecar").join(exe);
app.shell()
.command(&program)
.spawn()
.map_err(|e| format!("{}: {e}", program.display()))
});
let (mut rx, child) = match spawned { let (mut rx, child) = match spawned {
Ok(pair) => pair, Ok(pair) => pair,
Err(e) => { Err(e) => {
@@ -220,10 +316,15 @@ fn quit_ack(app: AppHandle) {
app.state::<Quit>().acked.store(true, Ordering::SeqCst); app.state::<Quit>().acked.store(true, Ordering::SeqCst);
} }
/// The user chose Cancel: forget the request. /// The user chose Cancel: forget the request. A staged update stays staged
/// but no longer relaunches; the next ordinary quit installs it.
#[tauri::command] #[tauri::command]
fn quit_cancel(app: AppHandle) { fn quit_cancel(app: AppHandle) {
app.state::<Quit>().acked.store(false, Ordering::SeqCst); app.state::<Quit>().acked.store(false, Ordering::SeqCst);
if let Some(staged) = app.state::<Staged>().0.lock().unwrap().as_mut() {
staged.relaunch = false;
let _ = app.emit("konduktor://update-deferred", ());
}
} }
/// Quit for real (nothing unsaved, or Save / Discard has finished). /// Quit for real (nothing unsaved, or Save / Discard has finished).
@@ -232,11 +333,130 @@ fn quit_now(app: AppHandle) {
exit_now(&app); exit_now(&app);
} }
/// Refuse up front what the macOS install could not do: replace a bundle on
/// a read-only volume (run from the DMG), a translocated copy, or a folder this
/// user cannot write. (The updater's own fallback for the last asks for an
/// admin password from the main thread, which the quit path may be blocking.)
#[cfg(target_os = "macos")]
fn check_installable() -> Result<(), String> {
const MOVE_IT: &str = "Move Konduktor to your Applications folder, open it from there, then try again.";
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let bundle = tauri_plugin_updater::extract_path_from_executable(&exe).map_err(|e| e.to_string())?;
if bundle.to_string_lossy().contains("/AppTranslocation/") {
return Err(MOVE_IT.into());
}
let parent = bundle.parent().ok_or_else(|| MOVE_IT.to_string())?;
let probe = parent.join(format!(".konduktor-update-check-{}", std::process::id()));
match std::fs::File::create(&probe) {
Ok(_) => {
let _ = std::fs::remove_file(&probe);
Ok(())
}
Err(_) => Err(MOVE_IT.into()),
}
}
#[cfg(not(target_os = "macos"))]
fn check_installable() -> Result<(), String> {
Ok(())
}
/// Download the update published with release `tag`, verify it and stage it
/// for installation at exit. Returns the version staged.
#[tauri::command]
async fn update_download(
app: AppHandle,
tag: String,
on_progress: Channel<UpdateProgress>,
) -> Result<String, String> {
check_installable()?;
let manifest = format!("https://github.com/{REPO}/releases/download/{tag}/latest.json");
let url = manifest.parse().map_err(|e| format!("{manifest}: {e}"))?;
let update = app
.updater_builder()
.endpoints(vec![url])
.and_then(|b| b.build())
.map_err(|e| e.to_string())?
.check()
.await
.map_err(|e| e.to_string())?
.ok_or_else(|| format!("{tag} is not newer than this version."))?;
let mut downloaded = 0u64;
let mut last_sent = Instant::now();
let bytes = update
.download(
|chunk, total| {
downloaded += chunk as u64;
// Chunks arrive every few KB: a few updates a second is plenty.
if last_sent.elapsed() >= Duration::from_millis(100) {
last_sent = Instant::now();
let _ = on_progress.send(UpdateProgress { downloaded, total });
}
},
|| {},
)
.await
.map_err(|e| e.to_string())?;
let dir = update_dir(&app).ok_or("No cache folder to download into.")?;
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
let path = dir.join(format!("{}.pkg", update.version));
std::fs::write(&path, &bytes).map_err(|e| e.to_string())?;
drop(bytes);
let version = update.version.clone();
let previous = app
.state::<Staged>()
.0
.lock()
.unwrap()
.replace(StagedUpdate { update, path: path.clone(), relaunch: false });
if let Some(old) = previous.filter(|old| old.path != path) {
let _ = std::fs::remove_file(old.path);
}
Ok(version)
}
/// Quit, install the staged update and relaunch. Goes through the ordinary
/// quit request, so unsaved changes are asked about first.
#[tauri::command]
fn update_restart(app: AppHandle) -> Result<(), String> {
match app.state::<Staged>().0.lock().unwrap().as_mut() {
Some(staged) => staged.relaunch = true,
None => return Err("No update has been downloaded.".into()),
}
request_quit(&app);
Ok(())
}
/// The last update's install failure, if any — reported once.
#[tauri::command]
fn update_take_failure(app: AppHandle) -> Option<UpdateFailure> {
let path = update_dir(&app)?.join("failed.json");
let bytes = std::fs::read(&path).ok()?;
let _ = std::fs::remove_file(&path);
serde_json::from_slice(&bytes).ok()
}
/// Packages left by a run that never exited normally (crash, force quit).
fn clear_stale_updates(app: &AppHandle) {
let Some(dir) = update_dir(app) else { return };
let Ok(entries) = std::fs::read_dir(dir) else { return };
for entry in entries.flatten() {
if entry.path().extension().is_some_and(|ext| ext == "pkg") {
let _ = std::fs::remove_file(entry.path());
}
}
}
#[cfg_attr(mobile, tauri::mobile_entry_point)] #[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() { pub fn run() {
tauri::Builder::default() tauri::Builder::default()
.plugin(tauri_plugin_shell::init()) .plugin(tauri_plugin_shell::init())
.plugin(tauri_plugin_updater::Builder::new().build())
.manage(Sidecar(Mutex::new(None))) .manage(Sidecar(Mutex::new(None)))
.manage(Staged(Mutex::new(None)))
.manage(Backend { status: Mutex::new(BackendStatus::Starting), generation: AtomicU64::new(0) }) .manage(Backend { status: Mutex::new(BackendStatus::Starting), generation: AtomicU64::new(0) })
.manage(Quit { allowed: AtomicBool::new(false), acked: AtomicBool::new(false) }) .manage(Quit { allowed: AtomicBool::new(false), acked: AtomicBool::new(false) })
.invoke_handler(tauri::generate_handler![ .invoke_handler(tauri::generate_handler![
@@ -244,7 +464,10 @@ pub fn run() {
backend_restart, backend_restart,
quit_ack, quit_ack,
quit_cancel, quit_cancel,
quit_now quit_now,
update_download,
update_restart,
update_take_failure
]) ])
.on_window_event(|window, event| { .on_window_event(|window, event| {
if let WindowEvent::CloseRequested { api, .. } = event { if let WindowEvent::CloseRequested { api, .. } = event {
@@ -264,6 +487,7 @@ pub fn run() {
)?; )?;
} }
clear_stale_updates(app.handle());
start_backend(app.handle()); start_backend(app.handle());
WebviewWindowBuilder::new(app, "main", WebviewUrl::App("index.html".into())) WebviewWindowBuilder::new(app, "main", WebviewUrl::App("index.html".into()))
+7
View File
@@ -16,9 +16,16 @@
"csp": null "csp": null
} }
}, },
"plugins": {
"updater": {
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEZBMUE5MkIyNkJFNDNENjMKUldSalBlUnJzcElhK2dpbSsyT0kzL1huSkpOOCsxaVcwN3h6TFk3V1ZHTm9uUWtJRTAwQnQrVE0K",
"windows": { "installMode": "passive" }
}
},
"bundle": { "bundle": {
"active": true, "active": true,
"targets": "all", "targets": "all",
"createUpdaterArtifacts": true,
"icon": [ "icon": [
"icons/32x32.png", "icons/32x32.png",
"icons/128x128.png", "icons/128x128.png",
@@ -0,0 +1,4 @@
{
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"bundle": { "createUpdaterArtifacts": false }
}
+77 -7
View File
@@ -6,7 +6,7 @@ import { CapabilitiesContext, slotLabeller } from './lib/capabilities'
import { readOnlyNotice, removalNote, writeHint } from './lib/platformCopy' import { readOnlyNotice, removalNote, writeHint } from './lib/platformCopy'
import { invalidateTrackLists } from './lib/trackQueries' import { invalidateTrackLists } from './lib/trackQueries'
import { addTracksToPlaylist } from './lib/addTracks' import { addTracksToPlaylist } from './lib/addTracks'
import { useDragPayload, useDropTarget } from './lib/drag' import { isForeign, useDragPayload, useDropTarget, type TracksOrFiles } from './lib/drag'
import { useNativeFileDrop } from './lib/fileDrop' import { useNativeFileDrop } from './lib/fileDrop'
import { api, type AnalyzeOptions, type AnalyzeResult, type CueBatchResult, type AutoCueSlot, type PlaylistNode, type StemBatchResult, type Track, type TrackOrigin } from './api' import { api, type AnalyzeOptions, type AnalyzeResult, type CueBatchResult, type AutoCueSlot, type PlaylistNode, type StemBatchResult, type Track, type TrackOrigin } from './api'
import { confirmDiscardUnsaved } from './lib/unsaved' import { confirmDiscardUnsaved } from './lib/unsaved'
@@ -226,6 +226,21 @@ export default function App() {
[qc, notify, onError, writeHintText], [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 // 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; // gated with `enabled: loaded` so they don't fire before a collection is open;
@@ -368,10 +383,10 @@ export default function App() {
// menu and the drag ask about duplicates alike. // menu and the drag ask about duplicates alike.
const duplicatesAllowed = !!capabilities.data?.playlists.duplicates const duplicatesAllowed = !!capabilities.data?.playlists.duplicates
const addToPlaylist = useCallback( const addToPlaylist = useCallback(
async (uuid: string, ids: string[]) => { async (uuid: string, ids: string[], index: number | null = null) => {
try { try {
const name = addablePlaylists.find((p) => p.id === uuid)?.name ?? 'playlist' const name = addablePlaylists.find((p) => p.id === uuid)?.name ?? 'playlist'
const msg = await addTracksToPlaylist({ qc, playlist: { id: uuid, name }, ids, duplicatesAllowed }) const msg = await addTracksToPlaylist({ qc, playlist: { id: uuid, name }, ids, duplicatesAllowed, index })
if (msg) notify('success', msg) if (msg) notify('success', msg)
} catch (e) { } catch (e) {
onError((e as Error).message) onError((e as Error).message)
@@ -424,7 +439,7 @@ export default function App() {
// rows, nothing to add first — straight into the target, if there is one. // rows, nothing to add first — straight into the target, if there is one.
const held = r.tracks.filter((t) => r.files[t.id]).map((t) => t.id) const held = r.tracks.filter((t) => r.files[t.id]).map((t) => t.id)
if (held.length === r.tracks.length) { if (held.length === r.tracks.length) {
if (target?.kind === 'playlist') void addToPlaylist(target.id, held) if (target?.kind === 'playlist') void addToPlaylist(target.id, held, target.index)
else if (target) void addToExport(target.id, held) else if (target) void addToExport(target.id, held)
else else
notify( notify(
@@ -458,7 +473,7 @@ export default function App() {
const files = folderFilesRef.current const files = folderFilesRef.current
// Rows that are all collection tracks already: nothing to add first. // Rows that are all collection tracks already: nothing to add first.
if (ids.every((id) => files[id])) { if (ids.every((id) => files[id])) {
if (target.kind === 'playlist') void addToPlaylist(target.id, ids) if (target.kind === 'playlist') void addToPlaylist(target.id, ids, target.index)
else void addToExport(target.id, ids) else void addToExport(target.id, ids)
} else setAdding({ ids: ids.map((id) => files[id] ?? id), target }) } else setAdding({ ids: ids.map((id) => files[id] ?? id), target })
} else if (origin === 'device') setImportDrop({ ids, target }) } else if (origin === 'device') setImportDrop({ ids, target })
@@ -651,6 +666,31 @@ export default function App() {
return find(playlists.data ?? []) return find(playlists.data ?? [])
}, [source, playlists.data]) }, [source, playlists.data])
const playlistEditable = canEdit && !!playlistNode?.can_reorder const playlistEditable = canEdit && !!playlistNode?.can_reorder
// Files, a Files folder's rows or a device's dropped on the open playlist's
// table: added to the collection and — unless the dialog's tick is cleared —
// into this playlist at the insertion line (decided 2026-10-17). A library
// that cannot add tracks leaves the drop to App's root target, which says why.
const playlistDrop = useMemo(() => {
if (!playlistEditable || !canAddFiles || source.kind !== 'playlist' || !playlistNode?.can_add_tracks) return undefined
const { id, name } = playlistNode
return {
label: `Add to ${name}…`,
onDrop: (p: TracksOrFiles, index: number | null) => {
const target: AddTarget = { kind: 'playlist', id, name, index }
if (p.kind === 'files') void dropFiles(p.paths, target)
else if (p.origin === 'folder' || p.origin === 'device') addForeign(p.origin, p.ids, target)
},
}
}, [playlistEditable, canAddFiles, source, playlistNode, dropFiles, addForeign])
// The same where no table is drawn: an empty playlist, or filters hiding
// every row (never both at once, so they share the one target).
const [emptyDropRef, emptyDropOver] = useDropTarget<true>({
hint: (p) => (playlistDrop && isForeign(p) ? true : null),
label: () => playlistDrop?.label ?? null,
onDrop: (p) => {
if (isForeign(p)) playlistDrop?.onDrop(p, null)
},
})
// A playlist's own 1-based positions, so the # column still means "where in // A playlist's own 1-based positions, so the # column still means "where in
// the playlist" once the view is sorted or filtered. // the playlist" once the view is sorted or filtered.
const playlistPositions = useMemo(() => { const playlistPositions = useMemo(() => {
@@ -1214,6 +1254,25 @@ export default function App() {
...(canEdit && !viewingDevice && menu.ids.length === 1 ...(canEdit && !viewingDevice && menu.ids.length === 1
? [{ label: 'Edit Tags…', onClick: gated(() => setEditing(menu.track)) }] ? [{ 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 ...(canAnalyze
? [ ? [
{ {
@@ -1729,14 +1788,24 @@ export default function App() {
/> />
) )
) : tracks.length === 0 ? ( ) : tracks.length === 0 ? (
<div className="flex h-full flex-col items-center justify-center gap-2 text-muted"> <div
ref={emptyDropRef}
className={`flex h-full flex-col items-center justify-center gap-2 text-muted ${
emptyDropOver ? 'rounded-lg outline-2 -outline-offset-2 outline-accent' : ''
}`}
>
<div className="text-lg">This playlist is empty</div> <div className="text-lg">This playlist is empty</div>
<div className="text-sm text-faint"> <div className="text-sm text-faint">
Go to <span className="text-text">All Tracks</span>, select tracks, and add them here. Go to <span className="text-text">All Tracks</span>, select tracks, and add them here.
</div> </div>
</div> </div>
) : filtered.length === 0 ? ( ) : filtered.length === 0 ? (
<div className="flex h-full flex-col items-center justify-center gap-1 text-muted"> <div
ref={emptyDropRef}
className={`flex h-full flex-col items-center justify-center gap-1 text-muted ${
emptyDropOver ? 'rounded-lg outline-2 -outline-offset-2 outline-accent' : ''
}`}
>
<div className="text-lg">No tracks match</div> <div className="text-lg">No tracks match</div>
<div className="text-sm text-faint">Try clearing some filters.</div> <div className="text-sm text-faint">Try clearing some filters.</div>
</div> </div>
@@ -1753,6 +1822,7 @@ export default function App() {
: undefined : undefined
} }
onRemove={playlistEditable ? confirmRemoveFromPlaylist : undefined} onRemove={playlistEditable ? confirmRemoveFromPlaylist : undefined}
foreignDrop={playlistDrop}
dragFrom={{ dragFrom={{
origin: 'collection', origin: 'collection',
playlistId: playlistEditable && source.kind === 'playlist' ? source.id : undefined, playlistId: playlistEditable && source.kind === 'playlist' ? source.id : undefined,
+59 -4
View File
@@ -39,6 +39,10 @@ export interface Track {
grid_marker_count: number grid_marker_count: number
grid_locked: boolean grid_locked: boolean
media_kind: MediaKind 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. */ /** 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 CueRole = 'hotcue' | 'memory'
export type CueType = 'cue' | 'fade_in' | 'fade_out' | 'load' | 'loop' export type CueType = 'cue' | 'fade_in' | 'fade_out' | 'load' | 'loop'
export type MediaKind = 'audio' | 'stem' | 'video' 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 PlaylistKind = 'folder' | 'playlist' | 'smart'
export type TrackField = export type TrackField =
| 'title' | 'artist' | 'album' | 'genre' | 'label' | 'remixer' | 'title' | 'artist' | 'album' | 'genre' | 'label' | 'remixer'
@@ -125,8 +138,8 @@ export type TrackField =
export interface CuePoint { export interface CuePoint {
name: string | null name: string | null
type: CueType type: CueType
/** Memory cues have no bank slot. Only Rekordbox has them, so they are /** A memory cue has no bank slot (Rekordbox / OneLibrary memory cues,
* preserved and shown but not editable anywhere yet. */ * Traktor's cues on no pad) and is addressed by `id`, not `slot`. */
role: CueRole role: CueRole
start: number // seconds start: number // seconds
length: number // seconds (>0 for loops) length: number // seconds (>0 for loops)
@@ -139,6 +152,10 @@ export interface CuePoint {
/** Index of the grid marker this cue mirrors, where the platform pairs them. /** Index of the grid marker this cue mirrors, where the platform pairs them.
* A display hint only; null on platforms that do not. */ * A display hint only; null on platforms that do not. */
grid_marker: number | null grid_marker: number | null
/** The handle the memory-cue commands take; null on a hot cue (addressed by
* slot). Opaque, and may change when THIS cue is edited — always use the
* fresh TrackCues a command returns. */
id: string | null
} }
/** One beatgrid marker. Its position in the list IS its index/identity. */ /** One beatgrid marker. Its position in the list IS its index/identity. */
@@ -208,7 +225,11 @@ export interface CueCapabilities {
hotcue_slots: number hotcue_slots: number
slot_labels: 'number' | 'letter' slot_labels: 'number' | 'letter'
memory_cues: boolean memory_cues: boolean
/** Per track; null = no limit. rekordbox stops at 10 without saying so. */
max_memory_cues: number | null max_memory_cues: number | null
/** A memory cue's colours are its own palette, not `palette`. */
memory_color: 'none' | 'palette'
memory_palette: string[]
types: CueType[] types: CueType[]
color: 'none' | 'free' | 'palette' color: 'none' | 'free' | 'palette'
palette: string[] palette: string[]
@@ -271,6 +292,8 @@ export interface Capabilities {
audio_destination: 'host' | 'library' audio_destination: 'host' | 'library'
/** Added files can be left where they are rather than copied. */ /** Added files can be left where they are rather than copied. */
reference: boolean reference: boolean
/** The track colours this library can store; empty = no track colour. */
colors: ColorSwatch[]
} }
playlists: { playlists: {
folders: boolean folders: boolean
@@ -444,6 +467,8 @@ export interface ImportRequest {
/** Every imported track (and any already held) also goes into this /** Every imported track (and any already held) also goes into this
* collection playlist / export — a drop of device tracks on one. */ * collection playlist / export — a drop of device tracks on one. */
into_playlist?: string | null into_playlist?: string | null
/** Where in it (a drop between rows); null appends. */
into_playlist_index?: number | null
export_id?: string | null export_id?: string | null
} }
@@ -510,6 +535,8 @@ export interface FolderAddRequest {
/** Required for `copy`. */ /** Required for `copy`. */
destination?: string | null destination?: string | null
playlist_id?: string | null playlist_id?: string | null
/** Where in it (a drop between rows); null appends. */
playlist_index?: number | null
export_id?: string | null export_id?: string | null
} }
@@ -1035,11 +1062,12 @@ export const api = {
/** Append tracks. `duplicates` decides tracks already there: skip them, /** Append tracks. `duplicates` decides tracks already there: skip them,
* add them again (where `playlists.duplicates`), or `ask` — nothing changes * add them again (where `playlists.duplicates`), or `ask` — nothing changes
* and the answer's `status: 'duplicates'` says how many, to ask and resend. */ * and the answer's `status: 'duplicates'` says how many, to ask and resend. */
addEntries: (nodeId: string, trackIds: string[], duplicates: 'skip' | 'add' | 'ask' = 'skip') => /** `index`: insert at this position among the current entries; null appends. */
addEntries: (nodeId: string, trackIds: string[], duplicates: 'skip' | 'add' | 'ask' = 'skip', index: number | null = null) =>
send<{ status: 'added' | 'duplicates'; added: number; duplicates: number; count: number }>( send<{ status: 'added' | 'duplicates'; added: number; duplicates: number; count: number }>(
'POST', 'POST',
`/api/playlists/${encodeURIComponent(nodeId)}/add`, `/api/playlists/${encodeURIComponent(nodeId)}/add`,
{ track_ids: trackIds, duplicates }, { track_ids: trackIds, duplicates, index },
), ),
/** Move a tree node to `index` among `parentId`'s children (null = top /** Move a tree node to `index` among `parentId`'s children (null = top
* level), counted without it. Answers its id AFTER the move. */ * level), counted without it. Answers its id AFTER the move. */
@@ -1064,6 +1092,11 @@ export const api = {
editTrack: (trackId: string, fields: Record<string, string | number | null>) => editTrack: (trackId: string, fields: Record<string, string | number | null>) =>
send<{ status: string }>('PATCH', '/api/tracks', { track_id: trackId, fields }), 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) => artUrl: (trackId: string) =>
`${API_BASE}/api/tracks/art?track_id=${encodeURIComponent(trackId)}`, `${API_BASE}/api/tracks/art?track_id=${encodeURIComponent(trackId)}`,
audioUrl: (trackId: string) => audioUrl: (trackId: string) =>
@@ -1141,6 +1174,28 @@ export const api = {
'DELETE', 'DELETE',
`/api/tracks/cue?track_id=${encodeURIComponent(trackId)}&slot=${slot}`, `/api/tracks/cue?track_id=${encodeURIComponent(trackId)}&slot=${slot}`,
), ),
/** A memory cue (a memory loop when `length` > 0). Refused past
* `capabilities.cues.max_memory_cues`. */
addMemoryCue: (trackId: string, start: number, type: CueType, length = 0) =>
send<TrackCues>('POST', '/api/tracks/memory-cue', { track_id: trackId, start, type, length }),
/** `cueId` is `CuePoint.id`; null / '' clears the name. */
renameMemoryCue: (trackId: string, cueId: string, name: string | null) =>
send<TrackCues>('PATCH', '/api/tracks/memory-cue', { track_id: trackId, cue_id: cueId, name }),
/** A point type from `capabilities.cues.types`; a memory loop is not retyped. */
setMemoryCueType: (trackId: string, cueId: string, type: CueType) =>
send<TrackCues>('PATCH', '/api/tracks/memory-cue/type', { track_id: trackId, cue_id: cueId, type }),
/** From `capabilities.cues.memory_palette`; null = uncoloured. */
setMemoryCueColor: (trackId: string, cueId: string, color: string | null) =>
send<TrackCues>('PATCH', '/api/tracks/memory-cue/color', {
track_id: trackId,
cue_id: cueId,
color,
}),
deleteMemoryCue: (trackId: string, cueId: string) =>
send<TrackCues>(
'DELETE',
`/api/tracks/memory-cue?track_id=${encodeURIComponent(trackId)}&cue_id=${encodeURIComponent(cueId)}`,
),
/** Retempo and/or move one marker. `index` is its position in grid_markers; /** Retempo and/or move one marker. `index` is its position in grid_markers;
* a move is clamped between its neighbours rather than reordering them. */ * a move is clamped between its neighbours rather than reordering them. */
setGridMarker: (trackId: string, index: number, patch: { bpm?: number; start?: number }) => setGridMarker: (trackId: string, index: number, patch: { bpm?: number; start?: number }) =>
+27 -2
View File
@@ -32,7 +32,10 @@ import { FolderPicker } from './FolderPicker'
* A playlist or export target still needs the files in the collection first — * A playlist or export target still needs the files in the collection first —
* both hold collection track ids — so the dialog says so rather than doing it * both hold collection track ids — so the dialog says so rather than doing it
* silently. Files the collection already holds are not added again, but still * silently. Files the collection already holds are not added again, but still
* go into the target. * go into the target. A PLAYLIST target can be unticked (`usePlaylistToggle`,
* on each time, never remembered — decided 2026-10-17): a drop on a playlist
* is usually meant for it, but a drop on its open table may only be "into
* the collection" aimed loosely.
*/ */
const POLL_MS = 300 const POLL_MS = 300
@@ -47,6 +50,25 @@ export interface AddTarget {
kind: 'playlist' | 'export' kind: 'playlist' | 'export'
id: string id: string
name: string name: string
/** A playlist: insert at this position among its entries (a drop between
* its rows); absent appends. */
index?: number | null
}
/** The add dialogs' "Also add to <playlist>" tick: on, unless unticked this
* time. Answers the target actually in force (null = the collection only).
* Exports have no tick — "Add to export" is the whole of that gesture. */
export function usePlaylistToggle(requested: AddTarget | null | undefined) {
const [on, setOn] = useState(true)
const offered = requested?.kind === 'playlist'
const target = offered && !on ? null : (requested ?? null)
const toggle = offered ? (
<label className="flex cursor-pointer items-center gap-2 text-xs text-muted">
<input type="checkbox" checked={on} onChange={(e) => setOn(e.target.checked)} className="accent-accent" />
Also add to “{requested.name}”
</label>
) : null
return { target, toggle }
} }
/** Where tracks headed for the collection come from: another library's or a /** Where tracks headed for the collection come from: another library's or a
@@ -74,8 +96,9 @@ function removableWarning(p: FolderAddPreview, newCount: number): string {
return `${what} on ${where}. They will go missing from your collection whenever ${unplugged} unplugged.` return `${what} on ${where}. They will go missing from your collection whenever ${unplugged} unplugged.`
} }
export function AddFilesDialog({ trackIds, target, note, onClose, onDone, onError }: Props) { export function AddFilesDialog({ trackIds, target: requested, note, onClose, onDone, onError }: Props) {
const qc = useQueryClient() const qc = useQueryClient()
const { target, toggle } = usePlaylistToggle(requested)
// The LIBRARY's capabilities (this dialog is mounted outside the browsed // The LIBRARY's capabilities (this dialog is mounted outside the browsed
// view's swapped context). A library that places its own audio — a stick — // view's swapped context). A library that places its own audio — a stick —
// decides copy vs in place itself, so there is nothing to ask. // decides copy vs in place itself, so there is nothing to ask.
@@ -115,6 +138,7 @@ export function AddFilesDialog({ trackIds, target, note, onClose, onDone, onErro
mode: places ? 'copy' : (mode ?? 'reference'), mode: places ? 'copy' : (mode ?? 'reference'),
destination: !places && mode === 'copy' ? folder : null, destination: !places && mode === 'copy' ? folder : null,
playlist_id: target?.kind === 'playlist' ? target.id : null, playlist_id: target?.kind === 'playlist' ? target.id : null,
playlist_index: target?.kind === 'playlist' ? (target.index ?? null) : null,
export_id: target?.kind === 'export' ? target.id : null, export_id: target?.kind === 'export' ? target.id : null,
} }
@@ -255,6 +279,7 @@ export function AddFilesDialog({ trackIds, target, note, onClose, onDone, onErro
<div className="space-y-4 px-5 py-4 text-sm"> <div className="space-y-4 px-5 py-4 text-sm">
{!job && ( {!job && (
<> <>
{toggle}
{target && ( {target && (
<div className="text-xs text-muted"> <div className="text-xs text-muted">
{target.kind === 'playlist' ? 'Playlists' : 'Exports'} hold tracks from your {target.kind === 'playlist' ? 'Playlists' : 'Exports'} hold tracks from your
+8 -4
View File
@@ -19,6 +19,10 @@ export type MenuItem =
selected: string | null selected: string | null
onPick: (color: string | null) => void onPick: (color: string | null) => void
disabled?: boolean 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 } | { separator: true }
@@ -259,13 +263,13 @@ function SwatchGrid({
return ( return (
<div className="px-3 pb-2 pt-1" onMouseEnter={onEnter}> <div className="px-3 pb-2 pt-1" onMouseEnter={onEnter}>
<div className="grid w-max grid-cols-8 gap-1.5"> <div className="grid w-max grid-cols-8 gap-1.5">
{item.swatches.map((color) => ( {item.swatches.map((color, i) => (
<button <button
key={color} key={color}
role="menuitemradio" role="menuitemradio"
aria-checked={selected === color.toUpperCase()} aria-checked={selected === color.toUpperCase()}
aria-label={color} aria-label={item.labels?.[i] ?? color}
title={color} title={item.labels?.[i] ?? color}
disabled={item.disabled} disabled={item.disabled}
onClick={() => pick(color)} onClick={() => pick(color)}
className={`h-4 w-4 rounded-full transition-transform disabled:cursor-default disabled:opacity-40 ${ring( 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' : '' selected === null ? 'outline outline-2 outline-offset-1 outline-white' : ''
}`} }`}
/> />
Default {item.noneLabel ?? 'Default'}
</button> </button>
</div> </div>
) )
+4 -42
View File
@@ -1,7 +1,8 @@
import { useRef, useState, type CSSProperties } from 'react' import type { CSSProperties } from 'react'
import type { CuePoint } from '../api' import type { CuePoint } from '../api'
import { CUE_TYPE_LABELS, cueColor, cueIcon, withAlpha } from '../lib/cues' import { CUE_TYPE_LABELS, cueColor, cueIcon, withAlpha } from '../lib/cues'
import { Icon } from '../lib/icons' import { Icon } from '../lib/icons'
import { RenameField } from './RenameField'
interface Props { interface Props {
cues: CuePoint[] cues: CuePoint[]
@@ -155,7 +156,7 @@ export function HotcueBar({
* backlit controller pad reads. Selection brightens the tint and rings it in * backlit controller pad reads. Selection brightens the tint and rings it in
* the colour itself, so it stays legible whichever colour the cue is. * the colour itself, so it stays legible whichever colour the cue is.
*/ */
function padStyle(color: string, selected: boolean): CSSProperties { export function padStyle(color: string, selected: boolean): CSSProperties {
return { return {
// The cue colour sits on a DARK GROUND (the last layer), not on bare glass: // The cue colour sits on a DARK GROUND (the last layer), not on bare glass:
// over a bright or warm ambient wash a thin tint alone came out the same hue // over a bright or warm ambient wash a thin tint alone came out the same hue
@@ -178,47 +179,8 @@ function padStyle(color: string, selected: boolean): CSSProperties {
/** A cue colour lifted toward white, for the pad's number: the raw colour is /** A cue colour lifted toward white, for the pad's number: the raw colour is
* too dark to read as text on its own tint (blue especially). */ * too dark to read as text on its own tint (blue especially). */
function lighten(hex: string, amount = 0.35): string { export function lighten(hex: string, amount = 0.35): string {
const v = parseInt(hex.slice(1, 7), 16) const v = parseInt(hex.slice(1, 7), 16)
const mix = (c: number) => Math.round(c + (255 - c) * amount) const mix = (c: number) => Math.round(c + (255 - c) * amount)
return `rgb(${mix(v >> 16)},${mix((v >> 8) & 255)},${mix(v & 255)})` return `rgb(${mix(v >> 16)},${mix((v >> 8) & 255)},${mix(v & 255)})`
} }
/** The pad's name, edited in place. Enter or clicking away commits; Esc cancels. */
function RenameField({
initial,
onCommit,
onCancel,
}: {
initial: string
onCommit: (name: string) => void
onCancel: () => void
}) {
const [val, setVal] = useState(initial)
// Enter commits and unmounts the field, which can fire a trailing blur.
const done = useRef(false)
const finish = (commit: boolean) => {
if (done.current) return
done.current = true
if (commit && val.trim() !== initial) onCommit(val.trim())
else onCancel()
}
return (
<input
autoFocus
value={val}
onChange={(e) => setVal(e.target.value)}
onFocus={(e) => e.currentTarget.select()}
onBlur={() => finish(true)}
// The pad is a button: keep its press/preview handlers out of the field.
onPointerDown={(e) => e.stopPropagation()}
onPointerUp={(e) => e.stopPropagation()}
onKeyDown={(e) => {
e.stopPropagation() // digits and Space must type, not trigger the deck
if (e.key === 'Enter') finish(true)
else if (e.key === 'Escape') finish(false)
}}
className="w-full min-w-0 rounded bg-well px-1 text-[11px] leading-4 text-text outline-none ring-1 ring-accent"
/>
)
}
+5 -2
View File
@@ -6,7 +6,7 @@ import { useCaps } from '../lib/capabilities'
import { placedAudioSummary } from '../lib/platformCopy' import { placedAudioSummary } from '../lib/platformCopy'
import type { AddTarget } from './AddFilesDialog' import type { AddTarget } from './AddFilesDialog'
import { FolderPicker } from './FolderPicker' import { FolderPicker } from './FolderPicker'
import { useServerImportFolder } from './AddFilesDialog' import { useServerImportFolder, usePlaylistToggle } from './AddFilesDialog'
/** /**
* Import a browsed device into the loaded collection. * Import a browsed device into the loaded collection.
@@ -41,8 +41,9 @@ interface Props {
onError: (msg: string) => void onError: (msg: string) => void
} }
export function ImportDialog({ playlistId, trackIds, target, deviceLabel, onClose, onDone, onError }: Props) { export function ImportDialog({ playlistId, trackIds, target: requested, deviceLabel, onClose, onDone, onError }: Props) {
const qc = useQueryClient() const qc = useQueryClient()
const { target, toggle } = usePlaylistToggle(requested)
// The BASE folder, and whether to put this device's audio in its own // The BASE folder, and whether to put this device's audio in its own
// subfolder of it. Kept apart rather than as one path because they are two // subfolder of it. Kept apart rather than as one path because they are two
// different decisions: where your music lives, and how one import is filed // different decisions: where your music lives, and how one import is filed
@@ -91,6 +92,7 @@ export function ImportDialog({ playlistId, trackIds, target, deviceLabel, onClos
track_ids: trackIds ?? [], track_ids: trackIds ?? [],
folder_name: deviceLabel, folder_name: deviceLabel,
into_playlist: target?.kind === 'playlist' ? target.id : null, into_playlist: target?.kind === 'playlist' ? target.id : null,
into_playlist_index: target?.kind === 'playlist' ? (target.index ?? null) : null,
export_id: target?.kind === 'export' ? target.id : null, export_id: target?.kind === 'export' ? target.id : null,
} }
@@ -203,6 +205,7 @@ export function ImportDialog({ playlistId, trackIds, target, deviceLabel, onClos
<div className="space-y-4 px-5 py-4 text-sm"> <div className="space-y-4 px-5 py-4 text-sm">
{!job && ( {!job && (
<> <>
{toggle}
{places && p && ( {places && p && (
<div className="rounded well px-3 py-2 text-xs text-muted"> <div className="rounded well px-3 py-2 text-xs text-muted">
{placedAudioSummary(caps.save, p.copied ?? 0, p.in_place ?? 0)} {placedAudioSummary(caps.save, p.copied ?? 0, p.in_place ?? 0)}
+10 -17
View File
@@ -1,4 +1,5 @@
import { Icon } from '../lib/icons' import { Icon } from '../lib/icons'
import { ModeSwitch } from './ModeSwitch'
/** One size, 1/32 → 32 beats, shared by beat loops AND beat jump: the number a /** One size, 1/32 → 32 beats, shared by beat loops AND beat jump: the number a
* DJ has in their head ("4 beats") should not differ between the two. */ * DJ has in their head ("4 beats") should not differ between the two. */
@@ -90,25 +91,17 @@ export function LoopControls({
// A beat jump needs a grid; moving a manual loop does not. // A beat jump needs a grid; moving a manual loop does not.
const canMove = ready && (loopActive || hasGrid) const canMove = ready && (loopActive || hasGrid)
const tab = (m: LoopMode, text: string, title: string) => (
<button
onClick={() => onMode(m)}
title={title}
aria-pressed={mode === m}
className={`h-[17px] rounded-[7px] px-[7px] text-[9px] font-bold tracking-[0.08em] transition-colors ${
mode === m ? 'btn-primary' : 'text-faint hover:text-text'
}`}
>
{text}
</button>
)
return ( return (
<div className="flex shrink-0 items-center gap-2"> <div className="flex shrink-0 items-center gap-2">
<div role="group" aria-label="Loop mode" className="well flex h-10 flex-col justify-center gap-0.5 rounded-[10px] p-0.5"> <ModeSwitch
{tab('beat', 'BEAT', 'Beat loops, sized in beats')} label="Loop mode"
{tab('manual', 'MAN', 'Manual loops: set IN and OUT')} value={mode}
</div> onChange={onMode}
options={[
{ value: 'beat', text: 'BEAT', title: 'Beat loops, sized in beats' },
{ value: 'manual', text: 'MAN', title: 'Manual loops: set IN and OUT' },
]}
/>
{mode === 'beat' ? ( {mode === 'beat' ? (
<div role="group" aria-label="Loop size" className={`${CLUSTER} font-mono`}> <div role="group" aria-label="Loop size" className={`${CLUSTER} font-mono`}>
+132
View File
@@ -0,0 +1,132 @@
import type { CuePoint } from '../api'
import { cueColor, cueIcon } from '../lib/cues'
import { Icon } from '../lib/icons'
import { lighten, padStyle } from './HotcueBar'
import { RenameField } from './RenameField'
interface Props {
/** The track's cues; only the memory cues are shown, in time order. */
cues: CuePoint[]
/** The deck's CUE point, so the memory cue it sits on reads as selected. */
cuePoint: number
onCall: (cue: CuePoint) => void
/** Right-click: the deck opens its Rename / Colour / Delete menu. */
onMenu: (cue: CuePoint, x: number, y: number) => void
onAdd: () => void
/** Why + MEMORY cannot add one (read-only library, the platform's cap), or null. */
addRefusal: string | null
/** The memory cue whose name is being edited in place, if any. */
renamingId: string | null
onRenameCommit: (cue: CuePoint, name: string) => void
onRenameCancel: () => void
}
/** `m:ss.s` — a chip's label when the cue has no name. */
function shortTime(secs: number): string {
const m = Math.floor(secs / 60)
const s = secs - m * 60
return `${m}:${s.toFixed(1).padStart(4, '0')}`
}
/** `m:ss.mmm` — the full position, for the chip's tooltip. */
function fullTime(secs: number): string {
const m = Math.floor(secs / 60)
const s = secs - m * 60
return `${m}:${s.toFixed(3).padStart(6, '0')}`
}
const named = (cue: CuePoint) => !!cue.name && cue.name !== 'n.n.'
/**
* The memory-cue bank: what the hot cue pads become in Memory mode. Memory cues
* have no pads, so this is + Memory, then a strip of chips in TIME order,
* scrolling sideways when it outgrows the row.
*
* Clicking a chip CALLS the cue, CDJ-style: the deck jumps there and makes it
* the CUE point (a memory loop also engages) — unlike a hot cue pad, it is not
* a trigger to perform with. Right-click edits it, as on a pad.
*/
export function MemoryCueStrip({
cues,
cuePoint,
onCall,
onMenu,
onAdd,
addRefusal,
renamingId,
onRenameCommit,
onRenameCancel,
}: Props) {
const memory = cues.filter((c) => c.role === 'memory').sort((a, b) => a.start - b.start)
return (
// At least one chip always shows (~6rem): the row's breakpoints fold the
// tempo group before the strip gets that narrow.
<div className="flex min-w-[12rem] flex-1 items-center gap-1.5">
<button
type="button"
onClick={onAdd}
aria-disabled={addRefusal != null}
title={addRefusal ?? 'Store a memory cue at the playhead (a memory loop when a loop is on)'}
className={
'btn-glass flex h-11 shrink-0 items-center gap-1 rounded-xl px-2.5 text-[11px] font-semibold ' +
(addRefusal != null ? 'cursor-not-allowed opacity-45' : '')
}
>
<Icon name="plus" size={13} strokeWidth={2.2} />
Memory
</button>
<div
className="flex min-w-[5.5rem] flex-1 items-center gap-1.5 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
// A vertical wheel scrolls the strip sideways: a mouse has no other way.
onWheel={(e) => {
if (Math.abs(e.deltaY) > Math.abs(e.deltaX)) e.currentTarget.scrollLeft += e.deltaY
}}
>
{memory.length === 0 && (
<span className="px-1 text-[11px] text-faint">
No memory cues — + Memory stores one at the playhead
</span>
)}
{memory.map((cue) => {
const color = cueColor(cue)
const selected = Math.abs(cue.start - cuePoint) < 0.0015
const locked = !cue.editable
const key = cue.id ?? `${cue.start}:${cue.type}`
return (
<button
key={key}
type="button"
onClick={() => onCall(cue)}
onContextMenu={(e) => {
e.preventDefault()
onMenu(cue, e.clientX, e.clientY)
}}
title={`${named(cue) ? `${cue.name} · ` : ''}${fullTime(cue.start)}${
cue.type === 'loop' ? ` · loop ${cue.length.toFixed(2)} s` : ''
}${locked ? ' · not editable here' : ''}`}
style={padStyle(color, selected)}
className="flex h-11 max-w-[9rem] shrink-0 items-center gap-1.5 rounded-xl px-2.5 text-left transition-[filter] hover:brightness-115"
>
<span className="flex shrink-0" style={{ color: lighten(color) }}>
<Icon name={locked ? 'lock' : cue.type === 'loop' ? 'loop' : cueIcon(cue)} size={13} strokeWidth={2.1} />
</span>
{renamingId != null && renamingId === cue.id ? (
<RenameField
initial={named(cue) ? cue.name! : ''}
onCommit={(name) => onRenameCommit(cue, name)}
onCancel={onRenameCancel}
/>
) : (
<span
className={`truncate text-[11px] leading-none ${named(cue) ? 'text-text' : 'font-mono text-text/80'}`}
>
{named(cue) ? cue.name : shortTime(cue.start)}
</span>
)}
</button>
)
})}
</div>
</div>
)
}
+38
View File
@@ -0,0 +1,38 @@
/**
* The deck's two-way mode switch: two small stacked tabs in a well, the chosen
* one lit. BEAT / MAN (loops) and HOT / MEM (the cue bank) are both this.
*/
export function ModeSwitch<T extends string>({
label,
value,
options,
onChange,
}: {
/** Names the group for assistive tech ("Loop mode", "Cue bank"). */
label: string
value: T
options: { value: T; text: string; title: string }[]
onChange: (value: T) => void
}) {
return (
<div
role="group"
aria-label={label}
className="well flex h-10 shrink-0 flex-col justify-center gap-0.5 rounded-[10px] p-0.5"
>
{options.map((o) => (
<button
key={o.value}
onClick={() => onChange(o.value)}
title={o.title}
aria-pressed={value === o.value}
className={`h-[17px] rounded-[7px] px-[7px] text-[9px] font-bold tracking-[0.08em] transition-colors ${
value === o.value ? 'btn-primary' : 'text-faint hover:text-text'
}`}
>
{o.text}
</button>
))}
</div>
)
}
+199 -15
View File
@@ -32,6 +32,8 @@ import { TrackInfoDialog } from './TrackInfoDialog'
import { ContextMenu, type MenuItem } from './ContextMenu' import { ContextMenu, type MenuItem } from './ContextMenu'
import { BpmReadout, GridEditStrip, TempoControls, TempoFold } from './GridControls' import { BpmReadout, GridEditStrip, TempoControls, TempoFold } from './GridControls'
import { HotcueBar } from './HotcueBar' import { HotcueBar } from './HotcueBar'
import { MemoryCueStrip } from './MemoryCueStrip'
import { ModeSwitch } from './ModeSwitch'
import { LoopControls, LOOP_SIZES, type LoopMode } from './LoopControls' import { LoopControls, LOOP_SIZES, type LoopMode } from './LoopControls'
import { MainWaveform, MIN_SEC, MAX_SEC, DEFAULT_SEC, type StemLane } from './MainWaveform' import { MainWaveform, MIN_SEC, MAX_SEC, DEFAULT_SEC, type StemLane } from './MainWaveform'
import { OverviewWaveform } from './OverviewWaveform' import { OverviewWaveform } from './OverviewWaveform'
@@ -156,6 +158,10 @@ export function PrepStrip({
const [gridMode, setGridMode] = useState(false) const [gridMode, setGridMode] = useState(false)
const [padMenu, setPadMenu] = useState<{ slot: number; x: number; y: number } | null>(null) const [padMenu, setPadMenu] = useState<{ slot: number; x: number; y: number } | null>(null)
const [renamingSlot, setRenamingSlot] = useState<number | null>(null) const [renamingSlot, setRenamingSlot] = useState<number | null>(null)
// Hot / Memory: which bank the pads' place in the row shows (persisted).
const [bankMode, setBankMode] = useState<'hot' | 'memory'>('hot')
const [memoryMenu, setMemoryMenu] = useState<{ cue: CuePoint; x: number; y: number } | null>(null)
const [renamingMemory, setRenamingMemory] = useState<string | null>(null)
// Loop state (transient — persisted only when saved as a hotcue later). // Loop state (transient — persisted only when saved as a hotcue later).
const [loopRegion, setLoopRegion] = useState<{ start: number; end: number } | null>(null) const [loopRegion, setLoopRegion] = useState<{ start: number; end: number } | null>(null)
@@ -220,6 +226,18 @@ export function PrepStrip({
writePrefs({ beatSize }) writePrefs({ beatSize })
}, [beatSize, writePrefs]) }, [beatSize, writePrefs])
// Hot / Memory bank, remembered the same way (decided 2026-10-16).
const bankHydratedRef = useRef(false)
useEffect(() => {
if (bankHydratedRef.current || !prefsQuery.data) return
bankHydratedRef.current = true
if ((prefsQuery.data as { cueBankMode?: unknown }).cueBankMode === 'memory') setBankMode('memory')
}, [prefsQuery.data])
useEffect(() => {
if (!bankHydratedRef.current) return // don't clobber saved prefs pre-hydration
writePrefs({ cueBankMode: bankMode })
}, [bankMode, writePrefs])
const getCtx = (): AudioContext => { const getCtx = (): AudioContext => {
if (!audioCtxRef.current) { if (!audioCtxRef.current) {
audioCtxRef.current = new (window.AudioContext ?? audioCtxRef.current = new (window.AudioContext ??
@@ -267,6 +285,8 @@ export function PrepStrip({
setSelectedSlot(null) setSelectedSlot(null)
setPadMenu(null) setPadMenu(null)
setRenamingSlot(null) setRenamingSlot(null)
setMemoryMenu(null)
setRenamingMemory(null)
setLoopRegion(null) setLoopRegion(null)
setLoopActive(false) setLoopActive(false)
setActiveBeats(null) setActiveBeats(null)
@@ -830,11 +850,18 @@ export function PrepStrip({
const eng = playbackRef.current const eng = playbackRef.current
if (!eng || !eng.ready) return if (!eng || !eng.ready) return
getCtx() getCtx()
// A loop hotcue jumps to its start AND engages a loop of its length — the enterCue(cue)
// new loop FIRST, so the seek is not wrapped back into the old one. The loop seek(cue.start)
// controls follow it: a beat-sized loop takes over the shared size (so −/+ // Paused at press → momentary preview: play while held.
// resize THIS loop), and one of no preset size shows in MAN, where its if (!eng.playing) beginPreview(`hc:${slot}`, cue.start)
// toggle is. }
// Before jumping to a cue: a loop cue engages a loop of its length — the new
// loop FIRST, so the seek is not wrapped back into the old one. The loop
// controls follow it: a beat-sized loop takes over the shared size (so −/+
// resize THIS loop), and one of no preset size shows in MAN, where its toggle
// is. A point cue outside an engaged loop leaves it.
const enterCue = (cue: CuePoint) => {
if (cue.type === 'loop' && cue.length > 0) { if (cue.type === 'loop' && cue.length > 0) {
const beats = beatsForLoop(cue.start, cue.length) const beats = beatsForLoop(cue.start, cue.length)
engagLoop(cue.start, cue.start + cue.length, beats) engagLoop(cue.start, cue.start + cue.length, beats)
@@ -847,9 +874,6 @@ export function PrepStrip({
} else { } else {
leaveLoopFor(cue.start) leaveLoopFor(cue.start)
} }
seek(cue.start)
// Paused at press → momentary preview: play while held.
if (!eng.playing) beginPreview(`hc:${slot}`, cue.start)
} }
// Hotcue slot released (mouse/touch up, or key up). Ends its momentary preview. // Hotcue slot released (mouse/touch up, or key up). Ends its momentary preview.
@@ -937,6 +961,125 @@ export function PrepStrip({
} }
} }
// ---- memory cues --------------------------------------------------------
// Cues on no pad, listed in time order (MemoryCueStrip). Calling one is
// CDJ-style: jump there and make it the CUE point — paused stays paused,
// playing keeps playing; a memory loop also engages (decided 2026-10-16).
const showMemory = caps.cues.memory_cues && bankMode === 'memory'
const memoryPalette = caps.cues.memory_color === 'palette' ? caps.cues.memory_palette : []
const memoryCount = cueData?.cues.filter((c) => c.role === 'memory' && c.editable).length ?? 0
const memoryCap = caps.cues.max_memory_cues
const memoryAddRefusal = !canEditCues
? (readOnlyNotice(caps) ?? `Cues cannot be edited on ${caps.save.app_name} libraries yet.`)
: memoryCap != null && memoryCount >= memoryCap
? `${caps.save.app_name} keeps at most ${memoryCap} memory cues per track`
: null
const callMemoryCue = (cue: CuePoint) => {
const eng = playbackRef.current
if (!eng || !eng.ready) return
getCtx()
enterCue(cue)
seek(cue.start)
setCuePoint(cue.start)
}
// + Memory: at the (snapped) playhead, or the engaged loop as a memory loop.
const addMemoryCue = async () => {
if (!track) return
if (memoryAddRefusal) {
onError?.(memoryAddRefusal)
return
}
try {
if (loopActive && loopRegion) {
const len = loopRegion.end - loopRegion.start
applyCueEdit(await api.addMemoryCue(track.id, loopRegion.start, 'loop', len))
} else {
const t = snapTime(playbackRef.current?.getPosition() ?? current)
applyCueEdit(await api.addMemoryCue(track.id, t, 'cue'))
}
} catch (e) {
onError?.((e as Error).message)
}
}
const editMemoryCue = async (edit: () => Promise<TrackCues>) => {
if (!track || refuseCueEdit()) return
try {
applyCueEdit(await edit())
} catch (e) {
onError?.((e as Error).message)
}
}
const memoryMenuItems = (cue: CuePoint): MenuItem[] => {
const id = cue.id
const locked = !cue.editable || id == null
const items: MenuItem[] = []
// Its type as one-click choices, as on a pad — where the platform has more
// than one point type (Traktor); a loop stays a loop.
if (cue.type === 'loop') {
items.push({ heading: 'Memory loop' })
} else if (pointCueTypes.length > 1) {
items.push({ heading: 'Memory cue · Type' })
for (const t of pointCueTypes) {
const color = cueTypeColor(t)
items.push({
label: CUE_TYPE_LABELS[t],
icon: (
<span
className="block h-2 w-2 rounded-full"
style={{ background: color, boxShadow: `0 0 6px ${color}` }}
/>
),
hint: t === cue.type ? '✓' : undefined,
disabled: locked,
onClick: () =>
t !== cue.type &&
id != null &&
void editMemoryCue(() => api.setMemoryCueType(track!.id, id, t)),
})
}
} else {
items.push({ heading: 'Memory cue' })
}
if (memoryPalette.length > 0) {
items.push({ separator: true })
items.push({ heading: 'Colour' })
items.push({
swatches: memoryPalette,
selected: cue.color,
disabled: locked,
onPick: (color) =>
color !== cue.color &&
id != null &&
void editMemoryCue(() => api.setMemoryCueColor(track!.id, id, color)),
})
}
if (locked) items.push({ heading: 'Managed by the DJ app — not editable here' })
items.push({ separator: true })
items.push({
label: 'Rename…',
disabled: locked,
onClick: () => !refuseCueEdit() && setRenamingMemory(id),
})
items.push({
label: 'Delete',
danger: true,
disabled: locked,
onClick: () => id != null && void editMemoryCue(() => api.deleteMemoryCue(track!.id, id)),
})
return items
}
const renameMemoryCue = (cue: CuePoint, name: string) => {
setRenamingMemory(null)
if (cue.id == null) return
const id = cue.id
void editMemoryCue(() => api.renameMemoryCue(track!.id, id, name || null))
}
// ---- beatgrid --------------------------------------------------------- // ---- beatgrid ---------------------------------------------------------
// Which marker the grid controls act on is derived from the playhead — there // Which marker the grid controls act on is derived from the playhead — there
// is no separate selection state to keep in sync. // is no separate selection state to keep in sync.
@@ -1471,10 +1614,11 @@ export function PrepStrip({
A container, so the row gives way in stages as the window narrows A container, so the row gives way in stages as the window narrows
instead of the pads sliding under the tempo group: the pads drop instead of the pads sliding under the tempo group: the pads drop
their names first (each pad queries its own width, see HotcueBar), their names first (each pad queries its own width, see HotcueBar),
then below 74rem the tempo group folds into one BPM button, and below then below 77rem the tempo group folds into one BPM button, and below
60rem the Grid toggle keeps only its icon. Those are the row's 63rem the Grid toggle keeps only its icon. Those are the row's
measured widths just before the pad bank would hit its minimum (with measured widths just before the pad bank would hit its minimum (with
a lockable grid's extra Lock button), so move them with the controls. */} a lockable grid's extra Lock button, and the Hot / Mem toggle's
~3rem with its gap), so move them with the controls. */}
<div className="@container flex h-11 shrink-0 items-center gap-3"> <div className="@container flex h-11 shrink-0 items-center gap-3">
<button <button
onClick={toggle} onClick={toggle}
@@ -1533,6 +1677,23 @@ export function PrepStrip({
onMove={moveOrJump} onMove={moveOrJump}
/> />
{DIVIDER} {DIVIDER}
{caps.cues.memory_cues && !gridMode && (
<ModeSwitch
label="Cue bank"
value={bankMode}
options={[
{ value: 'hot', text: 'HOT', title: 'Hot cues: the pads' },
{ value: 'memory', text: 'MEM', title: 'Memory cues: call one to make it the CUE point' },
]}
onChange={(m) => {
setBankMode(m)
setPadMenu(null)
setMemoryMenu(null)
setRenamingSlot(null)
setRenamingMemory(null)
}}
/>
)}
{gridMode ? ( {gridMode ? (
<GridEditStrip <GridEditStrip
markerIndex={activeMarkerIndex} markerIndex={activeMarkerIndex}
@@ -1550,6 +1711,18 @@ export function PrepStrip({
onDeleteGrid={deleteGrid} onDeleteGrid={deleteGrid}
onReset={resetGrid} onReset={resetGrid}
/> />
) : showMemory ? (
<MemoryCueStrip
cues={cueData?.cues ?? []}
cuePoint={cuePoint}
onCall={callMemoryCue}
onMenu={(cue, x, y) => setMemoryMenu({ cue, x, y })}
onAdd={() => void addMemoryCue()}
addRefusal={memoryAddRefusal}
renamingId={renamingMemory}
onRenameCommit={renameMemoryCue}
onRenameCancel={() => setRenamingMemory(null)}
/>
) : ( ) : (
<HotcueBar <HotcueBar
cues={cueData?.cues ?? []} cues={cueData?.cues ?? []}
@@ -1568,8 +1741,8 @@ export function PrepStrip({
/> />
)} )}
{DIVIDER} {DIVIDER}
<TempoControls {...tempoProps} className="@max-[74rem]:hidden" /> <TempoControls {...tempoProps} className="@max-[77rem]:hidden" />
<TempoFold locked={tempoProps.locked} className="hidden @max-[74rem]:flex"> <TempoFold locked={tempoProps.locked} className="hidden @max-[77rem]:flex">
<TempoControls {...tempoProps} /> <TempoControls {...tempoProps} />
</TempoFold> </TempoFold>
<button <button
@@ -1577,22 +1750,33 @@ export function PrepStrip({
setGridMode((g) => !g) setGridMode((g) => !g)
setPadMenu(null) setPadMenu(null)
setRenamingSlot(null) setRenamingSlot(null)
setMemoryMenu(null)
setRenamingMemory(null)
}} }}
aria-pressed={gridMode} aria-pressed={gridMode}
disabled={!track} disabled={!track}
title={gridMode ? 'Back to the hotcue pads' : 'Edit the beatgrid: markers, phase, reset'} title={gridMode ? 'Back to the hotcue pads' : 'Edit the beatgrid: markers, phase, reset'}
aria-label="Grid" aria-label="Grid"
className={`flex h-10 shrink-0 items-center gap-1.5 rounded-xl px-3 text-xs font-semibold transition-colors disabled:opacity-40 @max-[60rem]:w-10 @max-[60rem]:justify-center @max-[60rem]:px-0 ${ className={`flex h-10 shrink-0 items-center gap-1.5 rounded-xl px-3 text-xs font-semibold transition-colors disabled:opacity-40 @max-[63rem]:w-10 @max-[63rem]:justify-center @max-[63rem]:px-0 ${
gridMode gridMode
? 'bg-gold/15 text-gold shadow-[inset_0_0_0_1px_rgb(255_200_97/0.5),0_0_16px_-4px_rgb(255_200_97/0.6)]' ? 'bg-gold/15 text-gold shadow-[inset_0_0_0_1px_rgb(255_200_97/0.5),0_0_16px_-4px_rgb(255_200_97/0.6)]'
: 'btn-glass text-text' : 'btn-glass text-text'
}`} }`}
> >
<Icon name="grid" size={14} /> <Icon name="grid" size={14} />
<span className="@max-[60rem]:hidden">Grid</span> <span className="@max-[63rem]:hidden">Grid</span>
</button> </button>
</div> </div>
{memoryMenu && (
<ContextMenu
key={`m:${memoryMenu.cue.id}:${memoryMenu.x}:${memoryMenu.y}`}
x={memoryMenu.x}
y={memoryMenu.y}
items={memoryMenuItems(memoryMenu.cue)}
onClose={() => setMemoryMenu(null)}
/>
)}
{padMenu && ( {padMenu && (
<ContextMenu <ContextMenu
key={`${padMenu.slot}:${padMenu.x}:${padMenu.y}`} key={`${padMenu.slot}:${padMenu.x}:${padMenu.y}`}
+42
View File
@@ -0,0 +1,42 @@
import { useRef, useState } from 'react'
/** A pad's or memory cue's name, edited in place. Enter or clicking away
* commits; Esc cancels. Keys stay in the field, so digits and Space type
* rather than trigger the deck. */
export function RenameField({
initial,
onCommit,
onCancel,
}: {
initial: string
onCommit: (name: string) => void
onCancel: () => void
}) {
const [val, setVal] = useState(initial)
// Enter commits and unmounts the field, which can fire a trailing blur.
const done = useRef(false)
const finish = (commit: boolean) => {
if (done.current) return
done.current = true
if (commit && val.trim() !== initial) onCommit(val.trim())
else onCancel()
}
return (
<input
autoFocus
value={val}
onChange={(e) => setVal(e.target.value)}
onFocus={(e) => e.currentTarget.select()}
onBlur={() => finish(true)}
// The pad is a button: keep its press/preview handlers out of the field.
onPointerDown={(e) => e.stopPropagation()}
onPointerUp={(e) => e.stopPropagation()}
onKeyDown={(e) => {
e.stopPropagation() // digits and Space must type, not trigger the deck
if (e.key === 'Enter') finish(true)
else if (e.key === 'Escape') finish(false)
}}
className="w-full min-w-0 rounded bg-well px-1 text-[11px] leading-4 text-text outline-none ring-1 ring-accent"
/>
)
}
+25 -6
View File
@@ -30,7 +30,7 @@ import {
} from '@dnd-kit/sortable' } from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities' import { CSS } from '@dnd-kit/utilities'
import type { Track, TrackOrigin } from '../api' import type { Track, TrackOrigin } from '../api'
import { beginDrag, useDragPayload, useDropTarget } from '../lib/drag' import { beginDrag, isForeign, useDragPayload, useDropTarget, type TracksOrFiles } from '../lib/drag'
import { hasMod } from '../lib/modKey' import { hasMod } from '../lib/modKey'
import { TRACK_COLUMNS } from '../lib/trackColumns' import { TRACK_COLUMNS } from '../lib/trackColumns'
@@ -76,6 +76,11 @@ interface Props {
/** Where dragged rows come from: whose ids they are, and the editable /** Where dragged rows come from: whose ids they are, and the editable
* playlist they leave on a Cmd/Ctrl-drag (move). Defaults to the collection. */ * playlist they leave on a Cmd/Ctrl-drag (move). Defaults to the collection. */
dragFrom?: { origin: TrackOrigin; playlistId?: string } dragFrom?: { origin: TrackOrigin; playlistId?: string }
/** Things from outside the library dropped on the table — files from the
* OS, a Files folder's or a device's rows — headed for this view's
* playlist. `index` is the insertion line while `reorder` is enabled (the
* rows ARE the entry list then), else null: appended. */
foreignDrop?: { label: string; onDrop: (p: TracksOrFiles, index: number | null) => void }
/** Delete/Backspace removes the selected tracks from this view. */ /** Delete/Backspace removes the selected tracks from this view. */
onRemove?: (ids: string[]) => void onRemove?: (ids: string[]) => void
/** `viewIds` is every row's id in the order shown (sorted, filtered). */ /** `viewIds` is every row's id in the order shown (sorted, filtered). */
@@ -285,6 +290,7 @@ export function TrackTable({
positions, positions,
marked, marked,
reorder, reorder,
foreignDrop,
dragFrom, dragFrom,
onRemove, onRemove,
onRowContextMenu, onRowContextMenu,
@@ -447,14 +453,25 @@ export function TrackTable({
} }
}, [tableKey]) }, [tableKey])
const [dropRef, dropHint] = useDropTarget<{ drop: number }>({ // The table's own rows (reorder) and, where `foreignDrop` is given,
// things from outside the library (see the prop).
const foreignDropRef = useRef(foreignDrop)
foreignDropRef.current = foreignDrop
const [dropRef, dropHint] = useDropTarget<{ drop: number | null }>({
hint: (p, at) => { hint: (p, at) => {
if (p.kind !== 'tracks' || p.source !== tableKey || !reorderRef.current?.enabled) return null const own = p.kind === 'tracks' && p.source === tableKey
if (!own && !(foreignDropRef.current && isForeign(p))) return null
if (!reorderRef.current?.enabled) return own ? null : { drop: null }
const top = bodyRef.current?.getBoundingClientRect().top ?? 0 const top = bodyRef.current?.getBoundingClientRect().top ?? 0
return { drop: Math.max(0, Math.min(rowsRef.current.length, Math.round((at.y - top) / ROW_HEIGHT))) } return { drop: Math.max(0, Math.min(rowsRef.current.length, Math.round((at.y - top) / ROW_HEIGHT))) }
}, },
label: (p) => (p.kind === 'tracks' && p.source === tableKey ? null : (foreignDropRef.current?.label ?? null)),
onDrop: (p, { drop }) => { onDrop: (p, { drop }) => {
if (p.kind !== 'tracks') return if (p.kind !== 'tracks' || p.source !== tableKey) {
if (isForeign(p)) foreignDropRef.current?.onDrop(p, drop)
return
}
if (drop === null) return
const ids = new Set(p.ids) const ids = new Set(p.ids)
const rs = rowsRef.current.map((r) => r.original) const rs = rowsRef.current.map((r) => r.original)
const kept = rs.filter((t) => !ids.has(t.id)) const kept = rs.filter((t) => !ids.has(t.id))
@@ -547,7 +564,9 @@ export function TrackTable({
<div <div
ref={scrollerRef} ref={scrollerRef}
data-drag-scroll={bodyOffset.header} data-drag-scroll={bodyOffset.header}
className="h-full overflow-auto px-1.5" className={`h-full overflow-auto px-1.5 ${
dropHint && dropHint.drop === null ? 'rounded-lg outline-2 -outline-offset-2 outline-accent' : ''
}`}
onClick={(e) => { onClick={(e) => {
// A click in the empty space below the rows clears the selection. // A click in the empty space below the rows clears the selection.
const t = e.target as HTMLElement const t = e.target as HTMLElement
@@ -621,7 +640,7 @@ export function TrackTable({
</div> </div>
) )
})} })}
{dropHint && ( {dropHint && dropHint.drop !== null && (
<div <div
className="pointer-events-none absolute left-0 z-10 h-0.5 w-full bg-accent" className="pointer-events-none absolute left-0 z-10 h-0.5 w-full bg-accent"
style={{ top: dropHint.drop * ROW_HEIGHT - 1 }} style={{ top: dropHint.drop * ROW_HEIGHT - 1 }}
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff. Show more