mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-28 18:32:51 +01:00
Compare commits
15
Commits
v0.2.7-b17
...
v0.2.9-b19
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
422297d890 | ||
|
|
ee48e80440 | ||
|
|
0aeb5019ad | ||
|
|
1f2ca18e8a | ||
|
|
19a604f730 | ||
|
|
83b0978b14 | ||
|
|
0ced274f73 | ||
|
|
fc4e7804b3 | ||
|
|
77b063ba0e | ||
|
|
16c3552be6 | ||
|
|
32cfb034e2 | ||
|
|
b70798a0fe | ||
|
|
4c51f57fe9 | ||
|
|
7b2d6de411 | ||
|
|
8230722105 |
No files matched your search
@@ -169,6 +169,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write # required to create the tag + release
|
||||
pull-requests: read # to read the merged PR's patch notes
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
@@ -188,12 +189,50 @@ jobs:
|
||||
pattern: konduktor-*
|
||||
path: artifacts # → artifacts/konduktor-macOS/…, artifacts/konduktor-Windows/…
|
||||
|
||||
# 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
|
||||
# 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
|
||||
# push) or no such section → GitHub's generated notes, as before.
|
||||
- name: Patch notes from the merged PR
|
||||
id: notes
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
gh api "repos/${{ github.repository }}/commits/${{ github.sha }}/pulls" \
|
||||
--jq '[.[] | select(.base.ref == "main" and .merged_at != null)][0].body // ""' \
|
||||
> pr-body.md || : > pr-body.md
|
||||
python3 - <<'EOF'
|
||||
import os, re
|
||||
body = open("pr-body.md", encoding="utf-8").read().replace("\r\n", "\n")
|
||||
body = re.sub(r"<!--.*?-->", "", body, flags=re.S)
|
||||
section, level = [], None
|
||||
for line in body.split("\n"):
|
||||
m = re.match(r"^(#{1,6})\s+(.*?)\s*#*\s*$", line)
|
||||
if level is None:
|
||||
if m and re.fullmatch(r"patch[\s-]?notes:?", m.group(2), re.I):
|
||||
level = len(m.group(1))
|
||||
elif m and len(m.group(1)) <= level:
|
||||
break
|
||||
else:
|
||||
section.append(line)
|
||||
notes = "\n".join(section).strip()
|
||||
found = bool(notes)
|
||||
if found:
|
||||
with open("release-notes.md", "w", encoding="utf-8") as f:
|
||||
f.write("## What's Changed\n\n" + notes + "\n")
|
||||
with open(os.environ["GITHUB_OUTPUT"], "a") as out:
|
||||
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.")
|
||||
EOF
|
||||
|
||||
- name: Publish release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: v${{ steps.version.outputs.version }}-b${{ github.run_number }}
|
||||
name: Konduktor v${{ steps.version.outputs.version }}-b${{ github.run_number }}
|
||||
target_commitish: ${{ github.sha }}
|
||||
generate_release_notes: true # auto changelog from commits/PRs since last release
|
||||
body_path: ${{ steps.notes.outputs.found == 'true' && 'release-notes.md' || '' }}
|
||||
generate_release_notes: ${{ steps.notes.outputs.found != 'true' }}
|
||||
fail_on_unmatched_files: true
|
||||
files: artifacts/**/*
|
||||
@@ -315,8 +315,19 @@ Two independent apps that talk over HTTP:
|
||||
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
|
||||
bank. Point cues AND loops both write; `cue_types` owns the translation.
|
||||
**Memory cues stay preserved-but-uneditable** (Rekordbox is the only
|
||||
platform with them — the two-platform promotion rule).
|
||||
**Memory cues are editable** (`add_memory_cue` / `rename_` /
|
||||
`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
|
||||
/api/tracks/cue/color`) from `palette.SWATCHES` — all 16 of rekordbox's
|
||||
swatches, MEASURED (the teal-green, 0x13 #00FF30, came last: rekordbox
|
||||
@@ -392,8 +403,19 @@ Two independent apps that talk over HTTP:
|
||||
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
|
||||
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
|
||||
preserved-but-uneditable.
|
||||
A track with no analysis files refuses cue/grid edits.
|
||||
**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
|
||||
every Save (rekordbox's own edits let its playlists drift — measured). The
|
||||
stick's own pdb is EDITED (`pdb.PdbEditor`), not regenerated: ids are
|
||||
@@ -870,7 +892,7 @@ Two independent apps that talk over HTTP:
|
||||
too, so nested playlists are reachable). Tracks dropped on a playlist go
|
||||
through `lib/addTracks.ts` — shared with the context menu's "Add to" —
|
||||
which ASKS about duplicates where the platform can hold them (decided:
|
||||
ask each time), and Option/Alt moves them out of the editable playlist
|
||||
ask each time), and Cmd (Ctrl on Windows; `lib/modKey.ts`) moves them out of the editable playlist
|
||||
they came from. A device's or Files folder's tracks open `ImportDialog`
|
||||
(`trackIds` + `target`) / `AddFilesDialog` with the target filled in
|
||||
(`onAddForeign`), so copy-vs-reference is still asked. Export rows take the
|
||||
@@ -893,7 +915,7 @@ Two independent apps that talk over HTTP:
|
||||
/ Try again (`backend_restart`). The shell has no timeout of its own. Before
|
||||
ready it answers quit requests itself — nothing can be unsaved — and stops
|
||||
at ready so it never races `QuitGuard`), `SaveBar` (+ "Discard changes…" when
|
||||
dirty, and the settings gear beside it, whose menu opens `ShortcutsDialog` — the shortcut list is written out BY HAND, so a new or changed shortcut in `PrepStrip` / `TrackTable` must be added there too — and `AppSettings` ("Konduktor Settings…": app-level prefs, each with its default in `APP_SETTING_DEFAULTS` and read through `useAppSetting`; today `expandPlaylistFolders` and `exportRootFolder`, both default off — the latter read by the backend at `run_export` and passed down as `ExportPayload.root_folder`. The Sidebar holds folder open state as per-id overrides of that setting, reset on a new library or a change of the setting, and carried to the new ids when a rename/move changes a folder's path id)), `Toolbar` (search/filters; columns are chosen by right-clicking the table header),
|
||||
dirty, and the settings gear beside it, whose menu (or `?` anywhere) opens `ShortcutsDialog` — a KEYBOARD MAP (decided 2026-10-15): keys lit in the colour of what they do, a caption explaining the key pointed at or pressed (pressing explains, it never acts: a capture-phase listener keeps the deck's and table's keys from firing), holding or picking ⇧ / Cmd-Ctrl relights it with that layer, mouse gestures listed beneath. It shrinks to fit the dialog and drops the words on the keys when too small. Its content is `lib/shortcuts.ts`, written out BY HAND, so a new or changed shortcut in `PrepStrip` / `TrackTable` must be added there too — and `AppSettings` ("Konduktor Settings…": app-level prefs, each with its default in `APP_SETTING_DEFAULTS` and read through `useAppSetting`; today `expandPlaylistFolders` and `exportRootFolder`, both default off — the latter read by the backend at `run_export` and passed down as `ExportPayload.root_folder` — and `timeReadoutDecimals` (0–3, default 1: the deck's ELAPSED / REMAIN, truncated, never rounded). The Sidebar holds folder open state as per-id overrides of that setting, reset on a new library or a change of the setting, and carried to the new ids when a rename/move changes a folder's path id)), `Toolbar` (search/filters; columns are chosen by right-clicking the table header),
|
||||
`TrackTable` (**the one track list** — All Tracks, playlists, exports and
|
||||
devices. TanStack Table + **virtualized** grid; per-row play button,
|
||||
configurable columns, header sorting, inline double-click editing, and
|
||||
@@ -915,7 +937,7 @@ Two independent apps that talk over HTTP:
|
||||
pointer-y / ROW_HEIGHT. dnd-kit still reorders the header's columns.
|
||||
Every table's rows are a DRAG SOURCE through `lib/drag.tsx` (a selected row
|
||||
carries the selection, the payload's `lead` is the row grabbed, `dragFrom`
|
||||
says whose ids they are and which editable playlist an Option-drag leaves);
|
||||
says whose ids they are and which editable playlist a Cmd/Ctrl-drag leaves — a Cmd/Ctrl press arms a drag, and stays a toggle-click if it never moves);
|
||||
the in-table reorder is just the table's own drop target.)
|
||||
**`lib/drag.tsx` — drag and drop across the window** (decided 2026-10-06,
|
||||
[the discussion](.claude/discussions/discuss-drag-and-drop-2026-10-06.md)):
|
||||
@@ -996,9 +1018,12 @@ Two independent apps that talk over HTTP:
|
||||
column chooser uses those; "Add to" lists
|
||||
playlists + exports and acts on the whole selection; in an editable
|
||||
playlist "Set Position…" (`SetPositionDialog`, `lib/playlistOrder.ts`)
|
||||
moves the selection as ONE block in playlist order so its first track
|
||||
lands at #N — allowed while sorted/filtered, unlike drag, because it
|
||||
reorders the FULL entry list; "Remove ▸" holds
|
||||
moves the selection as ONE block so its first track lands at #N —
|
||||
allowed while sorted/filtered, unlike drag, because it reorders the FULL
|
||||
entry list. While the table is sorted the dialog asks the block's Order:
|
||||
"As sorted" (default; the menu's ids arrive in VIEW order, so the sort is
|
||||
written into the playlist and survives clearing it) or playlist order;
|
||||
"Remove ▸" holds
|
||||
From this playlist / From this export / Grids / Hotcues / From collection,
|
||||
each behind a `ConfirmDialog` — as is the playlist Delete key. Enter
|
||||
confirms unless a button has focus, so Tab-to-Cancel + Enter cancels) + `EditTagsDialog`
|
||||
@@ -1026,7 +1051,7 @@ Two independent apps that talk over HTTP:
|
||||
one amplitude lane per stem, each normalised to its own 99.5th percentile
|
||||
but never below 5% of the loudest (a silent stem stays silent).
|
||||
`MainWaveform` draws the lanes in the file's own colours with a mute
|
||||
button at each lane's left edge (click = mute, Alt/Option-click = solo);
|
||||
button at each lane's left edge (click = mute, Cmd/Ctrl-click = solo);
|
||||
Q W E R mute stems 1-4, Shift+ solos. **Solo is not a mode**: it SETS the
|
||||
mutes (every other stem muted), so each stem stays freely mutable after
|
||||
it; soloing the one stem still playing unmutes all. Mutes reset per track. Memory is
|
||||
@@ -1037,11 +1062,14 @@ Two independent apps that talk over HTTP:
|
||||
badge, the readout well (ELAPSED / REMAIN to tenths, KEY, and `BpmReadout` —
|
||||
click to type an exact BPM; with no grid, a typed or tapped BPM CREATES one at the playhead, and
|
||||
Set grid on a track with no BPM opens the readout to ask rather than failing), SNAP, Analyze, Auto hotcues. **Waveforms**:
|
||||
`MainWaveform` (scrolling; zoom +/− in its corner and Cmd/Ctrl+scroll, owned
|
||||
by `PrepStrip` so it survives track switches and persists) over
|
||||
`MainWaveform` (scrolling; zoom +/− in its corner and Cmd/Ctrl+scroll,
|
||||
0.25–64 s across, owned by `PrepStrip` so it survives track switches and
|
||||
persists; a toggle under the zoom buttons draws the RAW signal instead
|
||||
of bars — `lib/rawWave.ts`, below; persisted as `mainWaveRaw`) over
|
||||
`OverviewWaveform`, which frames the main view's visible range around the
|
||||
playhead (it takes `secPerView` for exactly that). **Controls**: play, CUE, `LoopControls`, then EITHER
|
||||
`HotcueBar` OR — in **Grid mode** — `GridEditStrip`, then `TempoControls`
|
||||
playhead (it takes `secPerView` for exactly that). **Controls**: play, CUE, `LoopControls`, then
|
||||
(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
|
||||
**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
|
||||
@@ -1065,6 +1093,20 @@ Two independent apps that talk over HTTP:
|
||||
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
|
||||
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
|
||||
choices, a colour swatch grid + Default where `cues.color` is `palette` —
|
||||
`ContextMenu`'s `swatches` item, Rename…, Delete); there is no standalone
|
||||
@@ -1095,9 +1137,12 @@ Two independent apps that talk over HTTP:
|
||||
`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`,
|
||||
`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
|
||||
exists: `slot_labels: 'letter'`, `loops: 'separate_bank'`, and
|
||||
memory-cue *editing* (one-platform features stay preserved-but-uneditable).
|
||||
since a platform may allow renaming but not deleting. Memory cues: the deck's
|
||||
Hot / Mem toggle shows on `cues.memory_cues`, + Memory refuses past
|
||||
`cues.max_memory_cues`, and a memory cue's swatches are `cues.memory_palette`
|
||||
where `cues.memory_color` is `palette` (its own 8, not `palette`'s 16).
|
||||
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
|
||||
columns (defs, default widths/visibility/order, the Columns-menu list, the
|
||||
inline `InlineEdit` cell, and the `TableMeta.onEditField` augmentation).
|
||||
@@ -1171,6 +1216,16 @@ serialization path.** It enforces:
|
||||
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
|
||||
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).
|
||||
The guard that catches serialization regressions like the lxml reformatting bug.
|
||||
- `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays
|
||||
Traktor-valid, backup-first, COLLECTION byte-identical, original untouched;
|
||||
@@ -1271,7 +1326,13 @@ serialization path.** It enforces:
|
||||
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
|
||||
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.
|
||||
Unlike the Rekordbox tests it needs **nothing installed and nothing plugged
|
||||
in**: it runs against `fixtures/onelibrary/`, a real rekordbox 7 export trimmed
|
||||
@@ -1302,10 +1363,15 @@ serialization path.** It enforces:
|
||||
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
|
||||
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
|
||||
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
|
||||
`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
|
||||
@@ -1322,7 +1388,9 @@ serialization path.** It enforces:
|
||||
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
|
||||
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
|
||||
byte-identically, that the job registry runs/fails/cancels, and that a
|
||||
cancelled import leaves **no orphaned audio and an untouched collection**.
|
||||
@@ -1585,6 +1653,16 @@ frontend at `http://localhost:5173`.
|
||||
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`
|
||||
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`
|
||||
is `FOLDER`, `PLAYLIST`, or `SMARTLIST`. Smart playlists are rule-based and
|
||||
have no static entry list. `PlaylistNode.id` is the playlist's stable `UUID`;
|
||||
@@ -1782,9 +1860,11 @@ that number and nothing else — everything derives from it:
|
||||
that swap so `SaveBar` still saves collection edits. While a device'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
|
||||
library. Lossiness follows the settled rule: memory cues become hot cues in
|
||||
spare pads (earliest first), cue colour is dropped (Traktor derives it from
|
||||
type).
|
||||
library. Lossiness follows the settled rule: memory cues stay memory cues
|
||||
(Traktor's `HOTCUE="-1"`; until 2026-10-16 they were promoted to spare
|
||||
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
|
||||
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,
|
||||
@@ -1793,8 +1873,7 @@ that number and nothing else — everything derives from it:
|
||||
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
|
||||
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,
|
||||
stem conversion. All format research — including the schema, which has no
|
||||
rekordbox 7. Same gaps as Rekordbox: cover-art writing, 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).
|
||||
- 🟡 **Export/conversion** — **in progress.** Both the design AND the user flow
|
||||
are settled; see
|
||||
@@ -1957,7 +2036,8 @@ that number and nothing else — everything derives from it:
|
||||
0x2C060E. **Parity with the OneLibrary target is done and verified in
|
||||
Rekordbox 7**: cue colours (palette code in `djmdCue.ColorTableIndex`,
|
||||
`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
|
||||
`_m` 240 / `_s` 80 letterboxed, `ImagePath` -> artwork.jpg). The exporter writes
|
||||
cues through `store.set_cue`/`add_memory_cue`, which share `_write_cue` with
|
||||
@@ -2166,6 +2246,38 @@ The prep strip plays every track through the **Web Audio API** (a plain
|
||||
full scale for whole sections, so a linear map draws a solid orange wall
|
||||
instead of the kick pulse. The main view draws 2 px bars with a 1 px gap,
|
||||
**binned in track space** so bars scroll rather than flicker.
|
||||
- `rawWave.ts` — **the raw waveform** (decided 2026-10-15,
|
||||
[the discussion](.claude/discussions/discuss-raw-waveform-2026-10-15.md)):
|
||||
the bars' ~7 ms columns of unsigned band energy hide where a kick starts, so
|
||||
the main view can draw the signal itself as a thin line, after Traktor at
|
||||
full zoom. Its own toggle (under the zoom buttons), NOT tied to Grid mode —
|
||||
tried first, changed after use.
|
||||
**Shape exact, colour approximate**: the tint is the bar palette weighted by
|
||||
the ~7 ms band columns, lerped, mixed in OKLab with the CHROMA restored
|
||||
(`bandColour`) — a plain RGB mean of orange/violet/cyan lands near grey and
|
||||
read as mud; chosen from five variants rendered on real tracks; the scale is fixed by the track's loudest
|
||||
sample (no per-view gain, so nothing pumps while scrolling). Each pixel is a
|
||||
min→max stroke stretched to touch its neighbour's, so it reads as an
|
||||
envelope zoomed out and a line zoomed in with no switch-over. Data: min/max
|
||||
per 32 samples summarised at load (~4 MB / 6 min) for wide views; below 128
|
||||
samples a pixel, the visible window read straight from the `AudioBuffer`
|
||||
(`copyFromChannel` — no full-length mono copy). Bins sit on a track-space
|
||||
grid like the bars'. A stem track's lanes each draw their own raw line, in
|
||||
the stem's colour, each at its own peak floored at 5% of the loudest.
|
||||
Measured in WKWebView: 0.3 ms a frame at 0.25 s, ~5 ms at 64 s.
|
||||
- `decodeAlign.ts` — **the deck's decode vs the grid's time base.** Positions
|
||||
are in the backend's PyAV decode; the deck decodes with `decodeAudioData`.
|
||||
Measured 2026-10-15 with click files: identical on every format and engine
|
||||
EXCEPT a **header-less MP3 under WebKit** (the macOS app), decoded 529
|
||||
samples (12 ms) EARLY — CoreAudio trims the decoder delay with no header to
|
||||
say so; FFmpeg (and Chromium/WebView2) do not. Invisible under bars, a
|
||||
12 ms miss on the raw line. The engine's offset is MEASURED once per session
|
||||
by decoding a built-in 2.7 KB header-less MP3 (`decodeProbe.ts`, click at a
|
||||
known FFmpeg sample), and a header-less MP3's buffer (`mp3HeaderFrame`, a
|
||||
port of `core/mp3_gapless.parse` behind an is-it-an-MP3 gate) is padded by
|
||||
it in `decodeUrl` — so playback, scratch and both waveforms move together.
|
||||
Not measured: a header without a trusted encoder-delay field; Edge on a real
|
||||
Windows machine (Chromium on macOS matched).
|
||||
- `cues.ts` — canvas drawers for cue markers (type-colored), the active loop
|
||||
band, the beatgrid (per-segment white beats/brighter downbeats, plus marker
|
||||
lines — gold for the one governing the playhead, accent otherwise, with the
|
||||
|
||||
@@ -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`.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -26,7 +26,7 @@ from ...core.capabilities import Capabilities
|
||||
from ...core.model import GridMarker, HotcueChip, PlaylistNode, Track, TrackCues
|
||||
from ...core.pathmap import PathMapping, common_dir_prefix
|
||||
from ...core.query import TrackIndex
|
||||
from ..rekordbox import palette
|
||||
from ..rekordbox import memory_palette, palette
|
||||
from ..rekordbox.cue_types import WRITABLE_CUE_TYPES
|
||||
from ...exporter import MANIFEST_NAME
|
||||
from . import capabilities as caps
|
||||
@@ -457,10 +457,8 @@ class OneLibraryAdapter:
|
||||
) -> TrackCues:
|
||||
self._require_writable("Editing cues")
|
||||
if role != "hotcue":
|
||||
# Preserved-but-uneditable, exactly as in the Rekordbox adapter.
|
||||
raise Unsupported(
|
||||
"Memory cues are shown but cannot be edited — only hot cues are writable"
|
||||
)
|
||||
# A memory cue has no slot to set; it has its own commands.
|
||||
raise InvalidCommand("Memory cues are added with add_memory_cue, not set_cue")
|
||||
self._check_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)
|
||||
@@ -494,6 +492,53 @@ class OneLibraryAdapter:
|
||||
self._store.place_cues(track_id, cues, overwrite=overwrite)
|
||||
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 -----------------------------------------------
|
||||
@staticmethod
|
||||
def _markers_from(markers: list) -> list:
|
||||
|
||||
@@ -36,8 +36,8 @@ from ...core.capabilities import (
|
||||
SaveCapabilities,
|
||||
TrackCapabilities,
|
||||
)
|
||||
from ..rekordbox import palette
|
||||
from ..rekordbox.cue_types import WRITABLE_CUE_TYPES
|
||||
from ..rekordbox import memory_palette, palette
|
||||
from ..rekordbox.cue_types import MAX_MEMORY_CUES, WRITABLE_CUE_TYPES
|
||||
|
||||
# Pads A-H. Unlike `djmdCue.Kind`, the ANLZ slot number is a dense 1-based index,
|
||||
# so the bank really is 1..8 (see `cues.py`).
|
||||
@@ -61,10 +61,12 @@ def capabilities_for(
|
||||
editable=True,
|
||||
hotcue_slots=HOTCUE_SLOTS,
|
||||
slot_labels="letter",
|
||||
# OneLibrary carries memory cues, as Rekordbox does: projected and
|
||||
# preserved, NOT editable (the two-platform rule, as in Rekordbox).
|
||||
# Memory cues, editable as in Rekordbox — in the ANLZ files, the
|
||||
# way rekordbox 7 edits them on a stick (measured, kit M2).
|
||||
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,
|
||||
color="palette",
|
||||
palette=[palette.hex_for(code) for code in palette.SWATCHES],
|
||||
|
||||
@@ -37,7 +37,7 @@ from __future__ import annotations
|
||||
import logging
|
||||
|
||||
from ...core.model import CuePoint
|
||||
from ..rekordbox import palette
|
||||
from ..rekordbox import memory_palette, palette
|
||||
|
||||
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
|
||||
|
||||
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(
|
||||
name=(str(comment) or None) if comment else None,
|
||||
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,
|
||||
length=length,
|
||||
slot=slot,
|
||||
color=_color(entry) if with_color else None,
|
||||
# Hot cues are editable on a drive opened for editing (the caller says
|
||||
# so). MEMORY cues never are — preserved-but-uneditable, as in the
|
||||
# Rekordbox adapter (the two-platform rule).
|
||||
editable=editable and role == "hotcue",
|
||||
readonly_reason=None if editable and role == "hotcue" else "platform_managed",
|
||||
color=color,
|
||||
# Editable on a drive opened for editing (the caller says so), memory
|
||||
# cues included; browsing a device is read-only.
|
||||
editable=editable,
|
||||
readonly_reason=None if editable else "platform_managed",
|
||||
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:
|
||||
"""Every entry of every `tag_type` tag in one parsed ANLZ file.
|
||||
|
||||
|
||||
@@ -44,7 +44,8 @@ from pathlib import Path
|
||||
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
|
||||
from ...core.cue_colors import effective_color
|
||||
from ..rekordbox import anlz_writer as W
|
||||
from ..rekordbox import artwork, palette, timebase
|
||||
from ..rekordbox import artwork, memory_palette, palette, timebase
|
||||
from ..rekordbox.cue_types import MAX_MEMORY_CUES
|
||||
from ..rekordbox.beatgrid import beats_from_markers
|
||||
from ..rekordbox.projection import render_key
|
||||
from .capabilities import capabilities_for
|
||||
@@ -359,15 +360,29 @@ class OneLibraryExporter:
|
||||
too far along.
|
||||
"""
|
||||
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
|
||||
# A hot cue carries 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. A
|
||||
# memory cue keeps rekordbox's own "unset".
|
||||
code, rgb = palette.code_for(cue.color if cue.role == "memory" else effective_color(cue))
|
||||
is_memory = cue.role == "memory" or cue.slot is None
|
||||
if is_memory:
|
||||
# rekordbox keeps 10 (earliest first; the rest are dropped, per
|
||||
# the lossiness rule). A memory cue's colour is PCP2 byte 28 from
|
||||
# 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({
|
||||
"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,
|
||||
"time_ms": int(round(timebase.to_pioneer(cue.start, 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
|
||||
@@ -114,7 +114,7 @@ def to_track_cues(cues: list, grid_markers: list[GridMarker]) -> TrackCues:
|
||||
|
||||
`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.
|
||||
Nothing here is editable: a OneLibrary drive is read-only in Konduktor, and
|
||||
`capabilities.writable` says so at the library level.
|
||||
Each cue already says whether it is editable (the store knows whether the
|
||||
drive was opened for editing or is only being browsed).
|
||||
"""
|
||||
return TrackCues(grid_markers=grid_markers, grid_locked=False, cues=list(cues))
|
||||
@@ -54,8 +54,9 @@ from ...core.edit_journal import EditJournal
|
||||
from ...core.grid_edit import ReplaceGridCommands
|
||||
from ...core.model import CuePoint
|
||||
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.cue_types import MAX_MEMORY_CUES
|
||||
from ..rekordbox import anlz_writer as W
|
||||
from ..rekordbox import beatgrid as rb_beatgrid
|
||||
from .layout import DriveLayout
|
||||
@@ -916,6 +917,60 @@ class OneLibraryStore(ReplaceGridCommands):
|
||||
self._replace_hot(track_id, hot, None, None)
|
||||
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]:
|
||||
"""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}
|
||||
|
||||
@@ -27,7 +27,7 @@ from ...core.model import GridMarker, PlaylistNode, Track, TrackCues
|
||||
from ...core.pathmap import PathMapping, common_dir_prefix
|
||||
from ...core.query import TrackIndex
|
||||
from . import capabilities as caps
|
||||
from . import palette, projection, timebase
|
||||
from . import memory_palette, palette, projection, timebase
|
||||
from ...core import add_analysis
|
||||
from .store import RekordboxStore
|
||||
|
||||
@@ -303,12 +303,8 @@ class RekordboxAdapter:
|
||||
) -> TrackCues:
|
||||
self._require_writable("Editing cues")
|
||||
if role != "hotcue":
|
||||
# Rekordbox is the ONLY platform with memory cues, so under the
|
||||
# two-platform promotion rule they stay preserved-but-uneditable:
|
||||
# they are projected and shown, never written.
|
||||
raise Unsupported(
|
||||
"Memory cues are shown but cannot be edited — only hot cues are writable"
|
||||
)
|
||||
# A memory cue has no slot to set; it has its own commands.
|
||||
raise InvalidCommand("Memory cues are added with add_memory_cue, not set_cue")
|
||||
self._check_cue_type(cue_type)
|
||||
self._store.set_cue(
|
||||
track_id, slot=slot, start_sec=start_sec, cue_type=cue_type,
|
||||
@@ -339,6 +335,53 @@ class RekordboxAdapter:
|
||||
self._store.delete_cue(track_id, slot)
|
||||
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:
|
||||
self._require_writable("Placing cues")
|
||||
for cue in cues:
|
||||
@@ -521,20 +564,25 @@ class RekordboxAdapter:
|
||||
|
||||
def _place_imported_cues(self, track_id: str, cues) -> None:
|
||||
"""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()
|
||||
memory = 0
|
||||
for cue in sorted(cues.cues or [], key=lambda c: c.start):
|
||||
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,
|
||||
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
|
||||
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)
|
||||
else:
|
||||
self._store.add_memory_cue(track_id, **common)
|
||||
elif memory < self._store.MAX_MEMORY_CUES:
|
||||
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:
|
||||
# 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_blue: int | None = None
|
||||
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]:
|
||||
@@ -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:]
|
||||
|
||||
|
||||
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:
|
||||
"""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),
|
||||
@@ -245,7 +277,8 @@ def _pco2(data: bytes) -> list[CueEntry]:
|
||||
hot_cue, = struct.unpack_from(">I", data, off + 12)
|
||||
kind = data[off + 16]
|
||||
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:
|
||||
e.loop_numerator, e.loop_denominator, len_comment = struct.unpack_from(">HHI", data, off + 36)
|
||||
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,
|
||||
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.
|
||||
|
||||
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
|
||||
one, so that detail is documented rather than measured. The entry stays the
|
||||
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""
|
||||
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",
|
||||
b"PCP2", 16, length, hot_cue, kind, 1000,
|
||||
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
|
||||
# (`palette`); a code of 0 draws its default colour whatever the RGB says.
|
||||
) + 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:
|
||||
"""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:
|
||||
return pcob_tag(cue_type, [
|
||||
entries = [
|
||||
pcpt_entry(hot_cue=c["hot_cue"], kind=c["kind"], time_ms=c["time_ms"],
|
||||
loop_ms=c["loop_ms"])
|
||||
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:
|
||||
return pco2_tag(cue_type, [
|
||||
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"),
|
||||
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
|
||||
])
|
||||
|
||||
|
||||
@@ -30,8 +30,8 @@ from ...core.capabilities import (
|
||||
SaveCapabilities,
|
||||
TrackCapabilities,
|
||||
)
|
||||
from . import palette
|
||||
from .cue_types import WRITABLE_CUE_TYPES
|
||||
from . import memory_palette, palette
|
||||
from .cue_types import MAX_MEMORY_CUES, WRITABLE_CUE_TYPES
|
||||
|
||||
# Rekordbox's addressable hot cue bank. The pads are labelled A-H; the stored
|
||||
# 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,
|
||||
readonly_cause="cloud_synced" if cloud_synced else None,
|
||||
cues=CueCapabilities(
|
||||
# Hot cues are writable: djmdCue rows plus the contentCue JSON
|
||||
# mirror, kept in step. MEMORY cues stay preserved-but-uneditable —
|
||||
# Rekordbox is the only platform that has them, and the two-platform
|
||||
# promotion rule says a one-platform concept does not become an
|
||||
# editing feature.
|
||||
# Hot AND memory cues are writable: djmdCue rows plus the
|
||||
# contentCue JSON mirror, kept in step (memory cues: measured
|
||||
# 2026-10-16, kit M1).
|
||||
editable=True,
|
||||
hotcue_slots=HOTCUE_SLOTS,
|
||||
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,
|
||||
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.
|
||||
types=WRITABLE_CUE_TYPES,
|
||||
# A hot cue's colour is one of rekordbox's 16 swatches (all
|
||||
|
||||
@@ -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
|
||||
|
||||
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.
|
||||
CUE_TYPES = ["cue", "loop"]
|
||||
|
||||
@@ -58,7 +58,7 @@ from sqlalchemy import text
|
||||
|
||||
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
|
||||
from ...core.cue_colors import effective_color
|
||||
from . import new_content, palette
|
||||
from . import memory_palette, new_content, palette
|
||||
from . import timebase
|
||||
from .beatgrid import beats_from_markers
|
||||
from .capabilities import capabilities_for
|
||||
@@ -199,24 +199,31 @@ class RekordboxExporter:
|
||||
from .adapter import RekordboxAdapter
|
||||
|
||||
adapter = RekordboxAdapter(library)
|
||||
# The store, not the adapter's commands: the adapter refuses memory cues
|
||||
# (editing them in a user's library is off-limits) and takes no colour.
|
||||
# Building a NEW library is neither an edit nor lossy by choice, so the
|
||||
# exporter writes both — through the same `_write_cue` every edit uses.
|
||||
# The store, not the adapter's commands: the adapter's set_cue takes no
|
||||
# colour and its memory-cue command takes only a swatch. A NEW library
|
||||
# maps any source colour to the nearest one instead — through the same
|
||||
# `_write_cue` every edit uses.
|
||||
store = adapter._store
|
||||
try:
|
||||
for item in payload.tracks:
|
||||
track_id = ids.get(item.source_id)
|
||||
if track_id is None or not item.cues:
|
||||
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:
|
||||
# rekordbox's own "unset" for a memory cue with no colour.
|
||||
code, _rgb = palette.code_for(cue.color)
|
||||
# rekordbox keeps 10 (earliest first; the rest are
|
||||
# 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(
|
||||
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
|
||||
# What Konduktor SHOWS — stored colour, else the type's (blue
|
||||
# cue, green loop) — as a palette code, which is what
|
||||
|
||||
@@ -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.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
|
||||
from . import beatgrid, palette, timebase
|
||||
from .cue_types import cue_type, role_and_slot
|
||||
from . import beatgrid, memory_palette, palette, timebase
|
||||
from .cue_types import cue_type, kind_for, role_and_slot
|
||||
|
||||
# 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
|
||||
@@ -140,10 +140,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
|
||||
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
|
||||
under the two-platform promotion rule they are shown and never written. A cue
|
||||
sitting on the reserved `Kind` occupies no pad and is projected the same way,
|
||||
because that is how Rekordbox itself displays one.
|
||||
So is every memory cue (`Kind` 0), addressed by its row id (`CuePoint.id`)
|
||||
since it has no pad. A cue sitting on the reserved `Kind` 4 occupies no pad
|
||||
either and is SHOWN as a memory cue, because that is how Rekordbox itself
|
||||
displays one — but it is not one, so it is not editable.
|
||||
"""
|
||||
markers: list[GridMarker] = []
|
||||
if grid is not None:
|
||||
@@ -158,7 +158,9 @@ def to_track_cues(cue_rows: list, grid: tuple | None, time_offset: float = 0.0)
|
||||
length = 0.0
|
||||
if out_msec is not None and out_msec > 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(
|
||||
CuePoint(
|
||||
name=(getattr(c, "Comment", None) or None),
|
||||
@@ -169,15 +171,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),
|
||||
length=length,
|
||||
slot=slot,
|
||||
color=_cue_color(c),
|
||||
color=_memory_cue_color(c) if memory else _cue_color(c),
|
||||
editable=editable,
|
||||
readonly_reason=None if editable else "platform_managed",
|
||||
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)
|
||||
|
||||
|
||||
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:
|
||||
"""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."""
|
||||
|
||||
@@ -47,8 +47,8 @@ from ...core.adapter import (
|
||||
from ...core.edit_journal import EditJournal
|
||||
from ...core.grid_edit import ReplaceGridCommands
|
||||
from ...core.pathmap import PathMapping, stored_form
|
||||
from . import timebase
|
||||
from .cue_types import beat_loop_size, kind_for, role_and_slot
|
||||
from . import memory_palette, timebase
|
||||
from .cue_types import MAX_MEMORY_CUES, beat_loop_size, kind_for, role_and_slot
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
@@ -1147,6 +1147,25 @@ class RekordboxStore(ReplaceGridCommands):
|
||||
)
|
||||
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(
|
||||
self,
|
||||
track_id: str,
|
||||
@@ -1156,23 +1175,59 @@ class RekordboxStore(ReplaceGridCommands):
|
||||
length_sec: float = 0.0,
|
||||
name: str | None = None,
|
||||
color_code: int | None = None,
|
||||
enforce_cap: bool = True,
|
||||
) -> 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
|
||||
stays refused under the two-platform promotion rule. A new export is not
|
||||
an edit, and dropping the source's memory cues would lose prep.
|
||||
`color_code` is a 0-based `memory_palette` code — NOT a hot-cue palette
|
||||
code: a memory cue keeps its colour in `Color`, not `ColorTableIndex`.
|
||||
`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(
|
||||
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,
|
||||
)
|
||||
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,
|
||||
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
|
||||
`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:
|
||||
raise InvalidCommand("A cue cannot be before the start of the track")
|
||||
row = self.content(track_id)
|
||||
@@ -1217,8 +1272,13 @@ class RekordboxStore(ReplaceGridCommands):
|
||||
cue.BeatLoopSize = None
|
||||
cue.ActiveLoop = None
|
||||
cue.CueMicrosec = None
|
||||
self._apply_color(cue, color_code, is_loop)
|
||||
cue.Comment = name or None
|
||||
if kind == kind_for("memory", 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._sync_content_cue(track_id)
|
||||
@@ -1240,6 +1300,21 @@ class RekordboxStore(ReplaceGridCommands):
|
||||
cue.Color = -1
|
||||
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:
|
||||
"""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."""
|
||||
@@ -1308,11 +1383,13 @@ class RekordboxStore(ReplaceGridCommands):
|
||||
"""
|
||||
t = self._tables
|
||||
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 = (
|
||||
self._db.session.query(t.DjmdCue)
|
||||
.filter(t.DjmdCue.ContentID == str(track_id))
|
||||
.filter(t.DjmdCue.rb_local_deleted == 0)
|
||||
.order_by(t.DjmdCue.InMsec)
|
||||
.order_by(text("djmdCue.rowid"))
|
||||
.all()
|
||||
)
|
||||
fields = (
|
||||
|
||||
@@ -234,6 +234,22 @@ class RemoteAdapter:
|
||||
def place_cues(self, track_id, cues, *, overwrite=False):
|
||||
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):
|
||||
return self._call("add_grid_marker", track_id=track_id, start_sec=start_sec, bpm=bpm)
|
||||
|
||||
|
||||
@@ -197,10 +197,11 @@ class TraktorAdapter:
|
||||
Lossiness follows the settled rule — degrade to the nearest equivalent,
|
||||
drop only where none exists:
|
||||
|
||||
* **Memory cues become hot cues in spare slots.** Traktor has no
|
||||
memory cues, and every Traktor cue occupies a slot. Filling the
|
||||
leftovers preserves the positions a DJ actually marked; when the
|
||||
bank is full the rest are dropped, because there is nowhere left.
|
||||
* **Memory cues stay memory cues** — Traktor's cues on no pad
|
||||
(HOTCUE="-1"), decided 2026-10-16 once Traktor was measured keeping
|
||||
them. They used to be promoted to spare pads.
|
||||
* **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
|
||||
type, so a free RGB value has nowhere to go.
|
||||
|
||||
@@ -250,29 +251,43 @@ class TraktorAdapter:
|
||||
self._place_imported_cue(track_id, cue.slot, cue)
|
||||
taken.add(cue.slot)
|
||||
|
||||
# Everything without a pad of its own competes for what is left: memory
|
||||
# cues, which Traktor has no equivalent for, and any hot cue whose pad
|
||||
# was already occupied. Earliest first, so that when the bank runs out
|
||||
# it is the late cues that are lost rather than an arbitrary set — and
|
||||
# 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"]
|
||||
# A hot cue whose pad was taken (or is past the bank) moves to a spare
|
||||
# pad, earliest first, because muscle memory is most of what a hot cue
|
||||
# layout is; once the bank is full it becomes a memory cue rather than
|
||||
# being lost. Memory cues cross as memory cues.
|
||||
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)
|
||||
if slot is None:
|
||||
break # bank full: the rest are dropped, per the lossiness rule
|
||||
self._place_imported_cue(track_id, slot, cue)
|
||||
self._place_imported_memory_cue(track_id, 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:
|
||||
cue_type = "loop" if getattr(cue, "length", 0) else "cue"
|
||||
if cue_type not in CUE_TYPE_TO_NATIVE:
|
||||
return
|
||||
self.set_cue(
|
||||
track_id,
|
||||
slot=slot,
|
||||
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,
|
||||
name=getattr(cue, "name", None),
|
||||
)
|
||||
@@ -296,8 +311,8 @@ class TraktorAdapter:
|
||||
name: str | None = None,
|
||||
) -> TrackCues:
|
||||
if role != "hotcue":
|
||||
# Memory cues are a Rekordbox concept; every Traktor cue holds a slot.
|
||||
raise Unsupported("Traktor cues always occupy a hotcue slot")
|
||||
# A memory cue has no slot to set; it has its own commands.
|
||||
raise InvalidCommand("Memory cues are added with add_memory_cue, not set_cue")
|
||||
with _translate():
|
||||
self._store.set_hotcue(
|
||||
track_id, slot, start_sec, self._native_cue_type(cue_type), length_sec, name
|
||||
@@ -318,6 +333,45 @@ class TraktorAdapter:
|
||||
self._store.delete_hotcue(track_id, slot)
|
||||
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:
|
||||
native = [
|
||||
SimpleNamespace(
|
||||
|
||||
@@ -46,8 +46,11 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
|
||||
editable=True,
|
||||
hotcue_slots=8,
|
||||
slot_labels="number",
|
||||
# Traktor has no memory cues — every cue occupies a bank slot.
|
||||
memory_cues=False,
|
||||
# Memory cues are CUE_V2s on no pad (HOTCUE="-1"), any type, no
|
||||
# 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,
|
||||
# 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.
|
||||
|
||||
@@ -175,6 +175,43 @@ def to_track(e) -> Track:
|
||||
)
|
||||
|
||||
|
||||
#: 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:
|
||||
"""Project an ENTRY's beatgrid + cues.
|
||||
|
||||
@@ -200,20 +237,30 @@ def to_track_cues(entry, offset_ms: float = 0.0) -> TrackCues:
|
||||
)
|
||||
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 = []
|
||||
for c in entry.cue_v2 or []:
|
||||
for c, memory_id in with_memory_ids(entry):
|
||||
if getattr(c, "grid", None) is not None:
|
||||
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))
|
||||
slot = c.hotcue if c.hotcue is not None and c.hotcue >= 0 else None
|
||||
cues.append(
|
||||
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:
|
||||
# preserving a cue we cannot name beats hiding it from the user.
|
||||
type=NATIVE_TO_CUE_TYPE.get(c.type, "cue"),
|
||||
# Every Traktor cue lives in the hotcue bank.
|
||||
role="hotcue",
|
||||
# A cue on no pad (HOTCUE="-1") is a memory cue.
|
||||
role="hotcue" if slot is not None else "memory",
|
||||
start=timebase.from_traktor_ms(c.start or 0.0, offset_ms),
|
||||
length=(c.len or 0.0) / 1000.0,
|
||||
slot=slot,
|
||||
@@ -221,6 +268,7 @@ def to_track_cues(entry, offset_ms: float = 0.0) -> TrackCues:
|
||||
editable=True,
|
||||
readonly_reason=None,
|
||||
grid_marker=marker,
|
||||
id=memory_id,
|
||||
)
|
||||
)
|
||||
return TrackCues(
|
||||
|
||||
@@ -56,7 +56,7 @@ from ...schemas import PlaylistNode
|
||||
from . import beatgrid, timebase
|
||||
from .locations import os_path_to_location, resolve_path
|
||||
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
|
||||
# this email is what makes the stars show up in Traktor itself.
|
||||
@@ -770,21 +770,7 @@ class TraktorStore:
|
||||
if name is not None:
|
||||
existing.name = name
|
||||
else:
|
||||
if entry.cue_v2 is None:
|
||||
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,
|
||||
)
|
||||
)
|
||||
self._insert_cue(entry, self._new_cue(cue_type, start_ms, len_ms, slot, name))
|
||||
# "add" only when it's a genuinely new hotcue; repositioning/retyping
|
||||
# an existing slot is a "modify" (keeps the net add/remove count honest).
|
||||
self._note(
|
||||
@@ -816,6 +802,87 @@ class TraktorStore:
|
||||
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:
|
||||
"""Change the type of the existing hotcue in `slot` (keeps its position)."""
|
||||
if cue_type not in self.POINT_CUE_TYPES:
|
||||
|
||||
@@ -318,6 +318,29 @@ class LibraryAdapter(Protocol):
|
||||
def delete_cue(self, track_id: str, slot: int) -> 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 ---------------------------------------------
|
||||
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: ...
|
||||
|
||||
@@ -45,10 +45,17 @@ class CueCapabilities(BaseModel):
|
||||
editable: bool = False
|
||||
hotcue_slots: int = 8 # size of the addressable bank; 0 = no bank
|
||||
slot_labels: Literal["number", "letter"] = "number"
|
||||
# Memory cues are Rekordbox-only today, so they are modelled and PRESERVED
|
||||
# but not editable anywhere yet (the two-platform promotion rule).
|
||||
# Cues on no pad, listed in time order and called CDJ-style (decided
|
||||
# 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
|
||||
# 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
|
||||
# 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"]
|
||||
color: Literal["none", "free", "palette"] = "none"
|
||||
palette: list[str] = []
|
||||
|
||||
@@ -25,9 +25,8 @@ MEMORY_COLOR = "#9AA1B2" # grey
|
||||
|
||||
|
||||
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:
|
||||
return cue.color.upper()
|
||||
if cue.role == "memory":
|
||||
return MEMORY_COLOR
|
||||
return TYPE_COLORS.get(cue.type, MEMORY_COLOR)
|
||||
@@ -167,21 +167,23 @@ class EditJournal:
|
||||
else:
|
||||
parts.append(f"{verb} {len(names)} {noun}s")
|
||||
|
||||
# --- hotcues: net change in count, scoped by how many tracks were touched ---
|
||||
hc_add = hc_del = 0
|
||||
hc_tracks: set[str] = set()
|
||||
# --- cues: net change in count, scoped by how many tracks were touched.
|
||||
# Memory cues (detail "memory") are counted apart from hotcues, so a
|
||||
# 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_del: set[str] = set()
|
||||
lock_on: set[str] = set()
|
||||
lock_off: set[str] = set()
|
||||
for c in self.changes:
|
||||
if c.scope == "cue":
|
||||
bucket = counts["memory cue" if c.detail == "memory" else "hotcue"]
|
||||
if c.target:
|
||||
hc_tracks.add(c.target)
|
||||
bucket[2].add(c.target)
|
||||
if c.op == "add":
|
||||
hc_add += 1
|
||||
bucket[0] += 1
|
||||
elif c.op == "delete":
|
||||
hc_del += 1
|
||||
bucket[1] += 1
|
||||
elif c.scope == "grid":
|
||||
# "delete" is the ONLY deletion op. Everything else — including
|
||||
# ops added later — counts as an edit, because mis-labelling an
|
||||
@@ -190,15 +192,17 @@ class EditJournal:
|
||||
elif c.scope == "lock":
|
||||
(lock_on if c.op == "on" else lock_off).add(c.target or "")
|
||||
|
||||
if hc_tracks:
|
||||
net = hc_add - hc_del
|
||||
scope = f" across {tracks(len(hc_tracks))}" if len(hc_tracks) > 1 else ""
|
||||
for noun, (added, deleted, touched) in counts.items():
|
||||
if not touched:
|
||||
continue
|
||||
net = added - deleted
|
||||
scope = f" across {tracks(len(touched))}" if len(touched) > 1 else ""
|
||||
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:
|
||||
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)
|
||||
parts.append(f"adjusted hotcues{scope}")
|
||||
parts.append(f"adjusted {noun}s{scope}")
|
||||
|
||||
# --- beatgrids & lock: per-track counts ---
|
||||
if grid_edit:
|
||||
|
||||
@@ -144,8 +144,8 @@ PlaylistNode.model_rebuild()
|
||||
class CuePoint(BaseModel):
|
||||
name: str | None = None
|
||||
type: CueType = "cue"
|
||||
# "memory" cues have no bank slot. Only Rekordbox has them, so they are
|
||||
# modelled and preserved but not yet editable anywhere.
|
||||
# A "memory" cue has no bank slot: Rekordbox's / OneLibrary's memory cues,
|
||||
# Traktor's cues on no pad (HOTCUE="-1"). Addressed by `id`, not `slot`.
|
||||
role: CueRole = "hotcue"
|
||||
start: float # seconds
|
||||
length: float # seconds (>0 for loops)
|
||||
@@ -158,6 +158,10 @@ class CuePoint(BaseModel):
|
||||
# Index of the grid marker this cue mirrors, where the platform pairs them.
|
||||
# A display hint only; None on platforms that do not.
|
||||
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):
|
||||
|
||||
@@ -102,6 +102,10 @@ from .schemas import (
|
||||
SetCue,
|
||||
SetCueColor,
|
||||
SetCueType,
|
||||
AddMemoryCue,
|
||||
RenameMemoryCue,
|
||||
SetMemoryCueColor,
|
||||
SetMemoryCueType,
|
||||
SetGridLock,
|
||||
Stats,
|
||||
Track,
|
||||
@@ -1842,6 +1846,45 @@ def delete_cue(track_id: str, slot: int) -> TrackCues:
|
||||
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)
|
||||
def add_grid_marker(body: AddGridMarker) -> TrackCues:
|
||||
"""Add a beatgrid marker. Omitting `bpm` inherits the governing tempo."""
|
||||
|
||||
@@ -36,7 +36,9 @@ from .core.model import AutoHotcue, Track, TrackCues
|
||||
#: method, the major for anything an older client would misread.
|
||||
#: 1.1 — `move_playlist` (sidebar drag and drop).
|
||||
#: 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`.
|
||||
API_VERSION: tuple[int, int] = (1, 3)
|
||||
|
||||
#: 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
|
||||
@@ -76,7 +78,8 @@ _READ = (
|
||||
_MUTATING = (
|
||||
"create_playlist", "create_folder", "rename_playlist", "delete_playlist",
|
||||
"move_playlist", "set_playlist_entries", "remove_tracks", "set_track_metadata", "set_key", "set_cue",
|
||||
"set_cue_type", "set_cue_color", "delete_cue", "place_cues", "add_grid_marker",
|
||||
"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",
|
||||
"set_analysed_grid", "delete_grid", "set_grid_lock", "add_tracks",
|
||||
)
|
||||
|
||||
@@ -200,6 +200,33 @@ class SetCueColor(BaseModel):
|
||||
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):
|
||||
# None = this computer's default engine; "windows-x64-cuda" to take the GPU one.
|
||||
target: str | None = None
|
||||
|
||||
@@ -14,5 +14,5 @@ Pillow>=11 # a Rekordbox add writes the cover's artwork files
|
||||
dulwich>=0.22 # version history, beside the library
|
||||
platformdirs>=4.0
|
||||
# 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
|
||||
@@ -24,7 +24,7 @@ scikit-learn>=1.5
|
||||
# what it had: pyrekordbox renamed `devicelib_plus` to `onelibrary` upstream,
|
||||
# every local test passed, and the released app could not export or read a
|
||||
# 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
|
||||
# files). Both ship prebuilt Python 3.14 wheels — no Rust/OpenSSL source build.
|
||||
#
|
||||
|
||||
@@ -236,7 +236,10 @@ def _real_cue_tags(path: Path) -> list[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":
|
||||
return tag
|
||||
out, off = bytearray(tag), struct.unpack(">I", tag[4:8])[0]
|
||||
@@ -244,6 +247,7 @@ def _mask_colour(tag: bytes) -> bytes:
|
||||
length = struct.unpack(">I", tag[off + 8:off + 12])[0]
|
||||
at = off + 44 + struct.unpack(">I", tag[off + 40:off + 44])[0]
|
||||
out[at:at + 4] = bytes(4)
|
||||
out[off + 28] = 0
|
||||
off += length
|
||||
return bytes(out)
|
||||
|
||||
@@ -424,6 +428,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
|
||||
# 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.
|
||||
from konduktor.adapters.rekordbox import anlz_file as A_ # noqa: E402
|
||||
from konduktor.adapters.rekordbox import palette # noqa: E402
|
||||
|
||||
check("a measured swatch keeps its exact code and RGB",
|
||||
@@ -451,6 +456,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",
|
||||
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 ==")
|
||||
# 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
|
||||
@@ -581,7 +615,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 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 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",
|
||||
mirror is not None and mirror[0].count('"Kind"') == 4 and '"ColorTableIndex": 22' in mirror[0].replace(":22", ": 22"),
|
||||
mirror and mirror[0][:200])
|
||||
|
||||
+34
-14
@@ -139,15 +139,29 @@ check("every hot cue keeps the pad it was on",
|
||||
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)
|
||||
|
||||
# Traktor has no memory cues, so they degrade into spare pads rather than being
|
||||
# dropped — the settled lossiness rule.
|
||||
# Memory cues cross AS memory cues — Traktor's cues on no pad (HOTCUE="-1"),
|
||||
# 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")
|
||||
check("memory cues are preserved in spare slots, not dropped",
|
||||
len(got.cues) == len(src_hot) + n_memory, f"{len(got.cues)} cues")
|
||||
check("and they do not overwrite a hot cue",
|
||||
len({c.slot for c in got.cues}) == len(got.cues))
|
||||
check("every imported cue occupies a real pad",
|
||||
all(c.role == "hotcue" and c.slot is not None for c in got.cues))
|
||||
padless = [c for c in dest._store.model_entry(ids[0]).cue_v2
|
||||
if c.grid is None and c.hotcue == -1]
|
||||
check("every memory cue is written as a memory cue (a CUE_V2 on no pad)",
|
||||
len(padless) == n_memory and n_memory > 0, f"{len(padless)} of {n_memory}")
|
||||
check("and no extra pad is taken",
|
||||
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
|
||||
# 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)],
|
||||
cues=[CuePoint(type="cue", role="hotcue", start=float(i), length=0.0, slot=i)
|
||||
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(
|
||||
track=Track(id="ignored", title="Crowded", bpm=120.0),
|
||||
@@ -238,11 +254,15 @@ crowded_id = dest2.add_tracks([NewTrack(
|
||||
cues=many,
|
||||
)])[0]
|
||||
crowded = dest2.track_cues(crowded_id)
|
||||
check("the bank is filled but not overflowed", len(crowded.cues) == 8, str(len(crowded.cues)))
|
||||
check("the hot cues are the ones that survived",
|
||||
sorted(c.slot for c in crowded.cues) == list(range(8)))
|
||||
check("the memory cue that would not fit is dropped, not misplaced",
|
||||
all(c.start < 99.0 for c in crowded.cues))
|
||||
crowded_hot = [c for c in crowded.cues if c.role == "hotcue"]
|
||||
check("the bank is filled but not overflowed", len(crowded_hot) == 8, str(len(crowded_hot)))
|
||||
check("the hot cues keep their own pads",
|
||||
sorted(c.slot for c in crowded_hot) == list(range(8))
|
||||
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 ==")
|
||||
# A source is a library read FROM, open alongside the loaded one. The whole slot
|
||||
|
||||
@@ -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("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("on an editable drive every hot cue is editable, no memory cue is",
|
||||
all(c.editable == (c.role == "hotcue") for c in cues.cues))
|
||||
check("on an editable drive every cue is editable, memory cues included",
|
||||
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)
|
||||
check("on a browsing drive no cue is editable",
|
||||
all(not c.editable for c in _browse.track_cues(one.id).cues))
|
||||
|
||||
@@ -131,8 +131,8 @@ dat = dat_of(a, TRACK_1)
|
||||
ext = dat.with_suffix(".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"}
|
||||
check("hot cues are editable, memory cues are not",
|
||||
all(c.editable == (c.role == "hotcue") for c in a.track_cues(TRACK_1).cues))
|
||||
check("hot cues and memory cues are editable on a drive opened for editing",
|
||||
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_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("a pad beyond the bank is refused",
|
||||
_raises(lambda: a.set_cue(TRACK_1, slot=8, start_sec=1.0, cue_type="cue"), InvalidCommand))
|
||||
check("memory cues are not editable",
|
||||
_raises(lambda: a.set_cue(TRACK_1, slot=0, start_sec=1.0, cue_type="cue", role="memory"), Unsupported))
|
||||
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"), InvalidCommand))
|
||||
check("a colour must be one of rekordbox's swatches",
|
||||
_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"),
|
||||
@@ -256,6 +256,127 @@ check("a 44-byte compact entry has no colour bytes to patch",
|
||||
/ "nemean.EXT", "PCO2", A.LIST_MEMORY)))[-1],
|
||||
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("RESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -216,8 +216,9 @@ with tempfile.TemporaryDirectory() as d:
|
||||
# writable hot cue with a padlock.
|
||||
check("ordinary hot cues are editable",
|
||||
all(c.editable for c in tc.cues if c.role == "hotcue" and c.type != "loop"))
|
||||
check("memory cues are preserved but not editable",
|
||||
all(not c.editable for c in tc.cues if c.role == "memory"))
|
||||
check("memory cues are editable and addressed by id",
|
||||
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",
|
||||
all(c.editable for c in tc.cues if c.type == "loop" and c.role == "hotcue"))
|
||||
check("an uneditable cue always says why",
|
||||
@@ -427,11 +428,10 @@ with tempfile.TemporaryDirectory() as d:
|
||||
check("a Traktor-only cue type is Unsupported",
|
||||
_raises(lambda: adapter.set_cue(cue_track.id, slot=2, start_sec=1.0,
|
||||
cue_type="fade_in"), Unsupported))
|
||||
# Rekordbox is the ONLY platform with memory cues, so they stay
|
||||
# preserved-but-uneditable under the two-platform promotion rule.
|
||||
check("memory cues are shown but not writable",
|
||||
# A memory cue has no slot; set_cue is for pads only.
|
||||
check("set_cue refuses role=memory (memory cues have their own commands)",
|
||||
_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.
|
||||
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]
|
||||
|
||||
@@ -97,6 +97,14 @@ def diff(before: dict, after: dict, ignore_columns=("updated_at", "created_at"))
|
||||
return changes
|
||||
|
||||
|
||||
def _raises(fn, exc) -> bool:
|
||||
try:
|
||||
fn()
|
||||
except exc:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def describe(changes) -> str:
|
||||
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)}")
|
||||
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 ---------------------
|
||||
print("== H: a beatgrid write is localized to the .DAT's PQTZ tag ==")
|
||||
from pyrekordbox.anlz import AnlzFile
|
||||
|
||||
@@ -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"})
|
||||
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])
|
||||
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)
|
||||
versions = len(history.list_history(work))
|
||||
r = c.post("/api/save").json()
|
||||
|
||||
@@ -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})
|
||||
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)
|
||||
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)]})
|
||||
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")
|
||||
|
||||
@@ -55,6 +55,14 @@ def playlist_block_span(data: bytes, uuid: str):
|
||||
return start, end
|
||||
|
||||
|
||||
def _raises_playlist(fn) -> bool:
|
||||
try:
|
||||
fn()
|
||||
except PlaylistError:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def tag_lines(b: bytes) -> list[str]:
|
||||
return b.replace(b"><", b">\n<").decode("utf-8", "replace").splitlines()
|
||||
|
||||
@@ -1191,5 +1199,147 @@ with tempfile.TemporaryDirectory() as d:
|
||||
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 < 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' "z"\"" 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("\nRESULT:", "FAILED" if failed else "ALL PASSED")
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -22,13 +22,21 @@ REAL = Path(__file__).resolve().parents[1] / "collection.nml"
|
||||
import traktor_nml_utils as tnu # 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.pathmap import PathMapping # noqa: E402
|
||||
|
||||
failed = False
|
||||
|
||||
|
||||
def _raises(fn, exc) -> bool:
|
||||
try:
|
||||
fn()
|
||||
except exc:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def check(label, cond, detail=""):
|
||||
global failed
|
||||
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)
|
||||
check("version read from the NML header", caps.version == "20", str(caps.version))
|
||||
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")
|
||||
# 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 == [])
|
||||
@@ -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")
|
||||
try:
|
||||
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")
|
||||
except Unsupported:
|
||||
check("memory cues are refused on Traktor", True)
|
||||
check("set_cue refuses role=memory (memory cues have their own commands)", False,
|
||||
"no error raised")
|
||||
except InvalidCommand:
|
||||
check("set_cue refuses role=memory (memory cues have their own commands)", True)
|
||||
try:
|
||||
adapter.set_cue_color(tid2, free, "#FF0000")
|
||||
check("cue colour is refused on Traktor", False, "no error raised")
|
||||
except Unsupported:
|
||||
check("cue colour is refused on Traktor", True)
|
||||
|
||||
# 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_before = len(adapter.track_cues(tid2).grid_markers)
|
||||
adapter.add_grid_marker(tid2, adapter.track_cues(tid2).grid_markers[0].start + 40.0)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"private": true,
|
||||
"version": "0.2.7",
|
||||
"version": "0.2.9",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
+18
-8
@@ -898,11 +898,16 @@ export default function App() {
|
||||
|
||||
// TrackTable retargets the selection to a right-clicked row outside it
|
||||
// before calling this, but that state update has not landed yet — so the
|
||||
// same rule is applied here to decide what the menu acts on.
|
||||
const openMenu = (track: Track, x: number, y: number, selectable: boolean) =>
|
||||
// same rule is applied here to decide what the menu acts on. The ids come
|
||||
// in the order the view shows them (Set Position can keep that order); a
|
||||
// selected track the view hides follows.
|
||||
const openMenu = (track: Track, x: number, y: number, selectable: boolean, viewIds: string[]) =>
|
||||
setMenu({
|
||||
track,
|
||||
ids: selectable && selected.has(track.id) ? [...selected] : [track.id],
|
||||
ids:
|
||||
selectable && selected.has(track.id)
|
||||
? [...new Set([...viewIds.filter((id) => selected.has(id)), ...selected])]
|
||||
: [track.id],
|
||||
x,
|
||||
y,
|
||||
})
|
||||
@@ -1321,6 +1326,7 @@ export default function App() {
|
||||
<SetPositionDialog
|
||||
order={tracks.map((t) => t.id)}
|
||||
ids={positioning}
|
||||
sorting={sorting}
|
||||
onMove={reorderPlaylist}
|
||||
onClose={() => setPositioning(null)}
|
||||
/>
|
||||
@@ -1444,6 +1450,10 @@ export default function App() {
|
||||
origin={prepOrigin}
|
||||
cuesRefresh={cuesRefresh}
|
||||
onPlayingChange={setDeckPlaying}
|
||||
// As the context menu's: a library that would refuse the save is
|
||||
// not offered the dialog, and a deck track outside the collection
|
||||
// (a device's, a loose file's) is not the collection's to edit.
|
||||
onEditTags={canEdit && prepOrigin === 'collection' ? setEditing : undefined}
|
||||
/>
|
||||
</CapabilitiesContext.Provider>
|
||||
</div>
|
||||
@@ -1603,7 +1613,7 @@ export default function App() {
|
||||
sorting={sorting}
|
||||
onSortingChange={setSorting}
|
||||
selection={{ selected, onChange: setSelected }}
|
||||
onRowContextMenu={(track, x, y) => openMenu(track, x, y, true)}
|
||||
onRowContextMenu={(track, x, y, viewIds) => openMenu(track, x, y, true, viewIds)}
|
||||
onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })}
|
||||
onPlay={playTrack}
|
||||
onEditField={canEdit ? editField : undefined}
|
||||
@@ -1644,7 +1654,7 @@ export default function App() {
|
||||
selection={{ selected, onChange: setSelected }}
|
||||
marked={{ ids: heldInFolder, title: 'Already in your collection' }}
|
||||
dragFrom={{ origin: 'folder' }}
|
||||
onRowContextMenu={(track, x, y) => openMenu(track, x, y, true)}
|
||||
onRowContextMenu={(track, x, y, viewIds) => openMenu(track, x, y, true, viewIds)}
|
||||
onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })}
|
||||
onPlay={playTrack}
|
||||
onEditField={canEdit ? folderEditField : undefined}
|
||||
@@ -1680,7 +1690,7 @@ export default function App() {
|
||||
tracks={filtered}
|
||||
sorting={sorting}
|
||||
onSortingChange={setSorting}
|
||||
onRowContextMenu={(track, x, y) => openMenu(track, x, y, false)}
|
||||
onRowContextMenu={(track, x, y, viewIds) => openMenu(track, x, y, false, viewIds)}
|
||||
dragFrom={{ origin: 'device' }}
|
||||
onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })}
|
||||
onPlay={playTrack}
|
||||
@@ -1705,7 +1715,7 @@ export default function App() {
|
||||
sorting={sorting}
|
||||
onSortingChange={setSorting}
|
||||
selection={{ selected, onChange: setSelected }}
|
||||
onRowContextMenu={(track, x, y) => openMenu(track, x, y, true)}
|
||||
onRowContextMenu={(track, x, y, viewIds) => openMenu(track, x, y, true, viewIds)}
|
||||
onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })}
|
||||
onPlay={playTrack}
|
||||
onEditField={canEdit ? editField : undefined}
|
||||
@@ -1747,7 +1757,7 @@ export default function App() {
|
||||
origin: 'collection',
|
||||
playlistId: playlistEditable && source.kind === 'playlist' ? source.id : undefined,
|
||||
}}
|
||||
onRowContextMenu={(track, x, y) => openMenu(track, x, y, true)}
|
||||
onRowContextMenu={(track, x, y, viewIds) => openMenu(track, x, y, true, viewIds)}
|
||||
onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })}
|
||||
onPlay={playTrack}
|
||||
onEditField={canEdit ? editField : undefined}
|
||||
|
||||
+32
-2
@@ -125,8 +125,8 @@ export type TrackField =
|
||||
export interface CuePoint {
|
||||
name: string | null
|
||||
type: CueType
|
||||
/** Memory cues have no bank slot. Only Rekordbox has them, so they are
|
||||
* preserved and shown but not editable anywhere yet. */
|
||||
/** A memory cue has no bank slot (Rekordbox / OneLibrary memory cues,
|
||||
* Traktor's cues on no pad) and is addressed by `id`, not `slot`. */
|
||||
role: CueRole
|
||||
start: number // seconds
|
||||
length: number // seconds (>0 for loops)
|
||||
@@ -139,6 +139,10 @@ export interface CuePoint {
|
||||
/** Index of the grid marker this cue mirrors, where the platform pairs them.
|
||||
* A display hint only; null on platforms that do not. */
|
||||
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. */
|
||||
@@ -208,7 +212,11 @@ export interface CueCapabilities {
|
||||
hotcue_slots: number
|
||||
slot_labels: 'number' | 'letter'
|
||||
memory_cues: boolean
|
||||
/** Per track; null = no limit. rekordbox stops at 10 without saying so. */
|
||||
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[]
|
||||
color: 'none' | 'free' | 'palette'
|
||||
palette: string[]
|
||||
@@ -1141,6 +1149,28 @@ export const api = {
|
||||
'DELETE',
|
||||
`/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;
|
||||
* a move is clamped between its neighbours rather than reordering them. */
|
||||
setGridMarker: (trackId: string, index: number, patch: { bpm?: number; start?: number }) =>
|
||||
|
||||
@@ -14,6 +14,8 @@ export const APP_SETTING_DEFAULTS = {
|
||||
expandPlaylistFolders: false,
|
||||
/** Read by the backend when an export runs (`main.run_export`). */
|
||||
exportRootFolder: false,
|
||||
/** Decimal places on the deck's ELAPSED / REMAIN readouts (0–3). */
|
||||
timeReadoutDecimals: 1,
|
||||
}
|
||||
|
||||
type AppSettingKey = keyof typeof APP_SETTING_DEFAULTS
|
||||
@@ -29,6 +31,7 @@ export function AppSettings({ onClose }: { onClose: () => void }) {
|
||||
const qc = useQueryClient()
|
||||
const expandFolders = useAppSetting('expandPlaylistFolders')
|
||||
const exportRootFolder = useAppSetting('exportRootFolder')
|
||||
const timeDecimals = useAppSetting('timeReadoutDecimals')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
@@ -95,6 +98,28 @@ export function AppSettings({ onClose }: { onClose: () => void }) {
|
||||
</span>
|
||||
</label>
|
||||
</section>
|
||||
<section className="space-y-2">
|
||||
<h3 className="text-[11px] font-semibold uppercase tracking-wider text-faint">Deck</h3>
|
||||
<label className="flex items-start justify-between gap-4">
|
||||
<span className="min-w-0">
|
||||
<span className="block text-sm text-text">Time readout precision</span>
|
||||
<span className="block text-xs text-faint">
|
||||
Decimal places on the Elapsed and Remain readouts. 1 shows tenths, 3 milliseconds.
|
||||
</span>
|
||||
</span>
|
||||
<select
|
||||
className="shrink-0 rounded-lg well px-2 py-1 text-sm text-text outline-none"
|
||||
value={timeDecimals}
|
||||
onChange={(e) => void set({ timeReadoutDecimals: Number(e.target.value) })}
|
||||
>
|
||||
{['00:00', '00:00.0', '00:00.00', '00:00.000'].map((sample, n) => (
|
||||
<option key={n} value={n}>
|
||||
{n} — {sample}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</section>
|
||||
{error && <div className="text-xs text-pink">{error}</div>}
|
||||
</div>
|
||||
<div className="flex justify-end gap-2 border-t border-line px-5 py-3">
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { createPortal } from 'react-dom'
|
||||
import type { ReactNode } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
|
||||
import { Icon } from '../lib/icons'
|
||||
|
||||
/** One row of a menu: an action, a submenu (`label ▸`), or a section heading. */
|
||||
@@ -69,6 +69,27 @@ export function ContextMenu({ x, y, items, onClose }: Props) {
|
||||
}
|
||||
}, [])
|
||||
|
||||
// Opened near the bottom of the window, the menu moves UP so its bottom sits
|
||||
// at the window's edge, and only scrolls once it cannot fit at its natural
|
||||
// height at all. The first render places it at the cursor; this measures the
|
||||
// list's full height before paint and repositions it.
|
||||
const [vertical, setVertical] = useState<{ top: number; maxHeight: number }>(() => {
|
||||
const top = Math.min(y, window.innerHeight - 100)
|
||||
return { top, maxHeight: Math.min(MENU_MAX_HEIGHT, window.innerHeight - top - 8) }
|
||||
})
|
||||
useLayoutEffect(() => {
|
||||
const panel = rootRef.current?.firstElementChild as HTMLElement | null
|
||||
const list = panel?.firstElementChild as HTMLElement | null
|
||||
if (!panel || !list) return
|
||||
const natural = Math.min(
|
||||
MENU_MAX_HEIGHT,
|
||||
panel.offsetHeight - list.clientHeight + list.scrollHeight,
|
||||
)
|
||||
const top = Math.max(8, Math.min(y, window.innerHeight - 8 - natural))
|
||||
const maxHeight = Math.min(MENU_MAX_HEIGHT, window.innerHeight - top - 8)
|
||||
setVertical((v) => (v.top === top && v.maxHeight === maxHeight ? v : { top, maxHeight }))
|
||||
}, [y, items])
|
||||
|
||||
return createPortal(
|
||||
// `contents`: the panels are fixed-positioned, so this wrapper must take no
|
||||
// part in layout. As an ordinary empty block it became one more item in
|
||||
@@ -78,14 +99,7 @@ export function ContextMenu({ x, y, items, onClose }: Props) {
|
||||
items={items}
|
||||
onClose={onClose}
|
||||
className="min-w-[160px]"
|
||||
style={(() => {
|
||||
const top = Math.min(y, window.innerHeight - 100)
|
||||
return {
|
||||
top,
|
||||
left: Math.min(x, window.innerWidth - 180),
|
||||
maxHeight: Math.min(MENU_MAX_HEIGHT, window.innerHeight - top - 8),
|
||||
}
|
||||
})()}
|
||||
style={{ ...vertical, left: Math.min(x, window.innerWidth - 180) }}
|
||||
/>
|
||||
</div>,
|
||||
document.body,
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useRef, useState, type CSSProperties } from 'react'
|
||||
import type { CSSProperties } from 'react'
|
||||
import type { CuePoint } from '../api'
|
||||
import { CUE_TYPE_LABELS, cueColor, cueIcon, withAlpha } from '../lib/cues'
|
||||
import { Icon } from '../lib/icons'
|
||||
import { RenameField } from './RenameField'
|
||||
|
||||
interface Props {
|
||||
cues: CuePoint[]
|
||||
@@ -155,7 +156,7 @@ export function HotcueBar({
|
||||
* backlit controller pad reads. Selection brightens the tint and rings it in
|
||||
* 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 {
|
||||
// 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
|
||||
@@ -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
|
||||
* 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 mix = (c: number) => Math.round(c + (255 - c) * amount)
|
||||
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"
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
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
|
||||
* 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.
|
||||
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 (
|
||||
<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">
|
||||
{tab('beat', 'BEAT', 'Beat loops, sized in beats')}
|
||||
{tab('manual', 'MAN', 'Manual loops: set IN and OUT')}
|
||||
</div>
|
||||
<ModeSwitch
|
||||
label="Loop mode"
|
||||
value={mode}
|
||||
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' ? (
|
||||
<div role="group" aria-label="Loop size" className={`${CLUSTER} font-mono`}>
|
||||
|
||||
@@ -1,11 +1,20 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import type { CuePoint } from '../api'
|
||||
import type { BeatGrid } from '../lib/beatgrid'
|
||||
import { Icon } from '../lib/icons'
|
||||
import { hasMod, MOD_NAME } from '../lib/modKey'
|
||||
import { drawBeatgrid, drawCuePoint, drawCues, drawLoop, drawLoopIn, drawPlayhead } from '../lib/cues'
|
||||
import { laneScales, makeSpans, paintRaw, rawSpans, tintAt, type RawWave } from '../lib/rawWave'
|
||||
import { paintLane, paintWave, type WaveColumn } from '../lib/waveform'
|
||||
|
||||
interface Props {
|
||||
cols: WaveColumn[]
|
||||
/** The samples, for the raw view. */
|
||||
raw?: RawWave | null
|
||||
/** Draw the raw signal as a thin line instead of bars (the toggle under
|
||||
the zoom buttons; owned by the parent, which persists it). */
|
||||
rawMode?: boolean
|
||||
onRawModeChange?: (raw: boolean) => void
|
||||
currentTime: number
|
||||
duration: number
|
||||
cues: CuePoint[]
|
||||
@@ -30,12 +39,14 @@ interface Props {
|
||||
onScratchEnd: (t: number) => void
|
||||
/** A stem track: one lane per stem instead of the three-band mix view. */
|
||||
lanes?: StemLane[] | null
|
||||
/** Click = mute toggle; Alt/Option-click = solo (mute all the others). */
|
||||
/** Click = mute toggle; Cmd/Ctrl-click = solo (mute all the others). */
|
||||
onStemToggle?: (index: number, solo: boolean) => void
|
||||
}
|
||||
|
||||
export interface StemLane {
|
||||
data: Float32Array
|
||||
/** The stem's samples, for the raw view. */
|
||||
raw?: RawWave | null
|
||||
name: string
|
||||
color: string
|
||||
/** Not muted. */
|
||||
@@ -46,11 +57,9 @@ export interface StemLane {
|
||||
shortcut: string
|
||||
}
|
||||
|
||||
const ALT = typeof navigator !== 'undefined' && /Mac/.test(navigator.platform) ? 'Option' : 'Alt'
|
||||
|
||||
const DRAG_THRESHOLD = 3 // px before a press becomes a scratch (vs a click-seek)
|
||||
|
||||
export const MIN_SEC = 2 // most zoomed-in (seconds across the view)
|
||||
export const MIN_SEC = 0.25 // most zoomed-in (seconds across the view): a kick's attack spans dozens of px
|
||||
export const MAX_SEC = 64 // most zoomed-out
|
||||
export const DEFAULT_SEC = 16
|
||||
|
||||
@@ -62,6 +71,9 @@ export const DEFAULT_SEC = 16
|
||||
*/
|
||||
export function MainWaveform({
|
||||
cols,
|
||||
raw = null,
|
||||
rawMode = false,
|
||||
onRawModeChange,
|
||||
currentTime,
|
||||
duration,
|
||||
cues,
|
||||
@@ -89,6 +101,7 @@ export function MainWaveform({
|
||||
const dragRef = useRef<{ startX: number; startTime: number; lastT: number; moved: boolean } | null>(
|
||||
null,
|
||||
)
|
||||
const spansRef = useRef(makeSpans())
|
||||
|
||||
// Draw closes over the latest props/state; a ref lets the ResizeObserver call
|
||||
// the current version without re-subscribing.
|
||||
@@ -111,7 +124,25 @@ export function MainWaveform({
|
||||
// 2 px bars with a 1 px gap: the texture that makes the scrolling view
|
||||
// read as discrete energy rather than a smear.
|
||||
const bars = { bar: Math.max(1, Math.round(2 * dpr)), gap: Math.max(1, Math.round(dpr)) }
|
||||
if (lanes && lanes.length) {
|
||||
// The raw line's minimum stroke, so silence and flat stretches still read.
|
||||
const thick = Math.max(1, 1.25 * dpr)
|
||||
const spans = spansRef.current
|
||||
if (rawMode && lanes && lanes.length && lanes.every((l) => l.raw)) {
|
||||
const laneH = h / lanes.length
|
||||
const scales = laneScales(lanes.map((l) => l.raw!.peak), laneH / 2 - thick)
|
||||
lanes.forEach((lane, k) => {
|
||||
rawSpans(lane.raw!, startSec, endSec, w, spans)
|
||||
ctx.globalAlpha = lane.audible ? 0.92 : 0.18
|
||||
paintRaw(ctx, spans, k * laneH, laneH, scales[k], thick, lane.color)
|
||||
})
|
||||
ctx.globalAlpha = 1
|
||||
ctx.fillStyle = 'rgba(255,255,255,0.06)'
|
||||
for (let k = 1; k < lanes.length; k++) ctx.fillRect(0, Math.round(k * laneH), w, Math.max(1, Math.round(dpr)))
|
||||
} else if (rawMode && !lanes?.length && raw) {
|
||||
rawSpans(raw, startSec, endSec, w, spans)
|
||||
const scale = (h / 2 - thick) / Math.max(raw.peak, 1e-6)
|
||||
paintRaw(ctx, spans, 0, h, scale, thick, (t) => tintAt(cols, duration, t))
|
||||
} else if (lanes && lanes.length) {
|
||||
// Stem lanes, Traktor-style: each stem its own strip in its own colour.
|
||||
const laneH = h / lanes.length
|
||||
lanes.forEach((lane, k) => {
|
||||
@@ -245,8 +276,8 @@ export function MainWaveform({
|
||||
<div key={k} className="flex flex-1 items-center">
|
||||
<button
|
||||
onPointerDown={(e) => e.stopPropagation()}
|
||||
onClick={(e) => onStemToggle?.(k, e.altKey)}
|
||||
title={`${lane.name} — click to mute, ${ALT}-click to mute all the others (${lane.shortcut})`}
|
||||
onClick={(e) => onStemToggle?.(k, hasMod(e))}
|
||||
title={`${lane.name} — click to mute, ${MOD_NAME}-click to mute all the others (${lane.shortcut})`}
|
||||
aria-pressed={lane.audible}
|
||||
className={`flex h-5 min-w-5 items-center justify-center rounded-md px-1 font-mono text-[10px] font-semibold backdrop-blur-md transition-opacity ${
|
||||
lane.audible ? '' : 'opacity-40'
|
||||
@@ -263,9 +294,10 @@ export function MainWaveform({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Zoom controls (Traktor-style +/-). stopPropagation on down so tapping a
|
||||
button doesn't begin a scratch drag. */}
|
||||
<div className="absolute right-2 top-2 flex flex-col gap-1">
|
||||
{/* Zoom in · raw/bars · zoom out, centred on the waveform's height.
|
||||
stopPropagation on down so tapping a button doesn't begin a scratch
|
||||
drag. */}
|
||||
<div className="absolute right-2 top-1/2 flex -translate-y-1/2 flex-col gap-1">
|
||||
<button
|
||||
onPointerDown={(e) => e.stopPropagation()}
|
||||
onClick={zoomIn}
|
||||
@@ -275,6 +307,17 @@ export function MainWaveform({
|
||||
>
|
||||
+
|
||||
</button>
|
||||
<button
|
||||
onPointerDown={(e) => e.stopPropagation()}
|
||||
onClick={() => onRawModeChange?.(!rawMode)}
|
||||
aria-pressed={rawMode}
|
||||
aria-label="Raw waveform"
|
||||
className="btn-glass flex h-6 w-6 items-center justify-center rounded-lg text-text backdrop-blur-md"
|
||||
title={rawMode ? 'Raw waveform — click for bars' : 'Bars — click for the raw waveform: the exact shape of every transient'}
|
||||
>
|
||||
{/* The icon shows the mode in force: bars, or the raw line. */}
|
||||
<Icon name={rawMode ? 'sine' : 'wave'} size={14} />
|
||||
</button>
|
||||
<button
|
||||
onPointerDown={(e) => e.stopPropagation()}
|
||||
onClick={zoomOut}
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -21,18 +21,23 @@ import { CUE_TYPE_LABELS, cueTypeColor } from '../lib/cues'
|
||||
import { keyColor } from '../lib/format'
|
||||
import { readOnlyShort, readOnlyNotice } from '../lib/platformCopy'
|
||||
import { analyzeStems, analyzeWaveform, type WaveColumn } from '../lib/waveform'
|
||||
import type { RawWave } from '../lib/rawWave'
|
||||
import { setAmbientFromArt } from '../lib/ambient'
|
||||
import { Icon } from '../lib/icons'
|
||||
import { ScratchEngine } from '../lib/scratchEngine'
|
||||
import { PlaybackEngine } from '../lib/playbackEngine'
|
||||
import { invalidateTrackLists } from '../lib/trackQueries'
|
||||
import { AutoCueDialog, eventLabel } from './AutoCueDialog'
|
||||
import { TrackInfoDialog } from './TrackInfoDialog'
|
||||
import { ContextMenu, type MenuItem } from './ContextMenu'
|
||||
import { BpmReadout, GridEditStrip, TempoControls, TempoFold } from './GridControls'
|
||||
import { HotcueBar } from './HotcueBar'
|
||||
import { MemoryCueStrip } from './MemoryCueStrip'
|
||||
import { ModeSwitch } from './ModeSwitch'
|
||||
import { LoopControls, LOOP_SIZES, type LoopMode } from './LoopControls'
|
||||
import { MainWaveform, MIN_SEC, MAX_SEC, DEFAULT_SEC, type StemLane } from './MainWaveform'
|
||||
import { OverviewWaveform } from './OverviewWaveform'
|
||||
import { useAppSetting } from './AppSettings'
|
||||
import { usePrefsWriter } from '../lib/prefs'
|
||||
|
||||
/** Keys that mute stems 1-4 (Shift = solo), by `KeyboardEvent.code`. */
|
||||
@@ -59,15 +64,24 @@ interface Props {
|
||||
cuesRefresh?: number
|
||||
/** Reports whether the deck is playing, so the library can light its row. */
|
||||
onPlayingChange?: (playing: boolean) => void
|
||||
/** Opens Edit Tags for the loaded track — passed only where the library
|
||||
* will accept the edit, so the cover popup offers it only then. */
|
||||
onEditTags?: (track: Track) => void
|
||||
}
|
||||
|
||||
/** m:ss.t — the deck's readouts show tenths, as a CDJ does. */
|
||||
function fmtTenths(secs: number): string {
|
||||
/** mm:ss.f — tenths by default, as a CDJ does; `places` is the
|
||||
* `timeReadoutDecimals` setting (0 drops the fraction). Truncates, never
|
||||
* rounds, so the readout never shows a second before it has been reached. */
|
||||
function fmtTime(secs: number, places: number): string {
|
||||
if (!isFinite(secs) || secs < 0) secs = 0
|
||||
const tenths = Math.floor(secs * 10)
|
||||
const m = Math.floor(tenths / 600)
|
||||
const s = Math.floor((tenths % 600) / 10)
|
||||
return `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}.${tenths % 10}`
|
||||
const scale = 10 ** places
|
||||
// The epsilon keeps e.g. 0.3 s from reading 0.299 at 3 places.
|
||||
const units = Math.floor(secs * scale + 1e-6)
|
||||
const whole = Math.floor(units / scale)
|
||||
const m = Math.floor(whole / 60)
|
||||
const s = whole % 60
|
||||
const frac = places > 0 ? `.${(units % scale).toString().padStart(places, '0')}` : ''
|
||||
return `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}${frac}`
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -102,6 +116,7 @@ export function PrepStrip({
|
||||
origin = 'collection',
|
||||
cuesRefresh = 0,
|
||||
onPlayingChange,
|
||||
onEditTags,
|
||||
}: Props) {
|
||||
const qc = useQueryClient()
|
||||
const [playing, setPlaying] = useState(false)
|
||||
@@ -111,9 +126,13 @@ export function PrepStrip({
|
||||
// which the pointer's :active alone cannot, since the key never touches it.
|
||||
const [cueHeld, setCueHeld] = useState(false)
|
||||
const [current, setCurrent] = useState(0)
|
||||
const timeDecimals = useAppSetting('timeReadoutDecimals')
|
||||
const [duration, setDuration] = useState(0)
|
||||
const [ready, setReady] = useState(false)
|
||||
const [cols, setCols] = useState<WaveColumn[] | null>(null)
|
||||
// The raw waveform's data: the mix's samples, or one per stem lane.
|
||||
const [raw, setRaw] = useState<RawWave | null>(null)
|
||||
const [stemRaws, setStemRaws] = useState<RawWave[] | null>(null)
|
||||
// A stem track: its stems (from the FILE), their lanes, and which are muted
|
||||
// — reset per track, as Traktor's stem deck does. There is no separate solo
|
||||
// state: solo is a shortcut that SETS the mutes, so every stem stays freely
|
||||
@@ -129,7 +148,9 @@ export function PrepStrip({
|
||||
const [snap, setSnap] = useState(true)
|
||||
const [selectedSlot, setSelectedSlot] = useState<number | null>(null)
|
||||
const [cuePoint, setCuePoint] = useState(0) // floating "CUE" point (frontend-only)
|
||||
const [infoOpen, setInfoOpen] = useState(false) // the cover's track-info popup
|
||||
const [secPerView, setSecPerView] = useState(DEFAULT_SEC) // main-waveform zoom (persisted)
|
||||
const [rawWave, setRawWave] = useState(false) // main waveform: raw line instead of bars (persisted)
|
||||
// ONE size, in beats, for beat loops and beat jump alike (persisted).
|
||||
const [beatSize, setBeatSize] = useState(4)
|
||||
const [loopMode, setLoopMode] = useState<LoopMode>('beat')
|
||||
@@ -137,6 +158,10 @@ export function PrepStrip({
|
||||
const [gridMode, setGridMode] = useState(false)
|
||||
const [padMenu, setPadMenu] = useState<{ slot: number; x: number; y: 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).
|
||||
const [loopRegion, setLoopRegion] = useState<{ start: number; end: number } | null>(null)
|
||||
@@ -164,7 +189,7 @@ export function PrepStrip({
|
||||
|
||||
const trackId = track?.id ?? null
|
||||
|
||||
// Main-waveform zoom persists to userprefs.json so it survives track switches
|
||||
// Main-waveform zoom (and the raw/bars toggle) persists to userprefs.json so it survives track switches
|
||||
// (MainWaveform unmounts during each load) and app restarts. Hydrate once from
|
||||
// the shared ['prefs'] query, then persist changes through the shared,
|
||||
// debounced prefs writer (as App's column layout does).
|
||||
@@ -178,11 +203,12 @@ export function PrepStrip({
|
||||
if (typeof z === 'number' && isFinite(z)) {
|
||||
setSecPerView(Math.min(MAX_SEC, Math.max(MIN_SEC, z)))
|
||||
}
|
||||
if ((prefsQuery.data as { mainWaveRaw?: unknown }).mainWaveRaw === true) setRawWave(true)
|
||||
}, [prefsQuery.data])
|
||||
useEffect(() => {
|
||||
if (!zoomHydratedRef.current) return // don't clobber saved prefs pre-hydration
|
||||
writePrefs({ mainZoomSec: secPerView })
|
||||
}, [secPerView, writePrefs])
|
||||
writePrefs({ mainZoomSec: secPerView, mainWaveRaw: rawWave })
|
||||
}, [secPerView, rawWave, writePrefs])
|
||||
|
||||
// The loop/jump size persists the same way (survives track switches +
|
||||
// restarts). `beatJumpBeats` is its name from when only beat jump had a size;
|
||||
@@ -200,6 +226,18 @@ export function PrepStrip({
|
||||
writePrefs({ beatSize })
|
||||
}, [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 => {
|
||||
if (!audioCtxRef.current) {
|
||||
audioCtxRef.current = new (window.AudioContext ??
|
||||
@@ -247,6 +285,8 @@ export function PrepStrip({
|
||||
setSelectedSlot(null)
|
||||
setPadMenu(null)
|
||||
setRenamingSlot(null)
|
||||
setMemoryMenu(null)
|
||||
setRenamingMemory(null)
|
||||
setLoopRegion(null)
|
||||
setLoopActive(false)
|
||||
setActiveBeats(null)
|
||||
@@ -271,11 +311,15 @@ export function PrepStrip({
|
||||
scratchRef.current = null
|
||||
if (!trackId) {
|
||||
setCols(null)
|
||||
setRaw(null)
|
||||
setStemRaws(null)
|
||||
setWaveStatus('loading')
|
||||
return
|
||||
}
|
||||
let cancelled = false
|
||||
setCols(null)
|
||||
setRaw(null)
|
||||
setStemRaws(null)
|
||||
setStems(null)
|
||||
setStemLanes(null)
|
||||
setWaveStatus('loading')
|
||||
@@ -286,15 +330,17 @@ export function PrepStrip({
|
||||
.then(async (found) => {
|
||||
if (found.length) {
|
||||
const res = await analyzeStems(found.map((_, k) => trackStemUrl(origin, trackId, k)))
|
||||
return { cols: res.cols, buffers: res.buffers, lanes: res.lanes, stems: found }
|
||||
return { cols: res.cols, buffers: res.buffers, lanes: res.lanes, stems: found, raw: null, raws: res.raws }
|
||||
}
|
||||
const res = await analyzeWaveform(trackAudioUrl(origin, trackId))
|
||||
return { cols: res.cols, buffers: [res.buffer], lanes: null, stems: null }
|
||||
return { cols: res.cols, buffers: [res.buffer], lanes: null, stems: null, raw: res.raw, raws: null }
|
||||
})
|
||||
load
|
||||
.then((res) => {
|
||||
if (cancelled) return
|
||||
setCols(res.cols)
|
||||
setRaw(res.raw)
|
||||
setStemRaws(res.raws)
|
||||
setStems(res.stems)
|
||||
setStemLanes(res.lanes)
|
||||
setWaveStatus('ready')
|
||||
@@ -804,11 +850,18 @@ export function PrepStrip({
|
||||
const eng = playbackRef.current
|
||||
if (!eng || !eng.ready) return
|
||||
getCtx()
|
||||
// A loop hotcue jumps to its start AND 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.
|
||||
enterCue(cue)
|
||||
seek(cue.start)
|
||||
// Paused at press → momentary preview: play while held.
|
||||
if (!eng.playing) beginPreview(`hc:${slot}`, cue.start)
|
||||
}
|
||||
|
||||
// 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) {
|
||||
const beats = beatsForLoop(cue.start, cue.length)
|
||||
engagLoop(cue.start, cue.start + cue.length, beats)
|
||||
@@ -821,9 +874,6 @@ export function PrepStrip({
|
||||
} else {
|
||||
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.
|
||||
@@ -911,13 +961,134 @@ 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 ---------------------------------------------------------
|
||||
// Which marker the grid controls act on is derived from the playhead — there
|
||||
// is no separate selection state to keep in sync.
|
||||
const activeMarkerIndex = grid ? grid.markerIndexAt(current) : -1
|
||||
const activeMarker = activeMarkerIndex >= 0 ? grid!.markers[activeMarkerIndex] : null
|
||||
// ~4px of the current zoom, so "on the marker" stays usable at 2s and 64s/view.
|
||||
const markerHitSec = Math.max(0.01, secPerView / 250)
|
||||
// ~4 px of the view either side, so "at a marker" stays a marker-sized
|
||||
// target at deep zoom instead of 4% of a 0.25 s view.
|
||||
const markerHitSec = Math.max(0.001, secPerView / 250)
|
||||
const atMarker = !!grid && grid.isOnMarker(current, markerHitSec)
|
||||
const beforeFirstMarker = !!grid && current < grid.markers[0].start - GRID_EPS
|
||||
|
||||
@@ -1097,6 +1268,7 @@ export function PrepStrip({
|
||||
stems && stemLanes
|
||||
? stems.map((st, k) => ({
|
||||
data: stemLanes[k],
|
||||
raw: stemRaws?.[k] ?? null,
|
||||
name: st.name,
|
||||
color: st.color,
|
||||
audible: stemLevels[k] > 0,
|
||||
@@ -1282,7 +1454,10 @@ export function PrepStrip({
|
||||
<div className="glass flex h-[19.75rem] shrink-0 flex-col gap-2 p-4">
|
||||
{/* ---- Header: the track, its readouts, the analysis actions ---- */}
|
||||
<div className="flex h-12 shrink-0 items-center gap-3">
|
||||
<CoverThumb trackId={track && origin === 'collection' ? track.id : null} />
|
||||
<CoverThumb
|
||||
trackId={track && origin === 'collection' ? track.id : null}
|
||||
onOpen={track ? () => setInfoOpen(true) : undefined}
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
{track ? (
|
||||
<>
|
||||
@@ -1314,12 +1489,12 @@ export function PrepStrip({
|
||||
<div className="well flex h-11 shrink-0 items-stretch rounded-xl">
|
||||
<div className="flex flex-col justify-center gap-px px-4">
|
||||
<span className="text-[10px] tracking-[0.08em] text-faint">ELAPSED</span>
|
||||
<span className="font-mono text-[17px] font-medium">{fmtTenths(current)}</span>
|
||||
<span className="font-mono text-[17px] font-medium">{fmtTime(current, timeDecimals)}</span>
|
||||
</div>
|
||||
<span aria-hidden className="my-2 w-px bg-line" />
|
||||
<div className="flex flex-col justify-center gap-px px-4">
|
||||
<span className="text-[10px] tracking-[0.08em] text-faint">REMAIN</span>
|
||||
<span className="font-mono text-[17px] font-medium">−{fmtTenths(Math.max(0, duration - current))}</span>
|
||||
<span className="font-mono text-[17px] font-medium">−{fmtTime(Math.max(0, duration - current), timeDecimals)}</span>
|
||||
</div>
|
||||
<span aria-hidden className="my-2 w-px bg-line" />
|
||||
<div className="flex flex-col justify-center gap-px px-4">
|
||||
@@ -1390,6 +1565,9 @@ export function PrepStrip({
|
||||
{showWaves ? (
|
||||
<MainWaveform
|
||||
cols={cols}
|
||||
raw={raw}
|
||||
rawMode={rawWave}
|
||||
onRawModeChange={setRawWave}
|
||||
currentTime={current}
|
||||
duration={duration}
|
||||
cues={cueData?.cues ?? []}
|
||||
@@ -1436,10 +1614,11 @@ export function PrepStrip({
|
||||
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
|
||||
their names first (each pad queries its own width, see HotcueBar),
|
||||
then below 74rem the tempo group folds into one BPM button, and below
|
||||
60rem the Grid toggle keeps only its icon. Those are the row's
|
||||
then below 77rem the tempo group folds into one BPM button, and below
|
||||
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
|
||||
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">
|
||||
<button
|
||||
onClick={toggle}
|
||||
@@ -1498,6 +1677,23 @@ export function PrepStrip({
|
||||
onMove={moveOrJump}
|
||||
/>
|
||||
{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 ? (
|
||||
<GridEditStrip
|
||||
markerIndex={activeMarkerIndex}
|
||||
@@ -1515,6 +1711,18 @@ export function PrepStrip({
|
||||
onDeleteGrid={deleteGrid}
|
||||
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
|
||||
cues={cueData?.cues ?? []}
|
||||
@@ -1533,8 +1741,8 @@ export function PrepStrip({
|
||||
/>
|
||||
)}
|
||||
{DIVIDER}
|
||||
<TempoControls {...tempoProps} className="@max-[74rem]:hidden" />
|
||||
<TempoFold locked={tempoProps.locked} className="hidden @max-[74rem]:flex">
|
||||
<TempoControls {...tempoProps} className="@max-[77rem]:hidden" />
|
||||
<TempoFold locked={tempoProps.locked} className="hidden @max-[77rem]:flex">
|
||||
<TempoControls {...tempoProps} />
|
||||
</TempoFold>
|
||||
<button
|
||||
@@ -1542,22 +1750,33 @@ export function PrepStrip({
|
||||
setGridMode((g) => !g)
|
||||
setPadMenu(null)
|
||||
setRenamingSlot(null)
|
||||
setMemoryMenu(null)
|
||||
setRenamingMemory(null)
|
||||
}}
|
||||
aria-pressed={gridMode}
|
||||
disabled={!track}
|
||||
title={gridMode ? 'Back to the hotcue pads' : 'Edit the beatgrid: markers, phase, reset'}
|
||||
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
|
||||
? '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'
|
||||
}`}
|
||||
>
|
||||
<Icon name="grid" size={14} />
|
||||
<span className="@max-[60rem]:hidden">Grid</span>
|
||||
<span className="@max-[63rem]:hidden">Grid</span>
|
||||
</button>
|
||||
</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 && (
|
||||
<ContextMenu
|
||||
key={`${padMenu.slot}:${padMenu.x}:${padMenu.y}`}
|
||||
@@ -1567,6 +1786,21 @@ export function PrepStrip({
|
||||
onClose={() => setPadMenu(null)}
|
||||
/>
|
||||
)}
|
||||
{infoOpen && track && (
|
||||
<TrackInfoDialog
|
||||
track={track}
|
||||
artUrl={origin === 'collection' ? api.artUrl(track.id) : null}
|
||||
onClose={() => setInfoOpen(false)}
|
||||
onEditTags={
|
||||
onEditTags
|
||||
? () => {
|
||||
setInfoOpen(false)
|
||||
onEditTags(track)
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{autoOpen && track && (
|
||||
<AutoCueDialog
|
||||
track={track}
|
||||
@@ -1585,14 +1819,19 @@ export function PrepStrip({
|
||||
/**
|
||||
* The loaded track's sleeve. Until it loads — and for a track with no art — a
|
||||
* swatch of the ambient colours stands in, so the header never has a hole in it.
|
||||
* With a track loaded it is a button that opens the track-info popup.
|
||||
*/
|
||||
function CoverThumb({ trackId }: { trackId: string | null }) {
|
||||
function CoverThumb({ trackId, onOpen }: { trackId: string | null; onOpen?: () => void }) {
|
||||
const [failed, setFailed] = useState<string | null>(null)
|
||||
const showArt = trackId != null && failed !== trackId
|
||||
return (
|
||||
<div
|
||||
aria-hidden
|
||||
className="relative h-11 w-11 shrink-0 overflow-hidden rounded-xl shadow-[inset_0_1px_0_rgb(255_255_255/0.35),0_8px_24px_-6px_var(--amb-2)]"
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpen}
|
||||
disabled={!onOpen}
|
||||
title={onOpen ? 'Track info' : undefined}
|
||||
aria-label="Track info"
|
||||
className="relative h-11 w-11 shrink-0 overflow-hidden rounded-xl shadow-[inset_0_1px_0_rgb(255_255_255/0.35),0_8px_24px_-6px_var(--amb-2)] transition-transform enabled:cursor-zoom-in enabled:hover:scale-105 enabled:active:scale-95 disabled:cursor-default"
|
||||
style={{ background: 'linear-gradient(135deg, var(--amb-1), var(--amb-2) 55%, var(--amb-3))' }}
|
||||
>
|
||||
{showArt && (
|
||||
@@ -1604,6 +1843,6 @@ function CoverThumb({ trackId }: { trackId: string | null }) {
|
||||
onError={() => setFailed(trackId)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -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"
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -1,24 +1,41 @@
|
||||
import { createPortal } from 'react-dom'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react'
|
||||
import type { SortingState } from '@tanstack/react-table'
|
||||
import { maxPosition, moveToPosition } from '../lib/playlistOrder'
|
||||
import { COLUMN_MENU } from '../lib/trackColumns'
|
||||
|
||||
interface Props {
|
||||
/** The playlist's full entry order — never the sorted or filtered view, so
|
||||
* the move is safe whatever the table is showing. */
|
||||
order: string[]
|
||||
/** The tracks to move; they keep their playlist order as one block. */
|
||||
/** The tracks to move, in the order the table shows them. */
|
||||
ids: string[]
|
||||
/** The table's sort. While there is one, the block may keep that order
|
||||
* instead of its playlist order — which writes the sort into the playlist. */
|
||||
sorting: SortingState
|
||||
onMove: (order: string[]) => void
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
/** "Set Position…": type where the first selected track should end up. */
|
||||
export function SetPositionDialog({ order, ids, onMove, onClose }: Props) {
|
||||
/** "Key" / "Key descending, then BPM" — the sort as the Order choice names it. */
|
||||
function describeSort(sorting: SortingState): string {
|
||||
const label = (id: string) => COLUMN_MENU.find((c) => c.id === id)?.label ?? id
|
||||
return sorting.map((s) => `${label(s.id)}${s.desc ? ' descending' : ''}`).join(', then ')
|
||||
}
|
||||
|
||||
/** "Set Position…": type where the first selected track should end up, and —
|
||||
* while the table is sorted — whether the block keeps its playlist order or
|
||||
* takes the sorted one. */
|
||||
export function SetPositionDialog({ order, ids, sorting, onMove, onClose }: Props) {
|
||||
const moving = new Set(ids)
|
||||
const count = order.filter((id) => moving.has(id)).length
|
||||
const max = maxPosition(order, moving)
|
||||
const current = order.findIndex((id) => moving.has(id)) + 1
|
||||
const [value, setValue] = useState(String(current))
|
||||
// With one track there is no order to choose; unsorted, both are the same.
|
||||
const canSort = sorting.length > 0 && count > 1
|
||||
const [mode, setMode] = useState<'playlist' | 'sorted'>('sorted')
|
||||
const sorted = canSort && mode === 'sorted'
|
||||
const input = useRef<HTMLInputElement>(null)
|
||||
|
||||
useEffect(() => input.current?.select(), [])
|
||||
@@ -28,7 +45,7 @@ export function SetPositionDialog({ order, ids, onMove, onClose }: Props) {
|
||||
|
||||
const submit = () => {
|
||||
if (position === null) return
|
||||
const next = moveToPosition(order, moving, position)
|
||||
const next = moveToPosition(order, moving, position, sorted ? ids : undefined)
|
||||
if (next.some((id, i) => id !== order[i])) onMove(next)
|
||||
onClose()
|
||||
}
|
||||
@@ -41,6 +58,26 @@ export function SetPositionDialog({ order, ids, onMove, onClose }: Props) {
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [onClose])
|
||||
|
||||
const option = (value: 'playlist' | 'sorted', label: string, detail: ReactNode) => (
|
||||
<label
|
||||
className={`flex cursor-pointer gap-3 rounded-lg px-3 py-2 ${
|
||||
mode === value ? 'is-selected' : 'hover:bg-ink-850'
|
||||
}`}
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="position-order"
|
||||
checked={mode === value}
|
||||
onChange={() => setMode(value)}
|
||||
className="mt-0.5 accent-accent"
|
||||
/>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block text-text">{label}</span>
|
||||
<span className="block text-xs text-faint">{detail}</span>
|
||||
</span>
|
||||
</label>
|
||||
)
|
||||
|
||||
const span = (p: number) => (count > 1 ? `#${p}–${p + count - 1}` : `#${p}`)
|
||||
|
||||
return createPortal(
|
||||
@@ -79,9 +116,24 @@ export function SetPositionDialog({ order, ids, onMove, onClose }: Props) {
|
||||
{position === null
|
||||
? 'Type a position.'
|
||||
: count > 1
|
||||
? `Will occupy ${span(position)}`
|
||||
? `Will occupy ${span(position)}${canSort ? '' : ', in the order they have in the playlist.'}`
|
||||
: `Now ${span(current)} · will be ${span(position)}`}
|
||||
</div>
|
||||
{canSort && (
|
||||
<div role="radiogroup" aria-label="Order" className="space-y-1">
|
||||
<div className="text-xs uppercase tracking-wide text-faint">Order</div>
|
||||
{option(
|
||||
'sorted',
|
||||
`As sorted: ${describeSort(sorting)}`,
|
||||
'In the order shown here. The playlist keeps this order when you clear the sort.',
|
||||
)}
|
||||
{option(
|
||||
'playlist',
|
||||
'Playlist order',
|
||||
'In the order they have in the playlist now, whatever the sort shows.',
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center justify-end gap-2 border-t border-line px-5 py-3">
|
||||
<button
|
||||
|
||||
@@ -38,6 +38,25 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
|
||||
return () => document.removeEventListener('mousedown', onDoc)
|
||||
}, [open])
|
||||
|
||||
// The `?` key opens the shortcut map from anywhere — unless typing, or
|
||||
// something already holds the keyboard. Pressed as it is, no Shift: by its
|
||||
// position (the US/UK "/ ?" key), and by the character on layouts that put
|
||||
// `?` elsewhere (typed with Shift there).
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.metaKey || e.ctrlKey || e.altKey) return
|
||||
if (!(e.code === 'Slash' && !e.shiftKey) && e.key !== '?') return
|
||||
const t = e.target as HTMLElement | null
|
||||
if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT' || t.isContentEditable)) return
|
||||
if (document.querySelector('[aria-modal="true"], [role="menu"]')) return
|
||||
e.preventDefault()
|
||||
setOpen(false)
|
||||
setShowShortcuts(true)
|
||||
}
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [])
|
||||
|
||||
const item =
|
||||
'flex w-full flex-col items-start rounded-[10px] px-2.5 py-1.5 text-left hover:bg-ink-800'
|
||||
|
||||
@@ -122,7 +141,7 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
|
||||
className={item}
|
||||
>
|
||||
<span className="text-sm text-text">View Shortcuts</span>
|
||||
<span className="text-[11px] text-faint">Every keyboard shortcut in one list</span>
|
||||
<span className="text-[11px] text-faint">Every keyboard shortcut, on a keyboard (?)</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1,112 +1,167 @@
|
||||
import { createPortal } from 'react-dom'
|
||||
import { useEffect } from 'react'
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react'
|
||||
import { useCaps } from '../lib/capabilities'
|
||||
import { Icon } from '../lib/icons'
|
||||
import {
|
||||
ARROW_GAP,
|
||||
ARROW_KEYS,
|
||||
AREA_COLORS,
|
||||
AREAS,
|
||||
KEY_ROWS,
|
||||
KEYBOARD_UNITS,
|
||||
KEYS_BY_CODE,
|
||||
LAYER_NAMES,
|
||||
LAYERS,
|
||||
MODIFIER_KEY,
|
||||
MOUSE,
|
||||
bindings,
|
||||
modifierLayer,
|
||||
padRange,
|
||||
unusedNote,
|
||||
type Area,
|
||||
type Binding,
|
||||
type KeyDef,
|
||||
type Layer,
|
||||
type MouseGesture,
|
||||
} from '../lib/shortcuts'
|
||||
|
||||
interface Props {
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
// Cmd on macOS, Ctrl elsewhere — the handlers accept either, but a list that
|
||||
// says "Cmd/Ctrl" everywhere is harder to scan than one that names your key.
|
||||
const IS_MAC = /Mac|iPhone|iPad/.test(navigator.userAgent)
|
||||
const MOD = IS_MAC ? '⌘' : 'Ctrl'
|
||||
const ALT_KEY = IS_MAC ? '⌥' : 'Alt'
|
||||
/** Key unit bounds, px. The map shrinks to fit the dialog; below LABEL_MIN the
|
||||
* words on the keys go (the caption still explains each key), below SHORT_MIN
|
||||
* the long modifier legends become symbols. */
|
||||
const UNIT_MAX = 52
|
||||
const UNIT_MIN = 20
|
||||
const LABEL_MIN = 44
|
||||
const SHORT_MIN = 38
|
||||
|
||||
type Row = { keys: string[][]; action: string }
|
||||
type Section = { title: string; rows: Row[] }
|
||||
const ALL_AREAS = Object.keys(AREAS) as Area[]
|
||||
const matchText = (b: Binding) => `${b.text} ${b.label}`.toLowerCase()
|
||||
const mouseText = (r: MouseGesture) => `${r.gesture} ${r.on ?? ''} ${r.text}`.toLowerCase()
|
||||
|
||||
/** Hotcue keys are digits in pad order, 0 being the tenth, so the list follows
|
||||
* the loaded library's bank size rather than hard-coding eight. */
|
||||
function hotcueKeys(slots: number): string {
|
||||
const n = Math.min(slots, 10)
|
||||
if (n <= 0) return '1'
|
||||
if (n <= 9) return `1–${n}`
|
||||
return '1–9, 0'
|
||||
}
|
||||
|
||||
function sections(slots: number): Section[] {
|
||||
const pads = hotcueKeys(slots)
|
||||
return [
|
||||
{
|
||||
title: 'Deck',
|
||||
rows: [
|
||||
{ keys: [['Space']], action: 'Play / pause' },
|
||||
{ keys: [['C']], action: 'CUE — jump back, set, or hold to preview' },
|
||||
{ keys: [['←'], ['→']], action: 'Beat jump back / forward — or move the loop, while one plays' },
|
||||
{ keys: [[MOD, '↓'], [MOD, '↑']], action: 'Halve / double the loop and jump size' },
|
||||
{ keys: [['Shift', '←'], ['Shift', '→']], action: 'Previous / next grid marker' },
|
||||
{ keys: [[pads]], action: 'Hotcue — set if empty, else jump (hold to preview)' },
|
||||
{ keys: [['Shift', pads]], action: 'Delete hotcue' },
|
||||
{ keys: [['Q'], ['W'], ['E'], ['R']], action: 'Stem track: mute / unmute stem 1–4' },
|
||||
{ keys: [['Shift', 'Q–R']], action: 'Stem track: solo — mute every other stem (again to unmute all)' },
|
||||
{ keys: [[ALT_KEY, 'Click', 'stem']], action: 'Solo a stem from its lane button' },
|
||||
{ keys: [['Drag waveform']], action: 'Scratch' },
|
||||
{ keys: [[MOD, 'Scroll']], action: 'Zoom the waveform' },
|
||||
{ keys: [['Right-click', 'pad']], action: 'Hotcue type, rename, delete' },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Track list',
|
||||
rows: [
|
||||
{ keys: [['Enter']], action: 'Load and play the highlighted track' },
|
||||
{ keys: [['↑'], ['↓']], action: 'Move the selection' },
|
||||
{ keys: [['Shift', '↑'], ['Shift', '↓']], action: 'Extend the selection' },
|
||||
{ keys: [[MOD, 'A']], action: 'Select all' },
|
||||
{ keys: [['Esc']], action: 'Clear the selection' },
|
||||
{ keys: [['Delete']], action: 'Remove from this playlist' },
|
||||
{ keys: [['Shift', 'Click']], action: 'Select a range' },
|
||||
{ keys: [[MOD, 'Click']], action: 'Add to / remove from the selection' },
|
||||
{ keys: [['Double-click']], action: 'Edit a cell' },
|
||||
{ keys: [['Right-click']], action: 'Track menu (header: choose columns)' },
|
||||
{ keys: [['Drag rows']], action: 'Onto a playlist or export to add, onto the deck to load, within a playlist to reorder' },
|
||||
{ keys: [[ALT_KEY, 'Drag']], action: 'Move tracks to another playlist (out of this one)' },
|
||||
{ keys: [['Esc']], action: 'While dragging: cancel the drag' },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Sidebar',
|
||||
rows: [
|
||||
{ keys: [['Right-click']], action: 'New playlist or folder, rename, delete' },
|
||||
{ keys: [['Drag']], action: 'Rearrange playlists and folders; onto an export to add one' },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Fields & dialogs',
|
||||
rows: [
|
||||
{ keys: [['Enter']], action: 'Save the edit / confirm' },
|
||||
{ keys: [['Esc']], action: 'Cancel / close' },
|
||||
],
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
function Keys({ combo }: { combo: string[] }) {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-0.5">
|
||||
{combo.map((k, i) => (
|
||||
<kbd
|
||||
key={i}
|
||||
className="min-w-[1.5rem] rounded border border-line bg-ink-800 px-1.5 py-0.5 text-center font-sans text-[11px] text-text"
|
||||
>
|
||||
{k}
|
||||
</kbd>
|
||||
))}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** Every keyboard shortcut (and the mouse gestures that go with them), from the
|
||||
* settings menu. Keep in step with the handlers in `PrepStrip` and `TrackTable`
|
||||
* — this list is written out by hand, not derived from them. */
|
||||
/** Every shortcut, drawn on a keyboard: a key lights in the colour of what it
|
||||
* does, pointing at (or pressing) it explains it, and holding a modifier — or
|
||||
* picking one above — relights the map with that layer. Mouse gestures are
|
||||
* listed beneath. The content lives in `lib/shortcuts.ts`. */
|
||||
export function ShortcutsDialog({ onClose }: Props) {
|
||||
const slots = useCaps().cues.hotcue_slots
|
||||
const binds = useMemo(() => bindings(slots), [slots])
|
||||
|
||||
const [sticky, setSticky] = useState<Layer>('base')
|
||||
const [held, setHeld] = useState<ReadonlySet<Layer>>(new Set())
|
||||
const [hover, setHover] = useState<string | null>(null)
|
||||
const [pressed, setPressed] = useState<string | null>(null)
|
||||
const [query, setQuery] = useState('')
|
||||
const [areas, setAreas] = useState<ReadonlySet<Area>>(new Set(ALL_AREAS))
|
||||
const layer: Layer = held.has('mod') ? 'mod' : held.has('shift') ? 'shift' : sticky
|
||||
const q = query.trim().toLowerCase()
|
||||
|
||||
// ---- fit: one key unit from the width the map has ----
|
||||
const fitRef = useRef<HTMLDivElement>(null)
|
||||
const [unit, setUnit] = useState(UNIT_MAX)
|
||||
useLayoutEffect(() => {
|
||||
const el = fitRef.current
|
||||
if (!el) return
|
||||
const fit = () => {
|
||||
const u = Math.floor(el.clientWidth / KEYBOARD_UNITS)
|
||||
setUnit(Math.max(UNIT_MIN, Math.min(UNIT_MAX, u)))
|
||||
}
|
||||
fit()
|
||||
const ro = new ResizeObserver(fit)
|
||||
ro.observe(el)
|
||||
return () => ro.disconnect()
|
||||
}, [])
|
||||
|
||||
// ---- keyboard: pressing a key explains it rather than doing it ----
|
||||
// Capture phase on window, so the deck's and the table's own listeners (which
|
||||
// are on window too, bubbling) never see a key pressed in here.
|
||||
const queryRef = useRef(query)
|
||||
queryRef.current = query
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
let release: number | undefined
|
||||
const onDown = (e: KeyboardEvent) => {
|
||||
const inField = (e.target as HTMLElement | null)?.tagName === 'INPUT'
|
||||
if (e.key === 'Escape') {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
if (inField && queryRef.current) setQuery('')
|
||||
else onClose()
|
||||
return
|
||||
}
|
||||
if (inField) return
|
||||
const mod = modifierLayer(e.code)
|
||||
if (mod) {
|
||||
setHeld((h) => new Set(h).add(mod))
|
||||
return
|
||||
}
|
||||
if (e.code === 'Tab' || !KEYS_BY_CODE[e.code]) return
|
||||
e.stopPropagation()
|
||||
// Space / Enter still press a focused control (a layer tab, a modifier key).
|
||||
const t = e.target as HTMLElement | null
|
||||
if ((e.code === 'Space' || e.code === 'Enter') && t?.tagName === 'BUTTON' && !t.dataset.mapKey) return
|
||||
e.preventDefault()
|
||||
setHover(e.code)
|
||||
setPressed(e.code)
|
||||
window.clearTimeout(release)
|
||||
release = window.setTimeout(() => setPressed(null), 160)
|
||||
}
|
||||
const onUp = (e: KeyboardEvent) => {
|
||||
const mod = modifierLayer(e.code)
|
||||
if (mod) {
|
||||
setHeld((h) => {
|
||||
const next = new Set(h)
|
||||
next.delete(mod)
|
||||
return next
|
||||
})
|
||||
} else if (KEYS_BY_CODE[e.code] && (e.target as HTMLElement | null)?.tagName !== 'INPUT') {
|
||||
e.stopPropagation() // the deck's keyup ends a held cue/hotcue preview
|
||||
}
|
||||
}
|
||||
const onBlur = () => setHeld(new Set())
|
||||
window.addEventListener('keydown', onDown, true)
|
||||
window.addEventListener('keyup', onUp, true)
|
||||
window.addEventListener('blur', onBlur)
|
||||
return () => {
|
||||
window.clearTimeout(release)
|
||||
window.removeEventListener('keydown', onDown, true)
|
||||
window.removeEventListener('keyup', onUp, true)
|
||||
window.removeEventListener('blur', onBlur)
|
||||
}
|
||||
}, [onClose])
|
||||
|
||||
const visible = (l: Layer, code: string) => (binds[l][code] ?? []).filter((b) => areas.has(b.area))
|
||||
const layerCount = (l: Layer) =>
|
||||
Object.values(binds[l]).flat().filter((b) => areas.has(b.area) && (!q || matchText(b).includes(q))).length +
|
||||
MOUSE.flatMap((c) => c.rows).filter((r) => (r.mod ?? 'base') === l && (!q || mouseText(r).includes(q))).length
|
||||
|
||||
const pickLayer = (l: Layer) => setSticky((s) => (s === l && l !== 'base' ? 'base' : l))
|
||||
const toggleArea = (a: Area) =>
|
||||
setAreas((cur) => {
|
||||
const next = new Set(cur)
|
||||
if (next.has(a) && next.size > 1) next.delete(a)
|
||||
else next.add(a)
|
||||
return next
|
||||
})
|
||||
|
||||
const gap = Math.max(2, Math.round(unit / 10))
|
||||
const keyProps = {
|
||||
unit,
|
||||
gap,
|
||||
labels: unit >= LABEL_MIN,
|
||||
short: unit < SHORT_MIN,
|
||||
layer,
|
||||
hover,
|
||||
pressed,
|
||||
q,
|
||||
visible,
|
||||
noted: (code: string) => !!unusedNote(code, slots),
|
||||
bound: (code: string) => LAYERS.some((l) => binds[l][code]),
|
||||
onHover: setHover,
|
||||
onPick: pickLayer,
|
||||
}
|
||||
|
||||
return createPortal(
|
||||
<div
|
||||
aria-modal="true"
|
||||
@@ -114,42 +169,387 @@ export function ShortcutsDialog({ onClose }: Props) {
|
||||
onClick={onClose}
|
||||
>
|
||||
<div
|
||||
className="flex max-h-full w-full max-w-lg flex-col overflow-hidden glass-overlay"
|
||||
className="flex max-h-full w-full max-w-[960px] flex-col overflow-hidden glass-overlay"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="flex items-center justify-between border-b border-line px-5 py-4">
|
||||
<div className="flex flex-wrap items-center gap-3 border-b border-line py-3.5 pl-5 pr-4">
|
||||
<div className="text-[15px] font-semibold tracking-tight">Keyboard Shortcuts</div>
|
||||
<input
|
||||
type="search"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder="Search shortcuts"
|
||||
aria-label="Search shortcuts"
|
||||
className="well ml-auto w-64 min-w-0 rounded-[9px] border border-line px-2.5 py-1.5 text-[13px] text-text outline-none"
|
||||
/>
|
||||
<button
|
||||
onClick={onClose}
|
||||
aria-label="Close"
|
||||
className="rounded px-1.5 text-muted hover:bg-ink-800 hover:text-text"
|
||||
className="h-7 w-7 rounded-md text-lg leading-none text-muted hover:bg-ink-800 hover:text-text"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
<div className="space-y-5 overflow-y-auto px-5 py-4">
|
||||
{sections(slots).map((s) => (
|
||||
<section key={s.title}>
|
||||
<div className="mb-1.5 text-[10px] font-semibold uppercase tracking-wider text-faint">
|
||||
{s.title}
|
||||
</div>
|
||||
<div className="divide-y divide-line/60">
|
||||
{s.rows.map((r, i) => (
|
||||
<div key={i} className="flex items-center justify-between gap-4 py-1.5">
|
||||
<span className="text-sm text-muted">{r.action}</span>
|
||||
<span className="flex shrink-0 items-center gap-1.5">
|
||||
{r.keys.map((combo, j) => (
|
||||
<Keys key={j} combo={combo} />
|
||||
))}
|
||||
</span>
|
||||
|
||||
<div className="overflow-y-auto">
|
||||
<div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2.5 px-5 pb-1 pt-3.5">
|
||||
<div className="well inline-flex flex-wrap gap-0.5 rounded-[10px] p-[3px]">
|
||||
{LAYERS.map((l) => (
|
||||
<button
|
||||
key={l}
|
||||
onClick={() => setSticky(l)}
|
||||
aria-pressed={l === layer}
|
||||
className={`inline-flex items-baseline gap-1.5 rounded-[7px] px-2.5 py-1 text-xs font-medium ${
|
||||
l === layer ? 'bg-ink-600 text-text' : 'text-muted hover:text-text'
|
||||
}`}
|
||||
>
|
||||
{LAYER_NAMES[l]}
|
||||
<span className="font-mono text-[10px] text-faint">{layerCount(l)}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{ALL_AREAS.map((a) => (
|
||||
<button
|
||||
key={a}
|
||||
onClick={() => toggleArea(a)}
|
||||
aria-pressed={areas.has(a)}
|
||||
className={`inline-flex items-center gap-1.5 rounded-full border border-line py-0.5 pl-2 pr-2.5 text-[11.5px] font-medium text-muted ${
|
||||
areas.has(a) ? '' : 'opacity-40'
|
||||
}`}
|
||||
>
|
||||
<i
|
||||
className="h-[7px] w-[7px] rounded-full"
|
||||
style={{ background: AREA_COLORS[a], boxShadow: areas.has(a) ? `0 0 8px ${AREA_COLORS[a]}` : undefined }}
|
||||
/>
|
||||
{AREAS[a]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div ref={fitRef} className="mx-5 mb-2.5 mt-4">
|
||||
<div
|
||||
className="mx-auto flex w-max items-end"
|
||||
style={{ gap: unit * ARROW_GAP }}
|
||||
onPointerLeave={() => setHover(null)}
|
||||
>
|
||||
<div className="flex flex-col" style={{ gap }}>
|
||||
{KEY_ROWS.map((row, i) => (
|
||||
<div key={i} className="flex" style={{ gap, marginBottom: i === 0 ? gap * 0.4 : 0 }}>
|
||||
{row.map((k) => (
|
||||
<Key key={k.code} def={k} fnRow={i === 0} {...keyProps} />
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
<div className="grid" style={{ gap, gridTemplateColumns: `repeat(3, ${unit - gap}px)` }}>
|
||||
{ARROW_KEYS.map((k, i) =>
|
||||
k ? <Key key={k.code} def={k} fnRow={false} {...keyProps} /> : <span key={i} />,
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
aria-live="polite"
|
||||
// A FIXED height, so the dialog does not resize under the pointer as
|
||||
// it moves between keys: tall enough for the fullest key (three
|
||||
// lines + "Also on this key"); search results scroll inside it.
|
||||
className="well mx-5 flex h-32 shrink-0 flex-col gap-[7px] overflow-y-auto rounded-xl px-3.5 py-3 text-[13px] text-muted"
|
||||
>
|
||||
<Caption
|
||||
hover={hover}
|
||||
layer={layer}
|
||||
q={q}
|
||||
query={query}
|
||||
slots={slots}
|
||||
binds={binds}
|
||||
areas={areas}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="px-5 pb-2 pt-5">
|
||||
<div className="mb-2.5 text-[10px] font-semibold uppercase tracking-wider text-faint">Mouse</div>
|
||||
<div className="grid grid-cols-[repeat(auto-fit,minmax(250px,1fr))] gap-x-7 gap-y-2">
|
||||
{MOUSE.map((col) => (
|
||||
<div key={col.title} className="min-w-0">
|
||||
<div className="pb-1.5 text-xs font-semibold text-muted">{col.title}</div>
|
||||
{col.rows.map((r, i) => {
|
||||
const m = r.mod ?? 'base'
|
||||
const hit = !q || mouseText(r).includes(q)
|
||||
const lit = layer !== 'base' && m === layer && hit
|
||||
const dim = (layer !== 'base' && m !== layer) || !hit
|
||||
return (
|
||||
<div
|
||||
key={i}
|
||||
className={`-mx-1.5 grid grid-cols-[minmax(8.5rem,auto)_1fr] items-baseline gap-2.5 rounded-md border-t px-1.5 py-1 text-[12.5px] transition-opacity ${
|
||||
lit ? 'border-transparent bg-accent-soft text-text' : 'border-line text-muted'
|
||||
} ${dim ? 'opacity-30' : ''}`}
|
||||
>
|
||||
<span className="inline-flex flex-wrap items-baseline gap-1">
|
||||
{r.mod && <Kbd>{MODIFIER_KEY[r.mod]}</Kbd>}
|
||||
<span className="inline-flex items-center gap-1 whitespace-nowrap rounded-full border border-dashed border-ink-600 py-px pl-1.5 pr-2 text-[11px] font-medium text-text">
|
||||
<Icon name="mouse" size={11} strokeWidth={2} />
|
||||
{r.gesture}
|
||||
{r.on ? ` ${r.on}` : ''}
|
||||
</span>
|
||||
</span>
|
||||
<span>{r.text}</span>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-2.5 border-t border-line px-5 py-3 text-xs text-faint">
|
||||
Press the <Kbd>?</Kbd> key anywhere to open this list.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
)
|
||||
}
|
||||
|
||||
function Kbd({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<kbd className="min-w-[1.5em] rounded-[5px] border border-b-2 border-line bg-ink-800 px-1.5 py-px text-center font-mono text-[11px] text-text">
|
||||
{children}
|
||||
</kbd>
|
||||
)
|
||||
}
|
||||
|
||||
function Combo({ layer, code }: { layer: Layer; code: string }) {
|
||||
const legend = KEYS_BY_CODE[code]?.legend ?? code
|
||||
return (
|
||||
<span className="inline-flex shrink-0 gap-[3px]">
|
||||
{layer !== 'base' && <Kbd>{MODIFIER_KEY[layer]}</Kbd>}
|
||||
<Kbd>{legend}</Kbd>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
function Line({ layer, code, b, other }: { layer: Layer; code: string; b: Binding; other?: boolean }) {
|
||||
return (
|
||||
<div className={`flex flex-wrap items-baseline gap-2.5 ${other ? 'text-xs' : ''}`}>
|
||||
<Combo layer={layer} code={code} />
|
||||
<span className={`min-w-0 ${other ? 'text-muted' : 'text-text'}`}>{b.text}</span>
|
||||
<span className="text-[9.5px] font-semibold uppercase tracking-wider" style={{ color: AREA_COLORS[b.area] }}>
|
||||
{AREAS[b.area]}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const Sub = ({ children }: { children: ReactNode }) => (
|
||||
<div className="mt-0.5 text-[10px] font-semibold uppercase tracking-wider text-faint">{children}</div>
|
||||
)
|
||||
|
||||
function Caption({
|
||||
hover,
|
||||
layer,
|
||||
q,
|
||||
query,
|
||||
slots,
|
||||
binds,
|
||||
areas,
|
||||
}: {
|
||||
hover: string | null
|
||||
layer: Layer
|
||||
q: string
|
||||
query: string
|
||||
slots: number
|
||||
binds: ReturnType<typeof bindings>
|
||||
areas: ReadonlySet<Area>
|
||||
}) {
|
||||
if (hover) {
|
||||
const role = KEYS_BY_CODE[hover]?.role
|
||||
if (role) {
|
||||
const keys = Object.keys(binds[role]).length
|
||||
const mouse = MOUSE.flatMap((c) => c.rows).filter((r) => r.mod === role).length
|
||||
return (
|
||||
<div className="flex flex-wrap items-baseline gap-2.5">
|
||||
<Kbd>{MODIFIER_KEY[role]}</Kbd>
|
||||
<span className="text-text">
|
||||
Hold, or click, to light up what {LAYER_NAMES[role]} changes: {keys} key{keys === 1 ? '' : 's'} and{' '}
|
||||
{mouse} mouse gesture{mouse === 1 ? '' : 's'}.
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
const here = binds[layer][hover] ?? []
|
||||
const others = LAYERS.filter((l) => l !== layer && binds[l][hover])
|
||||
return (
|
||||
<>
|
||||
{here.length ? (
|
||||
here.map((b, i) => <Line key={i} layer={layer} code={hover} b={b} />)
|
||||
) : (
|
||||
<div className="flex flex-wrap items-baseline gap-2.5">
|
||||
<Combo layer={layer} code={hover} />
|
||||
<span>{unusedNote(hover, slots) ?? 'Does nothing in Konduktor.'}</span>
|
||||
</div>
|
||||
)}
|
||||
{others.length > 0 && <Sub>Also on this key</Sub>}
|
||||
{others.flatMap((l) => binds[l][hover].map((b, i) => <Line key={`${l}${i}`} layer={l} code={hover} b={b} other />))}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
if (q) {
|
||||
const hits = LAYERS.flatMap((l) =>
|
||||
Object.entries(binds[l]).flatMap(([code, bs]) =>
|
||||
bs
|
||||
.filter((b) => areas.has(b.area) && matchText(b).includes(q))
|
||||
.map((b, i) => <Line key={`${l}${code}${i}`} layer={l} code={code} b={b} />),
|
||||
),
|
||||
)
|
||||
const mouse = MOUSE.flatMap((c) => c.rows).filter((r) => mouseText(r).includes(q)).length
|
||||
if (!hits.length && !mouse) return <span>No shortcut matches “{query.trim()}”.</span>
|
||||
return (
|
||||
<>
|
||||
{hits}
|
||||
{mouse > 0 && <Sub>{mouse} mouse gesture{mouse === 1 ? '' : 's'} below</Sub>}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
if (layer !== 'base') {
|
||||
return (
|
||||
<>
|
||||
<span className="text-text">
|
||||
Showing what {LAYER_NAMES[layer]} changes. The highlighted mouse gestures below use it too.
|
||||
</span>
|
||||
<span className="text-xs">Let go of the key, or pick “No modifier”, to go back.</span>
|
||||
</>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<span className="text-text">Point at a key, or press it, to see what it does.</span>
|
||||
<span className="text-xs">
|
||||
Hold <Kbd>{MODIFIER_KEY.shift}</Kbd> or <Kbd>{MODIFIER_KEY.mod}</Kbd>, or pick one above, to see what each
|
||||
modifier changes.
|
||||
</span>
|
||||
<span className="text-xs">
|
||||
{padRange(slots)} are this library's {slots} hotcue pads; Q W E R are the stems of a stem track.
|
||||
</span>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
interface KeyProps {
|
||||
def: KeyDef
|
||||
fnRow: boolean
|
||||
unit: number
|
||||
gap: number
|
||||
labels: boolean
|
||||
short: boolean
|
||||
layer: Layer
|
||||
hover: string | null
|
||||
pressed: string | null
|
||||
q: string
|
||||
visible: (layer: Layer, code: string) => Binding[]
|
||||
noted: (code: string) => boolean
|
||||
bound: (code: string) => boolean
|
||||
onHover: (code: string | null) => void
|
||||
onPick: (layer: Layer) => void
|
||||
}
|
||||
|
||||
function Key({ def, fnRow, unit, gap, labels, short, layer, hover, pressed, q, visible, noted, bound, onHover, onPick }: KeyProps) {
|
||||
const { code, role } = def
|
||||
const legend = short && def.short ? def.short : def.legend
|
||||
const ents = role ? [] : visible(layer, code)
|
||||
const first = ents[0]
|
||||
const kc = first ? (first.color ?? AREA_COLORS[first.area]) : 'var(--color-faint)'
|
||||
const on = role === layer
|
||||
const miss = !!first && !!q && !ents.some((b) => matchText(b).includes(q))
|
||||
const pad = first?.label === 'Pad' || first?.label === 'Delete'
|
||||
const interactive = !!role || bound(code) || noted(code)
|
||||
const inset = Math.max(2, Math.round(unit * 0.1))
|
||||
|
||||
const style: CSSProperties = {
|
||||
width: (def.w ?? 1) * unit - gap,
|
||||
height: fnRow ? Math.round(unit * 0.72) : unit - gap,
|
||||
padding: `${Math.max(2, inset - 1)}px ${inset}px`,
|
||||
borderRadius: pad ? Math.round(unit * 0.18) : Math.round(unit * 0.14),
|
||||
borderColor: 'rgb(255 255 255 / 0.05)',
|
||||
}
|
||||
if (on) {
|
||||
Object.assign(style, {
|
||||
background: 'var(--color-accent)',
|
||||
borderColor: 'transparent',
|
||||
color: 'var(--color-ink-950)',
|
||||
boxShadow: '0 0 22px -4px var(--color-accent)',
|
||||
})
|
||||
} else if (role) {
|
||||
style.borderColor = 'rgb(255 255 255 / 0.12)'
|
||||
} else if (first) {
|
||||
Object.assign(style, {
|
||||
background: pressed === code
|
||||
? `color-mix(in oklab, ${kc} 45%, transparent)`
|
||||
: `color-mix(in oklab, ${kc} ${pad ? 24 : 15}%, rgb(255 255 255 / 0.05))`,
|
||||
borderColor: hover === code
|
||||
? `color-mix(in oklab, ${kc} 85%, white)`
|
||||
: `color-mix(in oklab, ${kc} 50%, transparent)`,
|
||||
boxShadow: `0 0 18px -6px color-mix(in oklab, ${kc} 70%, transparent), inset 0 1px 0 rgb(255 255 255 / 0.1)`,
|
||||
})
|
||||
} else if (hover === code) {
|
||||
style.borderColor = 'rgb(255 255 255 / 0.3)'
|
||||
}
|
||||
|
||||
const legendSize = Math.max(8.5, Math.min(11, unit * 0.22)) - (role && !short ? 1 : 0)
|
||||
const body = (
|
||||
<>
|
||||
<span
|
||||
className={`whitespace-nowrap font-medium leading-none ${first || on ? (on ? '' : 'text-text') : ''}`}
|
||||
style={{ fontSize: legendSize }}
|
||||
>
|
||||
{legend}
|
||||
</span>
|
||||
{labels && first && (
|
||||
<span
|
||||
className="max-w-full overflow-hidden text-ellipsis whitespace-nowrap text-[9px] font-semibold leading-tight"
|
||||
style={{ color: kc }}
|
||||
>
|
||||
{first.label}
|
||||
</span>
|
||||
)}
|
||||
{ents.length > 1 && (
|
||||
<span className="absolute right-1 top-1 flex gap-0.5">
|
||||
{ents.map((b, i) => (
|
||||
<i key={i} className="h-[5px] w-[5px] rounded-full" style={{ background: AREA_COLORS[b.area] }} />
|
||||
))}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
const className = `relative flex shrink-0 flex-col items-start justify-between border text-left transition-[background,border-color,opacity,transform,box-shadow] duration-150 ${
|
||||
first || on ? '' : 'bg-ink-850'
|
||||
} ${role && !on ? 'text-muted' : 'text-faint'} ${miss ? 'opacity-25' : ''} ${pressed === code ? 'scale-[0.96]' : ''}`
|
||||
|
||||
if (!interactive) {
|
||||
return (
|
||||
<span className={className} style={style} onPointerEnter={() => onHover(def.legend ? code : null)}>
|
||||
{body}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={`${className} ${role ? 'cursor-pointer' : 'cursor-help'}`}
|
||||
style={style}
|
||||
aria-label={first ? `${def.legend}: ${first.text}` : def.legend}
|
||||
aria-pressed={role ? on : undefined}
|
||||
data-map-key={role ? undefined : code}
|
||||
onPointerEnter={() => onHover(code)}
|
||||
onFocus={() => onHover(code)}
|
||||
onClick={() => role && onPick(role)}
|
||||
>
|
||||
{body}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -114,9 +114,9 @@ interface RowActions {
|
||||
onCancelDraft: () => void
|
||||
/** Whether a drag of tracks (or of files from the OS) may drop on this playlist. */
|
||||
acceptsTracks: (node: PlaylistNode, p: TracksOrFiles) => boolean
|
||||
/** Tracks dropped on a playlist; `alt` (Option) moves them out of the
|
||||
/** Tracks dropped on a playlist; `mod` (Cmd/Ctrl) moves them out of the
|
||||
* playlist they came from. */
|
||||
onDropTracks: (node: PlaylistNode, p: TracksOrFiles, alt: boolean) => void
|
||||
onDropTracks: (node: PlaylistNode, p: TracksOrFiles, mod: boolean) => void
|
||||
/** Whether a node may be dragged elsewhere in the tree. */
|
||||
canMove: (node: PlaylistNode) => boolean
|
||||
/** A node dropped in the tree: `index` among `parentId`'s children,
|
||||
@@ -227,8 +227,8 @@ function NodeRow({
|
||||
// drop TARGET for tracks. Whether it takes them is the node's own
|
||||
// `can_add_tracks` plus the library being writable, decided by the sidebar.
|
||||
const startDrag = usePressToDrag(() => (renaming ? null : { kind: 'node', node, parentId }))
|
||||
const moves = (p: DragPayload, alt: boolean) =>
|
||||
p.kind === 'tracks' && alt && !!p.fromPlaylist && p.fromPlaylist !== node.id
|
||||
const moves = (p: DragPayload, mod: boolean) =>
|
||||
p.kind === 'tracks' && mod && !!p.fromPlaylist && p.fromPlaylist !== node.id
|
||||
|
||||
// A node held over this row: which zone, and where that puts it. Never into
|
||||
// itself or anything nested in it; a drop that would leave it exactly where
|
||||
@@ -267,14 +267,14 @@ function NodeRow({
|
||||
if (h.zone === 'tracks') {
|
||||
if (p.kind === 'tracks' && p.origin === 'device') return `Import into ${node.name}…`
|
||||
if ((p.kind === 'tracks' && p.origin === 'folder') || p.kind === 'files') return `Add to ${node.name}…`
|
||||
return `${moves(p, at.alt) ? 'Move' : 'Add'} to ${node.name}`
|
||||
return `${moves(p, at.mod) ? 'Move' : 'Add'} to ${node.name}`
|
||||
}
|
||||
if (h.zone === 'peek') return null
|
||||
return h.zone === 'into' || h.zone === 'first' ? `Move into ${node.name}` : `Move ${h.zone} ${node.name}`
|
||||
},
|
||||
onDrop: (p, h, at) => {
|
||||
if (p.kind !== 'node') {
|
||||
if (h.zone === 'tracks') actions.onDropTracks(node, p, at.alt)
|
||||
if (h.zone === 'tracks') actions.onDropTracks(node, p, at.mod)
|
||||
} else if ('parentId' in h) {
|
||||
actions.onMoveNode(p.node, h.parentId, h.index, h.zone === 'into' && !expanded ? node : null)
|
||||
}
|
||||
@@ -678,7 +678,7 @@ export function Sidebar({
|
||||
onError((e as Error).message)
|
||||
}
|
||||
},
|
||||
onDropTracks: async (node, p, alt) => {
|
||||
onDropTracks: async (node, p, mod) => {
|
||||
if (p.kind === 'files') {
|
||||
onAddForeign('dropped', p.paths, { kind: 'playlist', id: node.id, name: node.name })
|
||||
return
|
||||
@@ -693,7 +693,7 @@ export function Sidebar({
|
||||
playlist: node,
|
||||
ids: p.ids,
|
||||
duplicatesAllowed: caps.playlists.duplicates,
|
||||
moveFrom: alt ? p.fromPlaylist : undefined,
|
||||
moveFrom: mod ? p.fromPlaylist : undefined,
|
||||
})
|
||||
if (msg) onDone(msg)
|
||||
} catch (e) {
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
import { createPortal } from 'react-dom'
|
||||
import { useEffect, useState, type ReactNode } from 'react'
|
||||
import type { Track } from '../api'
|
||||
import { formatBpm, formatDuration, keyColor } from '../lib/format'
|
||||
import { useCaps } from '../lib/capabilities'
|
||||
import { Icon } from '../lib/icons'
|
||||
import { RatingStars } from './RatingStars'
|
||||
|
||||
interface Props {
|
||||
track: Track
|
||||
/** The cover's URL, or null where this track's library serves none (a
|
||||
* device or a loose file) — the ambient swatch stands in, as in the deck. */
|
||||
artUrl: string | null
|
||||
onClose: () => void
|
||||
/** Offered only where the library will accept the edit; closes this first. */
|
||||
onEditTags?: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* The deck cover's popup: the art large, beside everything the library knows
|
||||
* about the track. View-only apart from the one way out to Edit Tags. Rows with
|
||||
* no value are left out rather than shown as dashes, so a sparse track reads
|
||||
* as short rather than broken.
|
||||
*/
|
||||
export function TrackInfoDialog({ track, artUrl, onClose, onEditTags }: Props) {
|
||||
const caps = useCaps()
|
||||
const [artFailed, setArtFailed] = useState(false)
|
||||
const showArt = artUrl != null && !artFailed
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [onClose])
|
||||
|
||||
const grid =
|
||||
track.grid_marker_count === 0
|
||||
? null
|
||||
: `${track.grid_marker_count > 1 ? `Flexible · ${track.grid_marker_count} markers` : 'Constant tempo'}${
|
||||
track.grid_locked ? ' · locked' : ''
|
||||
}`
|
||||
const details: [string, ReactNode][] = (
|
||||
[
|
||||
['Album', track.album],
|
||||
['Label', track.label],
|
||||
['Genre', track.genre],
|
||||
['Remixer', track.remixer],
|
||||
['Producer', track.producer],
|
||||
['Mix', track.mix],
|
||||
['Released', track.release_date],
|
||||
['Added', track.import_date],
|
||||
['Last played', track.last_played],
|
||||
['Plays', track.playcount ? String(track.playcount) : null],
|
||||
// The generic bitrate is bits per second.
|
||||
['Bitrate', track.bitrate ? `${Math.round(track.bitrate / 1000)} kbps` : null],
|
||||
['Grid', grid],
|
||||
['Hotcues', track.hotcue_count ? String(track.hotcue_count) : null],
|
||||
['Comment', track.comment],
|
||||
['Comment 2', track.comment2],
|
||||
] as [string, ReactNode][]
|
||||
).filter(([, v]) => v != null && v !== '')
|
||||
|
||||
return createPortal(
|
||||
<div
|
||||
aria-modal="true"
|
||||
role="dialog"
|
||||
aria-label={track.title ?? 'Track info'}
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4 backdrop-blur-[3px]"
|
||||
onClick={onClose}
|
||||
>
|
||||
<div
|
||||
className="track-info-pop glass-overlay flex max-h-[90vh] w-full max-w-[860px] flex-col overflow-hidden sm:flex-row"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{/* The sleeve, bled into the card behind everything: a soft wash of the
|
||||
art's own colours. `filter` on this leaf is safe — nothing can open
|
||||
inside it. */}
|
||||
{showArt && (
|
||||
<img
|
||||
aria-hidden
|
||||
src={artUrl}
|
||||
alt=""
|
||||
// Between the tint (::after, z -1, earlier) and the rim (::before).
|
||||
style={{ zIndex: -1 }}
|
||||
className="pointer-events-none absolute inset-0 h-full w-full scale-125 object-cover opacity-30 blur-3xl saturate-150"
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="relative flex shrink-0 flex-col items-center gap-4 p-6 sm:pr-3">
|
||||
<div
|
||||
className="relative aspect-square w-[min(340px,70vw)] overflow-hidden rounded-2xl shadow-[inset_0_1px_0_rgb(255_255_255/0.35),0_24px_60px_-12px_var(--amb-2)]"
|
||||
style={{ background: 'linear-gradient(135deg, var(--amb-1), var(--amb-2) 55%, var(--amb-3))' }}
|
||||
>
|
||||
{showArt ? (
|
||||
<img
|
||||
src={artUrl}
|
||||
alt={`Cover of ${track.title ?? 'this track'}`}
|
||||
className="absolute inset-0 h-full w-full object-cover"
|
||||
onError={() => setArtFailed(true)}
|
||||
/>
|
||||
) : (
|
||||
<div className="absolute inset-0 flex items-center justify-center text-white/40">
|
||||
<Icon name="music" size={72} strokeWidth={1.2} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{track.rating > 0 && <RatingStars value={track.rating} max={caps.tracks.rating_max} />}
|
||||
</div>
|
||||
|
||||
<div className="relative flex min-h-0 min-w-0 flex-1 flex-col">
|
||||
<div className="min-h-0 flex-1 overflow-y-auto p-6 sm:pl-3">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<h2 className="text-2xl font-semibold leading-tight tracking-tight text-text select-text">
|
||||
{track.title ?? 'Untitled'}
|
||||
</h2>
|
||||
<div className="mt-1 text-[15px] text-muted select-text">{track.artist ?? 'Unknown artist'}</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={onClose}
|
||||
aria-label="Close"
|
||||
className="btn-glass -mr-2 -mt-2 flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-muted hover:text-text"
|
||||
>
|
||||
<Icon name="close" size={14} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="mt-5 flex flex-wrap gap-2">
|
||||
<Stat label="KEY" value={track.key || '—'} color={keyColor(track.key_wheel)} />
|
||||
<Stat label="BPM" value={formatBpm(track.bpm)} />
|
||||
<Stat label="LENGTH" value={formatDuration(track.length)} />
|
||||
{track.media_kind !== 'audio' && <Stat label="TYPE" value={track.media_kind.toUpperCase()} />}
|
||||
</div>
|
||||
|
||||
{details.length > 0 && (
|
||||
<dl className="mt-5 grid grid-cols-[auto_1fr] gap-x-5 gap-y-1.5 border-t border-line pt-4 text-[13px]">
|
||||
{details.map(([label, value]) => (
|
||||
<div key={label} className="contents">
|
||||
<dt className="text-faint">{label}</dt>
|
||||
<dd className="min-w-0 whitespace-pre-wrap break-words text-text select-text">{value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
)}
|
||||
|
||||
{track.filepath && (
|
||||
<div
|
||||
className="well mt-5 rounded-xl px-3 py-2 font-mono text-[11px] leading-relaxed text-muted break-all select-text"
|
||||
title={track.filepath}
|
||||
>
|
||||
{track.filepath}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{onEditTags && (
|
||||
<div className="flex justify-end px-6 pb-6 sm:pl-3">
|
||||
<button
|
||||
onClick={onEditTags}
|
||||
className="btn-glass flex h-9 items-center gap-2 rounded-full px-4 text-[13px] font-medium"
|
||||
>
|
||||
<Icon name="pencil" size={15} />
|
||||
Edit Tags…
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
)
|
||||
}
|
||||
|
||||
function Stat({ label, value, color }: { label: string; value: string; color?: string }) {
|
||||
return (
|
||||
<div className="well flex flex-col gap-px rounded-xl px-4 py-2">
|
||||
<span className="text-[10px] tracking-[0.08em] text-faint">{label}</span>
|
||||
<span className="font-mono text-[17px] font-semibold" style={{ color }}>
|
||||
{value}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
import { CSS } from '@dnd-kit/utilities'
|
||||
import type { Track, TrackOrigin } from '../api'
|
||||
import { beginDrag, useDragPayload, useDropTarget } from '../lib/drag'
|
||||
import { hasMod } from '../lib/modKey'
|
||||
import { TRACK_COLUMNS } from '../lib/trackColumns'
|
||||
|
||||
/** Fields this platform can persist, for the table's per-cell edit gating.
|
||||
@@ -73,11 +74,12 @@ interface Props {
|
||||
* active: reordering a partial or re-sorted list would lose the real order. */
|
||||
reorder?: { enabled: boolean; onReorder: (ids: string[]) => void }
|
||||
/** Where dragged rows come from: whose ids they are, and the editable
|
||||
* playlist they leave on an Option-drag (move). Defaults to the collection. */
|
||||
* playlist they leave on a Cmd/Ctrl-drag (move). Defaults to the collection. */
|
||||
dragFrom?: { origin: TrackOrigin; playlistId?: string }
|
||||
/** Delete/Backspace removes the selected tracks from this view. */
|
||||
onRemove?: (ids: string[]) => void
|
||||
onRowContextMenu?: (track: Track, x: number, y: number) => void
|
||||
/** `viewIds` is every row's id in the order shown (sorted, filtered). */
|
||||
onRowContextMenu?: (track: Track, x: number, y: number, viewIds: string[]) => void
|
||||
/** Right-click on the header row (the column chooser). */
|
||||
onHeaderContextMenu?: (x: number, y: number) => void
|
||||
onPlay?: (track: Track) => void
|
||||
@@ -431,7 +433,7 @@ export function TrackTable({
|
||||
fromPlaylist: from?.playlistId,
|
||||
source: tableKey,
|
||||
},
|
||||
{ x: e.clientX, y: e.clientY, alt: e.altKey },
|
||||
{ x: e.clientX, y: e.clientY, mod: hasMod(e) },
|
||||
)
|
||||
}
|
||||
const release = () => (pressRef.current = null)
|
||||
@@ -579,7 +581,9 @@ export function TrackTable({
|
||||
if (selection && (e.shiftKey || e.metaKey || e.ctrlKey)) e.preventDefault()
|
||||
}}
|
||||
onPointerDown={(e) => {
|
||||
if (e.button !== 0 || e.shiftKey || e.metaKey || e.ctrlKey) return
|
||||
// Cmd/Ctrl arms a drag too (it MOVES the tracks); without
|
||||
// movement it stays a Cmd/Ctrl-click, which toggles the row.
|
||||
if (e.button !== 0 || e.shiftKey || (!hasMod(e) && (e.metaKey || e.ctrlKey))) return
|
||||
// Not from a control inside the row (play, stars, an edit field).
|
||||
if ((e.target as HTMLElement).closest('button, input, textarea, select, a')) return
|
||||
pressRef.current = { x: e.clientX, y: e.clientY, index: vr.index }
|
||||
@@ -591,7 +595,7 @@ export function TrackTable({
|
||||
// Right-clicking outside the selection retargets it, so the
|
||||
// menu always acts on what is highlighted.
|
||||
if (selection && !isSelected) selectOnly(vr.index)
|
||||
onRowContextMenu(row.original, e.clientX, e.clientY)
|
||||
onRowContextMenu(row.original, e.clientX, e.clientY, rows.map((r) => r.original.id))
|
||||
}}
|
||||
>
|
||||
<span className="w-10 shrink-0 pr-2 text-right text-xs tabular-nums text-faint">
|
||||
|
||||
@@ -291,6 +291,18 @@ option {
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- Track info popup (see TrackInfoDialog.tsx) ---------------------- */
|
||||
.track-info-pop {
|
||||
animation: track-info-pop 220ms cubic-bezier(0.2, 0.9, 0.3, 1.15);
|
||||
}
|
||||
@keyframes track-info-pop {
|
||||
from { opacity: 0; transform: translateY(8px) scale(0.96); }
|
||||
to { opacity: 1; transform: none; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.track-info-pop { animation: none; }
|
||||
}
|
||||
|
||||
/* ---- Ambient backdrop (see AmbientBackdrop.tsx) ------------------------ */
|
||||
.ambient-wash {
|
||||
position: absolute;
|
||||
|
||||
@@ -13,7 +13,7 @@ const plural = (n: number) => `${n} track${n === 1 ? '' : 's'}`
|
||||
* elsewhere they are skipped and the message says so. Nothing is asked when
|
||||
* there are none.
|
||||
*
|
||||
* `moveFrom` is an Option-drag out of another (editable) playlist: once the
|
||||
* `moveFrom` is a Cmd/Ctrl-drag out of another (editable) playlist: once the
|
||||
* tracks are in the target they leave the source. Cancelling the duplicates
|
||||
* question cancels the move too.
|
||||
*
|
||||
|
||||
@@ -11,7 +11,7 @@ const TYPE_COLORS: Record<CueType, string> = {
|
||||
load: '#ffd23d', // yellow
|
||||
loop: '#3ddc84', // green
|
||||
}
|
||||
const MEMORY_COLOR = '#9aa1b2' // gray
|
||||
const MEMORY_COLOR = '#9aa1b2' // gray: an unknown type
|
||||
|
||||
export const CUE_TYPE_LABELS: Record<CueType, string> = {
|
||||
cue: 'Cue',
|
||||
@@ -43,7 +43,8 @@ const TYPE_ICONS: Record<CueType, IconName> = {
|
||||
*/
|
||||
export function cueColor(cue: CuePoint): string {
|
||||
if (cue.color) return cue.color
|
||||
if (cue.role === 'memory') return MEMORY_COLOR
|
||||
// A memory cue's type colours it just as a hot cue's does (decided
|
||||
// 2026-10-16) — Traktor draws both by type. Mirrors `core/cue_colors.py`.
|
||||
return TYPE_COLORS[cue.type] ?? MEMORY_COLOR
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { alignShift, mp3HeaderFrame } from './decodeAlign'
|
||||
import { PROBE_MP3_BASE64 } from './decodeProbe'
|
||||
|
||||
/** A stereo MPEG-1 Layer III frame header (128 kbps, 44.1 kHz) followed by
|
||||
* `tag` where a Xing/Info tag would sit, padded to 64 bytes. */
|
||||
function frame(tag = '') {
|
||||
const b = new Uint8Array(64)
|
||||
b.set([0xff, 0xfb, 0x90, 0x00])
|
||||
for (let i = 0; i < tag.length; i++) b[4 + 32 + i] = tag.charCodeAt(i)
|
||||
return b
|
||||
}
|
||||
|
||||
function withId3(body: Uint8Array, size = 1000) {
|
||||
const out = new Uint8Array(10 + size + body.length)
|
||||
out.set([0x49, 0x44, 0x33, 4, 0, 0])
|
||||
out.set([(size >> 21) & 127, (size >> 14) & 127, (size >> 7) & 127, size & 127], 6)
|
||||
out.set(body, 10 + size)
|
||||
return out
|
||||
}
|
||||
|
||||
describe('mp3HeaderFrame', () => {
|
||||
it('sees a Xing / Info header, after an ID3 tag too', () => {
|
||||
expect(mp3HeaderFrame(frame('Xing'))).toBe(true)
|
||||
expect(mp3HeaderFrame(withId3(frame('Info'), 200_000))).toBe(true)
|
||||
})
|
||||
it('sees an MP3 without one', () => {
|
||||
expect(mp3HeaderFrame(frame())).toBe(false)
|
||||
expect(mp3HeaderFrame(withId3(frame()))).toBe(false)
|
||||
})
|
||||
it('reads the built-in probe as header-less', () => {
|
||||
const bytes = Uint8Array.from(atob(PROBE_MP3_BASE64), (c) => c.charCodeAt(0))
|
||||
expect(mp3HeaderFrame(bytes)).toBe(false)
|
||||
})
|
||||
it('is not fooled by a frame sync inside another format', () => {
|
||||
const m4a = new Uint8Array(96)
|
||||
m4a.set([0, 0, 0, 0x20, 0x66, 0x74, 0x79, 0x70]) // ....ftyp
|
||||
m4a.set(frame(), 16)
|
||||
expect(mp3HeaderFrame(m4a)).toBeNull()
|
||||
const flac = withId3(new Uint8Array([0x66, 0x4c, 0x61, 0x43, ...frame()])) // ID3 + fLaC
|
||||
expect(mp3HeaderFrame(flac)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('alignShift', () => {
|
||||
it("prepends what this engine trimmed, only on a header-less MP3", () => {
|
||||
// WebKit measured 529 samples early at 44.1 kHz.
|
||||
const early = -529 / 44100
|
||||
expect(alignShift(false, early, 44100)).toBe(529)
|
||||
expect(alignShift(false, early, 48000)).toBe(Math.round(529 * 48000 / 44100))
|
||||
expect(alignShift(true, early, 44100)).toBe(0)
|
||||
expect(alignShift(null, early, 44100)).toBe(0)
|
||||
expect(alignShift(false, 0, 44100)).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,128 @@
|
||||
// The deck decodes audio in the BROWSER (decodeAudioData), while every stored
|
||||
// position — grids, cues — is in the backend's decoded time base (PyAV/FFmpeg,
|
||||
// `core/waveform.load`). Measured 2026-10-15 with click files: the two agree to
|
||||
// the sample on every format EXCEPT a header-less MP3 under WebKit (the macOS
|
||||
// app's WKWebView), which decodes 529 samples (12 ms) EARLY — CoreAudio trims
|
||||
// the MP3 decoder delay even when no Xing/Info header says to, FFmpeg trims
|
||||
// nothing. Chromium (WebView2) matches FFmpeg. Invisible under 7 ms bars, but
|
||||
// the raw waveform would draw every beat line 12 ms off its kick.
|
||||
//
|
||||
// Rather than hard-code WebKit's number, this engine's offset is MEASURED once,
|
||||
// by decoding a tiny built-in header-less MP3 (`decodeProbe.ts`) whose click
|
||||
// FFmpeg places at a known sample, and a header-less MP3's decoded buffer is
|
||||
// shifted by it — so playback, scratch and both waveforms share the grid's
|
||||
// clock. An MP3 WITH a header was measured to agree on both engines and is
|
||||
// never touched.
|
||||
|
||||
import { PROBE_MP3_BASE64, PROBE_ONSET, PROBE_RATE } from './decodeProbe'
|
||||
|
||||
/** How far past the ID3 tag to look for the first frame (junk, padding). */
|
||||
const SCAN = 64 * 1024
|
||||
|
||||
interface Frame {
|
||||
mpeg1: boolean
|
||||
mono: boolean
|
||||
}
|
||||
|
||||
/** A Layer III frame header at `i`, or null. The backend's
|
||||
* `core/mp3_gapless._frame_header`, kept in step with it. */
|
||||
function frameHeader(b: Uint8Array, i: number): Frame | null {
|
||||
if (i + 4 > b.length || b[i] !== 0xff || (b[i + 1] & 0xe0) !== 0xe0) return null
|
||||
const version = (b[i + 1] >> 3) & 3
|
||||
const layer = (b[i + 1] >> 1) & 3
|
||||
const bitrate = b[i + 2] >> 4
|
||||
const rate = (b[i + 2] >> 2) & 3
|
||||
if (version === 1 || layer !== 1 || bitrate === 0 || bitrate === 15 || rate === 3) return null
|
||||
return { mpeg1: version === 3, mono: b[i + 3] >> 6 === 3 }
|
||||
}
|
||||
|
||||
const ascii = (b: Uint8Array, i: number, n: number) => String.fromCharCode(...b.subarray(i, i + n))
|
||||
|
||||
/**
|
||||
* Whether `bytes` is an MP3 whose first frame is a Xing / Info / VBRI header
|
||||
* (true), an MP3 without one (false), or not an MP3 at all (null). The header
|
||||
* test is the backend's `core/mp3_gapless.parse`; the "is it an MP3" gate is
|
||||
* extra, because this sees every format the deck plays and a stray frame sync
|
||||
* inside an M4A or FLAC must not count. An MP3 starts with an ID3v2 tag or with
|
||||
* a frame — nothing else this app plays does (FLAC, RIFF, ftyp, FORM, OggS).
|
||||
*/
|
||||
export function mp3HeaderFrame(b: Uint8Array): boolean | null {
|
||||
let start = 0
|
||||
if (b.length >= 10 && b[0] === 0x49 && b[1] === 0x44 && b[2] === 0x33) {
|
||||
const size = ((b[6] & 127) << 21) | ((b[7] & 127) << 14) | ((b[8] & 127) << 7) | (b[9] & 127)
|
||||
start = 10 + size + (b[5] & 0x10 ? 10 : 0)
|
||||
if (ascii(b, start, 4) === 'fLaC') return null // a FLAC carrying a (non-standard) ID3 tag
|
||||
} else if (!frameHeader(b, 0)) {
|
||||
return null
|
||||
}
|
||||
const end = Math.min(b.length - 4, start + SCAN)
|
||||
for (let i = start; i < end; i++) {
|
||||
const h = frameHeader(b, i)
|
||||
if (!h) continue
|
||||
const side = h.mpeg1 ? (h.mono ? 17 : 32) : h.mono ? 9 : 17
|
||||
const tag = ascii(b, i + 4 + side, 4)
|
||||
if (tag === 'Xing' || tag === 'Info') return true
|
||||
return ascii(b, i + 36, 4) === 'VBRI'
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** The first sample of the probe's click (a quarter of its peak), or -1. */
|
||||
function clickOnset(buf: AudioBuffer): number {
|
||||
const d = new Float32Array(buf.length)
|
||||
buf.copyFromChannel(d, 0)
|
||||
let peak = 0
|
||||
for (let i = 0; i < d.length; i++) peak = Math.max(peak, Math.abs(d[i]))
|
||||
if (peak <= 0) return -1
|
||||
for (let i = 0; i < d.length; i++) if (Math.abs(d[i]) > peak * 0.25) return i
|
||||
return -1
|
||||
}
|
||||
|
||||
async function measure(): Promise<number> {
|
||||
const bytes = Uint8Array.from(atob(PROBE_MP3_BASE64), (c) => c.charCodeAt(0))
|
||||
const buf = await new OfflineAudioContext(1, 1, PROBE_RATE).decodeAudioData(bytes.buffer)
|
||||
const onset = clickOnset(buf)
|
||||
// An onset nowhere near the click means the probe did not decode sensibly;
|
||||
// shifting by it would be worse than the 12 ms it exists to fix.
|
||||
if (onset < 0 || Math.abs(onset - PROBE_ONSET) > 4096) return 0
|
||||
return (onset - PROBE_ONSET) / PROBE_RATE
|
||||
}
|
||||
|
||||
let offset: Promise<number> | null = null
|
||||
|
||||
/** Seconds by which this engine decodes a header-less MP3 AHEAD of FFmpeg
|
||||
* (negative = its audio starts earlier). Measured once per session; 0 if the
|
||||
* probe cannot be decoded. */
|
||||
export function headerlessMp3Offset(): Promise<number> {
|
||||
return (offset ??= measure().catch(() => 0))
|
||||
}
|
||||
|
||||
/**
|
||||
* Samples to PREPEND (negative: drop from the start) to a buffer this engine
|
||||
* decoded, to put it in the backend's time base. `header` is
|
||||
* `mp3HeaderFrame` of the file's bytes, read before decoding detaches them.
|
||||
*/
|
||||
export function alignShift(header: boolean | null, offsetSec: number, sampleRate: number): number {
|
||||
return header === false ? Math.round(-offsetSec * sampleRate) || 0 : 0
|
||||
}
|
||||
|
||||
/** `buffer`, decoded by this engine from a file whose `mp3HeaderFrame` is
|
||||
* `header`, moved into the backend's time base (the same buffer if no move). */
|
||||
export async function alignDecoded(buffer: AudioBuffer, header: boolean | null): Promise<AudioBuffer> {
|
||||
if (header !== false) return buffer
|
||||
const shift = alignShift(header, await headerlessMp3Offset(), buffer.sampleRate)
|
||||
if (shift === 0) return buffer
|
||||
const out = new AudioBuffer({
|
||||
length: Math.max(1, buffer.length + shift),
|
||||
numberOfChannels: buffer.numberOfChannels,
|
||||
sampleRate: buffer.sampleRate,
|
||||
})
|
||||
// copyFromChannel, never getChannelData: see the detach gotcha in scratchEngine.
|
||||
const tmp = new Float32Array(buffer.length)
|
||||
for (let c = 0; c < buffer.numberOfChannels; c++) {
|
||||
buffer.copyFromChannel(tmp, c)
|
||||
if (shift > 0) out.copyToChannel(tmp, c, shift)
|
||||
else out.copyToChannel(tmp.subarray(-shift), c, 0)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// A 0.3 s mono 44.1 kHz MP3, 64 kbps, encoded by LAME (via FFmpeg) WITHOUT a
|
||||
// Xing/Info header: silence with a 64-sample click at 0.1 s. FFmpeg decodes the
|
||||
// click at sample PROBE_ONSET — 4410 + 1105 samples of start padding it does not
|
||||
// trim, having no header to say how much. See decodeAlign.ts for its use.
|
||||
|
||||
export const PROBE_RATE = 44100
|
||||
export const PROBE_ONSET = 5515
|
||||
|
||||
export const PROBE_MP3_BASE64 =
|
||||
'SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjYyLjEyLjEwMgAAAAAAAAAAAAAA//tQxAADwAABpAAAACAAADSAAAAETEFNRTMu' +
|
||||
'MTAwVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUxBTUUzLjEwMFVVVVVVVVVVVVVVVVVVVVVV' +
|
||||
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVf/7UsRdg8AAAaQAAAAgAAA0gAAABFVVVVVVVVVVVVVVVVVV' +
|
||||
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVKKKKKKKKKKKK/wgdhBp1G6J/rUrOW2H/vW0ArmeSx1nA' +
|
||||
'Bvz47A8DIdw8/5YO8PZPH0bThO/80JBY9Meh+aUjp//Pzew4xQdy9kn//pM3PsNDizVDyVt///emf4ZFaJ2FDa5NVv///e+2' +
|
||||
'MY972MpJd0tRpyR7////9nNzexlPfbGTJrUG12ih//tSxKGDwAABpAAAACAAADSAAAAElGgywARRdQUoCyGCWFuOpvQ2OnTR' +
|
||||
'OlxYmJXK7DgEFJORBQDTkSM5RIlIiBoeCodWCrlgrLA0oGoKhsShosDTgaeJQ3yzvEUqCqw1ER4seWCvUHP/qBrlTvBpTEFN' +
|
||||
'RTMuMTAwVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVX/+1LEoYPAAAGkAAAAIAAANIKAAARVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUxBTUUzLjEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||
'VVVVVVVVVVVVVVVVVVVVVf/7UsT/gBEVjXM5lYAZYIlno55gAFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||
'VVVVVVVVVVVVVVVVVVVVVVVVTEFNRTMuMTAwVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||
'VVVVVVVVVVVV//tSxKGDwAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||
'VVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||
'VVX/+1LEoYPAAAGkAAAAIAAANIAAAARVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||
'VVVVVUxBTUUzLjEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVf/7UsSh' +
|
||||
'g8AAAaQAAAAgAAA0gAAABFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVTEFN' +
|
||||
'RTMuMTAwVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//tSxKGDwAABpAAA' +
|
||||
'ACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBV' +
|
||||
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVX/+1LEoYPAAAGkAAAAIAAANIAA' +
|
||||
'AARVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVUxBTUUzLjEwMFVVVVVVVVVV' +
|
||||
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVf/7UsShg8AAAaQAAAAgAAA0gAAABFVVVVVV' +
|
||||
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVTEFNRTMuMTAwVVVVVVVVVVVVVVVVVVVV' +
|
||||
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//tSxKGDwAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVV' +
|
||||
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVX/+1LEoYPAAAGkAAAAIAAANIAAAARVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV' +
|
||||
'VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVQ=='
|
||||
+17
-16
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useRef, useSyncExternalStore } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import type { PlaylistNode, Track, TrackOrigin } from '../api'
|
||||
import { Icon } from './icons'
|
||||
import { hasMod, MOD_KEY } from './modKey'
|
||||
|
||||
/**
|
||||
* Drag and drop across the whole window: track rows onto sidebar playlists,
|
||||
@@ -38,7 +39,7 @@ export type DragPayload =
|
||||
/** Which library the ids belong to — a device's or a folder's are not
|
||||
* the collection's, so collection targets must not take them as such. */
|
||||
origin: TrackOrigin
|
||||
/** The editable playlist they were dragged out of, for Option = move. */
|
||||
/** The editable playlist they were dragged out of, for Cmd/Ctrl = move. */
|
||||
fromPlaylist?: string
|
||||
/** Identity of the table that started the drag (its own reorder target). */
|
||||
source: object
|
||||
@@ -54,8 +55,8 @@ export type TracksOrFiles = Exclude<DragPayload, { kind: 'node' }>
|
||||
export interface DropPoint {
|
||||
x: number
|
||||
y: number
|
||||
/** Option/Alt held: tracks dragged out of a playlist MOVE instead of copy. */
|
||||
alt: boolean
|
||||
/** Cmd (macOS) / Ctrl held: tracks dragged out of a playlist MOVE instead of copy. */
|
||||
mod: boolean
|
||||
}
|
||||
|
||||
export interface DropSpec<H> {
|
||||
@@ -73,13 +74,13 @@ interface State {
|
||||
payload: DragPayload | null
|
||||
x: number
|
||||
y: number
|
||||
alt: boolean
|
||||
mod: boolean
|
||||
target: HTMLElement | null
|
||||
hint: unknown
|
||||
label: string | null
|
||||
}
|
||||
|
||||
const IDLE: State = { payload: null, x: 0, y: 0, alt: false, target: null, hint: null, label: null }
|
||||
const IDLE: State = { payload: null, x: 0, y: 0, mod: false, target: null, hint: null, label: null }
|
||||
let state: State = IDLE
|
||||
const listeners = new Set<() => void>()
|
||||
const targets = new Map<HTMLElement, { current: DropSpec<unknown> }>()
|
||||
@@ -107,9 +108,9 @@ function sameHint(a: unknown, b: unknown): boolean {
|
||||
|
||||
/** Find the innermost target under the pointer that accepts, and record its hint. */
|
||||
function evaluate() {
|
||||
const { payload, x, y, alt } = state
|
||||
const { payload, x, y, mod } = state
|
||||
if (!payload) return
|
||||
const at = { x, y, alt }
|
||||
const at = { x, y, mod }
|
||||
let el = document.elementFromPoint(x, y) as HTMLElement | null
|
||||
while (el) {
|
||||
const spec = targets.get(el)
|
||||
@@ -130,19 +131,19 @@ let detach: (() => void) | null = null
|
||||
|
||||
/** End the drag in progress, dropping on the target under the pointer if `drop`. */
|
||||
function finish(drop: boolean) {
|
||||
const { payload: p, target, hint, x, y, alt } = state
|
||||
const { payload: p, target, hint, x, y, mod } = state
|
||||
detach?.()
|
||||
if (!drop || !p || !target) return
|
||||
const spec = targets.get(target)
|
||||
try {
|
||||
spec?.current.onDrop(p, hint, { x, y, alt })
|
||||
spec?.current.onDrop(p, hint, { x, y, mod })
|
||||
} catch (err) {
|
||||
console.error('drop failed', err)
|
||||
}
|
||||
}
|
||||
|
||||
/** Publish a new drag and start edge auto-scroll. Returns what undoes both. */
|
||||
function open(payload: DragPayload, at: { x: number; y: number; alt: boolean }): () => void {
|
||||
function open(payload: DragPayload, at: { x: number; y: number; mod: boolean }): () => void {
|
||||
detach?.()
|
||||
set({ ...IDLE, payload, ...at })
|
||||
document.documentElement.classList.add('is-dragging')
|
||||
@@ -188,12 +189,12 @@ function open(payload: DragPayload, at: { x: number; y: number; alt: boolean }):
|
||||
}
|
||||
|
||||
/** Start a drag. Call it once the press has moved past the source's threshold. */
|
||||
export function beginDrag(payload: DragPayload, at: { x: number; y: number; alt: boolean }) {
|
||||
export function beginDrag(payload: DragPayload, at: { x: number; y: number; mod: boolean }) {
|
||||
const close = open(payload, at)
|
||||
|
||||
const onMove = (e: PointerEvent) => {
|
||||
// One notification per move: evaluate() publishes the position with the hint.
|
||||
state = { ...state, x: e.clientX, y: e.clientY, alt: e.altKey }
|
||||
state = { ...state, x: e.clientX, y: e.clientY, mod: hasMod(e) }
|
||||
evaluate()
|
||||
}
|
||||
const onUp = () => finish(true)
|
||||
@@ -206,8 +207,8 @@ export function beginDrag(payload: DragPayload, at: { x: number; y: number; alt:
|
||||
finish(false)
|
||||
return
|
||||
}
|
||||
if (e.key === 'Alt' && state.alt !== (e.type === 'keydown')) {
|
||||
set({ alt: e.type === 'keydown' })
|
||||
if (e.key === MOD_KEY && state.mod !== (e.type === 'keydown')) {
|
||||
set({ mod: e.type === 'keydown' })
|
||||
evaluate()
|
||||
}
|
||||
}
|
||||
@@ -240,7 +241,7 @@ export function beginDrag(payload: DragPayload, at: { x: number; y: number; alt:
|
||||
|
||||
/** A drag the OS owns (files from Finder / Explorer): it enters the window… */
|
||||
export function nativeDragStart(payload: DragPayload, at: { x: number; y: number }) {
|
||||
const close = open(payload, { ...at, alt: false })
|
||||
const close = open(payload, { ...at, mod: false })
|
||||
detach = () => {
|
||||
detach = null
|
||||
close()
|
||||
@@ -276,7 +277,7 @@ export function usePressToDrag(make: () => DragPayload | null): (e: React.Pointe
|
||||
if (Math.hypot(m.clientX - start.x, m.clientY - start.y) < 6) return
|
||||
stop()
|
||||
const payload = makeRef.current()
|
||||
if (payload) beginDrag(payload, { x: m.clientX, y: m.clientY, alt: m.altKey })
|
||||
if (payload) beginDrag(payload, { x: m.clientX, y: m.clientY, mod: hasMod(m) })
|
||||
}
|
||||
const stop = () => {
|
||||
window.removeEventListener('pointermove', onMove)
|
||||
|
||||
@@ -25,6 +25,7 @@ const PATHS = {
|
||||
),
|
||||
sparkle: <path d="M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8zM19 16l.7 1.8 1.8.7-1.8.7L19 21l-.7-1.8-1.8-.7 1.8-.7z" strokeLinejoin="round" />,
|
||||
wave: <path d="M3 12h2M7 8v8M11 5v14M15 9v6M19 11v2" />,
|
||||
sine: <path d="M2 12c2.5-8 5-8 7.5 0s5 8 7.5 0 3.5-5 5-3" strokeLinejoin="round" />,
|
||||
folder: <path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" strokeLinejoin="round" />,
|
||||
folderOpen: <path d="M3 7a2 2 0 0 1 2-2h4l2 2h6a2 2 0 0 1 2 2v1M3 7v10a2 2 0 0 0 2 2h12.5a2 2 0 0 0 1.9-1.4L21 12a1 1 0 0 0-1-1.3H8.5a2 2 0 0 0-1.9 1.4L4 19" strokeLinejoin="round" />,
|
||||
playlist: <path d="M8 6h13M8 12h13M8 18h13M3.5 6h.01M3.5 12h.01M3.5 18h.01" />,
|
||||
@@ -98,6 +99,12 @@ const PATHS = {
|
||||
fadeOut: <path d="M3 5l18 14H3z" strokeLinejoin="round" />,
|
||||
eject: <path d="M12 4l8 9H4zM4 18h16" strokeLinejoin="round" />,
|
||||
grid: <path d="M5 3v18M10 3v18M15 3v18M20 3v18" />,
|
||||
mouse: (
|
||||
<>
|
||||
<rect x="6" y="3" width="12" height="18" rx="6" />
|
||||
<path d="M12 7v3" />
|
||||
</>
|
||||
),
|
||||
} as const
|
||||
|
||||
export type IconName = keyof typeof PATHS
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
// The platform's command modifier: Cmd on macOS, Ctrl elsewhere. For mouse
|
||||
// gestures it is exactly that key — on macOS, Ctrl+click is a right-click, so
|
||||
// accepting either (as the keyboard shortcuts do) would start a drag under a
|
||||
// context menu.
|
||||
|
||||
export const IS_MAC = /Mac|iPhone|iPad/.test(navigator.userAgent)
|
||||
|
||||
/** Whether the command modifier is held. */
|
||||
export const hasMod = (e: { metaKey: boolean; ctrlKey: boolean }) => (IS_MAC ? e.metaKey : e.ctrlKey)
|
||||
|
||||
/** Its `KeyboardEvent.key`, for following it being pressed mid-gesture. */
|
||||
export const MOD_KEY = IS_MAC ? 'Meta' : 'Control'
|
||||
|
||||
/** Its name in a tooltip ("Cmd-click"). */
|
||||
export const MOD_NAME = IS_MAC ? 'Cmd' : 'Ctrl'
|
||||
@@ -27,6 +27,25 @@ describe('moveToPosition', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('moveToPosition with a view order', () => {
|
||||
const sorted = (ids: string[], position: number, view: string[]) =>
|
||||
moveToPosition(order, new Set(ids), position, view).join('')
|
||||
|
||||
it('moves the block in the order the view shows it', () => {
|
||||
expect(sorted(['B', 'E', 'F'], 1, ['F', 'B', 'E'])).toBe('FBEACDG')
|
||||
expect(sorted(['B', 'E', 'F'], 3, ['E', 'F', 'B'])).toBe('ACEFBDG')
|
||||
})
|
||||
|
||||
it('ignores view ids that are not moving', () => {
|
||||
expect(sorted(['B', 'D'], 1, ['G', 'D', 'A', 'B'])).toBe('DBACEFG')
|
||||
})
|
||||
|
||||
it('keeps a twice-listed track together, and appends a track the view lacks', () => {
|
||||
expect(moveToPosition(['A', 'B', 'A', 'C'], new Set(['A', 'C']), 1, ['C', 'A']).join('')).toBe('CAAB')
|
||||
expect(sorted(['B', 'C'], 1, ['C'])).toBe('CBADEFG')
|
||||
})
|
||||
})
|
||||
|
||||
describe('maxPosition', () => {
|
||||
it('leaves room for the block behind its first track', () => {
|
||||
expect(maxPosition(order, new Set(['B']))).toBe(7)
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
/** A playlist's entry order with `moving` lifted out as one block, kept in
|
||||
* their PLAYLIST order, and put back so the block's first track lands at the
|
||||
* 1-based `position` of the result. A position past the end puts the block
|
||||
* last. A track listed twice in the playlist moves with both entries, since a
|
||||
* selection is by track id. */
|
||||
export function moveToPosition(order: string[], moving: ReadonlySet<string>, position: number): string[] {
|
||||
const block = order.filter((id) => moving.has(id))
|
||||
/** A playlist's entry order with `moving` lifted out as one block and put
|
||||
* back so the block's first track lands at the 1-based `position` of the
|
||||
* result. A position past the end puts the block last. The block keeps the
|
||||
* tracks' PLAYLIST order, or with `blockOrder` (the ids as a sorted view
|
||||
* shows them) that order instead — so a sort can be written into the
|
||||
* playlist. A track listed twice in the playlist moves with both entries,
|
||||
* since a selection is by track id; in `blockOrder` they stay together. */
|
||||
export function moveToPosition(
|
||||
order: string[],
|
||||
moving: ReadonlySet<string>,
|
||||
position: number,
|
||||
blockOrder?: readonly string[],
|
||||
): string[] {
|
||||
const block = blockOrder ? orderBlock(order, moving, blockOrder) : order.filter((id) => moving.has(id))
|
||||
const rest = order.filter((id) => !moving.has(id))
|
||||
const at = Math.min(Math.max(Math.floor(position), 1) - 1, rest.length)
|
||||
return [...rest.slice(0, at), ...block, ...rest.slice(at)]
|
||||
@@ -15,3 +22,18 @@ export function moveToPosition(order: string[], moving: ReadonlySet<string>, pos
|
||||
export function maxPosition(order: string[], moving: ReadonlySet<string>): number {
|
||||
return order.length - order.filter((id) => moving.has(id)).length + 1
|
||||
}
|
||||
|
||||
/** The moving entries in `blockOrder`'s order, each track's repeats together.
|
||||
* A moving track `blockOrder` lacks (none should) follows in playlist order. */
|
||||
function orderBlock(order: string[], moving: ReadonlySet<string>, blockOrder: readonly string[]): string[] {
|
||||
const counts = new Map<string, number>()
|
||||
for (const id of order) if (moving.has(id)) counts.set(id, (counts.get(id) ?? 0) + 1)
|
||||
const block: string[] = []
|
||||
for (const id of [...blockOrder, ...order]) {
|
||||
const n = counts.get(id)
|
||||
if (!n) continue
|
||||
for (let i = 0; i < n; i++) block.push(id)
|
||||
counts.delete(id)
|
||||
}
|
||||
return block
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { laneScales, makeSpans, rawSpans, rawWaveFromMono, RAW_BLOCK, tintAt } from './rawWave'
|
||||
import type { WaveColumn } from './waveform'
|
||||
|
||||
const SR = 44100
|
||||
|
||||
/** `sec` of silence with a one-sample click of `amp` at sample `at`. */
|
||||
function click(sec: number, at: number, amp = 0.8) {
|
||||
const mono = new Float32Array(Math.round(sec * SR))
|
||||
mono[at] = amp
|
||||
return rawWaveFromMono(mono, SR)
|
||||
}
|
||||
|
||||
/** The bin whose centre time is nearest `sec`. */
|
||||
const binAt = (s: ReturnType<typeof makeSpans>, sec: number) => {
|
||||
let best = 0
|
||||
for (let k = 0; k < s.n; k++) if (Math.abs(s.t[k] - sec) < Math.abs(s.t[best] - sec)) best = k
|
||||
return best
|
||||
}
|
||||
|
||||
describe('rawWaveFromMono', () => {
|
||||
it('summarises min/max per block and finds the peak', () => {
|
||||
const mono = new Float32Array(RAW_BLOCK * 3)
|
||||
mono[5] = 0.5
|
||||
mono[RAW_BLOCK + 7] = -0.9
|
||||
const raw = rawWaveFromMono(mono, SR)
|
||||
expect(raw.min.length).toBe(3)
|
||||
expect(raw.max[0]).toBeCloseTo(0.5)
|
||||
expect(raw.min[1]).toBeCloseTo(-0.9)
|
||||
expect(raw.peak).toBeCloseTo(0.9)
|
||||
})
|
||||
})
|
||||
|
||||
describe('rawSpans', () => {
|
||||
// A 0.25 s view across 1200 px: ~9 samples a pixel — the SAMPLE path.
|
||||
// A 16 s view: ~588 a pixel — the BLOCK path.
|
||||
for (const [label, view] of [['deep zoom', 0.25], ['wide zoom', 16]] as const) {
|
||||
it(`puts a click in the pixel that holds it (${label})`, () => {
|
||||
const at = 2 * SR + 123
|
||||
const raw = click(30, at)
|
||||
const w = 1200
|
||||
const start = at / SR - view / 2
|
||||
const s = rawSpans(raw, start, start + view, w, makeSpans())
|
||||
const k = binAt(s, at / SR)
|
||||
expect(s.hi[k]).toBeCloseTo(0.8)
|
||||
// Its pixel is where the playhead (the view's centre) is.
|
||||
expect(Math.abs(Math.round(s.x0 + k) - w / 2)).toBeLessThanOrEqual(1)
|
||||
// Far from it, silence.
|
||||
expect(s.hi[k + 20]).toBe(0)
|
||||
expect(s.hi[k - 20]).toBe(0)
|
||||
})
|
||||
}
|
||||
|
||||
it('leaves bins outside the track empty', () => {
|
||||
const raw = click(1, 100)
|
||||
const s = rawSpans(raw, -0.5, 0.5, 1000, makeSpans())
|
||||
expect(Number.isNaN(s.lo[10])).toBe(true)
|
||||
expect(Number.isNaN(s.lo[900])).toBe(false)
|
||||
})
|
||||
|
||||
it('draws a sine as one continuous line at deep zoom', () => {
|
||||
const mono = new Float32Array(SR)
|
||||
for (let i = 0; i < mono.length; i++) mono[i] = Math.sin((2 * Math.PI * 60 * i) / SR) * 0.7
|
||||
const s = rawSpans(rawWaveFromMono(mono, SR), 0.4, 0.65, 1200, makeSpans())
|
||||
for (let k = 1; k < s.n; k++) {
|
||||
// Each stroke overlaps the previous: no gap a line could fall through.
|
||||
expect(s.lo[k]).toBeLessThanOrEqual(s.hi[k - 1] + 1e-6)
|
||||
expect(s.hi[k]).toBeGreaterThanOrEqual(s.lo[k - 1] - 1e-6)
|
||||
}
|
||||
})
|
||||
|
||||
it('interpolates when a pixel is narrower than a sample', () => {
|
||||
const mono = new Float32Array(SR)
|
||||
for (let i = 0; i < mono.length; i++) mono[i] = i / mono.length
|
||||
// 0.01 s across 4000 px: ~0.11 samples a pixel.
|
||||
const s = rawSpans(rawWaveFromMono(mono, SR), 0.5, 0.51, 4000, makeSpans())
|
||||
const k = 2000
|
||||
expect(s.lo[k]).toBeCloseTo(s.t[k], 3)
|
||||
})
|
||||
|
||||
it('agrees with itself across the block/sample switch-over', () => {
|
||||
const mono = new Float32Array(10 * SR)
|
||||
for (let i = 0; i < mono.length; i++) mono[i] = Math.sin(i * 0.001) * Math.sin(i * 0.37) * 0.9
|
||||
const raw = rawWaveFromMono(mono, SR)
|
||||
const w = 1000
|
||||
// Just either side of 128 samples a pixel.
|
||||
const sample = rawSpans(raw, 1, 1 + (127 * w) / SR, w, makeSpans())
|
||||
const block = rawSpans(raw, 1, 1 + (129 * w) / SR, w, makeSpans())
|
||||
// At the same time, the block path's extent contains the sample path's
|
||||
// (it may smear by part of a block, never miss a peak).
|
||||
for (const k of [100, 400, 700]) {
|
||||
const j = binAt(block, sample.t[k])
|
||||
const near = [j - 1, j, j + 1]
|
||||
expect(Math.min(...near.map((i) => block.lo[i]))).toBeLessThanOrEqual(sample.lo[k] + 1e-6)
|
||||
expect(Math.max(...near.map((i) => block.hi[i]))).toBeGreaterThanOrEqual(sample.hi[k] - 1e-6)
|
||||
}
|
||||
})
|
||||
|
||||
it('bins in track space, so scrolling does not regroup samples', () => {
|
||||
const mono = new Float32Array(4 * SR)
|
||||
for (let i = 0; i < mono.length; i++) mono[i] = Math.sin(i * 0.013) * Math.sin(i * 0.41)
|
||||
const raw = rawWaveFromMono(mono, SR)
|
||||
const w = 800
|
||||
const view = 8 // wide: block path
|
||||
const a = rawSpans(raw, 0.5, 0.5 + view, w, makeSpans())
|
||||
const lo = Array.from(a.lo.subarray(0, a.n))
|
||||
const shift = (view / w) * 0.37 // a fraction of a pixel
|
||||
const b = rawSpans(raw, 0.5 + shift, 0.5 + shift + view, w, makeSpans())
|
||||
expect(Array.from(b.lo.subarray(0, b.n))).toEqual(lo)
|
||||
})
|
||||
})
|
||||
|
||||
describe('laneScales', () => {
|
||||
it('scales each stem by its own peak', () => {
|
||||
const [a, b] = laneScales([1, 0.5], 100)
|
||||
expect(a).toBeCloseTo(100)
|
||||
expect(b).toBeCloseTo(200)
|
||||
})
|
||||
it('never magnifies a near-silent stem past 5% of the loudest', () => {
|
||||
const [, quiet] = laneScales([1, 0.001], 100)
|
||||
expect(quiet).toBeCloseTo(100 / 0.05)
|
||||
})
|
||||
})
|
||||
|
||||
describe('tintAt', () => {
|
||||
const col = (low: number, mid: number, high: number): WaveColumn => ({ peak: 1, low, mid, high })
|
||||
const rgb = (s: string) => s.slice(4, -1).split(',').map(Number)
|
||||
const saturation = (s: string) => Math.max(...rgb(s)) - Math.min(...rgb(s))
|
||||
it('keeps each band its bar colour', () => {
|
||||
const [r, g, b] = rgb(tintAt([col(1, 0, 0)], 1, 0.5))
|
||||
expect(r).toBeGreaterThan(g)
|
||||
expect(g).toBeGreaterThan(b) // orange
|
||||
const [r2, , b2] = rgb(tintAt([col(0, 0, 1)], 1, 0.5))
|
||||
expect(b2).toBeGreaterThan(r2) // cyan
|
||||
})
|
||||
it('never greys out where bands mix', () => {
|
||||
// A plain weighted mean of orange + violet + cyan spreads only 26-56 here.
|
||||
for (const mix of [col(1, 1, 1), col(1, 0, 1), col(0.6, 1, 0.4)]) {
|
||||
expect(saturation(tintAt([mix], 1, 0.5))).toBeGreaterThan(90)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,362 @@
|
||||
// The RAW waveform: the main view's alternative to bars (the toggle under its
|
||||
// zoom buttons, persisted as `mainWaveRaw`), after Traktor at full zoom — a thin
|
||||
// signed line of the actual signal, its colour shifting with the frequency mix.
|
||||
// The bars (`waveform.ts`) draw ~7 ms columns of unsigned band energy, which
|
||||
// hides where a kick actually starts; this draws the samples.
|
||||
//
|
||||
// Decided (discussion 2026-10-15): the SHAPE is exact and the COLOUR is
|
||||
// approximate — the tint comes from the bars' ~7 ms band columns, in the bars'
|
||||
// palette blended in OKLab (`bandColour`), lerped between columns. The vertical scale is fixed by the track's
|
||||
// loudest sample, so relative loudness is truthful and the height never pumps
|
||||
// while scrolling.
|
||||
//
|
||||
// Two data paths, by how many samples one pixel covers:
|
||||
// * many (wide zoom): min/max per RAW_BLOCK samples, summarised once at load
|
||||
// (~4 MB for a 6-minute track) — a 64 s view reads ~90k block values;
|
||||
// * few (deep zoom): the visible window read straight from the decoded
|
||||
// AudioBuffer each frame. No full-length mono copy is kept; the playback
|
||||
// engine holds the buffer anyway.
|
||||
// Each pixel is a vertical stroke from the lowest to the highest sample in it,
|
||||
// stretched to touch its neighbour's — zoomed out it reads as a filled
|
||||
// envelope, zoomed in it narrows to one continuous line, with no switch-over.
|
||||
|
||||
import type { WaveColumn } from './waveform'
|
||||
|
||||
/** Samples per entry of the min/max summary. */
|
||||
export const RAW_BLOCK = 32
|
||||
/** Below this many samples per pixel, read samples instead of blocks: a pixel
|
||||
* then spans at least 4 blocks, so block edges smear it by at most a quarter. */
|
||||
const SAMPLE_PATH_BELOW = 4 * RAW_BLOCK
|
||||
|
||||
export interface RawWave {
|
||||
sampleRate: number
|
||||
/** Samples in the track. */
|
||||
length: number
|
||||
/** Min / max of the mono downmix per RAW_BLOCK samples. */
|
||||
min: Float32Array
|
||||
max: Float32Array
|
||||
/** The loudest absolute sample — the fixed vertical scale. */
|
||||
peak: number
|
||||
/** Fill `dest` with the mono downmix from sample `start` (zeros outside). */
|
||||
readMono: (start: number, dest: Float32Array) => void
|
||||
}
|
||||
|
||||
/** A reader of an AudioBuffer's mono downmix. copyFromChannel copies, so this
|
||||
* never holds a view the playback engine could detach (the Firefox gotcha). */
|
||||
export function bufferReader(buffer: AudioBuffer): RawWave['readMono'] {
|
||||
let tmp = new Float32Array(0)
|
||||
const chs = buffer.numberOfChannels
|
||||
return (start, dest) => {
|
||||
dest.fill(0)
|
||||
const from = Math.max(0, start)
|
||||
const skip = from - start
|
||||
const n = Math.min(dest.length - skip, buffer.length - from)
|
||||
if (n <= 0) return
|
||||
if (tmp.length < n) tmp = new Float32Array(n)
|
||||
const view = tmp.subarray(0, n)
|
||||
for (let c = 0; c < chs; c++) {
|
||||
buffer.copyFromChannel(view, c, from)
|
||||
for (let i = 0; i < n; i++) dest[skip + i] += view[i] / chs
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Summarise a mono downmix. `readMono` defaults to reading `mono` itself
|
||||
* (tests); the deck passes `bufferReader` so `mono` can be dropped. */
|
||||
export function rawWaveFromMono(
|
||||
mono: Float32Array,
|
||||
sampleRate: number,
|
||||
readMono?: RawWave['readMono'],
|
||||
): RawWave {
|
||||
const len = mono.length
|
||||
const nb = Math.max(1, Math.ceil(len / RAW_BLOCK))
|
||||
const min = new Float32Array(nb)
|
||||
const max = new Float32Array(nb)
|
||||
let peak = 0
|
||||
for (let b = 0; b < nb; b++) {
|
||||
let lo = Infinity
|
||||
let hi = -Infinity
|
||||
const end = Math.min(len, (b + 1) * RAW_BLOCK)
|
||||
for (let i = b * RAW_BLOCK; i < end; i++) {
|
||||
const v = mono[i]
|
||||
if (v < lo) lo = v
|
||||
if (v > hi) hi = v
|
||||
}
|
||||
if (lo === Infinity) lo = hi = 0
|
||||
min[b] = lo
|
||||
max[b] = hi
|
||||
peak = Math.max(peak, -lo, hi)
|
||||
}
|
||||
return {
|
||||
sampleRate,
|
||||
length: len,
|
||||
min,
|
||||
max,
|
||||
peak,
|
||||
readMono:
|
||||
readMono ??
|
||||
((start, dest) => {
|
||||
dest.fill(0)
|
||||
for (let i = 0; i < dest.length; i++) {
|
||||
const j = start + i
|
||||
if (j >= 0 && j < len) dest[i] = mono[j]
|
||||
}
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/** Reusable per-pixel output of `rawSpans`. */
|
||||
export interface RawSpans {
|
||||
lo: Float32Array
|
||||
hi: Float32Array
|
||||
/** Track time at each bin's centre (for the colour). */
|
||||
t: Float64Array
|
||||
/** Bins filled; bin k is drawn at device pixel `round(x0 + k)`. */
|
||||
n: number
|
||||
x0: number
|
||||
scratch: Float32Array
|
||||
}
|
||||
|
||||
export function makeSpans(): RawSpans {
|
||||
return { lo: new Float32Array(0), hi: new Float32Array(0), t: new Float64Array(0), n: 0, x0: 0, scratch: new Float32Array(0) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-pixel min/max of `raw` across a `w`-pixel view of [startSec, endSec).
|
||||
* Bins sit on a TRACK-space grid (bin g covers [g, g+1) pixel widths of track
|
||||
* time), so a scrolling view moves bins rather than regrouping samples under
|
||||
* them — the same reason `paintWave` bins in track space: regrouping makes
|
||||
* every peak shimmer as the playhead advances. Bins outside the track are NaN.
|
||||
*/
|
||||
export function rawSpans(raw: RawWave, startSec: number, endSec: number, w: number, out: RawSpans): RawSpans {
|
||||
const secPerPx = (endSec - startSec) / w
|
||||
const spp = secPerPx * raw.sampleRate // samples per pixel
|
||||
const g0 = Math.floor(startSec / secPerPx)
|
||||
const n = w + 2
|
||||
if (out.lo.length < n) {
|
||||
out.lo = new Float32Array(n)
|
||||
out.hi = new Float32Array(n)
|
||||
out.t = new Float64Array(n)
|
||||
}
|
||||
out.n = n
|
||||
out.x0 = g0 - startSec / secPerPx
|
||||
const { lo, hi, t } = out
|
||||
for (let k = 0; k < n; k++) t[k] = (g0 + k + 0.5) * secPerPx
|
||||
|
||||
if (spp >= SAMPLE_PATH_BELOW) {
|
||||
const nb = raw.min.length
|
||||
for (let k = 0; k < n; k++) {
|
||||
const s0 = (g0 + k) * spp
|
||||
const s1 = s0 + spp
|
||||
if (s1 <= 0 || s0 >= raw.length) {
|
||||
lo[k] = hi[k] = NaN
|
||||
continue
|
||||
}
|
||||
const b0 = Math.max(0, Math.floor(s0 / RAW_BLOCK))
|
||||
const b1 = Math.min(nb, Math.max(b0 + 1, Math.ceil(s1 / RAW_BLOCK)))
|
||||
let a = Infinity
|
||||
let z = -Infinity
|
||||
for (let b = b0; b < b1; b++) {
|
||||
if (raw.min[b] < a) a = raw.min[b]
|
||||
if (raw.max[b] > z) z = raw.max[b]
|
||||
}
|
||||
lo[k] = a
|
||||
hi[k] = z
|
||||
}
|
||||
} else {
|
||||
// One read covers the window, plus a sample each side for interpolation.
|
||||
const first = Math.floor(g0 * spp) - 1
|
||||
const count = Math.ceil(n * spp) + 3
|
||||
if (out.scratch.length < count) out.scratch = new Float32Array(count)
|
||||
const win = out.scratch.subarray(0, count)
|
||||
raw.readMono(first, win)
|
||||
for (let k = 0; k < n; k++) {
|
||||
const s0 = (g0 + k) * spp
|
||||
const s1 = s0 + spp
|
||||
if (s1 <= 0 || s0 >= raw.length) {
|
||||
lo[k] = hi[k] = NaN
|
||||
continue
|
||||
}
|
||||
const i0 = Math.ceil(s0)
|
||||
const i1 = Math.ceil(s1)
|
||||
let a = Infinity
|
||||
let z = -Infinity
|
||||
for (let i = i0; i < i1; i++) {
|
||||
const v = win[i - first]
|
||||
if (v < a) a = v
|
||||
if (v > z) z = v
|
||||
}
|
||||
if (a === Infinity) {
|
||||
// Narrower than a sample: the line's value at the bin's centre.
|
||||
const c = (s0 + s1) / 2
|
||||
const i = Math.floor(c)
|
||||
const f = c - i
|
||||
a = z = win[i - first] * (1 - f) + win[i + 1 - first] * f
|
||||
}
|
||||
lo[k] = a
|
||||
hi[k] = z
|
||||
}
|
||||
}
|
||||
|
||||
// Join each stroke to the previous one (by its ORIGINAL extent), so a steep
|
||||
// edge stays a continuous line instead of a dotted one.
|
||||
let pLo = NaN
|
||||
let pHi = NaN
|
||||
for (let k = 0; k < n; k++) {
|
||||
const a = lo[k]
|
||||
const z = hi[k]
|
||||
if (a === a && pLo === pLo) {
|
||||
if (a > pHi) lo[k] = pHi
|
||||
if (z < pLo) hi[k] = pLo
|
||||
}
|
||||
pLo = a
|
||||
pHi = z
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Pixels per unit amplitude for each stem lane: each stem at its own peak,
|
||||
* but never below 5% of the loudest stem's — the same floor as the bar lanes,
|
||||
* so a near-silent stem draws as near-silence, not magnified noise. */
|
||||
export function laneScales(peaks: number[], halfHeight: number): number[] {
|
||||
const loudest = Math.max(1e-6, ...peaks)
|
||||
return peaks.map((p) => halfHeight / Math.max(p, loudest * 0.05, 1e-6))
|
||||
}
|
||||
|
||||
// The bars' band colours (waveform.ts LAYERS), as RGB.
|
||||
const BANDS = [
|
||||
[255, 138, 61], // bass
|
||||
[143, 107, 255], // mids
|
||||
[94, 231, 255], // highs
|
||||
]
|
||||
|
||||
// sRGB <-> OKLab (Björn Ottosson's matrices).
|
||||
function toLab([r, g, b]: number[]): number[] {
|
||||
const lin = (v: number) => ((v /= 255) <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4)
|
||||
const R = lin(r)
|
||||
const G = lin(g)
|
||||
const B = lin(b)
|
||||
const l = Math.cbrt(0.4122214708 * R + 0.5363325363 * G + 0.0514459929 * B)
|
||||
const m = Math.cbrt(0.2119034982 * R + 0.6806995451 * G + 0.1073969566 * B)
|
||||
const s = Math.cbrt(0.0883024619 * R + 0.2817188376 * G + 0.6299787005 * B)
|
||||
return [
|
||||
0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,
|
||||
1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s,
|
||||
0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s,
|
||||
]
|
||||
}
|
||||
|
||||
function fromLab([L, A, B]: number[]): number[] {
|
||||
const l = (L + 0.3963377774 * A + 0.2158037573 * B) ** 3
|
||||
const m = (L - 0.1055613458 * A - 0.0638541728 * B) ** 3
|
||||
const s = (L - 0.0894841775 * A - 1.291485548 * B) ** 3
|
||||
const enc = (v: number) => {
|
||||
v = Math.min(1, Math.max(0, v))
|
||||
return 255 * (v <= 0.0031308 ? 12.92 * v : 1.055 * v ** (1 / 2.4) - 0.055)
|
||||
}
|
||||
return [
|
||||
enc(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s),
|
||||
enc(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s),
|
||||
enc(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s),
|
||||
]
|
||||
}
|
||||
|
||||
const BAND_LAB = BANDS.map(toLab)
|
||||
const BAND_CHROMA = BAND_LAB.map(([, a, b]) => Math.hypot(a, b))
|
||||
|
||||
/**
|
||||
* A column's colour from its band energies. Mixed in OKLab, then the CHROMA is
|
||||
* put back to the bands' weighted chroma: a plain weighted mean of orange,
|
||||
* violet and cyan lands near grey (they sit around the hue wheel), which read
|
||||
* as mud on busy passages. Chosen 2026-10-15 from five candidates rendered on
|
||||
* real tracks: orange + violet blends through pink (Traktor-like), highs stay
|
||||
* cyan, and nothing greys out. Lifted a touch so it reads on the dark well.
|
||||
*/
|
||||
function bandColour(low: number, mid: number, high: number): number[] {
|
||||
const w = [low, mid, high]
|
||||
const sum = low + mid + high
|
||||
if (sum < 1e-6) return BANDS[0]
|
||||
const mix = [0, 1, 2].map((c) => BAND_LAB.reduce((acc, lab, b) => acc + lab[c] * w[b], 0) / sum)
|
||||
const chroma = BAND_CHROMA.reduce((acc, ch, b) => acc + ch * w[b], 0) / sum
|
||||
const k = chroma / Math.max(1e-6, Math.hypot(mix[1], mix[2]))
|
||||
return fromLab([mix[0] + 0.04, mix[1] * k, mix[2] * k])
|
||||
}
|
||||
|
||||
const columnRgb = new WeakMap<WaveColumn[], Float32Array>()
|
||||
|
||||
/** Each band column's colour (`bandColour`), computed once per analysis. */
|
||||
function rgbOf(cols: WaveColumn[]): Float32Array {
|
||||
let rgb = columnRgb.get(cols)
|
||||
if (rgb) return rgb
|
||||
rgb = new Float32Array(cols.length * 3)
|
||||
for (let i = 0; i < cols.length; i++) rgb.set(bandColour(cols[i].low, cols[i].mid, cols[i].high), i * 3)
|
||||
columnRgb.set(cols, rgb)
|
||||
return rgb
|
||||
}
|
||||
|
||||
const styles = new Map<number, string>()
|
||||
|
||||
/** The tint at track time `t`: lerped between the two nearest band columns,
|
||||
* quantised to 32 levels a channel so a frame reuses a small set of strings. */
|
||||
export function tintAt(cols: WaveColumn[], duration: number, t: number): string {
|
||||
const rgb = rgbOf(cols)
|
||||
const n = cols.length
|
||||
const c = Math.min(n - 1, Math.max(0, (t / duration) * n - 0.5))
|
||||
const i = Math.floor(c)
|
||||
const j = Math.min(n - 1, i + 1)
|
||||
const f = c - i
|
||||
let key = 0
|
||||
for (let ch = 0; ch < 3; ch++) {
|
||||
const v = rgb[i * 3 + ch] * (1 - f) + rgb[j * 3 + ch] * f
|
||||
key = (key << 5) | Math.min(31, Math.round(v / 8.226))
|
||||
}
|
||||
let s = styles.get(key)
|
||||
if (!s) {
|
||||
const r = ((key >> 10) & 31) * 8.226
|
||||
const g = ((key >> 5) & 31) * 8.226
|
||||
const b = (key & 31) * 8.226
|
||||
s = `rgb(${r | 0},${g | 0},${b | 0})`
|
||||
styles.set(key, s)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
/**
|
||||
* Paint spans as a line centred in [y0, y0 + h). `scale` is pixels per unit
|
||||
* amplitude; `thick` the minimum stroke (device px), so a flat stretch still
|
||||
* reads as a line. `colour` is a fixed style or a per-bin function (by time).
|
||||
*/
|
||||
export function paintRaw(
|
||||
ctx: CanvasRenderingContext2D,
|
||||
s: RawSpans,
|
||||
y0: number,
|
||||
h: number,
|
||||
scale: number,
|
||||
thick: number,
|
||||
colour: string | ((t: number) => string),
|
||||
): void {
|
||||
const mid = y0 + h / 2
|
||||
const fixed = typeof colour === 'string'
|
||||
if (fixed) ctx.fillStyle = colour
|
||||
let current = ''
|
||||
const wpx = Math.max(1, Math.round(thick * 0.8))
|
||||
for (let k = 0; k < s.n; k++) {
|
||||
const a = s.lo[k]
|
||||
if (a !== a) continue
|
||||
let top = mid - s.hi[k] * scale
|
||||
let bot = mid - a * scale
|
||||
if (bot - top < thick) {
|
||||
const c = (top + bot) / 2
|
||||
top = c - thick / 2
|
||||
bot = c + thick / 2
|
||||
}
|
||||
if (!fixed) {
|
||||
const style = colour(s.t[k])
|
||||
if (style !== current) {
|
||||
ctx.fillStyle = style
|
||||
current = style
|
||||
}
|
||||
}
|
||||
ctx.fillRect(Math.round(s.x0 + k), top, wpx, bot - top)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
// What every shortcut does, for the keyboard map in `ShortcutsDialog`.
|
||||
// Written out BY HAND, not derived from the handlers: keep it in step with
|
||||
// `PrepStrip` (deck), `TrackTable` (track list) and `SettingsMenu` (`?`).
|
||||
import { cueTypeColor, GRID_MARKER_ACTIVE_COLOR } from './cues'
|
||||
import { IS_MAC } from './modKey'
|
||||
|
||||
/** A modifier layer of the keyboard. `mod` is Cmd on macOS, Ctrl elsewhere —
|
||||
* the handlers accept either, but the map names your key. */
|
||||
export type Layer = 'base' | 'shift' | 'mod'
|
||||
export const LAYERS: Layer[] = ['base', 'shift', 'mod']
|
||||
|
||||
export const MODIFIER_KEY: Record<Exclude<Layer, 'base'>, string> = IS_MAC
|
||||
? { shift: '⇧', mod: '⌘' }
|
||||
: { shift: 'Shift', mod: 'Ctrl' }
|
||||
|
||||
export const LAYER_NAMES: Record<Layer, string> = IS_MAC
|
||||
? { base: 'No modifier', shift: '⇧ Shift', mod: '⌘ Command' }
|
||||
: { base: 'No modifier', shift: 'Shift', mod: 'Ctrl' }
|
||||
|
||||
/** Where a shortcut acts. The colour lights its key on the map. */
|
||||
export type Area = 'deck' | 'list' | 'any'
|
||||
export const AREAS: Record<Area, string> = { deck: 'Deck', list: 'Track list', any: 'Anywhere' }
|
||||
export const AREA_COLORS: Record<Area, string> = {
|
||||
deck: 'var(--color-accent)',
|
||||
list: '#6fd6e8',
|
||||
any: 'var(--color-text)',
|
||||
}
|
||||
|
||||
export interface Binding {
|
||||
area: Area
|
||||
/** Printed on the key — a word or two; the key's own legend names it. */
|
||||
label: string
|
||||
/** The caption's full sentence. */
|
||||
text: string
|
||||
/** Overrides the area colour where the key has a colour of its own (pads, stems). */
|
||||
color?: string
|
||||
}
|
||||
export type Bindings = Record<Layer, Record<string, Binding[]>>
|
||||
|
||||
/** A stem file's default layout (NI's), since the map cannot know the loaded track's. */
|
||||
const STEMS: [string, string][] = [
|
||||
['drums', '#009E73'],
|
||||
['bass', '#D55E00'],
|
||||
['synths', '#CC79A7'],
|
||||
['vox', '#56B4E9'],
|
||||
]
|
||||
const STEM_CODES = ['KeyQ', 'KeyW', 'KeyE', 'KeyR']
|
||||
|
||||
/** The digit keys of a bank of `slots` pads: 1–9, then 0 for the tenth, as
|
||||
* `PrepStrip`'s `slotForDigit` reads them. */
|
||||
export function padCodes(slots: number): string[] {
|
||||
return Array.from({ length: Math.min(slots, 10) }, (_, i) => (i === 9 ? 'Digit0' : `Digit${i + 1}`))
|
||||
}
|
||||
|
||||
/** "1–8", or "1–9, 0" for a ten-pad bank. */
|
||||
export function padRange(slots: number): string {
|
||||
const n = Math.min(slots, 10)
|
||||
if (n <= 1) return '1'
|
||||
if (n <= 9) return `1–${n}`
|
||||
return '1–9, 0'
|
||||
}
|
||||
|
||||
export function bindings(slots: number): Bindings {
|
||||
const b: Bindings = { base: {}, shift: {}, mod: {} }
|
||||
const pad = cueTypeColor('cue')
|
||||
padCodes(slots).forEach((code, i) => {
|
||||
const n = i + 1
|
||||
b.base[code] = [
|
||||
{ area: 'deck', label: 'Pad', color: pad, text: `Hotcue ${n}: set it if the pad is empty, otherwise jump to it. Hold to preview.` },
|
||||
]
|
||||
b.shift[code] = [{ area: 'deck', label: 'Delete', color: 'var(--color-pink)', text: `Delete hotcue ${n}` }]
|
||||
})
|
||||
STEM_CODES.forEach((code, i) => {
|
||||
const [name, color] = STEMS[i]
|
||||
b.base[code] = [{ area: 'deck', label: 'Mute', color, text: `Stem tracks: mute or unmute stem ${i + 1} (usually ${name})` }]
|
||||
b.shift[code] = [
|
||||
{ area: 'deck', label: 'Solo', color, text: `Solo stem ${i + 1}: mute every other stem. Press again to unmute them all.` },
|
||||
]
|
||||
})
|
||||
Object.assign(b.base, {
|
||||
Space: [{ area: 'deck', label: 'Play / pause', text: 'Play / pause' }],
|
||||
KeyC: [
|
||||
{ area: 'deck', label: 'CUE', color: 'var(--color-gold)', text: 'CUE: jump back to the cue point, set it while paused, or hold to preview' },
|
||||
],
|
||||
ArrowLeft: [
|
||||
{ area: 'deck', label: 'Jump −', text: 'Beat jump back by the loop size. While a loop plays, move the loop back by its length.' },
|
||||
],
|
||||
ArrowRight: [
|
||||
{ area: 'deck', label: 'Jump +', text: 'Beat jump forward by the loop size. While a loop plays, move the loop forward by its length.' },
|
||||
],
|
||||
ArrowUp: [{ area: 'list', label: 'Up', text: 'Move the selection up one track' }],
|
||||
ArrowDown: [{ area: 'list', label: 'Down', text: 'Move the selection down one track' }],
|
||||
Enter: [
|
||||
{ area: 'list', label: 'Load · OK', text: 'Load and play the highlighted track' },
|
||||
{ area: 'any', label: 'OK', text: 'Save an edit, or confirm a dialog' },
|
||||
],
|
||||
Backspace: [
|
||||
{
|
||||
area: 'list',
|
||||
label: 'Remove',
|
||||
text: `Remove the selected tracks from this playlist${IS_MAC ? '' : ' (Delete works too)'}`,
|
||||
},
|
||||
],
|
||||
Slash: [{ area: 'any', label: 'Help', text: 'Open this list of shortcuts' }],
|
||||
Escape: [
|
||||
{ area: 'list', label: 'Cancel', text: 'Clear the selection' },
|
||||
{ area: 'any', label: 'Cancel', text: 'Cancel a drag or an edit, or close a dialog' },
|
||||
],
|
||||
} satisfies Record<string, Binding[]>)
|
||||
Object.assign(b.shift, {
|
||||
ArrowLeft: [{ area: 'deck', label: '◂ Grid', color: GRID_MARKER_ACTIVE_COLOR, text: 'Go to the previous grid marker' }],
|
||||
ArrowRight: [{ area: 'deck', label: 'Grid ▸', color: GRID_MARKER_ACTIVE_COLOR, text: 'Go to the next grid marker' }],
|
||||
ArrowUp: [{ area: 'list', label: 'Extend', text: 'Extend the selection up' }],
|
||||
ArrowDown: [{ area: 'list', label: 'Extend', text: 'Extend the selection down' }],
|
||||
} satisfies Record<string, Binding[]>)
|
||||
Object.assign(b.mod, {
|
||||
ArrowDown: [{ area: 'deck', label: 'Size ÷2', text: 'Halve the loop and beat-jump size (down to 1/32 beat)' }],
|
||||
ArrowUp: [{ area: 'deck', label: 'Size ×2', text: 'Double the loop and beat-jump size (up to 32 beats)' }],
|
||||
KeyA: [{ area: 'list', label: 'All', text: 'Select every track in the list' }],
|
||||
} satisfies Record<string, Binding[]>)
|
||||
return b
|
||||
}
|
||||
|
||||
/** Why a digit past the bank does nothing — the bank follows the library. */
|
||||
export function unusedNote(code: string, slots: number): string | null {
|
||||
if (!/^Digit\d$/.test(code) || padCodes(slots).includes(code)) return null
|
||||
return `Not used: this library has ${slots} hotcue pad${slots === 1 ? '' : 's'}.`
|
||||
}
|
||||
|
||||
export interface MouseGesture {
|
||||
mod?: Exclude<Layer, 'base'>
|
||||
gesture: string
|
||||
/** What is clicked or dragged, when it is not the column's whole area. */
|
||||
on?: string
|
||||
text: string
|
||||
}
|
||||
export const MOUSE: { title: string; rows: MouseGesture[] }[] = [
|
||||
{
|
||||
title: 'Deck',
|
||||
rows: [
|
||||
{ gesture: 'Drag', on: 'waveform', text: 'Scratch' },
|
||||
{ mod: 'mod', gesture: 'Scroll', on: 'waveform', text: 'Zoom in and out' },
|
||||
{ gesture: 'Click', on: 'stem button', text: 'Mute or unmute that stem' },
|
||||
{ mod: 'mod', gesture: 'Click', on: 'stem button', text: 'Solo that stem' },
|
||||
{ gesture: 'Right-click', on: 'pad', text: 'Hotcue type, colour, rename, delete' },
|
||||
{ gesture: 'Click', on: 'memory cue', text: 'Jump there and make it the CUE point (a memory loop engages)' },
|
||||
{ gesture: 'Right-click', on: 'memory cue', text: 'Memory cue type, colour, rename, delete' },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Track list',
|
||||
rows: [
|
||||
{ gesture: 'Click', text: 'Select a track' },
|
||||
{ mod: 'shift', gesture: 'Click', text: 'Select a range' },
|
||||
{ mod: 'mod', gesture: 'Click', text: 'Add to or remove from the selection' },
|
||||
{ gesture: 'Double-click', on: 'cell', text: 'Edit it in place' },
|
||||
{ gesture: 'Right-click', text: 'Track menu. On the header: choose columns' },
|
||||
{ gesture: 'Drag', on: 'rows', text: 'Onto a playlist or export to add, onto the deck to load, within a playlist to reorder' },
|
||||
{ mod: 'mod', gesture: 'Drag', on: 'rows', text: 'Move them out of this playlist into another' },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Sidebar',
|
||||
rows: [
|
||||
{ gesture: 'Right-click', text: 'New playlist or folder, rename, delete' },
|
||||
{ gesture: 'Drag', on: 'playlist', text: 'Rearrange playlists and folders, or drop onto an export to add it' },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
// ---- the keyboard drawn -----------------------------------------------------
|
||||
|
||||
export interface KeyDef {
|
||||
code: string
|
||||
legend: string
|
||||
/** The legend when keys are too small for `legend`. */
|
||||
short?: string
|
||||
/** Width in key units. */
|
||||
w?: number
|
||||
/** A modifier key: holding or clicking it shows its layer. */
|
||||
role?: Exclude<Layer, 'base'>
|
||||
}
|
||||
|
||||
const key = (code: string, legend: string, w = 1, role?: KeyDef['role'], short?: string): KeyDef => ({
|
||||
code,
|
||||
legend,
|
||||
w,
|
||||
role,
|
||||
short,
|
||||
})
|
||||
const chars = (s: string, prefix: string) => [...s].map((c) => key(prefix + c, c))
|
||||
|
||||
/** The main block, a row per list. Every row is 14.5 units wide. */
|
||||
export const KEY_ROWS: KeyDef[][] = (() => {
|
||||
const fn = [key('Escape', 'esc', 1.5)]
|
||||
for (let i = 1; i <= 12; i++) fn.push(key(`F${i}`, `F${i}`))
|
||||
fn.push(key('Power', ''))
|
||||
const shift = IS_MAC ? 'shift ⇧' : 'Shift'
|
||||
const shiftShort = IS_MAC ? '⇧' : 'Shift'
|
||||
const bottom = IS_MAC
|
||||
? [
|
||||
key('Fn', 'fn'),
|
||||
key('ControlLeft', 'control', 1.25, undefined, 'ctrl'),
|
||||
key('AltLeft', 'option ⌥', 1.25, undefined, '⌥'),
|
||||
key('MetaLeft', 'command ⌘', 1.5, 'mod', '⌘'),
|
||||
key('Space', 'space', 6.75),
|
||||
key('MetaRight', 'command ⌘', 1.5, 'mod', '⌘'),
|
||||
key('AltRight', 'option ⌥', 1.25, undefined, '⌥'),
|
||||
]
|
||||
: [
|
||||
key('ControlLeft', 'Ctrl', 1.25, 'mod'),
|
||||
key('MetaLeft', 'Win', 1.25),
|
||||
key('AltLeft', 'Alt', 1.25),
|
||||
key('Space', 'space', 6.75),
|
||||
key('AltRight', 'Alt', 1.25),
|
||||
key('MetaRight', 'Win', 1.25),
|
||||
key('ControlRight', 'Ctrl', 1.5, 'mod'),
|
||||
]
|
||||
return [
|
||||
fn,
|
||||
[key('Backquote', '`'), ...chars('1234567890', 'Digit'), key('Minus', '-'), key('Equal', '='),
|
||||
key('Backspace', IS_MAC ? 'delete' : 'Backspace', 1.5, undefined, IS_MAC ? 'del' : 'Bksp')],
|
||||
[key('Tab', 'tab', 1.5), ...chars('QWERTYUIOP', 'Key'), key('BracketLeft', '['), key('BracketRight', ']'), key('Backslash', '\\')],
|
||||
[key('CapsLock', 'caps', 1.75), ...chars('ASDFGHJKL', 'Key'), key('Semicolon', ';'), key('Quote', "'"),
|
||||
key('Enter', IS_MAC ? 'return' : 'Enter', 1.75)],
|
||||
[key('ShiftLeft', shift, 2.25, 'shift', shiftShort), ...chars('ZXCVBNM', 'Key'), key('Comma', ','), key('Period', '.'),
|
||||
key('Slash', '/ ?'), key('ShiftRight', shift, 2.25, 'shift', shiftShort)],
|
||||
bottom,
|
||||
]
|
||||
})()
|
||||
|
||||
/** The inverted-T arrow cluster, 3 × 2, `null` for the gaps beside ↑. */
|
||||
export const ARROW_KEYS: (KeyDef | null)[] = [
|
||||
null, key('ArrowUp', '↑'), null,
|
||||
key('ArrowLeft', '←'), key('ArrowDown', '↓'), key('ArrowRight', '→'),
|
||||
]
|
||||
|
||||
/** The space between the main block and the arrows, in key units. */
|
||||
export const ARROW_GAP = 0.36
|
||||
/** The whole map's width in key units. */
|
||||
export const KEYBOARD_UNITS = 14.5 + ARROW_GAP + 3
|
||||
|
||||
export const KEYS_BY_CODE: Record<string, KeyDef> = Object.fromEntries(
|
||||
[...KEY_ROWS.flat(), ...ARROW_KEYS.filter((k): k is KeyDef => !!k)].map((k) => [k.code, k]),
|
||||
)
|
||||
|
||||
/** The modifier layer a physical key holds, if it is one. */
|
||||
export function modifierLayer(code: string): Exclude<Layer, 'base'> | null {
|
||||
if (code === 'ShiftLeft' || code === 'ShiftRight') return 'shift'
|
||||
const mod = IS_MAC ? ['MetaLeft', 'MetaRight'] : ['ControlLeft', 'ControlRight']
|
||||
return mod.includes(code) ? 'mod' : null
|
||||
}
|
||||
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user