Compare commits

...
6 Commits
Author SHA1 Message Date
patben8 4340e948ac Bumped version number 2026-10-17 20:21:28 +02:00
patben8 fe63acc2a2 Merge pull request #13 from MrPatben8/dev
Implemented Cross-Platform Track Color Support
2026-10-17 20:08:02 +02:00
patben8 06361a851f Implemented cross-platform track color support 2026-10-17 19:50:56 +02:00
patben8 0605dbabe6 Improved release description and file names 2026-10-16 18:04:54 +02:00
patben8 6be99e6d7e Merge pull request #12 from MrPatben8/dev
Implemented self-updating
2026-10-16 17:39:28 +02:00
patben8 0eac972173 Implemented self-updating 2026-10-16 17:38:35 +02:00
49 changed files with 1572 additions and 78 deletions

No files matched your search

+97
View File
@@ -0,0 +1,97 @@
"""Lay out one release's assets under user-facing names, plus the updater's
latest.json and the release notes' Download section.
Run by build.yml's release job:
python3 .github/scripts/release_assets.py artifacts release \\
--version 0.6.0 --tag v0.6.0-b42 --repo owner/konduktor
Finds, anywhere under `artifacts`, what `tauri build` produced: the macOS
`*.dmg` and `*.app.tar.gz` (+ `.sig`) and the Windows `*-setup.exe` (+ `.sig`).
Copies them into `release` as
Konduktor-<version>-macOS.dmg (download)
Konduktor-<version>-Windows-Setup.exe (download; the Windows updater runs it too)
Konduktor-<version>-app-updater.tar.gz (the macOS updater's package)
latest.json (the updater's manifest)
and writes `download.md`. Renaming is safe: the signatures cover contents,
not names, and latest.json is written from the final names. `latest.json`
itself keeps its name: the app asks for releases/download/<tag>/latest.json.
Fails if anything is missing: a manifest lacking a platform is refused by the
updater as a whole.
"""
import argparse
import json
import shutil
import sys
from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import quote
def find_one(root: Path, suffix: str) -> Path:
found = [p for p in root.rglob(f"*{suffix}") if p.is_file()]
if len(found) != 1:
sys.exit(f"expected exactly one *{suffix} under {root}, found {len(found)}")
return found[0]
def signature(asset: Path) -> str:
sig = asset.with_name(asset.name + ".sig")
if not sig.is_file():
sys.exit(f"missing signature {sig}")
return sig.read_text(encoding="utf-8").strip()
def lay_out(artifacts: Path, out: Path, version: str, tag: str, repo: str) -> None:
def url(name: str) -> str:
return f"https://github.com/{repo}/releases/download/{quote(tag)}/{quote(name)}"
dmg = find_one(artifacts, ".dmg")
app = find_one(artifacts, ".app.tar.gz")
setup = find_one(artifacts, "-setup.exe")
names = {
dmg: f"Konduktor-{version}-macOS.dmg",
setup: f"Konduktor-{version}-Windows-Setup.exe",
app: f"Konduktor-{version}-app-updater.tar.gz",
}
# Tauri's platform keys -> the file that platform's updater installs.
manifest = {
"version": version,
"pub_date": datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z"),
"platforms": {
"darwin-aarch64": {"signature": signature(app), "url": url(names[app])},
"windows-x86_64": {"signature": signature(setup), "url": url(names[setup])},
},
}
out.mkdir(parents=True, exist_ok=True)
for src, name in names.items():
shutil.copy2(src, out / name)
(out / "latest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
(out / "download.md").write_text(
"## Download\n"
f"- **macOS** (Apple Silicon): [{names[dmg]}]({url(names[dmg])})\n"
f"- **Windows**: [{names[setup]}]({url(names[setup])})\n",
encoding="utf-8",
)
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("artifacts", type=Path)
ap.add_argument("out", type=Path)
ap.add_argument("--version", required=True)
ap.add_argument("--tag", required=True)
ap.add_argument("--repo", required=True)
args = ap.parse_args()
lay_out(args.artifacts, args.out, args.version, args.tag, args.repo)
for p in sorted(args.out.iterdir()):
print(p.name)
if __name__ == "__main__":
main()
+36 -6
View File
@@ -86,20 +86,31 @@ jobs:
working-directory: frontend
run: npm ci
# createUpdaterArtifacts also signs the in-app update packages
# (Konduktor.app.tar.gz / the NSIS setup.exe) with the updater key, whose
# public half is plugins.updater.pubkey in tauri.conf.json. Losing the
# private key means installed copies can never update themselves again.
- name: Build Tauri app
working-directory: frontend
env:
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
run: npx tauri build
# Stage the single installer per OS into a flat folder. Uploading one
# directory (not multiple bundle subpaths) keeps the artifact root at
# ./installer, so the zip holds the bare file — no nested dmg/ or nsis/
# folder. We ship the DMG on macOS and the NSIS -setup.exe on Windows
# (the .msi is intentionally left out).
# (the .msi is intentionally left out), plus what the in-app updater
# installs: the .app.tar.gz on macOS (the setup.exe on Windows) and the
# .sig files the release job folds into latest.json.
- name: Stage installer (macOS)
if: runner.os == 'macOS'
run: |
mkdir -p installer
cp frontend/src-tauri/target/release/bundle/dmg/*.dmg installer/
cp frontend/src-tauri/target/release/bundle/macos/*.app.tar.gz installer/
cp frontend/src-tauri/target/release/bundle/macos/*.app.tar.gz.sig installer/
- name: Stage installer (Windows)
if: runner.os == 'Windows'
@@ -107,6 +118,7 @@ jobs:
run: |
New-Item -ItemType Directory -Force installer | Out-Null
Copy-Item frontend/src-tauri/target/release/bundle/nsis/*-setup.exe installer/
Copy-Item frontend/src-tauri/target/release/bundle/nsis/*-setup.exe.sig installer/
- name: Upload installer
uses: actions/upload-artifact@v4
@@ -189,11 +201,24 @@ jobs:
pattern: konduktor-*
path: artifacts # → artifacts/konduktor-macOS/…, artifacts/konduktor-Windows/…
# The release's files under user-facing names, the in-app updater's
# latest.json (the app reads releases/download/<tag>/latest.json) and the
# notes' Download section. The .sig files are folded into latest.json and
# not uploaded themselves.
- name: Release assets
run: |
python3 .github/scripts/release_assets.py artifacts release \
--version "${{ steps.version.outputs.version }}" \
--tag "v${{ steps.version.outputs.version }}-b${{ github.run_number }}" \
--repo "${{ github.repository }}"
# Release notes from the "Patch notes" section of the PR that merged this
# 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.
# push) or no such section → GitHub's generated notes, as before. The
# Download section always comes first (the action puts the body above
# generated notes); the dialog reads only "What's Changed".
- name: Patch notes from the merged PR
id: notes
env:
@@ -218,9 +243,10 @@ jobs:
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")
f.write(open("release/download.md", encoding="utf-8").read())
if found:
f.write("\n## 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.")
@@ -232,7 +258,11 @@ jobs:
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 }}
body_path: ${{ steps.notes.outputs.found == 'true' && 'release-notes.md' || '' }}
body_path: release-notes.md
generate_release_notes: ${{ steps.notes.outputs.found != 'true' }}
fail_on_unmatched_files: true
files: artifacts/**/*
files: |
release/*.dmg
release/*.exe
release/*.tar.gz
release/latest.json
+8 -3
View File
@@ -88,9 +88,14 @@ cd ..
# 2) Build the app (its beforeBuildCommand runs the Vite build)
cd frontend
npx tauri build
npx tauri build --config src-tauri/tauri.unsigned.conf.json
```
The `--config` override skips the in-app updater packages, which are signed
with the release key that only CI holds (`TAURI_SIGNING_PRIVATE_KEY`). With
that key set in the environment, plain `npx tauri build` makes them too.
`build.ps1` picks the right one by itself.
`build_sidecar.ps1` uses `backend\.venv\Scripts\python.exe` when it exists (else
whatever `python` resolves to), so the venv doesn't need to be activated. It
replaces the whole staged folder, so no file from an older build survives.
@@ -117,8 +122,8 @@ folder (`tauri.windows.conf.json` → `bundle.resources`), where `lib.rs` spawns
## Rebuilding after changes
If you changed **backend** Python, run `.\build.ps1` (or `build_sidecar.ps1`,
then `npx tauri build`). Frontend-only changes just need
`.\build.ps1 -SkipSidecar` (or `npx tauri build`).
then `npx tauri build` as above). Frontend-only changes just need
`.\build.ps1 -SkipSidecar`.
## Not part of this build: the stem engine
+57 -5
View File
@@ -1035,10 +1035,28 @@ Two independent apps that talk over HTTP:
stem engine publishes `engine-v*` releases in the same repo — and,
if its tag's **semver part** is newer than `__APP_VERSION__` — build-number
`-b<N>` bumps don't count — shows an update dialog with the release's
"What's Changed" bullets; Download opens the release page in the system
browser via `@tauri-apps/plugin-shell` `open` — falls back to `window.open`
outside Tauri; "Skip this version" persists `skippedUpdateVersion` to
userprefs via `/api/prefs`; all failures are silent).
"What's Changed" bullets; "Skip this version" persists
`skippedUpdateVersion` to userprefs via `/api/prefs`; check failures are
silent. **In the desktop app, Update installs it** (decided 2026-10-16,
[the discussion](.claude/discussions/discuss-self-update-2026-10-16.md)):
`update_download` (lib.rs, tauri-plugin-updater) reads THAT release's
`latest.json`, downloads with progress in the dialog, verifies the
signature and STAGES the package in app-cache; `update_restart` then
quits through the ordinary quit request, so QuitGuard asks about unsaved
edits. The package is installed in `exit_now`, only AFTER the sidecar is
killed — on macOS the running backend lazily loads native libraries from
inside the bundle being replaced, on Windows its `.exe` is locked (the
shell waits until it can open it for writing) — then the app relaunches.
Cancel in QuitGuard keeps it staged (`konduktor://update-deferred`) and the
next ordinary quit installs it without relaunching. On macOS a bundle run
from the DMG, translocated, or in a folder the user cannot write is
refused BEFORE downloading (the updater's own admin-password fallback
runs on the main thread, which the quit path may hold). Any failure shows
its reason + "Open release page" (the old Download, still the button in a
plain browser); an install that failed at exit is written to
`failed.json` and reported by the next launch (`update_take_failure`).
The updater's crate is built WITHOUT its `zip` feature — only for v1-style
zipped Windows installers, and every zip 4.x is yanked.
- **Stem playback** (decided 2026-09-30): a stem FILE always loads its four
stems (`trackStemsFor` / `trackStemUrl` in `api.ts`) and the deck plays
their SUM, as Traktor's stem deck does — the mix stream is never decoded,
@@ -1141,6 +1159,18 @@ Two independent apps that talk over HTTP:
Hot / Mem toggle shows on `cues.memory_cues`, + Memory refuses past
`cues.max_memory_cues`, and a memory cue's swatches are `cues.memory_palette`
where `cues.memory_color` is `palette` (its own 8, not `palette`'s 16).
**Track colour** (decided 2026-10-17, [the discussion](.claude/discussions/discuss-track-colour-2026-10-17.md)):
shown as the Type column's icon in `Track.color_hex`; set from the context
menu's **Colour ▸** (swatches from `tracks.colors`, + No Color, the whole
selection, `PATCH /api/tracks/color`) — nowhere else. `Track.color` is a
neutral NAME (`TrackColor`: pink red orange yellow green aqua blue purple),
which is what crosses platforms; each adapter's `track_palette.py` maps its
codes to it BY NAME, not hue: Traktor `INFO@COLOR` 1-7 = Red Orange Yellow
Green Blue Violet(purple) Magenta(pink), measured (kit T1), no file tag;
rekordbox `ColorID` / OneLibrary `color_id` / pdb `color_id` 1-8 = Pink…
Purple, 0 none. Traktor's Blue LOOKS like rekordbox's Aqua but crosses as
Blue (the name is the DJ's category); aqua arriving in Traktor becomes Blue.
Unmeasured: what Traktor leaves after "None" (Konduktor removes the attribute).
Carried but deliberately unused until a second adapter
exists: `slot_labels: 'letter'`, `loops: 'separate_bank'`.
- `lib/trackColumns.tsx` — single source of truth for the library table's
@@ -1226,6 +1256,10 @@ serialization path.** It enforces:
self-closed (`/>`, which Traktor never writes); a value containing
`name='x'` once came back with a bare `"` (malformed). Both were in the
fork's `format_traktor_layout`, fixed there (2026-10-16).
And **track colour** (R): `set_track_color` changes one line, that
entry's `<INFO>`, with `COLOR` last as Traktor writes it; aqua is stored as
Blue; clearing restores the original bytes; and a Traktor 4.5 collection
holding coloured tracks (when on the machine) renders byte-identically.
The guard that catches serialization regressions like the lxml reformatting bug.
- `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays
Traktor-valid, backup-first, COLLECTION byte-identical, original untouched;
@@ -1632,6 +1666,9 @@ frontend at `http://localhost:5173`.
`add_entry` write BOTH, the text in the collection's majority notation
(`TraktorStore.key_notation()`; an empty collection — an export — takes a
Traktor-native source's own, so Traktor→Traktor keeps the user's).
- **Track colour** = `INFO@COLOR`, 1-7 in the Color menu's order (Red …
Magenta), the LAST attribute of `<INFO>`; collection-only (`_COLLECTION_ONLY_FIELDS`).
See `track_palette.py`.
- **Beatgrid = an ORDERED LIST of markers**, never a single BPM + anchor.
Traktor stores each as a `CUE_V2 TYPE="4"` with its own `<GRID BPM>` child
(flexible beatgrids, 3.4+); `<TEMPO BPM>` mirrors the **first marker by
@@ -1771,7 +1808,22 @@ that number and nothing else — everything derives from it:
- **CI release** — `.github/workflows/build.yml` reads it with
`jq .version frontend/package.json` and tags each push
`v<version>-b<run_number>` (release name `Konduktor v<version>-b<run_number>`).
The `-b<N>` suffix keeps every push's tag/release unique.
The `-b<N>` suffix keeps every push's tag/release unique. Each release also
carries its files under user-facing names, laid out by
`.github/scripts/release_assets.py`: `Konduktor-<v>-macOS.dmg`,
`Konduktor-<v>-Windows-Setup.exe` (also the Windows update package),
`Konduktor-<v>-app-updater.tar.gz` (the macOS update package) and the
in-app updater's `latest.json` (`version` = package.json's, each platform's
URL + signature inlined; the name is fixed — the app asks for it by name).
The notes open with a "Download" section linking the two installers, above
the PR's patch notes or GitHub's generated ones; the update dialog reads
only "What's Changed" and skips "Download" when falling back.
`bundle.createUpdaterArtifacts` signs those with the updater key: the
repo secrets `TAURI_SIGNING_PRIVATE_KEY` / `_PASSWORD`, public half in
`tauri.conf.json` `plugins.updater.pubkey`. **Losing the private key means
installed copies can never update themselves again** — it is backed up
outside the repo. A local build without it passes
`--config src-tauri/tauri.unsigned.conf.json` (`build.ps1` does so itself).
- **NOT a source**: `src-tauri/Cargo.toml` `version` is inert Rust crate metadata
(Tauri uses the config's `../package.json`); don't treat it as the app version.
@@ -404,6 +404,12 @@ class OneLibraryAdapter:
self._refresh(track_id)
return self._index.get(track_id)
def set_track_color(self, track_id: str, color: str | None) -> Track | None:
self._require_writable("Setting the track colour")
self._store.set_track_color(track_id, color)
self._refresh(track_id)
return self._index.get(track_id)
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
self._refuse("Editing cover art")
@@ -36,7 +36,7 @@ from ...core.capabilities import (
SaveCapabilities,
TrackCapabilities,
)
from ..rekordbox import memory_palette, palette
from ..rekordbox import memory_palette, palette, track_palette
from ..rekordbox.cue_types import MAX_MEMORY_CUES, WRITABLE_CUE_TYPES
# Pads A-H. Unlike `djmdCue.Kind`, the ANLZ slot number is a dense 1-based index,
@@ -87,6 +87,8 @@ def capabilities_for(
addable=not read_only,
removable=not read_only,
key_writable=not read_only,
# `content.color_id`, rekordbox's eight; the pdb row follows at Save.
colors=[] if read_only else list(track_palette.SWATCHES),
places_audio=True,
# `artwork` gates EDITING, which Rekordbox does not do yet either
# (parity). Reading works: `store.cover_art` follows
@@ -121,10 +121,10 @@ def rebuild(existing: bytes, session) -> bytes | None:
# ---- tracks -----------------------------------------------------------------
old_tracks = {pdb.row_id(pdb.TRACKS, r): r for r in pdb.table_rows(existing, pdb.TRACKS)}
want = {}
for (cid, title, artist, remixer, album, genre, label, rating, bpm, year, released,
for (cid, title, artist, remixer, album, genre, label, rating, color, bpm, year, released,
comment, *fresh) in session.execute(text(
"SELECT content_id, title, artist_id_artist, artist_id_remixer, album_id, genre_id, "
"label_id, rating, bpmx100, releaseYear, releaseDate, djComment, "
"label_id, rating, color_id, bpmx100, releaseYear, releaseDate, djComment, "
"path, fileName, fileSize, fileType, bitrate, bitDepth, samplingRate, length, "
"analysisDataFilePath, dateAdded, key_id, image_id FROM content")):
cid = int(cid)
@@ -134,7 +134,8 @@ def rebuild(existing: bytes, session) -> bytes | None:
fields, strings = _fresh_track(cid, *fresh)
fields = {**fields, "artist_id": artist or 0, "remixer_id": remixer or 0,
"album_id": album or 0, "genre_id": genre or 0, "label_id": label or 0,
"rating": max(0, min(5, int(rating or 0))), "tempo": int(bpm or 0),
"rating": max(0, min(5, int(rating or 0))), "color_id": int(color or 0),
"tempo": int(bpm or 0),
"year": int(year or 0)}
strings = {**strings, "title": title or "", "comment": comment or "",
"release_date": released or ""}
@@ -44,7 +44,7 @@ from pathlib import Path
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
from ...core.cue_colors import effective_color
from ..rekordbox import anlz_writer as W
from ..rekordbox import artwork, memory_palette, palette, timebase
from ..rekordbox import artwork, memory_palette, palette, timebase, track_palette
from ..rekordbox.cue_types import MAX_MEMORY_CUES
from ..rekordbox.beatgrid import beats_from_markers
from ..rekordbox.projection import render_key
@@ -209,13 +209,13 @@ class OneLibraryExporter:
con.execute(
"INSERT INTO content (content_id, title, titleForSearch, bpmx100, length, "
"trackNo, artist_id_artist, album_id, genre_id, label_id, key_id, image_id, "
"trackNo, artist_id_artist, album_id, genre_id, label_id, key_id, color_id, image_id, "
"djComment, rating, releaseDate, dateAdded, path, fileName, fileSize, "
"fileType, bitrate, bitDepth, samplingRate, isHotCueAutoLoadOn, "
"isKuvoDeliverStatusOn, masterDbId, masterContentId, "
"analysisDataFilePath, analysedBits, contentLink, hasModified, cueUpdateCount, "
"analysisDataUpdateCount, informationUpdateCount) "
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
(
content_id, track.title, (track.title or "").lower(),
int(round((track.bpm or 0) * 100)) or None, track.length,
@@ -229,6 +229,7 @@ class OneLibraryExporter:
# where the deck expects "Cm". Rendered from the parsed wheel.
self._lookup(con, "key", lookups["key"],
render_key(track.key_wheel, track.key_mode)),
track_palette.id_for(track.color),
image_id,
track.comment, track.rating or 0, track.release_date,
date.today().isoformat(), rel, item.destination.name, size,
@@ -16,6 +16,7 @@ Field conventions are read off a real rekordbox 7 export rather than guessed:
from __future__ import annotations
from ...core.model import GridMarker, Track, TrackCues
from ..rekordbox import track_palette
from ..rekordbox.projection import parse_key
@@ -106,6 +107,8 @@ def to_track(row, drive_path: str | None = None, *, stem: bool = False) -> Track
grid_locked=False, # OneLibrary has no grid lock
# What the FILE is, as the deck plays it — see the Rekordbox projection.
media_kind="stem" if stem else "audio",
color=track_palette.color_for(getattr(row, "color_id", None)),
color_hex=track_palette.hex_for(getattr(row, "color_id", None)),
)
+20 -2
View File
@@ -55,7 +55,7 @@ from ...core.grid_edit import ReplaceGridCommands
from ...core.model import CuePoint
from ... import paths
from . import beatgrid, cues as cue_reader, memory_cues
from ..rekordbox import anlz_file, palette, timebase
from ..rekordbox import anlz_file, palette, timebase, track_palette
from ..rekordbox.cue_types import MAX_MEMORY_CUES
from ..rekordbox import anlz_writer as W
from ..rekordbox import beatgrid as rb_beatgrid
@@ -566,6 +566,23 @@ class OneLibraryStore(ReplaceGridCommands):
db.flush()
db.session.expire(row)
def set_track_color(self, track_id: str, color: str | None) -> None:
"""`content.color_id`, a 1-based id into the `color` table (see
`track_palette`); 0 = none, as rekordbox exports an uncoloured track.
Not a file tag; the pdb's track row follows at Save (`device_library`)."""
new = track_palette.id_for(color)
if color is not None and not new:
raise InvalidCommand(f"Not a track colour: {color!r}")
db = self._require_db()
row = self.content(track_id)
before = row.color_id
if int(before or 0) == new:
return
row.color_id = new
self._journal.record("track", "set", track_id, "color", before, new)
db.flush()
db.session.expire(row)
# ---- writes: playlists --------------------------------------------------
def _playlist(self, node_id: str):
from pyrekordbox.onelibrary import models
@@ -1182,7 +1199,7 @@ class OneLibraryStore(ReplaceGridCommands):
"isrc, djPlayCount, isHotCueAutoLoadOn, isKuvoDeliverStatusOn, kuvoDeliveryComment, "
"masterDbId, masterContentId, analysisDataFilePath, analysedBits, contentLink, "
"hasModified) VALUES (:cid, :title, NULL, '', :bpm, :length, 0, 0, :artist, :remixer, "
":album, :genre, :label, :key, 0, :image, :comment, :rating, :year, :released, "
":album, :genre, :label, :key, :color, :image, :comment, :rating, :year, :released, "
":added, :created, :path, :file, :size, :type, :bitrate, :depth, :rate, '', 0, 1, 1, "
"'', 0, :cid, :anlz, :bits, :link, 0)"), {
"cid": cid, "title": getattr(track, "title", None) or final.stem,
@@ -1192,6 +1209,7 @@ class OneLibraryStore(ReplaceGridCommands):
"label": lookup("Label", track.label),
# Rendered from the parsed wheel: a source's "10m" means nothing here.
"key": self._key_id(track.key_wheel, track.key_mode),
"color": track_palette.id_for(getattr(track, "color", None)),
"image": image_id, "comment": track.comment or "",
"rating": max(0, min(5, int(track.rating or 0))), "year": year, "released": released,
"added": datetime.now().strftime("%Y-%m-%d"), "created": created, "path": rel,
@@ -260,6 +260,12 @@ class RekordboxAdapter:
self._refresh(track_id)
return self._index.get(track_id)
def set_track_color(self, track_id: str, color: str | None) -> Track | None:
self._require_writable("Setting the track colour")
self._store.set_track_color(track_id, color)
self._refresh(track_id)
return self._index.get(track_id)
# ---- commands: playlists ----------------------------------------------
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
self._require_writable("Creating playlists")
@@ -30,7 +30,7 @@ from ...core.capabilities import (
SaveCapabilities,
TrackCapabilities,
)
from . import memory_palette, palette
from . import memory_palette, palette, track_palette
from .cue_types import MAX_MEMORY_CUES, WRITABLE_CUE_TYPES
# Rekordbox's addressable hot cue bank. The pads are labelled A-H; the stored
@@ -93,6 +93,8 @@ def capabilities_for(
removable=True,
addable=True,
key_writable=True,
# `djmdContent.ColorID`, rekordbox's eight (see `track_palette`).
colors=list(track_palette.SWATCHES),
artwork=False,
artwork_note=None,
),
@@ -41,7 +41,7 @@ from datetime import date
from pathlib import Path
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
from . import artwork, pdb
from . import artwork, pdb, track_palette
from .projection import render_key
log = logging.getLogger(__name__)
@@ -138,6 +138,7 @@ class RekordboxDeviceExporter:
"id": n, "year": year, "sample_depth": bit_depth or 0,
"duration": min(int(track.length or 0), 0xFFFF),
"u5": ANALYSED, "rating": max(0, min(5, int(track.rating or 0))),
"color_id": track_palette.id_for(track.color),
"u6": _file_type(item.destination), "u7": 3,
},
{
@@ -58,7 +58,7 @@ from sqlalchemy import text
from ...core.export import ExportPayload, ExportTrack, WrittenLibrary
from ...core.cue_colors import effective_color
from . import memory_palette, new_content, palette
from . import memory_palette, new_content, palette, track_palette
from . import timebase
from .beatgrid import beats_from_markers
from .capabilities import capabilities_for
@@ -313,6 +313,7 @@ class RekordboxExporter:
# export would put "10m" where Rekordbox shows "Cm".
content.KeyID = self._lookup(db, "key", render_key(track.key_wheel, track.key_mode))
content.ContentLink = CONTENT_LINK
content.ColorID = str(track_palette.id_for(track.color))
db.flush()
return content
@@ -7,7 +7,7 @@ from __future__ import annotations
from ...core import musical_key
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
from . import beatgrid, memory_palette, palette, timebase
from . import beatgrid, memory_palette, palette, timebase, track_palette
from .cue_types import cue_type, kind_for, role_and_slot
# Rekordbox names keys musically ("Abm", "F", "Ebm") — but its key table also
@@ -127,6 +127,8 @@ def to_track(row, cue_kinds=(), *, stem: bool = False) -> Track:
# file's mix, but Konduktor's deck plays its stems, and the Type column
# must not disagree with the deck.
media_kind="stem" if stem else "audio",
color=track_palette.color_for(getattr(row, "ColorID", None)),
color_hex=track_palette.hex_for(getattr(row, "ColorID", None)),
)
+20 -1
View File
@@ -47,7 +47,7 @@ from ...core.adapter import (
from ...core.edit_journal import EditJournal
from ...core.grid_edit import ReplaceGridCommands
from ...core.pathmap import PathMapping, stored_form
from . import memory_palette, timebase
from . import memory_palette, timebase, track_palette
from .cue_types import MAX_MEMORY_CUES, beat_loop_size, kind_for, role_and_slot
log = logging.getLogger(__name__)
@@ -556,6 +556,24 @@ class RekordboxStore(ReplaceGridCommands):
self._db.flush()
self._db.session.expire(row)
# ---- writes: track colour ---------------------------------------------
def set_track_color(self, track_id: str, color: str | None) -> None:
"""`djmdContent.ColorID`, a 1-based id into `djmdColor` (see
`track_palette`). Cleared = "0", as on the uncoloured rows of the local
library (a few hold NULL; both read as none)."""
new = track_palette.id_for(color)
if color is not None and not new:
raise InvalidCommand(f"Not a track colour: {color!r}")
row = self.content(track_id)
before = row.ColorID
if track_palette.id_for(track_palette.color_for(before)) == new:
return
row.ColorID = str(new)
self._journal.record("track", "set", track_id, "color", before, row.ColorID)
# A foreign key into djmdColor: flush + expire, as for the others.
self._db.flush()
self._db.session.expire(row)
# ---- writes: playlists ------------------------------------------------
def _playlist(self, node_id: str):
t = self._tables
@@ -761,6 +779,7 @@ class RekordboxStore(ReplaceGridCommands):
# Rekordbox's ("10m" is "Cm" here), and a row it already has is reused.
content.KeyID = self._key_id(track.key_wheel, track.key_mode)
content.ContentLink = new_content.CONTENT_LINK
content.ColorID = str(track_palette.id_for(track.color))
if stored != audio:
# pyrekordbox reads the file where it IS; the row names it as the
# library stores every other path (the server's mapping, inverted).
@@ -0,0 +1,50 @@
"""rekordbox's TRACK colours — the eight a track can be tagged with.
Stored as a 1-based id into the `djmdColor` table (master.db `djmdContent.ColorID`,
a string: "0" = none) and OneLibrary's `color` table (`content.color_id`, an
integer, 0 = none); the stick's legacy `export.pdb` track row has a `color_id`
byte with the same numbering. Both tables list the same eight rows in the same
order: 1 Pink, 2 Red, 3 Orange, 4 Yellow, 5 Green, 6 Aqua, 7 Blue, 8 Purple —
one per generic `TrackColor`, so the mapping is one to one.
Those are the memory-cue palette's names in its order, so the display RGB is
`memory_palette.COLOURS`' (sampled from rekordbox 7's own colour menu). Nothing
stores the RGB — `djmdColor.ColorCode` is NULL in a real library.
"""
from __future__ import annotations
from ...core.capabilities import ColorSwatch, TrackColor
from . import memory_palette
#: id - 1 -> the generic colour, in rekordbox's menu order.
_NAMES: list[TrackColor] = ["pink", "red", "orange", "yellow", "green", "aqua", "blue", "purple"]
#: What `capabilities.tracks.colors` offers.
SWATCHES: list[ColorSwatch] = [
ColorSwatch(color=name, hex=memory_palette.SWATCHES[i], label=memory_palette.COLOURS[i][0])
for i, name in enumerate(_NAMES)
]
def _id(color_id: int | str | None) -> int:
try:
return int(color_id) if color_id is not None else 0
except (TypeError, ValueError):
return 0
def color_for(color_id: int | str | None) -> TrackColor | None:
"""The generic colour for a stored id; None for 0, NULL or anything unknown."""
n = _id(color_id)
return _NAMES[n - 1] if 1 <= n <= len(_NAMES) else None
def hex_for(color_id: int | str | None) -> str | None:
"""rekordbox's display colour for a stored id; None when uncoloured."""
n = _id(color_id)
return SWATCHES[n - 1].hex if 1 <= n <= len(SWATCHES) else None
def id_for(color: TrackColor | str | None) -> int:
"""The id to store for a generic colour; 0 for none (or an unknown name)."""
return _NAMES.index(color) + 1 if color in _NAMES else 0
@@ -218,6 +218,9 @@ class RemoteAdapter:
def set_key(self, track_id, wheel, mode):
return self._call("set_key", track_id=track_id, wheel=wheel, mode=mode)
def set_track_color(self, track_id, color):
return self._call("set_track_color", track_id=track_id, color=color)
def set_cue(self, track_id, *, slot, start_sec, cue_type, length_sec=0.0, role="hotcue", name=None):
return self._call("set_cue", track_id=track_id, slot=slot, start_sec=start_sec,
cue_type=cue_type, length_sec=length_sec, role=role, name=name)
@@ -156,6 +156,12 @@ class TraktorAdapter:
self._refresh(track_id)
return self._index.get(track_id)
def set_track_color(self, track_id: str, color: str | None) -> Track | None:
with _translate():
self._store.set_track_color(track_id, color)
self._refresh(track_id)
return self._index.get(track_id)
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
with _translate():
self._store.set_track_art(track_id, data, mime)
@@ -19,6 +19,7 @@ from ...core.capabilities import (
SaveCapabilities,
TrackCapabilities,
)
from . import track_palette
_VERSION_RE = re.compile(rb'<NML\s+VERSION="(\d+)"')
@@ -68,6 +69,8 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
addable=True,
stem_convertible=True,
key_writable=True,
# INFO@COLOR, seven colours (measured, see `track_palette`).
colors=list(track_palette.SWATCHES),
# `.mp4` covers stem files (`.stem.mp4`). Traktor also reads WMA,
# but only on Windows, and a file added on one OS must play on both.
audio_formats=[".mp3", ".wav", ".aif", ".aiff", ".flac", ".m4a", ".mp4", ".ogg"],
@@ -9,7 +9,7 @@ import re
from ...core import musical_key
from ...core.model import CuePoint, GridMarker, HotcueChip, Track, TrackCues
from . import beatgrid, timebase
from . import beatgrid, timebase, track_palette
from .cue_types import NATIVE_TO_CUE_TYPE
# Traktor displays keys in Open Key ("10m" / "8d") or Camelot ("8A" / "8B"),
@@ -172,6 +172,8 @@ def to_track(e) -> Track:
grid_marker_count=len(markers),
grid_locked=bool(e.lock),
media_kind="stem" if getattr(e, "stems", None) is not None else "audio",
color=track_palette.color_for(info.color if info else None),
color_hex=track_palette.hex_for(info.color if info else None),
)
+25 -2
View File
@@ -53,7 +53,7 @@ from ...core.pathmap import PathMapping, stored_form
from ...core.relocate import PathGroup
from ...core.stem_file import NML_STEMS_JSON, nml_stems_for
from ...schemas import PlaylistNode
from . import beatgrid, timebase
from . import beatgrid, timebase, track_palette
from .locations import os_path_to_location, resolve_path
from ...core import musical_key
from .projection import iso_date, musical_key_value, traktor_date, with_memory_ids
@@ -446,7 +446,8 @@ class TraktorStore:
EDITABLE_FIELDS = {"title", "artist", "album", "rating", "comment2"} | _INFO_FIELDS
# Fields that live only in the collection: Traktor itself writes no file tag
# for "Comment 2" (verified on an m4a it had just edited), so neither do we.
_COLLECTION_ONLY_FIELDS = {"comment2"}
# Nor for the track colour (kit T1: no audio file's mtime moved).
_COLLECTION_ONLY_FIELDS = {"comment2", "color"}
def set_track_metadata(self, track_id: str, fields: dict) -> None:
with self._lock:
@@ -544,6 +545,27 @@ class TraktorStore:
self._journal.record("track", "set", track_id, "key", before, entry.info.key)
self.dirty = True
# ---- track colour -----------------------------------------------------
def set_track_color(self, track_id: str, color: str | None) -> None:
"""INFO@COLOR (see `track_palette`). Cleared = the attribute removed, as
every never-coloured entry has it; what Traktor itself leaves after
"None" (absent, or `COLOR="0"`) is not yet measured (kit T1 step 3)."""
code = track_palette.code_for(color)
if color is not None and code is None:
raise InvalidCommand(f"Not a track colour: {color!r}")
with self._lock:
entry = self._entry_by_key.get(track_id)
if entry is None:
raise PlaylistError(f"Track not found: {track_id}")
before = entry.info.color if entry.info is not None else None
if before == code:
return
if entry.info is None:
entry.info = Infotype()
entry.info.color = code
self._journal.record("track", "set", track_id, "color", before, code)
self.dirty = True
# ---- adding tracks --------------------------------------------------
def add_entry(self, track, audio_path: Path) -> str:
"""Append a brand-new ENTRY for `audio_path` and return its track id.
@@ -598,6 +620,7 @@ class TraktorStore:
# attribute at all rather than a zero.
ranking=(max(0, min(5, int(getattr(track, "rating", 0) or 0))) * 51) or None,
playtime=getattr(track, "length", None) or None,
color=track_palette.code_for(getattr(track, "color", None)),
)
album = None
if getattr(track, "album", None):
@@ -0,0 +1,59 @@
"""Traktor's TRACK colours — `INFO@COLOR`, an integer.
MEASURED in Traktor 4.5 (kit T1, 2026-10-17,
`.claude/discussions/discuss-track-colour-2026-10-17.md`) by colouring one track
per entry of the browser's Color menu, in its order: 1 Red · 2 Orange ·
3 Yellow · 4 Green · 5 Blue · 6 Violet · 7 Magenta. Traktor keeps it in the
collection only — it does not tag the audio file.
Mapped to the generic colours BY NAME (decided 2026-10-17): Violet is `purple`,
Magenta `pink`, and Blue is `blue` even though it LOOKS like rekordbox's Aqua —
the name is the DJ's category. Traktor has no seventh-and-a-half colour, so
`aqua` arriving from rekordbox is stored as Blue.
The RGB values are DISPLAY colours only — nothing stores them. They were
sampled from the colour dots in Traktor's own browser (a screenshot).
"""
from __future__ import annotations
from ...core.capabilities import ColorSwatch, TrackColor
#: What `capabilities.tracks.colors` offers; code - 1 -> swatch, menu order.
SWATCHES: list[ColorSwatch] = [
ColorSwatch(color="red", hex="#FB413E", label="Red"),
ColorSwatch(color="orange", hex="#F79525", label="Orange"),
ColorSwatch(color="yellow", hex="#F9F918", label="Yellow"),
ColorSwatch(color="green", hex="#52FA52", label="Green"),
ColorSwatch(color="blue", hex="#1ACBFA", label="Blue"),
ColorSwatch(color="purple", hex="#B26CFA", label="Violet"),
ColorSwatch(color="pink", hex="#FA51EB", label="Magenta"),
]
#: Generic colours Traktor has no swatch of its own for.
_FOLDED: dict[str, int] = {"aqua": 5}
def _swatch(code: int | None) -> ColorSwatch | None:
return SWATCHES[code - 1] if isinstance(code, int) and 1 <= code <= len(SWATCHES) else None
def color_for(code: int | None) -> TrackColor | None:
"""The generic colour for a stored code; None for absent, 0 or unknown."""
s = _swatch(code)
return s.color if s else None
def hex_for(code: int | None) -> str | None:
"""Traktor's display colour for a stored code; None when uncoloured."""
s = _swatch(code)
return s.hex if s else None
def code_for(color: TrackColor | str | None) -> int | None:
"""The `INFO@COLOR` to store for a generic colour; None for none."""
if color is None:
return None
for i, s in enumerate(SWATCHES, start=1):
if s.color == color:
return i
return _FOLDED.get(color)
+4 -1
View File
@@ -22,7 +22,7 @@ from dataclasses import dataclass, field
from pathlib import Path
from typing import Protocol, runtime_checkable
from .capabilities import Capabilities
from .capabilities import Capabilities, TrackColor
from .model import Facets, PlaylistNode, Stats, Track, TrackCues, TrackPage
from .pathmap import PathMapping
from .relocate import PathGroup
@@ -296,6 +296,9 @@ class LibraryAdapter(Protocol):
# analysis writes. Each platform renders it in its own notation (and its own
# analysed-key field, where it has one). Gated on `tracks.key_writable`.
def set_key(self, track_id: str, wheel: int, mode: str) -> Track | None: ...
# The track's colour tag (None clears it), mapped onto the platform's own
# palette by name. Gated on `tracks.colors` being non-empty.
def set_track_color(self, track_id: str, color: TrackColor | None) -> Track | None: ...
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None: ...
def cover_art(self, track_id: str) -> tuple[bytes, str] | None: ...
+17
View File
@@ -36,6 +36,20 @@ CueType = Literal["cue", "fade_in", "fade_out", "load", "loop"]
CueRole = Literal["hotcue", "memory"]
MediaKind = Literal["audio", "stem", "video"]
PlaylistKind = Literal["folder", "playlist", "smart"]
# A track's colour tag, as a platform-neutral IDENTITY — what crosses between
# libraries. Each adapter maps its own codes to and from these BY NAME (decided
# 2026-10-17, `.claude/discussions/discuss-track-colour-2026-10-17.md`): eight
# names because rekordbox has eight; Traktor's seven cover all but `aqua`,
# which it receives as its Blue.
TrackColor = Literal["pink", "red", "orange", "yellow", "green", "aqua", "blue", "purple"]
class ColorSwatch(BaseModel):
"""One track colour a library offers, in its own menu order."""
color: TrackColor
hex: str # the platform's own display colour
label: str # the platform's own name for it ("Violet" in Traktor)
class CueCapabilities(BaseModel):
@@ -107,6 +121,9 @@ class TrackCapabilities(BaseModel):
# Whether added files can be left where they are ("reference") rather than
# copied. False where the library cannot see this computer's files at all.
reference: bool = True
# The track colours this library can store (`set_track_color`), in its own
# menu order. Empty: the platform has no track colour.
colors: list[ColorSwatch] = []
class PlaylistCapabilities(BaseModel):
+6 -1
View File
@@ -13,7 +13,7 @@ from typing import Literal
from pydantic import BaseModel, ConfigDict, Field
from .capabilities import CueRole, CueType, MediaKind, PlaylistKind
from .capabilities import CueRole, CueType, MediaKind, PlaylistKind, TrackColor
class HotcueChip(BaseModel):
@@ -71,6 +71,11 @@ class Track(BaseModel):
grid_marker_count: int = 0
grid_locked: bool = False
media_kind: MediaKind = "audio"
# The track's colour tag: the neutral identity (what crosses platforms) and
# the platform's own display colour for it, both mapped from the stored
# code by the adapter. None = no colour.
color: TrackColor | None = None
color_hex: str | None = None
class TrackPage(BaseModel):
+12
View File
@@ -60,6 +60,7 @@ from .schemas import (
LibraryInfo,
PlatformOption,
EditTrack,
SetTrackColor,
Facets,
FileTagOutcome,
CreateExportSet,
@@ -1320,6 +1321,17 @@ def edit_track(body: EditTrack) -> dict:
return {"status": "updated", "id": body.track_id}
@app.patch("/api/tracks/color")
def set_track_color(body: SetTrackColor) -> dict:
"""Set (or clear) the colour tag of every given track (in-memory; persisted
on save). Gated on `tracks.colors`: the platform's swatches."""
a = require_adapter()
if not a.capabilities().tracks.colors:
raise Unsupported("This library cannot store a track colour")
tracks = [a.set_track_color(tid, body.color) for tid in body.track_ids]
return {"status": "updated", "tracks": [t for t in tracks if t is not None]}
@app.get("/api/tracks/art")
def track_art(track_id: str) -> Response:
"""Stream a track's embedded cover art (staged replacement if unsaved)."""
+4 -2
View File
@@ -38,7 +38,8 @@ from .core.model import AutoHotcue, Track, TrackCues
#: 1.2 — `/v1/folder/*`: the content folder browsed as a Files tree.
#: 1.3 — memory cues: `add_memory_cue`, `rename_memory_cue`,
#: `set_memory_cue_type`, `set_memory_cue_color`, `delete_memory_cue`.
API_VERSION: tuple[int, int] = (1, 3)
#: 1.4 — track colour: `set_track_color`, `Track.color` / `color_hex`.
API_VERSION: tuple[int, int] = (1, 4)
#: How long a session survives without a heartbeat, and how often the holder
#: sends one. Long enough to ride out a Wi-Fi blip or a switch to the fallback
@@ -77,7 +78,8 @@ _READ = (
)
_MUTATING = (
"create_playlist", "create_folder", "rename_playlist", "delete_playlist",
"move_playlist", "set_playlist_entries", "remove_tracks", "set_track_metadata", "set_key", "set_cue",
"move_playlist", "set_playlist_entries", "remove_tracks", "set_track_metadata", "set_key",
"set_track_color", "set_cue",
"set_cue_type", "set_cue_color", "delete_cue", "place_cues", "add_memory_cue",
"rename_memory_cue", "set_memory_cue_type", "set_memory_cue_color", "delete_memory_cue", "add_grid_marker",
"move_grid_marker", "set_grid_marker_bpm", "delete_grid_marker", "replace_grid",
+8 -1
View File
@@ -5,7 +5,7 @@ from typing import Literal
from pydantic import BaseModel, ConfigDict, Field
from .core.capabilities import CueRole, CueType
from .core.capabilities import CueRole, CueType, TrackColor
class CreatePlaylist(BaseModel):
@@ -40,6 +40,13 @@ class EditTrack(BaseModel):
fields: dict[str, str | int | None]
class SetTrackColor(BaseModel):
"""The context menu's Colour ▸: one colour (None = No Color) for a selection."""
track_ids: list[str]
color: TrackColor | None = None
class FileTagOutcome(BaseModel):
track_id: str
file: str
+4 -1
View File
@@ -153,7 +153,8 @@ for i, (title, artist, key) in enumerate((("One", "Artist A", (8, "minor")), ("T
png = __import__("io").BytesIO()
Image.new("RGB", (300, 300), (40 * i, 90, 160)).save(png, format="PNG")
t = Track(id=f"src{i}", title=title, artist=artist, album="LP", genre="House", bpm=125.0,
key_wheel=key[0], key_mode=key[1], length=6, rating=i + 1, filepath=str(audio))
key_wheel=key[0], key_mode=key[1], length=6, rating=i + 1, filepath=str(audio),
color=("purple", None, "aqua")[i])
tracks.append(ExportTrack(track=t, destination=audio, art=(png.getvalue(), "image/png"),
cues=TrackCues(track_id=t.id, grid_markers=[GridMarker(start=0.0, bpm=125.0)],
cues=[CuePoint(type="cue", role="hotcue", start=1.0, length=0.0, slot=0)])))
@@ -174,6 +175,8 @@ check("a track with no key has key 0", lib.tracks[1]["key_id"] == 0)
check("bpm x100, rating, file type, bitmask as rekordbox writes them",
all(t["tempo"] == 12500 and t["u6"] == 11 and t["bitmask"] == 0xC0700 and t["u5"] == 0x29 for t in lib.tracks)
and [t["rating"] for t in lib.tracks] == [1, 2, 3])
check("the track colour is the 1-based id (Purple 8, none 0, Aqua 6)",
[t["color_id"] for t in lib.tracks] == [8, 0, 6], str([t["color_id"] for t in lib.tracks]))
check("the file path is drive-relative", lib.tracks[0]["file_path"] == "/Contents/House/One.wav", lib.tracks[0]["file_path"])
check("no computer's masterDbId is claimed", all(t["u3"] == 0 and t["u4"] == 0 for t in lib.tracks))
tree = {p["name"]: p for p in lib.playlists}
+9 -1
View File
@@ -66,11 +66,14 @@ chosen = [flexible, cued, plain]
dest = Path(tempfile.mkdtemp()) / "GIG"
dest.mkdir(parents=True)
items = []
# Colours by generic name: `aqua` is rekordbox's, which Traktor stores as Blue.
COLOURS = {flexible.id: "aqua", cued.id: "pink", plain.id: None}
for track in chosen:
audio = dest / "Music" / "Library" / Path(track.filepath).name
audio.parent.mkdir(parents=True, exist_ok=True)
audio.write_bytes(b"\0" * 64)
items.append(ExportTrack(track=track, destination=audio, cues=src.track_cues(track.id)))
items.append(ExportTrack(track=track.model_copy(update={"color": COLOURS[track.id]}),
destination=audio, cues=src.track_cues(track.id)))
payload = ExportPayload(
name="GIG",
@@ -126,6 +129,11 @@ check("artist survived", by_title[plain.title].artist == plain.artist)
if plain.key:
check("key notation is copied, not converted", by_title[plain.title].key == plain.key)
check("track colours cross by name: aqua -> Blue (5), pink -> Magenta (7), none -> no COLOR",
[by_title[t.title].color for t in chosen] == ["blue", "pink", None]
and 'COLOR="5"' in text and 'COLOR="7"' in text and text.count(' COLOR="') == 2,
str([by_title[t.title].color for t in chosen]))
print("== the playlist tree ==")
tree = {}
+11 -1
View File
@@ -58,13 +58,19 @@ cued = next(t for t in src.tracks
chosen = [flexible, cued]
COLOURS = ["purple", "aqua"]
def build(root: Path) -> ExportPayload:
items = []
for i, track in enumerate(chosen):
audio = root / ("House" if i % 2 else "Techno") / Path(track.filepath).name
audio.parent.mkdir(parents=True, exist_ok=True)
audio.write_bytes(b"\0" * 4096)
items.append(ExportTrack(track=track, destination=audio,
# A colour each, as the generic name crosses (Traktor's Violet is
# `purple`; `aqua` is rekordbox's own, with no Traktor swatch).
coloured = track.model_copy(update={"color": COLOURS[i % len(COLOURS)]})
items.append(ExportTrack(track=coloured, destination=audio,
cues=src.track_cues(track.id)))
return ExportPayload(
name="GIG", tracks=items,
@@ -136,6 +142,10 @@ for platform, reopen in (
all(abs((by_title[t.title].bpm or 0) - (t.bpm or 0)) < 0.02
for t in chosen if t.bpm))
check("the track colour crossed by name",
[by_title[t.title].color for t in chosen] == COLOURS[:len(chosen)],
str([by_title[t.title].color for t in chosen]))
print(f"-- {platform}: the key was CONVERTED, not copied")
for track in chosen:
if not track.key:
+19
View File
@@ -438,6 +438,25 @@ check("refusing leaves nothing dirty", adapter.dirty is False)
check("an unknown track is a NotFound, not an Unsupported",
_raises(lambda: adapter.audio_path("no-such-track"), NotFound))
print("== track colour ==")
# Goober (`fixtures/onelibrary-goober`) is a stick coloured in rekordbox:
# `content.color_id` 1-based into the `color` table (1 Pink, 2 Red, 5 Green).
from konduktor.adapters.rekordbox import track_palette # noqa: E402
_gdir = Path(tempfile.mkdtemp(prefix="konduktor-ol-colour-")) / "goober"
shutil.copytree(FIXTURE.parent / "onelibrary-goober", _gdir)
_goober = OneLibraryAdapter(_gdir)
_colours = {t.title: (t.color, t.color_hex) for t in _goober.tracks}
check("rekordbox's track colours project by name + display RGB",
_colours.get("Nemean - Doomed") == ("red", "#E13121")
and _colours.get("Sleepnet - Lapse") == ("green", "#65DB41")
and _colours.get("Life Is A Loop - Grand Prix") == ("pink", "#E577EF"), str(_colours))
check("an uncoloured track has none", _colours.get("Demo Track 2") == (None, None))
_goober.close()
check("the palette maps ids both ways",
[track_palette.id_for(track_palette.color_for(i)) for i in range(9)] == list(range(9))
and track_palette.color_for("0") is None and track_palette.color_for(9) is None)
print("== reads that answer rather than refuse ==")
check("cover art is absent, not an error", adapter.cover_art(one.id) is None)
# A drive stores everything relative to its own root, so it cannot have stale
+43
View File
@@ -442,6 +442,49 @@ check("setting 12A reuses the stick's '12A' row instead of adding 'Dbm'",
if r2["title"] == target.title))["key_id"]) == names["12A"])
g.close()
print("== track colour ==")
# `content.color_id` (1 Pink .. 8 Purple, 0 none); the pdb track row's
# `color_id` byte uses the same ids, and Goober's two agree on every track.
from konduktor.adapters.rekordbox import pdb # noqa: E402
goober = Path(tempfile.mkdtemp(prefix="konduktor-olfid-colour-")) / "Goober"
shutil.copytree(FIXTURE.parent / "onelibrary-goober", goober, ignore=shutil.ignore_patterns("after"))
pdb_path = goober / "PIONEER" / "rekordbox" / "export.pdb"
def pdb_colours() -> dict:
return {pdb.row_id(pdb.TRACKS, r): pdb.track_fields(r)[0]["color_id"]
for r in pdb.table_rows(pdb_path.read_bytes(), pdb.TRACKS)}
before = dump(db_of(goober))
check("rekordbox's own pdb carries the same colour ids as the database",
pdb_colours() == {int(r["content_id"]): int(r["color_id"] or 0) for r in before["content"].values()},
str(pdb_colours()))
g = OneLibraryAdapter(goober)
check("an editable stick offers rekordbox's eight colours",
[s.color for s in g.capabilities().tracks.colors]
== ["pink", "red", "orange", "yellow", "green", "aqua", "blue", "purple"])
check("a browsed one offers none",
OneLibraryAdapter(goober, read_only=True).capabilities().tracks.colors == [])
g.set_track_color(next(x for x in g.tracks if x.color == "green").id, "green")
check("setting the colour it has is not an edit", g.dirty is False)
red = next(t for t in g.tracks if t.color == "red")
t = g.set_track_color(red.id, "blue")
check("the projection shows it at once", (t.color, t.color_hex) == ("blue", "#1F4EED"), str(t))
g.save()
changes = diff(before, dump(db_of(goober)))
check("exactly content.color_id changes (2 = Red -> 7 = Blue)",
len(changes) == 1 and changes[0][3] == {"color_id": (2, 7)}, describe(changes))
cid = int(changes[0][1]) if changes else None
check("and the pdb's track row follows", pdb_colours().get(cid) == 7, str(pdb_colours()))
g.set_track_color(red.id, None)
g.save()
check("No Color stores 0, in both",
dump(db_of(goober))["content"][changes[0][1]]["color_id"] == 0 and pdb_colours().get(cid) == 0)
check("an unknown colour is refused", _raises(lambda: g.set_track_color(red.id, "teal"), Exception))
g.close()
print()
print("RESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+24
View File
@@ -952,5 +952,29 @@ with tempfile.TemporaryDirectory() as d:
len(dump(work)["djmdKey"]) == len(after["djmdKey"]))
adapter.close()
print("== L: track colour is djmdContent.ColorID, one row + the counter ==")
clean_copy(REAL, work)
before = dump(work)
adapter = RekordboxAdapter(work)
t1 = adapter.tracks[0]
got = adapter.set_track_color(t1.id, "aqua")
check("the projection updates immediately", (got.color, got.color_hex) == ("aqua", "#55BBF1"), str(got))
adapter.save()
changes = diff(before, dump(work))
content = [c for c in changes if c[0] == "djmdContent"]
check("exactly the track row and the counter change",
{t for t, _, _, _ in changes} == {"djmdContent", "agentRegistry"} and len(changes) == 2,
describe(changes))
check("ColorID '6' (Aqua, 1-based into djmdColor)",
content and content[0][3].get("ColorID", (None, None))[1] == "6", str(content and content[0][3]))
before = dump(work)
adapter.set_track_color(t1.id, None)
adapter.save()
changes = diff(before, dump(work))
check("No Color writes '0'",
[c[3].get("ColorID", (None, None))[1] for c in changes if c[0] == "djmdContent"] == ["0"],
describe(changes))
adapter.close()
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+50
View File
@@ -63,6 +63,14 @@ def _raises_playlist(fn) -> bool:
return False
def _raises_any(fn) -> bool:
try:
fn()
except Exception:
return True
return False
def tag_lines(b: bytes) -> list[str]:
return b.replace(b"><", b">\n<").decode("utf-8", "replace").splitlines()
@@ -1341,5 +1349,47 @@ with tempfile.TemporaryDirectory() as d:
reread = TraktorStore(work)._nml.collection.entry[0].info.comment
check("…and reads back unchanged", reread == "x > y key='8A' \"z\"", repr(reread))
print("== R. track colour (INFO@COLOR) is localized, Traktor's shape, reversible ==")
# Measured in Traktor 4.5 (kit T1): COLOR="1".."7" (Red..Magenta), the LAST
# attribute of <INFO>; no file tag. Cleared = no attribute (unmeasured what
# Traktor itself leaves after "None"; absent is what an uncoloured entry has).
with tempfile.TemporaryDirectory() as d:
work = Path(d) / "collection.nml"
shutil.copy2(REAL, work)
original = work.read_bytes()
store = TraktorStore(work)
entry = next(e for e in store._nml.collection.entry if e.info is not None and e.info.color is None)
loc = entry.location
tid = f"{loc.volume}{loc.dir}{loc.file}"
store.set_track_color(tid, "blue")
store.save()
coloured = work.read_bytes()
o_s, o_e = _entry_span_by_file(original, loc.file)
c_s, c_e = _entry_span_by_file(coloured, loc.file)
check("only that ENTRY changes",
original[:o_s] + original[o_e:] == coloured[:c_s] + coloured[c_e:])
check("in one line: its <INFO>, with COLOR last, as Traktor writes it",
diff_count(original[o_s:o_e], coloured[c_s:c_e]) == 2 # one line: - and +
and _re.search(rb'<INFO [^>]* COLOR="5">', coloured[c_s:c_e]) is not None)
store = TraktorStore(work)
store.set_track_color(tid, "aqua")
check("aqua (rekordbox's) is stored as Traktor's Blue: a no-op", store.dirty is False)
store.set_track_color(tid, "purple")
check("purple is Traktor's Violet (6)",
store._entry_by_key[tid].info.color == 6)
store.set_track_color(tid, None)
store.save()
check("clearing restores the original bytes", work.read_bytes() == original)
check("an unknown colour is refused",
_raises_any(lambda: TraktorStore(work).set_track_color(tid, "teal")))
_KIT = Path.home() / "Documents/Native Instruments/Traktor 4.5.0/collection.nml"
if _KIT.exists() and b'COLOR="' in _KIT.read_bytes():
data = _KIT.read_bytes()
check("a Traktor 4.5 collection with coloured tracks renders byte-identically",
TraktorStore(_KIT)._render() == data)
else:
print(" [SKIP] no coloured Traktor 4.5 collection on this machine")
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+20
View File
@@ -332,5 +332,25 @@ if gridded is not None:
all(c.type != "grid" for c in cues.cues) and
gridded.cue_count == len(cues.cues))
print("== track colour ==")
# `INFO@COLOR` 1-7, measured in Traktor 4.5 (kit T1): Red ... Magenta, menu order.
from konduktor.adapters.traktor import projection, track_palette # noqa: E402
_entry = next(e for e in adapter._store.iter_entries() if e.info is not None)
_was = _entry.info.color
_seen = []
for _code in (None, 0, 1, 4, 7, 8):
_entry.info.color = _code
_t = projection.to_track(_entry)
_seen.append((_t.color, _t.color_hex))
_entry.info.color = _was
check("Traktor's track colours project by name + display RGB (none for absent/0/unknown)",
_seen == [(None, None), (None, None), ("red", "#FB413E"), ("green", "#52FA52"),
("pink", "#FA51EB"), (None, None)], str(_seen))
check("Traktor offers seven colours, Violet as purple and Magenta as pink",
[s.color for s in adapter.capabilities().tracks.colors]
== ["red", "orange", "yellow", "green", "blue", "purple", "pink"])
check("aqua (rekordbox's) is stored as Traktor's Blue", track_palette.code_for("aqua") == 5)
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+6
View File
@@ -40,6 +40,12 @@ try {
& (Join-Path $Root "backend\build_sidecar.ps1")
}
# Updater packages are signed with the release key (CI's secret). Without
# it, build the installers alone rather than fail at the signing step.
if (-not $env:TAURI_SIGNING_PRIVATE_KEY) {
$TauriArgs = @("--config", "src-tauri/tauri.unsigned.conf.json") + $TauriArgs
}
Write-Host ""
Write-Host "==> 2/2 Building the app (tauri build $TauriArgs)"
Set-Location (Join-Path $Root "frontend")
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "frontend",
"private": true,
"version": "0.2.9",
"version": "0.3.1",
"type": "module",
"scripts": {
"dev": "vite",
+412 -8
View File
@@ -86,6 +86,7 @@ dependencies = [
"tauri-build",
"tauri-plugin-log",
"tauri-plugin-shell",
"tauri-plugin-updater",
"tokio",
]
@@ -465,6 +466,16 @@ dependencies = [
"version_check",
]
[[package]]
name = "core-foundation"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "core-foundation"
version = "0.10.1"
@@ -488,7 +499,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97"
dependencies = [
"bitflags 2.13.0",
"core-foundation",
"core-foundation 0.10.1",
"core-graphics-types",
"foreign-types",
"libc",
@@ -501,7 +512,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb"
dependencies = [
"bitflags 2.13.0",
"core-foundation",
"core-foundation 0.10.1",
"libc",
]
@@ -905,6 +916,16 @@ dependencies = [
"rustc_version",
]
[[package]]
name = "filetime"
version = "0.2.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"
dependencies = [
"cfg-if",
"libc",
]
[[package]]
name = "find-msvc-tools"
version = "0.1.9"
@@ -1439,6 +1460,21 @@ dependencies = [
"want",
]
[[package]]
name = "hyper-rustls"
version = "0.27.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53"
dependencies = [
"http",
"hyper",
"hyper-util",
"rustls",
"tokio",
"tokio-rustls",
"tower-service",
]
[[package]]
name = "hyper-util"
version = "0.1.20"
@@ -1457,9 +1493,11 @@ dependencies = [
"percent-encoding",
"pin-project-lite",
"socket2",
"system-configuration",
"tokio",
"tower-service",
"tracing",
"windows-registry",
]
[[package]]
@@ -1707,6 +1745,36 @@ dependencies = [
"windows-sys 0.45.0",
]
[[package]]
name = "jni"
version = "0.22.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498"
dependencies = [
"cfg-if",
"combine",
"jni-macros",
"jni-sys 0.4.1",
"log",
"simd_cesu8",
"thiserror 2.0.18",
"walkdir",
"windows-link 0.2.1",
]
[[package]]
name = "jni-macros"
version = "0.22.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3"
dependencies = [
"proc-macro2",
"quote",
"rustc_version",
"simd_cesu8",
"syn 2.0.118",
]
[[package]]
name = "jni-sys"
version = "0.3.1"
@@ -1837,6 +1905,12 @@ dependencies = [
"libc",
]
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "litemap"
version = "0.8.2"
@@ -1893,6 +1967,12 @@ version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
[[package]]
name = "minisign-verify"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22f9645cb765ea72b8111f36c522475d2daa0d22c957a9826437e97534bc4e9e"
[[package]]
name = "miniz_oxide"
version = "0.8.9"
@@ -2134,6 +2214,7 @@ checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
dependencies = [
"bitflags 2.13.0",
"block2",
"libc",
"objc2",
"objc2-core-foundation",
]
@@ -2149,6 +2230,18 @@ dependencies = [
"objc2-core-foundation",
]
[[package]]
name = "objc2-osa-kit"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f112d1746737b0da274ef79a23aac283376f335f4095a083a267a082f21db0c0"
dependencies = [
"bitflags 2.13.0",
"objc2",
"objc2-app-kit",
"objc2-foundation",
]
[[package]]
name = "objc2-quartz-core"
version = "0.3.2"
@@ -2223,6 +2316,12 @@ dependencies = [
"libc",
]
[[package]]
name = "openssl-probe"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
[[package]]
name = "option-ext"
version = "0.2.0"
@@ -2239,6 +2338,20 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "osakit"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "732c71caeaa72c065bb69d7ea08717bd3f4863a4f451402fc9513e29dbd5261b"
dependencies = [
"objc2",
"objc2-foundation",
"objc2-osa-kit",
"serde",
"serde_json",
"thiserror 2.0.18",
]
[[package]]
name = "pango"
version = "0.18.3"
@@ -2673,15 +2786,20 @@ dependencies = [
"http-body",
"http-body-util",
"hyper",
"hyper-rustls",
"hyper-util",
"js-sys",
"log",
"percent-encoding",
"pin-project-lite",
"rustls",
"rustls-pki-types",
"rustls-platform-verifier",
"serde",
"serde_json",
"sync_wrapper",
"tokio",
"tokio-rustls",
"tokio-util",
"tower",
"tower-http",
@@ -2693,6 +2811,20 @@ dependencies = [
"web-sys",
]
[[package]]
name = "ring"
version = "0.17.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
dependencies = [
"cc",
"cfg-if",
"getrandom 0.2.17",
"libc",
"untrusted",
"windows-sys 0.52.0",
]
[[package]]
name = "rkyv"
version = "0.7.46"
@@ -2754,6 +2886,92 @@ dependencies = [
"semver",
]
[[package]]
name = "rustix"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"
dependencies = [
"bitflags 2.13.0",
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.61.2",
]
[[package]]
name = "rustls"
version = "0.23.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
dependencies = [
"once_cell",
"ring",
"rustls-pki-types",
"rustls-webpki",
"subtle",
"zeroize",
]
[[package]]
name = "rustls-native-certs"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4"
dependencies = [
"openssl-probe",
"rustls-pki-types",
"schannel",
"security-framework",
]
[[package]]
name = "rustls-pki-types"
version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
dependencies = [
"zeroize",
]
[[package]]
name = "rustls-platform-verifier"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98"
dependencies = [
"core-foundation 0.10.1",
"core-foundation-sys",
"jni 0.22.4",
"log",
"once_cell",
"rustls",
"rustls-native-certs",
"rustls-platform-verifier-android",
"rustls-webpki",
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.61.2",
]
[[package]]
name = "rustls-platform-verifier-android"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f"
[[package]]
name = "rustls-webpki"
version = "0.103.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
dependencies = [
"ring",
"rustls-pki-types",
"untrusted",
]
[[package]]
name = "rustversion"
version = "1.0.22"
@@ -2769,6 +2987,15 @@ dependencies = [
"winapi-util",
]
[[package]]
name = "schannel"
version = "0.1.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "schemars"
version = "0.8.22"
@@ -2832,6 +3059,29 @@ version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b"
[[package]]
name = "security-framework"
version = "3.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
dependencies = [
"bitflags 2.13.0",
"core-foundation 0.10.1",
"core-foundation-sys",
"libc",
"security-framework-sys",
]
[[package]]
name = "security-framework-sys"
version = "2.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "selectors"
version = "0.36.1"
@@ -3084,6 +3334,16 @@ version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214"
[[package]]
name = "simd_cesu8"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520"
dependencies = [
"rustc_version",
"simdutf8",
]
[[package]]
name = "simdutf8"
version = "0.1.5"
@@ -3202,6 +3462,12 @@ version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "swift-rs"
version = "1.0.7"
@@ -3255,6 +3521,27 @@ dependencies = [
"syn 2.0.118",
]
[[package]]
name = "system-configuration"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b"
dependencies = [
"bitflags 2.13.0",
"core-foundation 0.9.4",
"system-configuration-sys",
]
[[package]]
name = "system-configuration-sys"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "system-deps"
version = "6.2.2"
@@ -3276,7 +3563,7 @@ checksum = "d1c93047acf68669466a34690ac58cca7010bd1b201e1ec86f1fd0a75d3dd4a9"
dependencies = [
"bitflags 2.13.0",
"block2",
"core-foundation",
"core-foundation 0.10.1",
"core-graphics",
"crossbeam-channel",
"dbus",
@@ -3286,7 +3573,7 @@ dependencies = [
"gdkwayland-sys",
"gdkx11-sys",
"gtk",
"jni",
"jni 0.21.1",
"libc",
"log",
"ndk",
@@ -3325,6 +3612,17 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
[[package]]
name = "tar"
version = "0.4.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"
dependencies = [
"filetime",
"libc",
"xattr",
]
[[package]]
name = "target-lexicon"
version = "0.12.16"
@@ -3348,7 +3646,7 @@ dependencies = [
"gtk",
"heck 0.5.0",
"http",
"jni",
"jni 0.21.1",
"libc",
"log",
"mime",
@@ -3503,6 +3801,38 @@ dependencies = [
"tokio",
]
[[package]]
name = "tauri-plugin-updater"
version = "2.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a5cad8ed5948d988e1018ecd31e27cacedbf72ce3fb972940c3e4bf51639e4b"
dependencies = [
"base64 0.22.1",
"dirs",
"flate2",
"futures-util",
"http",
"infer",
"log",
"minisign-verify",
"osakit",
"percent-encoding",
"reqwest",
"rustls",
"semver",
"serde",
"serde_json",
"tar",
"tauri",
"tauri-plugin",
"tempfile",
"thiserror 2.0.18",
"time",
"tokio",
"url",
"windows-sys 0.60.2",
]
[[package]]
name = "tauri-runtime"
version = "2.11.3"
@@ -3513,7 +3843,7 @@ dependencies = [
"dpi",
"gtk",
"http",
"jni",
"jni 0.21.1",
"objc2",
"objc2-ui-kit",
"objc2-web-kit",
@@ -3536,7 +3866,7 @@ checksum = "4e6fac707727b7a2f48e4ded90976324267371073edbb415ffb73bb0458d203f"
dependencies = [
"gtk",
"http",
"jni",
"jni 0.21.1",
"log",
"objc2",
"objc2-app-kit",
@@ -3603,6 +3933,19 @@ dependencies = [
"toml 1.1.2+spec-1.1.0",
]
[[package]]
name = "tempfile"
version = "3.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.4.3",
"once_cell",
"rustix",
"windows-sys 0.61.2",
]
[[package]]
name = "tendril"
version = "0.5.0"
@@ -3724,6 +4067,16 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "tokio-rustls"
version = "0.26.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db"
dependencies = [
"rustls",
"tokio",
]
[[package]]
name = "tokio-util"
version = "0.7.18"
@@ -4014,6 +4367,12 @@ version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
[[package]]
name = "untrusted"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "url"
version = "2.5.8"
@@ -4275,6 +4634,15 @@ dependencies = [
"system-deps",
]
[[package]]
name = "webpki-root-certs"
version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b"
dependencies = [
"rustls-pki-types",
]
[[package]]
name = "webview2-com"
version = "0.38.2"
@@ -4460,6 +4828,17 @@ dependencies = [
"windows-link 0.1.3",
]
[[package]]
name = "windows-registry"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720"
dependencies = [
"windows-link 0.2.1",
"windows-result 0.4.1",
"windows-strings 0.5.1",
]
[[package]]
name = "windows-result"
version = "0.3.4"
@@ -4505,6 +4884,15 @@ dependencies = [
"windows-targets 0.42.2",
]
[[package]]
name = "windows-sys"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-sys"
version = "0.59.0"
@@ -4800,7 +5188,7 @@ dependencies = [
"gtk",
"http",
"javascriptcore-rs",
"jni",
"jni 0.21.1",
"libc",
"ndk",
"objc2",
@@ -4856,6 +5244,16 @@ dependencies = [
"pkg-config",
]
[[package]]
name = "xattr"
version = "1.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
dependencies = [
"libc",
"rustix",
]
[[package]]
name = "yoke"
version = "0.8.3"
@@ -4920,6 +5318,12 @@ dependencies = [
"synstructure",
]
[[package]]
name = "zeroize"
version = "1.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
[[package]]
name = "zerotrie"
version = "0.2.4"
+4
View File
@@ -28,3 +28,7 @@ tauri = { version = "2.11.3", features = [] }
tauri-plugin-log = "2"
tauri-plugin-shell = "2" # spawn the Python backend sidecar
tokio = { version = "1", features = ["time"] } # timeout on the port handshake
# One-click update (UpdateDialog.tsx). No `zip` feature: it only unpacks
# v1-style zipped Windows installers (we ship the bare NSIS setup.exe), and
# every zip 4.x it would need is yanked.
tauri-plugin-updater = { version = "2.12", default-features = false, features = ["rustls-tls", "system-proxy"] }
+236 -12
View File
@@ -26,16 +26,30 @@
// it — so it is killed only once the app really exits. If the webview does not
// acknowledge within ~2 s (hung, or not loaded yet), the app quits anyway: a
// broken page must never make the app unquittable.
//
// UPDATING rides on that same handshake (UpdateDialog.tsx). The page finds the
// release (its own GitHub check); `update_download` fetches THAT release's
// `latest.json`, downloads + verifies the package with tauri-plugin-updater and
// STAGES it on disk; `update_restart` then asks to quit like Cmd+Q does. The
// package is installed only in `exit_now`, after the sidecar is dead: on macOS
// the sidecar lazily loads native libraries from inside the bundle being
// replaced, and on Windows its .exe in the install folder is locked while it
// runs. Cancel in the Save / Discard prompt keeps the update staged, so the
// next ordinary quit installs it (without relaunching). A failed install is
// written to `failed.json` for the next launch's dialog to report.
use std::collections::VecDeque;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Mutex;
use std::time::Duration;
use std::time::{Duration, Instant};
use serde::Serialize;
use tauri::ipc::Channel;
use tauri::window::Color;
use tauri::{AppHandle, Emitter, Manager, RunEvent, WebviewUrl, WebviewWindowBuilder, WindowEvent};
use tauri_plugin_shell::process::{CommandChild, CommandEvent};
use tauri_plugin_shell::ShellExt;
use tauri_plugin_updater::{Update, UpdaterExt};
/// Holds the running sidecar child so we can terminate it on exit.
struct Sidecar(Mutex<Option<CommandChild>>);
@@ -67,15 +81,105 @@ struct Quit {
acked: AtomicBool,
}
/// A downloaded, verified update waiting for the app to exit.
struct StagedUpdate {
update: Update,
/// The package on disk (~150 MB: not worth holding in memory all session).
path: PathBuf,
/// Relaunch once installed: set by `update_restart`, cleared by Cancel.
relaunch: bool,
}
struct Staged(Mutex<Option<StagedUpdate>>);
/// Download progress for the update dialog.
#[derive(Clone, Serialize)]
struct UpdateProgress {
downloaded: u64,
total: Option<u64>,
}
/// An install that failed at exit, reported by the next launch.
#[derive(Serialize, serde::Deserialize)]
struct UpdateFailure {
version: String,
error: String,
}
const REPO: &str = "MrPatben8/konduktor";
/// The frozen backend's executable, in the bundled `sidecar/` folder (staged
/// into src-tauri/binaries/ by backend/build_sidecar.*).
fn sidecar_exe(app: &AppHandle) -> Result<PathBuf, String> {
let exe = if cfg!(windows) { "konduktor-sidecar.exe" } else { "konduktor-sidecar" };
let dir = app.path().resource_dir().map_err(|e| e.to_string())?;
Ok(dir.join("sidecar").join(exe))
}
fn kill_sidecar(app: &AppHandle) {
if let Some(child) = app.state::<Sidecar>().0.lock().unwrap().take() {
let _ = child.kill();
}
}
/// Windows only: `kill` asks the OS to end the process and returns at once,
/// and the installer must not find the sidecar's .exe still locked. Opening a
/// running executable for writing is refused, so poll that (up to ~5 s).
fn wait_for_sidecar_exit(app: &AppHandle) {
if !cfg!(windows) {
return;
}
let Ok(exe) = sidecar_exe(app) else { return };
let deadline = Instant::now() + Duration::from_secs(5);
while Instant::now() < deadline {
if std::fs::OpenOptions::new().write(true).open(&exe).is_ok() {
return;
}
std::thread::sleep(Duration::from_millis(100));
}
}
fn update_dir(app: &AppHandle) -> Option<PathBuf> {
app.path().app_cache_dir().ok().map(|dir| dir.join("update"))
}
/// Install a staged update, if any. Runs at exit with the sidecar already dead.
/// On Windows a successful install never returns (the updater starts the
/// installer and exits the process); on macOS the new bundle is in place and
/// a requested relaunch starts it.
fn install_staged(app: &AppHandle) {
let Some(staged) = app.state::<Staged>().0.lock().unwrap().take() else { return };
let StagedUpdate { update, path, relaunch } = staged;
let version = update.version.clone();
wait_for_sidecar_exit(app);
// Not re-verified: `download` checked the signature before staging, and
// whoever could alter the app's cache folder could alter the app itself.
let result = std::fs::read(&path).map_err(|e| e.to_string()).and_then(|bytes| {
update.restart_after_install(relaunch).install(bytes).map_err(|e| e.to_string())
});
let _ = std::fs::remove_file(&path);
match result {
Ok(()) if relaunch => app.restart(),
Ok(()) => {}
Err(error) => {
log::error!("update to {version} failed to install: {error}");
if let Some(dir) = update_dir(app) {
let failure = UpdateFailure { version, error };
if let Ok(json) = serde_json::to_vec(&failure) {
let _ = std::fs::write(dir.join("failed.json"), json);
}
}
if relaunch {
app.restart(); // back into the version that is still installed
}
}
}
}
fn exit_now(app: &AppHandle) {
app.state::<Quit>().allowed.store(true, Ordering::SeqCst);
kill_sidecar(app);
install_staged(app);
app.exit(0);
}
@@ -121,15 +225,7 @@ fn start_backend(app: &AppHandle) {
let gen = app.state::<Backend>().generation.fetch_add(1, Ordering::SeqCst) + 1;
set_status(app, gen, BackendStatus::Starting);
// The frozen backend lives in the bundled `sidecar/` folder (staged into
// src-tauri/binaries/ by backend/build_sidecar.*).
let exe = if cfg!(windows) { "konduktor-sidecar.exe" } else { "konduktor-sidecar" };
let spawned = app
.path()
.resource_dir()
.map_err(|e| e.to_string())
.and_then(|dir| {
let program = dir.join("sidecar").join(exe);
let spawned = sidecar_exe(app).and_then(|program| {
app.shell()
.command(&program)
.spawn()
@@ -220,10 +316,15 @@ fn quit_ack(app: AppHandle) {
app.state::<Quit>().acked.store(true, Ordering::SeqCst);
}
/// The user chose Cancel: forget the request.
/// The user chose Cancel: forget the request. A staged update stays staged
/// but no longer relaunches; the next ordinary quit installs it.
#[tauri::command]
fn quit_cancel(app: AppHandle) {
app.state::<Quit>().acked.store(false, Ordering::SeqCst);
if let Some(staged) = app.state::<Staged>().0.lock().unwrap().as_mut() {
staged.relaunch = false;
let _ = app.emit("konduktor://update-deferred", ());
}
}
/// Quit for real (nothing unsaved, or Save / Discard has finished).
@@ -232,11 +333,130 @@ fn quit_now(app: AppHandle) {
exit_now(&app);
}
/// Refuse up front what the macOS install could not do: replace a bundle on
/// a read-only volume (run from the DMG), a translocated copy, or a folder this
/// user cannot write. (The updater's own fallback for the last asks for an
/// admin password from the main thread, which the quit path may be blocking.)
#[cfg(target_os = "macos")]
fn check_installable() -> Result<(), String> {
const MOVE_IT: &str = "Move Konduktor to your Applications folder, open it from there, then try again.";
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let bundle = tauri_plugin_updater::extract_path_from_executable(&exe).map_err(|e| e.to_string())?;
if bundle.to_string_lossy().contains("/AppTranslocation/") {
return Err(MOVE_IT.into());
}
let parent = bundle.parent().ok_or_else(|| MOVE_IT.to_string())?;
let probe = parent.join(format!(".konduktor-update-check-{}", std::process::id()));
match std::fs::File::create(&probe) {
Ok(_) => {
let _ = std::fs::remove_file(&probe);
Ok(())
}
Err(_) => Err(MOVE_IT.into()),
}
}
#[cfg(not(target_os = "macos"))]
fn check_installable() -> Result<(), String> {
Ok(())
}
/// Download the update published with release `tag`, verify it and stage it
/// for installation at exit. Returns the version staged.
#[tauri::command]
async fn update_download(
app: AppHandle,
tag: String,
on_progress: Channel<UpdateProgress>,
) -> Result<String, String> {
check_installable()?;
let manifest = format!("https://github.com/{REPO}/releases/download/{tag}/latest.json");
let url = manifest.parse().map_err(|e| format!("{manifest}: {e}"))?;
let update = app
.updater_builder()
.endpoints(vec![url])
.and_then(|b| b.build())
.map_err(|e| e.to_string())?
.check()
.await
.map_err(|e| e.to_string())?
.ok_or_else(|| format!("{tag} is not newer than this version."))?;
let mut downloaded = 0u64;
let mut last_sent = Instant::now();
let bytes = update
.download(
|chunk, total| {
downloaded += chunk as u64;
// Chunks arrive every few KB: a few updates a second is plenty.
if last_sent.elapsed() >= Duration::from_millis(100) {
last_sent = Instant::now();
let _ = on_progress.send(UpdateProgress { downloaded, total });
}
},
|| {},
)
.await
.map_err(|e| e.to_string())?;
let dir = update_dir(&app).ok_or("No cache folder to download into.")?;
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
let path = dir.join(format!("{}.pkg", update.version));
std::fs::write(&path, &bytes).map_err(|e| e.to_string())?;
drop(bytes);
let version = update.version.clone();
let previous = app
.state::<Staged>()
.0
.lock()
.unwrap()
.replace(StagedUpdate { update, path: path.clone(), relaunch: false });
if let Some(old) = previous.filter(|old| old.path != path) {
let _ = std::fs::remove_file(old.path);
}
Ok(version)
}
/// Quit, install the staged update and relaunch. Goes through the ordinary
/// quit request, so unsaved changes are asked about first.
#[tauri::command]
fn update_restart(app: AppHandle) -> Result<(), String> {
match app.state::<Staged>().0.lock().unwrap().as_mut() {
Some(staged) => staged.relaunch = true,
None => return Err("No update has been downloaded.".into()),
}
request_quit(&app);
Ok(())
}
/// The last update's install failure, if any — reported once.
#[tauri::command]
fn update_take_failure(app: AppHandle) -> Option<UpdateFailure> {
let path = update_dir(&app)?.join("failed.json");
let bytes = std::fs::read(&path).ok()?;
let _ = std::fs::remove_file(&path);
serde_json::from_slice(&bytes).ok()
}
/// Packages left by a run that never exited normally (crash, force quit).
fn clear_stale_updates(app: &AppHandle) {
let Some(dir) = update_dir(app) else { return };
let Ok(entries) = std::fs::read_dir(dir) else { return };
for entry in entries.flatten() {
if entry.path().extension().is_some_and(|ext| ext == "pkg") {
let _ = std::fs::remove_file(entry.path());
}
}
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_shell::init())
.plugin(tauri_plugin_updater::Builder::new().build())
.manage(Sidecar(Mutex::new(None)))
.manage(Staged(Mutex::new(None)))
.manage(Backend { status: Mutex::new(BackendStatus::Starting), generation: AtomicU64::new(0) })
.manage(Quit { allowed: AtomicBool::new(false), acked: AtomicBool::new(false) })
.invoke_handler(tauri::generate_handler![
@@ -244,7 +464,10 @@ pub fn run() {
backend_restart,
quit_ack,
quit_cancel,
quit_now
quit_now,
update_download,
update_restart,
update_take_failure
])
.on_window_event(|window, event| {
if let WindowEvent::CloseRequested { api, .. } = event {
@@ -264,6 +487,7 @@ pub fn run() {
)?;
}
clear_stale_updates(app.handle());
start_backend(app.handle());
WebviewWindowBuilder::new(app, "main", WebviewUrl::App("index.html".into()))
+7
View File
@@ -16,9 +16,16 @@
"csp": null
}
},
"plugins": {
"updater": {
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEZBMUE5MkIyNkJFNDNENjMKUldSalBlUnJzcElhK2dpbSsyT0kzL1huSkpOOCsxaVcwN3h6TFk3V1ZHTm9uUWtJRTAwQnQrVE0K",
"windows": { "installMode": "passive" }
}
},
"bundle": {
"active": true,
"targets": "all",
"createUpdaterArtifacts": true,
"icon": [
"icons/32x32.png",
"icons/128x128.png",
@@ -0,0 +1,4 @@
{
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"bundle": { "createUpdaterArtifacts": false }
}
+34
View File
@@ -226,6 +226,21 @@ export default function App() {
[qc, notify, onError, writeHintText],
)
// The context menu's Colour ▸ — swatches are this library's own (by hex in
// the menu, sent as the neutral colour name), applied to the whole selection.
const trackColors = capabilities.data?.tracks.colors ?? []
const setTrackColor = (ids: string[], hex: string | null) => {
const swatch = trackColors.find((s) => s.hex === hex) ?? null
api
.setTrackColor(ids, swatch?.color ?? null)
.then(() => {
invalidateTrackLists(qc)
const what = swatch ? `Colour set to ${swatch.label}` : 'Colour cleared'
notify('success', `${what}${ids.length > 1 ? ` on ${ids.length} tracks` : ''} — ${writeHintText}`)
})
.catch((e) => onError((e as Error).message))
}
// NOTE: all hooks must run on every render (Rules of Hooks). Data queries are
// gated with `enabled: loaded` so they don't fire before a collection is open;
@@ -1214,6 +1229,25 @@ export default function App() {
...(canEdit && !viewingDevice && menu.ids.length === 1
? [{ label: 'Edit Tags…', onClick: gated(() => setEditing(menu.track)) }]
: []),
...(canEdit && !viewingDevice && trackColors.length
? [
{
label: 'Colour',
submenu: [
{
swatches: trackColors.map((s) => s.hex),
labels: trackColors.map((s) => s.label),
noneLabel: 'No Color',
// A multi-selection may hold several colours, so none
// is marked ('' matches no swatch and is not "none").
selected: menu.ids.length === 1 ? menu.track.color_hex : '',
onPick: (hex: string | null) =>
menuLoose.length ? void askToAdd(menuLoose) : setTrackColor(menu.ids, hex),
},
],
},
]
: []),
...(canAnalyze
? [
{
+20
View File
@@ -39,6 +39,10 @@ export interface Track {
grid_marker_count: number
grid_locked: boolean
media_kind: MediaKind
/** The track's colour tag — the platform-neutral identity — and the
* library's own display colour for it; both null when uncoloured. */
color: TrackColor | null
color_hex: string | null
}
/** One occupied hotcue slot, as the library table previews it. */
@@ -117,6 +121,15 @@ export type Platform = string
export type CueRole = 'hotcue' | 'memory'
export type CueType = 'cue' | 'fade_in' | 'fade_out' | 'load' | 'loop'
export type MediaKind = 'audio' | 'stem' | 'video'
/** A track colour tag; each library maps its own palette onto these by name. */
export type TrackColor = 'pink' | 'red' | 'orange' | 'yellow' | 'green' | 'aqua' | 'blue' | 'purple'
/** One track colour a library offers, in its own menu order. */
export interface ColorSwatch {
color: TrackColor
hex: string
/** The platform's own name for it ("Violet" in Traktor). */
label: string
}
export type PlaylistKind = 'folder' | 'playlist' | 'smart'
export type TrackField =
| 'title' | 'artist' | 'album' | 'genre' | 'label' | 'remixer'
@@ -279,6 +292,8 @@ export interface Capabilities {
audio_destination: 'host' | 'library'
/** Added files can be left where they are rather than copied. */
reference: boolean
/** The track colours this library can store; empty = no track colour. */
colors: ColorSwatch[]
}
playlists: {
folders: boolean
@@ -1072,6 +1087,11 @@ export const api = {
editTrack: (trackId: string, fields: Record<string, string | number | null>) =>
send<{ status: string }>('PATCH', '/api/tracks', { track_id: trackId, fields }),
setTrackColor: (trackIds: string[], color: TrackColor | null) =>
send<{ status: string; tracks: Track[] }>('PATCH', '/api/tracks/color', {
track_ids: trackIds,
color,
}),
artUrl: (trackId: string) =>
`${API_BASE}/api/tracks/art?track_id=${encodeURIComponent(trackId)}`,
audioUrl: (trackId: string) =>
+8 -4
View File
@@ -19,6 +19,10 @@ export type MenuItem =
selected: string | null
onPick: (color: string | null) => void
disabled?: boolean
/** Names for the swatches (tooltips), else the hex is shown. */
labels?: string[]
/** The uncoloured choice's wording; "Default" when omitted. */
noneLabel?: string
}
| { separator: true }
@@ -259,13 +263,13 @@ function SwatchGrid({
return (
<div className="px-3 pb-2 pt-1" onMouseEnter={onEnter}>
<div className="grid w-max grid-cols-8 gap-1.5">
{item.swatches.map((color) => (
{item.swatches.map((color, i) => (
<button
key={color}
role="menuitemradio"
aria-checked={selected === color.toUpperCase()}
aria-label={color}
title={color}
aria-label={item.labels?.[i] ?? color}
title={item.labels?.[i] ?? color}
disabled={item.disabled}
onClick={() => pick(color)}
className={`h-4 w-4 rounded-full transition-transform disabled:cursor-default disabled:opacity-40 ${ring(
@@ -289,7 +293,7 @@ function SwatchGrid({
selected === null ? 'outline outline-2 outline-offset-1 outline-white' : ''
}`}
/>
Default
{item.noneLabel ?? 'Default'}
</button>
</div>
)
+176 -9
View File
@@ -1,5 +1,5 @@
import { createPortal } from 'react-dom'
import { useState } from 'react'
import { useEffect, useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { api } from '../api'
@@ -12,8 +12,20 @@ import { api } from '../api'
* Failures are silent: an update check must never nag about itself.
* "Skip this version" persists `skippedUpdateVersion` to userprefs.json via
* the prefs API, keyed by the semver part, so a later version re-triggers.
*
* In the desktop app, Update installs it (decided 2026-10-16,
* .claude/discussions/discuss-self-update-2026-10-16.md): the shell
* (src-tauri/src/lib.rs) downloads THIS release's `latest.json` package with
* progress, verifies and stages it, then quits through the ordinary quit
* request — so unsaved edits are asked about by QuitGuard — and installs at
* exit, after the backend is dead, and relaunches. Cancel in that prompt
* leaves it staged for the next quit. A failure says why and offers the
* release page (what Download did before); an install that failed at exit is
* reported by the next launch. A plain browser keeps Download.
*/
const IN_TAURI = '__TAURI_INTERNALS__' in window
const REPO = 'MrPatben8/konduktor'
interface GithubRelease {
@@ -66,10 +78,17 @@ function whatsChanged(body: string | null): string[] {
const lines = body.split(/\r?\n/)
const start = lines.findIndex((l) => /^#{2,4}\s+what'?s changed/i.test(l.trim()))
const out: string[] = []
// Every release body opens with a "Download" section (build.yml): the
// fallback must not list the installer links as changes.
let inDownload = false
for (const raw of lines.slice(start + 1)) {
const line = raw.trim()
if (start !== -1 && (/^#{1,4}\s/.test(line) || line.startsWith('**Full Changelog**'))) break
if (line) {
if (/^#{1,4}\s/.test(line)) {
inDownload = /^#{1,4}\s+download/i.test(line)
continue
}
if (line && !inDownload) {
out.push(
line.replace(/^[*-]\s+/, '').replace(/\s+by\s+@[\w-]+\s+in\s+https?:\/\/\S+$/i, ''),
)
@@ -118,10 +137,31 @@ function ChangelogLine({ text }: { text: string }) {
)
}
type Phase =
| { kind: 'offer' }
| { kind: 'downloading'; downloaded: number; total: number | null }
| { kind: 'restarting' }
| { kind: 'deferred' }
| { kind: 'failed'; error: string }
interface UpdateFailure {
version: string
error: string
}
const mb = (bytes: number) => (bytes / 1e6).toFixed(0)
async function lastInstallFailure(): Promise<UpdateFailure | null> {
if (!IN_TAURI) return null
const { invoke } = await import('@tauri-apps/api/core')
return (await invoke<UpdateFailure | null>('update_take_failure')) ?? null
}
export function UpdateCheck() {
const qc = useQueryClient()
const [dismissed, setDismissed] = useState(false)
const [skipVersion, setSkipVersion] = useState(false)
const [phase, setPhase] = useState<Phase>({ kind: 'offer' })
const release = useQuery({
queryKey: ['latestRelease'],
@@ -129,20 +169,50 @@ export function UpdateCheck() {
staleTime: Infinity,
retry: false,
})
// Read (and cleared) once: the shell writes it when an install fails at exit.
const lastFailure = useQuery({
queryKey: ['updateFailure'],
queryFn: lastInstallFailure,
staleTime: Infinity,
retry: false,
})
// Shares App's ['prefs'] cache entry.
const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs })
// Cancel in QuitGuard's Save / Discard prompt: the update waits for the next quit.
useEffect(() => {
if (phase.kind !== 'restarting') return
let unlisten: (() => void) | undefined
let cancelled = false
void import('@tauri-apps/api/event').then(async ({ listen }) => {
const off = await listen('konduktor://update-deferred', () => setPhase({ kind: 'deferred' }))
if (cancelled) off()
else unlisten = off
})
return () => {
cancelled = true
unlisten?.()
}
}, [phase.kind])
const latest = release.data
const latestVer = latest ? parseVersion(latest.tag_name) : null
const currentVer = parseVersion(__APP_VERSION__)
const latestSemver = latestVer?.join('.')
const updateAvailable = !!(latestVer && currentVer && isNewer(latestVer, currentVer))
const skipped = !!latestSemver && prefs.data?.skippedUpdateVersion === latestSemver
const failedBefore = lastFailure.data ?? null
const releasePage = latest?.html_url ?? `https://github.com/${REPO}/releases`
if (dismissed) return null
// Wait for prefs before showing so a skipped version never flashes the dialog.
if (dismissed || !updateAvailable || !latest || !prefs.isSuccess || skipped) return null
const offering = updateAvailable && !!latest && prefs.isSuccess && !skipped
if (!offering && !failedBefore) return null
const busy = phase.kind === 'downloading' || phase.kind === 'restarting'
const close = () => {
if (busy) return
if (skipVersion && latestSemver) {
api
.patchPrefs({ skippedUpdateVersion: latestSemver })
@@ -152,12 +222,47 @@ export function UpdateCheck() {
setDismissed(true)
}
const download = () => {
openExternal(latest.html_url)
const openReleasePage = () => {
openExternal(releasePage)
setDismissed(true)
}
const changes = whatsChanged(latest.body)
const update = async () => {
if (!latest) return
setPhase({ kind: 'downloading', downloaded: 0, total: null })
try {
const { invoke, Channel } = await import('@tauri-apps/api/core')
const onProgress = new Channel<{ downloaded: number; total: number | null }>()
onProgress.onmessage = (p) => setPhase({ kind: 'downloading', ...p })
await invoke('update_download', { tag: latest.tag_name, onProgress })
setPhase({ kind: 'restarting' })
await invoke('update_restart')
} catch (e) {
setPhase({ kind: 'failed', error: e instanceof Error ? e.message : String(e) })
}
}
// An install that failed at the last exit, with no newer offer to make.
const reportOnly = !offering && !!failedBefore
const failure =
phase.kind === 'failed'
? phase.error
: reportOnly || (failedBefore && phase.kind === 'offer')
? `The update to v${failedBefore!.version} didn't install: ${failedBefore!.error}`
: null
const title =
phase.kind === 'downloading'
? 'Downloading update…'
: phase.kind === 'restarting'
? 'Installing update…'
: phase.kind === 'deferred'
? 'Update ready'
: phase.kind === 'failed' || reportOnly
? "Update didn't install"
: 'Update available'
const changes = latest ? whatsChanged(latest.body) : []
return createPortal(
<div
@@ -169,14 +274,44 @@ export function UpdateCheck() {
onClick={(e) => e.stopPropagation()}
>
<div className="border-b border-line px-5 py-4">
<div className="text-[15px] font-semibold tracking-tight">Update available</div>
<div className="text-[15px] font-semibold tracking-tight">{title}</div>
{latest && !reportOnly && (
<div className="text-xs text-muted">
Konduktor <span className="text-accent">{latest.tag_name}</span> is out — you have v
{__APP_VERSION__}.
</div>
)}
</div>
<div className="min-h-0 flex-1 overflow-y-auto px-5 py-4">
{failure && <p className="mb-3 text-sm text-pink">{failure}</p>}
{phase.kind === 'downloading' ? (
<div className="space-y-2">
<div className="well h-2 overflow-hidden rounded-full">
<div
className="h-full rounded-full bg-accent transition-[width] duration-150"
style={{
width: phase.total ? `${Math.min(100, (phase.downloaded / phase.total) * 100)}%` : '0%',
}}
/>
</div>
<div className="text-xs tabular-nums text-muted">
{mb(phase.downloaded)}
{phase.total ? ` / ${mb(phase.total)}` : ''} MB
</div>
</div>
) : phase.kind === 'restarting' ? (
<div className="text-sm text-muted">Konduktor will quit, install the update and reopen.</div>
) : phase.kind === 'deferred' ? (
<div className="text-sm text-muted">
The update will install the next time you quit Konduktor.
</div>
) : reportOnly ? (
<div className="text-sm text-muted">
You can download the installer from the release page instead.
</div>
) : (
<>
<div className="mb-2 text-xs font-medium text-muted">What's changed</div>
{changes.length ? (
<ul className="space-y-1.5">
@@ -192,9 +327,12 @@ export function UpdateCheck() {
) : (
<div className="text-sm text-faint">No release notes.</div>
)}
</>
)}
</div>
<div className="flex items-center gap-3 border-t border-line px-5 py-3">
{phase.kind === 'offer' && !reportOnly && (
<label className="flex cursor-pointer items-center gap-2 text-xs text-muted">
<input
type="checkbox"
@@ -204,7 +342,10 @@ export function UpdateCheck() {
/>
Skip this version
</label>
)}
<div className="flex-1" />
{phase.kind === 'offer' && !reportOnly && (
<>
<button
onClick={close}
className="rounded-md px-3 py-1.5 text-sm text-muted hover:bg-ink-800 hover:text-text"
@@ -212,11 +353,37 @@ export function UpdateCheck() {
Skip
</button>
<button
onClick={download}
onClick={IN_TAURI ? () => void update() : openReleasePage}
className="rounded-full btn-primary px-3 py-1.5 text-sm font-semibold"
>
Download
{IN_TAURI ? 'Update' : 'Download'}
</button>
</>
)}
{(phase.kind === 'failed' || reportOnly) && (
<>
<button
onClick={close}
className="rounded-md px-3 py-1.5 text-sm text-muted hover:bg-ink-800 hover:text-text"
>
Close
</button>
<button
onClick={openReleasePage}
className="rounded-full btn-primary px-3 py-1.5 text-sm font-semibold"
>
Open release page
</button>
</>
)}
{phase.kind === 'deferred' && (
<button
onClick={() => setDismissed(true)}
className="rounded-full btn-primary px-3 py-1.5 text-sm font-semibold"
>
OK
</button>
)}
</div>
</div>
</div>,
+10 -5
View File
@@ -169,10 +169,14 @@ export const TRACK_COLUMNS: ColumnDef<Track, any>[] = [
id: 'type',
header: 'Type',
size: 64,
cell: (c) =>
c.getValue() === 'stem' ? (
// The icon takes the track's colour tag, when it has one; otherwise both
// glyphs are neutral, so colour in this column only ever means the tag.
cell: (c) => {
const color = c.row.original.color_hex
const tint = color ? undefined : 'text-faint'
return c.getValue() === 'stem' ? (
// Stem file → stacked lines ("burger"), the usual stem glyph.
<span title="Stem file" className="text-accent">
<span title="Stem file" className={tint} style={color ? { color } : undefined}>
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-label="Stem">
<rect x="3" y="6" width="18" height="2.4" rx="1.2" />
<rect x="3" y="10.8" width="18" height="2.4" rx="1.2" />
@@ -181,12 +185,13 @@ export const TRACK_COLUMNS: ColumnDef<Track, any>[] = [
</span>
) : (
// Normal audio track → music note.
<span title="Audio track" className="text-faint">
<span title="Audio track" className={tint} style={color ? { color } : undefined}>
<svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor" aria-label="Audio">
<path d="M12 3v10.55A4 4 0 1 0 14 17V7h4V3h-6z" />
</svg>
</span>
),
)
},
}),
col.accessor('album', { id: 'album', header: 'Album', size: 180, cell: editable('album') }),
col.accessor('genre', { id: 'genre', header: 'Genre', size: 140, cell: editable('genre') }),