192 lines
6.9 KiB
Python
192 lines
6.9 KiB
Python
"""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
|