Files
lintunes/lintunes/gui/conflict_dialog.py
T
trav 51d2fb549c v0.12.0: the merge report stops reporting things you didn't do
"unplayed", "missed and never skipped" and "top 100 in past year" showed up in
the merge window constantly, and nobody had touched their rules. A live smart
playlist's membership is derived, but it was being persisted — and
recompute_smart_playlist rewrites it (and bumped date_modified) every time a
play count moves. Both machines did that against the same file after every
song, so Syncthing conflicted on a list the next load throws away and rebuilds
anyway. Membership now stays in memory: save_playlist writes track_ids: [] for
a live smart playlist, and the recompute passes touch=False so it marks nothing
dirty and moves no timestamp. live_update=False and unsupported criteria are
unchanged — their track_ids are a snapshot, which is real content. Since
_mark_playlist also dirties the metadata, library_metadata.json stops being
rewritten every song too.

The rest was presentation. Every summary read at the same weight, so someone
resizing a column on the other machine popped and raised the same window as a
21-track reconciliation, described as "Library columns/settings taken from the
most recently edited copy." Summaries now carry a level — WARNING for a merge
that couldn't resolve cleanly or discarded a side, CHANGE for real content,
INFO for cosmetic or derived — and the dialog has a Show: selector that filters
to one level and above. It opens at the highest level in the batch, so nothing
routine steals focus and a blank window can't happen; a later warning always
pulls the view back up to it. The wording says what happened instead of how the
merge works: a metadata merge names the keys that actually differed, and
adopting the other machine's music folder grades CHANGE rather than INFO,
because that one is a setting somebody chose.

Claude-Session: https://claude.ai/code/session_01Y9ZEFi4qNJ39FMiBtiAxy2
2026-08-25 14:53:37 -04:00

205 lines
8.0 KiB
Python

