Files
lintunes/lintunes/gui/main_window.py
T

3670 lines
166 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import logging
import shutil
import threading
from pathlib import Path
from PyQt6.QtWidgets import (
QMainWindow, QSplitter, QStackedWidget, QWidget, QVBoxLayout, QLineEdit,
QPlainTextEdit, QTextEdit, QAbstractSpinBox, QComboBox, QApplication,
QLabel, QMessageBox, QFileDialog, QProgressBar, QPushButton, QDialog,
QDialogButtonBox, QHBoxLayout, QMenu,
)
from PyQt6.QtCore import QRect, Qt, QEvent, QObject, QTimer, pyqtSignal
from PyQt6.QtGui import QAction, QKeySequence
from lintunes import paths as os_paths
from lintunes import (bpm_detect, device_sync, loudness, music_folder, shazam,
tagging, theme, url_import)
from lintunes import playlist_art
from lintunes.andtunes import layout as andtunes_layout
from lintunes.andtunes import install as andtunes_install
from lintunes.andtunes import sync as andtunes_sync
from lintunes.art_search import AlbumArtFetcher
from lintunes.airplay.controller import AirPlayController
from lintunes.cast.controller import CastController
from lintunes.eventlog import log_control
from lintunes.config import load_config, save_config
from lintunes.export import exporter, upload
from lintunes.fingerprint import TrackIdentifier, fpcalc_available
from lintunes.inhibit import INHIBIT_LOGOUT, INHIBIT_SUSPEND, SleepInhibitor
from lintunes.player import Player
from lintunes.storage import listen_history
from lintunes.importers import file_importer, lossless
from lintunes.gui.album_art_dialog import AlbumArtDialog
from lintunes.gui.art_ops import embed_artwork
from lintunes.gui.cast_dialog import AirPlayDialog, ChromecastDialog
from lintunes.gui.cassette_ui import CassetteUi
from lintunes.gui import menu_bar, sounds, titlebar
from lintunes.gui.device_sync_dialog import (
DeviceSyncSettingsDialog, resolve_sync_playlists,
)
from lintunes.gui.export_dialog import ExportKindDialog, WebMixDialog
from lintunes.gui.identify_batch_dialog import IdentifyBatchDialog
from lintunes.gui.identify_dialog import IdentifyDialog
from lintunes.identify_batch import (
IdentifyCollector, album_art_query, analyze,
)
from lintunes.gui.sidebar import SIDEBAR_INSET, SidebarPanel
from lintunes.gui.library_view import LibraryView
from lintunes.gui.playlist_view import PlaylistView
from lintunes.gui.transport import TransportBar
from lintunes.gui.url_import_dialog import UrlImportDialog
from lintunes.gui.url_import_progress import UrlImportProgress
from lintunes.gui.shazam_import import ShazamImportWindow, ShazamPreviewDialog
from lintunes.gui import web_upload_progress as web_progress
from lintunes.gui.info_dialog import InfoDialog
from lintunes.gui.playlist_info_dialog import PlaylistInfoDialog
from lintunes.gui.music_folder_dialog import MusicFolderDialog
from lintunes.gui.preferences_dialog import PreferencesDialog
from lintunes.gui.track_table import format_total_time
from lintunes.gui.version_button import VersionButton
from lintunes.updater import Updater
def album_tracks(library, artist: str, album: str) -> list:
"""Every library track on the given album (case-insensitive match on
album name + album artist, falling back to track artist — the same
grouping the art download uses)."""
artist_cf, album_cf = artist.casefold(), album.casefold()
return [t for t in library.tracks.values()
if t.album.casefold() == album_cf
and (t.album_artist or t.artist).casefold() == artist_cf]
class _StatusLabel(QLabel):
"""The status bar's transfer line, which also answers a click."""
clicked = pyqtSignal()
def mouseReleaseEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton:
self.clicked.emit()
super().mouseReleaseEvent(event)
class _CancelSyncButton(QPushButton):
"""Compact "✕" in the status bar's right corner that expands to say what
it does ("cancel transfer") while hovered, then shrinks back. Expanding
pushes the progress bar and label left; the button itself stays put.
Always the shared button face, only shrunk to fit the status bar."""
def __init__(self, parent=None):
super().__init__(parent)
self.setFocusPolicy(Qt.FocusPolicy.NoFocus)
self.setToolTip("Cancel the transfer")
self.setStyleSheet("QPushButton { padding: 0 4px; min-height: 0; }")
self._apply("✕")
def _apply(self, text: str):
self.setText(text)
self.setFixedWidth(self.fontMetrics().horizontalAdvance(text) + 14)
def enterEvent(self, event):
self._apply("cancel transfer")
super().enterEvent(event)
def leaveEvent(self, event):
self._apply("✕")
super().leaveEvent(event)
class _ResetRelay(QObject):
"""Carries reset_mtp_connection's answer back to the GUI thread."""
done = pyqtSignal(object)
# Import Shazams' default target: whatever playlist is current.
_CURRENT_TARGET = object()
def _as_jpeg_or_png(data: bytes) -> bytes:
"""A cover as playlist_art keeps it: JPEG or PNG as given, anything Qt
can read (WebP, GIF, BMP…) re-encoded as PNG."""
if playlist_art.image_suffix(data):
return data
from PyQt6.QtCore import QBuffer, QByteArray, QIODevice
from PyQt6.QtGui import QImage
image = QImage()
if not image.loadFromData(data):
raise ValueError("not an image")
out = QByteArray()
buffer = QBuffer(out)
buffer.open(QIODevice.OpenModeFlag.WriteOnly)
image.save(buffer, "PNG")
return bytes(out)
class MainWindow(QMainWindow):
# A playlist's cover finished downloading (emitted off the GUI thread).
_playlist_art_saved = pyqtSignal(str)
def __init__(self, manager, prefs, lastfm=None, parent=None):
super().__init__(parent)
self._manager = manager
self._prefs = prefs
self._lastfm = lastfm
self._prefs_dialog = None
self.player = Player(manager, self)
# Volume normalization measures each song with ffmpeg as it comes up;
# nothing is measured while it's off (the default, and in tests).
self.player.loudness = loudness.LoudnessAnalyzer(parent=self)
# A tag or art save on the playing song mustn't shift the audio
# under the decoder (tagging._editable).
tagging.in_use = self._files_in_use
# Owns the cast session, if any. Built before the transport bar, which
# takes it to drive the little cast indicator under the volume slider.
self._cast = CastController(self.player, self)
# The same for AirPlay. At most one of the two is ever connected:
# connecting either disconnects the other first.
self._airplay = AirPlayController(self.player, self)
# Where the Rabbit is, found off the GUI thread: a wedged gvfs-MTP
# mount blocks any listing of it forever (Round 71). Nothing probes
# until the Connections menu opens.
self._devices = device_sync.DeviceWatcher(parent=self)
self._devices.changed.connect(self._refresh_device_actions)
# Keep the machine awake while audio is actually playing.
self._inhibitor = SleepInhibitor()
# Context playback started from: "library" or "playlist:<pid>". Scopes
# the now-playing speaker icon to where the song is actually playing.
self._now_playing_context = ""
# The context the *playing* track came from. _now_playing_context
# moves to the new one before the old listen is closed.
self._listen_context = ""
# Friend sharing's menu group and dialogs. Its background service is
# started by run_gui (host machine only), never by constructing the
# window — tests build windows by the dozen.
self._cassette = CassetteUi(self, prefs, manager)
self.setWindowTitle("LinTunes")
# The title bar stays blank: the song is in the now-playing panel
# right under it (the title still names the window to the desktop).
self.setProperty(titlebar.BLANK_TITLE, True)
self.resize(1280, 800)
# Keep the window's minimum well under typical sizes so the WM never
# refuses an interactive shrink
self.setMinimumSize(560, 420)
self.setAcceptDrops(True)
central = QWidget()
layout = QVBoxLayout(central)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
self.setCentralWidget(central)
self._transport = TransportBar(self.player, manager, self._prefs,
cast=self._cast, airplay=self._airplay)
layout.addWidget(self._transport)
# DJ mode (Round 93): the shelf is made the first time it opens.
self._dj = None
self._dj_prep_worker = None
self._dj_on = False
self._dj_pin = None # (track id, ms, was playing) to go back to
self._dj_anim = None
self._dj_resize_from = None
self._transport.dj_toggled.connect(self.set_dj_mode)
splitter = QSplitter(Qt.Orientation.Horizontal)
# The handle is the gap between the playlists and the songs: as wide
# as the strip left of the playlists, so they sit evenly spaced.
splitter.setHandleWidth(SIDEBAR_INSET)
layout.addWidget(splitter, stretch=1)
self._sidebar = SidebarPanel(manager, self.player)
self._sidebar.setMinimumWidth(140)
splitter.addWidget(self._sidebar)
self._content = QStackedWidget()
# The same strip of bare window on the right as the sidebar keeps on
# the left, so the lists sit symmetrically in the window.
self._content.setContentsMargins(0, 0, SIDEBAR_INSET, 0)
splitter.addWidget(self._content)
splitter.setSizes([220, 1060])
splitter.setCollapsible(1, False)
self._library_view = LibraryView(manager)
self._content.addWidget(self._library_view)
self._library_view.search_changed.connect(
self._sidebar.tree.set_filter)
self._playlist_view = PlaylistView(manager)
self._content.addWidget(self._playlist_view)
self._content.setCurrentWidget(self._library_view)
# The header row under the transport boxes: the Library button over
# the sidebar, then whichever view is showing's own header (search
# box, playlist name), then the seek row.
self._transport.set_sidebar_header(self._sidebar.header)
self._transport.track_split(self._sidebar.list_area, self._content)
self._content.currentChanged.connect(self._mount_view_header)
self._mount_view_header()
# Moving the Library button out of the sidebar put it last in the
# focus chain, and a playlist tree that takes the first focus selects
# its first playlist: the window would open on that, not the library.
self._sidebar.library_button.setFocus()
# Bottom status bar, left to right: version/self-update button, then a
# centered totals readout. Both are non-permanent widgets, so a
# transient showMessage (import/scrobble/error/update text) replaces
# them for its duration and they come back — a permanent widget with
# stretch would squeeze the message area to zero width and swallow
# every message.
self.restart_requested = False # run_gui re-execs when True on quit
self._missing_folder_prompted = False
self._updater = Updater(self)
self._version_button = VersionButton(self._updater)
self.statusBar().addWidget(self._version_button)
self._totals_label = QLabel()
self._totals_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.statusBar().addWidget(self._totals_label, 1)
self._version_button.status_message.connect(
lambda msg: self.statusBar().showMessage(msg, 8000))
self._updater.update_applied.connect(self._restart_for_update)
self._updater.start_checking()
# Device-sync progress, right-justified: permanent widgets sit on the
# status bar's right and survive showMessage. No stretch (see above)
# and hidden while idle so it costs no space. Text lives in its own
# label — QProgressBar's overlay can't fit a sentence at this width.
# The group is laid out left to right but justified right, so whatever
# is added *last* owns the corner and never moves. The cancel button
# goes there deliberately: it is the one widget the user aims at, and
# the label beside it is as wide as the song title of the moment.
self._sync_label = _StatusLabel()
self._sync_label.hide()
# A click brings back a hidden link-import progress window.
self._sync_label.clicked.connect(self._show_url_progress)
self._sync_label.clicked.connect(self._show_web_progress)
self._sync_label.clicked.connect(self._show_compress_progress)
self.statusBar().addPermanentWidget(self._sync_label)
self._sync_progress = QProgressBar()
self._sync_progress.setFixedWidth(160)
self._sync_progress.setTextVisible(False)
self._sync_progress.hide()
self.statusBar().addPermanentWidget(self._sync_progress)
self._sync_cancel = _CancelSyncButton()
self._sync_cancel.hide()
self._sync_cancel.clicked.connect(self._confirm_cancel_sync)
self.statusBar().addPermanentWidget(self._sync_cancel)
self._andtunes_worker = None
self._andtunes_planner = None
# Full Rabbit Sync: the playlist target Import Shazams will use once
# the music sync is over (latched at the click), or None.
self._full_sync_target = None
self._full_sync_pending = False
self._install_worker = None
self._sync_device_name = ""
# Export shares the status-bar progress widgets with device sync —
# only one of the two may run at a time (each guards on the other).
self._export_worker = None
# Export Web Mix → Upload to web server: check the server, export into
# staging, rsync. _web_upload holds the run's host/folder/plan while
# it lasts; the window is non-modal and outlives a Hide.
self._server_check = None
self._upload_worker = None
self._web_upload = None
self._web_progress = None
# Identify Track… works through its selection one at a time, each
# behind its own review dialog.
self._identify_queue = []
self._identify_total = 0
self._identifier = None
# True from the first lookup until the queue drains, so tracks queued
# mid-run (Import from URL) wait their turn instead of starting a
# second lookup alongside.
self._identify_running = False
# Import from URL: also shares the status-bar progress widgets.
self._url_worker = None
# Calculate BPM: also shares the status-bar progress widgets.
self._bpm_worker = None
# A compressing import (gui/compress_import.py), from start until
# Done or Cancel — which can be after its worker has finished.
self._compress = None
self._boost = None # boost.BoostWorker while one runs
self._boost_typical = 0.0
self._compress_reload = QTimer(self)
self._compress_reload.setSingleShot(True)
self._compress_reload.setInterval(400)
self._compress_reload.timeout.connect(self._library_view_reload)
self._bpm_results: dict[int, int] = {}
self._url_target = None # url_import.ImportTarget, or None
self._url_inserted = 0 # songs added to the target so far
# "Make a new playlist of these songs": its name until the first
# song lands, then the playlist's pid (made then, so a link that
# downloads nothing leaves no empty playlist behind).
self._url_new_name = ""
self._url_new_cover = ""
self._url_source = ""
self._url_new_pid = ""
self._url_rows = None # a Spotify/Apple list, in order
self._url_owned = 0
self._url_placed = 0
self._url_current = ""
self._url_imported = 0
self._url_identify = True # False after "Stop Identifying"
self._url_note = ""
self._url_progress = None # UrlImportProgress, for several songs
# Several songs are looked up quietly while they download, and
# reviewed together once the last one has landed.
self._url_batch = None # identify_batch.IdentifyCollector
# Import Shazams runs as a URL import (it owns _url_worker and
# _url_progress), with its own window and its own lookup queue, so
# Identify proposals appear in that window as songs land.
self._shazam_window = None
self._shazam_identify: list = [] # (request id, track) to look up
self._shazam_identifier = None # the TrackIdentifier running
# Popups waiting for LinTunes to be the app in front (they must
# never land on top of another app).
self._popups_waiting: list = []
self._popups_hooked = False
# Separate instance from the playback inhibitor: pausing music
# mid-sync must not drop the sync's hold. Logout flag included so
# GNOME's shutdown/restart dialog names the transfer as the blocker.
self._sync_inhibitor = SleepInhibitor(
reason="Syncing a playlist to a device",
flags=INHIBIT_LOGOUT | INHIBIT_SUSPEND)
self._export_inhibitor = SleepInhibitor(
reason="Exporting a playlist",
flags=INHIBIT_LOGOUT | INHIBIT_SUSPEND)
# Wiring
self._transport.play_clicked.connect(self.play_pause)
self._transport.now_playing_clicked.connect(self._go_to_current_song)
self._transport.speakers_clicked.connect(self._show_speaker_menu)
self._transport.identify_clicked.connect(self._identify_from_toolbar)
self._sidebar.library_selected.connect(self._show_library)
self._sidebar.friend_selector_clicked.connect(
self._cassette.show_friend_menu)
self._sidebar.playlist_selected.connect(self._show_playlist)
self._sidebar.tree.export_requested.connect(self._export_playlist)
self._sidebar.tree.dj_prepare_requested.connect(self._prepare_playlist_for_dj)
self._sidebar.tree.info_requested.connect(self._playlist_info)
self._sidebar.art.download_art_requested.connect(
lambda tid: self._download_album_art([tid]))
self._content.currentChanged.connect(self._update_totals)
self._content.currentChanged.connect(self._update_playlist_art)
self._playlist_art_saved.connect(self._update_playlist_art)
for view in (self._library_view, self._playlist_view):
view.play_requested.connect(
lambda ids, start, v=view: self._play_from_view(v, ids, start))
view.info_requested.connect(self._show_info)
view.show_in_playlist_requested.connect(self._show_track_in_playlist)
view.table.tracks_changed.connect(self._update_totals)
view.table.download_art_requested.connect(self._download_album_art)
view.table.identify_requested.connect(self._identify_tracks)
view.table.bpm_requested.connect(self._calculate_bpm)
view.table.convert_requested.connect(self._convert_to_mp3)
view.table.boost_requested.connect(self._boost_volume)
view.table.dj_prepare_requested.connect(self._prepare_for_dj)
view.table.remove_from_library_requested.connect(
lambda ids: self._delete_tracks(ids, delete_files=False))
view.table.delete_from_library_requested.connect(
lambda ids: self._delete_tracks(ids, delete_files=True))
self._playlist_view.files_dropped.connect(self._import_files_to_playlist)
manager.tracks_removed.connect(self._on_tracks_removed)
manager.tracks_restored.connect(self._on_tracks_restored)
self.player.error_occurred.connect(
lambda msg: QMessageBox.warning(self, "Can't play track", msg))
self.player.track_missing.connect(self._on_track_missing)
self.player.track_changed.connect(self._on_track_changed)
self.player.listen_ended.connect(self._on_listen_ended)
self.player.playing_changed.connect(self._update_now_playing_icon)
self.player.playing_changed.connect(self._on_playing_changed)
manager.track_updated.connect(self._on_track_meta_updated)
manager.tag_write_failed.connect(
lambda name, err: self.statusBar().showMessage(
f"Couldn't write tags to “{name}”: {err}", 8000))
manager.file_move_failed.connect(
lambda name, err: self.statusBar().showMessage(
f"Couldn't move the file for “{name}”: {err}", 8000))
self.player.track_unplayable.connect(self._on_track_unplayable)
self._cast.connecting.connect(self._on_cast_connecting)
self._cast.connected.connect(self._on_cast_connected)
self._cast.disconnected.connect(self._on_cast_disconnected)
self._cast.failed.connect(
lambda msg: QMessageBox.warning(self, "Chromecast", msg))
self._airplay.connecting.connect(self._on_cast_connecting)
self._airplay.connected.connect(
lambda name: self.statusBar().showMessage(
f"Playing on {name} (AirPlay)", 6000))
self._airplay.disconnected.connect(
lambda reason: self.statusBar().showMessage(
reason or "Stopped AirPlay — playing here again", 8000))
# The toolbar's speakers button is lit while either plays.
for controller in (self._cast, self._airplay):
controller.connected.connect(self._show_speakers_state)
controller.disconnected.connect(self._show_speakers_state)
self._airplay.failed.connect(
lambda msg: QMessageBox.warning(self, "AirPlay", msg))
manager.library_reloaded.connect(self._on_library_reloaded)
manager.conflict_resolved.connect(self._on_conflict_resolved)
prefs.changed.connect(self._on_prefs_changed)
self._conflict_dialog = None
if lastfm is not None:
self.player.track_changed.connect(lastfm.handle_track_started)
self.player.track_finished.connect(lastfm.handle_track_finished)
lastfm.status_message.connect(
lambda msg: self.statusBar().showMessage(msg, 4000))
self._build_menus()
menu_bar.register_shortcuts(self, self.menuBar())
self._menu_bar = menu_bar.AltMenuBar(self, self._prefs)
self.apply_ui_metrics()
self._update_totals()
def _restart_for_update(self):
# The pull already succeeded. Route through close() — not a bare
# quit() — so closeEvent runs: it flushes the library, tears down the
# player, and can veto the restart while a device sync is copying.
self.restart_requested = True
if self.close():
QApplication.instance().quit()
else:
self.restart_requested = False
# ---- status bar totals ----
def _update_totals(self):
view = self._content.currentWidget()
count, total_ms = view.table.total_stats()
text = ""
if count:
noun = "track" if count == 1 else "tracks"
text = f"{count:,} {noun} · {format_total_time(total_ms)}"
# A friend's followed playlist also says when their folder last synced.
suffix = getattr(view, "status_suffix", None)
if suffix is not None and suffix():
text = f"{text} · {suffix()}" if text else suffix()
self._totals_label.setText(text)
# ---- preferences / theming ----
def _apply_normalize_pref(self):
on = bool(self._prefs.get("normalize_volume", False))
if on and not loudness.ffmpeg_available():
on = False
self.statusBar().showMessage(
"Volume normalization needs ffmpeg, which isn't installed.",
8000)
self.player.set_normalize(on)
if self._normalize_action.isChecked() != on:
self._normalize_action.blockSignals(True)
self._normalize_action.setChecked(on)
self._normalize_action.blockSignals(False)
def _on_prefs_changed(self):
self._apply_normalize_pref()
theme.apply_theme(QApplication.instance(), self._prefs)
self.apply_ui_metrics()
self._transport.refresh_theme()
self._version_button.refresh_theme()
self._sidebar.refresh_style()
if getattr(self, "_menu_bar", None) is not None:
self._menu_bar.apply()
dark = getattr(self, "_dark_action", None)
if dark is not None and dark.isChecked() != (theme.mode(self._prefs) == "dark"):
dark.blockSignals(True)
dark.setChecked(theme.mode(self._prefs) == "dark")
dark.blockSignals(False)
def _mount_view_header(self, _index=None):
view = self._content.currentWidget()
self._transport.set_view_header(getattr(view, "header", None))
def apply_ui_metrics(self):
metrics = theme.scale_metrics(self._prefs)
for view in (self._library_view, self._playlist_view):
view.table.verticalHeader().setDefaultSectionSize(metrics["row_height"])
self._sidebar.apply_metrics(metrics["header_strip"])
self._transport.set_header_height(metrics["header_strip"])
self.statusBar().setMinimumHeight(metrics["status_height"])
def _show_preferences(self):
if self._prefs_dialog is None:
self._prefs_dialog = PreferencesDialog(
self._prefs, self._lastfm, self,
music_folder=self._music_folder_summary,
on_music_folder_change=self._change_music_folder)
else:
self._prefs_dialog.refresh_music_folder()
self._prefs_dialog.show()
self._prefs_dialog.raise_()
self._prefs_dialog.activateWindow()
def _build_menus(self):
bar = self.menuBar()
file_menu = bar.addMenu("&File")
self._add_action(file_menu, "New Playlist", "Ctrl+N",
lambda: self._sidebar.tree.create_playlist_interactive())
self._add_action(file_menu, "New Smart Playlist", "Ctrl+Alt+N",
lambda: self._sidebar.tree.create_smart_playlist_interactive())
self._add_action(file_menu, "New Playlist Folder", "Ctrl+Shift+N",
lambda: self._sidebar.tree.create_folder_interactive())
file_menu.addSeparator()
self._add_action(file_menu, "Add Files to Library…", "Ctrl+O",
self._open_files_dialog)
self._url_import_action = self._add_action(
file_menu, "Import from URL…", "", self._import_from_url)
self._export_action = self._add_action(
file_menu, "Export Playlist…", "", self._export_playlist)
file_menu.aboutToShow.connect(self._refresh_export_action)
file_menu.aboutToShow.connect(self._refresh_url_import_action)
file_menu.addSeparator()
quit_action = self._add_action(file_menu, "Quit", "Ctrl+Q", self.close)
# On a Mac these two move to the app menu ("LinTunes ▸ Settings…",
# "Quit LinTunes"); elsewhere the role does nothing.
quit_action.setMenuRole(QAction.MenuRole.QuitRole)
edit_menu = bar.addMenu("&Edit")
self._undo_action = self._add_action(
edit_menu, "Undo", QKeySequence.StandardKey.Undo,
self._manager.undo_stack.undo)
self._redo_action = self._add_action(
edit_menu, "Redo", QKeySequence.StandardKey.Redo,
self._manager.undo_stack.redo)
# Accept both the platform default (Ctrl+Y) and Ctrl+Shift+Z for redo.
self._redo_action.setShortcuts([
QKeySequence(QKeySequence.StandardKey.Redo),
QKeySequence("Ctrl+Shift+Z"),
])
edit_menu.addSeparator()
prefs_action = self._add_action(
edit_menu, "Preferences…", "Ctrl+,", self._show_preferences)
prefs_action.setMenuRole(QAction.MenuRole.PreferencesRole)
self._manager.undo_stack.changed.connect(self._refresh_undo_actions)
self._refresh_undo_actions()
controls = bar.addMenu("&Controls")
self._add_action(controls, "Play/Pause", "", self.play_pause)
self._add_action(controls, "Next", "", self.player.next)
self._add_action(controls, "Previous", "", self.player.previous)
controls.addSeparator()
self._normalize_action = QAction("Normalize Volume", self)
self._normalize_action.setCheckable(True)
self._normalize_action.toggled.connect(
lambda on: self._prefs.set("normalize_volume", on))
controls.addAction(self._normalize_action)
self._apply_normalize_pref()
view_menu = bar.addMenu("&View")
self._add_action(view_menu, "Toggle Column Browser", "Ctrl+B",
self._library_view.toggle_browser)
# No platform convention for this; Ctrl+Shift+D leaves plain Ctrl+D
# (bookmark/duplicate/delete elsewhere) free, and is easy to hit.
self._dark_action = QAction("Dark Mode", self)
self._dark_action.setCheckable(True)
self._dark_action.setShortcut(QKeySequence("Ctrl+Shift+D"))
self._dark_action.setChecked(theme.mode(self._prefs) == "dark")
self._dark_action.toggled.connect(
lambda on: self._prefs.set("dark_mode", on))
view_menu.addAction(self._dark_action)
view_menu.addSeparator()
self._dj_action = QAction("DJ Mode", self)
self._dj_action.setCheckable(True)
self._dj_action.toggled.connect(self.set_dj_mode)
view_menu.addAction(self._dj_action)
view_menu.addSeparator()
view_menu.addAction("Customize Toolbar…",
lambda: self._transport.set_customizing(True))
track_menu = bar.addMenu("&Track")
self._add_action(track_menu, "Get Info", "Ctrl+I", self._info_for_current_view)
self._add_action(track_menu, "Go to Current Song", "Ctrl+L",
self._go_to_current_song)
# Mnemonic on the "n": Alt+C already belongs to &Controls.
connections_menu = bar.addMenu("Co&nnections")
self._andtunes_action = self._add_action(
connections_menu, "Sync Music to Rabbit", "",
self._sync_to_andtunes)
self._andtunes_action.setEnabled(False)
# The music sync, then Import Shazams as soon as it's over.
self._full_sync_action = self._add_action(
connections_menu, "Full Rabbit Sync", "", self._full_rabbit_sync)
self._full_sync_action.setEnabled(False)
self._sync_settings_action = self._add_action(
connections_menu, "Rabbit Sync Settings…", "",
self._show_device_sync_settings)
self._install_action = self._add_action(
connections_menu, "Install andTunes on Rabbit…", "",
self._install_andtunes)
self._shazam_action = self._add_action(
connections_menu, "Import Shazams…", "",
lambda: self._import_shazams())
if os_paths.IS_MAC:
# The Rabbit R1 features never exist on a Mac. The actions are
# kept (hidden) so everything that touches them still can.
for action in (self._andtunes_action, self._full_sync_action,
self._sync_settings_action, self._install_action,
self._shazam_action):
action.setVisible(False)
action.setEnabled(False)
# "Sync Playlist to Rabbit (Auxio)" was retired in Round 51, once
# andTunes could play what it syncs. device_sync's helpers stay: the
# export and andTunes code import them.
# Friend sharing (Cassette) sits between two separators of its own.
self._cassette.build_menu(connections_menu)
self._cast_action = self._add_action(
connections_menu, "Connect to Chromecast…", "", self._toggle_cast)
self._airplay_action = self._add_action(
connections_menu, "Connect to AirPlay…", "", self._toggle_airplay)
# Re-checked every time the menu opens. The device part is a
# background probe; its answer updates the open menu when it lands.
connections_menu.aboutToShow.connect(self._refresh_connection_actions)
@property
def cassette(self) -> CassetteUi:
return self._cassette
# What friend mode swaps in and out.
@property
def content_stack(self):
return self._content
@property
def sidebar(self):
return self._sidebar
def play_keys(self, keys, start, context):
"""Play a followed friend playlist (queue of friend-track keys)."""
self._now_playing_context = context
self.player.play_queue(keys, start)
@property
def now_playing_context(self) -> str:
return self._now_playing_context
def update_totals(self):
self._update_totals()
def refresh_library_view(self, _track_ids=None):
"""Songs arrived from somewhere other than an import dialog (a friend's
delivery): show them."""
self._library_view.reload()
def show_my_library(self):
self._sidebar.reflect_library()
self._show_library()
def _add_action(self, menu, text, shortcut, slot):
action = QAction(text, self)
if shortcut:
action.setShortcut(QKeySequence(shortcut))
action.triggered.connect(slot)
menu.addAction(action)
return action
def _refresh_undo_actions(self):
stack = self._manager.undo_stack
can_undo = stack.can_undo()
can_redo = stack.can_redo()
self._undo_action.setEnabled(can_undo)
self._redo_action.setEnabled(can_redo)
self._undo_action.setText(
f"Undo {stack.undo_label()}" if can_undo else "Undo")
self._redo_action.setText(
f"Redo {stack.redo_label()}" if can_redo else "Redo")
# ---- connections: device sync ----
def _refresh_connection_actions(self):
# An export in flight owns the same status-bar widgets, so it blocks
# a sync just as another sync would.
if not os_paths.IS_MAC: # no Rabbit on a Mac: never probe for one
self._devices.probe()
self._refresh_device_actions()
self._cassette.refresh_menu()
if not os_paths.IS_MAC:
# Enabled whenever there's an APK to offer; the click finds the
# Rabbit (adb or MTP) and says so if it can't — cheaper than
# asking adb on every menu open.
self._install_action.setEnabled(
andtunes_install.bundled_apk() is not None
and not (self._install_worker is not None
and self._install_worker.busy()))
self._shazam_action.setEnabled(self._busy_worker() is None)
# The self-updater ships code but not dependencies, so a machine that
# has pulled this round hasn't necessarily installed pychromecast (or
# pyatv) yet.
for action, controller, text in (
(self._cast_action, self._cast, "Connect to Chromecast…"),
(self._airplay_action, self._airplay, "Connect to AirPlay…")):
if controller.is_connected():
action.setText(f"Disconnect from {controller.device_name()}")
action.setEnabled(True)
action.setToolTip("")
continue
action.setText(text)
available, why = controller.is_available()
action.setEnabled(available)
action.setToolTip(
"" if available else f"{why} — run: pip install -e .")
# ---- connections: casting ----
def _toggle_cast(self):
if self._cast.is_connected():
self._cast.disconnect()
return
available, why = self._cast.is_available()
if not available:
QMessageBox.information(
self, "Chromecast support not installed",
f"{why}.\n\nRun “pip install -e .” in the lintunes checkout, "
"then restart LinTunes.")
return
dialog = ChromecastDialog(self._cast.discovery(), self)
if dialog.exec() and dialog.selected_device is not None:
self._airplay.disconnect()
self._cast.connect_to(dialog.selected_device)
def _toggle_airplay(self):
if self._airplay.is_connected():
self._airplay.disconnect()
return
available, why = self._airplay.is_available()
if not available:
QMessageBox.information(
self, "AirPlay support not installed",
f"{why}.\n\nRun “pip install -e .” in the lintunes checkout "
"(and install ffmpeg if it's missing), then restart LinTunes.")
return
dialog = AirPlayDialog(self._airplay.discovery(), self)
if dialog.exec() and dialog.selected_device is not None:
self._cast.disconnect()
self._airplay.connect_to(dialog.selected_device)
def _show_speaker_menu(self, button):
"""The toolbar's speakers button: Connections' Chromecast and AirPlay
entries (each "Disconnect from …" while it plays), under the button."""
self._refresh_connection_actions()
menu = QMenu(self)
menu.addAction(self._cast_action)
menu.addAction(self._airplay_action)
menu.exec(button.mapToGlobal(button.rect().bottomLeft()))
def _show_speakers_state(self, *_):
for controller in (self._cast, self._airplay):
if controller.is_connected():
self._transport.set_speakers_active(True, controller.device_name())
return
self._transport.set_speakers_active(False)
def _identify_from_toolbar(self):
"""The toolbar's Identify button: the playing song — the bar is about
what's on — or, with nothing on, the songs selected in the list."""
track = self.player.current_track
if track is not None and not isinstance(track.track_id, str) \
and track.track_id in self._manager.library.tracks:
ids = [track.track_id]
else:
ids = self._content.currentWidget().table.selected_track_ids()
if not ids:
self.statusBar().showMessage(
"Identify Track: play a song or select one first", 6000)
return
self._identify_tracks(ids)
def _on_cast_connecting(self, device):
self.statusBar().showMessage(f"Connecting to {device.name}…", 8000)
def _on_cast_connected(self, name: str):
self.statusBar().showMessage(f"Casting to {name}", 6000)
def _on_cast_disconnected(self, reason: str):
self.statusBar().showMessage(
reason or "Stopped casting — playing here again", 8000)
def _on_track_unplayable(self, track, reason: str):
self.statusBar().showMessage(
f"Skipped “{track.name}” — {reason}", 6000)
def _hide_sync_widgets(self):
self._sync_cancel.hide()
self._sync_label.hide()
self._sync_progress.hide()
def _busy_worker(self):
"""The transfer currently owning the status-bar progress widgets."""
for worker in (self._andtunes_planner, self._andtunes_worker,
self._export_worker, self._url_worker,
self._bpm_worker, self._server_check,
self._upload_worker, self._dj_prep_worker,
self._compress.worker if self._compress else None):
if worker is not None and worker.busy():
return worker
return None
def _confirm_cancel_sync(self):
if self._compress is not None and self._compress.worker.busy():
self._compress.request_cancel()
return
if self._dj_prep_worker is not None and self._dj_prep_worker.busy():
# What's prepared is kept; the song being split is abandoned.
self._dj_prep_worker.cancel()
return
if self._bpm_worker is not None and self._bpm_worker.busy():
# Nothing to lose: what's been measured is kept.
self._bpm_worker.cancel()
return
if self._url_worker is not None and self._url_worker.busy():
self._confirm_cancel_url_import()
return
if self._web_upload is not None:
self._confirm_stop_web_upload()
return
if self._export_worker is not None and self._export_worker.busy():
self._confirm_cancel_export()
return
worker = self._andtunes_worker
if worker is None or not worker.busy():
return
box = QMessageBox(self)
box.setWindowTitle("Cancel transfer")
box.setText(f"Cancel the transfer to the {self._sync_device_name}?\n"
"Tracks already copied stay on the device; syncing again "
"later picks up where this left off.")
cancel_button = box.addButton(
"Cancel Transfer", QMessageBox.ButtonRole.DestructiveRole)
keep = box.addButton("Keep Copying", QMessageBox.ButtonRole.RejectRole)
box.setDefaultButton(keep)
box.exec()
# The transfer keeps running while the dialog is up — it may well
# have finished by now, in which case there is nothing to cancel.
if box.clickedButton() is cancel_button and worker is not None:
worker.cancel()
def _on_sync_cancelled(self, summary):
self._full_sync_pending = False # a cancel stops a Full Sync too
self._full_sync_target = None
self._sync_inhibitor.release()
self._hide_sync_widgets()
self.statusBar().showMessage(
f"Sync cancelled — {summary['copied']} of {summary['total']} "
"tracks copied; sync again to finish.", 8000)
if summary.get("plays"):
# Counts are brought back before anything is copied, so even a
# cancelled sync has news for the journals.
self._manager.reload_from_disk()
def _refresh_device_actions(self):
"""Sync Music / Full Rabbit Sync from the watcher's cached answer — never a fresh
look at the mount, which is what froze the menu."""
if os_paths.IS_MAC:
return # the Rabbit actions are hidden there
busy = self._busy_worker() is not None
if self._devices.state == device_sync.STUCK:
# Enabled: the click explains and offers the reset.
self._andtunes_action.setText("Rabbit isn't responding…")
self._andtunes_action.setEnabled(True)
self._full_sync_action.setEnabled(False)
return
self._andtunes_action.setText("Sync Music to Rabbit")
# Whole-library sync doesn't care which view is open — only that a
# device is plugged in and at least one playlist is ticked.
ready = not busy and self._devices.device is not None
self._andtunes_action.setEnabled(ready)
self._full_sync_action.setEnabled(ready)
def _rabbit_stuck(self):
"""The mount stopped answering: say so, and offer the CLAUDE.md
recovery (kill gvfsd-mtp, remount) as one button."""
box = QMessageBox(self)
box.setIcon(QMessageBox.Icon.Warning)
box.setWindowTitle("Rabbit isn't responding")
box.setText("The Rabbit's USB connection has stopped answering, so "
"LinTunes can't reach it.")
box.setInformativeText(
"Reset Connection restarts the desktop's MTP service and "
"remounts the Rabbit. If that doesn't do it, unplug the Rabbit "
"and plug it back in.")
reset = box.addButton("Reset Connection",
QMessageBox.ButtonRole.AcceptRole)
box.addButton(QMessageBox.StandardButton.Cancel)
box.setDefaultButton(reset)
box.exec()
if box.clickedButton() is not reset:
return
self.statusBar().showMessage("Resetting the Rabbit connection…")
relay = self._reset_relay = _ResetRelay(self)
relay.done.connect(self._on_rabbit_reset)
threading.Thread(
target=lambda: relay.done.emit(device_sync.reset_mtp_connection()),
daemon=True).start()
def _on_rabbit_reset(self, error):
if error:
self.statusBar().clearMessage()
QMessageBox.warning(self, "Rabbit isn't responding",
f"The reset didn't work: {error}\n\n"
"Unplug the Rabbit and plug it back in.")
return
self.statusBar().showMessage("Rabbit connection reset", 6000)
self._devices.probe()
def _on_sync_failed(self, message):
self._sync_inhibitor.release()
self._hide_sync_widgets()
QMessageBox.warning(self, "Sync failed", message)
# Shazams come over adb, not the MTP mount that just failed.
self._then_shazams()
# ---- connections: andTunes (whole-library sync) ----
def _show_device_sync_settings(self):
device = self._devices.device # only for its name
dialog = DeviceSyncSettingsDialog(
self._prefs, self._manager.library, self,
device_name=device.name if device else "Rabbit")
dialog.exec()
def _selected_sync_playlists(self) -> list:
"""The ticked playlists (and everything in ticked folders)."""
return resolve_sync_playlists(self._manager.library,
self._prefs.device_sync)
def _sync_to_andtunes(self):
# Everything may have changed since the menu opened — re-verify.
if self._busy_worker() is not None:
return
self._full_sync_pending = False
self._devices.when_ready(self._sync_to_device)
def _full_rabbit_sync(self):
"""Sync Music to Rabbit, then Import Shazams into the playlist that
was current at the click (the user may browse away meanwhile)."""
if self._busy_worker() is not None:
return
self._full_sync_pending = True
self._full_sync_target = self._url_import_target()
self._devices.when_ready(self._sync_to_device)
def _then_shazams(self):
"""The music half of a Full Rabbit Sync is over (done, failed or
never started): on to the Shazams. A cancel ends the whole thing."""
if not self._full_sync_pending:
return
if self._busy_worker() is not None:
# The worker's thread clears its busy flag just after its last
# signal, which may reach us first.
QTimer.singleShot(50, self._then_shazams)
return
self._full_sync_pending = False
target, self._full_sync_target = self._full_sync_target, None
self._when_app_active(lambda: self._import_shazams(target=target))
def _sync_to_device(self, device, state):
if state == device_sync.STUCK:
self._full_sync_pending = False
self._rabbit_stuck()
return
if device is None or self._busy_worker() is not None:
self._full_sync_pending = False
return
playlists = self._selected_sync_playlists()
if not playlists:
if self._full_sync_pending:
self._then_shazams() # no music to send; Shazams still
return
QMessageBox.information(
self, "Nothing to sync",
"No playlists are set to sync yet.\n\n"
"Pick them in Connections → Rabbit Sync Settings…")
return
# Planning walks the whole device over MTP — off the GUI thread, or
# the window freezes and GNOME offers to kill it mid-sync.
root = andtunes_layout.root_for(device)
self._andtunes_planner = andtunes_sync.AndTunesPlanWorker(
playlists, self._manager.library.tracks, root, device,
copy_art=bool(self._prefs.device_sync.get("copy_art", True)),
data_dir=self._manager.data_dir, parent=self)
self._andtunes_planner.planned.connect(self._on_andtunes_planned)
self._andtunes_planner.failed.connect(self._on_sync_failed)
self._sync_device_name = device.name
self._sync_label.setText(f"Checking the {device.name}")
self._sync_progress.setRange(0, 0) # busy bar: no total to show yet
self._sync_label.show()
self._sync_progress.show()
self._andtunes_planner.start()
def _on_andtunes_planned(self, plan, free):
device = plan.device
plan.history = bool(self._prefs.wrapped.get("track_history"))
playlists = plan.playlists
self._hide_sync_widgets()
if plan.needs_ffmpeg and not exporter.web_support.ffmpeg_available():
conversions = plan.conversions
names = "\n".join(f" • {device_sync.track_display(i.track)}"
for i in conversions[:8])
more = (f"\n … and {len(conversions) - 8} more"
if len(conversions) > 8 else "")
answer = QMessageBox.question(
self, "FFmpeg not found",
f"{len(conversions)} song(s) need converting to FLAC before "
f"the {device.name} can play them, but the ffmpeg command "
f"isn't installed:\n\n{names}{more}\n\nSync without them?")
if answer != QMessageBox.StandardButton.Yes:
self._then_shazams()
return
plan.drop_conversions("it needs ffmpeg to convert")
needed = plan.bytes_to_copy + device_sync.SPACE_MARGIN
if free + plan.bytes_freed < needed:
QMessageBox.warning(
self, "Not enough space",
f"Syncing {len(playlists)} playlist(s) needs "
f"{device_sync.format_bytes(needed - plan.bytes_freed)}, but "
f"the {device.name} only has "
f"{device_sync.format_bytes(free)} free.")
self._then_shazams()
return
self._andtunes_worker = andtunes_sync.AndTunesSyncWorker(plan, self)
self._andtunes_worker.progress.connect(self._on_andtunes_progress)
self._andtunes_worker.finished.connect(self._on_andtunes_finished)
self._andtunes_worker.cancelled.connect(self._on_sync_cancelled)
self._andtunes_worker.failed.connect(self._on_sync_failed)
self._sync_device_name = device.name
self._sync_label.setText(f"Copying to {device.name}")
self._sync_progress.setRange(0, max(plan.bytes_to_copy // 1024, 1))
self._sync_progress.setValue(0)
self._sync_cancel.show()
self._sync_label.show()
self._sync_progress.show()
self._sync_inhibitor.inhibit()
self._andtunes_worker.start()
def _on_andtunes_progress(self, done_kib, total_kib, label):
# Unlike the per-playlist sync this run has phases that move no audio
# bytes (album art, then the index), so the label carries the story.
self._sync_progress.setRange(0, total_kib)
self._sync_progress.setValue(done_kib)
self._sync_label.setText(f"{self._sync_device_name} · {label}")
def _on_andtunes_finished(self, summary):
self._sync_inhibitor.release()
self._hide_sync_widgets()
msg = (f"Synced {summary['playlists']} playlist(s) to the "
f"{summary['device']}: {summary['tracks']} tracks "
f"({summary['copied']} copied, {summary['kept']} up to date), "
f"{summary['removed']} removed")
if summary.get("covers_copied"):
msg += f", {summary['covers_copied']} covers updated"
if summary["skipped"]:
msg += f", {summary['skipped']} skipped (no local file)"
if summary.get("refused"):
msg += f", {summary['refused']} left out (can't play there)"
if summary.get("unconverted"):
msg += f", {summary['unconverted']} couldn't be converted"
unwritable = summary.get("unwritable") or []
if unwritable:
msg += f", {len(unwritable)} the device wouldn't take"
if summary.get("plays"):
msg += f"; play counts back for {summary['plays']} song(s)"
# The journal landed in the data dir; fold it in now rather than
# waiting for the file watcher.
self._manager.reload_from_disk()
self.statusBar().showMessage(msg, 10000)
sounds.play_done(self._prefs)
if unwritable:
# Worth a dialog: these songs are *not* in the library the app
# reads, so they'd otherwise just be quietly absent from the
# playlist. A stale gvfs mount is the usual cause.
names = "\n".join(f" • {name} — {why}" for name, why in unwritable[:8])
more = (f"\n … and {len(unwritable) - 8} more"
if len(unwritable) > 8 else "")
QMessageBox.warning(
self, "Some songs wouldn't copy",
f"The {summary['device']} refused "
f"{len(unwritable)} song(s):\n\n{names}{more}\n\n"
"They've been left out of the library on the device, so the "
"app won't list a song it can't play. Unplugging the "
"device and plugging it back in usually clears this.")
self._then_shazams()
# ---- connections: install the andTunes app ----
def _install_andtunes(self):
if self._install_worker is not None and self._install_worker.busy():
return
apk = andtunes_install.bundled_apk()
if apk is None:
return
self._devices.when_ready(
lambda device, state: self._install_andtunes_to(apk, device, state))
def _install_andtunes_to(self, apk, device, state):
adb = andtunes_install.adb_path()
serial = andtunes_install.rabbit_serial(adb) if adb else None
if serial is None and state == device_sync.STUCK:
self._rabbit_stuck()
return
if serial is None and device is None:
QMessageBox.information(
self, "Rabbit not found",
"Plug the Rabbit in with USB debugging on, or in "
"File transfer mode, then try again.")
return
ours = andtunes_install.bundled_version()
ours_name = ours.get("version_name", "?")
if serial:
have = andtunes_install.installed_version(adb, serial)
if have is None:
verb = "Install"
detail = f"Install andTunes {ours_name} on the Rabbit?"
elif have["version_code"] < ours.get("version_code", 0):
verb = "Update"
detail = (f"The Rabbit has andTunes {have['version_name']}; "
f"this LinTunes carries {ours_name}. Update it?")
else:
verb = "Reinstall"
detail = (f"The Rabbit already has andTunes "
f"{have['version_name']}. Reinstall {ours_name}?")
else:
verb = "Copy"
detail = ("adb isn't available, so the app will be copied to "
"Download/ on the Rabbit for you to open in the Files "
"app and install by hand. Copy it?")
box = QMessageBox(self)
box.setWindowTitle(f"{verb} andTunes")
box.setText(detail)
go = box.addButton(verb, QMessageBox.ButtonRole.AcceptRole)
box.addButton(QMessageBox.StandardButton.Cancel)
box.setDefaultButton(go)
box.exec()
if box.clickedButton() is not go:
return
self._install_worker = andtunes_install.InstallWorker(
apk, adb, serial, device, self)
self._install_worker.finished.connect(self._on_install_finished)
self._install_worker.failed.connect(
lambda message: QMessageBox.warning(self, "andTunes", message))
self.statusBar().showMessage("Installing andTunes on the Rabbit…")
self._install_worker.start()
def _on_install_finished(self, result):
if result["method"] == "copied":
self.statusBar().clearMessage()
QMessageBox.information(
self, "andTunes copied",
f"Copied to {result['path']}.\n\nOn the Rabbit, open Files → "
"Download → andTunes.apk to install it.")
return
msg = "andTunes is installed on the Rabbit"
if not result.get("granted", True):
msg += " — open it once to allow file access"
self.statusBar().showMessage(msg, 8000)
# ---- export ----
def _refresh_export_action(self):
"""Export needs a playlist in view and no transfer already running."""
self._export_action.setEnabled(
self._busy_worker() is None
and self._content.currentWidget() is self._playlist_view
and bool(self._playlist_view.playlist_id))
def _export_playlist(self, pid: str = ""):
# Reachable from the File menu (no argument) and from the sidebar
# context menu (which names the playlist that was right-clicked).
if self._busy_worker() is not None:
return
pid = pid or self._playlist_view.playlist_id
playlist = self._manager.library.playlists.get(pid)
if playlist is None:
return
tracks = [self._manager.library.tracks[tid]
for tid in playlist.track_ids
if tid in self._manager.library.tracks]
if not tracks:
QMessageBox.information(
self, "Export Playlist",
f"“{playlist.name}” is empty — there is nothing to export.")
return
kind_dialog = ExportKindDialog(playlist.name, self)
if kind_dialog.exec() != ExportKindDialog.DialogCode.Accepted:
return
kind = kind_dialog.kind()
details = None
if kind == exporter.WEB:
web_dialog = WebMixDialog(playlist.name, self, load_config())
if web_dialog.exec() != WebMixDialog.DialogCode.Accepted:
return
details = web_dialog.values()
if details["upload"]:
self._export_and_upload(playlist, tracks, details)
return
start_dir = self._music_import_dir()
parent_dir = QFileDialog.getExistingDirectory(
self, "Export To",
str(start_dir.parent) if start_dir else str(Path.home()))
if not parent_dir:
return
try:
plan = exporter.plan_export(
playlist.name, tracks, Path(parent_dir), kind)
except OSError as e:
QMessageBox.warning(self, "Export failed",
f"Couldn't read the playlist's files: {e}")
return
if details is not None:
plan.title = details["title"] or playlist.name
plan.description = details["description"]
plan.images = details["images"]
plan.accent = details["accent"]
if not self._confirm_export(plan):
return
self._start_export(plan)
def _start_export(self, plan):
self._export_worker = exporter.ExportWorker(plan, self)
self._export_worker.progress.connect(self._on_export_progress)
self._export_worker.finished.connect(self._on_export_finished)
self._export_worker.cancelled.connect(self._on_export_cancelled)
self._export_worker.failed.connect(self._on_export_failed)
self._sync_label.setText("Exporting")
self._sync_progress.setRange(0, max(plan.bytes_to_copy // 1024, 1))
self._sync_progress.setValue(0)
self._sync_cancel.show()
self._sync_label.show()
self._sync_progress.show()
self._export_inhibitor.inhibit()
self._export_worker.start()
def _export_and_upload(self, playlist, tracks, details):
"""The upload half of Export Web Mix: no folder picker — the mix is
built in the cache's staging folder, then mirrored to the server."""
server = upload.server_settings(load_config())
if server is None: # the dialog checks; Preferences may not have
QMessageBox.warning(self, "Web server not set up",
"Fill in the web server in Preferences → "
"Integrations, then export again.")
return
host, path = server
slug = details["slug"]
try:
rdir = upload.remote_dir(path, slug)
plan = exporter.plan_export(
playlist.name, tracks, upload.staging_root(), exporter.WEB,
folder=slug)
except upload.UploadError as e:
QMessageBox.warning(self, "Export failed", str(e))
return
except OSError as e:
QMessageBox.warning(self, "Export failed",
f"Couldn't read the playlist's files: {e}")
return
plan.title = details["title"] or playlist.name
plan.description = details["description"]
plan.images = details["images"]
plan.accent = details["accent"]
if not self._confirm_export(plan, local=False):
return
self._web_upload = {"host": host, "rdir": rdir, "slug": slug,
"plan": plan, "step": web_progress.CHECK}
if self._web_progress is not None:
self._web_progress.close()
self._web_progress.deleteLater()
self._web_progress = web_progress.WebUploadProgress(
plan.title, f"{host}:{rdir}", self)
self._web_progress.stop_requested.connect(
self._confirm_stop_web_upload)
self._web_progress.show()
self._web_progress.begin(web_progress.CHECK, "Connecting…", busy=True)
self._server_check = upload.ServerCheckWorker(host, rdir, self)
self._server_check.result.connect(self._on_server_checked)
self._server_check.failed.connect(
lambda msg: self._web_upload_failed(web_progress.CHECK, msg))
self._server_check.cancelled.connect(self._web_upload_stopped)
self._sync_label.setText(f"Checking {host}…")
self._sync_progress.setRange(0, 0)
self._sync_cancel.show()
self._sync_label.show()
self._sync_progress.show()
self._server_check.start()
def _on_server_checked(self, exists: bool):
run = self._web_upload
if run is None:
return
if exists:
self._web_progress.complete(web_progress.CHECK,
"Connected — folder exists")
answer = QMessageBox.question(
self, "Replace mix on server?",
f"“{run['slug']}” already exists on {run['host']}.\n\n"
"Uploading replaces it with this mix, deleting any files in "
"that folder that aren't part of it. Continue?")
if answer != QMessageBox.StandardButton.Yes:
self._web_upload_stopped()
return
else:
self._web_progress.complete(web_progress.CHECK,
"Connected — new folder")
try:
upload.reset_staging(run["slug"])
except (upload.UploadError, OSError) as e:
self._web_upload_failed(web_progress.EXPORT,
f"Couldn't clear the staging folder: {e}")
return
run["step"] = web_progress.EXPORT
self._web_progress.begin(web_progress.EXPORT)
self._start_export(run["plan"])
def _start_upload(self, summary):
run = self._web_upload
run["step"] = web_progress.UPLOAD
run["export"] = summary
self._web_progress.complete(
web_progress.EXPORT,
f"{summary['exported']} track"
f"{'s' if summary['exported'] != 1 else ''} · "
f"{device_sync.format_bytes(summary.get('bytes', 0))}")
self._web_progress.begin(web_progress.UPLOAD, "Starting…")
self._upload_worker = upload.UploadWorker(
run["host"], run["plan"].dest_dir, run["rdir"], self)
self._upload_worker.progress.connect(self._on_upload_progress)
self._upload_worker.finished.connect(self._on_upload_finished)
self._upload_worker.failed.connect(
lambda msg: self._web_upload_failed(web_progress.UPLOAD, msg))
self._upload_worker.cancelled.connect(self._web_upload_stopped)
self._sync_label.setText(f"Uploading to {run['host']}")
self._sync_progress.setRange(0, 100)
self._sync_progress.setValue(0)
self._sync_cancel.show()
self._sync_label.show()
self._sync_progress.show()
self._export_inhibitor.inhibit()
self._upload_worker.start()
def _on_upload_progress(self, percent: int, line: str):
if self._web_upload is None:
return
self._web_progress.progress(web_progress.UPLOAD, percent, line)
self._sync_progress.setRange(0, 100)
self._sync_progress.setValue(percent)
self._sync_label.setText(
f"Uploading to {self._web_upload['host']} · {percent}%")
def _on_upload_finished(self, result):
run, self._web_upload = self._web_upload, None
self._export_inhibitor.release()
self._hide_sync_widgets()
if run is None:
return
sent = result.get("files_sent", 0)
self._web_progress.complete(
web_progress.UPLOAD,
f"{sent} file{'s' if sent != 1 else ''} sent")
summary = run.get("export", {})
msg = (f"Uploaded “{summary.get('playlist', run['slug'])}” "
f"({device_sync.format_bytes(summary.get('bytes', 0))}) to "
f"{run['host']}:{run['rdir']}")
extras = []
if summary.get("converted"):
extras.append(f"{summary['converted']} converted to FLAC")
if summary.get("skipped"):
extras.append(f"{summary['skipped']} skipped")
if summary.get("vanished"):
extras.append(f"{summary['vanished']} changed under us "
"(export again to pick them up)")
if extras:
msg += " — " + ", ".join(extras)
self._web_progress.finish(msg)
self.statusBar().showMessage(msg, 12000)
sounds.play_done(self._prefs)
def _web_upload_failed(self, step: int, message: str):
run, self._web_upload = self._web_upload, None
self._export_inhibitor.release()
self._hide_sync_widgets()
if run is None:
return
if step == web_progress.UPLOAD:
message += ("\n\nThe mix's folder on the server may be "
"half-updated; uploading again finishes it.")
self._web_progress.fail(step, message)
self._show_web_progress()
self.statusBar().showMessage("Web mix upload failed", 8000)
def _web_upload_stopped(self, *_args):
run, self._web_upload = self._web_upload, None
self._export_inhibitor.release()
self._hide_sync_widgets()
if run is None:
return
self._web_progress.fail(run["step"], "Stopped — nothing more was "
"sent. Export again to finish.", "Stopped")
self.statusBar().showMessage("Web mix upload stopped", 6000)
def _confirm_stop_web_upload(self):
run = self._web_upload
if run is None:
return
answer = QMessageBox.question(
self, "Stop upload",
"Stop exporting and uploading this mix?",
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
QMessageBox.StandardButton.No)
if answer != QMessageBox.StandardButton.Yes or self._web_upload is None:
return
for worker in (self._server_check, self._export_worker,
self._upload_worker):
if worker is not None and worker.busy():
worker.cancel()
def _show_web_progress(self):
if self._web_progress is not None and (
self._web_upload is not None or self._web_progress.ended):
self._web_progress.show()
self._web_progress.raise_()
self._web_progress.activateWindow()
def _confirm_export(self, plan, local: bool = True) -> bool:
"""Last look before writing: overwrite, ffmpeg, and skipped tracks."""
if plan.needs_ffmpeg and not exporter.web_support.ffmpeg_available():
names = "\n".join(f" • {i.display}" for i in plan.conversions[:8])
more = (f"\n … and {len(plan.conversions) - 8} more"
if len(plan.conversions) > 8 else "")
answer = QMessageBox.question(
self, "FFmpeg not found",
f"{len(plan.conversions)} track(s) need converting before a "
f"browser can play them, but the ffmpeg command isn't "
f"installed:\n\n{names}{more}\n\nExport without them?")
if answer != QMessageBox.StandardButton.Yes:
return False
plan.skipped += [(i.display, "it needs ffmpeg to convert")
for i in plan.conversions]
plan.items = [i for i in plan.items if not i.convert_to]
plan.bytes_to_copy = sum(i.size for i in plan.items)
if not plan.items:
QMessageBox.information(
self, "Export Playlist",
"Nothing left to export once those are left out.")
return False
if plan.skipped:
names = "\n".join(f" • {d} — {why}" for d, why in plan.skipped[:8])
more = (f"\n … and {len(plan.skipped) - 8} more"
if len(plan.skipped) > 8 else "")
answer = QMessageBox.question(
self, "Some tracks can't be exported",
f"{len(plan.skipped)} of {len(plan.skipped) + len(plan.items)} "
f"track(s) will be left out:\n\n{names}{more}\n\nExport the "
f"other {len(plan.items)}?")
if answer != QMessageBox.StandardButton.Yes:
return False
if local and plan.dest_dir.exists():
answer = QMessageBox.question(
self, "Folder exists",
f"“{plan.dest_dir.name}” already exists in that folder. "
f"Files with the same names will be overwritten.\n\nContinue?")
if answer != QMessageBox.StandardButton.Yes:
return False
return True
def _confirm_cancel_export(self):
if self._export_worker is None or not self._export_worker.busy():
return
box = QMessageBox(self)
box.setWindowTitle("Cancel export")
box.setText("Cancel the export?\n"
"The folder is left as-is, without a playlist file — "
"exporting again starts it over.")
cancel_button = box.addButton(
"Cancel Export", QMessageBox.ButtonRole.DestructiveRole)
keep = box.addButton("Keep Exporting", QMessageBox.ButtonRole.RejectRole)
box.setDefaultButton(keep)
box.exec()
# The export keeps running while the dialog is up — it may well have
# finished by now, in which case there is nothing to cancel.
if (box.clickedButton() is cancel_button
and self._export_worker is not None):
self._export_worker.cancel()
def _on_export_progress(self, done_kib, total_kib, label):
if self._web_upload is not None:
self._web_progress.progress(
web_progress.EXPORT, done_kib * 100 // max(total_kib, 1),
label)
self._sync_progress.setRange(0, total_kib)
self._sync_progress.setValue(done_kib)
self._sync_label.setText(
f"Exporting · {device_sync.format_bytes(done_kib * 1024)} / "
f"{device_sync.format_bytes(total_kib * 1024)}")
def _on_export_finished(self, summary):
if self._web_upload is not None:
self._start_upload(summary)
return
self._export_inhibitor.release()
self._hide_sync_widgets()
what = "web mix" if summary["kind"] == exporter.WEB else "folder"
msg = (f"Exported “{summary['playlist']}” as a {what}: "
f"{summary['exported']} tracks, "
f"{device_sync.format_bytes(summary.get('bytes', 0))} → "
f"{summary['dest']}")
if summary["converted"]:
msg += f", {summary['converted']} converted to FLAC"
if summary["skipped"]:
msg += f", {summary['skipped']} skipped"
if summary["vanished"]:
msg += (f", {summary['vanished']} changed under us "
"(export again to pick them up)")
self.statusBar().showMessage(msg, 12000)
sounds.play_done(self._prefs)
def _on_export_cancelled(self, summary):
if self._web_upload is not None:
self._web_upload_stopped()
return
self._export_inhibitor.release()
self._hide_sync_widgets()
self.statusBar().showMessage(
f"Export cancelled — {summary['exported']} of {summary['total']} "
f"tracks written to {summary['dest']}.", 8000)
def _on_export_failed(self, message):
if self._web_upload is not None:
self._web_upload_failed(web_progress.EXPORT, message)
return
self._export_inhibitor.release()
self._hide_sync_widgets()
QMessageBox.warning(self, "Export failed", message)
# ---- view switching ----
def _show_library(self):
self._content.setCurrentWidget(self._library_view)
self._update_now_playing_icon()
def _show_playlist(self, persistent_id: str):
playlist = self._manager.library.playlists.get(persistent_id)
if playlist:
self._playlist_view.show_playlist(playlist)
self._content.setCurrentWidget(self._playlist_view)
self._update_now_playing_icon()
self._update_playlist_art()
def _playlist_info(self, pid: str):
"""The playlist's Get Info; OK renames it and sets its cover."""
playlist = self._manager.library.playlists.get(pid)
if playlist is None:
return
data_dir = self._manager.data_dir
path = playlist_art.find(data_dir, pid)
try:
art = path.read_bytes() if path is not None else None
except OSError:
art = None
tracks = [self._manager.library.tracks[t] for t in playlist.track_ids
if t in self._manager.library.tracks]
dialog = PlaylistInfoDialog(
playlist, tracks, art=art,
last_played=self._manager.playlist_last_played(pid), parent=self)
if not dialog.exec():
return
if dialog.new_name():
self._manager.rename_playlist(pid, dialog.new_name())
if dialog.source_change() is not None:
self._manager.set_playlist_source(pid, dialog.source_change())
change = dialog.art_change()
if change is not None:
try:
if change:
playlist_art.save(data_dir, pid, _as_jpeg_or_png(change))
else:
playlist_art.remove(data_dir, pid)
except (OSError, ValueError) as e:
QMessageBox.warning(self, "Playlist Art",
f"Couldn't save the cover:\n\n{e}")
self._update_playlist_art()
def _update_playlist_art(self, *_):
"""Hand the art panel the shown playlist's cover (it shows it only
while nothing is playing)."""
path, name = None, ""
if self._content.currentWidget() is self._playlist_view:
pid = self._playlist_view.playlist_id
playlist = self._manager.library.playlists.get(pid)
if playlist is not None:
path = playlist_art.find(self._manager.data_dir, pid)
name = playlist.name
self._sidebar.art.set_playlist_art(path, name)
def _go_to_current_song(self):
"""Jump to wherever the current song is playing from, select it, and
scroll it into view. No-op when nothing is cued."""
track = self.player.current_track
if track is None:
return
ctx = self._now_playing_context
if ctx == "library":
self._show_library()
self._sidebar.reflect_library()
self._library_view.reveal_track(track.track_id)
elif ctx.startswith("playlist:"):
pid = ctx.split(":", 1)[1]
if pid in self._manager.library.playlists:
self._show_playlist(pid)
self._sidebar.reflect_playlist(pid)
self._playlist_view.reveal_track(track.track_id)
def _show_track_in_playlist(self, track_id: int, pid: str):
"""Jump to a playlist and highlight the first instance of the track,
reusing the Go-to-Current-Song navigation pattern."""
if pid in self._manager.library.playlists:
self._show_playlist(pid)
self._sidebar.reflect_playlist(pid)
self._playlist_view.reveal_track(track_id)
# ---- multi-machine sync ----
def _on_library_reloaded(self):
"""Another machine's changes were reconciled in. Refresh the library
view (the sidebar and open playlist refresh via playlists_changed),
keeping the user's scroll and selection. Never touches the player."""
table = self._library_view.table
selected = table.selected_track_ids()
scroll = table.verticalScrollBar().value()
self._library_view.reload()
if selected:
table.reveal_track(selected[0])
table.verticalScrollBar().setValue(scroll)
def _on_conflict_resolved(self, summaries):
self.statusBar().showMessage(
f"Merged changes from your other machine "
f"({len(summaries)} item(s))", 8000)
self.show_conflict_summary(summaries)
def show_conflict_summary(self, summaries):
"""Show (or extend) the one merge window. Syncthing can deliver conflicts
every few minutes; each merge becomes another entry in the open window
rather than another window.
Only raise it when the new batch has something to say at the level on
screen — otherwise the entry is folded in quietly and is there when the
user dials the filter down."""
from lintunes.gui.conflict_dialog import ConflictSummaryDialog
if self._conflict_dialog is not None:
if self._conflict_dialog.add_event(summaries):
self._conflict_dialog.raise_()
return
# Modeless so a merge never blocks playback or what you're doing.
self._conflict_dialog = ConflictSummaryDialog(
summaries, self._manager, self)
self._conflict_dialog.finished.connect(self._on_conflict_dialog_closed)
self._conflict_dialog.show()
self._conflict_dialog.raise_()
def _on_conflict_dialog_closed(self, _result):
"""Drop the reference (and the widget) so the next merge opens a fresh
window instead of touching a deleted C++ object."""
dialog, self._conflict_dialog = self._conflict_dialog, None
if dialog is not None:
dialog.deleteLater()
# ---- info dialog ----
def _show_info(self, track_ids: list[int]):
if track_ids:
dialog = InfoDialog(self._manager, track_ids, self)
dialog.boost_requested.connect(self._boost_volume)
dialog.exec()
def _info_for_current_view(self):
view = self._content.currentWidget()
ids = view.table.selected_track_ids()
self._show_info(ids)
# ---- music folder ----
def check_music_folder(self):
"""Ask where the music goes, if we don't already know.
Called once shortly after the window appears, and again lazily if an
import happens while no folder is set. Never blocks startup: by the
time this runs the main window is already up, so the dialog is a normal
child dialog rather than a popup in front of an empty screen.
"""
state = self._manager.music_folder_state()
if state.path is not None:
return
if state.source == "unset":
if music_folder.prompt_seen():
return
elif self._missing_folder_prompted:
return # asked once this session; don't nag on every import
dialog = MusicFolderDialog(
self, missing_path=state.stored if state.source == "missing" else "")
dialog.exec()
chosen = dialog.chosen_folder()
# Remember we asked, whatever the answer — including "Not Now".
music_folder.mark_prompt_seen()
self._missing_folder_prompted = True
if chosen is not None:
# A folder that exists elsewhere but not here is this machine's own
# problem to solve; don't overwrite what the other machine set.
self._manager.set_music_folder(
chosen, machine_only=(state.source == "missing"))
self.statusBar().showMessage(
f"Music folder set to {self._manager.organize_root()}", 6000)
def _change_music_folder(self):
"""Preferences ▸ Music folder ▸ Change… — pick a new one."""
state = self._manager.music_folder_state()
start = str(state.path) if state.path else str(Path.home())
chosen = QFileDialog.getExistingDirectory(
self, "Choose Music Folder", start)
if not chosen:
return
media = music_folder.normalize_media_folder(chosen)
old_root = self._manager.organize_root()
if old_root is not None and old_root.exists() and \
media != Path(state.path or ""):
# Say the quiet part out loud: nothing moves, and from here on only
# new music goes to the new place. Otherwise the change looks total
# but silently applies to future additions only.
answer = QMessageBox.question(
self, "Change music folder?",
f"Your existing songs will stay where they are:\n{old_root}\n\n"
f"Only music you add from now on will go to:\n"
f"{music_folder.organize_root_for(media)}\n\n"
"Change the folder?",
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
QMessageBox.StandardButton.No)
if answer != QMessageBox.StandardButton.Yes:
return
self._manager.set_music_folder(
media, machine_only=state.is_machine_local)
self.statusBar().showMessage(
f"Music folder set to {self._manager.organize_root()}", 6000)
def _music_folder_summary(self) -> tuple[str, str]:
"""(folder, note) for the Preferences row."""
state = self._manager.music_folder_state()
if state.path is None:
return ("", "Not set yet — pick a folder to start adding music.")
if state.is_machine_local:
return (str(state.path), "Used on this computer only.")
return (str(state.path), "Shared with your other computers.")
# ---- file import ----
def _music_import_dir(self) -> Path | None:
"""Where imports are filed, or None when no music folder is usable.
Deliberately no fallback. The old `or Path("Music")` was *relative*, so
it resolved against the process working directory — which GNOME's dash
does not set predictably (see packaging/install-desktop.sh), scattering
a new user's music somewhere they'd never find it.
"""
return self._manager.organize_root()
def _open_files_dialog(self):
paths, _filter = QFileDialog.getOpenFileNames(
self, "Add Files to Library", "",
"Audio files (*.mp3 *.m4a *.flac *.aac *.wav *.aiff)")
if paths:
self.import_files([Path(p) for p in paths])
def _ensure_music_dir(self) -> Path | None:
music_dir = self._music_import_dir()
if music_dir is None:
# Ask rather than guess — better one question than music copied
# somewhere unfindable.
self.check_music_folder()
music_dir = self._music_import_dir()
if music_dir is None:
self.statusBar().showMessage(
"Choose where to keep your music first — Edit ▸ Preferences.",
8000)
return music_dir
def import_files(self, paths, playlist_pid: str = "",
position: int | None = None) -> list:
"""Returns the tracks imported — except when lossless files are being
compressed, which happens in the background and returns []."""
music_dir = self._ensure_music_dir()
if music_dir is None:
return []
if self._start_compressing_import(paths, music_dir, playlist_pid,
position):
return []
self.statusBar().showMessage(f"Importing {len(paths)} item(s)…")
imported = file_importer.import_paths(
paths, music_dir, self._manager, playlist_pid,
position)
self.statusBar().showMessage(f"Imported {len(imported)} track(s)", 5000)
if imported:
self._library_view.reload()
return imported
def _start_compressing_import(self, paths, music_dir, playlist_pid,
position) -> bool:
"""With Compress lossless imports on and a lossless file among
``paths``, run the whole import through the converter (in order, so a
playlist drop keeps its order). False = import the ordinary way."""
on, kbps = lossless.settings(self._prefs)
if not on:
return False
from lintunes.gui import compress_import
files = file_importer.expand_paths(paths)
items = compress_import.plan_items(files, self._manager, music_dir)
if not any(convert for _s, convert, _d in items):
return False
if not lossless.ffmpeg_available():
QMessageBox.warning(
self, "Compress Lossless Imports",
"Compressing needs ffmpeg, which is not installed, so these "
"songs are imported as they are.\n\nInstall your distro's "
"“ffmpeg” package to compress the next import.")
return False
if self._busy_worker() is not None or self._compress is not None:
self.statusBar().showMessage(
"Wait for the current import or transfer to finish first", 6000)
return True
batch = compress_import.CompressImport(
self._manager, music_dir, items, kbps, playlist_pid, position, self)
batch.status.connect(self._on_compress_status)
batch.landed.connect(self._compress_reload.start)
batch.worker_finished.connect(self._free_sync_widgets)
batch.over.connect(self._on_compress_over)
self._compress = batch
self._sync_label.setText("Importing…")
self._sync_progress.setRange(0, 100)
self._sync_progress.setValue(0)
for widget in (self._sync_label, self._sync_progress, self._sync_cancel):
widget.show()
batch.start()
return True
def _on_compress_status(self, label: str, value: int, maximum: int):
self._sync_label.setText(label)
self._sync_progress.setRange(0, maximum)
self._sync_progress.setValue(value)
def _on_compress_over(self, message: str):
self._compress = None
self._free_sync_widgets() # mid-song, the worker's finish does it
self._compress_reload.stop()
self._library_view_reload()
self.statusBar().showMessage(message, 8000)
if "cancelled" not in message:
sounds.play_done(self._prefs)
# ---- Boost Volume (Round 131, lintunes/boost.py) ----
def _boost_volume(self, track_ids: list[int]):
"""Right-click or Get Info › Boost Volume…: measure, say what it
would do, amplify the files, swap them in as one undo step."""
from lintunes import boost
if not lossless.ffmpeg_available():
QMessageBox.warning(
QApplication.activeWindow() or self, "Boost Volume",
"Boosting needs ffmpeg, which is not installed.\n\n"
"Install your distro's “ffmpeg” package and try again.")
return
if self._boost is not None:
self.statusBar().showMessage(
"Wait for the current boost to finish first", 6000)
return
tracks = [self._manager.library.tracks[t] for t in track_ids
if t in self._manager.library.tracks]
tracks = [t for t in tracks if t.location and Path(t.location).exists()]
if not tracks:
self.statusBar().showMessage("No song file to boost", 6000)
return
analyzer = getattr(self.player, "loudness", None)
typical = (analyzer.typical_lufs() if analyzer is not None
else loudness.TYPICAL_LUFS)
worker = boost.BoostWorker(
[(t.track_id, t.location, t.name or Path(t.location).stem)
for t in tracks], typical, self)
self._boost = worker
self._boost_typical = typical
worker.progress.connect(lambda text: self.statusBar().showMessage(text))
worker.measured.connect(self._on_boost_measured)
worker.amplified.connect(self._on_boost_amplified)
worker.start_measuring()
def _boost_end(self, message: str = ""):
worker, self._boost = self._boost, None
if worker is not None and worker.tmp_dir is not None:
shutil.rmtree(worker.tmp_dir, ignore_errors=True)
if message:
self.statusBar().showMessage(message, 8000)
else:
self.statusBar().clearMessage()
def _on_boost_measured(self, plans: dict):
gains = self._ask_boost(plans)
if not gains:
self._boost_end()
return
self._boost.start_amplifying(gains)
def _ask_boost(self, plans: dict) -> dict:
"""The warning before anything changes: how many dB, and whether it
clips. ``{track id: gain dB}`` to apply, empty for none."""
from lintunes import boost
parent = QApplication.activeWindow() or self
tracks = self._manager.library.tracks
name = lambda tid: f"“{tracks[tid].name}”" if tid in tracks else "This song"
typical = self._boost_typical
unmeasurable = [t for t, p in plans.items() if not p.measurable]
loud = [t for t, p in plans.items() if p.measurable and not p.worth_it]
todo = {t: p for t, p in plans.items() if p.worth_it}
if not todo:
if unmeasurable and not loud:
text = (f"{name(unmeasurable[0])} couldn't be measured — it "
"may be silent or unreadable." if len(plans) == 1 else
"None of those songs could be measured.")
elif len(plans) == 1:
p = plans[loud[0]]
text = (f"{name(loud[0])} is already as loud as a typical song "
f"({p.lufs:.1f} LUFS; typical is {typical:.1f}) — "
"nothing to boost.")
else:
text = "Those songs are already as loud as a typical song."
QMessageBox.information(parent, "Boost Volume", text)
return {}
undo_note = ("The original goes to the trash; Edit ▸ Undo puts it back."
if len(todo) == 1 else
"The originals go to the trash; Edit ▸ Undo puts them all back.")
box = QMessageBox(parent)
box.setWindowTitle("Boost Volume")
box.setIcon(QMessageBox.Icon.Question)
clipping = {t: p for t, p in todo.items() if p.clips}
if len(todo) == 1:
tid, p = next(iter(todo.items()))
if not p.clips:
box.setText(f"{name(tid)} will be amplified {p.target_db:+.1f} dB, "
"to a typical song's loudness, and will not clip.")
else:
box.setText(
f"{name(tid)} needs {p.target_db:+.1f} dB to be as loud as "
f"a typical song, which would clip it. Without clipping it "
f"can be amplified {p.clean_gain:+.1f} dB.")
else:
lines = [f"{name(t)}: {p.target_db:+.1f} dB"
+ (f" (clips; {p.clean_gain:+.1f} dB without)" if p.clips else "")
for t, p in todo.items()]
skipped = len(loud) + len(unmeasurable)
box.setText(f"{len(todo)} songs will be amplified to a typical "
"song's loudness" + (" — some would clip:" if clipping
else ", and none will clip:"))
box.setDetailedText("\n".join(lines))
box.setInformativeText(
"\n".join(lines[:8]) + ("\n…" if len(lines) > 8 else "")
+ (f"\n\n{skipped} already loud enough or unmeasurable, left as they are."
if skipped else "") + "\n\n" + undo_note)
if len(todo) == 1:
box.setInformativeText(undo_note)
full = clean = None
if not clipping:
full = box.addButton("Amplify", QMessageBox.ButtonRole.AcceptRole)
box.setDefaultButton(full)
else:
if len(todo) == 1:
p = next(iter(todo.values()))
if p.clean_gain >= boost.MIN_BOOST_DB:
clean = box.addButton(f"Amplify {p.clean_gain:+.1f} dB",
QMessageBox.ButtonRole.AcceptRole)
full = box.addButton(f"Amplify {p.target_db:+.1f} dB (clips)",
QMessageBox.ButtonRole.AcceptRole)
else:
clean = box.addButton("Amplify Without Clipping",
QMessageBox.ButtonRole.AcceptRole)
full = box.addButton("Amplify All the Way (clips)",
QMessageBox.ButtonRole.AcceptRole)
box.setDefaultButton(clean or full)
box.addButton(QMessageBox.StandardButton.Cancel)
box.exec()
chosen = box.clickedButton()
if chosen is full:
return {t: p.target_db for t, p in todo.items()}
if chosen is clean:
return {t: p.clean_gain for t, p in todo.items()
if p.clean_gain >= boost.MIN_BOOST_DB}
return {}
def _on_boost_amplified(self, done: list, failed: list):
try:
failures = self._manager.replace_track_files(
done, label="Boost Volume", in_place=True)
except Exception as e: # never leave the boost stuck "running"
logging.getLogger(__name__).exception("Boost Volume failed")
self._boost_end(f"Boost Volume failed: {e}")
return
current = self.player.current_track
if current is not None and any(tid == current.track_id for tid, _ in done):
self.player.reopen_current()
n = len(done) - len(failures)
text = (f"Boosted {n} song{'s' if n != 1 else ''} · Edit ▸ Undo puts "
f"{'it' if n == 1 else 'them'} back" if n else "Nothing was boosted")
problems = len(failed) + len(failures)
if problems:
first = failed[0][1] if failed else failures[0][1]
text += f" · {problems} couldn't be ({first})"
self._boost_end(text)
def _convert_to_mp3(self, track_ids: list[int]):
"""Right-click › Convert to MP3…: shrink lossless songs already in
the library (gui/compress_import.ConvertLibrary)."""
from lintunes.gui import compress_import
if not lossless.ffmpeg_available():
QMessageBox.warning(
self, "Convert to MP3",
"Converting needs ffmpeg, which is not installed.\n\n"
"Install your distro's “ffmpeg” package and try again.")
return
if self._busy_worker() is not None or self._compress is not None:
self.statusBar().showMessage(
"Wait for the current import or transfer to finish first", 6000)
return
tracks = [self._manager.library.tracks[t] for t in track_ids
if t in self._manager.library.tracks]
tracks = compress_import.convertible(tracks)
if not tracks:
self.statusBar().showMessage(
"None of those songs are lossless — nothing to convert", 6000)
return
kbps = self._ask_convert_kbps(tracks)
if kbps is None:
return
batch = compress_import.ConvertLibrary(self._manager, tracks, kbps, self)
batch.status.connect(self._on_compress_status)
batch.worker_finished.connect(self._free_sync_widgets)
batch.over.connect(self._on_compress_over)
self._compress = batch
self._sync_label.setText("Converting…")
self._sync_progress.setRange(0, 100)
self._sync_progress.setValue(0)
for widget in (self._sync_label, self._sync_progress, self._sync_cancel):
widget.show()
batch.start()
def _ask_convert_kbps(self, tracks) -> int | None:
"""Confirm, and at what bitrate (starting at Preferences' one)."""
n = len(tracks)
dialog = QDialog(self)
dialog.setWindowTitle("Convert to MP3")
layout = QVBoxLayout(dialog)
what = (f"“{tracks[0].name}”" if n == 1 else f"{n} lossless songs")
text = QLabel(f"Convert {what} to MP3? Play counts, ratings and "
"playlists stay as they are. The original files go to "
"the trash, and Edit ▸ Undo brings them back.")
text.setWordWrap(True)
layout.addWidget(text)
row = QHBoxLayout()
row.addWidget(QLabel("Bitrate:"))
combo = QComboBox()
for rate in lossless.BITRATES:
combo.addItem(f"{rate} kbps", rate)
combo.setCurrentIndex(lossless.BITRATES.index(lossless.settings(self._prefs)[1]))
row.addWidget(combo)
row.addStretch(1)
layout.addLayout(row)
buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Cancel)
buttons.addButton("Convert", QDialogButtonBox.ButtonRole.AcceptRole)
buttons.accepted.connect(dialog.accept)
buttons.rejected.connect(dialog.reject)
layout.addWidget(buttons)
dialog.resize(420, dialog.sizeHint().height())
if dialog.exec() != QDialog.DialogCode.Accepted:
return None
return combo.currentData()
def _free_sync_widgets(self):
"""Hide the status-bar progress unless another transfer took it."""
if self._busy_worker() is None:
self._hide_sync_widgets()
def _show_compress_progress(self):
if self._compress is not None:
self._compress.show_window()
def _library_view_reload(self):
self._library_view.reload()
def _import_files_to_playlist(self, paths, pid, position=None):
self.import_files([Path(p) for p in paths], pid, position)
# ---- importing from a link (trav's `song` helper, in-process) ----
def _refresh_url_import_action(self):
"""One transfer owns the status-bar progress widgets at a time."""
self._url_import_action.setEnabled(self._busy_worker() is None)
def _url_import_target(self):
shown, row = "", None
if self._content.currentWidget() is self._playlist_view:
shown = self._playlist_view.playlist_id
rows = self._playlist_view.table.selected_source_rows()
row = rows[0] if rows else None
return url_import.resolve_target(
self._manager.library, shown, row, self._now_playing_context)
def _import_from_url(self):
if self._busy_worker() is not None:
return
missing = [name for name, ok in (
("yt-dlp", url_import.ytdlp_available()),
("ffmpeg", exporter.web_support.ffmpeg_available())) if not ok]
if missing:
QMessageBox.warning(
self, "Import from URL",
f"Importing from a link needs {' and '.join(missing)}, "
f"which {'is' if len(missing) == 1 else 'are'} not "
f"installed.\n\n"
"yt-dlp: pip install --user yt-dlp (or your distro's "
"package)\nffmpeg: your distro's “ffmpeg” package")
return
target = self._url_import_target()
cookies = load_config().get(url_import.COOKIES_KEY)
dialog = UrlImportDialog(
target.description if target else None, self,
cookies_browser=cookies,
library_tracks=lambda: self._manager.library.tracks.values())
accepted = dialog.exec()
if dialog.cookies_used: # the listing needed them
self._remember_cookies_browser(dialog.cookies_used)
cookies = dialog.cookies_used
if not accepted:
return
if self._ensure_music_dir() is None:
return
chosen = dialog.chosen_entries()
self._url_target = target if dialog.add_to_playlist() else None
self._url_inserted = 0
self._url_new_name = dialog.new_playlist_name()
self._url_new_cover = dialog.new_playlist_cover()
self._url_source = dialog.url()
self._url_new_pid = ""
self._url_imported = 0
self._url_identify = True
problem = self._identify_setup_problem()
self._url_note = (f"tags proposed from filenames only ({problem})"
if problem else "")
spotify = dialog.spotify_tracks()
# A Spotify/Apple list: its songs in order, the ones the library
# already has standing in as themselves (placed by _place_url_rows).
self._url_rows = dialog.link_rows()
self._url_placed = 0
self._url_current = ""
self._url_owned = sum(1 for r in self._url_rows or [] if r["owned"])
if self._url_rows is not None and not spotify:
self._place_url_rows(final=True) # nothing to download
owned = sum(1 for r in self._url_rows if r["owned"])
self.statusBar().showMessage(
f"{owned} song{'' if owned == 1 else 's'} already in your "
"library" + (", added to the playlist" if owned and (
self._url_target is not None or self._url_new_pid)
else "") + " · nothing to download", 12000)
self._url_rows = None
return
if self._url_batch is not None:
self._url_batch.cancel()
self._url_batch = None
if max(len(spotify), len(chosen)) > 1:
batch = IdentifyCollector(
self._prefs.acoustid.get("api_key", "").strip(), self)
batch.progress.connect(self._on_url_batch_progress)
batch.ready.connect(self._on_url_batch_ready)
self._url_batch = batch
if spotify:
# Spotify won't hand over audio: each song is found on YouTube
# and arrives already wearing Spotify's tags.
worker = url_import.SpotifyImportWorker(
spotify, self, cookies_browser=cookies)
else:
# The chosen songs by their own pages, never the list link: that
# would download the whole list again, and a Mix reshuffles.
worker = url_import.UrlImportWorker(
dialog.download_urls(), self,
cookies_browser=cookies)
if self._url_progress is not None:
self._url_progress.close()
self._url_progress.deleteLater()
self._url_progress = None
self._shazam_window = None
if len(chosen) > 1:
self._url_progress = UrlImportProgress(chosen, self)
self._url_progress.stop_requested.connect(
self._confirm_cancel_url_import)
worker.item_failed.connect(self._url_progress.failed)
worker.progress.connect(self._url_progress.progress)
self._url_progress.show()
worker.cookies_used.connect(self._remember_cookies_browser)
worker.item_started.connect(self._on_url_item_started)
worker.item_failed.connect(self._on_url_item_failed)
worker.progress.connect(self._sync_progress.setValue)
worker.downloaded.connect(self._on_url_downloaded)
worker.finished.connect(self._on_url_finished)
worker.failed.connect(self._on_url_failed)
self._url_worker = worker
self._sync_label.setText("Downloading…")
self._sync_progress.setRange(0, 100)
self._sync_progress.setValue(0)
self._sync_cancel.show()
self._sync_label.show()
self._sync_progress.show()
worker.start()
def _show_url_progress(self):
if (self._url_progress is not None
and self._url_worker is not None and self._url_worker.busy()):
self._url_progress.show()
self._url_progress.raise_()
self._url_progress.activateWindow()
def _remember_cookies_browser(self, browser: str):
"""A bot-checked link got through on this browser's cookies: send
them from the start next time. config.json, not preferences — the
browser holding a YouTube login is this machine's business."""
config = load_config()
if config.get(url_import.COOKIES_KEY) != browser:
config[url_import.COOKIES_KEY] = browser
save_config(config)
def _on_url_item_started(self, index: int, count: int, item_id: str,
title: str):
self._url_current = item_id
if self._url_progress is not None:
self._url_progress.started(item_id)
short = title if len(title) <= 40 else title[:39] + "…"
where = f"{index} of {count} · " if count > 1 else ""
self._sync_label.setText(f"Downloading {where}{short}")
self._sync_progress.setValue(0)
def _place_url_rows(self, final: bool = False):
"""Put a Spotify/Apple list's songs into the playlists in the link's
order, as far as they're known: an owned song or a landed download
goes in, a song still downloading holds back everything after it,
a failed one is skipped. ``final``: nothing more is coming."""
rows = self._url_rows or []
ready = []
while self._url_placed < len(rows):
row = rows[self._url_placed]
if row["download"] and row["owned"] is None and not final:
break # still to land (or fail)
self._url_placed += 1
if row["owned"] is not None \
and row["owned"] in self._manager.library.tracks:
ready.append(row["owned"])
if not ready:
return
target = self._url_target
if target is not None and target.pid in self._manager.library.playlists:
position = (None if target.position is None
else target.position + self._url_inserted)
self._manager.add_tracks_to_playlist(target.pid, ready, position)
self._url_inserted += len(ready)
if self._url_new_name or self._url_new_pid:
self._add_to_new_url_playlist(
[self._manager.library.tracks[t] for t in ready])
def _url_row_done(self, key: str, track_id):
"""A download of a Spotify/Apple list's song landed (a track id) or
failed (None)."""
for row in self._url_rows or []:
if row["key"] == key and row["download"] and row["owned"] is None:
row["owned"] = track_id
row["download"] = track_id is not None
break
self._place_url_rows()
def _on_url_item_failed(self, key: str, _reason: str = ""):
if self._url_rows is not None:
self._url_row_done(key, None)
def _on_url_downloaded(self, path: str):
"""One song is off the network: file it and identify it now, so the
first dialog can be up while the rest are still downloading."""
if self._url_rows is not None:
imported = self.import_files([Path(path)])
self._url_row_done(self._url_current,
imported[0].track_id if imported else None)
self._url_imported += len(imported)
if self._url_progress is not None:
self._url_progress.landed(bool(imported))
if imported and self._url_identify:
if self._url_batch is not None:
self._url_batch.add(imported)
else:
self._enqueue_identify(imported)
return
target = self._url_target
pid, position = "", None
if target is not None and target.pid in self._manager.library.playlists:
pid = target.pid
if target.position is not None:
# Each song goes after the ones already added, so the batch
# keeps the link's order, all of it above the selected song.
position = target.position + self._url_inserted
imported = self.import_files([Path(path)], pid, position)
if pid:
self._url_inserted += len(imported)
if imported and (self._url_new_name or self._url_new_pid):
self._add_to_new_url_playlist(imported)
self._url_imported += len(imported)
if self._url_progress is not None:
self._url_progress.landed(bool(imported))
if imported and self._url_identify:
if self._url_batch is not None:
self._url_batch.add(imported) # reviewed when all are in
else:
self._enqueue_identify(imported)
def _add_to_new_url_playlist(self, tracks):
"""Into the link's own new playlist, in the order the songs land
(the link's order). One undo step: undoing "New Playlist" takes
it away with everything in it."""
if self._url_new_pid not in self._manager.library.playlists:
if not self._url_new_name:
return # it was made, then deleted mid-import
playlist = self._manager.create_playlist(
self._url_new_name, source_url=self._url_source)
self._url_new_pid = playlist.persistent_id
self._url_new_name = ""
if self._url_new_cover: # shown by the art panel
playlist_art.fetch_in_background(
self._url_new_cover, self._manager.data_dir,
playlist.persistent_id,
saved=self._playlist_art_saved.emit)
self._url_new_cover = ""
self._manager.add_tracks_to_playlist(
self._url_new_pid, [t.track_id for t in tracks], undoable=False)
def _finish_url_import(self):
if self._url_rows is not None:
self._place_url_rows(final=True) # the rest, in order
self._url_rows = None
if self._url_worker is not None:
self._url_worker.cleanup()
self._hide_sync_widgets()
if self._url_batch is not None:
self._url_batch.close() # no more songs are coming
def _on_url_batch_progress(self, done: int, total: int):
worker = self._url_worker
if worker is None or not worker.busy():
self.statusBar().showMessage(
f"Identifying the imported songs: {done} of {total}…")
def _on_url_batch_ready(self, entries: list):
"""Every song is downloaded and looked up: one window for them all
(one song, if that's all that landed, gets the ordinary one)."""
if self.sender() is not self._url_batch:
return
self._url_batch = None
library = self._manager.library
entries = [(t, c) for t, c in entries if t.track_id in library.tracks]
if not entries or not self._url_identify:
return
self.statusBar().clearMessage()
if len(entries) == 1:
analysis = analyze(entries)
self._when_app_active(
lambda: self._review_individually(analysis.rows))
return
analysis = analyze(entries)
self._when_app_active(lambda: self._show_batch_review(analysis))
def _show_batch_review(self, analysis):
dialog = IdentifyBatchDialog(analysis, album_art_query(analysis),
self)
if not dialog.exec():
self.statusBar().showMessage(
"Identify cancelled — the songs keep the tags they have",
6000)
return
if dialog.outcome == dialog.REVIEW_ALL:
self._review_individually(dialog.all_rows())
return
edits = dialog.edits()
if edits:
# 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)
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, image, mime)
if edits:
self.statusBar().showMessage(
f"Updated tags for {len(edits)} song(s)", 6000)
self._review_individually(dialog.unchecked_rows())
def _review_individually(self, rows: list):
"""The ordinary Identify window, one song at a time, from lookups
already made."""
rows = [r for r in rows if r.candidates
and r.track.track_id in self._manager.library.tracks]
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,
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
window only ever stacks over LinTunes, but one opened while another
app has focus would still jump in front of it. Meanwhile the window
asks for attention instead."""
app = QApplication.instance()
if app.applicationState() == Qt.ApplicationState.ApplicationActive:
show()
return
self._popups_waiting.append(show)
QApplication.alert(self)
if not self._popups_hooked:
self._popups_hooked = True
app.applicationStateChanged.connect(self._on_app_state_changed)
def _on_app_state_changed(self, state):
if (state == Qt.ApplicationState.ApplicationActive
and self._popups_waiting):
waiting, self._popups_waiting = self._popups_waiting, []
def run():
for show in waiting:
show()
# After the activation event has finished being delivered.
QTimer.singleShot(0, run)
def _on_url_finished(self, summary: dict):
self._finish_url_import()
if self._url_progress is not None:
self._url_progress.finish(summary["cancelled"])
count = self._url_imported
if summary["cancelled"]:
msg = f"Import cancelled — {count} song(s) imported"
else:
msg = f"Imported {count} song(s) from the link"
sounds.play_done(self._prefs)
target = self._url_target
playlist = (self._manager.library.playlists.get(target.pid)
if target is not None else None)
if playlist is not None and count:
msg += f" into “{playlist.name}”"
owned = self._url_owned
if owned:
msg += f" · {owned} already in your library"
if self._url_target is not None or self._url_new_pid:
msg += f", added in {'its' if owned == 1 else 'their'} place"
if summary["errors"]:
msg += f" · {len(summary['errors'])} couldn't be downloaded"
if self._url_note and count and self._url_identify:
msg += f" · {self._url_note}"
self.statusBar().showMessage(msg, 12000)
def _on_url_failed(self, message: str):
self._finish_url_import()
if self._url_progress is not None:
self._url_progress.finish(False)
self._when_app_active(lambda: QMessageBox.warning(
self, "Import from URL",
f"Couldn't import from that link:\n\n{message}"))
# ---- Import Shazams (Connections menu) ----
def _import_shazams(self, target=_CURRENT_TARGET):
"""``target`` is the playlist to add to (a Full Rabbit Sync latches
it at its click); left out, it's the current one."""
if self._busy_worker() is not None:
self.statusBar().showMessage(
"Wait for the current transfer to finish first", 6000)
return
missing = [name for name, ok in (
("adb", andtunes_install.adb_path() is not None),
("yt-dlp", url_import.ytdlp_available()),
("ffmpeg", exporter.web_support.ffmpeg_available())) if not ok]
if missing:
QMessageBox.warning(
self, "Import Shazams",
f"Importing Shazams needs {', '.join(missing)}, which "
f"{'is' if len(missing) == 1 else 'are'} not installed.\n\n"
"adb: Fedora's “android-tools” package\n"
"yt-dlp: pip install --user yt-dlp (or your distro's "
"package)\nffmpeg: your distro's “ffmpeg” package")
return
if target is _CURRENT_TARGET:
target = self._url_import_target()
handled = shazam.handled_ids(self._prefs) | shazam.legacy_handled()
dialog = ShazamPreviewDialog(
shazam.ShazamReader(), handled,
self._manager.library.tracks.values(),
target.description if target else None, self)
if not dialog.exec() or self._ensure_music_dir() is None:
return
# Unticked and already-owned songs are dealt with now; the others
# only once they're imported, so a failure is offered again.
shazam.mark_handled(self._prefs, dialog.passed_over())
chosen = dialog.chosen()
if not chosen:
return
self._url_target = target if dialog.add_to_playlist() else None
self._url_inserted = 0
self._url_imported = 0
self._url_identify = True
self._url_note = ""
if self._url_batch is not None:
self._url_batch.cancel()
self._url_batch = None
self._shazam_identify = []
worker = shazam.ShazamImportWorker(
chosen, self,
cookies_browser=load_config().get(url_import.COOKIES_KEY))
if self._url_progress is not None:
self._url_progress.close()
self._url_progress.deleteLater()
window = ShazamImportWindow(chosen, self)
window.stop_requested.connect(self._confirm_cancel_url_import)
window.apply_tags.connect(self._apply_shazam_tags)
self._url_progress = self._shazam_window = window
worker.stage.connect(window.set_stage)
worker.item_failed.connect(window.failed)
worker.cookies_used.connect(self._remember_cookies_browser)
worker.item_started.connect(self._on_shazam_started)
worker.progress.connect(self._sync_progress.setValue)
worker.landed.connect(self._on_shazam_landed)
worker.finished.connect(self._on_shazam_finished)
worker.failed.connect(self._on_shazam_failed)
self._url_worker = worker
self._sync_label.setText("Importing Shazams…")
self._sync_progress.setRange(0, 100)
self._sync_progress.setValue(0)
self._sync_cancel.show()
self._sync_label.show()
self._sync_progress.show()
window.show()
worker.start()
def _on_shazam_started(self, index: int, count: int, _rid: str,
title: str):
short = title if len(title) <= 40 else title[:39] + "…"
self._sync_label.setText(f"Shazam {index} of {count} · {short}")
self._sync_progress.setValue(0)
def _on_shazam_landed(self, rid: str, path: str):
"""One song is downloaded and wearing Shazam's tags: import it, then
look it up for the window's tagging panel."""
window = self._shazam_window
if window is not None:
window.importing(rid)
target = self._url_target
pid, position = "", None
if target is not None and target.pid in self._manager.library.playlists:
pid = target.pid
if target.position is not None:
position = target.position + self._url_inserted
imported = self.import_files([Path(path)], pid, position)
if pid:
self._url_inserted += len(imported)
self._url_imported += len(imported)
if imported:
shazam.mark_handled(self._prefs, [rid])
if window is not None:
window.imported(rid, imported[0] if imported else None)
if imported:
self._shazam_identify.append((rid, imported[0]))
if self._shazam_identifier is None:
self._shazam_identify_next()
def _shazam_identify_next(self):
"""One lookup at a time (AcoustID allows three a second)."""
self._shazam_identifier = None
while self._shazam_identify:
rid, track = self._shazam_identify.pop(0)
if track.track_id in self._manager.library.tracks:
break
else:
return
window = self._shazam_window
identifier = TrackIdentifier()
identifier.finished.connect(
lambda result, r=rid, w=window:
self._on_shazam_identified(w, r, result))
self._shazam_identifier = identifier
identifier.identify(track,
self._prefs.acoustid.get("api_key", "").strip())
def _on_shazam_identified(self, window, rid: str, result: dict):
# The file already carries Shazam's own title and artist, which beat
# anything read off a YouTube upload's name: only real matches.
candidates = [c for c in result.get("candidates", [])
if c.source != "filename"]
if window is not None and window is self._shazam_window:
window.identified(rid, candidates)
self._shazam_identify_next()
def _apply_shazam_tags(self, track_id: int, fields: dict):
if track_id in self._manager.library.tracks:
# The edit funnel writes the tags, may relocate the file and
# records one undo step.
self._manager.edit_track_fields(track_id, fields)
def _on_shazam_finished(self, summary: dict):
self._finish_url_import()
window = self._shazam_window
if window is not None:
window.finish(summary["cancelled"])
if window.waiting_to_tag() and not window.isVisible():
# Hidden mid-run, and the status-bar line that brought it
# back is gone: songs still waiting to be tagged reopen it.
self._when_app_active(window.show)
count = self._url_imported
if summary["cancelled"]:
msg = f"Shazam import stopped — {count} song(s) imported"
else:
msg = f"Imported {count} Shazam(s)"
sounds.play_done(self._prefs)
target = self._url_target
playlist = (self._manager.library.playlists.get(target.pid)
if target is not None else None)
if playlist is not None and count:
msg += f" into “{playlist.name}”"
if summary["errors"]:
msg += f" · {len(summary['errors'])} couldn't be found"
self.statusBar().showMessage(msg, 12000)
def _on_shazam_failed(self, message: str):
self._finish_url_import()
if self._shazam_window is not None:
self._shazam_window.finish(False)
self._when_app_active(lambda: QMessageBox.warning(
self, "Import Shazams",
f"Couldn't import the Shazams:\n\n{message}"))
def _confirm_cancel_url_import(self):
box = QMessageBox(self)
box.setWindowTitle("Stop downloading")
box.setText("Stop downloading from the link?\n"
"Songs already imported stay in your library.")
stop = box.addButton("Stop Downloading",
QMessageBox.ButtonRole.DestructiveRole)
keep = box.addButton("Keep Downloading",
QMessageBox.ButtonRole.RejectRole)
box.setDefaultButton(keep)
box.exec()
if box.clickedButton() is stop and self._url_worker is not None:
self._url_worker.cancel()
# ---- deleting tracks ----
def _delete_tracks(self, track_ids: list[int], delete_files: bool):
tracks = [self._manager.library.tracks[tid] for tid in track_ids
if tid in self._manager.library.tracks]
if not tracks or not self._confirm_delete(tracks, delete_files):
return
removed, failures = self._manager.delete_tracks(
[t.track_id for t in tracks], delete_files=delete_files)
if removed:
where = "moved to Trash" if delete_files else "file kept"
self.statusBar().showMessage(
f"Removed {len(removed)} song(s) from your library "
f"({where}) — undo with "
f"{'⌘Z' if os_paths.IS_MAC else 'Ctrl+Z'}", 8000)
if failures:
QMessageBox.warning(
self, "Couldn't delete",
f"{len(failures)} file(s) could not be moved to the Trash, so "
"those songs are still in your library:\n\n"
+ "\n".join(f"• “{name}”: {err}" for name, err in failures[:5]))
def _confirm_delete(self, tracks: list, delete_files: bool) -> bool:
if len(tracks) == 1:
track = tracks[0]
who = f" by {track.artist}" if track.artist else ""
question = f"Delete “{track.name}”{who} from your library?"
else:
question = f"Delete {len(tracks)} songs from your library?"
if delete_files:
fate = ("The file will be moved to your Trash, so you can put it "
"back later." if len(tracks) == 1 else
"The files will be moved to your Trash, so you can put "
"them back later.")
else:
fate = ("The file stays where it is on disk."
if len(tracks) == 1 else
"The files stay where they are on disk.")
doomed = {t.track_id for t in tracks}
playlists = {pid for pid, _name in
[entry for t in tracks
for entry in self._manager.playlists_containing(t.track_id)]}
lines = [question, fate]
if playlists:
lines.append(f"{'It' if len(doomed) == 1 else 'They'} will also be "
f"removed from {len(playlists)} playlist(s).")
box = QMessageBox(self)
box.setIcon(QMessageBox.Icon.Warning)
box.setWindowTitle("Delete from Library")
box.setText("\n".join(lines))
delete_button = box.addButton(
"Delete Song" if len(tracks) == 1 else "Delete Songs",
QMessageBox.ButtonRole.DestructiveRole)
cancel = box.addButton("Cancel", QMessageBox.ButtonRole.RejectRole)
box.setDefaultButton(cancel)
box.exec()
return box.clickedButton() is delete_button
def _on_tracks_removed(self, track_ids: list):
"""Tracks left the library (deleted here, or undone/redone). Keep the
player off dead ids and rebuild the library view."""
self.player.drop_tracks(set(track_ids))
self._on_library_reloaded()
self._update_totals()
def _on_tracks_restored(self, track_ids: list):
"""An undo put tracks back — show them again."""
self._on_library_reloaded()
self._update_totals()
# ---- album art download ----
def _download_album_art(self, track_ids: list[int]):
"""Fetch cover art from the iTunes Search API for the selection,
grouped per album, each behind its own confirmation dialog."""
groups: dict[tuple, dict] = {}
skipped = 0
for tid in track_ids:
track = self._manager.library.tracks.get(tid)
if track is None:
continue
artist = track.album_artist or track.artist
if not artist or not track.album:
skipped += 1
continue
key = (artist.casefold(), track.album.casefold())
group = groups.setdefault(
key, {"artist": artist, "album": track.album, "tracks": []})
group["tracks"].append(track)
if skipped:
self.statusBar().showMessage(
f"Skipped {skipped} track(s) with no artist/album to search by",
6000)
self._art_groups = list(groups.values())
self._art_next_group()
def _art_next_group(self):
if not self._art_groups:
return
group = self._art_groups.pop(0)
self.statusBar().showMessage(
f"Searching artwork for {group['artist']} — {group['album']}…")
# Kept as an attribute so the fetcher (and its thread's signal source)
# outlives this method.
self._art_fetcher = AlbumArtFetcher()
self._art_fetcher.search_finished.connect(
lambda result, g=group: self._on_art_search(g, result))
self._art_fetcher.search(group["artist"], group["album"])
def _on_art_search(self, group, result):
if "error" in result:
self.statusBar().showMessage(
f"Artwork search failed: {result['error']}", 6000)
elif not result["candidates"]:
self.statusBar().showMessage(
f"No artwork found for {group['artist']} — {group['album']}",
6000)
else:
self.statusBar().clearMessage()
whole_album = album_tracks(self._manager.library,
group["artist"], group["album"])
dialog = AlbumArtDialog(result["candidates"],
len(group["tracks"]),
album_count=len(whole_album), parent=self)
if dialog.exec() and dialog.selected_image:
targets = whole_album if dialog.apply_to_album \
else group["tracks"]
self._embed_album_art(targets, dialog.selected_image,
dialog.selected_mime)
self._art_next_group()
def _embed_album_art(self, tracks, image: bytes, mime: str):
"""Embed confirmed artwork into each track's file (not undoable —
see ``art_ops``)."""
done, failures = embed_artwork(self._manager, tracks, image, mime)
if failures:
QMessageBox.warning(
self, "Download Album Art",
"Couldn't embed artwork in some files:\n\n"
+ "\n".join(failures[:10]))
if done:
# Normally track_updated already did this, but only when the
# file's size changed.
self._sidebar.art.refresh()
if done and not failures:
noun = "track" if done == 1 else "tracks"
self.statusBar().showMessage(
f"Artwork embedded in {done} {noun}", 5000)
# ---- track identification (fingerprint lookup) ----
def _identify_tracks(self, track_ids: list[int]):
"""Fingerprint the selection and look each track up on AcoustID, one
at a time, each behind its own proposal dialog."""
if not fpcalc_available():
QMessageBox.warning(
self, "Identify Track",
"Track identification needs the fpcalc tool from Chromaprint.\n\n"
+ ("Install it (Homebrew: brew install chromaprint) and try "
"again." if os_paths.IS_MAC else
"Install it (Fedora: chromaprint-tools, Debian: "
"libchromaprint-tools) and try again."))
return
api_key = self._prefs.acoustid.get("api_key", "").strip()
if not api_key:
QMessageBox.information(
self, "Identify Track",
"AcoustID needs a free application key.\n\n"
"Register one at acoustid.org/new-application, then paste it "
"into Preferences under Track Identification.")
return
tracks = []
skipped = 0
for tid in track_ids:
track = self._manager.library.tracks.get(tid)
if track is None:
continue
if not track.location:
skipped += 1
continue
tracks.append(track)
if skipped:
self.statusBar().showMessage(
f"Skipped {skipped} track(s) with no file to fingerprint", 6000)
if not tracks:
return
self._enqueue_identify(tracks)
# ---- Prepare for DJ ----
def _prepare_playlist_for_dj(self, pid: str):
playlist = self._manager.library.playlists.get(pid)
if playlist is not None:
self._prepare_for_dj(list(playlist.track_ids))
def _prepare_for_dj(self, track_ids: list[int]):
"""BPM and vocals for these songs now, so they load onto a deck
instantly — with the vocals model chosen in Preferences › DJ."""
from lintunes.dj import stems
from lintunes.dj.prepare import DjPrepWorker
if self._busy_worker() is not None:
self.statusBar().showMessage(
"Wait for the current transfer to finish first", 6000)
return
if not stems.available() and not stems.instant_available():
QMessageBox.information(
self, "Prepare for DJ",
"Separating vocals needs Demucs or instant vocal splitting, "
"and neither is set up on this computer. Instant is a button "
"in Preferences › DJ; Demucs is a one-time ~1 GB download:\n\n"
+ stems.setup_command())
return
items, seen = [], set()
for tid in track_ids:
track = self._manager.library.tracks.get(tid)
if track is None or not track.location or tid in seen:
continue
seen.add(tid)
label = (f"{track.artist} — {track.name}" if track.artist
else track.name) or Path(track.location).name
items.append((tid, track.location, label, bool(track.bpm)))
if not items:
return
model = (stems.INSTANT if stems.default_engine(self._prefs) == stems.FAST
else stems.model_choice(self._prefs))
worker = DjPrepWorker(items, model, stems.gentle_choice(self._prefs), self)
self._dj_prep_bpm = {}
worker.bpm_found.connect(self._dj_prep_bpm.__setitem__)
worker.progress.connect(self._on_dj_prep_progress)
worker.finished.connect(self._on_dj_prep_finished)
self._dj_prep_worker = worker
self._sync_label.setText(f"Preparing for DJ ({stems.label(model)})…")
self._sync_progress.setRange(0, len(items))
self._sync_progress.setValue(0)
self._sync_cancel.show()
self._sync_label.show()
self._sync_progress.show()
worker.start()
def _on_dj_prep_progress(self, done: int, total: int, label: str):
self._sync_progress.setRange(0, total)
self._sync_progress.setValue(done)
if label:
short = label if len(label) <= 48 else label[:47] + "…"
where = f"{done + 1} of {total} · " if total > 1 else ""
self._sync_label.setText(f"DJ {where}{short}")
def _on_dj_prep_finished(self, summary: dict):
self._hide_sync_widgets()
found, self._dj_prep_bpm = self._dj_prep_bpm, {}
if found:
self._manager.set_tracks_bpm(found)
msg = (f"Prepared {summary['done']} song(s) for DJ"
f" · {summary['split']} vocals separated · {summary['bpm']} BPM found")
if summary["cancelled"]:
msg = "Prepare for DJ stopped — " + msg[0].lower() + msg[1:]
if summary["failed"]:
msg += f" · {summary['failed']} couldn't be done"
if not summary["cancelled"]:
sounds.play_done(self._prefs)
self.statusBar().showMessage(msg, 12000)
# ---- Calculate BPM ----
def _calculate_bpm(self, track_ids: list[int]):
"""Measure the tempo of the selection on a worker thread, with the
status-bar progress bar; results land as one undoable edit."""
if not exporter.web_support.ffmpeg_available():
QMessageBox.warning(
self, "Calculate BPM",
"Calculating BPM needs ffmpeg, which is not installed.\n\n"
"Install your distro's “ffmpeg” package and try again.")
return
if self._busy_worker() is not None:
self.statusBar().showMessage(
"Wait for the current transfer to finish first", 6000)
return
items = []
for tid in track_ids:
track = self._manager.library.tracks.get(tid)
if track is not None and track.location:
label = (f"{track.artist} — {track.name}" if track.artist
else track.name) or Path(track.location).name
items.append((tid, track.location, label))
if not items:
return
self._bpm_results = {}
worker = bpm_detect.BpmWorker(items, self)
worker.progress.connect(self._on_bpm_progress)
worker.detected.connect(self._bpm_results.__setitem__)
worker.finished.connect(self._on_bpm_finished)
self._bpm_worker = worker
self._sync_label.setText("Calculating BPM…")
self._sync_progress.setRange(0, len(items))
self._sync_progress.setValue(0)
self._sync_cancel.show()
self._sync_label.show()
self._sync_progress.show()
worker.start()
def _on_bpm_progress(self, done: int, total: int, label: str):
self._sync_progress.setRange(0, total)
self._sync_progress.setValue(done)
if label:
short = label if len(label) <= 40 else label[:39] + "…"
where = f"{done + 1} of {total} · " if total > 1 else ""
self._sync_label.setText(f"BPM {where}{short}")
def _on_bpm_finished(self, summary: dict):
self._hide_sync_widgets()
results, self._bpm_results = self._bpm_results, {}
self._manager.set_tracks_bpm(results)
if len(results) == 1 and not summary["cancelled"]:
msg = f"BPM: {next(iter(results.values()))}"
else:
msg = f"BPM set for {len(results)} track(s)"
if summary["cancelled"]:
msg = "Calculate BPM stopped — " + msg[0].lower() + msg[1:]
if summary["no_beat"]:
msg += f" · no steady beat in {summary['no_beat']}"
if summary["failed"]:
msg += f" · {summary['failed']} couldn't be read"
if not summary["cancelled"]:
sounds.play_done(self._prefs)
self.statusBar().showMessage(msg, 10000)
def _identify_setup_problem(self) -> str:
"""Why an AcoustID lookup can't run on this machine, or ''."""
if not fpcalc_available():
return "fpcalc isn't installed"
if not self._prefs.acoustid.get("api_key", "").strip():
return "no AcoustID key in Preferences"
return ""
def _enqueue_identify(self, tracks: list):
"""Queue tracks for Identify and start the queue if it's idle. An
Import from URL adds songs one at a time while an earlier one is still
behind its dialog, so the queue can grow mid-run."""
if not self._identify_running:
self._identify_queue = []
self._identify_total = 0
self._identify_queue.extend(tracks)
self._identify_total += len(tracks)
if not self._identify_running:
self._identify_next()
def _identify_next(self):
if not self._identify_queue:
self._identify_running = False
return
self._identify_running = True
track = self._identify_queue.pop(0)
if track.track_id not in self._manager.library.tracks:
self._identify_next() # deleted while it waited its turn
return
done = self._identify_total - len(self._identify_queue)
counter = (f" ({done} of {self._identify_total})"
if self._identify_total > 1 else "")
self.statusBar().showMessage(
f"Identifying “{track.name}”{counter}…")
# Kept as an attribute so the identifier (and its thread's signal
# source) outlives this method.
self._identifier = TrackIdentifier()
self._identifier.finished.connect(
lambda result, t=track: self._on_identified(t, result))
# Read fresh for every track. With no key (only an Import from URL
# gets this far without one) the identifier proposes from the
# filename alone.
self._identifier.identify(
track, self._prefs.acoustid.get("api_key", "").strip())
def _on_identified(self, track, result: dict):
if "error" in result:
self.statusBar().showMessage(
f"Couldn't identify “{track.name}”: {result['error']}", 6000)
elif not result["candidates"]:
self.statusBar().showMessage(
f"Nothing to propose for “{track.name}” — no database match "
f"and the filename says nothing", 6000)
else:
self.statusBar().clearMessage()
self._when_app_active(
lambda: self._show_identify(track, result["candidates"]))
return
self._identify_next()
def _show_identify(self, track, candidates):
if track.track_id in self._manager.library.tracks:
dialog = IdentifyDialog(track, candidates,
remaining=len(self._identify_queue),
parent=self, find_art=True,
embed_art=not self._has_artwork(track))
accepted = dialog.exec()
if accepted:
fields = dialog.result_fields()
if fields:
# The edit funnel writes the tags, may relocate the file
# and records one undo step — see LibraryManager.
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
# Also covers songs a URL import has yet to download: they
# still import, they just don't get a dialog each.
self._url_identify = False
if self._url_batch is not None:
self._url_batch.cancel()
self._url_batch = None
self.statusBar().clearMessage()
return
self._identify_next()
# ---- relocating a moved/renamed file ----
def _existing_ancestor(self, path: str) -> str:
"""Deepest existing directory at or above `path`'s parent, so the file
picker opens somewhere real even if the exact folder is gone."""
if path:
p = Path(path).parent
while not p.exists() and p != p.parent:
p = p.parent
if p.exists():
return str(p)
music = self._music_import_dir()
return str(music) if music and music.exists() else str(Path.home())
def _on_track_missing(self, track):
"""A track's file is gone (moved/renamed outside lintunes). Offer to
relocate it manually; on success, repoint the track and resume. One
renamed to its NFC spelling (Syncthing does that) is followed
without asking."""
if self._manager.repair_location(track):
QTimer.singleShot(0, self.player.retry_current)
return
box = QMessageBox(self)
box.setIcon(QMessageBox.Icon.Warning)
box.setWindowTitle("Can't play track")
box.setText(f"Can't play “{track.name}”.")
box.setInformativeText(
f"File not found:\n{track.location or '(no location)'}")
locate_btn = box.addButton("Locate File…", QMessageBox.ButtonRole.ActionRole)
box.addButton(QMessageBox.StandardButton.Cancel)
box.exec()
if box.clickedButton() is not locate_btn:
return
chosen, _filter = QFileDialog.getOpenFileName(
self, f"Locate “{track.name}”", self._existing_ancestor(track.location),
"Audio files (*.mp3 *.m4a *.flac *.aac *.wav *.aiff *.aif);;All files (*)")
if not chosen:
return
self._manager.set_track_location(track.track_id, chosen)
# Defer the retry so it runs after this modal handler unwinds.
QTimer.singleShot(0, self.player.retry_current)
# ---- window-level drops (import anywhere) ----
def dragEnterEvent(self, event):
if event.mimeData().hasUrls():
event.acceptProposedAction()
def dropEvent(self, event):
paths = [Path(u.toLocalFile()) for u in event.mimeData().urls()
if u.isLocalFile()]
if paths:
self.import_files(paths)
event.acceptProposedAction()
# ---- playback ----
def play_pause(self):
"""Play/pause like iTunes: with nothing cued, start the visible
view's tracks (from the selected row, else the top)."""
if getattr(self, "_dj_on", False):
return # each deck has its own play button
if self.player.current_track is not None:
self.player.toggle_play()
return
view = self._content.currentWidget()
ids = view.table.view_order_track_ids()
if not ids:
return
selected = view.table.selectionModel().selectedRows()
start = selected[0].row() if selected else 0
self._play_from_view(view, ids, start)
# ---- DJ mode ----
ANIMATE_MS = 350
def set_dj_mode(self, on: bool):
"""Open or close the DJ shelf: the window parts under the row of
transport boxes and the shelf shows in the gap; closing plays the
same thing backwards. The main player pauses while it's open —
unless both decks are empty: then its song carries on and Deck A
takes it over without a gap, and closing goes back to it."""
on = bool(on)
if on == self._dj_on:
return
self._dj_on = on
if self._dj_action.isChecked() != on:
self._dj_action.blockSignals(True)
self._dj_action.setChecked(on)
self._dj_action.blockSignals(False)
from lintunes.gui import track_table
if on:
shelf = self._ensure_dj()
handoff = (self.player.is_local and self.player.current_track is not None
and all(v.track is None for v in shelf.views))
# pauses it (but not the song Deck A is about to take), and keeps it so
self.player.set_suspended(True, pause=not handoff)
target = self._dj_target_height()
self._transport.set_dj_mode(True, self._dj_titles())
track_table.deck_tag = self._deck_tag
shelf.set_master(self._dj_master())
shelf.set_layout_height(target) # laid out full size, revealed
split, before = self._snapshot_below_boxes()
shelf.setFixedHeight(target)
shelf.show()
shelf.start()
shelf.set_visualizer(self._transport._visualizer)
if handoff:
self._hand_to_deck(shelf)
self._sidebar.art.hide() # room for the lists instead
self._slide(split, before, shift=target + self._row_gap(), opening=True)
else:
shelf = self._dj
track_table.deck_tag = None
shelf.set_layout_height(shelf.height()) # covered, not squeezed
split, before = self._snapshot_below_boxes(shelf)
shift = shelf.height() + self._row_gap()
self._dj_closed_now()
self._slide(split, before, shift=shift, opening=False)
self._refresh_tables()
def _hand_to_deck(self, shelf):
"""Load the playing song on Deck A while the main player carries
on, then cross over: the deck starts where the song will be heard a
sink's latency from now and the main player pauses as that arrives.
Where it paused is the pin closing goes back to."""
track = self.player.current_track
view = shelf.views[0]
shelf.crossfader.setValue(0) # Deck A alone, at full level
def ready(loaded):
if not self._dj_on:
return
current = self.player.current_track
if loaded is None or current is None or current.track_id != track.track_id:
self.player.pause() # it failed, or the song moved on
return
position = self.player.position_ms()
if not self.player.is_playing():
shelf.cue(loaded, position / 1000, play=False)
self._dj_pin = (track.track_id, position, False)
return
shelf.cue(loaded, position / 1000, play=True)
QTimer.singleShot(shelf.latency_ms(), lambda: self._pin_main(track.track_id))
shelf.load(view, track, handoff=ready)
def _pin_main(self, track_id: int):
if not self._dj_on:
return # closed in the meantime: it never stopped
self.player.pause()
self._dj_pin = (track_id, self.player.position_ms(), True)
def _back_to_pin(self):
"""DJ mode closed: the main player goes back to where Deck A took
its song over, playing if it was."""
pin, self._dj_pin = self._dj_pin, None
current = self.player.current_track
if pin is None or current is None or current.track_id != pin[0]:
return
_, position, playing = pin
self.player.seek(position)
if playing:
self.player.play()
def _ensure_dj(self):
if self._dj is None:
from lintunes.gui.dj_shelf import DjShelf
shelf = DjShelf(self._manager, self._prefs)
shelf.hide()
shelf.message.connect(lambda msg: self.statusBar().showMessage(msg, 8000))
shelf.decks_changed.connect(self._on_decks_changed)
shelf.resize_requested.connect(self._on_dj_resize)
shelf.resize_finished.connect(self._on_dj_resize_done)
shelf.resize_reset.connect(self._on_dj_resize_reset)
self._transport.volume_level_changed.connect(
lambda _level: shelf.set_master(self._dj_master()))
self._transport.insert_shelf(shelf)
self._dj = shelf
return self._dj
def _dj_master(self) -> float:
"""The volume slider as linear gain, through Qt's curve, so a
position is as loud in DJ mode as out of it."""
from PyQt6.QtMultimedia import QAudio
return QAudio.convertVolume(
self._transport.volume_level(),
QAudio.VolumeScale.LogarithmicVolumeScale,
QAudio.VolumeScale.LinearVolumeScale)
def _dj_geometry(self) -> tuple[int, int, int]:
"""(viewport with the shelf closed, row height, current shelf)."""
table = self._content.currentWidget().table
row = table.verticalHeader().defaultSectionSize()
current = self._dj.height() if self._dj is not None and self._dj.isVisible() else 0
return table.viewport().height() + current, row, current
def _dj_bounds(self) -> tuple[int, int]:
from lintunes.gui.dj_shelf import height_bounds
viewport, row, _ = self._dj_geometry()
return height_bounds(viewport, row)
def _dj_target_height(self) -> int:
from lintunes.gui.dj_shelf import default_height
viewport, row, _ = self._dj_geometry()
low, high = self._dj_bounds()
saved = load_config().get("dj_shelf_height")
target = int(saved) if isinstance(saved, (int, float)) else default_height(viewport, row)
return max(low, min(high, target))
def _animate_shelf(self, start: int, end: int, done=None):
from PyQt6.QtCore import QEasingCurve, QVariantAnimation
if self._dj_anim is not None:
self._dj_anim.stop()
anim = QVariantAnimation(self)
anim.setStartValue(int(start))
anim.setEndValue(int(end))
anim.setDuration(self.ANIMATE_MS)
anim.setEasingCurve(QEasingCurve.Type.OutCubic if end > start
else QEasingCurve.Type.InCubic)
anim.valueChanged.connect(lambda v: self._dj.setFixedHeight(int(v)))
if done is not None:
anim.finished.connect(done)
self._dj_anim = anim
anim.start()
# ---- the slide (Round 96) ----
# Animating the shelf's real height re-laid-out the whole window every
# frame — the flicker. Instead the window goes straight to its final
# layout and a picture of what was below the transport boxes slides
# over it: opening, the old lists slide down off the decks (which are
# live underneath); closing, a picture of the shelf stays put while the
# lists' picture slides up over it. Only an image moves.
def _row_gap(self) -> int:
from lintunes.gui.transport import ROW_GAP
return ROW_GAP
def _snapshot_below_boxes(self, shelf=None):
"""(y in the central widget where the window parts, a picture of
everything from there down)."""
central = self.centralWidget()
anchor = shelf if shelf is not None and shelf.isVisible() else \
self._transport._header_row
split = anchor.mapTo(central, anchor.rect().topLeft()).y()
picture = central.grab(QRect(0, split, central.width(), central.height() - split))
return split, picture
def _slide(self, split: int, picture, shift: int, opening: bool):
from PyQt6.QtCore import QEasingCurve, QVariantAnimation
from lintunes.gui.dj_shelf import SlideOverlay
if self._dj_anim is not None:
self._dj_anim.stop()
old = getattr(self, "_dj_overlay", None)
if old is not None:
old.deleteLater()
central = self.centralWidget()
overlay = SlideOverlay(central, picture, shift, opening)
overlay.setGeometry(0, split, central.width(), central.height() - split)
overlay.show()
overlay.raise_()
self._dj_overlay = overlay
anim = QVariantAnimation(self)
anim.setStartValue(0.0)
anim.setEndValue(1.0)
anim.setDuration(self.ANIMATE_MS)
anim.setEasingCurve(QEasingCurve.Type.OutCubic if opening
else QEasingCurve.Type.InOutCubic)
anim.valueChanged.connect(overlay.set_progress)
def finished():
overlay.hide()
overlay.deleteLater()
if getattr(self, "_dj_overlay", None) is overlay:
self._dj_overlay = None
anim.finished.connect(finished)
self._dj_anim = anim
anim.start()
def _dj_closed_now(self):
"""Closing, for real (the slide only shows it)."""
self._dj.set_visualizer(None)
self._dj.stop()
self._dj.hide()
self._sidebar.art.show()
self.player.set_suspended(False)
self._back_to_pin()
self._transport.set_dj_mode(False)
def _dj_closed(self):
if self._dj_on:
return # reopened mid-close
self._dj.set_visualizer(None)
self._dj.stop()
self._dj.hide()
self._sidebar.art.show()
self.player.set_suspended(False)
self._back_to_pin()
self._transport.set_dj_mode(False)
def _on_dj_resize(self, dy: int):
if self._dj_anim is not None and self._dj_anim.state() == self._dj_anim.State.Running:
return
if self._dj_resize_from is None:
self._dj_resize_from = self._dj.height()
low, high = self._dj_bounds()
height = max(low, min(high, self._dj_resize_from + dy))
self._dj.set_layout_height(height)
self._dj.setFixedHeight(height)
def _on_dj_resize_done(self):
self._dj_resize_from = None
config = load_config()
config["dj_shelf_height"] = self._dj.height()
save_config(config)
def _on_dj_resize_reset(self):
from lintunes.gui.dj_shelf import default_height
viewport, row, _ = self._dj_geometry()
low, high = self._dj_bounds()
config = load_config()
config.pop("dj_shelf_height", None)
save_config(config)
target = max(low, min(high, default_height(viewport, row)))
self._dj.set_layout_height(target)
self._animate_shelf(self._dj.height(), target)
def _deck_tag(self, track_id: int):
if self._dj is None:
return None
name = self._dj.deck_of(track_id)
if name is None:
return None
from lintunes.gui.dj_shelf import COLORS
return name, COLORS[name].darker(115)
def _dj_titles(self) -> str:
if self._dj is None:
return ""
names = [v.track.name for v in self._dj.views if v.track is not None]
return " × ".join(names)
def _on_decks_changed(self, _decks: dict):
if self._dj_on:
self._transport.set_dj_titles(self._dj_titles())
self._refresh_tables()
def _refresh_tables(self):
for view in (self._library_view, self._playlist_view):
view.table.viewport().update()
def _play_from_view(self, view, ids, start):
"""Start playback, recording which view it came from so the now-playing
icon (and Go to Current Song) can find the right context."""
self._now_playing_context = view.table.context_id()
self.player.play_queue(ids, start)
def _on_track_changed(self, track):
if track is None:
self.setWindowTitle("LinTunes")
else:
self._listen_context = self._now_playing_context
self.setWindowTitle(f"{track.name} — {track.artist} · LinTunes")
if self._now_playing_context.startswith("playlist:"):
self._manager.record_playlist_play(
self._now_playing_context.split(":", 1)[1])
self._update_now_playing_icon()
def _on_listen_ended(self, key, track, started, heard_ms, how):
"""One listen for the Wrapped history, if the user keeps one."""
if not self._prefs.get("wrapped", {}).get("track_history"):
return
ctx = self._listen_context
if ctx.startswith("followed:"):
ctx = "friend:" + ctx.split(":")[2] # followed:cassette:<token>:<pid>
self._manager.record_listen(listen_history.entry_for(
track, started=started or listen_history.local_now(),
heard_ms=heard_ms, how=how,
src=("desktop" if self.player.is_local else
getattr(self.player.active_sink(), "listen_src", "cast")),
ctx=ctx, shuffle=self.player.is_shuffle(),
track_id=None if isinstance(key, str) else key))
def _files_in_use(self):
track = getattr(self.player, "current_track", None)
location = getattr(track, "location", None)
return (location,) if location else ()
def _on_track_meta_updated(self, track_id: int):
current = self.player.current_track
if current is not None and current.track_id == track_id:
self._sidebar.art.refresh()
def _update_now_playing_icon(self, _playing=None):
track = self.player.current_track
track_id = track.track_id if track else None
playing = self.player.is_playing()
# Only the table showing the context playback started from gets the icon,
# so the same song appearing in another playlist/library isn't flagged.
for view in (self._library_view, self._playlist_view):
match = (track_id is not None
and view.table.context_id() == self._now_playing_context)
view.table.model_.set_now_playing(track_id if match else None,
playing)
# ---- global media keys (spacebar / arrows), per spec detail 8 ----
def eventFilter(self, obj, event):
if event.type() == QEvent.Type.KeyPress and self.isActiveWindow():
focus = QApplication.focusWidget()
if isinstance(focus, (QLineEdit, QPlainTextEdit, QTextEdit,
QAbstractSpinBox, QComboBox)):
return False
key = event.key()
if key in (Qt.Key.Key_Space, Qt.Key.Key_Right, Qt.Key.Key_Left) \
and event.isAutoRepeat():
# On Wayland key repeat is generated client-side until the
# compositor delivers the release — and a compositor busy
# with our own MPRIS churn delivers it late, so one held
# arrow became 1,676 track skips (Round 56). A transport key
# acts once per press; the repeats are swallowed so they
# don't fall through and move the table's cursor either.
return True
if key == Qt.Key.Key_Space:
self._log_key(event, "space")
self.play_pause()
return True
if key in (Qt.Key.Key_Right, Qt.Key.Key_Left) and getattr(self, "_dj_on", False):
return True # no queue to step through in DJ mode
if key == Qt.Key.Key_Right:
self._log_key(event, "right")
self.player.next()
return True
if key == Qt.Key.Key_Left:
self._log_key(event, "left")
self.player.previous()
return True
return super().eventFilter(obj, event)
@staticmethod
def _log_key(event, name: str):
"""Provenance for keys the filter acts on: which input device sent
the press (compositor permitting) — see eventlog module docstring."""
detail = ""
try:
device = event.device()
if device is not None:
detail = f"device={device.name()!r}"
except Exception:
pass
log_control("keyfilter", name, detail)
def _on_playing_changed(self, playing: bool):
if playing:
self._inhibitor.inhibit()
else:
self._inhibitor.release()
def closeEvent(self, event):
# Unsaved cassette choices in friend mode: Save / Don't Save / Cancel.
if not self._cassette.confirm_quit():
event.ignore()
return
# Quitting mid-transfer abandons a partial file on the device (it
# self-heals next sync, but silently) — make it a deliberate choice.
# A link import has nothing half-written on a device to warn about:
# it is simply stopped below.
busy = self._busy_worker()
if busy is not None and busy not in (
self._compress.worker
if self._compress else None,
self._export_worker,
self._url_worker,
self._server_check,
self._upload_worker):
box = QMessageBox(self)
box.setWindowTitle("Sync in progress")
box.setText(
f"Still copying to the {self._sync_device_name}.\n"
"If you quit now, the unfinished track will be re-copied "
"on the next sync.")
quit_button = box.addButton(
"Quit Anyway", QMessageBox.ButtonRole.DestructiveRole)
keep = box.addButton(
"Keep Syncing", QMessageBox.ButtonRole.RejectRole)
box.setDefaultButton(keep)
box.exec()
if box.clickedButton() is not quit_button:
event.ignore()
return
if self._url_worker is not None:
self._url_worker.cancel()
self._url_worker.cleanup()
if self._compress is not None:
self._compress.shutdown() # what landed stays imported
for worker in (self._server_check, self._upload_worker):
if worker is not None:
worker.cancel() # kills ssh/rsync rather than orphan it
self._inhibitor.release()
self._sync_inhibitor.release()
# Before the player: this stops the device and kills the HTTP server it
# is fetching from. Skipped, the Chromecast sits buffering a dead URL.
self._cassette.shutdown()
self._cast.shutdown()
self._airplay.shutdown()
if self._dj is not None:
self._dj.shutdown() # its audio thread must end before Qt does
self.player.shutdown()
self.player.loudness.save()
self._manager.flush()
super().closeEvent(event)