diff --git a/BUILDING-WINDOWS.md b/BUILDING-WINDOWS.md index 0224ce6..ead3d1e 100644 --- a/BUILDING-WINDOWS.md +++ b/BUILDING-WINDOWS.md @@ -1,21 +1,27 @@ # Building Konduktor for Windows -The desktop app can't be cross-compiled — a Windows build must be produced **on -Windows** (Tauri needs the MSVC toolchain + WebView2; PyInstaller must freeze the -backend into a Windows `.exe`). The macOS `.dmg` is built separately on a Mac. +The desktop app can't be cross-compiled. A Windows build must be produced **on +Windows**: Tauri needs the MSVC toolchain and WebView2, and PyInstaller must +freeze the backend into a Windows `.exe`. The macOS `.dmg` is built separately +on a Mac (see [docs/BUILDING.md](docs/BUILDING.md)). -This mirrors the macOS build exactly; only the toolchain install and the -sidecar-build command differ. +The recipe is the same as on macOS. Only the toolchain install and the +sidecar-build command differ. CI does exactly this on `windows-latest` +([.github/workflows/build.yml](.github/workflows/build.yml)), so if a local build +disagrees with CI, check that workflow first. ## One-time setup -1. **Rust** — install via (gives the `x86_64-pc-windows-msvc` +1. **Rust**: install via (gives the `x86_64-pc-windows-msvc` toolchain). You also need the **MSVC C++ build tools**: install "Desktop development with C++" from the Visual Studio Build Tools installer. -2. **WebView2 Runtime** — preinstalled on current Windows 10/11. If missing, get - the Evergreen runtime from Microsoft (Tauri's installer can also bootstrap it). -3. **Python 3.11–3.14** — (tick "Add to PATH"). -4. **Node 18+** — . +2. **WebView2 Runtime**: preinstalled on current Windows 10/11. If it's missing, + get the Evergreen runtime from Microsoft (Tauri's installer can also + bootstrap it). +3. **Python 3.11–3.14**: (tick "Add to PATH"). CI builds + with **3.12**, the safest choice. +4. **Node 20.19+ or 22.12+**: . Vite 8 refuses older + versions, so Node 18 no longer works. CI uses Node 20. Then, from the repo root: @@ -33,50 +39,115 @@ npm install cd .. ``` -## Build +If PowerShell refuses to run `Activate.ps1` or `dev.ps1` ("running scripts is +disabled on this system"), either allow local scripts once with +`Set-ExecutionPolicy -Scope CurrentUser RemoteSigned`, or run a script with +`powershell -ExecutionPolicy Bypass -File .\dev.ps1`. + +## Develop (no build) + +```powershell +.\dev.ps1 # backend on :8000 + Vite on :5173, both reloading; Ctrl-C stops both +``` + +Then open in a browser. `dev.ps1` is the Windows +counterpart of `dev.sh`. It needs the `backend\.venv` and `frontend\node_modules` +from the setup above. It runs the Python source, not the frozen sidecar, so it +can't show desktop-shell behaviour (startup screen, quit prompt, WebView2, file +drops from Explorer). For that, run `npx tauri dev` in `frontend`. Note that this +still spawns the **frozen** sidecar staged in `src-tauri\binaries\`, so backend +changes need `build_sidecar.ps1` first. + +### Tests + +`backend/run_tests.sh` expects a POSIX venv (`.venv/bin/activate`), so it won't +run as-is on Windows. Run a suite directly with the venv's Python instead: ```powershell -# 1) Freeze + stage the backend sidecar (from the activated backend venv) cd backend -.\.venv\Scripts\Activate.ps1 # if not already active +.\.venv\Scripts\python.exe test_save_fidelity.py +``` + +## Build + +One command does both steps and lists the installers it produced: + +```powershell +.\build.ps1 # sidecar + app +.\build.ps1 -SkipSidecar # frontend-only change: reuse the staged sidecar +.\build.ps1 --debug # any other argument is passed on to `tauri build` +``` + +By hand, that is: + +```powershell +# 1) Freeze + stage the backend sidecar +cd backend .\build_sidecar.ps1 # → frontend\src-tauri\binaries\konduktor-sidecar\ (a folder) cd .. -# 2) Build the app +# 2) Build the app (its beforeBuildCommand runs the Vite build) cd frontend npx tauri build ``` +`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. + +The sidecar is a PyInstaller **onedir** folder (`konduktor-sidecar.exe` plus +`_internal\`), not a single `.exe`. Don't switch it back to onefile; see +gotcha 4 in [CLAUDE.md](CLAUDE.md). + ## Output Installers land in: ``` -frontend\src-tauri\target\release\bundle\msi\Konduktor_0.1.0_x64_en-US.msi -frontend\src-tauri\target\release\bundle\nsis\Konduktor_0.1.0_x64-setup.exe +frontend\src-tauri\target\release\bundle\nsis\Konduktor__x64-setup.exe +frontend\src-tauri\target\release\bundle\msi\Konduktor__x64_en-US.msi ``` -Either one installs the app, with the sidecar folder in its `sidecar\` resource -folder (`tauri.windows.conf.json`). +`` is the `version` in [frontend/package.json](frontend/package.json), +the app's only version source. Either installer works. Releases ship only the +NSIS `-setup.exe`. Both put the sidecar folder in the app's `sidecar\` resource +folder (`tauri.windows.conf.json` → `bundle.resources`), where `lib.rs` spawns +`sidecar\konduktor-sidecar.exe`. ## Rebuilding after changes -Same as macOS: if you changed **backend** Python, re-run `build_sidecar.ps1` -first; then `npx tauri build`. Frontend-only changes just need `npx tauri build` -(its `beforeBuildCommand` rebuilds the web app). +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`). + +## Not part of this build: the stem engine + +Convert to Stems uses a separate program, `engine/` (torch + demucs), built and +released on its own channel by +[.github/workflows/engine.yml](.github/workflows/engine.yml) (`windows-x64-cpu` +and `windows-x64-cuda`). The app downloads it at runtime into a short +`%LOCALAPPDATA%\Konduktor\engine` path to stay under Windows' 260-character path +limit. You don't need it to build or run the app. ## Known Windows caveats -- **Unsigned build → SmartScreen.** We don't code-sign yet, so the first launch - shows a "Windows protected your PC" prompt. Click **More info → Run anyway**. - (Signing is a future step.) +- **Unsigned build → SmartScreen.** Builds aren't code-signed yet, so the first + launch shows a "Windows protected your PC" prompt. Click **More info → Run + anyway**. - **Mixed content is already handled.** The webview is forced to the `http` custom-protocol scheme (`use_https_scheme(false)` in `src-tauri/src/lib.rs`) so it can fetch the sidecar at `http://127.0.0.1:` without being blocked. Leave that setting as-is. -- **Sidecar console window.** The sidecar is frozen as a console app (needed for - the `KONDUKTOR_PORT` stdout handshake). Tauri's shell plugin normally spawns it - without a visible window; if a console flashes on launch, tell me and we'll add - the `CREATE_NO_WINDOW` spawn flag. -- **The sidecar must be frozen on Windows** — a macOS-built sidecar won't run. +- **The sidecar is a console app, but no console appears.** It's frozen with + `console=True` because the shell reads the `KONDUKTOR_PORT=` line from its + stdout. Tauri's shell plugin spawns it with `CREATE_NO_WINDOW`, so no window + flashes. +- **The sidecar doesn't watch stdin on Windows.** On macOS it exits when its + stdin closes. On Windows a pending stdin read stalled loading scipy's OpenBLAS + DLL, which hung the first analysis, so it waits on the parent process instead + (`backend/sidecar.py`). Keep this in mind before touching that watcher. +- **Decode audio through `waveform.load`, never `librosa.load`.** librosa reads + AAC only through CoreAudio or a system ffmpeg, so on Windows every `.m4a` / + `.stem.m4a` failed with "Format not recognised". PyAV bundles FFmpeg. +- **The sidecar must be frozen on Windows.** A macOS-built sidecar won't run. `build_sidecar.ps1` handles this; just don't copy binaries between OSes. diff --git a/CLAUDE.md b/CLAUDE.md index ecf43f8..95d46e8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -170,7 +170,14 @@ Two independent apps that talk over HTTP: file** (Convert to Stems). An `ipod` MP4 with five AAC stereo 44.1 kHz streams (mix, drums, bass, synths, vox), streams 1-4 `disposition` 0, muxed IN LOCKSTEP, plus a `moov/udta/stem` JSON box appended in place - (moov is last, so only two sizes change). The separation is a CALLBACK — + (moov is last, so only two sizes change). **Each stream encodes on its + own thread** (PyAV releases the GIL in FFmpeg; ~3x faster with `aac`, + 104 → 35 s for a 5-minute track's real stems) while ONE thread muxes in + the single-threaded order, so the file is byte-identical; every codec is + opened and the header written before a worker starts, since the first + `mux()` would otherwise open codecs a worker is using. `aac_coder=fast` + was measured and rejected: 3-4x faster per stream, but it drops whole + 8-20 kHz bands for moments (twoloop: never). The separation is a CALLBACK — the backend never imports torch; the engine (below) supplies it, the tests a fake. Measured traps: FFmpeg's resampler upmixes mono at -3 dB, so mono is duplicated by hand; resampling does not move time; both @@ -927,6 +934,21 @@ Two independent apps that talk over HTTP: could not be dropped on. Targets: playlist + export rows (Sidebar, ExportsSection), the tree's zones, the table's reorder, and the DECK (App), which loads the grabbed row paused, in its own origin. + **Files from Finder / Explorer** (decided 2026-10-13) ride the same store + as a `files` payload: `lib/fileDrop.ts` feeds Tauri's `onDragDropEvent` + (real paths; a plain browser has none, so no file drop there) through + `nativeDragStart`/`Move`/`End`, refused at enter while an `aria-modal` + dialog is open or no library is loaded. A playlist/export row opens + `AddFilesDialog` with its target, ONE audio file on the deck loads it to + listen to, anywhere else (App's root target, with a window overlay) adds + to the collection — or says why the library cannot. `POST + /api/folder/dropped` resolves the paths first (`FolderScanner.dropped`: + folders RECURSIVELY, capped at `MAX_DROPPED`; single files held apart + from the folder cache so a partial listing never hides a folder's other + files from the sidebar) and makes each file addable and playable through + the folder routes. Copy vs in place is asked as for a browsed folder; the + add preview counts external-drive files PER FILE (`removable_count` / + `removable_drives`, a drop can mix drives) and `in_destination`. `ConvertStemsDialog` (**Convert to Stems**, one dialog — decided: Where = Replace the originals (its option STATES that Save deletes them, since the choice is remembered and may be preselected) or Save to a folder; In @@ -1098,6 +1120,7 @@ Two independent apps that talk over HTTP: ```bash ./dev.sh # start both servers (see README for one-time setup) +.\dev.ps1 # the same on Windows (BUILDING-WINDOWS.md) # Backend cd backend && source .venv/bin/activate @@ -1170,7 +1193,10 @@ serialization path.** It enforces: 48 kHz resampling does not move time; MP3 and FLAC through both encoders give five streams with only the mix enabled, no shift (cross-correlation), the bitrate rule (256 floor, lossless 320), every tag + cover; `verify` refuses a - shifted, truncated or box-less file; a raising checkpoint cancels. + shifted, truncated or box-less file; a raising checkpoint cancels. The + threaded encode is byte-identical to a single-threaded reference (with each + encoder present), reports progress 0 → 1, and a cancel or a failing encoder + thread leaves no thread running. - `test_stem_swap.py` — `apply_stem_swaps` on a temp copy of the real collection with a generated MP3 (with header) and a real stem file: prep reads back at the same decoded second while its START moves by the 2257- @@ -1367,7 +1393,11 @@ serialization path.** It enforces: scan did not find; **a file the collection already points at is never added twice** (on Traktor that would be two ENTRYs sharing a primary key — a corrupt collection) but still reaches the playlist/export it was headed for; "copy" - points the entry at the copy and "reference" at the original. + points the entry at the copy and "reference" at the original. And a DROP + (`/api/folder/dropped`): folders recursively minus hidden ones, dropped + non-audio counted as skipped, only what was dropped becomes streamable, the + folder's own listing stays whole, the cap, held files as their collection + track, and the preview's per-file external-drive count and `in_destination`. - `test_picker.py` — the picker's routes. Pins the scoping, because the bug it replaced was invisible: `/api/library/options` flattened every driver's detections and returned `[0]`, so a plugged-in USB stick could be offered as diff --git a/backend/build_sidecar.ps1 b/backend/build_sidecar.ps1 index c5196ec..7cf8282 100644 --- a/backend/build_sidecar.ps1 +++ b/backend/build_sidecar.ps1 @@ -16,7 +16,12 @@ Set-Location $Root $Py = Join-Path $Root ".venv\Scripts\python.exe" if (-not (Test-Path $Py)) { $Py = "python" } -& $Py -m PyInstaller --noconfirm --clean konduktor-sidecar.spec +# PyInstaller logs to stderr. Windows PowerShell 5.1 (unlike pwsh 7) turns a +# native command's stderr into an error record, which "Stop" makes fatal on the +# first INFO line — so relax it for this call and judge by the exit code. +$ErrorActionPreference = "Continue" +& $Py -m PyInstaller --noconfirm --clean konduktor-sidecar.spec 2>&1 | ForEach-Object { "$_" } +$ErrorActionPreference = "Stop" if ($LASTEXITCODE -ne 0) { throw "PyInstaller failed ($LASTEXITCODE)" } Write-Host "Built: $Root\dist\konduktor-sidecar\" diff --git a/backend/konduktor/core/folder.py b/backend/konduktor/core/folder.py index 5f04ce0..f80c77c 100644 --- a/backend/konduktor/core/folder.py +++ b/backend/konduktor/core/folder.py @@ -14,7 +14,9 @@ This is opened by the folder routes and nothing else. Three rules: * **This folder only.** Subfolders are not scanned — the tree is how you get to - them — so a click on a drive root never walks the whole drive. + them — so a click on a drive root never walks the whole drive. A folder + DROPPED onto the window is the exception (`FolderScanner.dropped`): the user + asked for everything in it, so it recurses, capped at `MAX_DROPPED`. * **A track id is the file's absolute path.** It is the one identity a loose file has, and it is what the audio route checks a request against. * **Tags are read once per folder state.** Reading tags opens every file, which @@ -26,6 +28,7 @@ from __future__ import annotations import logging import os import threading +from dataclasses import dataclass, field from pathlib import Path from .capabilities import Capabilities, SaveCapabilities, TrackCapabilities @@ -165,17 +168,88 @@ class FolderSource: return capabilities_for(self.path) +# A drop of a whole drive must not read tags for hours: past this many audio +# files the rest are left out and the answer says so. +MAX_DROPPED = 20_000 + + +@dataclass +class Dropped: + """What a drop onto the window resolved to.""" + + tracks: list[Track] = field(default_factory=list) + # Dropped FILES that are not audio this library can hold (or are gone). + # Non-audio inside a dropped folder is not counted: an album folder's + # cover and cue sheet are not something the user asked to add. + skipped: int = 0 + # More than MAX_DROPPED audio files: the rest were left out. + truncated: bool = False + + class FolderScanner: """Scans folders on request, caching each until its contents change. Also the gatekeeper for streaming: `source_for_file` answers only for a file - found by a scan, so the audio route cannot be used to read an arbitrary path - off the disk — only audio the user has browsed to. + found by a scan — or dropped onto the window by the user — so the audio + route cannot be used to read an arbitrary path off the disk, only audio the + user has browsed to or handed over. """ def __init__(self) -> None: self._lock = threading.Lock() self._cache: dict[str, tuple[float, tuple[str, ...], FolderSource]] = {} + # Files dropped one by one: their folder was never scanned (and is not + # cached as if it had been — a partial listing would hide its other + # files from the sidebar), so each is held on its own. + self._files: dict[str, Track] = {} + + def dropped(self, paths: list[str], formats: list[str], limit: int = MAX_DROPPED) -> Dropped: + """Resolve paths dropped onto the window: folders RECURSIVELY (hidden + and OS-housekeeping folders left out, as the tree leaves them out), + files as themselves. Every audio file found becomes addable and + playable through the folder routes, exactly as if it had been browsed.""" + wanted = {f.lower() for f in formats} + out = Dropped() + seen: set[str] = set() + + def take(tracks: list[Track]) -> bool: + for t in tracks: + if t.id in seen: + continue + if len(out.tracks) >= limit: + out.truncated = True + return False + seen.add(t.id) + out.tracks.append(t) + return True + + for raw in paths: + path = Path(raw).expanduser() + if path.is_dir(): + for folder in _walk(path): + if not audio_files(folder, formats): + continue + if not take(self.scan(folder, formats).tracks): + return out + elif path.is_file() and path.suffix.lower() in wanted and not is_hidden(path): + track = self._file_track(path) + if not take([track]): + return out + else: + out.skipped += 1 + return out + + def _file_track(self, path: Path) -> Track: + key = str(path) + with self._lock: + hit = self._cache.get(str(path.parent)) + known = hit[2].track(key) if hit is not None else None + if known is not None: + return known + track = read_track(path) + with self._lock: + self._files[key] = track + return track def scan(self, folder: Path, formats: list[str]) -> FolderSource: folder = Path(folder) @@ -198,10 +272,32 @@ class FolderScanner: folder = str(Path(track_id).parent) with self._lock: hit = self._cache.get(folder) - if hit is None or hit[2].track(track_id) is None: - return None - return hit[2] + loose = self._files.get(track_id) + if hit is not None and hit[2].track(track_id) is not None: + return hit[2] + if loose is not None: + return FolderSource(Path(folder), [loose]) + return None def clear(self) -> None: with self._lock: self._cache.clear() + self._files.clear() + + +def _walk(root: Path): + """`root` and every visible folder under it, depth first, sorted by name.""" + yield root + try: + with os.scandir(root) as it: + subs = [] + for entry in it: + try: + if entry.is_dir(follow_symlinks=False) and not is_hidden(entry): + subs.append(Path(entry.path)) + except OSError: + continue + except OSError: + return + for sub in sorted(subs, key=lambda p: p.name.lower()): + yield from _walk(sub) diff --git a/backend/konduktor/core/grid_detect.py b/backend/konduktor/core/grid_detect.py index 7c852f7..87efe2b 100644 --- a/backend/konduktor/core/grid_detect.py +++ b/backend/konduktor/core/grid_detect.py @@ -235,8 +235,8 @@ def detect_grid( if bpm is not None and not (20.0 <= bpm <= 400.0): raise ValueError(f"Not a usable BPM: {bpm}") if y is None: - import librosa - y, sr = librosa.load(audio_path, sr=sr, mono=True) + from . import waveform + y, sr = waveform.load(audio_path, sr=sr) y = np.asarray(y, dtype=np.float32) duration = len(y) / sr if duration < 1.5: diff --git a/backend/konduktor/core/key_detect.py b/backend/konduktor/core/key_detect.py index 02173a8..f429a6e 100644 --- a/backend/konduktor/core/key_detect.py +++ b/backend/konduktor/core/key_detect.py @@ -178,7 +178,7 @@ def with_detected_key(track, y: np.ndarray | None, sr: int): def detect_key(audio_path: str) -> KeyResult | None: - import librosa + from . import waveform - y, sr = librosa.load(audio_path, sr=SR, mono=True) + y, sr = waveform.load(audio_path, sr=SR) return detect_key_samples(y, sr) diff --git a/backend/konduktor/core/stem_file.py b/backend/konduktor/core/stem_file.py index b17cc1e..68033e5 100644 --- a/backend/konduktor/core/stem_file.py +++ b/backend/konduktor/core/stem_file.py @@ -37,8 +37,10 @@ from __future__ import annotations import fractions import json +import queue import struct import sys +import threading from dataclasses import dataclass from pathlib import Path from typing import Callable @@ -151,15 +153,36 @@ def decode(path: Path | str) -> Source: return Source(pcm=np.ascontiguousarray(pcm), codec=codec, bit_rate=bit_rate) +#: Encoded frames each stream's thread may run ahead of the muxer. +_ENCODE_QUEUE = 64 +#: Frames between `checkpoint()` / `progress()` calls (~6 s of audio). +_ENCODE_TICK = 256 + + def _encode(fp, tracks: list[np.ndarray], *, bit_rate: int, encoder: str, - checkpoint: Callable[[], None] | None) -> None: - """Mux five AAC streams IN LOCKSTEP — one frame of each in turn — so the - muxer never buffers a whole stream (which it would if they came one after - another).""" + checkpoint: Callable[[], None] | None, + progress: Callable[[float], None] | None = None) -> None: + """Encode the AAC streams on one thread EACH and mux them on this one, IN + LOCKSTEP — per frame stream 0..4, then each stream's flush — so the muxer + never buffers a whole stream (which it would if they came one after another). + + The encoders are independent and PyAV releases the GIL inside FFmpeg, so + this is ~3x faster than one thread with FFmpeg's `aac` (a 5-minute track's + real stems: 104 s -> 35 s on a 6-core i7) — and since the mux order is the single-threaded + one, the file is byte-identical. Every codec is opened and the header written + HERE before any worker starts: the first `mux()` would otherwise open (and + read) codec contexts a worker may be opening or encoding with. After that + this thread never touches a codec, and a worker never touches the container. + + `checkpoint()` and `progress(fraction)` are called from this thread only. + """ import av n = tracks[0].shape[1] tb = fractions.Fraction(1, SR) + offsets = range(0, n, FRAME) + stop = threading.Event() + threads: list[threading.Thread] = [] container = av.open(fp, "w", format="ipod") try: streams = [] @@ -169,21 +192,63 @@ def _encode(fp, tracks: list[np.ndarray], *, bit_rate: int, encoder: str, if k: s.disposition = 0 # present, not enabled: a plain player plays the mix streams.append(s) - for i, offset in enumerate(range(0, n, FRAME)): - if checkpoint is not None and i % 512 == 0: - checkpoint() - for s, x in zip(streams, tracks): - frame = av.AudioFrame.from_ndarray( - np.ascontiguousarray(x[:, offset:offset + FRAME], dtype=np.float32), - format="fltp", layout="stereo", - ) - frame.sample_rate, frame.pts, frame.time_base = SR, offset, tb - for packet in s.encode(frame): - container.mux(packet) for s in streams: - for packet in s.encode(None): + s.codec_context.open(strict=False) + container.start_encoding() + queues = [queue.Queue(maxsize=_ENCODE_QUEUE) for _ in tracks] + + def put(q: queue.Queue, item) -> bool: + while not stop.is_set(): + try: + q.put(item, timeout=0.1) + return True + except queue.Full: + pass + return False # the muxer gave up: stop encoding + + def work(s, x: np.ndarray, q: queue.Queue) -> None: + try: + for offset in offsets: + frame = av.AudioFrame.from_ndarray( + np.ascontiguousarray(x[:, offset:offset + FRAME], dtype=np.float32), + format="fltp", layout="stereo", + ) + frame.sample_rate, frame.pts, frame.time_base = SR, offset, tb + if not put(q, s.encode(frame)): + return + put(q, s.encode(None)) + except BaseException as ex: # noqa: BLE001 — re-raised by the muxer + put(q, ex) + + def mux(q: queue.Queue) -> None: + packets = q.get() + if isinstance(packets, BaseException): + raise packets + for packet in packets: container.mux(packet) + + threads = [threading.Thread(target=work, args=(s, x, q), daemon=True, name=f"stem-encode-{k}") + for k, (s, x, q) in enumerate(zip(streams, tracks, queues))] + for t in threads: + t.start() + for i in range(len(offsets)): + if i % _ENCODE_TICK == 0: + if checkpoint is not None: + checkpoint() + if progress is not None: + progress(i / len(offsets)) + for q in queues: + mux(q) + for q in queues: + mux(q) # each stream's flush + if progress is not None: + progress(1.0) finally: + # A cancel or a failure: the workers stop at their next frame, and must + # have stopped before the container (and their codecs) are freed. + stop.set() + for t in threads: + t.join() container.close() @@ -302,14 +367,16 @@ Separate = Callable[[np.ndarray], list[np.ndarray]] def build(source_path: Path | str, target: Path | str, separate: Separate, *, - encoder: str | None = None, checkpoint: Callable[[], None] | None = None) -> Written: + encoder: str | None = None, checkpoint: Callable[[], None] | None = None, + on_encode: Callable[[float], None] | None = None) -> Written: """Convert `source_path` into a stem file at `target`. `separate(pcm)` gets the stereo 44.1 kHz mix and must return the four stems in `DEMUCS_ORDER`, each the mix's shape. `target` may be any name — the batch writes a `*.konduktor-partial` and renames it once the batch commits — since nothing here infers a format from the suffix. `checkpoint()` is called between - phases and during the encode, and may raise to cancel. + phases and during the encode, and may raise to cancel. `on_encode(fraction)` + reports the encode's progress, 0 to 1 (verifying after it takes ~1 s). """ target = Path(target) tick = checkpoint or (lambda: None) @@ -322,7 +389,7 @@ def build(source_path: Path | str, target: Path | str, separate: Separate, *, bit_rate = choose_bitrate(source) with open(target, "wb") as fp: _encode(fp, [source.pcm, *stems], bit_rate=bit_rate, - encoder=encoder or default_encoder(), checkpoint=checkpoint) + encoder=encoder or default_encoder(), checkpoint=checkpoint, progress=on_encode) add_stem_box(target) tags = tag_copy.copy_tags(source_path, target) verify(target, source) diff --git a/backend/konduktor/core/structure.py b/backend/konduktor/core/structure.py index 70222af..4535644 100644 --- a/backend/konduktor/core/structure.py +++ b/backend/konduktor/core/structure.py @@ -273,8 +273,8 @@ def analyse( if not markers: raise ValueError("Set a beatgrid first") if y is None: - import librosa - y, _ = librosa.load(audio_path, sr=_SR, mono=True) + from . import waveform + y, _ = waveform.load(audio_path, sr=_SR) y = np.asarray(y, dtype=np.float32) duration = len(y) / _SR beats, bar0 = grid_beats(markers, duration) diff --git a/backend/konduktor/core/waveform.py b/backend/konduktor/core/waveform.py index 9c00067..2e97c55 100644 --- a/backend/konduktor/core/waveform.py +++ b/backend/konduktor/core/waveform.py @@ -84,8 +84,8 @@ class Analysis: return self.columns.duration -def _decode_pyav(path: Path) -> np.ndarray: - """Mono float32 at `SR`, via PyAV — FFmpeg's decoders, bundled in its wheel. +def _decode_pyav(path: Path, sr: int = SR) -> np.ndarray: + """Mono float32 at `sr`, via PyAV — FFmpeg's decoders, bundled in its wheel. The reason it is first: it decodes AAC (every Traktor `.stem.m4a`) on EVERY OS, where librosa needs CoreAudio (macOS only) or a system ffmpeg. Measured @@ -98,7 +98,7 @@ def _decode_pyav(path: Path) -> np.ndarray: with pyav.open_input(path) as container: stream = container.streams.audio[0] - resampler = av.AudioResampler(format="flt", layout="mono", rate=SR) + resampler = av.AudioResampler(format="flt", layout="mono", rate=sr) chunks = [] for frame in container.decode(stream): for out in resampler.resample(frame): @@ -122,16 +122,24 @@ def even_slices(n: int, k: int) -> list[slice]: return [slice(int(a), int(max(b, a + 1)) if n else 0) for a, b in zip(edges[:-1], edges[1:])] -def _decode(path: Path) -> np.ndarray | None: +def load(path: Path | str, sr: int = SR) -> tuple[np.ndarray, int]: + """Mono float32 at `sr` as `(y, sr)` — `librosa.load`'s shape, raising as it + does. EVERY analysis decode goes through here, never `librosa.load` itself: + librosa reads AAC only through CoreAudio or a system ffmpeg, so on Windows + a `.stem.m4a` failed with "Format not recognised".""" try: - return _decode_pyav(path) + return _decode_pyav(Path(path), sr), sr except Exception as ex: # PyAV missing, or a file FFmpeg cannot open log.debug("PyAV could not decode %s (%s); trying librosa", path, ex) - try: - import librosa + import librosa - y, _ = librosa.load(str(path), sr=SR, mono=True) - return y + y, _ = librosa.load(str(path), sr=sr, mono=True) + return y, sr + + +def _decode(path: Path) -> np.ndarray | None: + try: + return load(path)[0] except Exception as ex: # any decoder failure: no waveform, not a failed export log.warning("could not decode %s for a waveform: %s", path, ex) return None diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index 199b0ec..82797ab 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -69,6 +69,8 @@ from .schemas import ( ExportSetOut, ExportPreview, Drive, + DroppedFiles, + DroppedPaths, FolderAddRequest, FolderTracks, FsEntry, @@ -120,8 +122,12 @@ app.add_middleware( "http://localhost:5173", "http://127.0.0.1:5173", # Packaged desktop app: the webview's origin when Tauri loads the built - # frontend (macOS uses tauri://, Windows/Linux use https://tauri.localhost). + # frontend. macOS uses tauri://; Windows/Linux default to + # https://tauri.localhost, but lib.rs forces the http scheme + # (use_https_scheme(false)) so the sidecar is not mixed content — + # without the http origin here, the Windows app reaches no API at all. "tauri://localhost", + "http://tauri.localhost", "https://tauri.localhost", ], allow_methods=["*"], @@ -1662,10 +1668,10 @@ def analyze_preview(body: AnalyzeRequest) -> AnalyzePreview: def _decode_for_analysis(path: Path): """Mono samples at the rate BOTH detectors work at (they share one decode).""" - import librosa + from .core import waveform assert grid_detect._SR == key_detect.SR, "grid and key detection must share a sample rate" - return librosa.load(str(path), sr=key_detect.SR, mono=True) + return waveform.load(path, sr=key_detect.SR) def _analyse_one(a, track_id: str, body: AnalyzeRequest, result: dict) -> None: @@ -2317,6 +2323,18 @@ def folder_tracks(path: str) -> FolderTracks: ) +@app.post("/api/folder/dropped", response_model=DroppedFiles) +def folder_dropped(body: DroppedPaths) -> DroppedFiles: + """Files and folders dropped onto the window. Folders are searched all the + way down; every audio file found is then addable and playable through the + folder routes, as if it had been browsed to in the sidebar.""" + dest = require_adapter() + dropped = FOLDERS.dropped(body.paths, _formats()) + held = importer._existing_files(dest) + rows, files = _folder_rows(dest, dropped.tracks, lambda t: held.get(importer._key(Path(t.id)))) + return DroppedFiles(tracks=rows, files=files, skipped=dropped.skipped, truncated=dropped.truncated) + + def _folder_track(track_id: str) -> FolderSource: # Only a file a scan found. This is what keeps the audio route from being a # way to read any path on the disk. @@ -2443,8 +2461,28 @@ def folder_add_preview(body: FolderAddRequest) -> dict: elif body.mode == "reference": # Nothing is copied, so there is no size to fit anywhere. out.update(total_bytes=0, free_bytes=None, enough_space=None) - drive = _drive_of(Path(body.track_ids[0]), places.drives()) if body.track_ids else None - out["removable"] = drive is None or drive["kind"] == "external" + elif destination is not None: + # Copying a file that is already in the import folder makes a second + # copy beside it — legal, but rarely meant, so the dialog says so. + home = destination.resolve() + out["in_destination"] = sum( + 1 for t in plan.importable + if t.source_path is not None and t.source_path.resolve().is_relative_to(home) + ) + # Per FILE, not per request: a drop can mix the computer's own disk with a + # stick, and only the files on the stick go missing when it is unplugged. + drives = places.drives() + external: dict[str, int] = {} + for t in plan.importable: + if t.source_path is None: + continue + drive = _drive_of(t.source_path, drives) + if drive is None or drive["kind"] == "external": + name = drive["name"] if drive else str(t.source_path.anchor or t.source_path.parent) + external[name] = external.get(name, 0) + 1 + out["removable"] = bool(external) + out["removable_count"] = sum(external.values()) + out["removable_drives"] = sorted(external) return out diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index d051a21..721586e 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -549,6 +549,25 @@ class FolderTracks(BaseModel): removable: bool +class DroppedPaths(BaseModel): + """Files and folders dropped onto the window from Finder / Explorer.""" + + paths: list[str] + + +class DroppedFiles(BaseModel): + """What a drop resolved to: the audio in it, as a folder lists its files.""" + + tracks: list[Track] + # As FolderTracks: rows the collection holds are its tracks, and this maps + # their collection id back to the file's folder id, which adding takes. + files: dict[str, str] = {} + # Dropped files that are not audio the library can hold, or are gone. + skipped: int = 0 + # Too many files: only the first MAX_DROPPED are here. + truncated: bool = False + + class FolderAddRequest(BaseModel): """Add browsed files to the collection, and optionally to a playlist/export. diff --git a/backend/konduktor/stems/convert.py b/backend/konduktor/stems/convert.py index b08d4ae..5f5acbe 100644 --- a/backend/konduktor/stems/convert.py +++ b/backend/konduktor/stems/convert.py @@ -39,11 +39,25 @@ _BYTES_PER_SECOND = {256_000: 5 * 256_000 / 8 * 1.03, 320_000: 5 * 320_000 / 8 * _WORK_BYTES_PER_SECOND = 5 * 2 * 4 * sf.SR -#: Shares of ONE track's conversion time, for the status bar's within-track -#: progress (measured on the M3 Pro: decode ~1 s, separate ~50 s, encode + -#: verify ~4 s for a 4-minute track). -_DECODE_SHARE = 0.03 -_SEPARATE_SHARE = 0.90 +#: Shares of ONE track's conversion time (decode, separate; encoding + verifying +#: take the rest), for the status bar's within-track progress, by AAC encoder. +#: Measured: `aac_at` on the M3 Pro (4-minute track: decode ~1 s, separate +#: ~50 s, encode + verify ~4 s); `aac` on an i7-9750H + RTX 2070 (5-minute +#: track: decode 0.5 s, separate ~102 s, encode ~38 s on five threads, verify ~1 s). +_SHARES = {"aac_at": (0.03, 0.90), "aac": (0.01, 0.71)} + + +def track_shares(encoder: str) -> tuple[float, float]: + return _SHARES.get(encoder, _SHARES["aac"]) + + +def encode_reporter(handle, start: float, end: float = 0.99) -> Callable[[float], None]: + """`on_encode` for `stem_file.build`: the encode runs from `start` to `end` + of the track, and the ~1 s of tags + verification after it reads as such.""" + def report(f: float) -> None: + frac = start + f * (end - start) + handle.progress(fraction=frac, status=f"{'verifying' if f >= 1 else 'encoding'} {frac * 100:.0f} %") + return report class ConvertError(Exception): @@ -227,6 +241,7 @@ def run(handle, adapter, planned: Plan, opts: Options, pending: Pending, *, work = work_root() / f"batch-{id(handle):x}" finished: list[tuple[Planned, dict, sf.Written]] = [] needs_engine = any(p.reuse is None for p in items) + encoder = sf.default_encoder() if needs_engine and not mgr.ready(): raise ConvertError("The stem engine is not installed") @@ -258,22 +273,22 @@ def run(handle, adapter, planned: Plan, opts: Options, pending: Pending, *, "stem": str(item.target), "state": "converting", "facts": source_facts(item.source)}) item.target.parent.mkdir(parents=True, exist_ok=True) - # Of a TRACK's time, separation is nearly all (~90 % on MPS); - # decoding before it and encoding + verifying after share the rest. + # Of a TRACK's time, separation is nearly all; decoding before it + # and encoding + verifying after share the rest. + decode_share, separate_share = track_shares(encoder) + def on_progress(f: float) -> None: - frac = _DECODE_SHARE + f * (_SEPARATE_SHARE) + frac = decode_share + f * separate_share handle.progress(fraction=frac, status=f"separating {frac * 100:.0f} %") def separate(pcm): - handle.progress(fraction=_DECODE_SHARE, status=f"separating {_DECODE_SHARE * 100:.0f} %") - stems = engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled) - done_at = _DECODE_SHARE + _SEPARATE_SHARE - handle.progress(fraction=done_at, status=f"encoding {done_at * 100:.0f} %") - return stems + handle.progress(fraction=decode_share, status=f"separating {decode_share * 100:.0f} %") + return engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled) handle.progress(status="decoding 0 %") try: - written = sf.build(item.source, partial, separate, checkpoint=checkpoint) + written = sf.build(item.source, partial, separate, encoder=encoder, checkpoint=checkpoint, + on_encode=encode_reporter(handle, decode_share + separate_share)) except (_Cancel, EngineCancelled): partial.unlink(missing_ok=True) pending.drop([pitem]) diff --git a/backend/konduktor/stems/remote_convert.py b/backend/konduktor/stems/remote_convert.py index 14b120c..98952b1 100644 --- a/backend/konduktor/stems/remote_convert.py +++ b/backend/konduktor/stems/remote_convert.py @@ -153,13 +153,12 @@ def run(handle, adapter, planned: RemotePlan, opts: convert.Options, *, still_cu def separate(pcm): handle.progress(fraction=0.05, status="separating 5 %") - stems = engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled) - handle.progress(fraction=0.85, status="encoding 85 %") - return stems + return engine.separate(pcm, work, on_progress=on_progress, cancelled=lambda: handle.cancelled) partial = work / f"{n}.stem.m4a" try: - written = sf.build(local, partial, separate, checkpoint=checkpoint) + written = sf.build(local, partial, separate, checkpoint=checkpoint, + on_encode=convert.encode_reporter(handle, 0.85, 0.9)) except (convert._Cancel, EngineCancelled): partial.unlink(missing_ok=True) raise diff --git a/backend/sidecar.py b/backend/sidecar.py index 49fb2cf..7ec8ae3 100644 --- a/backend/sidecar.py +++ b/backend/sidecar.py @@ -28,16 +28,38 @@ def _watch_parent_and_exit() -> None: shut down, so the backend can never be orphaned (the Rust-side kill-on-exit only covers the graceful path). When run standalone from a terminal, stdin is a TTY and this blocks harmlessly forever. + + NOT on Windows: there a read left pending on the stdin pipe stalls loading + scipy's OpenBLAS DLL in any other thread, forever — so the first analysis + hung the packaged app (dev runs no watcher). Measured 2026-10-12 with plain + Python, through the CRT and through kernel32.ReadFile alike. Windows waits + on the parent PROCESS instead, which also covers a crash. """ - try: - while sys.stdin.buffer.read(1): + if sys.platform == "win32": + _wait_for_parent_process() + else: + try: + while sys.stdin.buffer.read(1): + pass + except Exception: pass - except Exception: - pass _release_remote() os._exit(0) +def _wait_for_parent_process() -> None: + """Block until the process that started us exits (Windows only).""" + import ctypes + + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.OpenProcess.restype = ctypes.c_void_p + kernel32.WaitForSingleObject.argtypes = (ctypes.c_void_p, ctypes.c_uint32) + synchronize, infinite = 0x00100000, 0xFFFFFFFF + handle = kernel32.OpenProcess(synchronize, False, os.getppid()) + if handle: # None: the parent is already gone + kernel32.WaitForSingleObject(handle, infinite) + + def _release_remote() -> None: """Hand back a remote library's session on the way out, so the next computer opens it at once instead of waiting out the lease (or being asked diff --git a/backend/test_folders.py b/backend/test_folders.py index 4672e3f..ee8d443 100644 --- a/backend/test_folders.py +++ b/backend/test_folders.py @@ -197,6 +197,82 @@ with TestClient(main.app, raise_server_exceptions=False) as c: c.post("/api/folder/add/preview", json={"track_ids": ["/etc/passwd"], "mode": "reference"}).status_code == 404) + print("== a drop onto the window: folders all the way down, files as themselves ==") + drop = Path(tempfile.mkdtemp()) / "Dropped" + d_a = flac(drop / "Album" / "a.flac", title="Dropped A") + d_b = flac(drop / "Album" / "CD2" / "b.flac") + (drop / "Album" / "cover.jpg").write_bytes(b"not audio") + flac(drop / "Album" / ".cache" / "h.flac") + single = flac(drop / "Loose" / "single.flac", title="Single") + sibling = flac(drop / "Loose" / "sibling.flac") + (drop / "Loose" / "readme.txt").write_text("not audio") + r = c.post("/api/folder/dropped", json={"paths": [ + str(drop / "Album"), str(single), str(drop / "Loose" / "readme.txt"), + str(drop / "gone.flac"), str(single), str(d_a), + ]}) + check("answers 200", r.status_code == 200, r.text[:300]) + body = r.json() + ids = [t["id"] for t in body["tracks"]] + check("the folder's audio, subfolders included, then the file — each once", + ids == [str(d_a), str(d_b), str(single)], str(ids)) + check("a hidden folder inside is left out", str(drop / "Album" / ".cache" / "h.flac") not in ids) + check("a dropped non-audio file and a missing one are counted as skipped", + body["skipped"] == 2, str(body["skipped"])) + check("non-audio INSIDE a dropped folder is not counted", body["skipped"] == 2) + check("tags are read", body["tracks"][0]["title"] == "Dropped A") + check("not truncated", body["truncated"] is False) + check("a dropped file streams", + c.get("/api/folder/tracks/audio", params={"track_id": str(single)}).status_code == 200) + check("so does one found inside a dropped folder", + c.get("/api/folder/tracks/audio", params={"track_id": str(d_b)}).status_code == 200) + check("but not its undropped sibling", + c.get("/api/folder/tracks/audio", params={"track_id": str(sibling)}).status_code == 404) + listed = [t["id"] for t in c.get("/api/folder/tracks", params={"path": str(drop / "Loose")}).json()["tracks"]] + check("browsing that folder afterwards still lists ALL of it", + listed == [str(sibling), str(single)], str(listed)) + r = c.post("/api/folder/dropped", json={"paths": [str(drop / "Loose" / "readme.txt")]}) + check("a non-audio file is never made streamable", + r.json()["tracks"] == [] and c.get("/api/folder/tracks/audio", params={ + "track_id": str(drop / "Loose" / "readme.txt")}).status_code == 404) + capped = main.FOLDERS.dropped([str(drop / "Album")], main._formats(), limit=1) + check("past the cap the rest are left out, and it says so", + len(capped.tracks) == 1 and capped.truncated) + + body = c.post("/api/folder/dropped", json={"paths": [str(one)]}).json() + check("a dropped file the collection holds IS its collection track", + [t["id"] for t in body["tracks"]] == [added] and body["files"] == {added: str(one)}, + str(body)) + + req = {"track_ids": [str(d_b)], "mode": "copy", "destination": str(drop / "Album")} + p = c.post("/api/folder/add/preview", json=req).json() + check("copying into the folder they are already in is flagged", p.get("in_destination") == 1, str(p)) + req["destination"] = str(Path(tempfile.mkdtemp())) + p = c.post("/api/folder/add/preview", json=req).json() + check("…and not elsewhere", p.get("in_destination") == 0, str(p)) + + real_drives = main.places.drives + main.places.drives = lambda: [ + {"name": "Computer", "path": drop.anchor, "kind": "local"}, + {"name": "Stick", "path": str(drop / "Album"), "kind": "external"}, + ] + try: + req = {"track_ids": [str(d_a), str(single)], "mode": "reference"} + p = c.post("/api/folder/add/preview", json=req).json() + check("the external-drive warning counts files per drive, not by the first", + p["removable"] is True and p["removable_count"] == 1 and p["removable_drives"] == ["Stick"], + str(p)) + p = c.post("/api/folder/add/preview", json={"track_ids": [str(single), str(d_a)], + "mode": "reference"}).json() + check("…whichever file comes first", p["removable_count"] == 1, str(p)) + finally: + main.places.drives = real_drives + + n = len(a.tracks) + job = wait(c, c.post("/api/folder/add", json={"track_ids": [str(d_a), str(single)], + "mode": "reference"}).json()) + check("dropped files are added like browsed ones", job["state"] == "done" and len(a.tracks) == n + 2, + str(job)) + print("== Rekordbox: the same route adds to a master.db ==") from konduktor.adapters.rekordbox import discovery as rb_discovery diff --git a/backend/test_stem_file.py b/backend/test_stem_file.py index c142641..dddee8f 100644 --- a/backend/test_stem_file.py +++ b/backend/test_stem_file.py @@ -262,11 +262,71 @@ def stop_in_encode(): raise Stop() +def encoder_threads(): + import threading + + return [t.name for t in threading.enumerate() if t.name.startswith("stem-encode-")] + + try: sf.build(MP3, tmp / "cancelled.partial", fake_separate, encoder="aac", checkpoint=stop_in_encode) check("a checkpoint that raises stops the build", False, "it finished") except Stop: check("a checkpoint that raises stops the build", True) +check("…and no encoder thread outlives it", not encoder_threads(), str(encoder_threads())) + +print("== 6. the encode runs on one thread per stream ==") + + +def encode_single_threaded(fp, tracks, *, bit_rate, encoder): + """The encode as it was before it was threaded: the reference for the bytes.""" + tb = fractions.Fraction(1, SR) + c = av.open(fp, "w", format="ipod") + try: + streams = [] + for k in range(len(tracks)): + s = c.add_stream(encoder, rate=SR, layout="stereo") + s.bit_rate = bit_rate + if k: + s.disposition = 0 + streams.append(s) + for offset in range(0, tracks[0].shape[1], sf.FRAME): + for s, x in zip(streams, tracks): + f = av.AudioFrame.from_ndarray(np.ascontiguousarray(x[:, offset:offset + sf.FRAME]), + format="fltp", layout="stereo") + f.sample_rate, f.pts, f.time_base = SR, offset, tb + for p in s.encode(f): + c.mux(p) + for s in streams: + for p in s.encode(None): + c.mux(p) + finally: + c.close() + + +source = sf.decode(MP3) +# A length that is not a whole number of frames, and stems that differ from the mix. +five = [np.ascontiguousarray(t[:, :-333]) for t in (source.pcm, *fake_separate(source.pcm))] +for enc in encoders: + ref, par = tmp / f"ref.{enc}.m4a", tmp / f"par.{enc}.m4a" + with open(ref, "wb") as fp: + encode_single_threaded(fp, five, bit_rate=320_000, encoder=enc) + seen = [] + with open(par, "wb") as fp: + sf._encode(fp, five, bit_rate=320_000, encoder=enc, checkpoint=None, progress=seen.append) + check(f"{enc}: the threaded encode is byte-identical to the single-threaded one", + ref.read_bytes() == par.read_bytes(), f"{ref.stat().st_size} vs {par.stat().st_size} bytes") + check(f"{enc}: progress runs 0 -> 1, never backwards", + len(seen) >= 3 and seen[0] == 0 and seen[-1] == 1.0 and seen == sorted(seen), str(seen)) + +try: + with open(tmp / "broken.m4a", "wb") as fp: + # A mono array in a stereo stream: that stream's thread fails on its first frame. + sf._encode(fp, [five[0], five[1][:1], *five[2:]], bit_rate=320_000, encoder="aac", checkpoint=None) + check("a failing encoder thread fails the encode", False, "it finished") +except Exception as ex: # noqa: BLE001 + check("a failing encoder thread fails the encode, with its own error", not isinstance(ex, Stop), repr(ex)) +check("…and no encoder thread outlives it", not encoder_threads(), str(encoder_threads())) print("\nRESULT:", "FAILED" if failed else "ALL PASSED") sys.exit(1 if failed else 0) diff --git a/build.ps1 b/build.ps1 new file mode 100644 index 0000000..d061296 --- /dev/null +++ b/build.ps1 @@ -0,0 +1,69 @@ +# Build the Konduktor desktop app on Windows: freeze + stage the backend sidecar, +# then build the Tauri installers. First run? See one-time setup in +# BUILDING-WINDOWS.md (the backend venv with requirements-build.txt, and +# `npm install`). +# +# .\build.ps1 # sidecar + app (release installers) +# .\build.ps1 -SkipSidecar # frontend-only change: reuse the staged sidecar +# .\build.ps1 --debug # anything else is passed on to `tauri build` +# (if scripts are blocked: powershell -ExecutionPolicy Bypass -File .\build.ps1) +param([switch]$SkipSidecar) +$ErrorActionPreference = "Stop" +$Root = $PSScriptRoot +$TauriArgs = $args + +$Py = Join-Path $Root "backend\.venv\Scripts\python.exe" +if (-not (Test-Path $Py)) { throw "No backend venv at backend\.venv - see BUILDING-WINDOWS.md for setup." } +if (-not (Test-Path (Join-Path $Root "frontend\node_modules"))) { throw "No frontend\node_modules - run ``npm install`` in frontend first." } +$Staged = Join-Path $Root "frontend\src-tauri\binaries\konduktor-sidecar\konduktor-sidecar.exe" + +# rustup puts cargo in %USERPROFILE%\.cargo\bin and adds it to PATH only for +# terminals opened AFTER the install - so find it there before giving up, rather +# than failing ten minutes in, after the sidecar build. +if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) { + $CargoBin = Join-Path $env:USERPROFILE ".cargo\bin" + if (-not (Test-Path (Join-Path $CargoBin "cargo.exe"))) { throw "No Rust toolchain (cargo) - install it from https://rustup.rs, see BUILDING-WINDOWS.md." } + $env:PATH = "$CargoBin;$env:PATH" +} + +$Started = Get-Date +# build_sidecar.ps1 changes directory itself, and a location change outlives the +# script it was made in - so put ours back whatever happens. +Push-Location $Root +try { + if ($SkipSidecar) { + if (-not (Test-Path $Staged)) { throw "No staged sidecar to reuse - run without -SkipSidecar first." } + Write-Host "==> Reusing the staged sidecar (-SkipSidecar)" + } + else { + Write-Host "==> 1/2 Freezing the backend sidecar" + & (Join-Path $Root "backend\build_sidecar.ps1") + } + + Write-Host "" + Write-Host "==> 2/2 Building the app (tauri build $TauriArgs)" + Set-Location (Join-Path $Root "frontend") + # npx is a .cmd and cargo reports progress on stderr: relax "Stop" for the + # call (as build_sidecar.ps1 does for PyInstaller) and judge by exit code. + $ErrorActionPreference = "Continue" + & npx tauri build @TauriArgs + $code = $LASTEXITCODE + $ErrorActionPreference = "Stop" + if ($code -ne 0) { throw "tauri build failed ($code)" } +} +finally { + Pop-Location +} + +# List what this run produced (release or --debug profile). +$Bundles = Join-Path $Root "frontend\src-tauri\target\*\bundle" +$Built = Get-ChildItem -Path "$Bundles\nsis\*-setup.exe", "$Bundles\msi\*.msi" -File -ErrorAction SilentlyContinue | + Where-Object { $_.LastWriteTime -ge $Started } +Write-Host "" +if ($Built) { + Write-Host "Installers:" + $Built | ForEach-Object { Write-Host " $($_.FullName)" } +} +else { + Write-Host "Done (no installer bundled - see frontend\src-tauri\target\)." +} diff --git a/dev.ps1 b/dev.ps1 new file mode 100644 index 0000000..eaee385 --- /dev/null +++ b/dev.ps1 @@ -0,0 +1,42 @@ +# Start both Konduktor servers (backend + frontend) together - the Windows +# counterpart of dev.sh. Ctrl-C stops both. First run? See one-time setup in +# BUILDING-WINDOWS.md (the backend venv and `npm install`). +# +# .\dev.ps1 +# (if scripts are blocked: powershell -ExecutionPolicy Bypass -File .\dev.ps1) +$ErrorActionPreference = "Stop" +$Root = $PSScriptRoot + +$Py = Join-Path $Root "backend\.venv\Scripts\python.exe" +if (-not (Test-Path $Py)) { throw "No backend venv at backend\.venv - see BUILDING-WINDOWS.md for setup." } +# Vite through node, not `npm run dev`: npm is a .cmd batch file, and Ctrl-C in a +# shared console makes cmd ask "Terminate batch job (Y/N)?" instead of exiting. +$Vite = Join-Path $Root "frontend\node_modules\vite\bin\vite.js" +if (-not (Test-Path $Vite)) { throw "No frontend\node_modules - run ``npm install`` in frontend first." } + +# Backend (FastAPI on :8000) +$Backend = Start-Process -FilePath $Py -NoNewWindow -PassThru ` + -ArgumentList "-m", "uvicorn", "konduktor.main:app", "--reload", "--port", "8000", "--app-dir", "`"$Root\backend`"" + +# Frontend (Vite on :5173, proxies /api -> :8000) +$Frontend = Start-Process -FilePath "node" -NoNewWindow -PassThru ` + -WorkingDirectory (Join-Path $Root "frontend") -ArgumentList "`"$Vite`"" + +Write-Host "" +Write-Host " Konduktor is starting..." +Write-Host " -> App: http://localhost:5173" +Write-Host " -> API docs: http://localhost:8000/docs" +Write-Host " (Ctrl-C to stop both)" +Write-Host "" + +try { + # If either one dies, stop the other rather than leave half a dev setup. + while (-not $Backend.HasExited -and -not $Frontend.HasExited) { Start-Sleep -Milliseconds 500 } +} +finally { + # Kill the whole tree: uvicorn --reload runs the server in a child process, + # which would otherwise keep :8000 bound after the reloader has gone. + foreach ($p in $Backend, $Frontend) { + if ($p -and -not $p.HasExited) { & taskkill /PID $p.Id /T /F 2>&1 | Out-Null } + } +} diff --git a/frontend/package.json b/frontend/package.json index 721b709..4e9fe5a 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "frontend", "private": true, - "version": "0.2.6", + "version": "0.2.7", "type": "module", "scripts": { "dev": "vite", diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index c630aec..616d368 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,11 +1,13 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { createPortal } from 'react-dom' import { useQuery, useQueryClient } from '@tanstack/react-query' import type { ColumnSizingState, SortingState, VisibilityState } from '@tanstack/react-table' import { CapabilitiesContext, slotLabeller } from './lib/capabilities' -import { removalNote, writeHint } from './lib/platformCopy' +import { readOnlyNotice, removalNote, writeHint } from './lib/platformCopy' import { invalidateTrackLists } from './lib/trackQueries' import { addTracksToPlaylist } from './lib/addTracks' -import { useDropTarget } from './lib/drag' +import { useDragPayload, useDropTarget } from './lib/drag' +import { useNativeFileDrop } from './lib/fileDrop' import { api, type AnalyzeOptions, type AnalyzeResult, type CueBatchResult, type AutoCueSlot, type PlaylistNode, type StemBatchResult, type Track, type TrackOrigin } from './api' import { confirmDiscardUnsaved } from './lib/unsaved' import { askConfirm } from './lib/confirm' @@ -30,7 +32,7 @@ import { RelocateDialog } from './components/RelocateDialog' import { HistoryPanel } from './components/HistoryPanel' import { PrepStrip } from './components/PrepStrip' import { ImportDialog } from './components/ImportDialog' -import { AddFilesDialog, type AddTarget } from './components/AddFilesDialog' +import { AddFilesDialog, type AddTarget, type ForeignOrigin } from './components/AddFilesDialog' import { ConvertStemsDialog } from './components/ConvertStemsDialog' import { StemReportDialog } from './components/StemReportDialog' import { SetPositionDialog } from './components/SetPositionDialog' @@ -84,8 +86,12 @@ export default function App() { // The browsed folder's rows that ARE collection tracks: collection id → the // file's folder id. A ref, for the callbacks below that outlive a render. const folderFilesRef = useRef>({}) - // Browsed files being added to the collection (and maybe a playlist/export). - const [adding, setAdding] = useState<{ ids: string[]; target: AddTarget | null } | null>(null) + // Browsed (or dropped) files being added to the collection (and maybe a + // playlist/export). `note` says what a drop left out. + const [adding, setAdding] = useState<{ ids: string[]; target: AddTarget | null; note?: string | null } | null>(null) + // How many dropped items are being read (a dropped folder is searched all + // the way down, which can take a while): shown until the dialog opens. + const [readingDrop, setReadingDrop] = useState(0) const [playRequest, setPlayRequest] = useState(0) // bump → deck loads & auto-plays const [importing, setImporting] = useState(false) // Device tracks dropped on a collection playlist / export: Import, with @@ -377,9 +383,78 @@ export default function App() { // export: they are not in the collection yet, so the drop opens the dialog // that adds them — with that target filled in, and copy-vs-reference still // asked (decided 2026-10-06). + // Files dragged in from Finder / Explorer (lib/fileDrop.ts). What is in them + // is read first — folders all the way down — and then they go where a + // browsed folder's files go: the add dialog, copy-vs-reference asked. + const readDrop = useCallback( + async (paths: string[]) => { + setReadingDrop(paths.length) + try { + return await api.folderDropped(paths) + } catch (e) { + onError((e as Error).message) + return null + } finally { + setReadingDrop(0) + } + }, + [onError], + ) + const dropFiles = useCallback( + async (paths: string[], target: AddTarget | null) => { + const r = await readDrop(paths) + if (!r) return + if (!r.tracks.length) { + onError( + paths.length === 1 && r.skipped + ? 'That is not an audio file this library can hold.' + : 'No audio files this library can hold were found there.', + ) + return + } + const notes: string[] = [] + if (r.skipped) + notes.push( + r.skipped === 1 + ? '1 dropped item is not audio this library can hold and was left out.' + : `${r.skipped} dropped items are not audio this library can hold and were left out.`, + ) + if (r.truncated) notes.push(`Only the first ${r.tracks.length.toLocaleString()} files are included.`) + // Files the collection holds are its tracks already: as with a folder's + // rows, nothing to add first — straight into the target, if there is one. + const held = r.tracks.filter((t) => r.files[t.id]).map((t) => t.id) + if (held.length === r.tracks.length) { + if (target?.kind === 'playlist') void addToPlaylist(target.id, held) + else if (target) void addToExport(target.id, held) + else + notify( + 'success', + held.length === 1 ? 'Already in your collection' : `All ${held.length} are already in your collection`, + ) + return + } + setAdding({ ids: r.tracks.map((t) => r.files[t.id] ?? t.id), target, note: notes.join(' ') || null }) + }, + [readDrop, addToPlaylist, addToExport, notify, onError], + ) + // One dropped audio file on the deck: loaded to listen to, added to nothing. + const loadDropped = useCallback( + async (path: string) => { + const r = await readDrop([path]) + if (!r) return + const t = r.tracks[0] + if (!t) { + onError('That is not an audio file this library can hold.') + return + } + loadTrack(t, r.files[t.id] ? 'collection' : 'folder') + }, + [readDrop, loadTrack, onError], + ) const addForeign = useCallback( - (origin: TrackOrigin, ids: string[], target: AddTarget) => { - if (origin === 'folder') { + (origin: ForeignOrigin, ids: string[], target: AddTarget) => { + if (origin === 'dropped') void dropFiles(ids, target) + else if (origin === 'folder') { const files = folderFilesRef.current // Rows that are all collection tracks already: nothing to add first. if (ids.every((id) => files[id])) { @@ -388,13 +463,44 @@ export default function App() { } else setAdding({ ids: ids.map((id) => files[id] ?? id), target }) } else if (origin === 'device') setImportDrop({ ids, target }) }, - [addToPlaylist, addToExport], + [addToPlaylist, addToExport, dropFiles], ) + const audioFormats = capabilities.data?.tracks.audio_formats + const isAudioPath = (path: string) => + path.lastIndexOf('.') > 0 && !!audioFormats?.includes(path.slice(path.lastIndexOf('.')).toLowerCase()) const [deckDropRef, deckOver] = useDropTarget({ - hint: (p) => (p.kind === 'tracks' ? true : null), + hint: (p) => + p.kind === 'tracks' || (p.kind === 'files' && p.paths.length === 1 && isAudioPath(p.paths[0])) ? true : null, label: (p) => (p.kind === 'tracks' && p.ids.length > 1 ? `Load “${p.lead.title || 'Untitled'}” into the deck` : 'Load into the deck'), - onDrop: (p) => p.kind === 'tracks' && loadTrack(p.lead, p.origin), + onDrop: (p) => { + if (p.kind === 'tracks') loadTrack(p.lead, p.origin) + else if (p.kind === 'files') void loadDropped(p.paths[0]) + }, }) + // Files dropped anywhere no other target takes them: the collection. A + // library that cannot add tracks still takes the drop, to say why not — + // silently ignoring it would read as the feature being broken. + const canAddFiles = (capabilities.data?.writable ?? false) && !!capabilities.data?.tracks.addable + const cannotAddFiles = + capabilities.data && !capabilities.data.writable + ? (readOnlyNotice(capabilities.data) ?? 'This library is read-only.') + : 'Tracks cannot be added to this library.' + const [rootDropRef, rootOver] = useDropTarget({ + hint: (p) => (p.kind === 'files' ? true : null), + label: () => (canAddFiles ? 'Add to your collection…' : null), + onDrop: (p) => { + if (p.kind !== 'files') return + if (canAddFiles) void dropFiles(p.paths, null) + else notify('error', cannotAddFiles) + }, + }) + const draggingFiles = useDragPayload()?.kind === 'files' + useNativeFileDrop(loaded && !forcePicker, () => + notify( + 'warning', + 'Dropping files works in the Konduktor app, not in a browser (it cannot tell the page where a file is). Browse to it under Files in the sidebar instead.', + ), + ) const removeFromExport = useCallback( async (id: string, ids: string[]) => { try { @@ -1066,8 +1172,26 @@ export default function App() { {/* Floating glass panels with gaps between them: the ambient backdrop (main.tsx) shows through the gutters as well as through the glass. */} -
+
setToast(null)} /> + {draggingFiles && rootOver && + createPortal( +
+
+
+ + {canAddFiles ? 'Drop to add to your collection' : cannotAddFiles} +
+
, + document.body, + )} + {readingDrop > 0 && + createPortal( +
+ Looking for audio in {readingDrop === 1 ? 'the dropped item' : `${readingDrop} dropped items`}… +
, + document.body, + )} {menu && ( setAdding(null)} onDone={(msg) => { setAdding(null) diff --git a/frontend/src/api.ts b/frontend/src/api.ts index e58ce42..38f8319 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -514,7 +514,27 @@ export interface FolderAddRequest { } export interface FolderAddPreview extends ImportPreview { + /** Some of the files to add are on an external drive. */ removable: boolean + /** How many, and on which drives — per FILE, since a drop can mix drives. */ + removable_count?: number + removable_drives?: string[] + /** Copy mode: files already inside the import folder (copying makes a + * second copy beside them). */ + in_destination?: number +} + +/** What files dropped onto the window from the OS resolved to: the audio in + * them (folders searched all the way down), listed as a folder lists its + * files — a file the collection holds is its collection track. */ +export interface DroppedFiles { + tracks: Track[] + /** Collection id → the file's folder id (= its path), for held rows. */ + files: Record + /** Dropped files that are not audio this library can hold, or are gone. */ + skipped: number + /** Too many files: only the first 20,000 are included. */ + truncated: boolean } export type JobState = 'running' | 'done' | 'failed' | 'cancelled' @@ -1177,6 +1197,7 @@ export const api = { folderAddPreview: (body: FolderAddRequest) => send('POST', '/api/folder/add/preview', body), folderAdd: (body: FolderAddRequest) => send('POST', '/api/folder/add', body), + folderDropped: (paths: string[]) => send('POST', '/api/folder/dropped', { paths }), // ---- import ---- importPreview: (body: ImportRequest) => send('POST', '/api/import/preview', body), /** Starts the job and returns immediately — poll `job()` for progress. */ diff --git a/frontend/src/components/AddFilesDialog.tsx b/frontend/src/components/AddFilesDialog.tsx index d53349d..f707bdb 100644 --- a/frontend/src/components/AddFilesDialog.tsx +++ b/frontend/src/components/AddFilesDialog.tsx @@ -1,7 +1,7 @@ import { createPortal } from 'react-dom' import { useEffect, useRef, useState, type ReactNode } from 'react' import { useQuery, useQueryClient } from '@tanstack/react-query' -import { api, isServerPath, type FolderAddPreview, type FolderAddRequest, type JobStatus } from '../api' +import { api, isServerPath, type FolderAddPreview, type FolderAddRequest, type JobStatus, type TrackOrigin } from '../api' import { useCaps } from '../lib/capabilities' import { placedAudioSummary } from '../lib/platformCopy' import { FolderPicker } from './FolderPicker' @@ -25,6 +25,10 @@ import { FolderPicker } from './FolderPicker' * library can reach them, so they are added in place, uploaded nowhere and * nothing asked (decided 2026-10-10). * + * Files dropped onto the window from the OS (`lib/fileDrop.ts`) arrive here + * too, so a drop asks exactly what the sidebar's Add to Collection asks. A + * drop can mix drives, so the external-drive warning counts files per drive. + * * A playlist or export target still needs the files in the collection first — * both hold collection track ids — so the dialog says so rather than doing it * silently. Files the collection already holds are not added again, but still @@ -45,15 +49,32 @@ export interface AddTarget { name: string } +/** Where tracks headed for the collection come from: another library's or a + * folder's track ids, or — `dropped` — paths dragged in from the OS. */ +export type ForeignOrigin = TrackOrigin | 'dropped' + interface Props { trackIds: string[] target: AddTarget | null + /** A line about what was left out before the dialog (a drop's non-audio files). */ + note?: string | null onClose: () => void onDone: (msg: string) => void onError: (msg: string) => void } -export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: Props) { +/** The leave-in-place warning, per drive: a drop can mix the computer's own + * disk with a stick, and only the stick's files go missing on unplug. */ +function removableWarning(p: FolderAddPreview, newCount: number): string { + const count = p.removable_count ?? newCount + const drives = p.removable_drives ?? [] + const where = drives.length === 1 ? `${drives[0]}, an external drive` : 'external drives' + const what = count >= newCount ? 'These files are' : `${count} of these files are` + const unplugged = drives.length === 1 ? 'it is' : 'they are' + return `${what} on ${where}. They will go missing from your collection whenever ${unplugged} unplugged.` +} + +export function AddFilesDialog({ trackIds, target, note, onClose, onDone, onError }: Props) { const qc = useQueryClient() // The LIBRARY's capabilities (this dialog is mounted outside the browsed // view's swapped context). A library that places its own audio — a stick — @@ -177,9 +198,12 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P const newCount = p?.importable ?? 0 const shown = places ? 'placed' : mode const libraryName = places ? caps.save.app_name : 'your collection' + // Every file is held already: nothing is copied or referenced, so there is + // nothing to ask — only the target to fill. + const nothingNew = !!p && newCount === 0 && p.existing.length > 0 const canAdd = - !starting && shown !== null && !!p && (newCount > 0 || (!!target && p.existing.length > 0)) && - p.enough_space !== false + !starting && (shown !== null || nothingNew) && !!p && + (newCount > 0 || (!!target && p.existing.length > 0)) && p.enough_space !== false const title = target ? `Add ${n} track${n === 1 ? '' : 's'} to ${target.name}` @@ -265,7 +289,9 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
)} - {!places && !uploads && !onServer && ( + {note &&
{note}
} + + {!places && !uploads && !onServer && !nothingNew && (
{option( 'copy', @@ -296,9 +322,14 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P )} {mode === 'reference' && p?.removable && ( +
{removableWarning(p, newCount)}
+ )} + + {mode === 'copy' && !!p?.in_destination && (
- These files are on an external drive. They will go missing from your - collection whenever the drive is unplugged. + {p.in_destination === newCount ? 'These files are' : `${p.in_destination} of these files are`}{' '} + already in your import folder. Copying makes a second copy beside{' '} + {p.in_destination === 1 ? 'it' : 'them'}.
)} diff --git a/frontend/src/components/ExportsSection.tsx b/frontend/src/components/ExportsSection.tsx index ff32fc3..fe9a0d7 100644 --- a/frontend/src/components/ExportsSection.tsx +++ b/frontend/src/components/ExportsSection.tsx @@ -1,7 +1,7 @@ import { useState } from 'react' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' -import { api, type ExportSet, type TrackOrigin } from '../api' -import type { AddTarget } from './AddFilesDialog' +import { api, type ExportSet } from '../api' +import type { AddTarget, ForeignOrigin } from './AddFilesDialog' import { useCaps } from '../lib/capabilities' import { ExportDialog } from './ExportDialog' import { ExportRunDialog } from './ExportRunDialog' @@ -31,7 +31,7 @@ interface Props { onSelect: (s: Source) => void onDone: (msg: string) => void onError: (msg: string) => void - onAddForeign: (origin: TrackOrigin, ids: string[], target: AddTarget) => void + onAddForeign: (origin: ForeignOrigin, ids: string[], target: AddTarget) => void } export function ExportsSection({ source, onSelect, onDone, onError, onAddForeign }: Props) { @@ -151,7 +151,7 @@ function ExportRow({ onDelete: () => void onDone: (msg: string) => void onError: (msg: string) => void - onAddForeign: (origin: TrackOrigin, ids: string[], target: AddTarget) => void + onAddForeign: (origin: ForeignOrigin, ids: string[], target: AddTarget) => void }) { const qc = useQueryClient() // The COLLECTION's capabilities (the sidebar sits outside the browsed view's @@ -196,14 +196,20 @@ function ExportRow({ const accepts = (p: DragPayload) => p.kind === 'tracks' ? p.origin === 'collection' || (caps.writable && caps.tracks.addable) - : playlistIdsUnder(p.node).length > 0 + : p.kind === 'files' + ? caps.writable && caps.tracks.addable + : playlistIdsUnder(p.node).length > 0 const [dropRef, over] = useDropTarget({ hint: (p) => (accepts(p) ? true : null), label: (p) => p.kind === 'tracks' && p.origin === 'device' ? `Import into export ${set.name}…` - : `Add to export ${set.name}${p.kind === 'tracks' && p.origin === 'folder' ? '…' : ''}`, + : `Add to export ${set.name}${(p.kind === 'tracks' && p.origin === 'folder') || p.kind === 'files' ? '…' : ''}`, onDrop: async (p) => { + if (p.kind === 'files') { + onAddForeign('dropped', p.paths, { kind: 'export', id: set.id, name: set.name }) + return + } if (p.kind === 'tracks' && p.origin !== 'collection') { onAddForeign(p.origin, p.ids, { kind: 'export', id: set.id, name: set.name }) return diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx index 0287718..f4abfee 100644 --- a/frontend/src/components/Sidebar.tsx +++ b/frontend/src/components/Sidebar.tsx @@ -1,7 +1,7 @@ import { useEffect, useRef, useState } from 'react' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' -import { api, type PlaylistKind, type PlaylistNode, type TrackOrigin } from '../api' -import type { AddTarget } from './AddFilesDialog' +import { api, type PlaylistKind, type PlaylistNode } from '../api' +import type { AddTarget, ForeignOrigin } from './AddFilesDialog' import { useCaps } from '../lib/capabilities' import { SaveBar } from './SaveBar' import { confirmDiscardUnsaved } from '../lib/unsaved' @@ -14,7 +14,7 @@ import { ContextMenu, type MenuItem } from './ContextMenu' import { Icon, type IconName } from '../lib/icons' import { PlatformIcon } from '../lib/platformIcons' import { addTracksToPlaylist } from '../lib/addTracks' -import { useDragPayload, usePressToDrag, useDropTarget, type DragPayload } from '../lib/drag' +import { useDragPayload, usePressToDrag, useDropTarget, type DragPayload, type TracksOrFiles } from '../lib/drag' import { findNode, idsAfter, nodeIdsUnder, playlistIdsUnder } from '../lib/playlistTree' /** @@ -55,9 +55,10 @@ interface Props { /** Open a drive's library as THE library (Devices' "Open for editing…"). */ onOpenLibrary: (path: string) => void onDone: (msg: string) => void - /** Tracks not in the collection yet (a device's, a folder's) dropped on a - * playlist or export: open the dialog that adds them, target filled in. */ - onAddForeign: (origin: TrackOrigin, ids: string[], target: AddTarget) => void + /** Tracks not in the collection yet (a device's, a folder's — or files + * dropped from the OS, as paths) dropped on a playlist or export: open the + * dialog that adds them, target filled in. */ + onAddForeign: (origin: ForeignOrigin, ids: string[], target: AddTarget) => void onOpenPathMapping: () => void /** After unsaved edits were discarded (SaveBar). */ onDiscarded?: () => void @@ -111,11 +112,11 @@ interface RowActions { onPickExport: (e: React.MouseEvent, node: PlaylistNode) => void onCommitDraft: (name: string) => void onCancelDraft: () => void - /** Whether a drag of tracks may drop on this playlist. */ - acceptsTracks: (node: PlaylistNode, p: Extract) => boolean + /** Whether a drag of tracks (or of files from the OS) may drop on this playlist. */ + acceptsTracks: (node: PlaylistNode, p: TracksOrFiles) => boolean /** Tracks dropped on a playlist; `alt` (Option) moves them out of the * playlist they came from. */ - onDropTracks: (node: PlaylistNode, p: Extract, alt: boolean) => void + onDropTracks: (node: PlaylistNode, p: TracksOrFiles, alt: boolean) => void /** Whether a node may be dragged elsewhere in the tree. */ canMove: (node: PlaylistNode) => boolean /** A node dropped in the tree: `index` among `parentId`'s children, @@ -265,14 +266,14 @@ function NodeRow({ label: (p, h, at) => { if (h.zone === 'tracks') { if (p.kind === 'tracks' && p.origin === 'device') return `Import into ${node.name}…` - if (p.kind === 'tracks' && p.origin === 'folder') return `Add to ${node.name}…` + if ((p.kind === 'tracks' && p.origin === 'folder') || p.kind === 'files') return `Add to ${node.name}…` return `${moves(p, at.alt) ? 'Move' : 'Add'} to ${node.name}` } if (h.zone === 'peek') return null return h.zone === 'into' || h.zone === 'first' ? `Move into ${node.name}` : `Move ${h.zone} ${node.name}` }, onDrop: (p, h, at) => { - if (p.kind === 'tracks') { + if (p.kind !== 'node') { if (h.zone === 'tracks') actions.onDropTracks(node, p, at.alt) } else if ('parentId' in h) { actions.onMoveNode(p.node, h.parentId, h.index, h.zone === 'into' && !expanded ? node : null) @@ -664,7 +665,7 @@ export function Sidebar({ acceptsTracks: (node, p) => caps.writable && node.can_add_tracks && - (p.origin === 'collection' ? p.fromPlaylist !== node.id : caps.tracks.addable), + (p.kind === 'tracks' && p.origin === 'collection' ? p.fromPlaylist !== node.id : caps.tracks.addable), canMove: (node) => caps.writable && node.can_move, onMoveNode: async (node, parentId, index, into) => { try { @@ -678,6 +679,10 @@ export function Sidebar({ } }, onDropTracks: async (node, p, alt) => { + if (p.kind === 'files') { + onAddForeign('dropped', p.paths, { kind: 'playlist', id: node.id, name: node.name }) + return + } if (p.origin !== 'collection') { onAddForeign(p.origin, p.ids, { kind: 'playlist', id: node.id, name: node.name }) return diff --git a/frontend/src/lib/drag.tsx b/frontend/src/lib/drag.tsx index 63fbca4..df0361c 100644 --- a/frontend/src/lib/drag.tsx +++ b/frontend/src/lib/drag.tsx @@ -18,6 +18,11 @@ import { Icon } from './icons' * events for its own file drop on Windows, so HTML5 DnD silently dies in the * packaged app. * + * Files dragged in from Finder / Explorer ride the same store as a `files` + * payload: Tauri reports that drag (with real paths) instead of the webview, + * and `lib/fileDrop.ts` feeds it in through `nativeDragStart` / `Move` / `End`, + * so the same targets light up and the same ghost names what a drop would do. + * * The state lives in a module-level store read through useSyncExternalStore * with narrow selectors, so a pointer move re-renders only the target under it * (and the ghost) — never the table. @@ -39,6 +44,12 @@ export type DragPayload = source: object } | { kind: 'node'; node: PlaylistNode; parentId: string | null } + /** Files and folders from the OS, as absolute paths. Not yet tracks: a + * target hands them to the drop resolver, which reads what is in them. */ + | { kind: 'files'; paths: string[] } + +/** What a playlist or export row takes: track rows, or files from the OS. */ +export type TracksOrFiles = Exclude export interface DropPoint { x: number @@ -117,44 +128,26 @@ function evaluate() { let detach: (() => void) | null = null -/** Start a drag. Call it once the press has moved past the source's threshold. */ -export function beginDrag(payload: DragPayload, at: { x: number; y: number; alt: boolean }) { +/** End the drag in progress, dropping on the target under the pointer if `drop`. */ +function finish(drop: boolean) { + const { payload: p, target, hint, x, y, alt } = state + detach?.() + if (!drop || !p || !target) return + const spec = targets.get(target) + try { + spec?.current.onDrop(p, hint, { x, y, alt }) + } catch (err) { + console.error('drop failed', err) + } +} + +/** Publish a new drag and start edge auto-scroll. Returns what undoes both. */ +function open(payload: DragPayload, at: { x: number; y: number; alt: boolean }): () => void { detach?.() set({ ...IDLE, payload, ...at }) document.documentElement.classList.add('is-dragging') window.getSelection()?.removeAllRanges() - const onMove = (e: PointerEvent) => { - // One notification per move: evaluate() publishes the position with the hint. - state = { ...state, x: e.clientX, y: e.clientY, alt: e.altKey } - evaluate() - } - const finish = (drop: boolean) => { - const { payload: p, target, hint, x, y, alt } = state - detach?.() - if (!drop || !p || !target) return - const spec = targets.get(target) - try { - spec?.current.onDrop(p, hint, { x, y, alt }) - } catch (err) { - console.error('drop failed', err) - } - } - const onUp = () => finish(true) - const onCancel = () => finish(false) - const onKey = (e: KeyboardEvent) => { - if (e.key === 'Escape' && e.type === 'keydown') { - // Before every other Esc handler: cancelling the drag is all Esc does. - e.preventDefault() - e.stopImmediatePropagation() - finish(false) - return - } - if (e.key === 'Alt' && state.alt !== (e.type === 'keydown')) { - set({ alt: e.type === 'keydown' }) - evaluate() - } - } // Hold near the edge of a `data-drag-scroll` element to scroll it. Its // value is the height covered at the top (a sticky header). The edge is // thinner than a row and must be HELD for a moment first: otherwise the @@ -187,6 +180,37 @@ export function beginDrag(payload: DragPayload, at: { x: number; y: number; alt: } raf = requestAnimationFrame(autoScroll) + return () => { + cancelAnimationFrame(raf) + document.documentElement.classList.remove('is-dragging') + set(IDLE) + } +} + +/** Start a drag. Call it once the press has moved past the source's threshold. */ +export function beginDrag(payload: DragPayload, at: { x: number; y: number; alt: boolean }) { + const close = open(payload, at) + + const onMove = (e: PointerEvent) => { + // One notification per move: evaluate() publishes the position with the hint. + state = { ...state, x: e.clientX, y: e.clientY, alt: e.altKey } + evaluate() + } + const onUp = () => finish(true) + const onCancel = () => finish(false) + const onKey = (e: KeyboardEvent) => { + if (e.key === 'Escape' && e.type === 'keydown') { + // Before every other Esc handler: cancelling the drag is all Esc does. + e.preventDefault() + e.stopImmediatePropagation() + finish(false) + return + } + if (e.key === 'Alt' && state.alt !== (e.type === 'keydown')) { + set({ alt: e.type === 'keydown' }) + evaluate() + } + } window.addEventListener('pointermove', onMove) window.addEventListener('pointerup', onUp) window.addEventListener('pointercancel', onCancel) @@ -195,14 +219,12 @@ export function beginDrag(payload: DragPayload, at: { x: number; y: number; alt: window.addEventListener('blur', onCancel) detach = () => { detach = null - cancelAnimationFrame(raf) window.removeEventListener('pointermove', onMove) window.removeEventListener('pointerup', onUp) window.removeEventListener('pointercancel', onCancel) window.removeEventListener('keydown', onKey, true) window.removeEventListener('keyup', onKey, true) window.removeEventListener('blur', onCancel) - document.documentElement.classList.remove('is-dragging') // The pointerup that ended the drag is followed by a click on whatever // is under it; that click is part of the drop, not a click of its own. const swallow = (e: MouseEvent) => { @@ -211,11 +233,34 @@ export function beginDrag(payload: DragPayload, at: { x: number; y: number; alt: } window.addEventListener('click', swallow, true) setTimeout(() => window.removeEventListener('click', swallow, true), 0) - set(IDLE) + close() } evaluate() } +/** A drag the OS owns (files from Finder / Explorer): it enters the window… */ +export function nativeDragStart(payload: DragPayload, at: { x: number; y: number }) { + const close = open(payload, { ...at, alt: false }) + detach = () => { + detach = null + close() + } + evaluate() +} + +/** …moves over it (window coordinates, CSS pixels)… */ +export function nativeDragMove(at: { x: number; y: number }) { + if (!state.payload) return + state = { ...state, ...at } + evaluate() +} + +/** …and is dropped (or leaves the window: `drop` false). */ +export function nativeDragEnd(drop: boolean, at?: { x: number; y: number }) { + if (drop && at) nativeDragMove(at) + finish(drop) +} + /** A pointerdown handler that starts a drag once the press moves 6 px. A plain * click never moves that far, so the element keeps its click; a press on a * field inside it (a rename input) never drags. `make` is asked at the moment @@ -273,6 +318,10 @@ export function useDropTarget(spec: DropSpec): [(el: HTMLElement | null) = function describe(p: DragPayload): { icon: 'music' | 'playlist' | 'folder' | 'smart'; text: string } { if (p.kind === 'node') return { icon: p.node.kind === 'folder' ? 'folder' : p.node.kind === 'smart' ? 'smart' : 'playlist', text: p.node.name } + if (p.kind === 'files') + return p.paths.length === 1 + ? { icon: 'music', text: p.paths[0].split(/[\\/]/).filter(Boolean).pop() ?? p.paths[0] } + : { icon: 'music', text: `${p.paths.length} items` } if (p.ids.length === 1) { const t = p.tracks[0] return { icon: 'music', text: t ? [t.artist, t.title].filter(Boolean).join(' – ') || 'Untitled' : '1 track' } diff --git a/frontend/src/lib/fileDrop.ts b/frontend/src/lib/fileDrop.ts new file mode 100644 index 0000000..6711885 --- /dev/null +++ b/frontend/src/lib/fileDrop.ts @@ -0,0 +1,84 @@ +import { useEffect, useRef } from 'react' +import { nativeDragEnd, nativeDragMove, nativeDragStart } from './drag' + +/** + * Files dragged in from Finder / Explorer, fed into the window's ONE drag + * store (`lib/drag.tsx`) as a `files` payload, so the targets that take track + * rows — playlists, exports, the deck — take files too, and anywhere else is + * "add to the collection" (App's own target). + * + * Tauri only: the shell's webview hands the OS drag to Tauri, which reports it + * with real paths — what adding a file IN PLACE needs. A plain browser gives a + * page `File` objects without paths, so in a browser a file drop is only + * CAUGHT — left alone, the browser navigates to the dropped file and the app + * is gone — and `onBrowserDrop` says why nothing happened. + * + * `enabled` false (no library open yet) and an open dialog both refuse the + * drag at its start, before anything is highlighted. + */ +export function useNativeFileDrop(enabled: boolean, onBrowserDrop: () => void) { + const enabledRef = useRef(enabled) + enabledRef.current = enabled + const onBrowserDropRef = useRef(onBrowserDrop) + onBrowserDropRef.current = onBrowserDrop + + useEffect(() => { + if (!('__TAURI_INTERNALS__' in window)) { + // Only drags carrying files: the app's own drags are pointer events, + // and a text drag into a field must keep working. + const hasFiles = (e: DragEvent) => !!e.dataTransfer?.types.includes('Files') + const over = (e: DragEvent) => { + if (hasFiles(e)) e.preventDefault() + } + const drop = (e: DragEvent) => { + if (!hasFiles(e)) return + e.preventDefault() + onBrowserDropRef.current() + } + window.addEventListener('dragover', over) + window.addEventListener('drop', drop) + return () => { + window.removeEventListener('dragover', over) + window.removeEventListener('drop', drop) + } + } + let unlisten: (() => void) | undefined + let cancelled = false + let active = false + void (async () => { + const { getCurrentWebview } = await import('@tauri-apps/api/webview') + const off = await getCurrentWebview().onDragDropEvent(({ payload }) => { + // Tauri reports PHYSICAL pixels; the page works in CSS pixels. + const scale = window.devicePixelRatio || 1 + const at = 'position' in payload ? { x: payload.position.x / scale, y: payload.position.y / scale } : null + switch (payload.type) { + case 'enter': + active = + enabledRef.current && + payload.paths.length > 0 && + !document.querySelector('[aria-modal="true"]') + if (active && at) nativeDragStart({ kind: 'files', paths: payload.paths }, at) + break + case 'over': + if (active && at) nativeDragMove(at) + break + case 'drop': + if (active) nativeDragEnd(true, at ?? undefined) + active = false + break + case 'leave': + if (active) nativeDragEnd(false) + active = false + break + } + }) + if (cancelled) off() + else unlisten = off + })() + return () => { + cancelled = true + unlisten?.() + if (active) nativeDragEnd(false) + } + }, []) +}