Improved file browser

This commit is contained in:
patben8 committed 2026-09-23 11:19:58 +02:00
1 parent 8d11acd783
commit 93ec2ef425
10 files changed
+540 -204

No files matched your search

@@ -14,49 +14,17 @@ app feel broken.
from __future__ import annotations
import logging
import os
import string
import sys
from pathlib import Path
# Where this OS mounts drives is not adapter knowledge — the file browser needs
# the same answer, and two scanners would drift. It grew here because this is
# the platform whose libraries ARE drives; it lives in core now.
from ...core.places import mount_points as _mount_points
from .layout import DriveLayout
log = logging.getLogger(__name__)
def _mount_points() -> list[Path]:
"""Plausible removable-media mount points for this OS."""
out: list[Path] = []
if sys.platform == "darwin":
out.append(Path("/Volumes"))
elif sys.platform.startswith("linux"):
out.extend([Path("/media"), Path("/mnt"), Path("/run/media")])
user = os.environ.get("USER")
if user:
out.append(Path("/media") / user)
out.append(Path("/run/media") / user)
roots: list[Path] = []
for base in out:
try:
if not base.is_dir():
continue
roots.extend(p for p in base.iterdir() if p.is_dir())
except OSError:
continue
if sys.platform == "win32":
# No mount-point directory to list: check the drive letters directly.
for letter in string.ascii_uppercase:
drive = Path(f"{letter}:\\")
try:
if drive.is_dir():
roots.append(drive)
except OSError:
continue
return roots
def describe(path: Path) -> dict:
"""A candidate record for a drive or database path, shaped for the picker."""
path = Path(path)
+142
View File
@@ -0,0 +1,142 @@
"""Where a person keeps things on this computer.
Two jobs, both of them "ask the OS rather than assume":
* **Mounted volumes.** Where a drive appears is per-OS and nothing else in the
app can work it out. This lives here rather than in the OneLibrary adapter —
which is where it grew, because that is the platform whose libraries ARE
drives — because "where does this OS mount things" is not adapter knowledge.
The file browser needs the same answer, and two scanners would drift.
* **The user's own folders.** `platformdirs` answers these, and hardcoding
them would be wrong on every OS in a different way: `~/Videos` is `Movies`
on macOS, Linux's are XDG user-dirs which are user-configurable AND
localised, and Windows Known Folders are routinely **relocated by OneDrive**
so Documents and Desktop are often not under the home directory at all.
A place that does not exist is never returned. A file browser offering a Music
folder that is not there reads as breakage, whereas its absence reads as an
accurate description of the machine.
"""
from __future__ import annotations
import logging
import os
import string
import sys
from pathlib import Path
import platformdirs
log = logging.getLogger(__name__)
def mount_points() -> list[Path]:
"""Every mounted volume's root directory, for this OS.
Only the ROOTS: a drive can hold tens of thousands of files, and walking a
slow USB stick to answer "what is plugged in" is exactly the kind of thing
that makes an app feel broken.
"""
bases: list[Path] = []
if sys.platform == "darwin":
bases.append(Path("/Volumes"))
elif sys.platform.startswith("linux"):
bases.extend([Path("/media"), Path("/mnt"), Path("/run/media")])
user = os.environ.get("USER")
if user:
bases.append(Path("/media") / user)
bases.append(Path("/run/media") / user)
roots: list[Path] = []
for base in bases:
try:
if not base.is_dir():
continue
roots.extend(p for p in base.iterdir() if p.is_dir())
except OSError:
continue
if sys.platform == "win32":
# No mount-point directory to list: check the drive letters directly.
for letter in string.ascii_uppercase:
drive = Path(f"{letter}:\\")
try:
if drive.is_dir():
roots.append(drive)
except OSError:
continue
return roots
def _boot_device() -> int | None:
try:
return Path("/").stat().st_dev
except OSError:
return None
def is_boot_volume(path: Path) -> bool:
"""Whether `path` is the volume the OS itself booted from.
macOS lists the startup disk in `/Volumes` alongside real removable media,
so a "Drives" list that does not filter it leads with a path back to where
the user already is. Compared by DEVICE id rather than by name, because
`Macintosh HD` is only the default name and is freely renamed.
"""
boot = _boot_device()
if boot is None:
return False
try:
return path.stat().st_dev == boot
except OSError:
return False
def volumes(*, include_boot: bool = False) -> list[Path]:
"""Mounted volumes, newest-mounted order not guaranteed. Sorted by name."""
found = [v for v in mount_points() if include_boot or not is_boot_volume(v)]
return sorted(set(found), key=lambda p: p.name.lower())
# The user's own folders, in the order a file browser should show them. Music
# sits high because this is a DJ app: it is the likeliest destination by far.
_USER_DIRS: tuple[tuple[str, str, str], ...] = (
("home", "Home", ""),
("music", "Music", "user_music_dir"),
("desktop", "Desktop", "user_desktop_dir"),
("documents", "Documents", "user_documents_dir"),
("downloads", "Downloads", "user_downloads_dir"),
)
def user_places() -> list[dict]:
"""The user's own folders that actually exist on this machine."""
out: list[dict] = []
seen: set[str] = set()
for kind, name, getter in _USER_DIRS:
try:
path = Path.home() if not getter else Path(getattr(platformdirs, getter)())
if not path.is_dir():
continue
key = str(path)
# Windows can resolve two Known Folders to one place; listing it
# twice under different names would just look like a bug.
if key in seen:
continue
seen.add(key)
out.append({"kind": kind, "name": name, "path": key})
except (OSError, AttributeError):
continue
return out
def volume_places() -> list[dict]:
"""Mounted drives, named as the user sees them."""
out: list[dict] = []
for vol in volumes():
try:
out.append({"kind": "volume", "name": vol.name or str(vol), "path": str(vol)})
except OSError:
continue
return out
+42 -1
View File
@@ -17,7 +17,7 @@ from . import __version__, history, prefs
from .app_state import STATE
from .core import auto_hotcues as ah
from . import importer
from .core import registry
from .core import places, registry
from .core.adapter import (
AdapterError,
InvalidCommand,
@@ -45,6 +45,7 @@ from .schemas import (
FileTagOutcome,
FsEntry,
FsListing,
FsPlace,
AddGridMarker,
GridMarkerEdit,
ReplaceGrid,
@@ -245,6 +246,46 @@ def patch_prefs(patch: dict) -> dict:
return prefs.update_prefs(patch)
@app.get("/api/fs/places", response_model=list[FsPlace])
def fs_places(platform: str | None = None) -> list[FsPlace]:
"""Sidebar shortcuts for the file browser: the user's folders, then drives.
Answered by the server because only it can stat a filesystem, and re-asked
by the client rather than cached: drives come and go while a dialog is open,
and a browser that exists to find a stick you just plugged in has to show it.
`platform` adds that platform's own default location, which is the likeliest
destination when browsing for one of its libraries. Only for platforms whose
library sits at a fixed path — a removable one's libraries ARE the drives,
which are already listed.
"""
out = [FsPlace(**p) for p in places.user_places()]
out += [FsPlace(**p) for p in places.volume_places()]
if platform:
try:
driver = registry.driver_by_platform(platform)
except LibraryNotSupported:
driver = None
if driver is not None and not getattr(driver, "removable", False):
seen = {p.path for p in out}
try:
found = driver.detect()
except OSError:
found = []
for candidate in found:
# The place is the folder CONTAINING the library, because a
# place is somewhere you navigate to, not something you pick.
folder = Path(candidate["path"]).parent
if str(folder) in seen or not folder.is_dir():
continue
seen.add(str(folder))
out.append(
FsPlace(kind="library", name=candidate.get("label") or folder.name,
path=str(folder))
)
return out
@app.get("/api/fs/list", response_model=FsListing)
def fs_list(path: str | None = None, platform: str | None = None) -> FsListing:
"""List directories and openable library files for the in-app file browser.
+13
View File
@@ -135,6 +135,19 @@ class CollectionOptions(BaseModel):
recent: CollectionCandidate | None = None # last opened (from userprefs)
class FsPlace(BaseModel):
"""A shortcut in the file browser's sidebar.
`kind` groups it and picks its icon; it is never a finished sentence, and
the browser decides what "volume" looks like. A place is always a DIRECTORY
that exists right now — one that does not is omitted rather than disabled.
"""
kind: str # home | music | desktop | documents | downloads | volume | library
name: str
path: str
class FsEntry(BaseModel):
name: str
path: str
+46 -2
View File
@@ -23,8 +23,8 @@ _TMP = tempfile.TemporaryDirectory()
prefs._PREFS_PATH = Path(_TMP.name) / "userprefs.json"
prefs._LEGACY_PREFS_PATH = Path(_TMP.name) / "absent.json"
from konduktor.core import registry # noqa: E402
from konduktor.main import collection_options, fs_list, platforms # noqa: E402
from konduktor.core import places, registry # noqa: E402
from konduktor.main import collection_options, fs_list, fs_places, platforms # noqa: E402
failed = False
@@ -120,6 +120,50 @@ check("folders are listed for every platform",
all({d.name for d in fs_list(str(root), p).dirs} == {"SomeDrive"}
for p in (None, "traktor", "rekordbox", "onelibrary")))
print("== /api/fs/places: the browser's sidebar ==")
rows = fs_places()
check("there is always somewhere to go", len(rows) > 0)
# A greyed-out Music folder on a machine that has none reads as breakage; its
# absence reads as an accurate description of the machine.
check("every place exists and is a directory",
all(Path(r.path).is_dir() for r in rows),
[r.path for r in rows if not Path(r.path).is_dir()])
check("home is always offered", any(r.kind == "home" for r in rows))
check("no duplicate paths", len({r.path for r in rows}) == len(rows))
check("nothing is unnamed", all(r.name for r in rows))
# macOS lists the startup disk in /Volumes next to real removable media, so a
# Drives list that does not filter it leads with a path back to where you are.
# Compared by DEVICE, because "Macintosh HD" is only the default name.
check("the boot volume is not offered as a drive",
not any(places.is_boot_volume(Path(r.path)) for r in rows if r.kind == "volume"),
[r.path for r in rows if r.kind == "volume" and places.is_boot_volume(Path(r.path))])
lib_places = lambda plat: [r for r in fs_places(plat) if r.kind == "library"] # noqa: E731
check("no library shortcut without a platform", lib_places(None) == [])
for plat in ("traktor", "rekordbox"):
found = registry.detect_for(plat)
expected = {str(Path(c["path"]).parent) for c in found}
got = {r.path for r in lib_places(plat)}
# The shortcut is the folder CONTAINING the library: a place is somewhere
# you navigate to, not something you pick.
check(f"{plat}: shortcut points at the containing folder", got <= expected, f"{got} vs {expected}")
if found:
check(f"{plat}: the shortcut is offered", len(got) > 0)
# A removable platform's libraries ARE the drives, which the Drives group
# already lists — a second row for the same place would just be noise.
check("no library shortcut for a removable platform", lib_places("onelibrary") == [])
check("an unknown platform does not raise", isinstance(fs_places("nonesuch"), list))
print("== the mount scanner is shared, not duplicated ==")
# It grew inside the OneLibrary adapter, because that is the platform whose
# libraries are drives. "Where does this OS mount things" is not adapter
# knowledge, though, and two scanners would drift.
import konduktor.adapters.onelibrary.discovery as onelib_discovery # noqa: E402
check("the adapter uses core's scanner, not its own",
onelib_discovery._mount_points is places.mount_points)
check("volumes() drops the boot volume, mount_points() does not",
set(places.volumes()) <= set(places.mount_points()))
print("== a library may be a DIRECTORY, not just a file ==")
drives = registry.detect_for("onelibrary")
if drives: