Implemented Discard changes button

This commit is contained in:
patben8 committed 2026-10-01 10:54:27 +02:00
1 parent 681add852a
commit 28b705173e
17 files changed
+564 -43

No files matched your search

@@ -80,7 +80,9 @@ class RekordboxAdapter:
self._store.close()
def reload(self) -> None:
self._store._load()
"""Re-read the library from disk, DISCARDING unsaved edits (see
`RekordboxStore.discard` for why a plain re-open is not enough)."""
self._store.discard()
self._cloud_synced = self._store.cloud_synced
self._rebuild()
@@ -101,6 +101,24 @@ class RekordboxStore:
self._content_cache: list | None = None
self._by_id: dict[str, object] | None = None
def discard(self) -> None:
"""Drop every unsaved edit and re-open the library as it is on disk.
Three things hold edits here, and all three must go: the SQLAlchemy
session (rolled back, then closed with its engine — `_load()` alone
would open a SECOND connection and leak the first), the buffered grid
writes (which the next save would otherwise still write to ANLZ files),
and the journal (else the library keeps reporting unsaved changes).
"""
try:
self._db.session.rollback()
except Exception: # noqa: BLE001 — discarding must not fail halfway
pass
self.close()
self._journal = EditJournal()
self._pending_grids.clear()
self._load()
def close(self) -> None:
"""Release the session AND the pooled connection.
+8 -5
View File
@@ -1241,11 +1241,14 @@ class TraktorStore:
return key_remap
# ---- stem conversion ---------------------------------------------------
#: Whether a converted entry keeps Traktor's analysis fingerprint. It is a
#: fingerprint of the OLD file; cleared, Traktor re-analyses the new one on
#: load (the import precedent: prep survives). Settled by the milestone-2
#: check in Traktor 4.5.
_KEEP_AUDIO_ID_ON_STEM = False
#: Whether a converted entry keeps Traktor's analysis fingerprint (AUDIO_ID).
#: KEPT, as measured in Traktor 4.5 (kit 5, 2026-09-30): with it kept, Traktor
#: loads the stem entry as it is — cues, grid and fingerprint untouched. With
#: it cleared, Traktor re-analyses on load: it keeps grid POSITIONS (even a
#: hand-nudged, unlocked one) but re-measures the grid's BPM (125.000023 ->
#: 125.00042), i.e. it rewrites prep the user set. The stem file's mix is the
#: same audio as the original, so the old fingerprint still describes it.
_KEEP_AUDIO_ID_ON_STEM = True
def apply_stem_swaps(self, swaps: list, *, add_to_playlist: str | None = None) -> StemSwapResult:
"""Point entries at converted stem files ("repoint"), or add entries for
+25
View File
@@ -25,6 +25,7 @@ human summary, and this module versions them.
from __future__ import annotations
import os
import threading
from pathlib import Path
from . import __version__, adapters, history, library_id, prefs # noqa: F401 — registers adapters
@@ -51,6 +52,11 @@ class AppState:
# This open's missing-files check (see `relocation.py`). A new one per
# open, which is what makes the dialog ask again on a reopen.
self.relocation: RelocationCheck | None = None
# Serialises the operations that REPLACE or COMMIT the whole library —
# open, save, discard (and a stem batch's swap step). A save landing in
# the middle of another would commit a half-applied state; reentrant so
# one of them may call another.
self.mutation = threading.RLock()
@property
def loaded(self) -> bool:
@@ -95,6 +101,10 @@ class AppState:
pass
def open(self, path: Path) -> None:
with self.mutation:
self._open(path)
def _open(self, path: Path) -> None:
# The registry picks the adapter by probing the file, not by extension —
# a Rekordbox library is a .db and a Serato one is a directory. Raises on
# an unrecognised or unparseable file; only commit once it has parsed.
@@ -146,6 +156,10 @@ class AppState:
cannot restore from.
"""
assert self.adapter is not None and self.path is not None
with self.mutation:
return self._save()
def _save(self):
outcome = self.adapter.save()
# Not every platform is versioned. A library that is more than one file
# has no single blob that IS the library, and it says so through its
@@ -158,6 +172,17 @@ class AppState:
)
return outcome, commit
def discard(self) -> None:
"""Drop every unsaved edit: the library re-reads itself from disk.
Through the adapter's own `reload`, NOT `open` — reopening would start a
new missing-files check and forget this session's relocation answers,
which are not edits and survive a reload (the store keeps them).
"""
assert self.adapter is not None
with self.mutation:
self.adapter.reload()
STATE = AppState()
+33 -10
View File
@@ -163,16 +163,7 @@ def open_collection(body: OpenCollection) -> CollectionStatus:
# This checks only that the path is there at all; `can_open()` decides.
if not path.exists():
raise HTTPException(400, f"Not found: {path}")
# A running analysis writes into the library being replaced; stop it, and
# WAIT for it to stop — a job still finishing its current track would
# otherwise keep writing (or, for file work, keep moving files) after the
# switch. Batches check for a cancel between tracks, so this is short.
stopping = [job for kind in BATCH_JOBS for job in JOBS.active(kind)]
for job in stopping:
JOBS.cancel(job.id)
for job in stopping:
if not JOBS.wait(job.id, timeout=60):
log.warning("batch %s (%s) still running after cancel; opening anyway", job.id, job.kind)
_stop_batches()
try:
STATE.open(path)
except AdapterError as ex:
@@ -740,6 +731,22 @@ def state() -> EditState:
return EditState(dirty=require_adapter().dirty, library=_library_info())
@app.post("/api/discard", response_model=EditState)
def discard_changes() -> EditState:
"""Drop every unsaved edit — the library re-reads itself from disk.
A running batch is stopped first (and waited for): it writes into the
library being discarded, so it would otherwise keep adding edits to the
freshly reloaded one.
"""
adapter = require_adapter()
if not adapter.capabilities().writable:
raise HTTPException(409, "This library cannot be edited, so there is nothing to discard")
_stop_batches()
STATE.discard()
return state()
@app.post("/api/reload")
def reload_collection() -> dict:
if not STATE.loaded:
@@ -1040,6 +1047,22 @@ CUE_JOB = "auto-hotcues"
BATCH_JOBS = (GRID_JOB, CUE_JOB)
def _stop_batches() -> None:
"""Cancel every running batch analysis and WAIT for it to stop.
Used wherever the library is about to be replaced or reloaded: a job still
finishing its current track would otherwise keep writing into it (or, for
file work, keep moving files) afterwards. Batches check for a cancel
between tracks, so this is short.
"""
stopping = [job for kind in BATCH_JOBS for job in JOBS.active(kind)]
for job in stopping:
JOBS.cancel(job.id)
for job in stopping:
if not JOBS.wait(job.id, timeout=60):
log.warning("batch %s (%s) still running after cancel; continuing", job.id, job.kind)
def _require_no_batch() -> None:
"""An early, friendly refusal. Not race-free on its own — the batch routes
START through `_submit_batch`, which re-checks under the registry's lock."""