- KDE/Windows accent-driven Material 3 theme, live updating - Library, tabbed playlists, smart/saved lists, queue, ratings - mpv and Qt Multimedia engines, EQ, ReplayGain, gapless - Synced lyrics (LRCLIB, NetEase, local .lrc), covers, MusicBrainz tags - Last.fm/ListenBrainz scrobbling, MPRIS, Windows media keys - Audio CD playback and ripping - PyInstaller, Inno Setup and AppImage builds via GitHub Actions Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01J7imThHV9BMkG24GaxPDeq
869 lines
39 KiB
Python
869 lines
39 KiB
Python
"""Main window: wires library, playlists, player, hero, sidebar and services."""
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import sys
|
|
|
|
from PyQt6.QtCore import QByteArray, QEvent, QSize, Qt, QTimer, QUrl
|
|
from PyQt6.QtGui import QAction, QDesktopServices, QIcon, QKeySequence, QPixmap, QShortcut
|
|
from PyQt6.QtWidgets import (QApplication, QFileDialog, QHBoxLayout, QInputDialog, QLabel,
|
|
QLineEdit, QMainWindow, QMenu, QMessageBox, QSplitter,
|
|
QSystemTrayIcon, QToolButton, QVBoxLayout, QWidget)
|
|
|
|
from . import library as L
|
|
from . import theme as Th
|
|
from .config import APP_NAME, IS_LINUX, IS_WIN, fmt_time, settings
|
|
from .icons import icon
|
|
try: # MPRIS + freedesktop notifications (Linux); QtDBus isn't shipped on Windows
|
|
from .mpris import Mpris, notify
|
|
except ImportError:
|
|
Mpris, notify = None, None
|
|
from .nowplaying import NowPlaying
|
|
from .player import Player
|
|
from .playlist import PlaylistManager
|
|
from .playlistio import EXPORT_FILTERS, IMPORT_FILTER, export_playlist
|
|
from .scrobble import Scrobbler
|
|
from .song import Song
|
|
from .spectrum import Spectrum
|
|
from .widgets.analyzer import Analyzer
|
|
from .widgets.dialogs import (AboutDialog, BatchTagFetch, CoverManager, EqualizerDialog,
|
|
MusicBrainzDialog, RipDialog, SettingsDialog, TagEditor)
|
|
from .widgets.bassshape import BassShape
|
|
from .widgets.hero import Hero
|
|
from .widgets.m3 import IconButton, VolumeSlider, WavySlider
|
|
from .widgets.playlistview import PlaylistArea, show_in_file_manager
|
|
from .widgets.sidebar import Sidebar
|
|
|
|
|
|
class MainWindow(QMainWindow):
|
|
def __init__(self):
|
|
super().__init__()
|
|
self.setWindowTitle(APP_NAME)
|
|
self.setWindowIcon(app_icon())
|
|
self.setAcceptDrops(True)
|
|
self.current_art_path = ""
|
|
self._quitting = False
|
|
self._notif_id = 0
|
|
|
|
self.mgr = PlaylistManager()
|
|
self.mgr.restore()
|
|
self.player = Player(self.mgr)
|
|
self.spectrum = Spectrum(64)
|
|
if self.player.backend.provides_pcm:
|
|
self.player.backend.pcm.connect(self.spectrum.push)
|
|
self.np = NowPlaying(self.player)
|
|
self.scrobbler = Scrobbler(self.player)
|
|
self.scrobbler.status.connect(self.toast)
|
|
self.player.message.connect(self.toast)
|
|
self.player.state_changed.connect(self._on_state)
|
|
self.player.song_changed.connect(self._on_song)
|
|
self.np.art_changed.connect(self._on_art)
|
|
|
|
# ------------------------------------------------------------ layout
|
|
self.sidebar = Sidebar()
|
|
self.hero = Hero(self.player, self.np, self.spectrum, self.scrobbler)
|
|
self.hero.open_menu.connect(lambda pos: self.player.song and self.song_menu(
|
|
[self.player.song], pos, self.player.playlist))
|
|
self.hero.cover_clicked.connect(self.toggle_focus_mode)
|
|
self.area = PlaylistArea(self.mgr)
|
|
self.area.play_requested.connect(lambda pl, s: self.player.play_song(pl, s))
|
|
self.area.context_requested.connect(self._playlist_menu)
|
|
self.area.tool["import"].clicked.connect(self.import_playlist)
|
|
self.area.tool["export"].clicked.connect(lambda: self.export_playlist(self.mgr.current))
|
|
|
|
self.vsplit = QSplitter(Qt.Orientation.Vertical)
|
|
self.vsplit.addWidget(self.hero)
|
|
self.vsplit.addWidget(self.area)
|
|
self.vsplit.setChildrenCollapsible(False)
|
|
self.vsplit.setStretchFactor(0, 0)
|
|
self.vsplit.setStretchFactor(1, 1)
|
|
self.hsplit = QSplitter(Qt.Orientation.Horizontal)
|
|
self.hsplit.addWidget(self.sidebar)
|
|
self.hsplit.addWidget(self.vsplit)
|
|
self.hsplit.setStretchFactor(1, 1)
|
|
self.hsplit.setSizes([300, 1100])
|
|
|
|
bottom = QWidget()
|
|
bl = QHBoxLayout(bottom)
|
|
bl.setContentsMargins(14, 2, 14, 6)
|
|
bl.setSpacing(10)
|
|
self.summary = QLabel()
|
|
self.summary.setObjectName("muted")
|
|
self.toast_lbl = QLabel()
|
|
self.toast_lbl.setObjectName("muted")
|
|
self.analyzer = Analyzer(self.spectrum)
|
|
self.mute_btn = QToolButton()
|
|
self.mute_btn.setIcon(icon("volume_up"))
|
|
self.mute_btn.clicked.connect(self.player.toggle_mute)
|
|
self.vol = VolumeSlider()
|
|
self.vol.setFixedWidth(130)
|
|
self.vol.set_value(self.player.volume)
|
|
self.vol.changed.connect(self.player.set_volume)
|
|
self.vol_lbl = QLabel(f"{self.player.volume}%")
|
|
self.vol_lbl.setObjectName("muted")
|
|
self.vol_lbl.setMinimumWidth(38)
|
|
self.player.volume_changed.connect(self._on_volume)
|
|
self.mini = QWidget()
|
|
ml = QHBoxLayout(self.mini)
|
|
ml.setContentsMargins(0, 0, 0, 0)
|
|
ml.setSpacing(4)
|
|
self.mini_prev = IconButton("skip_previous_fill", "standard", 34, 22, tooltip="Previous")
|
|
self.mini_play = IconButton("play_arrow_fill", "filled", 36, 22, wide=56, tooltip="Play / Pause")
|
|
self.mini_next = IconButton("skip_next_fill", "standard", 34, 22, tooltip="Next")
|
|
self.mini_wave = WavySlider()
|
|
self.mini_wave.setFixedWidth(260)
|
|
self.mini_time = QLabel("0:00")
|
|
self.mini_time.setObjectName("muted")
|
|
self.mini_prev.clicked.connect(self.player.prev)
|
|
self.mini_play.clicked.connect(self.player.play_pause)
|
|
self.mini_next.clicked.connect(self.player.next)
|
|
self.mini_wave.seek_requested.connect(lambda v: self.player.seek(v * self.player.dur))
|
|
self.player.position_changed.connect(lambda p, d: (self.mini_wave.set_value(p / d if d else 0, d),
|
|
self.mini_time.setText(f"{fmt_time(p)} / {fmt_time(d)}")))
|
|
for wdg in (self.mini_prev, self.mini_play, self.mini_next, self.mini_wave, self.mini_time):
|
|
ml.addWidget(wdg)
|
|
bl.addWidget(self.mini)
|
|
bl.addWidget(self.summary)
|
|
bl.addWidget(self.toast_lbl)
|
|
bl.addWidget(self.analyzer, 1)
|
|
bl.addWidget(self.mute_btn)
|
|
bl.addWidget(self.vol)
|
|
bl.addWidget(self.vol_lbl)
|
|
|
|
central = QWidget()
|
|
cl = QVBoxLayout(central)
|
|
cl.setContentsMargins(4, 0, 4, 0)
|
|
cl.setSpacing(0)
|
|
cl.addWidget(self.hsplit, 1)
|
|
cl.addWidget(bottom)
|
|
self.setCentralWidget(central)
|
|
self.bottom_bar = bottom
|
|
self.shape = BassShape(self.spectrum, self.player, central)
|
|
self.shape.hide_requested.connect(lambda: self._set_shape(False))
|
|
self.bottom_bar.installEventFilter(self)
|
|
|
|
self._toast_timer = QTimer(self, singleShot=True, interval=6000)
|
|
self._toast_timer.timeout.connect(lambda: self.toast_lbl.setText(""))
|
|
self.mgr.summary_changed.connect(self._summary)
|
|
self.mgr.busy.connect(lambda b: self.toast("Adding files…") if b else None)
|
|
self._summary()
|
|
|
|
# ------------------------------------------------------------ sidebar wiring
|
|
sb = self.sidebar
|
|
sb.library.add_songs.connect(self.add_songs)
|
|
sb.library.context.connect(lambda songs, pos: self.song_menu(songs, pos, None))
|
|
sb.files.add_paths.connect(self.add_paths)
|
|
sb.playlists.open_smart.connect(self._open_smart)
|
|
sb.playlists.open_saved.connect(self.mgr.reopen_saved)
|
|
sb.radio.play_stream.connect(lambda s, mode: self.add_songs([s], mode))
|
|
sb.cd.add_songs.connect(self.add_songs)
|
|
sb.cd.rip.connect(lambda songs, cover: RipDialog(songs, cover, self).exec())
|
|
sb.nav.set_current(settings.raw().value("ui/sidebar_tab", 0, int), animate=False)
|
|
|
|
self._build_menus()
|
|
self._shortcuts()
|
|
self.mpris = Mpris(self, self.player, self.mgr) if Mpris is not None else _NoMpris()
|
|
self.media_keys = None
|
|
if IS_WIN:
|
|
try:
|
|
from .winmedia import WindowsMediaKeys
|
|
self.media_keys = WindowsMediaKeys(self.player)
|
|
except Exception as e: # noqa: BLE001
|
|
print("media keys unavailable:", e)
|
|
self._tray()
|
|
self.apply_layout_settings()
|
|
self._restore_geometry()
|
|
Th.theme.changed.connect(self._theme_changed)
|
|
QApplication.instance().installEventFilter(self)
|
|
|
|
if settings.get("library/scan_on_start") and settings.get("library/folders"):
|
|
QTimer.singleShot(1500, lambda: L.library.scan(False))
|
|
QTimer.singleShot(0, self._resume)
|
|
|
|
# ================================================================ menus
|
|
def _build_menus(self):
|
|
mb = self.menuBar()
|
|
m = mb.addMenu("&Music")
|
|
self.act = {}
|
|
|
|
def A(menu, text, slot, shortcut=None, ic=None, checkable=False):
|
|
a = QAction(text, self)
|
|
if ic:
|
|
a.setIcon(icon(ic))
|
|
if shortcut:
|
|
a.setShortcut(QKeySequence(shortcut))
|
|
a.setCheckable(checkable)
|
|
a.triggered.connect(slot)
|
|
menu.addAction(a)
|
|
return a
|
|
|
|
A(m, "Open files…", self.open_files, "Ctrl+O", "file_open")
|
|
A(m, "Open folder…", self.open_folder, "Ctrl+Shift+O", "folder_open")
|
|
A(m, "Open audio CD", lambda: self.sidebar.nav.set_current(4), None, "album")
|
|
A(m, "Open stream URL…", self.open_url, "Ctrl+U", "link")
|
|
m.addSeparator()
|
|
A(m, "Previous", self.player.prev, "Ctrl+Left", "skip_previous_fill")
|
|
self.act["play"] = A(m, "Play / Pause", self.player.play_pause, None, "play_arrow_fill")
|
|
A(m, "Stop", self.player.stop, "Ctrl+Shift+S", "stop_fill")
|
|
self.act["stop_after"] = A(m, "Stop after this track", self._stop_after, "Ctrl+Alt+V", "stop_circle", True)
|
|
A(m, "Next", self.player.next, "Ctrl+Right", "skip_next_fill")
|
|
A(m, "Seek forward 10 s", lambda: self.player.seek_relative(10), "Alt+Right")
|
|
A(m, "Seek back 10 s", lambda: self.player.seek_relative(-10), "Alt+Left")
|
|
A(m, "Volume up", lambda: self.player.set_volume(self.player.volume + 5), "Ctrl+Up", "volume_up")
|
|
A(m, "Volume down", lambda: self.player.set_volume(self.player.volume - 5), "Ctrl+Down", "volume_down")
|
|
A(m, "Mute", self.player.toggle_mute, "Ctrl+M", "volume_off")
|
|
m.addSeparator()
|
|
A(m, "Love current track", lambda: self.hero.love.click(), "Ctrl+L", "favorite")
|
|
m.addSeparator()
|
|
A(m, "Quit", self.quit_app, "Ctrl+Q", "close")
|
|
|
|
p = mb.addMenu("&Playlist")
|
|
A(p, "New playlist", lambda: self.mgr.new_playlist(), "Ctrl+T", "playlist_add")
|
|
A(p, "Import playlist…", self.import_playlist, "Ctrl+I", "file_open")
|
|
A(p, "Export playlist…", lambda: self.export_playlist(self.mgr.current), "Ctrl+S", "save")
|
|
A(p, "Close playlist", lambda: self.mgr.close_playlist(self.mgr.current), "Ctrl+W", "close")
|
|
p.addSeparator()
|
|
A(p, "Undo", lambda: self.mgr.current.undo.undo(), "Ctrl+Z", "undo")
|
|
A(p, "Redo", lambda: self.mgr.current.undo.redo(), "Ctrl+Shift+Z", "redo")
|
|
A(p, "Select all", lambda: self.area.view() and self.area.view().selectAll(), "Ctrl+A")
|
|
A(p, "Filter…", lambda: self.area.filter.setFocus(), "Ctrl+F", "search")
|
|
A(p, "Jump to playing track", self.area.jump_to_current, "Ctrl+J", "queue_play_next")
|
|
A(p, "Queue selected tracks", self._queue_selected, "Ctrl+D", "queue_music")
|
|
A(p, "Clear queue", self.mgr.clear_queue, None, "clear_all")
|
|
p.addSeparator()
|
|
A(p, "Shuffle playlist order", lambda: self.mgr.current.shuffle_items(), None, "shuffle")
|
|
A(p, "Remove duplicates", lambda: self.mgr.current.remove_duplicates(), None, "content_copy")
|
|
A(p, "Remove unavailable", lambda: self.mgr.current.remove_unavailable(), None, "delete")
|
|
A(p, "Clear playlist", lambda: self.mgr.current.clear(), None, "clear_all")
|
|
p.addSeparator()
|
|
self.act["shuffle"] = A(p, "Shuffle", self._menu_shuffle, "Ctrl+H", "shuffle", True)
|
|
rm = p.addMenu(icon("repeat"), "Repeat")
|
|
self.act["repeat"] = {}
|
|
for k, t in (("off", "Off"), ("playlist", "Playlist"), ("track", "Track")):
|
|
self.act["repeat"][k] = A(rm, t, lambda _c, k=k: self._menu_repeat(k), None, None, True)
|
|
|
|
t = mb.addMenu("&Tools")
|
|
A(t, "Edit tags…", lambda: self._tag_selected(), "Ctrl+E", "edit")
|
|
A(t, "Fetch tags from MusicBrainz…", lambda: self._mb_selected(), None, "cloud_download")
|
|
A(t, "Album cover…", lambda: self._cover_selected(), None, "image")
|
|
A(t, "Equalizer…", lambda: EqualizerDialog(self).exec(), None, "tune")
|
|
A(t, "Rip audio CD…", lambda: self.sidebar.nav.set_current(4), None, "download")
|
|
t.addSeparator()
|
|
A(t, "Update library", lambda: L.library.scan(False), "F5", "refresh")
|
|
A(t, "Full library rescan", lambda: L.library.scan(True), "Ctrl+F5", "sync")
|
|
A(t, "Add music folder…", lambda: self.add_library_folder(), None, "library_add")
|
|
t.addSeparator()
|
|
A(t, "Settings…", lambda: SettingsDialog(self).exec(), "Ctrl+,", "settings")
|
|
|
|
v = mb.addMenu("&View")
|
|
hm = v.addMenu(icon("art_track"), "Now playing panel")
|
|
self.act["hero"] = {}
|
|
for k, tt in (("full", "Large"), ("compact", "Compact"), ("hidden", "Hidden")):
|
|
self.act["hero"][k] = A(hm, tt, lambda _c, k=k: self._set_hero(k), None, None, True)
|
|
self.act["sidebar"] = A(v, "Show sidebar", self._toggle_sidebar, "Ctrl+B", "menu", True)
|
|
self.act["sidebar"].setChecked(True)
|
|
self.act["analyzer"] = A(v, "Show spectrum analyzer", self._toggle_analyzer, None, "graphic_eq", True)
|
|
self.act["shape"] = A(v, "Floating bass shape", lambda: self._set_shape(self.act["shape"].isChecked()),
|
|
None, "auto_awesome", True)
|
|
A(v, "Focus mode (cover & lyrics)", self.toggle_focus_mode, "F11", "open_in_full")
|
|
v.addSeparator()
|
|
A(v, "Theme: follow system colours", lambda: self._quick_theme("kde"), None, "palette")
|
|
A(v, "Theme: colours from album art", lambda: self._quick_theme("album"), None, "image")
|
|
|
|
h = mb.addMenu("&Help")
|
|
A(h, f"About {APP_NAME}", lambda: AboutDialog(self).exec(), None, "info")
|
|
A(h, "About Qt", QApplication.aboutQt)
|
|
self.sync_modes()
|
|
|
|
def _shortcuts(self):
|
|
sc = QShortcut(QKeySequence(Qt.Key.Key_Space), self)
|
|
sc.setContext(Qt.ShortcutContext.WindowShortcut)
|
|
sc.activated.connect(self._space)
|
|
for key, fn in ((Qt.Key.Key_MediaPlay, self.player.play_pause), (Qt.Key.Key_MediaTogglePlayPause, self.player.play_pause),
|
|
(Qt.Key.Key_MediaNext, self.player.next), (Qt.Key.Key_MediaPrevious, self.player.prev),
|
|
(Qt.Key.Key_MediaStop, self.player.stop), (Qt.Key.Key_MediaPause, self.player.pause)):
|
|
s = QShortcut(QKeySequence(key), self)
|
|
s.activated.connect(fn)
|
|
|
|
def _space(self):
|
|
if isinstance(QApplication.focusWidget(), QLineEdit):
|
|
fw = QApplication.focusWidget()
|
|
fw.insert(" ")
|
|
return
|
|
self.player.play_pause()
|
|
|
|
# ================================================================ modes
|
|
def sync_modes(self):
|
|
self.act["shuffle"].setChecked(self.mgr.shuffle)
|
|
for k, a in self.act["repeat"].items():
|
|
a.setChecked(k == self.mgr.repeat)
|
|
self.hero.sync_modes()
|
|
if hasattr(self, "mpris"):
|
|
self.mpris.modes_changed()
|
|
|
|
def _menu_shuffle(self):
|
|
self.mgr.set_shuffle(self.act["shuffle"].isChecked())
|
|
self.player.refresh_next()
|
|
self.sync_modes()
|
|
|
|
def _menu_repeat(self, k):
|
|
self.mgr.set_repeat(k)
|
|
self.player.refresh_next()
|
|
self.sync_modes()
|
|
|
|
def _stop_after(self):
|
|
self.mgr.stop_after = self.player.song if self.act["stop_after"].isChecked() else None
|
|
self.player.refresh_next()
|
|
|
|
def _set_hero(self, mode):
|
|
settings.set("appearance/hero", mode)
|
|
self.apply_layout_settings()
|
|
|
|
def apply_layout_settings(self):
|
|
mode = settings.get("appearance/hero")
|
|
for k, a in self.act["hero"].items():
|
|
a.setChecked(k == mode)
|
|
self.hero.setVisible(mode != "hidden")
|
|
if mode != "hidden":
|
|
self.hero.set_mode(mode)
|
|
h = 300 if mode == "full" else 118
|
|
self.hero.setMinimumHeight(h)
|
|
self.hero.setMaximumHeight(h + 140 if mode == "full" else h)
|
|
sizes = self.vsplit.sizes()
|
|
total = sum(sizes) or 900
|
|
self.vsplit.setSizes([h, max(200, total - h)])
|
|
ana = settings.get("appearance/analyzer")
|
|
self.analyzer.setVisible(ana)
|
|
self.act["analyzer"].setChecked(ana)
|
|
self.spectrum.enabled = ana or settings.get("appearance/floating_shape") or (settings.get("appearance/visualizer") and mode == "full")
|
|
self.spectrum._update_running()
|
|
self.spectrum.use_monitor = self.player.backend.name == "mpv" and IS_LINUX
|
|
self.spectrum._update_monitor()
|
|
self.mini.setVisible(mode == "hidden")
|
|
self.area.set_art(self.area._art)
|
|
on = settings.get("appearance/floating_shape")
|
|
self.act["shape"].setChecked(on)
|
|
self.shape.setVisible(on)
|
|
self.bottom_bar.layout().setContentsMargins(14 + (78 if on else 0), 2, 14, 6)
|
|
self.sidebar.layout().setContentsMargins(4, 0, 0, 40 if on else 0)
|
|
self._place_shape()
|
|
if hasattr(self, "tray_icon"):
|
|
self.tray_icon.setVisible(settings.get("appearance/tray"))
|
|
|
|
def _toggle_sidebar(self):
|
|
self.sidebar.setVisible(self.act["sidebar"].isChecked())
|
|
|
|
def _set_shape(self, on):
|
|
settings.set("appearance/floating_shape", on)
|
|
self.apply_layout_settings()
|
|
|
|
def _place_shape(self):
|
|
c = self.centralWidget()
|
|
if c is None or not hasattr(self, "shape"):
|
|
return
|
|
bb = self.bottom_bar.geometry()
|
|
y = bb.center().y() - self.shape.height() // 2 - 16 # floats up out of the bar
|
|
self.shape.move(4, max(0, y))
|
|
self.shape.raise_()
|
|
|
|
def resizeEvent(self, e):
|
|
super().resizeEvent(e)
|
|
self._place_shape()
|
|
|
|
def _toggle_analyzer(self):
|
|
settings.set("appearance/analyzer", self.act["analyzer"].isChecked())
|
|
self.apply_layout_settings()
|
|
|
|
def toggle_focus_mode(self):
|
|
"""Hide everything but the hero (big cover + lyrics)."""
|
|
focus = not getattr(self, "_focus", False)
|
|
self._focus = focus
|
|
self.sidebar.setVisible(not focus and self.act["sidebar"].isChecked())
|
|
self.area.setVisible(not focus)
|
|
if focus:
|
|
self.hero.set_mode("full")
|
|
self.hero.setVisible(True)
|
|
self.hero.setMaximumHeight(16777215)
|
|
self.hero.cover.setFixedSize(420, 420)
|
|
else:
|
|
self.apply_layout_settings()
|
|
|
|
def _quick_theme(self, src):
|
|
settings.set("appearance/color_source", src)
|
|
if src == "album" and self.np.image is not None:
|
|
Th.theme.album_seed = Th.dominant_color(self.np.image)
|
|
Th.theme.rebuild()
|
|
|
|
def _theme_changed(self):
|
|
self.setWindowIcon(app_icon())
|
|
if hasattr(self, "tray_icon"):
|
|
self.tray_icon.setIcon(app_icon())
|
|
for v in self.area.views.values():
|
|
v.viewport().update()
|
|
self.update()
|
|
|
|
# ================================================================ adding
|
|
def add_songs(self, songs: list[Song], mode: str):
|
|
if not songs:
|
|
return
|
|
pl = self.mgr.current
|
|
if mode == "new":
|
|
name = songs[0].album or songs[0].display_artist() or "Playlist"
|
|
pl = self.mgr.new_playlist(name, [])
|
|
self.mgr.add_songs(songs, pl, play=True)
|
|
elif mode == "replace":
|
|
self.mgr.add_songs(songs, pl, play=True, replace=True)
|
|
elif mode == "play":
|
|
self.mgr.add_songs(songs, pl, play=True)
|
|
elif mode == "queue":
|
|
pl.insert_songs(songs)
|
|
self.mgr.enqueue(pl, songs)
|
|
elif mode == "next":
|
|
row = pl.current_row() + 1 if pl.current_song is not None else -1
|
|
pl.insert_songs(songs, row)
|
|
self.mgr.enqueue(pl, songs, front=True)
|
|
else:
|
|
self.mgr.add_songs(songs, pl)
|
|
|
|
def _open_smart(self, name, songs):
|
|
"""Smart lists reuse their tab (refreshed) instead of piling up copies."""
|
|
for pl in self.mgr.playlists:
|
|
if pl.name == name and getattr(pl, "smart", False):
|
|
pl.replace(songs)
|
|
self.mgr.set_current(pl)
|
|
return
|
|
pl = self.mgr.new_playlist(name, songs)
|
|
pl.smart = True
|
|
|
|
def add_paths(self, paths, mode="append"):
|
|
if mode == "new":
|
|
pl = self.mgr.new_playlist(os.path.basename(paths[0].rstrip("/")) or "Playlist")
|
|
self.mgr.add_paths(paths, pl, play=True)
|
|
elif mode == "replace":
|
|
self.mgr.add_paths(paths, self.mgr.current, play=True, replace=True)
|
|
else:
|
|
self.mgr.add_paths(paths, self.mgr.current, play=mode == "play")
|
|
|
|
def open_files(self):
|
|
from .config import AUDIO_EXTS
|
|
exts = " ".join(f"*.{e}" for e in sorted(AUDIO_EXTS))
|
|
files, _ = QFileDialog.getOpenFileNames(self, "Open audio files", os.path.expanduser("~/Music"),
|
|
f"Audio ({exts});;Playlists (*.m3u *.m3u8 *.pls *.xspf *.cue);;All files (*)")
|
|
if files:
|
|
self.add_paths(files, "play")
|
|
|
|
def open_folder(self):
|
|
d = QFileDialog.getExistingDirectory(self, "Open folder", os.path.expanduser("~/Music"))
|
|
if d:
|
|
self.add_paths([d], "play")
|
|
|
|
def open_url(self):
|
|
url, ok = QInputDialog.getText(self, "Open stream", "URL:")
|
|
if ok and url.strip():
|
|
self.add_songs([Song(url=url.strip(), title=url.strip(), filetype="Stream")], "play")
|
|
|
|
def add_library_folder(self, d=None):
|
|
if d is None:
|
|
d = QFileDialog.getExistingDirectory(self, "Add music folder", os.path.expanduser("~/Music"))
|
|
if d:
|
|
folders = settings.get("library/folders")
|
|
if d not in folders:
|
|
settings.set("library/folders", folders + [d])
|
|
L.library.scan(False)
|
|
self.sidebar.files.go_home()
|
|
|
|
def import_playlist(self):
|
|
files, _ = QFileDialog.getOpenFileNames(self, "Import playlist", os.path.expanduser("~/Music"), IMPORT_FILTER)
|
|
for f in files:
|
|
pl = self.mgr.new_playlist(os.path.splitext(os.path.basename(f))[0])
|
|
self.mgr.add_paths([f], pl)
|
|
|
|
def export_playlist(self, pl):
|
|
if pl is None:
|
|
return
|
|
path, flt = QFileDialog.getSaveFileName(self, "Export playlist",
|
|
os.path.join(os.path.expanduser("~/Music"), pl.name + ".m3u8"),
|
|
EXPORT_FILTERS)
|
|
if not path:
|
|
return
|
|
if not os.path.splitext(path)[1]:
|
|
path += "." + flt.split("*.")[1].rstrip(")")
|
|
rel = QMessageBox.question(self, "Export playlist", "Use paths relative to the playlist file?\n"
|
|
"(Recommended if you move the music folder with the playlist.)") \
|
|
== QMessageBox.StandardButton.Yes
|
|
try:
|
|
export_playlist(path, pl.songs, rel)
|
|
self.toast(f"Exported {len(pl.songs)} tracks to {os.path.basename(path)}")
|
|
except Exception as e: # noqa: BLE001
|
|
QMessageBox.warning(self, "Export failed", str(e))
|
|
|
|
# ================================================================ context menus
|
|
def _playlist_menu(self, view, pos):
|
|
songs = view.selected_songs()
|
|
if not songs:
|
|
return
|
|
self.song_menu(songs, pos, view.pl, view)
|
|
|
|
def song_menu(self, songs: list[Song], pos, pl=None, view=None):
|
|
m = QMenu(self)
|
|
if pl is not None:
|
|
m.addAction(icon("play_arrow"), "Play", lambda: self.player.play_song(pl, songs[0]))
|
|
qa = m.addAction(icon("queue_music"), "Queue / dequeue")
|
|
qa.triggered.connect(lambda: self._toggle_queue(pl, songs))
|
|
m.addAction(icon("queue_play_next"), "Play next",
|
|
lambda: self.mgr.enqueue(pl, songs, front=True))
|
|
sa = m.addAction(icon("stop_circle"), "Stop after this track")
|
|
sa.triggered.connect(lambda: (setattr(self.mgr, "stop_after", songs[0]), self.player.refresh_next()))
|
|
m.addSeparator()
|
|
if view is not None:
|
|
m.addAction(icon("delete"), "Remove from playlist", view.remove_selected)
|
|
m.addAction(icon("filter_list"), "Crop to selection",
|
|
lambda: pl.remove_rows([i for i in range(len(pl.songs)) if i not in set(view.selected_rows())]))
|
|
else:
|
|
m.addAction(icon("playlist_add"), "Append to playlist", lambda: self.add_songs(songs, "append"))
|
|
m.addAction(icon("play_arrow"), "Append and play", lambda: self.add_songs(songs, "play"))
|
|
m.addAction(icon("playlist_play"), "Replace current playlist", lambda: self.add_songs(songs, "replace"))
|
|
m.addAction(icon("queue_music"), "Open in new playlist", lambda: self.add_songs(songs, "new"))
|
|
m.addAction(icon("queue_play_next"), "Play next", lambda: self.add_songs(songs, "next"))
|
|
m.addAction(icon("queue_music"), "Add to queue", lambda: self.add_songs(songs, "queue"))
|
|
sub = m.addMenu(icon("playlist_add"), "Add to playlist")
|
|
for other in self.mgr.playlists:
|
|
if other is not pl:
|
|
sub.addAction(other.name, lambda o=other: o.insert_songs(list(songs)))
|
|
sub.addSeparator()
|
|
sub.addAction(icon("add"), "New playlist…", lambda: self.mgr.new_playlist(
|
|
songs[0].album or "Playlist", list(songs)))
|
|
m.addSeparator()
|
|
rate = m.addMenu(icon("star"), "Rating")
|
|
for r in range(6):
|
|
rate.addAction("★" * r + "☆" * (5 - r) if r else "No rating",
|
|
lambda r=r: [L.library.set_rating(s, r) for s in songs] and self._refresh_songs(songs))
|
|
local = [s for s in songs if s.is_local]
|
|
if local:
|
|
m.addAction(icon("edit"), "Edit tags…", lambda: TagEditor(local, self).exec())
|
|
mbm = m.addMenu(icon("cloud_download"), "Fetch tags")
|
|
mbm.addAction("Choose match (MusicBrainz)…", lambda: self._mb_for(local))
|
|
mbm.addAction(f"Auto-apply best match ({len(local)} song(s))", lambda: BatchTagFetch.run(self, local))
|
|
m.addAction(icon("image"), "Album cover…", lambda: CoverManager(songs[0], self).exec())
|
|
if local:
|
|
m.addAction(icon("folder_open"), "Show in file manager", lambda: show_in_file_manager(local[0].path))
|
|
if any(s.is_cd for s in songs):
|
|
m.addAction(icon("download"), "Rip selected CD tracks…",
|
|
lambda: RipDialog([s for s in songs if s.is_cd], self.sidebar.cd.cover, self).exec())
|
|
m.exec(pos)
|
|
|
|
def _toggle_queue(self, pl, songs):
|
|
queued = {id(s) for _, s in self.mgr.queue}
|
|
if all(id(s) in queued for s in songs):
|
|
for s in songs:
|
|
self.mgr.dequeue(s)
|
|
else:
|
|
self.mgr.enqueue(pl, [s for s in songs if id(s) not in queued])
|
|
self.player.refresh_next()
|
|
|
|
def _queue_selected(self):
|
|
v = self.area.view()
|
|
if v:
|
|
songs = v.selected_songs()
|
|
if songs:
|
|
self._toggle_queue(v.pl, songs)
|
|
|
|
def _selected_or_current(self):
|
|
v = self.area.view()
|
|
songs = v.selected_songs() if v else []
|
|
if not songs and self.player.song:
|
|
songs = [self.player.song]
|
|
return songs
|
|
|
|
def _tag_selected(self):
|
|
songs = [s for s in self._selected_or_current() if s.is_local]
|
|
if songs:
|
|
TagEditor(songs, self).exec()
|
|
|
|
def _mb_selected(self):
|
|
songs = [s for s in self._selected_or_current() if s.is_local]
|
|
if songs:
|
|
self._mb_for(songs)
|
|
|
|
def _mb_for(self, songs):
|
|
if len(songs) > 1:
|
|
TagEditor(songs, self).exec()
|
|
return
|
|
dlg = MusicBrainzDialog(songs[0], self)
|
|
if dlg.exec() and dlg.choice:
|
|
c = dlg.choice
|
|
vals = {k: c[k] for k in ("title", "artist", "album", "albumartist", "year", "track", "disc",
|
|
"genre", "mb_trackid", "mb_albumid") if c.get(k)}
|
|
from . import tags as T
|
|
try:
|
|
T.write_tags(songs[0].path, vals)
|
|
except Exception as e: # noqa: BLE001
|
|
QMessageBox.warning(self, "Tags", str(e))
|
|
return
|
|
ns = L.library.reread(songs[0].path) or T.read_song(songs[0].path)
|
|
if ns:
|
|
ns.art = ns.art or songs[0].art
|
|
self.song_replaced(songs[0], ns)
|
|
self.toast("Tags updated from MusicBrainz")
|
|
|
|
def _cover_selected(self):
|
|
songs = self._selected_or_current()
|
|
if songs:
|
|
CoverManager(songs[0], self).exec()
|
|
|
|
# ================================================================ song updates
|
|
def song_replaced(self, old: Song, new: Song):
|
|
"""After tag edits: swap the Song object everywhere it appears."""
|
|
for pl in self.mgr.playlists:
|
|
for i, s in enumerate(pl.songs):
|
|
if s is old or (s.url == old.url and s.begin == old.begin):
|
|
for f in ("title", "artist", "album", "albumartist", "genre", "composer", "comment", "year",
|
|
"track", "disc", "mb_trackid", "mb_albumid", "art", "id"):
|
|
setattr(s, f, getattr(new, f))
|
|
pl.dataChanged.emit(pl.index(i, 0), pl.index(i, pl.columnCount() - 1))
|
|
pl.dirty = True
|
|
if self.player.song is not None and self.player.song.url == old.url:
|
|
self.player.song_changed.emit(self.player.song)
|
|
self.mgr.schedule_save()
|
|
|
|
def _refresh_songs(self, songs):
|
|
for pl in self.mgr.playlists:
|
|
for s in songs:
|
|
r = pl.row_of(s)
|
|
if r >= 0:
|
|
pl.dataChanged.emit(pl.index(r, 0), pl.index(r, pl.columnCount() - 1))
|
|
|
|
def refresh_art(self, songs):
|
|
self._refresh_songs(songs)
|
|
self.mgr.schedule_save()
|
|
|
|
def refresh_saved_playlists(self):
|
|
self.sidebar.playlists.refresh()
|
|
|
|
# ================================================================ player events
|
|
def _on_state(self, st):
|
|
self.spectrum.set_playing(st == "playing")
|
|
self.mini_play.set_icon("pause_fill" if st == "playing" else "play_arrow_fill")
|
|
self.mini_play.set_morph(st == "playing")
|
|
self.mini_wave.set_playing(st == "playing")
|
|
self.act["play"].setIcon(icon("pause_fill" if st == "playing" else "play_arrow_fill"))
|
|
if hasattr(self, "tray_play"):
|
|
self.tray_play.setText("Pause" if st == "playing" else "Play")
|
|
if st == "stopped" and self.player.song is None:
|
|
self.setWindowTitle(APP_NAME)
|
|
|
|
def _on_song(self, s: Song):
|
|
title = s.stream_title or s.display_title() if s.is_stream else s.display_title()
|
|
artist = s.display_artist()
|
|
self.setWindowTitle(f"{artist} - {title} — {APP_NAME}" if artist else f"{title} — {APP_NAME}")
|
|
if hasattr(self, "tray_icon"):
|
|
self.tray_icon.setToolTip(f"{title}\n{artist}")
|
|
v = self.area.view_for(self.mgr.active)
|
|
if v is not None and not v.underMouse():
|
|
v.scroll_to_current()
|
|
self.area._refresh_tabs()
|
|
self._pending_notify = True
|
|
QTimer.singleShot(700, self._notify)
|
|
if self.act["stop_after"].isChecked() and self.mgr.stop_after is not s:
|
|
self.act["stop_after"].setChecked(self.mgr.stop_after is not None)
|
|
|
|
def _notify(self):
|
|
if not getattr(self, "_pending_notify", False) or not settings.get("appearance/notifications"):
|
|
return
|
|
self._pending_notify = False
|
|
s = self.player.song
|
|
if s is None or self.isActiveWindow() or self.player.state != "playing":
|
|
return
|
|
title = s.stream_title or s.display_title()
|
|
body = " — ".join(x for x in (s.display_artist(), s.album) if x)
|
|
if notify is not None and not IS_WIN:
|
|
notify(title, body, self.current_art_path, self._notif_id)
|
|
elif hasattr(self, "tray_icon") and self.tray_icon.isVisible():
|
|
from PyQt6.QtGui import QIcon as _QIcon
|
|
ic = _QIcon(self.current_art_path) if self.current_art_path else app_icon()
|
|
self.tray_icon.showMessage(title, body, ic, 4000)
|
|
|
|
def _on_art(self, img, path):
|
|
self.current_art_path = path
|
|
pm = QPixmap.fromImage(img) if img is not None else None
|
|
self.area.set_art(pm)
|
|
if settings.get("appearance/color_source") == "album":
|
|
Th.theme.set_album_seed(Th.dominant_color(img) if img is not None else None)
|
|
else:
|
|
Th.theme.album_seed = Th.dominant_color(img) if img is not None else None
|
|
if getattr(self, "mpris", None) is not None and self.mpris.ok:
|
|
self.mpris.art_changed()
|
|
|
|
def _on_volume(self, v):
|
|
self.vol.set_value(v)
|
|
self.vol_lbl.setText(f"{v}%")
|
|
self.mute_btn.setIcon(icon("volume_off" if v == 0 else "volume_down" if v < 50 else "volume_up"))
|
|
|
|
def _summary(self):
|
|
pl = self.mgr.current
|
|
if pl is None:
|
|
return
|
|
n = len(pl.songs)
|
|
self.summary.setText(f"{n} track{'s' if n != 1 else ''} · {fmt_time(pl.total_length(), force_hours=True)}")
|
|
|
|
def toast(self, msg):
|
|
if not msg:
|
|
return
|
|
self.toast_lbl.setText(" • " + str(msg))
|
|
self._toast_timer.start()
|
|
|
|
# ================================================================ tray
|
|
def _tray(self):
|
|
if not QSystemTrayIcon.isSystemTrayAvailable():
|
|
return
|
|
self.tray_icon = QSystemTrayIcon(app_icon(), self)
|
|
m = QMenu()
|
|
m.addAction(icon("skip_previous_fill"), "Previous", self.player.prev)
|
|
self.tray_play = m.addAction(icon("play_arrow_fill"), "Play", self.player.play_pause)
|
|
m.addAction(icon("skip_next_fill"), "Next", self.player.next)
|
|
m.addAction(icon("stop_fill"), "Stop", self.player.stop)
|
|
m.addSeparator()
|
|
m.addAction("Show / hide", self._toggle_visible)
|
|
m.addAction(icon("close"), "Quit", self.quit_app)
|
|
self.tray_icon.setContextMenu(m)
|
|
self.tray_icon.activated.connect(
|
|
lambda r: self._toggle_visible() if r == QSystemTrayIcon.ActivationReason.Trigger else
|
|
self.player.play_pause() if r == QSystemTrayIcon.ActivationReason.MiddleClick else None)
|
|
self.tray_icon.setVisible(settings.get("appearance/tray"))
|
|
|
|
def _toggle_visible(self):
|
|
if self.isVisible() and self.isActiveWindow():
|
|
self.hide()
|
|
else:
|
|
self.show()
|
|
self.raise_()
|
|
self.activateWindow()
|
|
|
|
# ================================================================ drag & drop
|
|
def dragEnterEvent(self, e):
|
|
if e.mimeData().hasUrls():
|
|
e.acceptProposedAction()
|
|
|
|
def dropEvent(self, e):
|
|
paths = [u.toLocalFile() for u in e.mimeData().urls() if u.isLocalFile()]
|
|
streams = [Song(url=u.toString(), title=u.toString()) for u in e.mimeData().urls() if not u.isLocalFile()]
|
|
if paths:
|
|
self.add_paths(paths, "append")
|
|
if streams:
|
|
self.add_songs(streams, "append")
|
|
|
|
def eventFilter(self, obj, ev):
|
|
if obj is getattr(self, "bottom_bar", None) and ev.type() in (QEvent.Type.Resize, QEvent.Type.Move):
|
|
QTimer.singleShot(0, self._place_shape)
|
|
if ev.type() == QEvent.Type.Polish and isinstance(obj, QMenu):
|
|
obj.setWindowFlag(Qt.WindowType.FramelessWindowHint, True)
|
|
obj.setWindowFlag(Qt.WindowType.NoDropShadowWindowHint, True)
|
|
obj.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True)
|
|
return False
|
|
|
|
# ================================================================ lifecycle
|
|
def handle_args(self, args: list[str]):
|
|
paths = [a for a in args if os.path.exists(a)]
|
|
urls = [a for a in args if "://" in a and not os.path.exists(a)]
|
|
if paths:
|
|
self.add_paths(paths, "play")
|
|
for u in urls:
|
|
if u.startswith("file://"):
|
|
from .playlist import url_to_path
|
|
self.add_paths([url_to_path(u)], "play")
|
|
else:
|
|
self.add_songs([Song(url=u, title=u)], "play")
|
|
if args:
|
|
self.show()
|
|
self.raise_()
|
|
self.activateWindow()
|
|
|
|
def _resume(self):
|
|
if self.player.song is not None or not settings.get("playback/resume"):
|
|
return
|
|
pl = self.mgr.active
|
|
if pl and pl.current_song is not None and not pl.current_song.is_stream:
|
|
try:
|
|
pos = float(L.library.kv("resume_pos", 0) or 0)
|
|
except ValueError:
|
|
pos = 0.0
|
|
self.player.play_song(pl, pl.current_song, start=pos, paused=True)
|
|
|
|
def _restore_geometry(self):
|
|
q = settings.raw()
|
|
g = q.value("ui/geometry")
|
|
if isinstance(g, QByteArray):
|
|
self.restoreGeometry(g)
|
|
else:
|
|
self.resize(1380, 880)
|
|
for key, sp in (("ui/hsplit", self.hsplit), ("ui/vsplit", self.vsplit)):
|
|
st = q.value(key)
|
|
if isinstance(st, QByteArray):
|
|
sp.restoreState(st)
|
|
|
|
def closeEvent(self, e):
|
|
if not self._quitting and settings.get("appearance/tray") and hasattr(self, "tray_icon") \
|
|
and self.tray_icon.isVisible():
|
|
self.hide()
|
|
e.ignore()
|
|
return
|
|
self.quit_app()
|
|
e.accept()
|
|
|
|
def quit_app(self):
|
|
if self._quitting:
|
|
return
|
|
self._quitting = True
|
|
q = settings.raw()
|
|
q.setValue("ui/geometry", self.saveGeometry())
|
|
q.setValue("ui/hsplit", self.hsplit.saveState())
|
|
q.setValue("ui/vsplit", self.vsplit.saveState())
|
|
L.library.set_kv("resume_pos", f"{self.player.pos:.1f}" if self.player.song else "0")
|
|
self.mgr.save_all()
|
|
L.library.stop_scan()
|
|
self.player.shutdown()
|
|
if self.media_keys is not None:
|
|
self.media_keys.close()
|
|
q.sync()
|
|
if hasattr(self, "tray_icon"):
|
|
self.tray_icon.hide()
|
|
QApplication.instance().quit()
|
|
|
|
|
|
class _NoMpris:
|
|
ok = False
|
|
|
|
def modes_changed(self):
|
|
pass
|
|
|
|
def art_changed(self):
|
|
pass
|
|
|
|
|
|
def app_icon() -> QIcon:
|
|
"""Cookie-shaped app icon in the current accent colour."""
|
|
from PyQt6.QtCore import QPointF, QRectF
|
|
from PyQt6.QtGui import QPainter, QPainterPath
|
|
import math
|
|
ic = QIcon()
|
|
for size in (16, 22, 32, 48, 64, 128, 256):
|
|
pm = QPixmap(size, size)
|
|
pm.fill(Qt.GlobalColor.transparent)
|
|
p = QPainter(pm)
|
|
p.setRenderHint(QPainter.RenderHint.Antialiasing)
|
|
c = size / 2
|
|
R = size * 0.47
|
|
path = QPainterPath()
|
|
for i in range(121):
|
|
t = i / 120 * 2 * math.pi
|
|
r = R * (0.92 + 0.08 * math.cos(9 * t))
|
|
pt = QPointF(c + r * math.cos(t), c + r * math.sin(t))
|
|
path.moveTo(pt) if i == 0 else path.lineTo(pt)
|
|
p.fillPath(path, Th.theme["primary"] if Th.theme else Qt.GlobalColor.magenta)
|
|
from .icons import paint_icon
|
|
s = size * 0.56
|
|
paint_icon(p, QRectF(c - s / 2, c - s / 2, s, s), "music_note",
|
|
Th.theme["onPrimary"] if Th.theme else Qt.GlobalColor.white)
|
|
p.end()
|
|
ic.addPixmap(pm)
|
|
return ic
|