"""A read-only summary of Syncthing conflicts LinTunes auto-merged, with the
option to open or restore the pre-merge backup.
One dialog per session, not one per merge: Syncthing can deliver conflicts every
few minutes, so ``add_event`` folds each new merge into the open window as a
timestamped entry instead of stacking another window on the desktop.
Entries are graded (see conflict_resolver's WARNING/CHANGE/INFO) and the window
shows one level and above. It opens at whatever the *highest* level in the batch
is, so there is always something to read: a batch of nothing but column-width
merges opens on the details view rather than blank, and a real divergence is
never hidden behind a filter the user left set to something quieter.
"""
from datetime import datetime
from pathlib import Path
from PyQt6.QtCore import QUrl
from PyQt6.QtGui import QDesktopServices
from PyQt6.QtWidgets import (
QDialog, QVBoxLayout, QHBoxLayout, QComboBox, QLabel, QTextEdit,
QPushButton, QMessageBox)
from lintunes.storage.conflict_resolver import (
WARNING, CHANGE, INFO, LEVEL_ORDER, at_least, max_level)
INTRO = ("LinTunes found changes made on more than one machine and merged them "
"(play counts kept highest, newest edits win, nothing removed). Both "
"versions were backed up first — restore them if a merge isn't what "
"you wanted.")
# Coarsest first, so the combo reads top-down like a volume knob.
LEVEL_CHOICES = [
(WARNING, "Warnings only"),
(CHANGE, "Changes and warnings"),
(INFO, "Everything"),
]
MARKERS = {WARNING: "!", CHANGE: "●", INFO: "·"}
class ConflictSummaryDialog(QDialog):
def __init__(self, summaries, manager, parent=None):
super().__init__(parent)
self._manager = manager
self._events = [] # newest last: (datetime, list[ConflictSummary])
self._level = INFO
self._user_picked = False
self.setWindowTitle("Synced changes merged")
self.resize(560, 440)
layout = QVBoxLayout(self)
self._intro = QLabel(INTRO)
self._intro.setWordWrap(True)
layout.addWidget(self._intro)
filter_row = QHBoxLayout()
filter_row.addWidget(QLabel("Show:"))
self._level_box = QComboBox()
for level, label in LEVEL_CHOICES:
self._level_box.addItem(label, level)
self._level_box.activated.connect(self._on_level_picked)
filter_row.addWidget(self._level_box)
filter_row.addStretch(1)
layout.addLayout(filter_row)
self._body = QTextEdit()
self._body.setReadOnly(True)
layout.addWidget(self._body, 1)
buttons = QHBoxLayout()
self._open_btn = QPushButton("Open backup folder")
self._open_btn.clicked.connect(self._open_backup)
self._restore_btn = QPushButton("Restore pre-merge backup")
self._restore_btn.clicked.connect(self._restore_backup)
keep_btn = QPushButton("Keep merged")
keep_btn.setDefault(True)
keep_btn.clicked.connect(self.accept)
buttons.addWidget(self._open_btn)
buttons.addWidget(self._restore_btn)
buttons.addStretch(1)
buttons.addWidget(keep_btn)
layout.addLayout(buttons)
self.add_event(summaries)
# ---- events ----
def add_event(self, summaries, when=None) -> bool:
"""Fold another merge into this window as its own timestamped entry.
Returns True if the new batch has anything to show at the level now on
screen — the caller uses that to decide whether to raise the window, so
a column resize on the other machine never steals focus."""
summaries = list(summaries or [])
self._events.append((when or datetime.now(), summaries))
self._set_level(self._level_for(summaries))
self._refresh()
return any(at_least(s.level, self._level) for s in summaries)
@property
def level(self) -> str:
return self._level
def _level_for(self, incoming) -> str:
"""Which level to display now that ``incoming`` has arrived.
Untouched by the user, the view follows the most serious thing seen so
far. Once the user has picked a level, their choice stands — except that
a batch more serious than what they are looking at pulls the view back
up to it."""
incoming_max = max_level(incoming)
if not self._user_picked:
return max(
(max_level(s) for _when, s in self._events),
key=lambda lvl: LEVEL_ORDER.get(lvl, 0), default=INFO)
if LEVEL_ORDER.get(incoming_max, 0) > LEVEL_ORDER.get(self._level, 0):
return incoming_max
return self._level
def _set_level(self, level: str):
self._level = level
index = self._level_box.findData(level)
if index >= 0:
self._level_box.blockSignals(True)
self._level_box.setCurrentIndex(index)
self._level_box.blockSignals(False)
def _on_level_picked(self, index: int):
self._user_picked = True
self._level = self._level_box.itemData(index)
self._refresh()
@property
def _backup_dir(self) -> str:
"""The newest event's backup snapshot. One resolve_conflicts() call makes
one timestamped dir, so every summary in an event shares it."""
for _when, summaries in reversed(self._events):
if summaries and summaries[0].backup_dir:
return summaries[0].backup_dir
return ""
def _refresh(self):
self._body.setPlainText(self._format())
count = len(self._events)
self._intro.setText(
INTRO if count < 2 else f"{INTRO}\n\n{count} merges this session.")
newest = self._events[-1][0] if self._events else None
self._restore_btn.setText(
f"Restore backup from {newest.strftime('%-I:%M %p')}"
if newest and count > 1 else "Restore pre-merge backup")
self._open_btn.setEnabled(bool(self._backup_dir))
self._restore_btn.setEnabled(bool(self._backup_dir))
def _format(self) -> str:
blocks = []
hidden = 0
shown = 0
multi = len(self._events) > 1
for when, summaries in reversed(self._events): # newest first
visible = [s for s in summaries if at_least(s.level, self._level)]
hidden += len(summaries) - len(visible)
shown += len(visible)
if not visible:
continue # no orphan timestamp headers for a filtered-out merge
lines = []
if multi:
lines.append(f"── {when.strftime('%-I:%M %p')} " + "─" * 30)
for s in visible:
lines.append(f"{MARKERS.get(s.level, '●')} {s.file}")
lines.extend(f" {line}" for line in s.lines)
lines.append("")
blocks.append("\n".join(lines).rstrip())
if not shown:
blocks.append("Nothing at this level.")
if hidden:
entries = "entry" if hidden == 1 else "entries"
blocks.append(f"({hidden} routine {entries} hidden — switch to "
f"“Everything” to see them.)")
return "\n\n".join(blocks)
# ---- actions ----
def _open_backup(self):
if self._backup_dir:
QDesktopServices.openUrl(QUrl.fromLocalFile(self._backup_dir))
def _restore_backup(self):
backup_dir = self._backup_dir
if not backup_dir:
return
if QMessageBox.question(
self, "Restore backup",
"Replace the current files with the pre-merge versions from this "
"backup? The other machine's changes may re-sync as a new "
"conflict later.") != QMessageBox.StandardButton.Yes:
return
from lintunes.storage import conflict_resolver
conflict_resolver.restore_backup(Path(backup_dir), self._manager.data_dir)
self._manager.reload_from_disk()
QMessageBox.information(self, "Restored", "Restored the pre-merge backup.")
self.accept()