diff --git a/CLAUDE.md b/CLAUDE.md index 6816d1f..7368c29 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -838,6 +838,15 @@ persistence) → GUI (Qt widgets that read the manager and connect to its signal test that downloads several songs must stub `_show_batch_review` and cancel `_url_batch` on teardown, or a late lookup opens a modal dialog in the next test. + **Both Identify windows search the cover too** (Round 119, + `gui/art_picker.ArtPicker`, Download Album Art's search as a widget): + `IdentifyDialog(find_art=True)` (every MainWindow caller) searches the + album its grid proposes and re-searches on a candidate switch or after + typing rests; Embed ticks itself only when the file has no cover + (`MainWindow._has_artwork`). A playlist batch gets a picker per album — + searched one at a time, a Cover column, the selected song's album + beside the table; `selected_art()` is [(rows, image, mime)], embedded + in that album's rows whether ticked or not (the tick is about tags). - **`lintunes/shazam.py`** + **`gui/shazam_import.py`** — Connections › Import Shazams… (Round 103), the `/shazam-import` skill inside the app. diff --git a/lintunes/__init__.py b/lintunes/__init__.py index c9beb4c..969f23e 100644 --- a/lintunes/__init__.py +++ b/lintunes/__init__.py @@ -1,3 +1,3 @@ """LinTunes — iTunes-style music library manager and player for Linux.""" -__version__ = "0.85.1" +__version__ = "0.86.0" diff --git a/lintunes/gui/art_picker.py b/lintunes/gui/art_picker.py new file mode 100644 index 0000000..d3bf0f2 --- /dev/null +++ b/lintunes/gui/art_picker.py @@ -0,0 +1,191 @@ +"""A cover-art search inside another window (Round 119). + +Download Album Art's search (iTunes + Deezer, ``AlbumArtFetcher``) as a +widget: the picture, what it is, **Next Artwork** to cycle the results and +an **Embed** box. The Identify windows carry one, so an Import from URL +proposes tags and a cover in the same place. + +Passive like the dialogs it sits in: nothing is written. The caller reads +``selected()`` after an accept and embeds through ``art_ops``. +""" +from PyQt6.QtCore import Qt, pyqtSignal +from PyQt6.QtGui import QPixmap +from PyQt6.QtWidgets import ( + QCheckBox, QHBoxLayout, QLabel, QPushButton, QVBoxLayout, QWidget, +) + +from lintunes.art_search import AlbumArtFetcher + +ART_PX = 180 + + +class ArtPicker(QWidget): + # The picture or the Embed box changed (a table's thumbnail follows). + changed = pyqtSignal() + # A search has come to rest: no results, an error, or its first image + # (good or bad). A queue of pickers starts the next one on this. + settled = pyqtSignal() + + def __init__(self, embed_text: str = "Embed this artwork", + size: int = ART_PX, parent=None): + super().__init__(parent) + self._candidates = [] + self._index = 0 + self._image: bytes | None = None + self._mime = "image/jpeg" + self._embed_default = True + self._generation = 0 + self._fetchers = [] # kept alive while their threads run + self._settled = True + self.query: tuple | None = None + + layout = QVBoxLayout(self) + layout.setContentsMargins(0, 0, 0, 0) + self._art = QLabel("No artwork search") + self._art.setFixedSize(size, size) + self._art.setAlignment(Qt.AlignmentFlag.AlignCenter) + self._art.setStyleSheet("border: 1px solid palette(mid);") + self._art.setWordWrap(True) + layout.addWidget(self._art) + self._caption = QLabel() + self._caption.setWordWrap(True) + self._caption.setEnabled(False) + self._caption.setMaximumWidth(max(size, 220)) + layout.addWidget(self._caption) + row = QHBoxLayout() + self._embed = QCheckBox(embed_text) + self._embed.setEnabled(False) + self._embed.toggled.connect(lambda _on: self.changed.emit()) + self._next = QPushButton("Next Artwork") + self._next.setEnabled(False) + self._next.clicked.connect(self.next_artwork) + row.addWidget(self._embed) + row.addWidget(self._next) + row.addStretch(1) + layout.addLayout(row) + layout.addStretch(1) + + # ---- searching ---- + + def search(self, artist: str, album: str, embed_by_default: bool = True): + """Look up (artist, album), dropping whatever an earlier search was + still doing. The Embed box ticks itself when the first picture + arrives, if ``embed_by_default``.""" + self.query = (artist, album) + self._embed_default = embed_by_default + self._reset("Searching…") + self._settled = False + fetcher = self._fetcher() + fetcher.search(artist, album) + + def clear(self, text: str = "No album to search artwork by"): + self.query = None + self._reset(text) + self._settled = True + self.changed.emit() + + def _reset(self, text: str): + self._generation += 1 + self._candidates = [] + self._index = 0 + self._image = None + self._caption.setText("") + self._art.setPixmap(QPixmap()) + self._art.setText(text) + self._next.setEnabled(False) + self._embed.blockSignals(True) + self._embed.setChecked(False) + self._embed.blockSignals(False) + self._embed.setEnabled(False) + + def _fetcher(self): + """A fetcher whose answers count only while its search is the + latest one.""" + gen = self._generation + fetcher = AlbumArtFetcher() + fetcher.search_finished.connect( + lambda result: gen == self._generation + and self._on_search(result)) + fetcher.image_finished.connect( + lambda result: gen == self._generation + and self._on_image(result)) + self._fetchers = self._fetchers[-3:] + [fetcher] + return fetcher + + def _on_search(self, result: dict): + self._candidates = result.get("candidates") or [] + if not self._candidates: + self._art.setText("No artwork found" if "error" not in result + else "Artwork search failed") + self._caption.setText(result.get("error", "")) + self._settle() + return + self._next.setEnabled(len(self._candidates) > 1) + self._load() + + def _load(self): + candidate = self._candidates[self._index] + n = len(self._candidates) + self._caption.setText( + f"{candidate.artist} — {candidate.album}, via {candidate.source}" + + (f" ({self._index + 1}/{n})" if n > 1 else "")) + self._image = None + self._embed.setEnabled(False) + self._art.setPixmap(QPixmap()) + self._art.setText("Loading…") + self._fetchers[-1].fetch(candidate) + self.changed.emit() + + def next_artwork(self): + if len(self._candidates) < 2: + return + self._index = (self._index + 1) % len(self._candidates) + self._load() + + def _on_image(self, result: dict): + if "candidate" in result and ( + not self._candidates + or result["candidate"] is not self._candidates[self._index]): + return # a stale download after Next Artwork + if "error" in result: + self._art.setText("Couldn't load the image") + self._settle() + return + pixmap = QPixmap() + if not pixmap.loadFromData(result["image"]): + self._art.setText("Couldn't decode the image") + self._settle() + return + self._image = result["image"] + self._mime = result["mime"] + self._art.setPixmap(pixmap.scaled( + self._art.size(), Qt.AspectRatioMode.KeepAspectRatio, + Qt.TransformationMode.SmoothTransformation)) + first = not self._settled + self._embed.setEnabled(True) + if first and self._embed_default: + self._embed.blockSignals(True) + self._embed.setChecked(True) + self._embed.blockSignals(False) + self.changed.emit() + self._settle() + + def _settle(self): + if not self._settled: + self._settled = True + self.settled.emit() + + # ---- what the caller reads ---- + + def set_embed_text(self, text: str): + self._embed.setText(text) + + def image(self) -> bytes | None: + """The picture on show, embedded or not.""" + return self._image + + def selected(self) -> tuple[bytes, str] | None: + """(image, mime) when the Embed box is ticked over a picture.""" + if self._image and self._embed.isChecked(): + return self._image, self._mime + return None diff --git a/lintunes/gui/identify_batch_dialog.py b/lintunes/gui/identify_batch_dialog.py index 810fa19..9568e7e 100644 --- a/lintunes/gui/identify_batch_dialog.py +++ b/lintunes/gui/identify_batch_dialog.py @@ -11,22 +11,28 @@ album-wide fields sit above the table, once. Editing them edits every row. Beside them is the album's cover from the same search Download Album Art uses, with Next Artwork to cycle through the results. +A playlist gets a cover per album (Round 119): a Cover column shows each +song's, and the panel beside the table is the selected song's album — +its picture, Next Artwork, and whether to embed it in that album's songs. +The searches run one at a time, so a long playlist doesn't fire dozens +at the art APIs at once. + Passive like IdentifyDialog: nothing is written until the caller reads -``edits()``, ``unchecked_rows()`` and ``selected_image`` after an accept. +``edits()``, ``unchecked_rows()`` and ``selected_art()`` after an accept. """ import re -from PyQt6.QtCore import Qt -from PyQt6.QtGui import QFont, QPixmap +from PyQt6.QtCore import QSize, Qt +from PyQt6.QtGui import QFont, QIcon, QPixmap from PyQt6.QtWidgets import ( - QAbstractItemView, QCheckBox, QDialog, QDialogButtonBox, QFormLayout, + QAbstractItemView, QDialog, QDialogButtonBox, QFormLayout, QHBoxLayout, QHeaderView, QLabel, QLineEdit, QPushButton, QSpinBox, - QTableWidget, QTableWidgetItem, QVBoxLayout, + QStackedWidget, QTableWidget, QTableWidgetItem, QVBoxLayout, ) -from lintunes.art_search import AlbumArtFetcher +from lintunes.gui.art_picker import ART_PX, ArtPicker -ART_PX = 180 +THUMB_PX = 36 # (header, fields shown in the column) COLUMNS = [ @@ -86,14 +92,15 @@ class IdentifyBatchDialog(QDialog): r.proposal.get("track_number") or 999)) self.outcome = 0 - self.selected_image: bytes | None = None - self.selected_mime = "image/jpeg" - self._art_candidates = [] - self._art_index = 0 - self._art_image = None - self._art_mime = "image/jpeg" - self._fetcher = None self._filling = False + # Playlist mode: one picker per album, the rows that album covers, + # and the searches still waiting their turn. + self._pickers: dict[tuple, ArtPicker] = {} + self._group_rows: dict[tuple, list[int]] = {} + self._row_group: dict[int, tuple] = {} + self._art_queue: list[ArtPicker] = [] + self._art = None + self._cover_col = None layout = QVBoxLayout(self) n = len(self._rows) @@ -106,13 +113,16 @@ class IdentifyBatchDialog(QDialog): layout.addWidget(header) self._album_edit = self._album_artist_edit = self._year_edit = None - self._embed = None if analysis.is_album: layout.addLayout(self._album_panel(art_query)) + else: + self._cover_col = SOURCE_COL + 1 - self._table = QTableWidget(n, SOURCE_COL + 1) + columns = SOURCE_COL + 1 + (self._cover_col is not None) + self._table = QTableWidget(n, columns) self._table.setHorizontalHeaderLabels( - [""] + [h for h, _f in COLUMNS] + ["Found by"]) + [""] + [h for h, _f in COLUMNS] + ["Found by"] + + (["Cover"] if self._cover_col is not None else [])) self._table.verticalHeader().hide() self._table.setSelectionBehavior( QAbstractItemView.SelectionBehavior.SelectRows) @@ -124,13 +134,29 @@ class IdentifyBatchDialog(QDialog): head.setSectionResizeMode(QHeaderView.ResizeMode.Interactive) head.setSectionResizeMode(CHECK_COL, QHeaderView.ResizeMode.ResizeToContents) - head.setStretchLastSection(True) + if self._cover_col is None: + head.setStretchLastSection(True) + else: + head.setSectionResizeMode(SOURCE_COL, + QHeaderView.ResizeMode.Stretch) + head.setSectionResizeMode(self._cover_col, + QHeaderView.ResizeMode.Fixed) + self._table.setColumnWidth(self._cover_col, THUMB_PX + 16) + self._table.setIconSize(QSize(THUMB_PX, THUMB_PX)) + self._table.verticalHeader().setDefaultSectionSize(THUMB_PX + 6) self._fill_table() self._table.itemChanged.connect(self._on_item_changed) for col, width in zip(range(FIRST_FIELD_COL, SOURCE_COL), (200, 150, 120, 170, 55, 70, 45)): self._table.setColumnWidth(col, width) - layout.addWidget(self._table, 1) + if self._cover_col is None: + layout.addWidget(self._table, 1) + else: + middle = QHBoxLayout() + middle.addWidget(self._table, 1) + middle.addSpacing(8) + middle.addWidget(self._cover_panel()) + layout.addLayout(middle, 1) hint = QLabel("Bold is what changes (hover to see what it was). " "Double-click to edit. Unticked songs are shown one " @@ -157,20 +183,24 @@ class IdentifyBatchDialog(QDialog): layout.addWidget(buttons) self._update_apply() self._table.setFocus() # not the Album box: nothing to type yet - self.resize(1000, min(260 + 30 * n + (ART_PX if analysis.is_album - else 0), 820)) + if self._cover_col is None: + self.resize(1000, min(260 + 30 * n + ART_PX, 820)) + else: + self.resize(1260, min(max(260 + (THUMB_PX + 6) * n, + ART_PX + 260), 820)) + if n: + self._table.selectRow(0) + self._next_search() # ---- the album panel ---- def _album_panel(self, art_query): a = self._analysis row = QHBoxLayout() - self._art = QLabel("Searching…" if art_query else "No artwork search") - self._art.setFixedSize(ART_PX, ART_PX) - self._art.setAlignment(Qt.AlignmentFlag.AlignCenter) - self._art.setStyleSheet("border: 1px solid palette(mid);") - self._art.setWordWrap(True) + self._art = ArtPicker(f"Embed this artwork in all " + f"{len(self._rows)} songs", parent=self) row.addWidget(self._art) + row.addSpacing(12) side = QVBoxLayout() form = QFormLayout() @@ -191,79 +221,79 @@ class IdentifyBatchDialog(QDialog): self._year_edit.valueChanged.connect( lambda v: self._set_column(("year",), str(v) if v else "")) side.addLayout(form) - - self._art_caption = QLabel() - self._art_caption.setWordWrap(True) - self._art_caption.setEnabled(False) - side.addWidget(self._art_caption) - art_row = QHBoxLayout() - self._embed = QCheckBox(f"Embed this artwork in all " - f"{len(self._rows)} songs") - self._embed.setEnabled(False) - self._next_art = QPushButton("Next Artwork") - self._next_art.setEnabled(False) - self._next_art.clicked.connect(self._on_next_art) - art_row.addWidget(self._embed) - art_row.addWidget(self._next_art) - art_row.addStretch(1) - side.addLayout(art_row) side.addStretch(1) row.addLayout(side, 1) if art_query: - self._fetcher = AlbumArtFetcher() - self._fetcher.search_finished.connect(self._on_art_search) - self._fetcher.image_finished.connect(self._on_art_image) - self._fetcher.search(*art_query) + self._art.search(*art_query) return row - def _on_art_search(self, result: dict): - self._art_candidates = result.get("candidates") or [] - if not self._art_candidates: - self._art.setText("No artwork found" if "error" not in result - else "Artwork search failed") - self._art_caption.setText(result.get("error", "")) - return - self._next_art.setEnabled(len(self._art_candidates) > 1) - self._load_art() + # ---- a playlist's covers, one per album ---- - def _load_art(self): - candidate = self._art_candidates[self._art_index] - n = len(self._art_candidates) - self._art_caption.setText( - f"{candidate.artist} — {candidate.album}, via {candidate.source}" - + (f" ({self._art_index + 1}/{n})" if n > 1 else "")) - self._art_image = None - self._embed.setEnabled(False) - self._art.setPixmap(QPixmap()) - self._art.setText("Loading…") - self._fetcher.fetch(candidate) + def _cover_panel(self): + """The selected song's album cover, with a picker per album held in + a stack: switching songs on one album keeps its choice.""" + for r, row in enumerate(self._rows): + artist = (row.proposal.get("album_artist") + or row.current("album_artist") + or row.proposal.get("artist") or row.current("artist")) + album = row.proposal.get("album") or row.current("album") + if not (artist and album): + continue + key = (artist.casefold(), album.casefold()) + self._row_group[r] = key + self._group_rows.setdefault(key, []).append(r) + if key not in self._pickers: + picker = ArtPicker(parent=self) + picker.query = (artist, album) # searched in turn + picker.changed.connect( + lambda k=key: self._refresh_thumbs(k)) + picker.settled.connect(self._next_search) + self._pickers[key] = picker + self._art_queue.append(picker) + for key, picker in self._pickers.items(): + n = len(self._group_rows[key]) + picker.set_embed_text("Embed in this song" if n == 1 else + f"Embed in its {n} songs here") + self._cover_stack = QStackedWidget() + self._no_album = QLabel("This song has no album to search " + "artwork by.") + self._no_album.setWordWrap(True) + self._no_album.setEnabled(False) + self._no_album.setFixedWidth(ART_PX) + self._no_album.setAlignment(Qt.AlignmentFlag.AlignTop) + self._cover_stack.addWidget(self._no_album) + for picker in self._pickers.values(): + picker._art.setText("Waiting to search…") + self._cover_stack.addWidget(picker) + self._table.itemSelectionChanged.connect(self._show_cover) + return self._cover_stack - def _on_next_art(self): - self._art_index = (self._art_index + 1) % len(self._art_candidates) - self._load_art() + def _next_search(self): + if self._art_queue: + picker = self._art_queue.pop(0) + picker.search(*picker.query) - def _on_art_image(self, result: dict): - if not self._art_candidates or result.get("candidate") is not \ - self._art_candidates[self._art_index]: - if "candidate" in result: - return # a stale download after Next Artwork - if "error" in result: - self._art.setText("Couldn't load the image") - return - pixmap = QPixmap() - if not pixmap.loadFromData(result["image"]): - self._art.setText("Couldn't decode the image") - return - self._art_image = result["image"] - self._art_mime = result["mime"] - self._art.setPixmap(pixmap.scaled( - self._art.size(), Qt.AspectRatioMode.KeepAspectRatio, - Qt.TransformationMode.SmoothTransformation)) - first = not self._embed.isEnabled() and self._art_index == 0 - self._embed.setEnabled(True) - if first: - self._embed.setChecked(True) + def _show_cover(self): + rows = {i.row() for i in self._table.selectedItems()} + key = self._row_group.get(min(rows)) if rows else None + self._cover_stack.setCurrentWidget( + self._pickers[key] if key else self._no_album) + + def _refresh_thumbs(self, key): + picker = self._pickers[key] + chosen = picker.selected() + icon = QIcon() + if chosen: + pixmap = QPixmap() + if pixmap.loadFromData(chosen[0]): + icon = QIcon(pixmap.scaled( + THUMB_PX, THUMB_PX, Qt.AspectRatioMode.KeepAspectRatio, + Qt.TransformationMode.SmoothTransformation)) + self._table.blockSignals(True) + for r in self._group_rows[key]: + self._table.item(r, self._cover_col).setIcon(icon) + self._table.blockSignals(False) # ---- the table ---- @@ -293,6 +323,12 @@ class IdentifyBatchDialog(QDialog): source.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsSelectable) self._table.setItem(r, SOURCE_COL, source) + if self._cover_col is not None: + cover = QTableWidgetItem() + cover.setFlags(Qt.ItemFlag.ItemIsEnabled + | Qt.ItemFlag.ItemIsSelectable) + cover.setTextAlignment(Qt.AlignmentFlag.AlignCenter) + self._table.setItem(r, self._cover_col, cover) self._filling = False def _mark(self, r: int, c: int): @@ -371,12 +407,23 @@ class IdentifyBatchDialog(QDialog): def all_rows(self) -> list: return list(self._rows) + def selected_art(self) -> list: + """[(rows, image, mime)] for every cover whose Embed box is ticked — + all the songs for an album, that album's songs for a playlist, + ticked or not (the tick is about the tags).""" + if self._art is not None: + chosen = self._art.selected() + return [(self.all_rows(), *chosen)] if chosen else [] + out = [] + for key, picker in self._pickers.items(): + chosen = picker.selected() + if chosen: + out.append(([self._rows[r] for r in self._group_rows[key]], + *chosen)) + return out + def _on_apply(self): self.outcome = self.APPLY - if self._embed is not None and self._embed.isChecked() \ - and self._art_image: - self.selected_image = self._art_image - self.selected_mime = self._art_mime self.accept() def _on_review_all(self): diff --git a/lintunes/gui/identify_dialog.py b/lintunes/gui/identify_dialog.py index 236351b..78c4cc8 100644 --- a/lintunes/gui/identify_dialog.py +++ b/lintunes/gui/identify_dialog.py @@ -9,12 +9,19 @@ through LibraryManager afterwards. The proposal itself is ``IdentifyPanel``, a plain widget, so Import Shazams can show it inside its own window while songs are still downloading. + +With ``find_art`` the dialog also searches a cover for the album the grid +proposes (Round 119, ``art_picker``), re-searching when the candidate or +the artist/album boxes change; ``selected_image`` is set on accept. """ +from PyQt6.QtCore import QTimer, pyqtSignal from PyQt6.QtWidgets import ( - QCheckBox, QComboBox, QDialog, QDialogButtonBox, QGridLayout, QLabel, - QLineEdit, QPushButton, QSpinBox, QVBoxLayout, QWidget, + QCheckBox, QComboBox, QDialog, QDialogButtonBox, QGridLayout, QHBoxLayout, + QLabel, QLineEdit, QPushButton, QSpinBox, QVBoxLayout, QWidget, ) +from lintunes.gui.art_picker import ArtPicker + # (field, label, is_number, spinbox max) _FIELDS = [ ("name", "Name", False, 0), @@ -31,6 +38,9 @@ _FIELDS = [ class IdentifyPanel(QWidget): """One track's proposals: the candidate drop-down and the field grid.""" + # The candidate switched, or a box or tick was edited. + proposal_changed = pyqtSignal() + def __init__(self, track, candidates, parent=None): super().__init__(parent) self._track = track @@ -72,6 +82,13 @@ class IdentifyPanel(QWidget): else: editor = QLineEdit() check.toggled.connect(editor.setEnabled) + check.toggled.connect(lambda _on: self.proposal_changed.emit()) + if is_number: + editor.valueChanged.connect( + lambda _v: self.proposal_changed.emit()) + else: + editor.textChanged.connect( + lambda _t: self.proposal_changed.emit()) self._checks[field] = check self._current_labels[field] = current self._editors[field] = editor @@ -125,6 +142,12 @@ class IdentifyPanel(QWidget): # ---- result ---- + def value(self, field): + """What ``field`` will be after Apply: the box when its row is + ticked and filled, else the track's own value.""" + proposed = self.result_fields().get(field) + return proposed if proposed else self._current_value(field) + def result_fields(self) -> dict: """Checked rows only, keyed by LinTunes field names — ready for ``LibraryManager.edit_track_fields``. Blank editors are dropped (a @@ -144,15 +167,37 @@ class IdentifyDialog(QDialog): """``IdentifyPanel`` as its own window, with Apply / Cancel and, for a queue, Stop Identifying.""" - def __init__(self, track, candidates, remaining: int = 0, parent=None): + # How long typing in Artist/Album rests before the cover is searched. + ART_DELAY_MS = 700 + + def __init__(self, track, candidates, remaining: int = 0, parent=None, + find_art: bool = False, embed_art: bool = True): super().__init__(parent) self.setWindowTitle("Identify Track") # True when the user pressed "Stop Identifying" on a queued batch. self.cancel_all = False + self.selected_image: bytes | None = None + self.selected_mime = "image/jpeg" layout = QVBoxLayout(self) + top = QHBoxLayout() self.panel = IdentifyPanel(track, candidates, self) - layout.addWidget(self.panel) + top.addWidget(self.panel, 1) + self.art = None + if find_art: + self._embed_art = embed_art + self.art = ArtPicker("Embed this artwork", parent=self) + top.addSpacing(12) + top.addWidget(self.art) + self._art_timer = QTimer(self) + self._art_timer.setSingleShot(True) + self._art_timer.setInterval(self.ART_DELAY_MS) + self._art_timer.timeout.connect(self._search_art) + self.panel.proposal_changed.connect(self._art_timer.start) + self.panel._combo.currentIndexChanged.connect( + lambda _i: self._search_art()) + self._search_art() + layout.addLayout(top) # What the tests reach into. self._header = self.panel._header self._combo = self.panel._combo @@ -169,10 +214,30 @@ class IdentifyDialog(QDialog): buttons.addButton(stop_btn, QDialogButtonBox.ButtonRole.ActionRole) stop_btn.clicked.connect(self._stop_all) - buttons.accepted.connect(self.accept) + buttons.accepted.connect(self._on_accept) buttons.rejected.connect(self.reject) layout.addWidget(buttons) + def art_query(self) -> tuple[str, str] | None: + """(artist, album) the proposal would leave the song with.""" + artist = self.panel.value("album_artist") or self.panel.value("artist") + album = self.panel.value("album") + return (artist, album) if artist and album else None + + def _search_art(self): + self._art_timer.stop() + query = self.art_query() + if query is None: + self.art.clear() + elif query != self.art.query: + self.art.search(*query, embed_by_default=self._embed_art) + + def _on_accept(self): + chosen = self.art.selected() if self.art is not None else None + if chosen: + self.selected_image, self.selected_mime = chosen + self.accept() + def _stop_all(self): self.cancel_all = True self.reject() diff --git a/lintunes/gui/main_window.py b/lintunes/gui/main_window.py index 1d133f4..ace4cd6 100644 --- a/lintunes/gui/main_window.py +++ b/lintunes/gui/main_window.py @@ -2044,13 +2044,11 @@ class MainWindow(QMainWindow): # The edit funnel writes the tags, may relocate the files, and # records the whole list as one undo step. self._manager.edit_many_track_fields(edits) - if dialog.selected_image: - library = self._manager.library - tracks = [library.tracks[r.track.track_id] - for r in dialog.all_rows() + library = self._manager.library + for rows, image, mime in dialog.selected_art(): + tracks = [library.tracks[r.track.track_id] for r in rows if r.track.track_id in library.tracks] - self._embed_album_art(tracks, dialog.selected_image, - dialog.selected_mime) + self._embed_album_art(tracks, image, mime) if edits: self.statusBar().showMessage( f"Updated tags for {len(edits)} song(s)", 6000) @@ -2064,14 +2062,34 @@ class MainWindow(QMainWindow): for i, row in enumerate(rows): track = self._manager.library.tracks[row.track.track_id] dialog = IdentifyDialog(track, row.candidates, - remaining=len(rows) - i - 1, parent=self) + remaining=len(rows) - i - 1, parent=self, + find_art=True, + embed_art=not self._has_artwork(track)) if dialog.exec(): fields = dialog.result_fields() if fields: self._manager.edit_track_fields(track.track_id, fields) + self._embed_identified_art(track, dialog) elif dialog.cancel_all: return + @staticmethod + def _has_artwork(track) -> bool: + """Whether the file already carries a cover: then Identify's own + cover search shows one, but doesn't tick Embed by itself.""" + return bool(track.location + and tagging.read_embedded_artwork(track.location)) + + def _embed_identified_art(self, track, dialog): + """The cover an Identify window's Embed box was ticked over. After + the tag edit, which may have moved the file: read the track fresh.""" + if not dialog.selected_image: + return + track = self._manager.library.tracks.get(track.track_id) + if track is not None: + self._embed_album_art([track], dialog.selected_image, + dialog.selected_mime) + def _when_app_active(self, show): """Run ``show`` (which opens a window over this one) now if LinTunes is the app in front, else once it is. A dialog parented to the main @@ -2701,7 +2719,8 @@ class MainWindow(QMainWindow): if track.track_id in self._manager.library.tracks: dialog = IdentifyDialog(track, candidates, remaining=len(self._identify_queue), - parent=self) + parent=self, find_art=True, + embed_art=not self._has_artwork(track)) accepted = dialog.exec() if accepted: fields = dialog.result_fields() @@ -2711,6 +2730,7 @@ class MainWindow(QMainWindow): self._manager.edit_track_fields(track.track_id, fields) self.statusBar().showMessage( f"Updated tags for “{track.name}”", 5000) + self._embed_identified_art(track, dialog) elif dialog.cancel_all: self._identify_queue.clear() self._identify_running = False diff --git a/tests/test_round119.py b/tests/test_round119.py new file mode 100644 index 0000000..55e2922 --- /dev/null +++ b/tests/test_round119.py @@ -0,0 +1,161 @@ +"""Round 119: the Identify windows find the album art too. + +- One song: the Identify window searches a cover for the album its grid + proposes, and searches again when the proposal changes. +- Embed ticks itself only when the song has no cover yet. +- A playlist batch gets a cover per album: one search at a time, a Cover + column, the selected song's album beside the table. +""" +import pytest +from PyQt6.QtCore import QBuffer, QByteArray, QIODevice, QObject, pyqtSignal +from PyQt6.QtGui import QImage + +from lintunes.art_search import ArtCandidate +from lintunes.fingerprint import IdentifyCandidate +from lintunes.gui import art_picker +from lintunes.gui.identify_batch_dialog import IdentifyBatchDialog +from lintunes.gui.identify_dialog import IdentifyDialog +from lintunes.identify_batch import analyze +from lintunes.models.track import Track + + +class _Signals(QObject): + search_finished = pyqtSignal(object) + image_finished = pyqtSignal(object) + + +@pytest.fixture +def fetchers(monkeypatch): + made = [] + + class _Fetcher: + def __init__(self): + self._s = _Signals() + self.search_finished = self._s.search_finished + self.image_finished = self._s.image_finished + self.searched, self.fetched = [], [] + made.append(self) + + def search(self, artist, album): + self.searched.append((artist, album)) + + def fetch(self, candidate): + self.fetched.append(candidate) + monkeypatch.setattr(art_picker, "AlbumArtFetcher", _Fetcher) + return made + + +def _png(): + image = QImage(4, 4, QImage.Format.Format_RGB32) + image.fill(0x00ff00) + data = QByteArray() + buf = QBuffer(data) + buf.open(QIODevice.OpenModeFlag.WriteOnly) + image.save(buf, "PNG") + return bytes(data) + + +def _c(name, album, artist="Digable Planets", score=0.9): + return IdentifyCandidate(score=score, source="acoustid", name=name, + artist=artist, album=album) + + +def _answer(fetcher, album="Reachin'"): + art = ArtCandidate("Digable Planets", album, "http://x/a.jpg") + fetcher.search_finished.emit({"candidates": [art]}) + fetcher.image_finished.emit({"candidate": art, "image": _png(), + "mime": "image/png"}) + + +def test_one_song_searches_the_proposed_album(qapp, fetchers): + track = Track(track_id=1, name="rebirth of slick [abc123]") + dialog = IdentifyDialog(track, [_c("Rebirth of Slick", "Reachin'"), + _c("Rebirth of Slick", "Best Of")], + find_art=True) + assert fetchers[-1].searched == [("Digable Planets", "Reachin'")] + _answer(fetchers[-1]) + assert dialog.art._embed.isChecked() + dialog._on_accept() + assert dialog.selected_image == _png() + assert dialog.selected_mime == "image/png" + + +def test_another_candidate_searches_again_and_old_answers_are_ignored( + qapp, fetchers): + track = Track(track_id=1, name="x") + dialog = IdentifyDialog(track, [_c("Song", "Reachin'"), + _c("Song", "Best Of")], find_art=True) + first = fetchers[-1] + dialog.panel._combo.setCurrentIndex(1) + assert fetchers[-1].searched == [("Digable Planets", "Best Of")] + _answer(first) # the old search, late + assert dialog.art.image() is None + dialog._on_accept() + assert dialog.selected_image is None + + +def test_typing_an_album_searches_after_a_pause(qapp, fetchers): + track = Track(track_id=1, name="x") + dialog = IdentifyDialog(track, [_c("Song", "")], find_art=True) + assert fetchers == [] # nothing to search by + album = dialog.panel._editors["album"] + dialog.panel._checks["album"].setEnabled(True) + dialog.panel._checks["album"].setChecked(True) + album.setText("Blowout Comb") + assert fetchers == [] # still typing + dialog._art_timer.timeout.emit() + assert fetchers[-1].searched == [("Digable Planets", "Blowout Comb")] + + +def test_a_song_with_a_cover_isnt_ticked_to_replace_it(qapp, fetchers): + track = Track(track_id=1, name="x") + dialog = IdentifyDialog(track, [_c("Song", "Reachin'")], find_art=True, + embed_art=False) + _answer(fetchers[-1]) + assert not dialog.art._embed.isChecked() + dialog._on_accept() + assert dialog.selected_image is None + + +def test_plain_identify_dialog_searches_nothing(qapp, fetchers): + dialog = IdentifyDialog(Track(track_id=1, name="x"), + [_c("Song", "Reachin'")]) + assert dialog.art is None and fetchers == [] + + +def test_a_playlist_gets_a_cover_per_album_one_search_at_a_time( + qapp, fetchers): + analysis = analyze([ + (Track(track_id=1), [_c("A", "Reachin'")]), + (Track(track_id=2), [_c("B", "Blowout Comb")]), + (Track(track_id=3), [_c("C", "Reachin'")]), + (Track(track_id=4), []), # nothing to search by + ]) + dialog = IdentifyBatchDialog(analysis, None) + assert not analysis.is_album + assert [f.searched for f in fetchers] == [ + [("Digable Planets", "Reachin'")]] + _answer(fetchers[0]) + assert [f.searched for f in fetchers][1:] == [ + [("Digable Planets", "Blowout Comb")]] + + rows = {r.track.track_id: i for i, r in enumerate(dialog._rows)} + cover = dialog._cover_col + assert not dialog._table.item(rows[1], cover).icon().isNull() + assert not dialog._table.item(rows[3], cover).icon().isNull() + assert dialog._table.item(rows[2], cover).icon().isNull() + + dialog._table.selectRow(rows[2]) + assert dialog._cover_stack.currentWidget() is \ + dialog._pickers[("digable planets", "blowout comb")] + dialog._table.selectRow(rows[4]) + assert dialog._cover_stack.currentWidget() is dialog._no_album + + [(art_rows, image, _mime)] = dialog.selected_art() + assert sorted(r.track.track_id for r in art_rows) == [1, 3] + assert image == _png() + + # Unticking Embed takes the thumbnails away and the cover with them. + dialog._pickers[("digable planets", "reachin'")]._embed.setChecked(False) + assert dialog._table.item(rows[1], cover).icon().isNull() + assert dialog.selected_art() == [] diff --git a/tests/test_round77.py b/tests/test_round77.py index a3e0ec0..e09d18d 100644 --- a/tests/test_round77.py +++ b/tests/test_round77.py @@ -14,7 +14,7 @@ from PyQt6.QtCore import Qt from lintunes import identify_batch from lintunes.fingerprint import IdentifyCandidate -from lintunes.gui import identify_batch_dialog as dialog_module +from lintunes.gui import art_picker as dialog_module from lintunes.gui.identify_batch_dialog import ( IdentifyBatchDialog, format_cell, parse_cell, ) @@ -183,7 +183,7 @@ def test_the_album_window_applies_ticked_rows(qapp, no_network): assert [r.track.track_id for r in dialog.unchecked_rows()] == [2] dialog._on_apply() assert dialog.outcome == dialog.APPLY - assert dialog.selected_image is None # no art loaded + assert dialog.selected_art() == [] # no art loaded def test_art_arrives_ticked_and_is_handed_over(qapp, no_network): @@ -200,21 +200,23 @@ def test_art_arrives_ticked_and_is_handed_over(qapp, no_network): analysis = _album_analysis() dialog = IdentifyBatchDialog(analysis, ("The Breeders", "Last Splash")) art = ArtCandidate("The Breeders", "Last Splash", "http://x/a.jpg") - dialog._on_art_search({"candidates": [art]}) - dialog._on_art_image({"candidate": art, "image": bytes(data), - "mime": "image/png"}) - assert dialog._embed.isChecked() + dialog._art._on_search({"candidates": [art]}) + dialog._art._on_image({"candidate": art, "image": bytes(data), + "mime": "image/png"}) + assert dialog._art._embed.isChecked() dialog._on_apply() - assert dialog.selected_image == bytes(data) - assert dialog.selected_mime == "image/png" + [(rows, image, mime)] = dialog.selected_art() + assert len(rows) == 2 + assert image == bytes(data) and mime == "image/png" def test_a_playlist_window_has_no_album_panel(qapp, no_network): analysis = analyze([(_t(1), [_c("A", "One")]), (_t(2), [_c("B", "Two")])]) dialog = IdentifyBatchDialog(analysis, None) - assert dialog._album_edit is None and dialog._embed is None - assert no_network == [] + assert dialog._album_edit is None and dialog._art is None + # A cover per album instead (Round 119), searched one at a time. + assert no_network == [("The Breeders", "One")] dialog._on_review_all() assert dialog.outcome == dialog.REVIEW_ALL @@ -319,7 +321,8 @@ def test_a_batch_review_applies_then_reviews_the_unticked(window, qapp, class _Batch: APPLY, REVIEW_ALL = 1, 2 outcome = 1 - selected_image = None + def selected_art(self): + return [] def __init__(self, analysis, query, parent): pass def exec(self):