diff --git a/BUILDING-WINDOWS.md b/BUILDING-WINDOWS.md index 549898a..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,62 +39,115 @@ npm install cd .. ``` +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. This is `dev.sh` for Windows. -It runs the Python source, not the frozen sidecar, so it cannot show -desktop-shell behaviour (startup screen, quit prompt, WebView2). For that, use -`npx tauri dev` in `frontend` — but note it still spawns the FROZEN sidecar from -`src-tauri\binaries\`, so backend changes need `build_sidecar.ps1` first. +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 +cd backend +.\.venv\Scripts\python.exe test_save_fidelity.py +``` ## Build +One command does both steps and lists the installers it produced: + ```powershell -# 1) Freeze + stage the backend sidecar (from the activated backend venv) +.\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 -.\.venv\Scripts\Activate.ps1 # if not already active .\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 e202b9e..95d46e8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -934,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 @@ -1378,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/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/main.py b/backend/konduktor/main.py index 9ea0388..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, @@ -2321,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. @@ -2447,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/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/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/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) + } + }, []) +}