commit 615b21d64a3d2c0c1f59af8b643aed856e96f8d4 Author: Mulberry Date: Fri Oct 9 23:00:48 2026 -0500 Mulberry 1.1.0: Material You music player for Linux and Windows - 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 Claude-Session: https://claude.ai/code/session_01J7imThHV9BMkG24GaxPDeq diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..2a94e32 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,115 @@ +name: Build + +on: + push: + branches: [main] + tags: ["v*"] + pull_request: + workflow_dispatch: + +permissions: + contents: write + +jobs: + windows: + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install -r requirements.txt pyinstaller + - name: Version + shell: bash + run: echo "VERSION=$(python -c "import re;print(re.search(r'VERSION = \"(.+?)\"', open('mulberry/config.py').read()).group(1))")" >> $GITHUB_ENV + - name: Icons + run: python packaging/make_icons.py + - name: Fetch libmpv (gapless, EQ, CD playback & ripping) + continue-on-error: true + shell: pwsh + env: + GH_TOKEN: ${{ github.token }} + run: | + $rel = Invoke-RestMethod "https://api.github.com/repos/shinchiro/mpv-winbuild-cmake/releases/latest" -Headers @{ Authorization = "Bearer $env:GH_TOKEN" } + $asset = $rel.assets | Where-Object { $_.name -match '^mpv-dev-x86_64-\d{8}-git-[0-9a-f]+\.7z$' } | Select-Object -First 1 + if (-not $asset) { throw "libmpv asset not found" } + Invoke-WebRequest $asset.browser_download_url -OutFile mpv-dev.7z + 7z x mpv-dev.7z -ompv-dev -y | Out-Null + New-Item -ItemType Directory -Force packaging/windows/mpv | Out-Null + Copy-Item mpv-dev/libmpv-2.dll packaging/windows/mpv/ + Get-ChildItem packaging/windows/mpv + - name: PyInstaller + run: pyinstaller packaging/mulberry.spec --noconfirm --distpath build/dist --workpath build/work + - name: Portable zip + shell: pwsh + run: | + New-Item -ItemType Directory -Force dist | Out-Null + Compress-Archive -Path build/dist/Mulberry -DestinationPath "dist/Mulberry-$env:VERSION-Windows-Portable.zip" + - name: Installer (Inno Setup) + shell: pwsh + run: | + $iscc = "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe" + if (-not (Test-Path $iscc)) { choco install innosetup -y --no-progress; $iscc = "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe" } + & $iscc "/DAppVersion=$env:VERSION" packaging\windows\mulberry.iss + - uses: actions/upload-artifact@v4 + with: + name: windows + path: dist/* + + linux: + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: System packages + run: sudo apt-get update && sudo apt-get install -y libegl1 libxkbcommon0 libxcb-cursor0 desktop-file-utils file + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install -r requirements.txt pyinstaller + - name: Version + run: echo "VERSION=$(python -c "import re;print(re.search(r'VERSION = \"(.+?)\"', open('mulberry/config.py').read()).group(1))")" >> $GITHUB_ENV + - name: Icons + run: python packaging/make_icons.py + - name: PyInstaller + run: pyinstaller packaging/mulberry.spec --noconfirm --distpath build/dist --workpath build/work + - name: Tarball + run: | + mkdir -p dist + cp mulberry.desktop mulberry/assets/mulberry.svg build/dist/Mulberry/ + tar -C build/dist -czf "dist/Mulberry-$VERSION-Linux-x86_64.tar.gz" Mulberry + - name: AppImage + run: | + APPDIR=build/AppDir + mkdir -p $APPDIR/usr/lib $APPDIR/usr/share/icons/hicolor/256x256/apps $APPDIR/usr/share/applications + cp -r build/dist/Mulberry $APPDIR/usr/lib/mulberry + cp packaging/linux/AppRun $APPDIR/AppRun && chmod +x $APPDIR/AppRun + grep -v '^Actions=\|^\[Desktop Action\|^Name=Play\|^Name=Next\|^Name=Previous\|^Exec=dbus' mulberry.desktop > $APPDIR/mulberry.desktop + cp $APPDIR/mulberry.desktop $APPDIR/usr/share/applications/ + cp packaging/build-icons/mulberry-256.png $APPDIR/mulberry.png + cp packaging/build-icons/mulberry-256.png $APPDIR/usr/share/icons/hicolor/256x256/apps/mulberry.png + wget -q https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-x86_64.AppImage -O appimagetool + chmod +x appimagetool + ARCH=x86_64 ./appimagetool --appimage-extract-and-run $APPDIR "dist/Mulberry-$VERSION-x86_64.AppImage" + - uses: actions/upload-artifact@v4 + with: + name: linux + path: dist/* + + release: + if: startsWith(github.ref, 'refs/tags/v') + needs: [windows, linux] + runs-on: ubuntu-latest + steps: + - uses: actions/download-artifact@v4 + with: + path: artifacts + - uses: softprops/action-gh-release@v2 + with: + files: artifacts/**/* + generate_release_notes: true diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fb36c52 --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +__pycache__/ +*.pyc +build/ +dist/ +packaging/build-icons/ +packaging/windows/mpv/ +*.spec.bak +.venv/ +venv/ +*.AppImage diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..645c164 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Mulberry contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..da87946 --- /dev/null +++ b/README.md @@ -0,0 +1,122 @@ +# Mulberry 🫐 + +A full-featured Material You music player for **Linux (KDE and others) and Windows**, written in PyQt6. It combines Strawberry's layout (library sidebar, tabbed playlists, analyzer) with an expressive "now playing" panel: a cookie-shaped cover with a radial visualizer, a wavy seek bar, morphing buttons and synced lyrics. Its colours come live from your system: the KDE colour scheme and accent on Linux, the Windows accent colour and light/dark mode on Windows. + +![Mulberry](docs/screenshot.png) + +## Download + +Grab the latest build from the **[Releases](../../releases)** page: + +| Platform | File | Notes | +|---|---|---| +| Windows 10/11 (x64) | `Mulberry-x.y.z-Windows-Setup.exe` | Installer with Start menu entry and "Open with" integration | +| Windows (portable) | `Mulberry-x.y.z-Windows-Portable.zip` | Unzip anywhere and run `Mulberry.exe` | +| Linux (any distro) | `Mulberry-x.y.z-x86_64.AppImage` | `chmod +x` it and run it | +| Linux | `Mulberry-x.y.z-Linux-x86_64.tar.gz` | Plain folder; run `Mulberry/mulberry` | + +The Windows builds include libmpv, so gapless playback, the EQ, CD playback and CD ripping work out of the box. On Linux, Mulberry uses your system's `mpv` (install it for those features); without it, the built-in Qt/FFmpeg engine still plays nearly everything. + +## Run from source + +**Linux** +```bash +./install.sh # venv + `mulberry` launcher + app-menu entry and icon +mulberry +``` +Or run it straight from the folder: `pip install -r requirements.txt && ./run.sh` + +**Windows** (Python 3.10+) +```bat +py -m pip install -r requirements.txt +run.bat +``` + +**Build the packages yourself:** `pip install pyinstaller && python packaging/make_icons.py && pyinstaller packaging/mulberry.spec`. GitHub Actions builds every format on each push, and pushing a tag like `v1.1.0` publishes a Release automatically. + +### Optional Linux packages + +| Package | What it enables | +|---|---| +| `mpv` / `libmpv` | Gapless playback, 10-band EQ, ReplayGain, audio-CD playback | +| `cdparanoia` + `ffmpeg` | Best-quality CD ripping (libmpv is used otherwise) | +| `libdiscid` | Faster CD TOC reading | +| `chromaprint` (`fpcalc`) | AcoustID audio fingerprint tag lookup | + +### Platform differences + +| | Linux | Windows | +|---|---|---| +| Theme source | KDE `kdeglobals`, live-updating (or the Qt palette on other desktops) | Accent colour + light/dark mode from Windows settings, live-updating | +| Default engine | mpv, falling back to Qt | Qt (needed for the visualizer); mpv is selectable in Settings for EQ and gapless playback | +| Media keys / OS media controls | MPRIS: Plasma widget, lock screen, KDE Connect, shells | Global media keys | +| Notifications | Desktop notifications with cover art | Tray notifications | + +## Features + +**Look and feel** +- Material 3 colour roles built from your KDE accent and window colours (`~/.config/kdeglobals`). Change your KDE colours and the player recolours instantly. +- Other colour sources: dynamic colours taken from the album art, or a custom seed colour. Light/dark either follows KDE or can be forced. +- Hero panel: a cookie-shaped cover with a slow-spinning radial spectrum, a wavy M3 Expressive progress bar, a play button that morphs shape, and a synced lyrics card where you can click a line to seek. +- Three layouts: Large, Compact bar, or Hidden (a mini transport moves to the bottom bar). F11 or clicking the cover gives a Focus mode with a big cover and lyrics. +- An optional **floating bass shape** in the bottom-left corner (Settings › Appearance, or View menu). It morphs between Material shapes on bass hits, spins, pulses in size and cycles through your theme colours. Click it to play or pause. +- The playing track gets a gradient pill, and the album art shows faintly behind the playlist. The bottom bar has a block spectrum analyzer. + +**Library and playback** +- SQLite collection with an incremental background scanner (only changed files are re-read). Group by album artist, artist, genre, year or album, and search with `artist:` `album:` `genre:` `year:>2000` `rating:>3`. +- Formats: MP3, FLAC, Ogg Vorbis/Opus/Speex, AAC/ALAC/M4A, WMA, APE, WavPack, Musepack, TTA, OptimFROG, TAK, AIFF, WAV, DSF/DFF, MKA, tracker modules, MIDI and more. Cue sheets play as separate tracks. +- Tabbed playlists with undo/redo, drag and drop, column chooser, sort by column, filtering, duplicate and unavailable-file removal, and saved/pinned playlists. +- A play queue with Play next, Stop after this track, shuffle, and repeat (track or playlist). +- Smart playlists: Recently added, Most played, Recently played, Loved & top rated, Never played, Random 100, Most skipped. +- Play counts, skip counts and 0–5 star ratings. +- Playlist import: M3U, M3U8, PLS, XSPF, WPL, ASX, CUE. Export: M3U, M3U8, PLS, XSPF, WPL, with relative or absolute paths. +- Internet radio with ICY now-playing titles. A few SomaFM, Radio Paradise and KEXP stations are included, and you can add your own. +- Output device selection, a 10-band equalizer with presets, ReplayGain (track or album, with pre-amp), and resume where you left off. + +**Online and metadata** +- Last.fm scrobbling, now-playing updates and Love. Scrobbles are cached offline and batch-sent later. +- ListenBrainz submissions and loved-track feedback. +- Tag editor for single files or many at once, with cover embedding for MP3, FLAC, Ogg, M4A and APE/WavPack. +- MusicBrainz tag lookup, either picking a match or auto-applying it in batch, plus AcoustID fingerprinting. +- Automatic cover fetching (iTunes, Deezer, Cover Art Archive, Last.fm) and a cover manager with a grid of candidates. +- Synced lyrics. In the lyrics card's ⋮ menu you can pick the source: **Auto** (local `.lrc` → embedded → LRCLIB → NetEase), **LRCLIB**, **NetEase Cloud Music**, **Local .lrc files** (such as those downloaded by LRCGET) or **Embedded tags**. You can also turn on **Show as plain text**. Click any synced line to jump there. You can also edit lyrics, nudge their timing, and switch the card to the artist bio. + +**Audio CD** +- Detects drives, reads the TOC (libdiscid, cdparanoia or cd-info), looks the disc up on MusicBrainz and fetches its cover. +- Plays CD tracks (mpv backend). +- Ripper: format, quality, folder and filename pattern are configurable. It tags the files, embeds the cover and adds the result to your library. + +**Desktop integration** +- Full MPRIS2 support, so Plasma's media controls, the lock screen, KDE Connect, media keys and shell widgets like Quickshell all see and control it. +- Desktop notifications with the album art. +- Tray icon (close to tray), single instance (opening files from Dolphin adds them to the running player), and native KDE file dialogs through the XDG portal. + +## Last.fm setup +In **Settings › Scrobbling**, click **Log in with Last.fm**. Your browser opens Last.fm's authorisation page. Click *Yes, allow access* there, and Mulberry detects it within a few seconds; no further clicks are needed. + +Last.fm issues API keys per application, so the login button needs one key for this copy of Mulberry. You only have to add it once: +- **Simplest:** tick *Use my own API key*, create a free key at , paste the key and secret, then press Log in. +- **Or for everyone on the machine:** put the key in `mulberry/lastfm_app.py`, in `~/.config/mulberry/lastfm_app.json` (`{"key": "...", "secret": "..."}`), or in the `MULBERRY_LASTFM_KEY` and `MULBERRY_LASTFM_SECRET` environment variables. After that the login button works without anyone touching keys. + +## Keyboard shortcuts +| Keys | Action | +|---|---| +| Space | Play / pause | +| Ctrl+← / Ctrl+→ | Previous / next | +| Alt+← / Alt+→ | Seek −/+ 10 s | +| Ctrl+↑ / Ctrl+↓, Ctrl+M | Volume, mute | +| Ctrl+D | Queue / dequeue selected | +| Ctrl+J | Jump to the playing track | +| Ctrl+F | Filter the playlist | +| Ctrl+E | Edit tags | +| Ctrl+T / Ctrl+W | New / close playlist | +| Ctrl+I / Ctrl+S | Import / export playlist | +| Ctrl+Z / Ctrl+Shift+Z | Undo / redo | +| Ctrl+L | Love the current track | +| F5 / Ctrl+F5 | Update library / full rescan | +| F11 | Focus mode | + +## Files (Linux; on Windows they live in `%APPDATA%\Mulberry` and `%LOCALAPPDATA%\Mulberry`) +- Settings: `~/.config/mulberry/mulberry.conf` +- Library, playlists and lyrics cache: `~/.local/share/mulberry/library.db` +- Covers: `~/.local/share/mulberry/covers`, thumbnails in `~/.cache/mulberry` diff --git a/docs/screenshot.png b/docs/screenshot.png new file mode 100644 index 0000000..204f68d Binary files /dev/null and b/docs/screenshot.png differ diff --git a/docs/shape.png b/docs/shape.png new file mode 100644 index 0000000..db3c606 Binary files /dev/null and b/docs/shape.png differ diff --git a/install.sh b/install.sh new file mode 100755 index 0000000..9b76794 --- /dev/null +++ b/install.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +# Installs Mulberry for the current user (no root needed for the app itself). +set -euo pipefail +SRC="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PREFIX="${XDG_DATA_HOME:-$HOME/.local/share}/mulberry-app" +BIN="$HOME/.local/bin" + +echo "==> Checking system packages" +missing=() +ldconfig -p 2>/dev/null | grep -q libmpv.so || missing+=("mpv / libmpv (gapless, EQ, ReplayGain, audio CD playback)") +command -v cdparanoia >/dev/null || missing+=("cdparanoia (CD ripping)") +command -v ffmpeg >/dev/null || missing+=("ffmpeg (CD rip encoding)") +command -v fpcalc >/dev/null || missing+=("chromaprint / fpcalc (optional: AcoustID fingerprints)") +if ((${#missing[@]})); then + echo " Optional tools not found (install with your package manager):" + for m in "${missing[@]}"; do echo " - $m"; done + echo " e.g. Arch: sudo pacman -S mpv cdparanoia ffmpeg chromaprint libdiscid" + echo " Fedora: sudo dnf install mpv-libs cdparanoia ffmpeg chromaprint-tools libdiscid" + echo " Debian/Ubuntu/KDE neon: sudo apt install libmpv2 cdparanoia ffmpeg libchromaprint-tools libdiscid0" +fi + +echo "==> Creating virtual environment in $PREFIX" +mkdir -p "$PREFIX" +python3 -m venv "$PREFIX/venv" +"$PREFIX/venv/bin/pip" install --upgrade pip >/dev/null +"$PREFIX/venv/bin/pip" install -r "$SRC/requirements.txt" +"$PREFIX/venv/bin/pip" install discid >/dev/null 2>&1 || true # optional, uses libdiscid + +echo "==> Copying application" +rm -rf "$PREFIX/mulberry" +cp -r "$SRC/mulberry" "$PREFIX/mulberry" + +mkdir -p "$BIN" +cat > "$BIN/mulberry" < Desktop integration" +APPS="${XDG_DATA_HOME:-$HOME/.local/share}/applications" +ICONS="${XDG_DATA_HOME:-$HOME/.local/share}/icons/hicolor/scalable/apps" +mkdir -p "$APPS" "$ICONS" +sed "s|^Exec=mulberry|Exec=$BIN/mulberry|" "$SRC/mulberry.desktop" > "$APPS/mulberry.desktop" +cp "$SRC/mulberry/assets/mulberry.svg" "$ICONS/mulberry.svg" +command -v update-desktop-database >/dev/null && update-desktop-database "$APPS" || true +command -v kbuildsycoca6 >/dev/null && kbuildsycoca6 >/dev/null 2>&1 || true + +echo +echo "Done! Launch Mulberry from your app menu, or run: mulberry" diff --git a/mulberry.desktop b/mulberry.desktop new file mode 100644 index 0000000..1544bd1 --- /dev/null +++ b/mulberry.desktop @@ -0,0 +1,26 @@ +[Desktop Entry] +Type=Application +Name=Mulberry +GenericName=Music Player +Comment=Material You music player that follows your KDE colours +Exec=mulberry %U +Icon=mulberry +Terminal=false +Categories=AudioVideo;Audio;Player;Qt;KDE; +MimeType=audio/mpeg;audio/flac;audio/x-flac;audio/ogg;audio/x-vorbis+ogg;audio/opus;audio/mp4;audio/aac;audio/x-m4a;audio/x-wav;audio/x-ms-wma;audio/x-ape;audio/x-wavpack;audio/x-musepack;audio/x-aiff;audio/x-mpegurl;audio/x-scpls;application/xspf+xml;application/x-cue;x-content/audio-cdda; +Keywords=music;player;audio;lyrics;lastfm;cd; +StartupWMClass=mulberry +X-KDE-StartupNotify=true +Actions=PlayPause;Next;Previous; + +[Desktop Action PlayPause] +Name=Play/Pause +Exec=dbus-send --session --type=method_call --dest=org.mpris.MediaPlayer2.mulberry /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.PlayPause + +[Desktop Action Next] +Name=Next track +Exec=dbus-send --session --type=method_call --dest=org.mpris.MediaPlayer2.mulberry /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.Next + +[Desktop Action Previous] +Name=Previous track +Exec=dbus-send --session --type=method_call --dest=org.mpris.MediaPlayer2.mulberry /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.Previous diff --git a/mulberry/__init__.py b/mulberry/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/mulberry/__main__.py b/mulberry/__main__.py new file mode 100644 index 0000000..4ad1020 --- /dev/null +++ b/mulberry/__main__.py @@ -0,0 +1,98 @@ +"""Entry point: python -m mulberry [files/urls…]""" +from __future__ import annotations + +import json +import os +import sys + + +def main(): + from PyQt6.QtCore import Qt + from PyQt6.QtNetwork import QLocalServer, QLocalSocket + from PyQt6.QtWidgets import QApplication + + from .config import APP_ID, APP_NAME, IS_LINUX, IS_WIN + + if IS_LINUX: + # pip-installed Qt has no KDE platform theme; use the XDG portal so + # file dialogs are the native KDE ones. + from PyQt6.QtCore import QLibraryInfo + themes = os.path.join(QLibraryInfo.path(QLibraryInfo.LibraryPath.PluginsPath), "platformthemes") + have_kde = os.path.isdir(themes) and any("kde" in f.lower() for f in os.listdir(themes)) + if not have_kde and os.environ.get("QT_QPA_PLATFORMTHEME", "kde").lower() in ("kde", ""): + os.environ["QT_QPA_PLATFORMTHEME"] = "xdgdesktopportal" + if IS_WIN: + # own taskbar identity (correct icon + grouping instead of python.exe) + try: + import ctypes + ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("Mulberry.MusicPlayer") + except Exception: # noqa: BLE001 + pass + + QApplication.setHighDpiScaleFactorRoundingPolicy(Qt.HighDpiScaleFactorRoundingPolicy.PassThrough) + app = QApplication(sys.argv) + app.setApplicationName(APP_NAME) + app.setApplicationDisplayName(APP_NAME) + app.setOrganizationName(APP_ID) + app.setDesktopFileName(APP_ID) + app.setStyle("Fusion") + app.setQuitOnLastWindowClosed(False) + import locale + locale.setlocale(locale.LC_NUMERIC, "C") + + args = [a for a in sys.argv[1:] if not a.startswith("-")] + import getpass + try: + who = getpass.getuser() + except Exception: # noqa: BLE001 + who = "user" + server_name = f"{APP_ID}-{who}" + sock = QLocalSocket() + sock.connectToServer(server_name) + if sock.waitForConnected(300): + sock.write(json.dumps([os.path.abspath(a) if os.path.exists(a) else a for a in args] or ["--raise"]).encode()) + sock.flush() + sock.waitForBytesWritten(500) + sock.disconnectFromServer() + return 0 + + from .theme import init_theme + init_theme() + from .library import init_library + init_library() + from .mainwindow import MainWindow + + win = MainWindow() + win.show() + + server = QLocalServer() + QLocalServer.removeServer(server_name) + server.listen(server_name) + + def incoming(): + c = server.nextPendingConnection() + if c is None: + return + + def read(): + try: + items = json.loads(bytes(c.readAll()).decode() or "[]") + except ValueError: + items = [] + items = [i for i in items if i != "--raise"] + win.handle_args(items) + win.show() + win.raise_() + win.activateWindow() + c.readyRead.connect(read) + server.newConnection.connect(incoming) + + if args: + win.handle_args([os.path.abspath(a) if os.path.exists(a) else a for a in args]) + rc = app.exec() + server.close() + return rc + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/mulberry/assets/mulberry.svg b/mulberry/assets/mulberry.svg new file mode 100644 index 0000000..b434a53 --- /dev/null +++ b/mulberry/assets/mulberry.svg @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/mulberry/cd.py b/mulberry/cd.py new file mode 100644 index 0000000..ded638c --- /dev/null +++ b/mulberry/cd.py @@ -0,0 +1,371 @@ +"""Audio CD: drive detection, TOC reading, MusicBrainz disc lookup, playback +songs and ripping (cdparanoia/icedax/mpv → FLAC/Opus/MP3/Vorbis/ALAC/WAV).""" +from __future__ import annotations + +import base64 +import glob +import hashlib +import os +import re +import shutil +import subprocess +import tempfile +from pathlib import Path + +from PyQt6.QtCore import QThread, pyqtSignal + +from . import online +from . import tags as T +from .song import Song + + +IS_WIN = os.name == "nt" + + +def list_drives() -> list[str]: + if IS_WIN: + import ctypes + import string + out = [] + mask = ctypes.windll.kernel32.GetLogicalDrives() + for i, letter in enumerate(string.ascii_uppercase): + if mask & (1 << i) and ctypes.windll.kernel32.GetDriveTypeW(f"{letter}:\\") == 5: # DRIVE_CDROM + out.append(f"{letter}:") + return out + drives = sorted(set(glob.glob("/dev/sr[0-9]*"))) + if not drives and os.path.exists("/dev/cdrom"): + drives = ["/dev/cdrom"] + return drives + + +def compute_discid(first: int, last: int, leadout: int, offsets: list[int]) -> str: + s = f"{first:02X}{last:02X}{leadout:08X}" + offs = offsets + [0] * (99 - len(offsets)) + s += "".join(f"{o:08X}" for o in offs[:99]) + h = hashlib.sha1(s.encode("ascii")).digest() + return base64.b64encode(h).decode().replace("+", ".").replace("/", "_").replace("=", "-") + + +def read_toc(device: str) -> dict: + """Returns {'first','last','leadout','offsets','discid','tracks':[(n,start_s,len_s)]}.""" + try: + import discid # python-discid (libdiscid) + d = discid.read(device) + offsets = [t.offset for t in d.tracks] + toc = {"first": d.first_track_num, "last": d.last_track_num, "leadout": d.sectors, + "offsets": offsets, "discid": d.id} + except Exception: # noqa: BLE001 + toc = (_toc_windows(device) if IS_WIN else None) or _toc_cdparanoia(device) or _toc_cdinfo(device) + if not toc: + raise RuntimeError("No audio CD found (or no TOC reader available — install cdparanoia " + "or libdiscid).") + toc["discid"] = compute_discid(toc["first"], toc["last"], toc["leadout"], toc["offsets"]) + offs = toc["offsets"] + [toc["leadout"]] + toc["tracks"] = [(toc["first"] + i, (offs[i] - offs[0]) / 75.0, (offs[i + 1] - offs[i]) / 75.0) + for i in range(len(toc["offsets"]))] + toc["device"] = device + return toc + + +def _toc_windows(device): + """Read the TOC with IOCTL_CDROM_READ_TOC (no extra tools needed).""" + import ctypes + from ctypes import wintypes + k32 = ctypes.windll.kernel32 + k32.CreateFileW.restype = wintypes.HANDLE + h = k32.CreateFileW(f"\\\\.\\{device.rstrip(':')}:", 0x80000000, 0x1 | 0x2, None, 3, 0, None) + if h in (None, wintypes.HANDLE(-1).value): + return None + try: + buf = (ctypes.c_ubyte * 804)() + got = wintypes.DWORD() + if not k32.DeviceIoControl(h, 0x24000, None, 0, buf, 804, ctypes.byref(got), None): + return None + first, last = buf[2], buf[3] + entries = [] + for i in range(last - first + 2): # + lead-out (0xAA) + base = 4 + i * 8 + control = buf[base + 1] >> 4 + num = buf[base + 2] + m, s_, f = buf[base + 5], buf[base + 6], buf[base + 7] + entries.append((num, control, (m * 60 + s_) * 75 + f)) + audio = [e for e in entries[:-1] if not e[1] & 0x4] + if not audio: + return None + leadout = entries[-1][2] + nxt = [e for e in entries[:-1] if e[0] > audio[-1][0]] + if nxt: # enhanced CD: data session after audio + leadout = nxt[0][2] - 11400 + return {"first": audio[0][0], "last": audio[-1][0], "leadout": leadout, + "offsets": [e[2] for e in audio]} + finally: + k32.CloseHandle(h) + + +def _toc_cdparanoia(device): + exe = shutil.which("cdparanoia") + if not exe: + return None + try: + p = subprocess.run([exe, "-Q", "-d", device], capture_output=True, text=True, timeout=30) + except (OSError, subprocess.TimeoutExpired): + return None + rows = re.findall(r"^\s*(\d+)\.\s+(\d+)\s+\[[^\]]+\]\s+(\d+)\s+\[", p.stderr + p.stdout, re.M) + if not rows: + return None + nums = [int(r[0]) for r in rows] + offsets = [int(r[2]) + 150 for r in rows] + leadout = int(rows[-1][2]) + int(rows[-1][1]) + 150 + return {"first": nums[0], "last": nums[-1], "leadout": leadout, "offsets": offsets} + + +def _toc_cdinfo(device): + exe = shutil.which("cd-info") + if not exe: + return None + try: + p = subprocess.run([exe, "--no-header", "--no-device-info", "--no-cddb", "-C", device], + capture_output=True, text=True, timeout=30) + except (OSError, subprocess.TimeoutExpired): + return None + rows = re.findall(r"^\s*(\d+):\s+\d+:\d+:\d+\s+(\d+)\s+audio", p.stdout, re.M) + lead = re.search(r"^\s*170:\s+\d+:\d+:\d+\s+(\d+)\s+leadout", p.stdout, re.M) + if not rows or not lead: + return None + return {"first": int(rows[0][0]), "last": int(rows[-1][0]), "leadout": int(lead.group(1)) + 150, + "offsets": [int(r[1]) + 150 for r in rows]} + + +def musicbrainz_lookup(toc: dict) -> list[dict]: + """Return candidate releases: {'album','albumartist','year','mb_albumid','tracks':[{title,artist,mbid}]}""" + tocstr = " ".join(str(x) for x in [toc["first"], toc["last"], toc["leadout"], *toc["offsets"]]) + try: + r = online.mb_get(f"discid/{toc['discid']}", {"inc": "recordings+artist-credits", "toc": tocstr}) + except Exception: # noqa: BLE001 + return [] + releases = r.get("releases", []) if "releases" in r else ([r] if r.get("media") else []) + out = [] + for rel in releases: + aa = "".join(a.get("name", "") + a.get("joinphrase", "") for a in rel.get("artist-credit", [])) + for med in rel.get("media", []): + discids = [d.get("id") for d in med.get("discs", [])] + if discids and toc["discid"] not in discids and len(med.get("tracks", [])) != len(toc["offsets"]): + continue + tracks = [] + for t in med.get("tracks", []): + ar = "".join(a.get("name", "") + a.get("joinphrase", "") for a in t.get("artist-credit", [])) or aa + tracks.append({"title": t.get("title", ""), "artist": ar, + "mbid": (t.get("recording") or {}).get("id", "")}) + out.append({"album": rel.get("title", ""), "albumartist": aa, + "year": int((rel.get("date") or "0")[:4] or 0), "mb_albumid": rel.get("id", ""), + "disc": med.get("position", 1), "tracks": tracks, + "country": rel.get("country", "")}) + break + return out + + +def songs_for(toc: dict, release: dict | None, art: str = "") -> list[Song]: + out = [] + for i, (n, start, length) in enumerate(toc["tracks"]): + t = (release or {}).get("tracks", []) + info = t[i] if i < len(t) else {} + s = Song(url=f"cdda://{n}", title=info.get("title") or f"Track {n}", + artist=info.get("artist", (release or {}).get("albumartist", "")), + album=(release or {}).get("album", "Audio CD"), + albumartist=(release or {}).get("albumartist", ""), + year=(release or {}).get("year", 0), track=n, disc=(release or {}).get("disc", 0), + length=length, begin=start, end=start + length, cd_track=n, cd_device=toc["device"], + filetype="CDDA", samplerate=44100, bitdepth=16, channels=2, bitrate=1411, + mb_trackid=info.get("mbid", ""), mb_albumid=(release or {}).get("mb_albumid", ""), art=art) + out.append(s) + return out + + +def eject(device: str): + if IS_WIN: + import ctypes + mci = ctypes.windll.winmm.mciSendStringW + mci(f"open {device} type cdaudio alias mulberrycd", None, 0, None) + mci("set mulberrycd door open", None, 0, None) + mci("close mulberrycd", None, 0, None) + return + exe = shutil.which("eject") + if exe: + subprocess.Popen([exe, device]) + else: + subprocess.Popen(["udisksctl", "eject", "-b", device] if shutil.which("udisksctl") else ["true"]) + + +# ------------------------------------------------------------------ ripping +FORMATS = { + "flac": ("FLAC (lossless)", "flac", lambda q: ["-c:a", "flac", "-compression_level", str(min(max(q, 0), 12))]), + "alac": ("ALAC (lossless, .m4a)", "m4a", lambda q: ["-c:a", "alac"]), + "opus": ("Opus", "opus", lambda q: ["-c:a", "libopus", "-b:a", f"{[64, 96, 128, 160, 192, 256][min(max(q, 0), 5)]}k"]), + "ogg": ("Ogg Vorbis", "ogg", lambda q: ["-c:a", "libvorbis", "-q:a", str(min(max(q, 0), 10))]), + "mp3": ("MP3 (LAME VBR)", "mp3", lambda q: ["-c:a", "libmp3lame", "-q:a", str(max(0, 9 - min(q, 9)))]), + "wav": ("WAV (uncompressed)", "wav", lambda q: ["-c:a", "pcm_s16le"]), +} + + +def rip_tools() -> dict: + return {"cdparanoia": shutil.which("cdparanoia"), "icedax": shutil.which("icedax") or shutil.which("cdda2wav"), + "mpv": shutil.which("mpv"), "ffmpeg": shutil.which("ffmpeg")} + + +def _safe(s: str) -> str: + return re.sub(r'[\\/:*?"<>|\x00-\x1f]', "_", s).strip(" .") or "Unknown" + + +class Ripper(QThread): + progress = pyqtSignal(int, int, str) # track idx, total, message + track_done = pyqtSignal(str) + finished_rip = pyqtSignal(bool, str) + + def __init__(self, songs: list[Song], fmt: str, quality: int, outdir: str, pattern: str, + cover: bytes | None = None): + super().__init__() + self.songs, self.fmt, self.quality = songs, fmt, quality + self.outdir, self.pattern, self.cover = outdir, pattern, cover + self.abort = False + self.proc = None + + def _finish_file(self, s: Song, out: Path): + if self.fmt != "wav": + try: + T.write_tags(str(out), {"title": s.title, "artist": s.artist, "album": s.album, + "albumartist": s.albumartist, "year": s.year, "track": s.track, + "disc": s.disc, "mb_trackid": s.mb_trackid, "mb_albumid": s.mb_albumid}) + if self.cover: + T.embed_cover(str(out), self.cover) + except Exception as e: # noqa: BLE001 + print("tagging failed", e) + if self.cover and not (out.parent / "cover.jpg").exists(): + (out.parent / "cover.jpg").write_bytes(self.cover) + + def cancel(self): + self.abort = True + m = getattr(self, "_mpv", None) + if m is not None: + try: + m.command("stop") + except Exception: # noqa: BLE001 + pass + if self.proc and self.proc.poll() is None: + self.proc.terminate() + + def _grab(self, s: Song, wav: str): + tools = rip_tools() + dev = s.cd_device + if tools["cdparanoia"]: + cmd = [tools["cdparanoia"], "-q", "-d", dev, str(s.cd_track), wav] + elif tools["icedax"]: + cmd = [tools["icedax"], "-D", dev, "-t", str(s.cd_track), "-O", "wav", "-q", wav] + elif tools["mpv"]: + cmd = [tools["mpv"], "--no-config", "--vo=null", f"--cdrom-device={dev}", "cdda://", + f"--start={s.begin:.3f}", f"--end={s.end:.3f}", "--ao=pcm", f"--ao-pcm-file={wav}"] + else: + raise RuntimeError("No CD reader found. Install cdparanoia (recommended).") + self.proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) + _, err = self.proc.communicate() + if self.abort: + raise RuntimeError("Cancelled") + if self.proc.returncode != 0 or not os.path.exists(wav): + raise RuntimeError(f"Reading track {s.cd_track} failed: {err.decode(errors='replace')[-300:]}") + + MPV_CODECS = {"flac": "flac", "alac": "alac", "opus": "libopus", "ogg": "libvorbis", + "mp3": "libmp3lame", "wav": "pcm_s16le"} + + def _mpv_encode(self, s: Song, out: Path): + """Read + encode in one go with libmpv's encoding mode (works on + Windows without cdparanoia/ffmpeg).""" + from .player import mpv_available + if not mpv_available(): + raise RuntimeError("No CD reader found. Install mpv (libmpv), or cdparanoia + ffmpeg.") + import mpv + q = self.quality + opts = {} + if self.fmt == "opus": + opts["oacopts"] = f"b={[64, 96, 128, 160, 192, 256][min(max(q, 0), 5)]}000" + elif self.fmt in ("ogg", "mp3"): + opts["oacopts"] = f"b={[128, 160, 192, 224, 256, 320][min(max(q // 2, 0), 5)]}000" + elif self.fmt == "flac": + opts["oacopts"] = f"compression_level={min(max(q, 0), 12)}" + m = mpv.MPV(video=False, vo="null", terminal=False, config=False, o=str(out), + oac=self.MPV_CODECS[self.fmt], cdrom_device=s.cd_device, + start=f"{s.begin:.3f}", end=f"{s.end:.3f}", **opts) + self._mpv = m + try: + m.play("cdda://") + m.wait_for_playback() + finally: + self._mpv = None + m.terminate() + if self.abort: + raise RuntimeError("Cancelled") + if not out.exists() or out.stat().st_size < 1024: + raise RuntimeError(f"Ripping track {s.cd_track} failed") + + def run(self): + ff = shutil.which("ffmpeg") + tools = rip_tools() + classic = bool(ff and (tools["cdparanoia"] or tools["icedax"] or tools["mpv"])) + if not classic: + from .player import mpv_available + if not mpv_available(): + self.finished_rip.emit(False, "Ripping needs cdparanoia + ffmpeg, or mpv (libmpv).") + return + label, ext, args = FORMATS[self.fmt] + tmp = tempfile.mkdtemp(prefix="mulberry-rip-") + try: + for i, s in enumerate(self.songs): + if self.abort: + break + vals = {"title": _safe(s.title), "artist": _safe(s.display_artist()), "album": _safe(s.album), + "albumartist": _safe(s.effective_albumartist() or "Various Artists"), + "year": s.year, "track": s.track, "disc": s.disc} + try: + rel = self.pattern.format(**vals) + except (KeyError, ValueError, IndexError): + rel = f"{vals['albumartist']}/{vals['album']}/{s.track:02d} - {vals['title']}" + out = Path(self.outdir) / f"{rel}.{ext}" + out.parent.mkdir(parents=True, exist_ok=True) + self.progress.emit(i, len(self.songs), f"Reading track {s.track}: {s.title}") + wav = os.path.join(tmp, f"t{s.cd_track}.wav") + if not classic: + self._mpv_encode(s, out) + self._finish_file(s, out) + self.track_done.emit(str(out)) + continue + self._grab(s, wav) + self.progress.emit(i, len(self.songs), f"Encoding {out.name}") + if self.fmt == "wav" and not ff: + shutil.move(wav, out) + else: + cmd = [ff, "-y", "-loglevel", "error", "-i", wav, *args(self.quality), str(out)] + self.proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) + _, err = self.proc.communicate() + if self.proc.returncode != 0: + raise RuntimeError(f"Encoding failed: {err.decode(errors='replace')[-300:]}") + if self.fmt != "wav": + try: + T.write_tags(str(out), {"title": s.title, "artist": s.artist, "album": s.album, + "albumartist": s.albumartist, "year": s.year, + "track": s.track, "disc": s.disc, + "mb_trackid": s.mb_trackid, "mb_albumid": s.mb_albumid}) + if self.cover: + T.embed_cover(str(out), self.cover) + except Exception as e: # noqa: BLE001 + print("tagging failed", e) + if self.cover and not (out.parent / "cover.jpg").exists(): + (out.parent / "cover.jpg").write_bytes(self.cover) + try: + os.remove(wav) + except OSError: + pass + self.track_done.emit(str(out)) + self.progress.emit(len(self.songs), len(self.songs), "Done") + self.finished_rip.emit(not self.abort, "Cancelled" if self.abort else f"Ripped {len(self.songs)} tracks") + except Exception as e: # noqa: BLE001 + self.finished_rip.emit(False, str(e)) + finally: + shutil.rmtree(tmp, ignore_errors=True) diff --git a/mulberry/clock.py b/mulberry/clock.py new file mode 100644 index 0000000..adb7c36 --- /dev/null +++ b/mulberry/clock.py @@ -0,0 +1,67 @@ +"""One shared, display-rate animation clock. + +Every animated thing (spectrum analysis, cover, wavy bar, lyrics scroll, the +floating shape) runs off this single timer so frames stay in lock-step instead +of two timers beating against each other. Subscribers receive `dt` in seconds +and should animate by time, not by tick count, so jitter never shows as stutter. +""" +from __future__ import annotations + +import time + +from PyQt6.QtCore import Qt, QTimer +from PyQt6.QtGui import QGuiApplication + + +class FrameClock: + _timer: QTimer | None = None + _pre: dict = {} # run first (data producers, e.g. spectrum) + _subs: dict = {} # then painters + _last = 0.0 + dt = 1 / 60 + + @classmethod + def _ensure(cls): + if cls._timer is None: + cls._timer = QTimer() + cls._timer.setTimerType(Qt.TimerType.PreciseTimer) + hz = 60.0 + try: + scr = QGuiApplication.primaryScreen() + if scr is not None and scr.refreshRate() > 30: + hz = min(scr.refreshRate(), 165.0) + except Exception: # noqa: BLE001 + pass + cls._timer.setInterval(max(5, int(1000 / hz))) + cls._timer.timeout.connect(cls._tick) + + @classmethod + def subscribe(cls, fn, pre=False): + cls._ensure() + (cls._pre if pre else cls._subs)[fn] = True + if not cls._timer.isActive(): + cls._last = time.monotonic() + cls._timer.start() + + @classmethod + def unsubscribe(cls, fn): + cls._pre.pop(fn, None) + cls._subs.pop(fn, None) + if not cls._pre and not cls._subs and cls._timer: + cls._timer.stop() + + @classmethod + def is_subscribed(cls, fn) -> bool: + return fn in cls._pre or fn in cls._subs + + @classmethod + def _tick(cls): + now = time.monotonic() + dt = now - cls._last + cls._last = now + # clamp: after a stall don't jump animations forward + cls.dt = dt = max(1 / 240, min(dt, 1 / 20)) + for fn in list(cls._pre): + fn(dt) + for fn in list(cls._subs): + fn(dt) diff --git a/mulberry/config.py b/mulberry/config.py new file mode 100644 index 0000000..54c25f4 --- /dev/null +++ b/mulberry/config.py @@ -0,0 +1,223 @@ +"""Paths, settings and small shared helpers.""" +from __future__ import annotations + +import os +import sys +import traceback +from pathlib import Path + +from PyQt6.QtCore import QObject, QRunnable, QSettings, QThreadPool, pyqtSignal + +APP_NAME = "Mulberry" +APP_ID = "mulberry" +VERSION = "1.1.0" +USER_AGENT = f"{APP_NAME}/{VERSION} ( https://github.com/mulberry-player )" + +IS_WIN = sys.platform == "win32" +IS_MAC = sys.platform == "darwin" +IS_LINUX = not IS_WIN and not IS_MAC +FROZEN = bool(getattr(sys, "frozen", False)) +# folder holding bundled extras (libmpv dll, assets) in a PyInstaller build +BUNDLE_DIR = Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parent.parent)) + + +def _xdg(var: str, default: str) -> Path: + return Path(os.environ.get(var) or os.path.expanduser(default)) + + +if IS_WIN: + _roaming = Path(os.environ.get("APPDATA") or Path.home() / "AppData" / "Roaming") + _local = Path(os.environ.get("LOCALAPPDATA") or Path.home() / "AppData" / "Local") + CONFIG_DIR = _roaming / APP_NAME + DATA_DIR = _local / APP_NAME + CACHE_DIR = _local / APP_NAME / "cache" +elif IS_MAC: + _sup = Path.home() / "Library" / "Application Support" / APP_NAME + CONFIG_DIR, DATA_DIR = _sup, _sup + CACHE_DIR = Path.home() / "Library" / "Caches" / APP_NAME +else: + CONFIG_DIR = _xdg("XDG_CONFIG_HOME", "~/.config") / APP_ID + DATA_DIR = _xdg("XDG_DATA_HOME", "~/.local/share") / APP_ID + CACHE_DIR = _xdg("XDG_CACHE_HOME", "~/.cache") / APP_ID +COVER_DIR = DATA_DIR / "covers" +THUMB_DIR = CACHE_DIR / "thumbs" +DB_PATH = DATA_DIR / "library.db" +SCROBBLE_CACHE = DATA_DIR / "scrobble_cache.json" + +for _d in (CONFIG_DIR, DATA_DIR, CACHE_DIR, COVER_DIR, THUMB_DIR): + _d.mkdir(parents=True, exist_ok=True) + +AUDIO_EXTS = { + "mp3", "mp2", "mp1", "flac", "ogg", "oga", "opus", "spx", "m4a", "m4b", "mp4", "aac", + "alac", "wav", "wave", "aif", "aiff", "aifc", "wma", "asf", "ape", "wv", "mpc", "mp+", + "tta", "ofr", "ofs", "tak", "dsf", "dff", "mka", "webm", "ac3", "eac3", "dts", "amr", + "au", "snd", "caf", "w64", "rf64", "mod", "xm", "it", "s3m", "mtm", "umx", "669", + "med", "okt", "far", "stm", "ult", "psm", "mptm", "spc", "vgm", "vgz", "gym", "nsf", + "sid", "mid", "midi", "kar", "3gp", "m4r", "aa", "aax", "voc", "mlp", "thd", "truehd", +} +PLAYLIST_EXTS = {"m3u", "m3u8", "pls", "xspf", "wpl", "asx", "cue"} + + +class Settings: + """Thin typed wrapper around QSettings with defaults.""" + + DEFAULTS = { + "library/folders": [], + "library/scan_on_start": True, + "library/grouping": "albumartist_album", + "playback/backend": "auto", # auto (mpv on Linux, Qt on Windows) | mpv | qt + "playback/device": "", + "playback/volume": 70, + "playback/replaygain": "off", # off | track | album + "playback/rg_preamp": 0.0, + "playback/gapless": True, + "playback/eq_enabled": False, + "playback/eq_bands": [0.0] * 10, + "playback/eq_preamp": 0.0, + "playback/repeat": "off", # off | track | playlist + "playback/shuffle": False, + "playback/resume": True, + "appearance/color_source": "kde", # kde (= follow system) | album | custom + "appearance/mode": "kde", # kde | dark | light + "appearance/custom_color": "#9a7fd1", + "appearance/hero": "full", # full | compact | hidden + "appearance/playlist_art_bg": True, + "appearance/visualizer": True, + "appearance/analyzer": True, + "appearance/font": "", + "appearance/notifications": True, + "appearance/tray": True, + "lastfm/enabled": False, + "lastfm/api_key": "", + "lastfm/use_own_key": False, + "lastfm/api_secret": "", + "lastfm/session": "", + "lastfm/user": "", + "listenbrainz/enabled": False, + "listenbrainz/token": "", + "online/auto_lyrics": True, + "lyrics/source": "auto", # auto | lrclib | netease | local | embedded + "lyrics/plain": False, + "appearance/floating_shape": True, + "online/auto_covers": True, + "online/save_covers_to_folder": False, + "online/acoustid_key": "", + "cd/device": "", + "cd/rip_format": "flac", + "cd/rip_quality": 5, + "cd/rip_dir": str(Path.home() / "Music"), + "cd/rip_pattern": "{albumartist}/{album}/{track:02d} - {title}", + } + + def __init__(self): + self.q = QSettings(str(CONFIG_DIR / "mulberry.conf"), QSettings.Format.IniFormat) + + def get(self, key: str, default=None): + d = self.DEFAULTS.get(key, default) + v = self.q.value(key, d) + if v is None: + return d + if isinstance(d, bool): + return v if isinstance(v, bool) else str(v).lower() in ("1", "true", "yes") + if isinstance(d, int) and not isinstance(d, bool): + try: + return int(v) + except (TypeError, ValueError): + return d + if isinstance(d, float): + try: + return float(v) + except (TypeError, ValueError): + return d + if isinstance(d, list): + if isinstance(v, str): + v = [v] if v else [] + if d and isinstance(d[0], float): + try: + return [float(x) for x in v] + except (TypeError, ValueError): + return d + return list(v) + return v + + def set(self, key: str, value): + self.q.setValue(key, value) + + def raw(self): + return self.q + + +settings = Settings() + + +# ---------------------------------------------------------------- async helper +class _Signals(QObject): + done = pyqtSignal(object) + failed = pyqtSignal(str) + + +class _Job(QRunnable): + def __init__(self, fn, args, kwargs): + super().__init__() + self.fn, self.args, self.kwargs = fn, args, kwargs + self.sig = _Signals() + self.setAutoDelete(True) + + def run(self): + try: + res = self.fn(*self.args, **self.kwargs) + except Exception as e: # noqa: BLE001 + import urllib.error + if not isinstance(e, (urllib.error.URLError, TimeoutError, OSError, RuntimeError)): + traceback.print_exc() + try: + self.sig.failed.emit(str(e) or e.__class__.__name__) + except RuntimeError: + pass + return + try: + self.sig.done.emit(res) + except RuntimeError: + pass + + +_jobs: set = set() +_pool = QThreadPool() +_pool.setMaxThreadCount(6) + + +def run_async(fn, *args, on_done=None, on_error=None, **kwargs): + """Run fn in a worker thread; deliver result/error on the GUI thread.""" + job = _Job(fn, args, kwargs) + sig = job.sig + _jobs.add(sig) + + def _finish(res): + _jobs.discard(sig) + if on_done: + on_done(res) + + def _fail(msg): + _jobs.discard(sig) + if on_error: + on_error(msg) + + sig.done.connect(_finish) + sig.failed.connect(_fail) + _pool.start(job) + return sig + + +def fmt_time(sec: float | int | None, force_hours=False) -> str: + if sec is None or sec < 0: + return "--:--" + sec = int(sec) + h, rem = divmod(sec, 3600) + m, s = divmod(rem, 60) + if h or force_hours: + return f"{h}:{m:02d}:{s:02d}" + return f"{m}:{s:02d}" + + +def is_audio_file(path: str) -> bool: + return Path(path).suffix.lower().lstrip(".") in AUDIO_EXTS diff --git a/mulberry/icondata.py b/mulberry/icondata.py new file mode 100644 index 0000000..fd171c0 --- /dev/null +++ b/mulberry/icondata.py @@ -0,0 +1,91 @@ +"""Material Symbols Rounded (Apache 2.0) path data, viewBox 0 -960 960 960.""" +PATHS = { + 'play_arrow_fill': 'M320-258v-450q0-14 9-22t21-8q4 0 8 1t8 3l354 226q7 5 10.5 11t3.5 14q0 8-3.5 14T720-458L366-232q-4 2-8 3t-8 1q-12 0-21-8t-9-22Z', + 'pause_fill': 'M615-200q-24.75 0-42.37-17.63Q555-235.25 555-260v-440q0-24.75 17.63-42.38Q590.25-760 615-760h55q24.75 0 42.38 17.62Q730-724.75 730-700v440q0 24.75-17.62 42.37Q694.75-200 670-200h-55Zm-325 0q-24.75 0-42.37-17.63Q230-235.25 230-260v-440q0-24.75 17.63-42.38Q265.25-760 290-760h55q24.75 0 42.38 17.62Q405-724.75 405-700v440q0 24.75-17.62 42.37Q369.75-200 345-200h-55Z', + 'skip_previous_fill': 'M220-270v-420q0-13 8.5-21.5T250-720q13 0 21.5 8.5T280-690v420q0 13-8.5 21.5T250-240q-13 0-21.5-8.5T220-270Zm473-3L430-455q-7-5-10-11.5t-3-13.5q0-7 3-13.5t10-11.5l263-182q4-3 8-4.5t9-1.5q12 0 21 8t9 22v366q0 14-9 22t-21 8q-5 0-9-1.5t-8-4.5Z', + 'skip_next_fill': 'M680-270v-420q0-13 8.5-21.5T710-720q13 0 21.5 8.5T740-690v420q0 13-8.5 21.5T710-240q-13 0-21.5-8.5T680-270Zm-460-27v-366q0-14 9-22t21-8q5 0 9 1.5t8 4.5l263 182q7 5 10 11.5t3 13.5q0 7-3 13.5T530-455L267-273q-4 3-8 4.5t-9 1.5q-12 0-21-8t-9-22Z', + 'stop_fill': 'M240-300v-360q0-24.75 17.63-42.38Q275.25-720 300-720h360q24.75 0 42.38 17.62Q720-684.75 720-660v360q0 24.75-17.62 42.37Q684.75-240 660-240H300q-24.75 0-42.37-17.63Q240-275.25 240-300Z', + 'shuffle': 'M606-160q-13 0-21.5-8.5T576-190q0-13 8.5-21.5T606-220h90L543-372q-9-9-9-21t9-21q9-9 21.5-9.5T586-415l154 153v-91q0-13 8.5-21.5T770-383q13 0 21.5 8.5T800-353v163q0 13-8.5 21.5T770-160H606Zm-436-10q-9-9-9-21t9-21l528-528h-92q-13 0-21.5-8.5T576-770q0-13 8.5-21.5T606-800h164q13 0 21.5 8.5T800-770v163q0 13-8.5 21.5T770-577q-13 0-21.5-8.5T740-607v-90L212-169q-9 9-21 8.5t-21-9.5Zm-1-579q-9-9-9-21.5t9-21.5q9-9 21-9t21 9l205 205q9 9 9.5 21t-8.5 21q-9 9-21.5 9t-21.5-9L169-749Z', + 'repeat': 'm236-210 65 65q9 9 8.5 21t-8.75 21.12q-9 9.12-21.37 9.5Q267-93 258-102L141-219q-5-5-7-10.13-2-5.14-2-11 0-5.87 2-10.87 2-5 7-10l117-117q9.07-9 21.53-8.5Q292-386 301-377q8.25 9 8.63 21 .37 12-8.63 21l-65 65h464v-130q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v130q0 24.75-17.62 42.37Q724.75-210 700-210H236Zm488-480H260v130q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82 0-21.32-8.63-8.5-8.62-8.5-21.37v-130q0-24.75 17.63-42.38Q235.25-750 260-750h464l-65-65q-9-9-8.5-21t8.75-21.12q9-9.12 21.38-9.5Q693-867 702-858l117 117q5 5 7 10.13 2 5.14 2 11 0 5.87-2 10.87-2 5-7 10L702-582q-9.07 9-21.53 8.5Q668-574 659-583q-8.25-9-8.62-21-.38-12 8.62-21l65-65Z', + 'repeat_one': 'M466-551h-32q-10.4 0-17.2-7.12-6.8-7.11-6.8-18 0-10.88 7.08-17.38 7.09-6.5 17.92-6.5h50q12.75 0 21.38 8.62Q515-582.75 515-570v184q0 10.4-6.5 17.2-6.5 6.8-17.38 6.8-10.89 0-18-7.08Q466-376.17 466-387v-164ZM236-210l65 65q9 9 8.5 21t-8.75 21.12q-9 9.12-21.37 9.5Q267-93 258-102L141-219q-5-5-7-10.13-2-5.14-2-11 0-5.87 2-10.87 2-5 7-10l117-117q9.07-9 21.53-8.5Q292-386 301-377q8.25 9 8.63 21 .37 12-8.63 21l-65 65h464v-130q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v130q0 24.75-17.62 42.37Q724.75-210 700-210H236Zm488-480H260v130q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82 0-21.32-8.63-8.5-8.62-8.5-21.37v-130q0-24.75 17.63-42.38Q235.25-750 260-750h464l-65-65q-9-9-8.5-21t8.75-21.12q9-9.12 21.38-9.5Q693-867 702-858l117 117q5 5 7 10.13 2 5.14 2 11 0 5.87-2 10.87-2 5-7 10L702-582q-9.07 9-21.53 8.5Q668-574 659-583q-8.25-9-8.62-21-.38-12 8.62-21l65-65Z', + 'volume_up': 'M780-481q0-94-52.5-169T590-759q-12-5-17-16t0-22q5-12 17.5-16.5t25.5.5q101 41 162.5 131T840-481q0 111-61.5 201T616-149q-13 5-25.5.5T573-165q-5-11 0-22t17-16q85-34 137.5-109T780-481ZM280-360H150q-13 0-21.5-8.5T120-390v-180q0-13 8.5-21.5T150-600h130l149-149q14-14 32.5-6.5T480-728v496q0 20-18.5 27.5T429-211L280-360Zm380-120q0 52-26 94t-73 64q-8 4-14.5-1t-6.5-13v-289q0-8 6.5-13t14.5-1q47 22 73 65t26 94ZM420-648 307-540H180v120h127l113 109v-337ZM298-480Z', + 'volume_down': 'M360-360H230q-13 0-21.5-8.5T200-390v-180q0-13 8.5-21.5T230-600h130l149-149q14-14 32.5-6.5T560-728v496q0 20-18.5 27.5T509-211L360-360Zm380-120q0 52-26 94t-73 64q-8 4-14.5-1t-6.5-13v-289q0-8 6.5-13t14.5-1q47 22 73 65t26 94ZM500-648 387-540H260v120h127l113 109v-337ZM378-480Z', + 'volume_off': 'M681-188q-17 12-35.5 22T607-148q-12 5-24.5 0T565-165q-5-11 .5-22t17.5-16q15-5 28.5-12t26.5-17L473-397v165q0 20-18.5 27.5T422-211L273-360H143q-13 0-21.5-8.5T113-390v-180q0-13 8.5-21.5T143-600h126L70-799q-9-9-8.5-21.5T71-842q9-9 21.5-9t21.5 9l721 721q9 9 9 21.5T835-78q-9 9-22 9t-22-9L681-188Zm92-293q0-93-52.5-168.5T583-759q-12-5-17-16t0-22q5-12 17.5-16.5t25.5.5q101 41 162.5 130.5T833-481q0 38-7.5 75T802-334q-8 17-19.5 20.5T760-315q-11-5-16.5-14.5t.5-20.5q15-30 22-63t7-68ZM576-628q38 23 57.5 63.5T653-480v15q0 7-2 15-2 10-11 13t-17-5l-61-61q-5-5-7-10t-2-11v-91q0-9 7.5-13.5t15.5.5Zm-196-57q-5-5-5-11t5-11l42-42q14-14 32.5-6.5T473-728v100q0 10-9.5 13.5T447-618l-67-67Zm33 379v-150l-84-84H173v120h126l114 114Zm-42-192Z', + 'library_music': 'M486-333q41 0 70-28.42T585-431v-252h86q12.75 0 21.38-8.68 8.62-8.67 8.62-21.5 0-12.82-8.62-21.32-8.63-8.5-21.38-8.5h-96q-12.75 0-21.37 8.62Q545-725.75 545-713v207q-11-9-26.32-14T486-525q-39.06 0-66.03 27.37-26.97 27.36-26.97 67Q393-391 419.97-362q26.97 29 66.03 29ZM260-200q-24 0-42-18t-18-42v-560q0-24 18-42t42-18h560q24 0 42 18t18 42v560q0 24-18 42t-42 18H260Zm0-60h560v-560H260v560ZM140-80q-24 0-42-18t-18-42v-590q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v590h590q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32Q742.75-80 730-80H140Zm120-740v560-560Z', + 'folder': 'M140-160q-24 0-42-18.5T80-220v-520q0-23 18-41.5t42-18.5h256q12.44 0 23.72 5t19.37 13.09L481-740h339q23 0 41.5 18.5T880-680v460q0 23-18.5 41.5T820-160H140Zm0-60h680v-460H456l-60-60H140v520Zm0 0v-520 520Z', + 'queue_music': 'M642.94-160q-47.94 0-81.44-33.56t-33.5-81.5q0-47.94 32.67-81.44Q593.33-390 640-390q15.97 0 30.48 3Q685-384 698-377v-308q0-14.88 10.35-24.94T734-720h111q14.88 0 24.94 10.29t10.06 25.5Q880-669 869.94-659T845-649h-87v375q0 47.5-33.56 80.75T642.94-160ZM150-320q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h246q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H150Zm0-170q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h413q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H150Zm0-170q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h413q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H150Z', + 'radio': 'M140-80q-24 0-42-18t-18-42v-511q0-22 15-38.5t35-24.5l471-190q10.59-5 20.79-.5Q632-900 636-889t-.18 21.12Q631.64-857.75 621-854L286-720h534q24 0 42 18t18 42v520q0 24-18 42t-42 18H140Zm0-60h680v-310H140v310Zm248-91.18q28-28.19 28-69Q416-341 387.82-369q-28.19-28-69-28Q278-397 250-368.82q-28 28.19-28 69Q222-259 250.18-231q28.19 28 69 28Q360-203 388-231.18ZM140-510h520v-30.18q0-12.82 8.68-21.32 8.67-8.5 21.5-8.5 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v30h100v-150H140v150Zm0 370v-310 310Z', + 'album': 'M480-316q70 0 120-47.5T650-480q0-71-49.5-120.5T480-650q-69 0-116.5 50T316-480q0 69 47.5 116.5T480-316Zm-28.5-135.5Q440-463 440-480t11.5-28.5Q463-520 480-520t28.5 11.5Q520-497 520-480t-11.5 28.5Q497-440 480-440t-28.5-11.5ZM480-80q-82 0-155-31.5t-127.5-86Q143-252 111.5-325T80-480q0-83 31.5-156t86-127Q252-817 325-848.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 82-31.5 155T763-197.5q-54 54.5-127 86T480-80Zm0-60q142 0 241-99.5T820-480q0-142-99-241t-241-99q-141 0-240.5 99T140-480q0 141 99.5 240.5T480-140Zm0-340Z', + 'search': 'M378-329q-108.16 0-183.08-75Q120-479 120-585t75-181q75-75 181.5-75t181 75Q632-691 632-584.85 632-542 618-502q-14 40-42 75l242 240q9 8.56 9 21.78T818-143q-9 9-22.22 9-13.22 0-21.78-9L533-384q-30 26-69.96 40.5Q423.08-329 378-329Zm-1-60q81.25 0 138.13-57.5Q572-504 572-585t-56.87-138.5Q458.25-781 377-781q-82.08 0-139.54 57.5Q180-666 180-585t57.46 138.5Q294.92-389 377-389Z', + 'add': 'M450-450H230q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h220v-220q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v220h220q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H510v220q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82 0-21.32-8.63-8.5-8.62-8.5-21.37v-220Z', + 'close': 'M480-438 270-228q-9 9-21 9t-21-9q-9-9-9-21t9-21l210-210-210-210q-9-9-9-21t9-21q9-9 21-9t21 9l210 210 210-210q9-9 21-9t21 9q9 9 9 21t-9 21L522-480l210 210q9 9 9 21t-9 21q-9 9-21 9t-21-9L480-438Z', + 'save': 'M180-120q-24 0-42-18t-18-42v-600q0-24 18-42t42-18h478q12.44 0 23.72 5T701-822l121 121q8 8 13 19.28 5 11.28 5 23.72v478q0 24-18 42t-42 18H180Zm600-536L656-780H180v600h600v-476ZM553.5-275.26q30.5-30.27 30.5-73.5 0-43.24-30.26-73.74-30.27-30.5-73.5-30.5-43.24 0-73.74 30.26-30.5 30.27-30.5 73.5 0 43.24 30.26 73.74 30.27 30.5 73.5 30.5 43.24 0 73.74-30.26ZM263-584h298q12.75 0 21.38-8.63Q591-601.25 591-614v-83q0-12.75-8.62-21.38Q573.75-727 561-727H263q-12.75 0-21.37 8.62Q233-709.75 233-697v83q0 12.75 8.63 21.37Q250.25-584 263-584Zm-83-72v476-600 124Z', + 'undo': 'M289-200q-13 0-21.5-8.5T259-230q0-13 8.5-21.5T289-260h280q70 0 120.5-46.5T740-422q0-69-50.5-115.5T569-584H274l93 93q9 9 9 21t-9 21q-9 9-21 9t-21-9L181-593q-5-5-7-10t-2-11q0-6 2-11t7-10l144-144q9-9 21-9t21 9q9 9 9 21t-9 21l-93 93h294q95 0 163.5 64T800-422q0 94-68.5 158T568-200H289Z', + 'redo': 'M686-584H391q-70 0-120.5 46.5T220-422q0 69 50.5 115.5T391-260h280q13 0 21.5 8.5T701-230q0 13-8.5 21.5T671-200H392q-95 0-163.5-64T160-422q0-94 68.5-158T392-644h294l-93-93q-9-9-9-21t9-21q9-9 21-9t21 9l144 144q5 5 7 10t2 11q0 6-2 11t-7 10L635-449q-9 9-21 9t-21-9q-9-9-9-21t9-21l93-93Z', + 'more_vert': 'M479.86-160Q460-160 446-174.14t-14-34Q432-228 446.14-242t34-14Q500-256 514-241.86t14 34Q528-188 513.86-174t-34 14Zm0-272Q460-432 446-446.14t-14-34Q432-500 446.14-514t34-14Q500-528 514-513.86t14 34Q528-460 513.86-446t-34 14Zm0-272Q460-704 446-718.14t-14-34Q432-772 446.14-786t34-14Q500-800 514-785.86t14 34Q528-732 513.86-718t-34 14Z', + 'lyrics': 'M270-410h100q12.75 0 21.38-8.68 8.62-8.67 8.62-21.5 0-12.82-8.62-21.32-8.63-8.5-21.38-8.5H270q-12.75 0-21.37 8.68-8.63 8.67-8.63 21.5 0 12.82 8.63 21.32 8.62 8.5 21.37 8.5Zm489.88-80Q714-490 682-522.12q-32-32.12-32-78T682.06-678q32.06-32 77.86-32 10.08 0 22.58 3 12.5 3 27.5 8v-191q0-12.75 8.63-21.38Q827.25-920 840-920h90q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5h-60v260q0 45.83-32.12 77.92-32.12 32.08-78 32.08ZM270-530h220q12.75 0 21.38-8.68 8.62-8.67 8.62-21.5 0-12.82-8.62-21.32-8.63-8.5-21.38-8.5H270q-12.75 0-21.37 8.68-8.63 8.67-8.63 21.5 0 12.82 8.63 21.32 8.62 8.5 21.37 8.5Zm0-120h220q12.75 0 21.38-8.68 8.62-8.67 8.62-21.5 0-12.82-8.62-21.32-8.63-8.5-21.38-8.5H270q-12.75 0-21.37 8.68-8.63 8.67-8.63 21.5 0 12.82 8.63 21.32 8.62 8.5 21.37 8.5Zm350 410H240L131-131q-5 5-10.5 7t-10.83 2Q99-122 89.5-130q-9.5-8-9.5-22v-668q0-24.75 17.63-42.38Q115.25-880 140-880h480q24.75 0 42.38 17.62Q680-844.75 680-820v59q-17 9-32.36 21-15.35 12-27.64 27v-107H140v596l74-76h406v-187q12.29 15 27.64 27Q663-448 680-439v139q0 24.75-17.62 42.37Q644.75-240 620-240Zm-480-60v-520 520Z', + 'favorite': 'M458.19-144Q447-148 439-156l-53-49Q262-320 171-424.5T80-643q0-90.15 60.5-150.58Q201-854 290-854q51 0 101 24.5t89 80.5q44-56 91-80.5t99-24.5q89 0 149.5 60.42Q880-733.15 880-643q0 114-91 218.5T574-205l-53 49q-8.25 8.38-19.12 12.19Q491-140 480.19-140q-10.8 0-22-4ZM454-683q-27-49-71-80t-93-31q-66 0-108 42.5t-42 108.93q0 57.57 38.88 121.22 38.88 63.66 93 123.5Q326-338 384-286.5q58 51.5 96 86.5 38-34 96-86t112-112.5q54-60.5 93-124.19T820-643q0-66-42.5-108.5T670-794q-50 0-93.5 30.5T504-683q-5 8-11 11.5t-14 3.5q-8 0-14.5-3.5T454-683Zm26 186Z', + 'favorite_fill': 'M458-144q-11-4-19-12l-53-49Q262-320 171-424.5T80-643q0-90 60.5-150.5T290-854q51 0 101 24.5t89 80.5q44-56 91-80.5t99-24.5q89 0 149.5 60.5T880-643q0 114-91 218.5T574-205l-53 49q-8 8-19 12t-22 4q-11 0-22-4Z', + 'settings': 'M421-80q-14 0-25-9t-13-23l-15-94q-19-7-40-19t-37-25l-86 40q-14 6-28 1.5T155-226L97-330q-8-13-4.5-27t15.5-23l80-59q-2-9-2.5-20.5T185-480q0-9 .5-20.5T188-521l-80-59q-12-9-15.5-23t4.5-27l58-104q8-13 22-17.5t28 1.5l86 40q16-13 37-25t40-18l15-95q2-14 13-23t25-9h118q14 0 25 9t13 23l15 94q19 7 40.5 18.5T669-710l86-40q14-6 27.5-1.5T804-734l59 104q8 13 4.5 27.5T852-580l-80 57q2 10 2.5 21.5t.5 21.5q0 10-.5 21t-2.5 21l80 58q12 8 15.5 22.5T863-330l-58 104q-8 13-22 17.5t-28-1.5l-86-40q-16 13-36.5 25.5T592-206l-15 94q-2 14-13 23t-25 9H421Zm15-60h88l14-112q33-8 62.5-25t53.5-41l106 46 40-72-94-69q4-17 6.5-33.5T715-480q0-17-2-33.5t-7-33.5l94-69-40-72-106 46q-23-26-52-43.5T538-708l-14-112h-88l-14 112q-34 7-63.5 24T306-642l-106-46-40 72 94 69q-4 17-6.5 33.5T245-480q0 17 2.5 33.5T254-413l-94 69 40 72 106-46q24 24 53.5 41t62.5 25l14 112Zm44-210q54 0 92-38t38-92q0-54-38-92t-92-38q-54 0-92 38t-38 92q0 54 38 92t92 38Zm0-130Z', + 'sync': 'M220-477q0 63 23.5 109.5T307-287l30 21v-94q0-13 8.5-21.5T367-390q13 0 21.5 8.5T397-360v170q0 13-8.5 21.5T367-160H197q-13 0-21.5-8.5T167-190q0-13 8.5-21.5T197-220h100l-15-12q-64-51-93-111t-29-134q0-94 49.5-171.5T342-766q11-5 21 0t14 16q5 11 0 22.5T361-710q-64 34-102.5 96.5T220-477Zm520-6q0-48-23.5-97.5T655-668l-29-26v94q0 13-8.5 21.5T596-570q-13 0-21.5-8.5T566-600v-170q0-13 8.5-21.5T596-800h170q13 0 21.5 8.5T796-770q0 13-8.5 21.5T766-740H665l15 14q60 56 90 120t30 123q0 93-48 169.5T623-195q-11 6-22.5 1.5T584-210q-5-11 0-22.5t16-17.5q65-33 102.5-96T740-483Z', + 'cloud_download': 'M451-448v-289q-86 11-135 75.5T267-522h-19q-61 0-104.5 43T100-371q0 65 45 108t106 43h500q45 0 77-32t32-77q0-45-32-77t-77-32h-63v-84q0-68-33-117.5T570-718v-65q81 29 129.5 101T748-522v24q72-2 122 46t50 123q0 69-50 119t-119 50H251q-88 0-149.5-61.5T40-371q0-79 50.5-137.5T217-579q15-84 82-148.5T451-792q24 0 42 13.5t18 36.5v294l62-62q9-9 21-9t21 9q9 9 9 21.5t-9 21.5L502-353q-9 9-21 9t-21-9L346-467q-9-9-8.5-21.5T347-510q9-9 21.5-9t21.5 9l61 62Zm29-59Z', + 'image': 'M180-120q-24 0-42-18t-18-42v-600q0-24 18-42t42-18h600q24 0 42 18t18 42v600q0 24-18 42t-42 18H180Zm0-60h600v-600H180v600Zm0 0v-600 600Zm86-97h429q8.5 0 12.75-8t-.75-16L590-457q-5-6-12-6t-12 6L446-302l-81-111q-5-6-12-6t-12 6l-86 112q-6 8-1.75 16t12.75 8Z', + 'edit': 'M180-180h44l472-471-44-44-472 471v44Zm-30 60q-13 0-21.5-8.5T120-150v-73q0-12 5-23.5t13-19.5l557-556q8-8 19-12.5t23-4.5q11 0 22 4.5t20 12.5l44 44q9 9 13 20t4 22q0 11-4.5 22.5T823-694L266-138q-8 8-19.5 13t-23.5 5h-73Zm629-617-41-41 41 41Zm-105 64-22-22 44 44-22-22Z', + 'delete': 'M261-120q-24.75 0-42.37-17.63Q201-155.25 201-180v-570h-11q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h158q0-13 8.63-21.5 8.62-8.5 21.37-8.5h204q12.75 0 21.38 8.62Q612-822.75 612-810h158q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5h-11v570q0 24.75-17.62 42.37Q723.75-120 699-120H261Zm438-630H261v570h438v-570ZM418.5-274.63q8.5-8.62 8.5-21.37v-339q0-12.75-8.68-21.38-8.67-8.62-21.5-8.62-12.82 0-21.32 8.62-8.5 8.63-8.5 21.38v339q0 12.75 8.68 21.37 8.67 8.63 21.5 8.63 12.82 0 21.32-8.63Zm166 0q8.5-8.62 8.5-21.37v-339q0-12.75-8.68-21.38-8.67-8.62-21.5-8.62-12.82 0-21.32 8.62-8.5 8.63-8.5 21.38v339q0 12.75 8.68 21.37 8.67 8.63 21.5 8.63 12.82 0 21.32-8.63ZM261-750v570-570Z', + 'playlist_add': 'M150-330q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h240q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H150Zm0-165q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h410q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H150Zm0-165q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h410q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H150Zm508.5 491.37Q650-177.25 650-190v-140H510q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h140v-140q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v140h140q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H710v140q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82 0-21.32-8.63Z', + 'playlist_play': 'M150-330q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h246q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H150Zm0-165q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h413q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H150Zm0-165q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h413q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H150Zm536 522q-4 3-8 3.5t-8-1.5q-4-2-6-5.6-2-3.6-2-8.4v-262q0-4.8 2-8.4 2-3.6 6-5.6 4-2 8-1.5t8 3.5l178 131q3.33 2 4.67 5 1.33 3 1.33 7t-1.33 7q-1.34 3-4.67 5L686-138Z', + 'file_open': 'M220-80q-24 0-42-18t-18-42v-680q0-24 18-42t42-18h315q12.44 0 23.72 5T578-862l204 204q8 8 13 19.28 5 11.28 5 23.72v215q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82 0-21.32-8.63-8.5-8.62-8.5-21.37v-200H550q-12.75 0-21.37-8.63Q520-617.25 520-630v-190H220v680h380q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32Q612.75-80 600-80H220Zm530-127v95q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82 0-21.32-8.63Q690-99.25 690-112v-168q0-12.75 8.63-21.38Q707.25-310 720-310h168q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5h-96l107 107q9 9 9 21.16t-8.61 21Q890-92 877.53-92q-12.46 0-21.53-9L750-207Zm-530 67v-680 680Z', + 'download': 'M469-327q-5-2-10-7L308-485q-9-9.27-8.5-21.64.5-12.36 9.11-21.36 9.39-9 21.89-9t21.5 9l98 99v-341q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v341l99-99q8.8-9 20.9-8.5 12.1.5 21.49 9.5 8.61 9 8.61 21.5t-9 21.5L501-334q-5 5-10.13 7-5.14 2-11 2-5.87 0-10.87-2ZM220-160q-24 0-42-18t-18-42v-113q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v113h520v-113q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v113q0 24-18 42t-42 18H220Z', + 'upload': 'M220-160q-24 0-42-18t-18-42v-113q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v113h520v-113q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v113q0 24-18 42t-42 18H220Zm230-524-99 99q-8.8 9-20.9 8.5-12.1-.5-21.49-9.5-8.61-9-8.61-21.5t9-21.5l150-150q5-5 10.13-7 5.14-2 11-2 5.87 0 10.87 2 5 2 10 7l151 151q9 9 9 21t-8.61 21q-9.39 9-21.89 9t-21.5-9l-99-98v341q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82 0-21.32-8.63-8.5-8.62-8.5-21.37v-341Z', + 'equalizer': 'M180.5-180.56Q160-201.13 160-230v-180q0-28.88 20.59-49.44t49.5-20.56q28.91 0 49.41 20.56Q300-438.88 300-410v180q0 28.87-20.59 49.44Q258.82-160 229.91-160t-49.41-20.56ZM479.91-160q-28.91 0-49.41-20.56Q410-201.13 410-230v-500q0-28.88 20.59-49.44t49.5-20.56q28.91 0 49.41 20.56Q550-758.88 550-730v500q0 28.87-20.59 49.44Q508.82-160 479.91-160Zm200.59-20.56Q660-201.13 660-230v-300q0-28.88 20.59-49.44t49.5-20.56q28.91 0 49.41 20.56Q800-558.88 800-530v300q0 28.87-20.59 49.44Q758.82-160 729.91-160t-49.41-20.56Z', + 'tune': 'M435.5-128.63Q427-137.25 427-150v-165q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v53h323q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H487v52q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82 0-21.32-8.63ZM150-202q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h187q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H150Zm165.5-174.63Q307-385.25 307-398v-52H150q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h157v-54q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v166q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82 0-21.32-8.63ZM457-450q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h353q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H457Zm144.5-173.63Q593-632.25 593-645v-165q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v52h157q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H653v53q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82 0-21.32-8.63ZM150-698q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h353q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H150Z', + 'info': 'M504.5-288.63q8.5-8.62 8.5-21.37v-180q0-12.75-8.68-21.38-8.67-8.62-21.5-8.62-12.82 0-21.32 8.62-8.5 8.63-8.5 21.38v180q0 12.75 8.68 21.37 8.67 8.63 21.5 8.63 12.82 0 21.32-8.63Zm-1-314.57q9.5-9.2 9.5-22.8 0-14.45-9.48-24.22-9.48-9.78-23.5-9.78t-23.52 9.78Q447-640.45 447-626q0 13.6 9.48 22.8 9.48 9.2 23.5 9.2t23.52-9.2ZM480.27-80q-82.74 0-155.5-31.5Q252-143 197.5-197.5t-86-127.34Q80-397.68 80-480.5t31.5-155.66Q143-709 197.5-763t127.34-85.5Q397.68-880 480.5-880t155.66 31.5Q709-817 763-763t85.5 127Q880-563 880-480.27q0 82.74-31.5 155.5Q817-252 763-197.68q-54 54.31-127 86Q563-80 480.27-80Zm.23-60Q622-140 721-239.5t99-241Q820-622 721.19-721T480-820q-141 0-240.5 98.81T140-480q0 141 99.5 240.5t241 99.5Zm-.5-340Z', + 'person': 'M372-523q-42-42-42-108t42-108q42-42 108-42t108 42q42 42 42 108t-42 108q-42 42-108 42t-108-42ZM160-220v-34q0-38 19-65t49-41q67-30 128.5-45T480-420q62 0 123 15.5T731-360q31 14 50 41t19 65v34q0 25-17.5 42.5T740-160H220q-25 0-42.5-17.5T160-220Zm60 0h520v-34q0-16-9.5-30.5T707-306q-64-31-117-42.5T480-360q-57 0-111 11.5T252-306q-14 7-23 21.5t-9 30.5v34Zm324.5-346.5Q570-592 570-631t-25.5-64.5Q519-721 480-721t-64.5 25.5Q390-670 390-631t25.5 64.5Q441-541 480-541t64.5-25.5ZM480-631Zm0 411Z', + 'music_note': 'M286.5-163.5Q243-207 243-270t43.5-106.5Q330-420 393-420q28 0 50.5 8t39.5 22v-420q0-13 8.5-21.5T513-840h174q13 0 21.5 8.5T717-810v75q0 13-8.5 21.5T687-705H543v435q0 63-43.5 106.5T393-120q-63 0-106.5-43.5Z', + 'graphic_eq': 'M285-270v-420q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v420q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82 0-21.32-8.63-8.5-8.62-8.5-21.37Zm165 160v-740q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v740q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82 0-21.32-8.63Q450-97.25 450-110ZM120-430v-100q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v100q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82 0-21.32-8.63-8.5-8.62-8.5-21.37Zm495 160v-420q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v420q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82 0-21.32-8.63-8.5-8.62-8.5-21.37Zm165-160v-100q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v100q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82 0-21.32-8.63-8.5-8.62-8.5-21.37Z', + 'clear_all': 'M150-280q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h500q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H150Zm80-170q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h500q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H230Zm80-170q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h500q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H310Z', + 'refresh': 'M480-160q-133 0-226.5-93.5T160-480q0-133 93.5-226.5T480-800q85 0 149 34.5T740-671v-99q0-13 8.5-21.5T770-800q13 0 21.5 8.5T800-770v194q0 13-8.5 21.5T770-546H576q-13 0-21.5-8.5T546-576q0-13 8.5-21.5T576-606h138q-38-60-97-97t-137-37q-109 0-184.5 75.5T220-480q0 109 75.5 184.5T480-220q75 0 140-39.5T717-366q5-11 16.5-16.5t22.5-.5q12 5 16 16.5t-1 23.5q-39 84-117.5 133.5T480-160Z', + 'eject': 'M230-260h500q13 0 21.5 8.5T760-230q0 13-8.5 21.5T730-200H230q-13 0-21.5-8.5T200-230q0-13 8.5-21.5T230-260Zm10-139 215-323q5-7 11-10.5t14-3.5q8 0 14 3.5t11 10.5l215 323q10 15 1.5 31T695-352H265q-18 0-26.5-16t1.5-31Zm241-13Zm-162 0h322L480-650 319-412Z', + 'open_in_full': 'M150-120q-12.75 0-21.37-8.63Q120-137.25 120-150v-240q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v168l558-558H570q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h240q12.75 0 21.38 8.62Q840-822.75 840-810v240q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82 0-21.32-8.63-8.5-8.62-8.5-21.37v-168L222-180h168q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H150Z', + 'close_fullscreen': 'M420-378 143-101q-9 9-21 9t-21-9q-9-9-9-21t9-21l277-277H190q-13 0-21.5-8.5T160-450q0-13 8.5-21.5T190-480h260q13 0 21.5 8.5T480-450v260q0 13-8.5 21.5T450-160q-13 0-21.5-8.5T420-190v-188Zm162-162h188q13 0 21.5 8.5T800-510q0 13-8.5 21.5T770-480H510q-13 0-21.5-8.5T480-510v-260q0-13 8.5-21.5T510-800q13 0 21.5 8.5T540-770v188l277-277q9-9 21-9t21 9q9 9 9 21t-9 21L582-540Z', + 'mic': 'M408-453.92q-29-30.91-29-75.08v-251q0-41.67 29.44-70.83Q437.88-880 479.94-880t71.56 29.17Q581-821.67 581-780v251q0 44.17-29 75.08Q523-423 480-423t-72-30.92ZM480-651Zm-30 501v-106q-96-11-166.5-77.5T202-498q-2-12.85 6.59-21.93 8.6-9.07 21.5-9.07 12.91 0 21.41 9t10.5 22q12 81 74.71 132.5Q399.42-314 479.65-314q81.35 0 143.85-51.5T698-498q2-13 10.68-22 8.67-9 21.5-9 12.82 0 21.32 9.07 8.5 9.08 6.5 21.93-11 97-81 164t-167 78v106q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82 0-21.32-8.63-8.5-8.62-8.5-21.37Zm59.5-346.5Q521-510 521-529v-251q0-17-11.79-28.5T480-820q-17.42 0-29.21 11.5T439-780v251q0 19 11.5 32.5T480-483q18 0 29.5-13.5Z', + 'star': 'm323-245 157-94 157 95-42-178 138-120-182-16-71-168-71 167-182 16 138 120-42 178Zm157-24L294-157q-8 5-17 4.5t-16-5.5q-7-5-10.5-13t-1.5-18l49-212-164-143q-8-7-9.5-15.5t.5-16.5q2-8 9-13.5t17-6.5l217-19 84-200q4-9 12-13.5t16-4.5q8 0 16 4.5t12 13.5l84 200 217 19q10 1 17 6.5t9 13.5q2 8 .5 16.5T826-544L662-401l49 212q2 10-1.5 18T699-158q-7 5-16 5.5t-17-4.5L480-269Zm0-206Z', + 'star_fill': 'M480-269 294-157q-8 5-17 4.5t-16-5.5q-7-5-10.5-13t-1.5-18l49-212-164-143q-8-7-9.5-15.5t.5-16.5q2-8 9-13.5t17-6.5l217-19 84-200q4-9 12-13.5t16-4.5q8 0 16 4.5t12 13.5l84 200 217 19q10 1 17 6.5t9 13.5q2 8 .5 16.5T826-544L662-401l49 212q2 10-1.5 18T699-158q-7 5-16 5.5t-17-4.5L480-269Z', + 'filter_list': 'M430-240q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h100q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H430ZM270-450q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h420q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H270ZM150-660q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h660q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H150Z', + 'sort': 'M150-240q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h180q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H150Zm0-210q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h420q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H150Zm0-210q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h660q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H150Z', + 'menu': 'M150-240q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h660q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H150Zm0-210q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h660q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H150Zm0-210q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h660q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H150Z', + 'chevron_left': 'm406-481 177 177q9 9 8.5 21t-9.5 21q-9 9-21.5 9t-21.5-9L341-460q-5-5-7-10t-2-11q0-6 2-11t7-10l199-199q9-9 21.5-9t21.5 9q9 9 9 21.5t-9 21.5L406-481Z', + 'chevron_right': 'M530-481 353-658q-9-9-8.5-21t9.5-21q9-9 21.5-9t21.5 9l198 198q5 5 7 10t2 11q0 6-2 11t-7 10L396-261q-9 9-21 8.5t-21-9.5q-9-9-9-21.5t9-21.5l176-176Z', + 'arrow_back': 'm274-450 227 227q9 9 9 21t-9 21q-9 9-21 9t-21-9L181-459q-5-5-7-10t-2-11q0-6 2-11t7-10l278-278q9-9 21-9t21 9q9 9 9 21t-9 21L274-510h496q13 0 21.5 8.5T800-480q0 13-8.5 21.5T770-450H274Z', + 'link': 'M280-280q-83 0-141.5-58.5T80-480q0-83 58.5-141.5T280-680h140q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H280q-58.33 0-99.17 40.76-40.83 40.77-40.83 99Q140-422 180.83-381q40.84 41 99.17 41h140q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H280Zm75-170q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h250q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H355Zm185 170q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h140q58.33 0 99.17-40.76 40.83-40.77 40.83-99Q820-538 779.17-579q-40.84-41-99.17-41H540q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h140q83 0 141.5 58.5T880-480q0 83-58.5 141.5T680-280H540Z', + 'history': 'M477-120q-142 0-243.5-95.5T121-451q-1-12 7.5-21t21.5-9q12 0 20.5 8.5T181-451q11 115 95 193t201 78q127 0 215-89t88-216q0-124-89-209.5T477-780q-68 0-127.5 31T246-667h75q13 0 21.5 8.5T351-637q0 13-8.5 21.5T321-607H172q-13 0-21.5-8.5T142-637v-148q0-13 8.5-21.5T172-815q13 0 21.5 8.5T202-785v76q52-61 123.5-96T477-840q75 0 141 28t115.5 76.5Q783-687 811.5-622T840-482q0 75-28.5 141t-78 115Q684-177 618-148.5T477-120Zm34-374 115 113q9 9 9 21.5t-9 21.5q-9 9-21 9t-21-9L460-460q-5-5-7-10.5t-2-11.5v-171q0-13 8.5-21.5T481-683q13 0 21.5 8.5T511-653v159Z', + 'travel_explore': 'M80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q137 0 241.5 80T863-595q4 13-2 24.5T842-556q-12 3-22-4.5T806-580q-22-74-74-131.5T607-799v18q0 35-24 61t-59 26h-87v87q0 17-13.5 28T393-568h-83v88h80q13 0 21.5 8.5T420-450v95h-67L149-559q-5 20-7 39.5t-2 39.5q0 128 82.5 223.5T431-144q12 2 19.5 11.5T458-111q0 13-9 21t-22 6q-148-20-247.5-131.5T80-480Zm749 351L716-241q-21 15-45.5 23t-50.5 8q-71 0-120.5-49.5T450-380q0-71 49.5-120.5T620-550q71 0 120.5 49.5T790-380q0 26-8.5 50.5T759-283l112 112q9 9 9.5 21t-8.5 21q-9 9-21.5 9t-21.5-9ZM698-302q32-32 32-78t-32-78q-32-32-78-32t-78 32q-32 32-32 78t32 78q32 32 78 32t78-32Z', + 'fingerprint': 'M481-779q108 0 203.5 46T843-601q3 5 2.5 8t-3.5 6q-3 3-7.5 3t-8.5-5q-59-82-150.5-126T481-759q-103 0-193 44.5T138-589q-4 5-7.5 6t-7.5-1q-4-2-4-6.5t2-8.5q62-86 157-133t203-47Zm0 96q136 0 233.5 90T812-371q0 46-34 78t-82 32q-49 0-84-32t-35-78q0-39-28.5-65T481-462q-39 0-68 26t-29 65q0 104 63 173.5T604-100q6 2 7.5 5t.5 7q-1 5-4 7t-8 0q-103-26-169.5-103T364-371q0-47 34.5-79t82.5-32q48 0 82.5 32t34.5 79q0 38 29.5 64t68.5 26q38 0 66.5-26t28.5-64q0-123-91.5-206T481-660q-127 0-218.5 83T171-371q0 24 5.5 62.5T200-221q2 5 0 7.5t-5 4.5q-4 2-8.5 1t-6.5-6q-13-38-20.5-77.5T152-371q0-129 98-220.5T481-683Zm0-197q65 0 127.5 16T728-819q5 2 5.5 6t-1.5 7q-2 3-5.5 5t-8.5 0q-55-27-115-42.5T481-859q-62 0-121 14.5T247-801q-5 2-7.5.5T235-805q-2-2-2-6t3-6q57-31 119.5-47T481-880Zm0 298q92 0 158.5 61T706-371q0 5-2.5 7.5T696-361q-5 0-8-2.5t-3-7.5q0-81-60.5-136T481-562q-83 0-142.5 55T279-371q0 85 29.5 145T396-106q4 4 3.5 7.5T396-92q-2 2-6.5 3.5T381-92q-58-60-90.5-126T258-371q0-89 65.5-150T481-582Zm-1 200q5 0 7.5 3t2.5 8q0 81 59.5 133.5T687-185q8 0 19-1t24-3q5-1 8 1.5t4 5.5q1 4-.5 7t-6.5 4q-18 5-31.5 5.5t-16.5.5q-88 0-152.5-58.5T470-371q0-5 2.5-8t7.5-3Z', + 'check': 'm378-332 363-363q9-9 21.5-9t21.5 9q9 9 9 21.5t-9 21.5L399-267q-9 9-21 9t-21-9L175-449q-9-9-8.5-21.5T176-492q9-9 21.5-9t21.5 9l159 160Z', + 'palette': 'M480-80q-82 0-155-31.5t-127.5-86Q143-252 111.5-325T80-480q0-85 32-158t87.5-127q55.5-54 130-84.5T489-880q79 0 150 26.5T763.5-780q53.5 47 85 111.5T880-527q0 108-63 170.5T650-294h-75q-18 0-31 14t-13 31q0 27 14.5 46t14.5 44q0 38-21 58.5T480-80Zm0-400Zm-198 11q15-15 15-35t-15-35q-15-15-35-15t-35 15q-15 15-15 35t15 35q15 15 35 15t35-15Zm126-170q15-15 15-35t-15-35q-15-15-35-15t-35 15q-15 15-15 35t15 35q15 15 35 15t35-15Zm214 0q15-15 15-35t-15-35q-15-15-35-15t-35 15q-15 15-15 35t15 35q15 15 35 15t35-15Zm131 170q15-15 15-35t-15-35q-15-15-35-15t-35 15q-15 15-15 35t15 35q15 15 35 15t35-15ZM480-140q11 0 15.5-4.5T500-159q0-14-14.5-26T471-238q0-46 30-81t76-35h73q76 0 123-44.5T820-527q0-132-100-212.5T489-820q-146 0-247.5 98.5T140-480q0 141 99.5 240.5T480-140Z', + 'queue_play_next': 'M868-230 768-330q-10-9.96-10-22.98t9.97-23.02q9.96-10 23-10Q804-386 814-376l126 125q9 9 9 21t-9 21L814-83q-9.96 10-22.98 10T768-83.18q-10-10.19-10-23.5Q758-120 768-130l100-100ZM360-120q-12.75 0-21.37-8.63Q330-137.25 330-150v-50H140q-24 0-42-18t-18-42v-520q0-24 18-42t42-18h680q24 0 42 18t18 42v267q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82 0-21.32-8.63-8.5-8.62-8.5-21.37v-267H140v520h516q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5h-26v50q0 12.75-8.62 21.37Q612.75-120 600-120H360Zm89-379v100q0 12.75 8.68 21.37 8.67 8.63 21.5 8.63 12.82 0 21.32-8.63 8.5-8.62 8.5-21.37v-100h100q12.75 0 21.38-8.68 8.62-8.67 8.62-21.5 0-12.82-8.62-21.32-8.63-8.5-21.38-8.5H509v-100q0-12.75-8.68-21.38-8.67-8.62-21.5-8.62-12.82 0-21.32 8.62-8.5 8.63-8.5 21.38v100H349q-12.75 0-21.37 8.68-8.63 8.67-8.63 21.5 0 12.82 8.63 21.32 8.62 8.5 21.37 8.5h100ZM140-260v-520 520Z', + 'library_add': 'M561.5-386.63q8.5-8.62 8.5-21.37v-102h102q12.75 0 21.38-8.68 8.62-8.67 8.62-21.5 0-12.82-8.62-21.32-8.63-8.5-21.38-8.5H570v-102q0-12.75-8.68-21.38-8.67-8.62-21.5-8.62-12.82 0-21.32 8.62-8.5 8.63-8.5 21.38v102H408q-12.75 0-21.37 8.68-8.63 8.67-8.63 21.5 0 12.82 8.63 21.32 8.62 8.5 21.37 8.5h102v102q0 12.75 8.68 21.37 8.67 8.63 21.5 8.63 12.82 0 21.32-8.63ZM260-200q-24 0-42-18t-18-42v-560q0-24 18-42t42-18h560q24 0 42 18t18 42v560q0 24-18 42t-42 18H260Zm0-60h560v-560H260v560ZM140-80q-24 0-42-18t-18-42v-590q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v590h590q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32Q742.75-80 730-80H140Zm120-740v560-560Z', + 'folder_open': 'M140-160q-23 0-41.5-18.5T80-220v-520q0-23 18.5-41.5T140-800h256q12.44 0 23.72 5t19.37 13.09L481-740h369q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H455l-60-60H140v520l90-355q5-20 21.83-32.5Q268.65-620 289-620h574q29 0 47.5 23t10.5 52l-88 339q-6 24-22 35t-41 11H140Zm63-60h572l84-340H287l-84 340Zm-63-353v-167 167Zm63 353 84-340-84 340Z', + 'album_fill': 'M480-316q70 0 120-47.5T650-480q0-71-49.5-120.5T480-650q-69 0-116.5 50T316-480q0 69 47.5 116.5T480-316Zm-28.5-135.5Q440-463 440-480t11.5-28.5Q463-520 480-520t28.5 11.5Q520-497 520-480t-11.5 28.5Q497-440 480-440t-28.5-11.5ZM480-80q-82 0-155-31.5t-127.5-86Q143-252 111.5-325T80-480q0-83 31.5-156t86-127Q252-817 325-848.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 82-31.5 155T763-197.5q-54 54.5-127 86T480-80Z', + 'podcasts': 'M450-110v-296q-22-9-36-29t-14-45q0-33 23.5-56.5T480-560q33 0 56.5 23.5T560-480q0 25-14 45t-36 29v296q0 13-8.5 21.5T480-80q-13 0-21.5-8.5T450-110ZM226-212q-9 9-22.5 9T182-213q-48-54-75-121.5T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 78-27 145.5T778-213q-8 10-21.5 10.5T734-211q-9-9-8-22t10-23q40-45 62-102t22-122q0-142-99-241t-241-99q-142 0-241 99t-99 241q0 65 22 122t62 102q9 10 10 22.5t-8 21.5Zm113-113q-9 9-22 9t-21-10q-26-32-41-70.5T240-480q0-100 70-170t170-70q100 0 170 70t70 170q0 45-15 83.5T664-326q-8 10-20.5 10.5T622-324q-9-9-9-22t8-23q18-23 28.5-51t10.5-60q0-75-52.5-127.5T480-660q-75 0-127.5 52.5T300-480q0 32 10.5 60t28.5 51q8 10 8.5 22.5T339-325Z', + 'content_copy': 'M300-200q-24 0-42-18t-18-42v-560q0-24 18-42t42-18h440q24 0 42 18t18 42v560q0 24-18 42t-42 18H300Zm0-60h440v-560H300v560ZM180-80q-24 0-42-18t-18-42v-590q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v590h470q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32Q662.75-80 650-80H180Zm120-180v-560 560Z', + 'drag_indicator': 'M349.91-160q-28.91 0-49.41-20.59-20.5-20.59-20.5-49.5t20.59-49.41q20.59-20.5 49.5-20.5t49.41 20.59q20.5 20.59 20.5 49.5t-20.59 49.41q-20.59 20.5-49.5 20.5Zm260 0q-28.91 0-49.41-20.59-20.5-20.59-20.5-49.5t20.59-49.41q20.59-20.5 49.5-20.5t49.41 20.59q20.5 20.59 20.5 49.5t-20.59 49.41q-20.59 20.5-49.5 20.5Zm-260-250q-28.91 0-49.41-20.59-20.5-20.59-20.5-49.5t20.59-49.41q20.59-20.5 49.5-20.5t49.41 20.59q20.5 20.59 20.5 49.5t-20.59 49.41q-20.59 20.5-49.5 20.5Zm260 0q-28.91 0-49.41-20.59-20.5-20.59-20.5-49.5t20.59-49.41q20.59-20.5 49.5-20.5t49.41 20.59q20.5 20.59 20.5 49.5t-20.59 49.41q-20.59 20.5-49.5 20.5Zm-260-250q-28.91 0-49.41-20.59-20.5-20.59-20.5-49.5t20.59-49.41q20.59-20.5 49.5-20.5t49.41 20.59q20.5 20.59 20.5 49.5t-20.59 49.41q-20.59 20.5-49.5 20.5Zm260 0q-28.91 0-49.41-20.59-20.5-20.59-20.5-49.5t20.59-49.41q20.59-20.5 49.5-20.5t49.41 20.59q20.5 20.59 20.5 49.5t-20.59 49.41q-20.59 20.5-49.5 20.5Z', + 'stop_circle': 'M360-330h240q12.75 0 21.38-8.63Q630-347.25 630-360v-240q0-12.75-8.62-21.38Q612.75-630 600-630H360q-12.75 0-21.37 8.62Q330-612.75 330-600v240q0 12.75 8.63 21.37Q347.25-330 360-330ZM480.27-80q-82.74 0-155.5-31.5Q252-143 197.5-197.5t-86-127.34Q80-397.68 80-480.5t31.5-155.66Q143-709 197.5-763t127.34-85.5Q397.68-880 480.5-880t155.66 31.5Q709-817 763-763t85.5 127Q880-563 880-480.27q0 82.74-31.5 155.5Q817-252 763-197.68q-54 54.31-127 86Q563-80 480.27-80Zm.23-60Q622-140 721-239.5t99-241Q820-622 721.19-721T480-820q-141 0-240.5 98.81T140-480q0 141 99.5 240.5t241 99.5Zm-.5-340Z', + 'fiber_manual_record': 'M478-478ZM281.5-281.5Q200-363 200-480t81.5-198.5Q363-760 480-760t198.5 81.5Q760-597 760-480t-81.5 198.5Q597-200 480-200t-198.5-81.5ZM636-324q64-64 64-156t-64-156q-64-64-156-64t-156 64q-64 64-64 156t64 156q64 64 156 64t156-64Z', + 'lists': 'M399-160q-36 0-61-25.58t-25-61.5Q313-283 338-308t61-25h395q36 0 61 25t25 60.92q0 35.92-25 61.5T794-160H399Zm1-233q-35.89 0-61.44-25.58Q313-444.16 313-480.08t25.56-61.42Q364.11-567 400-567h393q35.89 0 61.44 25.58Q880-515.84 880-479.92t-25.56 61.42Q828.89-393 793-393H400Zm-1-234q-36 0-61-25.58t-25-61.5Q313-750 338-775t61-25h395q36 0 61 25t25 60.92q0 35.92-25 61.5T794-627H399Zm-293.42-25.58Q80-678.16 80-714.08T105.58-775q25.58-25 61.5-25T228-775q25 25 25 60.92t-25 61.5Q203-627 167.08-627t-61.5-25.58ZM166.92-393q-35.92 0-61.42-25.58T80-480.08q0-35.92 25.58-61.42t61.5-25.5q35.92 0 61.42 25.58t25.5 61.5q0 35.92-25.58 61.42t-61.5 25.5Zm.16 233q-35.92 0-61.5-25.58T80-247.08Q80-283 105.58-308t61.5-25Q203-333 228-308t25 60.92q0 35.92-25 61.5T167.08-160Z', + 'art_track': 'M100-200q-24 0-42-18t-18-42v-440q0-24 18-42t42-18h440q24 0 42 18t18 42v440q0 24-18 42t-42 18H100Zm0-60h440v-440H100v440Zm196-120-48-66q-5-6-12-6t-12 6l-50 65q-6 8-1.32 16t13.32 8h265q8.5 0 12.75-8t-.75-16l-70-93q-5-6-12-6t-12 6l-73 94Zm412.5 171.37Q700-217.25 700-230v-500q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v500q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82 0-21.32-8.63Zm160 0Q860-217.25 860-230v-500q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v500q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82 0-21.32-8.63ZM100-260v-440 440Z', + 'expand_more': 'M469-358q-5-2-10-7L261-563q-9-9-8.5-21.5T262-606q9-9 21.5-9t21.5 9l175 176 176-176q9-9 21-8.5t21 9.5q9 9 9 21.5t-9 21.5L501-365q-5 5-10 7t-11 2q-6 0-11-2Z', + 'expand_less': 'M480-554 304-378q-9 9-21 8.5t-21-9.5q-9-9-9-21.5t9-21.5l197-197q9-9 21-9t21 9l198 198q9 9 9 21t-9 21q-9 9-21.5 9t-21.5-9L480-554Z', + 'auto_awesome': 'M550-590q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h100v-160q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v160h100q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H550Zm108.5 461.37Q650-137.25 650-150v-350q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v350q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82 0-21.32-8.63Zm-400 0Q250-137.25 250-150v-150H150q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h260q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H310v150q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82 0-21.32-8.63Zm0-300Q250-437.25 250-450v-360q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v360q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82 0-21.32-8.63Z', + 'artist': 'M616-189q-29-29-29-76t29-76q29-29 76-29 17 0 31 4t25 12v-176q0-12.75 8.63-21.38Q765.25-560 778-560h72q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5h-53v235q0 47-29 76t-76 29q-47 0-76-29Zm-506 29q-12.75 0-21.37-8.63Q80-177.25 80-190v-64q0-32 17-61.5t51-44.5q75-33 133.39-46.5Q339.78-420 400-420q35 0 68.5 4.5T537-402q16 5 21 15.38t3 21.5Q559-354 550-347q-9 7-22 3-29-8-61.21-12-32.22-4-66.79-4-58 0-109 11t-119 43q-16 8-24 22.5t-8 29.5v34h372q15 0 22.5 9.32t7.5 20.5q0 11.18-7.75 20.68T511-160H110Zm182-363q-42-42-42-108t42-108q42-42 108-42t108 42q42 42 42 108t-42 108q-42 42-108 42t-108-42Zm172.5-43.5Q490-592 490-631t-25.5-64.5Q439-721 400-721t-64.5 25.5Q310-670 310-631t25.5 64.5Q361-541 400-541t64.5-25.5ZM400-631Zm0 411Z', + 'scrobble': 'm450-478-62 62q-9 9-21.1 9-12.1 0-20.9-9-9-9-9-21.5t9-21.5l113-114q9-9 21-9t21 9l114 114q9 9 9 21t-9 21q-9 9-21.5 9t-21.5-9l-62-61v258h241q45 0 77-32t32-77q0-45-32-77t-77-32h-63v-84q0-89-60.5-153T478-739q-89 0-150 64t-61 153h-19q-62 0-105 43.5T100-371q0 62 43.93 106.5T250-220h110q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H250q-86 0-148-62T40-370q0-78 49.5-137.5T217-579q20-97 94-158.5T482-799q113 0 189.5 81.5T748-522v24q72-2 122 46.5T920-329q0 69-50 119t-119 50H510q-24 0-42-18t-18-42v-258Zm30 28Z', + 'label': 'M140-160q-24.75 0-42.37-17.63Q80-195.25 80-220v-520q0-24.75 17.63-42.38Q115.25-800 140-800h471q14.25 0 27 6.37 12.75 6.38 21 17.63l195 260q12 15.68 12 35.84Q866-460 854-444L660-184q-8.25 11.25-21 17.62-12.75 6.38-27 6.38H140Zm0-60h471l195-260-195-260H140v520Zm333-260Z', + 'text_snippet': 'M180-180h600v-375L555-780H180v600Zm0 60q-24.75 0-42.37-17.63Q120-155.25 120-180v-600q0-24.75 17.63-42.38Q155.25-840 180-840h375q12.44 0 23.72 5T598-822l224 224q8 8 13 19.28 5 11.28 5 23.72v375q0 24.75-17.62 42.37Q804.75-120 780-120H180Zm129-171h342q12.75 0 21.38-8.68 8.62-8.67 8.62-21.5 0-12.82-8.62-21.32-8.63-8.5-21.38-8.5H309q-12.75 0-21.37 8.68-8.63 8.67-8.63 21.5 0 12.82 8.63 21.32 8.62 8.5 21.37 8.5Zm0-159h342q12.75 0 21.38-8.68 8.62-8.67 8.62-21.5 0-12.82-8.62-21.32-8.63-8.5-21.38-8.5H309q-12.75 0-21.37 8.68-8.63 8.67-8.63 21.5 0 12.82 8.63 21.32 8.62 8.5 21.37 8.5Zm0-159h216q12.75 0 21.38-8.68 8.62-8.67 8.62-21.5 0-12.82-8.62-21.32-8.63-8.5-21.38-8.5H309q-12.75 0-21.37 8.68-8.63 8.67-8.63 21.5 0 12.82 8.63 21.32 8.62 8.5 21.37 8.5ZM180-180v-600 600Z', + 'dark': 'M480-120q-150 0-255-105T120-480q0-135 79.5-229T408-830q20-5 34-1t22 15q8 10 7.5 25t-8.5 35q-9 23-14 47t-5 49q0 90 63 153t153 63q25 0 48.5-4.5T754-461q22-8 38-7t26 9q10 8 13 23t-2 36q-27 121-121 200.5T480-120Zm0-60q109 0 190-67.5T771-406q-25 11-53.5 16.5T660-384q-115 0-195.5-80.5T384-660q0-24 5-51.5t18-62.5q-98 27-162.5 109.5T180-480q0 125 87.5 212.5T480-180Zm-4-297Z', + 'light': 'M579-380.76q41-40.77 41-99Q620-538 579.24-579q-40.77-41-99-41Q422-620 381-579.24q-41 40.77-41 99Q340-422 380.76-381q40.77 41 99 41Q538-340 579-380.76ZM338.5-338.5Q280-397 280-480t58.5-141.5Q397-680 480-680t141.5 58.5Q680-563 680-480t-58.5 141.5Q563-280 480-280t-141.5-58.5ZM70-450q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32Q57.25-510 70-510h100q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H70Zm720 0q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h100q12.75 0 21.38 8.68 8.62 8.67 8.62 21.5 0 12.82-8.62 21.32-8.63 8.5-21.38 8.5H790ZM458.5-768.63Q450-777.25 450-790v-100q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v100q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82 0-21.32-8.63Zm0 720Q450-57.25 450-70v-100q0-12.75 8.68-21.38 8.67-8.62 21.5-8.62 12.82 0 21.32 8.62 8.5 8.63 8.5 21.38v100q0 12.75-8.68 21.37-8.67 8.63-21.5 8.63-12.82 0-21.32-8.63ZM240-678l-57-56q-9-9-8.63-21.6.37-12.61 8.53-21.5 8.89-8.9 21.5-8.9 12.6 0 21.6 9l56 57q8 9 8 21t-8 20.5q-8 8.5-20.5 8.5t-21.5-8Zm494 495-56-57q-8-9-8-21.38 0-12.37 8.5-20.62 8.5-9 20.5-9t21 9l57 56q9 9 8.63 21.6-.37 12.61-8.53 21.5-8.89 8.9-21.5 8.9-12.6 0-21.6-9Zm-56-495q-9-9-9-21t9-21l56-57q9-9 21.6-8.63 12.61.37 21.5 8.53 8.9 8.89 8.9 21.5 0 12.6-9 21.6l-57 56q-8 8-20.36 8-12.37 0-21.64-8ZM182.9-182.9q-8.9-8.89-8.9-21.5 0-12.6 9-21.6l57-56q8.8-9 20.9-9 12.1 0 20.71 9 9.39 9 9.39 21t-9 21l-56 57q-9 9-21.6 8.63-12.61-.37-21.5-8.53ZM480-480Z', + 'visibility': 'M600.5-379.62q49.5-49.62 49.5-120.5T600.38-620.5Q550.76-670 479.88-670T359.5-620.38Q310-570.76 310-499.88t49.62 120.38q49.62 49.5 120.5 49.5t120.38-49.62Zm-200-41.12q-32.5-32.73-32.5-79.5 0-46.76 32.74-79.26 32.73-32.5 79.5-32.5 46.76 0 79.26 32.74 32.5 32.73 32.5 79.5 0 46.76-32.74 79.26-32.73 32.5-79.5 32.5-46.76 0-79.26-32.74ZM234.5-276Q124-352 57-470q-4-7.13-6-14.65-2-7.52-2-15.43 0-7.92 2-15.38 2-7.47 6-14.54 67-118 177.5-194T480-800q135 0 245.5 76T903-530q4 7.12 6 14.65 2 7.52 2 15.43 0 7.92-2 15.38-2 7.47-6 14.54-67 118-177.5 194T480-200q-135 0-245.5-76ZM480-500Zm222.5 174.5Q804-391 857-500q-53-109-154.33-174.5Q601.34-740 480.17-740T257.5-674.5Q156-609 102-500q54 109 155.33 174.5Q358.66-260 479.83-260t222.67-65.5Z', + 'trending_up': 'M102-252q-9-9-9-21.5t9-21.5l228-227q16.93-17 41.97-17Q397-539 414-522l125 125 241-241h-97q-12.75 0-21.37-8.68-8.63-8.67-8.63-21.5 0-12.82 8.63-21.32 8.62-8.5 21.37-8.5h167q12.75 0 21.38 8.62Q880-680.75 880-668v167q0 12-8.27 21t-20.5 9Q839-471 830-480t-9-21v-93L580-354q-16.93 17-41.97 17Q513-337 496-354L371-478 145-252q-9 9-21.5 9t-21.5-9Z', + 'skip_next': 'M680-270v-420q0-13 8.5-21.5T710-720q13 0 21.5 8.5T740-690v420q0 13-8.5 21.5T710-240q-13 0-21.5-8.5T680-270Zm-460-27v-366q0-14 9-22t21-8q5 0 9 1.5t8 4.5l263 182q7 5 10 11.5t3 13.5q0 7-3 13.5T530-455L267-273q-4 3-8 4.5t-9 1.5q-12 0-21-8t-9-22Zm60-183Zm0 125 181-125-181-125v250Z', + 'my_location': 'M450-72v-45q-137-14-228-105T117-450H72q-13 0-21.5-8.5T42-480q0-13 8.5-21.5T72-510h45q14-137 105-228t228-105v-45q0-13 8.5-21.5T480-918q13 0 21.5 8.5T510-888v45q137 14 228 105t105 228h45q13 0 21.5 8.5T918-480q0 13-8.5 21.5T888-450h-45q-14 137-105 228T510-117v45q0 13-8.5 21.5T480-42q-13 0-21.5-8.5T450-72Zm244.5-193.5Q784-355 784-480t-89.5-214.5Q605-784 480-784t-214.5 89.5Q176-605 176-480t89.5 214.5Q355-176 480-176t214.5-89.5Zm-321-108Q330-417 330-480t43.5-106.5Q417-630 480-630t106.5 43.5Q630-543 630-480t-43.5 106.5Q543-330 480-330t-106.5-43.5ZM544-416q26-26 26-64t-26-64q-26-26-64-26t-64 26q-26 26-26 64t26 64q26 26 64 26t64-26Zm-64-64Z', + 'play_arrow': 'M320-258v-450q0-14 9-22t21-8q4 0 8 1t8 3l354 226q7 5 10.5 11t3.5 14q0 8-3.5 14T720-458L366-232q-4 2-8 3t-8 1q-12 0-21-8t-9-22Zm60-225Zm0 171 269-171-269-171v342Z', +} diff --git a/mulberry/icons.py b/mulberry/icons.py new file mode 100644 index 0000000..ab0a3c2 --- /dev/null +++ b/mulberry/icons.py @@ -0,0 +1,86 @@ +"""Theme-aware Material Symbols icons. + +Icons are rendered from SVG path data at paint time using the *current* theme +colour for their role, so they recolour automatically when KDE colours change. +""" +from __future__ import annotations + +from PyQt6.QtCore import QByteArray, QRectF, QSize, Qt +from PyQt6.QtGui import QColor, QIcon, QIconEngine, QPainter, QPixmap +from PyQt6.QtSvg import QSvgRenderer + +from . import theme as T +from .icondata import PATHS + +_renderers: dict[str, QSvgRenderer] = {} + + +def _renderer(name: str, color: QColor) -> QSvgRenderer: + key = f"{name}:{color.name(QColor.NameFormat.HexArgb)}" + r = _renderers.get(key) + if r is None: + d = PATHS.get(name) or PATHS["music_note"] + op = color.alphaF() + svg = (f'' + f'') + r = QSvgRenderer(QByteArray(svg.encode())) + if len(_renderers) > 600: + _renderers.clear() + _renderers[key] = r + return r + + +def paint_icon(p: QPainter, rect: QRectF, name: str, color: QColor): + _renderer(name, color).render(p, QRectF(rect)) + + +def role_color(role: str | QColor) -> QColor: + if isinstance(role, QColor): + return role + if T.theme is None: + return QColor("#cccccc") + return T.theme.c.get(role, T.theme.c["onSurface"]) + + +class MaterialIconEngine(QIconEngine): + def __init__(self, name: str, role: str | QColor = "onSurfaceVariant", + checked_name: str | None = None, checked_role: str | QColor | None = None): + super().__init__() + self.name, self.role = name, role + self.checked_name = checked_name + self.checked_role = checked_role + + def paint(self, p: QPainter, rect, mode, state): + on = state == QIcon.State.On + name = self.checked_name if (on and self.checked_name) else self.name + col = QColor(role_color(self.checked_role if (on and self.checked_role) else self.role)) + if mode == QIcon.Mode.Disabled: + col.setAlphaF(0.38) + elif mode == QIcon.Mode.Selected and T.theme is not None: + col = QColor(T.theme.c["onSecondaryContainer"]) + p.save() + p.setRenderHint(QPainter.RenderHint.Antialiasing) + paint_icon(p, QRectF(rect), name, col) + p.restore() + + def pixmap(self, size: QSize, mode, state): + pm = QPixmap(size) + pm.fill(Qt.GlobalColor.transparent) + p = QPainter(pm) + self.paint(p, pm.rect(), mode, state) + p.end() + return pm + + def scaledPixmap(self, size, mode, state, scale): + s = QSize(int(size.width() * scale), int(size.height() * scale)) + pm = self.pixmap(s, mode, state) + pm.setDevicePixelRatio(scale) + return pm + + def clone(self): + return MaterialIconEngine(self.name, self.role, self.checked_name, self.checked_role) + + +def icon(name: str, role: str | QColor = "onSurfaceVariant", checked: str | None = None, + checked_role: str | QColor | None = None) -> QIcon: + return QIcon(MaterialIconEngine(name, role, checked, checked_role)) diff --git a/mulberry/lastfm_app.py b/mulberry/lastfm_app.py new file mode 100644 index 0000000..5eecd5e --- /dev/null +++ b/mulberry/lastfm_app.py @@ -0,0 +1,13 @@ +"""Application-wide Last.fm API credentials. + +Last.fm gives every *application* its own API key. If you register Mulberry once +at https://www.last.fm/api/account/create (any name/description, callback URL can +be left empty) and paste the key + shared secret below, the "Log in with +Last.fm" button works for every user without them touching keys. + +They can also be supplied without editing code via the environment variables +MULBERRY_LASTFM_KEY / MULBERRY_LASTFM_SECRET or the file +~/.config/mulberry/lastfm_app.json -> {"key": "...", "secret": "..."} +""" +API_KEY = "" +API_SECRET = "" diff --git a/mulberry/library.py b/mulberry/library.py new file mode 100644 index 0000000..024c4d3 --- /dev/null +++ b/mulberry/library.py @@ -0,0 +1,430 @@ +"""SQLite-backed music collection with an incremental background scanner.""" +from __future__ import annotations + +import json +import os +import sqlite3 +import threading +import time +from pathlib import Path + +from PyQt6.QtCore import QObject, QThread, pyqtSignal + +from .config import AUDIO_EXTS, DB_PATH, settings +from .song import Song +from . import tags as T + +SONG_COLS = ("url title artist album albumartist genre composer comment year track disc length " + "bitrate samplerate bitdepth channels filetype filesize mtime art playcount skipcount " + "lastplayed rating added rg_track rg_album mb_trackid mb_albumid").split() + +SCHEMA = f""" +CREATE TABLE IF NOT EXISTS songs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + url TEXT UNIQUE NOT NULL, title TEXT, artist TEXT, album TEXT, albumartist TEXT, + genre TEXT, composer TEXT, comment TEXT, year INTEGER, track INTEGER, disc INTEGER, + length REAL, bitrate INTEGER, samplerate INTEGER, bitdepth INTEGER, channels INTEGER, + filetype TEXT, filesize INTEGER, mtime REAL, art TEXT, playcount INTEGER DEFAULT 0, + skipcount INTEGER DEFAULT 0, lastplayed INTEGER DEFAULT 0, rating INTEGER DEFAULT 0, + added INTEGER, rg_track REAL, rg_album REAL, mb_trackid TEXT, mb_albumid TEXT, + unavailable INTEGER DEFAULT 0 +); +CREATE INDEX IF NOT EXISTS idx_songs_aa ON songs(albumartist, album); +CREATE INDEX IF NOT EXISTS idx_songs_artist ON songs(artist); +CREATE INDEX IF NOT EXISTS idx_songs_genre ON songs(genre); +CREATE TABLE IF NOT EXISTS playlists ( + id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, ui_order INTEGER DEFAULT 0, + is_open INTEGER DEFAULT 1, favorite INTEGER DEFAULT 0, current INTEGER DEFAULT -1, + items TEXT DEFAULT '[]' +); +CREATE TABLE IF NOT EXISTS lyrics (key TEXT PRIMARY KEY, text TEXT, source TEXT, fetched INTEGER); +CREATE TABLE IF NOT EXISTS radio (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, url TEXT, ui_order INTEGER DEFAULT 0); +CREATE TABLE IF NOT EXISTS kv (k TEXT PRIMARY KEY, v TEXT); +""" + +DEFAULT_RADIO = [ + ("SomaFM · Groove Salad", "https://ice1.somafm.com/groovesalad-128-mp3"), + ("SomaFM · Drone Zone", "https://ice1.somafm.com/dronezone-128-mp3"), + ("SomaFM · Indie Pop Rocks", "https://ice1.somafm.com/indiepop-128-mp3"), + ("SomaFM · Metal Detector", "https://ice1.somafm.com/metal-128-mp3"), + ("Radio Paradise · Main Mix", "https://stream.radioparadise.com/aac-320"), + ("Radio Paradise · Rock Mix", "https://stream.radioparadise.com/rock-320"), + ("KEXP 90.3 Seattle", "https://kexp.streamguys1.com/kexp160.aac"), +] + + +def connect() -> sqlite3.Connection: + con = sqlite3.connect(str(DB_PATH), timeout=30, check_same_thread=False) + con.row_factory = sqlite3.Row + con.execute("PRAGMA journal_mode=WAL") + con.execute("PRAGMA synchronous=NORMAL") + con.execute("PRAGMA temp_store=MEMORY") + return con + + +def row_to_song(r: sqlite3.Row) -> Song: + d = {k: r[k] for k in r.keys() if k in SONG_COLS or k == "id"} + for k, v in list(d.items()): + if v is None and k not in ("rg_track", "rg_album"): + d[k] = "" if k in ("title", "artist", "album", "albumartist", "genre", "composer", + "comment", "filetype", "art", "mb_trackid", "mb_albumid") else 0 + return Song.from_dict(d) + + +class Library(QObject): + changed = pyqtSignal() + scan_progress = pyqtSignal(int, int, str) # done, total, current + scan_finished = pyqtSignal(int, int, int) # added, updated, removed + song_updated = pyqtSignal(object) + + def __init__(self): + super().__init__() + self.con = connect() + self.lock = threading.RLock() + with self.lock: + self.con.executescript(SCHEMA) + if not self.con.execute("SELECT 1 FROM radio LIMIT 1").fetchone(): + if not self.kv("radio_seeded"): + self.con.executemany("INSERT INTO radio(name,url,ui_order) VALUES (?,?,?)", + [(n, u, i) for i, (n, u) in enumerate(DEFAULT_RADIO)]) + self.set_kv("radio_seeded", "1") + self.con.commit() + self._scanner: Scanner | None = None + + # ------------------------------------------------------------ kv + def kv(self, k, default=None): + r = self.con.execute("SELECT v FROM kv WHERE k=?", (k,)).fetchone() + return r[0] if r else default + + def set_kv(self, k, v): + with self.lock: + self.con.execute("INSERT OR REPLACE INTO kv(k,v) VALUES (?,?)", (k, str(v))) + self.con.commit() + + # ------------------------------------------------------------ queries + def query(self, sql, args=()): + with self.lock: + return self.con.execute(sql, args).fetchall() + + def count(self) -> tuple[int, float]: + r = self.query("SELECT COUNT(*), COALESCE(SUM(length),0) FROM songs WHERE unavailable=0")[0] + return r[0], r[1] + + def songs_where(self, where="1", args=(), order="albumartist COLLATE NOCASE, album COLLATE NOCASE, disc, track, title"): + rows = self.query(f"SELECT * FROM songs WHERE unavailable=0 AND ({where}) ORDER BY {order}", args) + return [row_to_song(r) for r in rows] + + def song_by_url(self, url: str) -> Song | None: + r = self.query("SELECT * FROM songs WHERE url=?", (url,)) + return row_to_song(r[0]) if r else None + + def filter_clause(self, text: str): + """Build WHERE for a search string. Supports field:value tokens.""" + text = (text or "").strip() + if not text: + return "1", () + clauses, args = [], [] + fields_map = {"artist": "artist", "album": "album", "title": "title", "genre": "genre", + "year": "year", "albumartist": "albumartist", "composer": "composer", + "type": "filetype", "rating": "rating"} + for tok in text.split(): + if ":" in tok: + f, v = tok.split(":", 1) + if f.lower() in fields_map and v: + col = fields_map[f.lower()] + if col in ("year", "rating"): + op = ">=" if v.startswith(">") else "<=" if v.startswith("<") else "=" + clauses.append(f"{col} {op} ?") + args.append(int(v.lstrip("<>=") or 0)) + else: + clauses.append(f"{col} LIKE ?") + args.append(f"%{v}%") + continue + clauses.append("(title LIKE ? OR artist LIKE ? OR album LIKE ? OR albumartist LIKE ? OR genre LIKE ? OR composer LIKE ?)") + args += [f"%{tok}%"] * 6 + return " AND ".join(clauses), tuple(args) + + # ------------------------------------------------------------ updates + def update_fields(self, song_id: int, **vals): + if song_id < 0 or not vals: + return + cols = ", ".join(f"{k}=?" for k in vals) + with self.lock: + self.con.execute(f"UPDATE songs SET {cols} WHERE id=?", (*vals.values(), song_id)) + self.con.commit() + + def mark_played(self, song: Song): + if song.id < 0: + return + now = int(time.time()) + with self.lock: + self.con.execute("UPDATE songs SET playcount=playcount+1, lastplayed=? WHERE id=?", (now, song.id)) + self.con.commit() + song.playcount += 1 + song.lastplayed = now + + def mark_skipped(self, song: Song): + if song.id < 0: + return + with self.lock: + self.con.execute("UPDATE songs SET skipcount=skipcount+1 WHERE id=?", (song.id,)) + self.con.commit() + song.skipcount += 1 + + def set_rating(self, song: Song, rating: int): + song.rating = rating + self.update_fields(song.id, rating=rating) + self.song_updated.emit(song) + + def reread(self, path: str) -> Song | None: + """Re-read tags for one file after editing and persist.""" + s = T.read_song(path) + if s is None: + return None + old = self.song_by_url(path) + if old: + s.id, s.playcount, s.skipcount, s.lastplayed, s.rating, s.added = ( + old.id, old.playcount, old.skipcount, old.lastplayed, old.rating, old.added) + s.art = old.art + self._upsert(self.con, s) + self.con.commit() + self.song_updated.emit(s) + self.changed.emit() + return s + + def set_album_art(self, artist: str, album: str, art_path: str): + with self.lock: + self.con.execute("UPDATE songs SET art=? WHERE (albumartist=? OR (albumartist='' AND artist=?)) AND album=?", + (art_path, artist, artist, album)) + self.con.commit() + self.changed.emit() + + @staticmethod + def _upsert(con, s: Song): + d = s.to_dict() + vals = [getattr(s, c) for c in SONG_COLS] + if s.id >= 0: + con.execute(f"UPDATE songs SET {', '.join(c + '=?' for c in SONG_COLS)}, unavailable=0 WHERE id=?", + (*vals, s.id)) + else: + con.execute(f"INSERT OR REPLACE INTO songs({', '.join(SONG_COLS)}) VALUES ({', '.join('?' * len(SONG_COLS))})", + vals) + return d + + # ------------------------------------------------------------ lyrics cache + def get_lyrics(self, key: str): + r = self.query("SELECT text, source FROM lyrics WHERE key=?", (key,)) + return (r[0][0], r[0][1]) if r else (None, None) + + def put_lyrics(self, key: str, text: str, source: str): + with self.lock: + self.con.execute("INSERT OR REPLACE INTO lyrics(key,text,source,fetched) VALUES (?,?,?,?)", + (key, text, source, int(time.time()))) + self.con.commit() + + # ------------------------------------------------------------ playlists + def load_playlists(self): + return self.query("SELECT * FROM playlists ORDER BY ui_order, id") + + def save_playlist(self, pid: int | None, name: str, songs: list[Song], ui_order=0, is_open=1, + current=-1, favorite=0) -> int: + items = json.dumps([s.to_dict() for s in songs], separators=(",", ":")) + with self.lock: + if pid is None or pid < 0: + cur = self.con.execute("INSERT INTO playlists(name,ui_order,is_open,favorite,current,items) VALUES (?,?,?,?,?,?)", + (name, ui_order, is_open, favorite, current, items)) + pid = cur.lastrowid + else: + self.con.execute("UPDATE playlists SET name=?, ui_order=?, is_open=?, favorite=?, current=?, items=? WHERE id=?", + (name, ui_order, is_open, favorite, current, items, pid)) + self.con.commit() + return pid + + def update_playlist_meta(self, pid: int, name: str, ui_order: int, current: int, favorite: int): + with self.lock: + self.con.execute("UPDATE playlists SET name=?, ui_order=?, current=?, favorite=?, is_open=1 WHERE id=?", + (name, ui_order, current, favorite, pid)) + self.con.commit() + + def delete_playlist(self, pid: int): + with self.lock: + self.con.execute("DELETE FROM playlists WHERE id=?", (pid,)) + self.con.commit() + + # ------------------------------------------------------------ radio + def radios(self): + return self.query("SELECT * FROM radio ORDER BY ui_order, id") + + def add_radio(self, name, url): + with self.lock: + self.con.execute("INSERT INTO radio(name,url,ui_order) VALUES (?,?,999)", (name, url)) + self.con.commit() + + def remove_radio(self, rid): + with self.lock: + self.con.execute("DELETE FROM radio WHERE id=?", (rid,)) + self.con.commit() + + # ------------------------------------------------------------ scanning + def scan(self, full=False): + if self._scanner and self._scanner.isRunning(): + return + folders = [f for f in settings.get("library/folders") if f] + self._scanner = Scanner(folders, full) + self._scanner.progress.connect(self.scan_progress) + self._scanner.finished_scan.connect(self._scan_done) + self._scanner.start(QThread.Priority.LowPriority) + + def scanning(self) -> bool: + return bool(self._scanner and self._scanner.isRunning()) + + def stop_scan(self): + if self._scanner: + self._scanner.abort = True + self._scanner.wait(3000) + + def _scan_done(self, a, u, r): + self.scan_finished.emit(a, u, r) + self.changed.emit() + + +class Scanner(QThread): + progress = pyqtSignal(int, int, str) + finished_scan = pyqtSignal(int, int, int) + + def __init__(self, folders, full): + super().__init__() + self.folders, self.full, self.abort = folders, full, False + + def run(self): + con = connect() + known = {r["url"]: (r["id"], r["mtime"], r["art"]) for r in + con.execute("SELECT id,url,mtime,art FROM songs")} + files = [] + for folder in self.folders: + for root, dirs, fnames in os.walk(folder, followlinks=True): + if self.abort: + return + dirs[:] = [d for d in dirs if not d.startswith(".")] + for fn in fnames: + if fn.rsplit(".", 1)[-1].lower() in AUDIO_EXTS: + files.append(os.path.join(root, fn)) + seen = set(files) + added = updated = 0 + total = len(files) + art_cache: dict[str, str] = {} + dir_cover: dict[str, str | None] = {} + now = int(time.time()) + batch = 0 + for i, path in enumerate(files): + if self.abort: + break + try: + mtime = os.stat(path).st_mtime + except OSError: + continue + prev = known.get(path) + if prev and not self.full and abs((prev[1] or 0) - mtime) < 1: + continue + if i % 25 == 0: + self.progress.emit(i, total, path) + s = T.read_song(path) + if s is None: + continue + d = os.path.dirname(path) + key = T.album_key(s.effective_albumartist(), s.album, d) + if key in art_cache: + s.art = art_cache[key] + else: + art = "" + if d not in dir_cover: + dir_cover[d] = T.find_folder_cover(d) + src = dir_cover[d] + data = None if src else T.extract_embedded_cover(path) + if src or data: + art = T.store_cover(src or data, key) or "" + art_cache[key] = art + s.art = art + if prev: + s.id = prev[0] + cols = [c for c in SONG_COLS if c not in ("playcount", "skipcount", "lastplayed", "rating", "added")] + con.execute(f"UPDATE songs SET {', '.join(c + '=?' for c in cols)}, unavailable=0 WHERE id=?", + (*[getattr(s, c) for c in cols], s.id)) + updated += 1 + else: + s.added = now + con.execute(f"INSERT INTO songs({', '.join(SONG_COLS)}) VALUES ({', '.join('?' * len(SONG_COLS))})", + [getattr(s, c) for c in SONG_COLS]) + added += 1 + batch += 1 + if batch >= 200: + con.commit() + batch = 0 + con.commit() + removed = 0 + if not self.abort: + in_folders = lambda u: any(u.startswith(f.rstrip("/") + "/") for f in self.folders) # noqa: E731 + gone = [(u,) for u in known if u not in seen] + # songs outside configured folders get removed, missing ones too + if gone: + con.executemany("DELETE FROM songs WHERE url=?", gone) + removed = len(gone) + con.commit() + _ = in_folders + self.progress.emit(total, total, "") + con.close() + self.finished_scan.emit(added, updated, removed) + + +library: Library | None = None + + +def init_library() -> Library: + global library + library = Library() + return library + + +def scan_paths(paths: list[str]) -> list[Song]: + """Expand files/dirs to songs (used for drops & 'open'), using DB if known.""" + out: list[Song] = [] + files: list[str] = [] + for p in paths: + if os.path.isdir(p): + for root, dirs, fns in os.walk(p): + dirs.sort() + for fn in sorted(fns): + if fn.rsplit(".", 1)[-1].lower() in AUDIO_EXTS: + files.append(os.path.join(root, fn)) + else: + files.append(p) + lib_rows = {} + if library is not None and files: + con = connect() + for i in range(0, len(files), 500): + chunk = files[i:i + 500] + q = f"SELECT * FROM songs WHERE url IN ({','.join('?' * len(chunk))})" + for r in con.execute(q, chunk): + lib_rows[r["url"]] = row_to_song(r) + con.close() + dir_art: dict[str, str] = {} + for f in files: + if f in lib_rows: + out.append(lib_rows[f]) + continue + s = T.read_song(f) + if s is None: + continue + d = os.path.dirname(f) + if d not in dir_art: + src = T.find_folder_cover(d) + key = T.album_key(s.effective_albumartist(), s.album, d) + data = None if src else T.extract_embedded_cover(f) + cached = Path(T.COVER_DIR / f"{key}.jpg") + if cached.exists(): + dir_art[d] = str(cached) + else: + dir_art[d] = (T.store_cover(src or data, key) or "") if (src or data) else "" + s.art = dir_art[d] + out.append(s) + return out diff --git a/mulberry/mainwindow.py b/mulberry/mainwindow.py new file mode 100644 index 0000000..9a47120 --- /dev/null +++ b/mulberry/mainwindow.py @@ -0,0 +1,869 @@ +"""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 diff --git a/mulberry/mpris.py b/mulberry/mpris.py new file mode 100644 index 0000000..12b7428 --- /dev/null +++ b/mulberry/mpris.py @@ -0,0 +1,350 @@ +"""MPRIS2 D-Bus interface so Plasma's media controls, KDE Connect, media keys +and shell widgets (Quickshell, etc.) see and control Mulberry.""" +from __future__ import annotations + +import os +from pathlib import Path + +from PyQt6.QtCore import QMetaType, QObject, pyqtClassInfo, pyqtProperty, pyqtSignal, pyqtSlot +from PyQt6.QtDBus import (QDBusAbstractAdaptor, QDBusArgument, QDBusConnection, QDBusMessage, + QDBusObjectPath) + +from .config import APP_ID, APP_NAME + +PATH = "/org/mpris/MediaPlayer2" +ROOT_XML = """ + + + + + + + + + +""" +PLAYER_XML = """ + + + + + + + + + + + + + + + + + + + + + + +""" + + +@pyqtClassInfo("D-Bus Interface", "org.mpris.MediaPlayer2") +@pyqtClassInfo("D-Bus Introspection", ROOT_XML) +class RootAdaptor(QDBusAbstractAdaptor): + def __init__(self, parent, window): + super().__init__(parent) + self.window = window + self.setAutoRelaySignals(False) + + @pyqtProperty(bool) + def CanQuit(self): + return True + + @pyqtProperty(bool) + def CanRaise(self): + return True + + @pyqtProperty(bool) + def HasTrackList(self): + return False + + @pyqtProperty(str) + def Identity(self): + return APP_NAME + + @pyqtProperty(str) + def DesktopEntry(self): + return APP_ID + + @pyqtProperty("QStringList") + def SupportedUriSchemes(self): + return ["file", "http", "https", "cdda"] + + @pyqtProperty("QStringList") + def SupportedMimeTypes(self): + return ["audio/mpeg", "audio/flac", "audio/ogg", "audio/x-vorbis+ogg", "audio/opus", + "audio/mp4", "audio/aac", "audio/x-wav", "audio/x-ms-wma", "audio/x-ape", + "audio/x-wavpack", "audio/x-musepack", "audio/x-aiff", "audio/x-mpegurl", + "audio/x-scpls", "application/xspf+xml"] + + @pyqtSlot() + def Raise(self): + w = self.window + w.show() + w.raise_() + w.activateWindow() + + @pyqtSlot() + def Quit(self): + self.window.quit_app() + + +@pyqtClassInfo("D-Bus Interface", "org.mpris.MediaPlayer2.Player") +@pyqtClassInfo("D-Bus Introspection", PLAYER_XML) +class PlayerAdaptor(QDBusAbstractAdaptor): + Seeked = pyqtSignal("qlonglong") + + def __init__(self, parent, player, mgr): + super().__init__(parent) + self.player, self.mgr = player, mgr + self.setAutoRelaySignals(False) + + @pyqtProperty(str) + def PlaybackStatus(self): + return {"playing": "Playing", "paused": "Paused"}.get(self.player.state, "Stopped") + + @pyqtProperty(str) + def LoopStatus(self): + return {"track": "Track", "playlist": "Playlist"}.get(self.mgr.repeat, "None") + + @LoopStatus.setter + def LoopStatus(self, v): + self.mgr.set_repeat({"Track": "track", "Playlist": "playlist"}.get(v, "off")) + self.parent().repeat_changed_external() + + @pyqtProperty(float) + def Rate(self): + return 1.0 + + @Rate.setter + def Rate(self, v): + pass + + @pyqtProperty(bool) + def Shuffle(self): + return bool(self.mgr.shuffle) + + @Shuffle.setter + def Shuffle(self, v): + self.mgr.set_shuffle(bool(v)) + self.parent().repeat_changed_external() + + @pyqtProperty("QVariantMap") + def Metadata(self): + return self.parent().metadata() + + @pyqtProperty(float) + def Volume(self): + return self.player.volume / 100.0 + + @Volume.setter + def Volume(self, v): + self.player.set_volume(int(round(v * 100))) + + @pyqtProperty("qlonglong") + def Position(self): + return int(self.player.pos * 1_000_000) + + @pyqtProperty(float) + def MinimumRate(self): + return 1.0 + + @pyqtProperty(float) + def MaximumRate(self): + return 1.0 + + @pyqtProperty(bool) + def CanGoNext(self): + return True + + @pyqtProperty(bool) + def CanGoPrevious(self): + return True + + @pyqtProperty(bool) + def CanPlay(self): + return True + + @pyqtProperty(bool) + def CanPause(self): + return True + + @pyqtProperty(bool) + def CanSeek(self): + return self.player.song is not None and not self.player.song.is_stream + + @pyqtProperty(bool) + def CanControl(self): + return True + + @pyqtSlot() + def Next(self): + self.player.next() + + @pyqtSlot() + def Previous(self): + self.player.prev() + + @pyqtSlot() + def Pause(self): + self.player.pause() + + @pyqtSlot() + def PlayPause(self): + self.player.play_pause() + + @pyqtSlot() + def Stop(self): + self.player.stop() + + @pyqtSlot() + def Play(self): + self.player.play() + + @pyqtSlot("qlonglong") + def Seek(self, offset): + self.player.seek_relative(offset / 1_000_000) + + @pyqtSlot(QDBusObjectPath, "qlonglong") + def SetPosition(self, track, pos): + self.player.seek(pos / 1_000_000) + + @pyqtSlot(str) + def OpenUri(self, uri): + from .playlist import url_to_path + p = url_to_path(uri) + if os.path.exists(p): + self.mgr.add_paths([p], play=True) + + +class Mpris(QObject): + def __init__(self, window, player, mgr): + super().__init__() + self.player, self.mgr, self.window = player, mgr, window + self.ok = False + bus = QDBusConnection.sessionBus() + if not bus.isConnected(): + return + self.root = RootAdaptor(self, window) + self.padaptor = PlayerAdaptor(self, player, mgr) + if not bus.registerObject(PATH, self): + return + name = "org.mpris.MediaPlayer2." + APP_ID + if not bus.registerService(name): + bus.registerService(f"{name}.instance{os.getpid()}") + self.ok = True + player.state_changed.connect(lambda *_: self._changed(["PlaybackStatus", "CanSeek"])) + player.song_changed.connect(lambda *_: self._changed(["Metadata", "CanSeek"])) + player.volume_changed.connect(lambda *_: self._changed(["Volume"])) + player.seeked.connect(lambda s: self._emit_seeked(s)) + + def repeat_changed_external(self): + self._changed(["LoopStatus", "Shuffle"]) + if hasattr(self.window, "sync_modes"): + self.window.sync_modes() + + def modes_changed(self): + self._changed(["LoopStatus", "Shuffle"]) + + def metadata(self) -> dict: + s = self.player.song + if s is None: + return {"mpris:trackid": QDBusObjectPath("/org/mpris/MediaPlayer2/TrackList/NoTrack")} + title = s.display_title() + artist = s.display_artist() + if s.is_stream: + st = s.stream_title + if st and " - " in st: + artist, title = [x.strip() for x in st.split(" - ", 1)] + else: + title = st or s.title or s.url + artist = artist or s.title + tid = QDBusObjectPath(f"/org/{APP_ID}/track/{abs(hash(s.key())) % 10**12}") + md = { + "mpris:trackid": tid, + "mpris:length": _i64(int(max(self.player.dur, s.duration()) * 1_000_000)), + "xesam:title": title, + "xesam:album": s.album, + "xesam:artist": _as([artist] if artist else []), + "xesam:albumArtist": _as([s.effective_albumartist()] if s.effective_albumartist() else []), + "xesam:genre": _as([s.genre] if s.genre else []), + "xesam:trackNumber": s.track, + "xesam:discNumber": s.disc, + "xesam:useCount": s.playcount, + "xesam:userRating": s.rating / 5.0, + "xesam:url": Path(s.path).as_uri() if s.is_local and os.path.isabs(s.path) else s.url, + } + art = getattr(self.window, "current_art_path", "") or s.art + if art and os.path.exists(art): + md["mpris:artUrl"] = Path(art).as_uri() + if s.year: + md["xesam:contentCreated"] = f"{s.year:04d}-01-01T00:00:00" + return md + + def _changed(self, props): + if not self.ok: + return + changed = {} + for p in props: + if p == "Metadata": + changed[p] = self.metadata() + else: + changed[p] = getattr(self.padaptor, p) + msg = QDBusMessage.createSignal(PATH, "org.freedesktop.DBus.Properties", "PropertiesChanged") + msg.setArguments(["org.mpris.MediaPlayer2.Player", changed, + QDBusArgument([], QMetaType.Type.QStringList.value)]) + QDBusConnection.sessionBus().send(msg) + + def art_changed(self): + self._changed(["Metadata"]) + + def _emit_seeked(self, sec): + if not self.ok: + return + msg = QDBusMessage.createSignal(PATH, "org.mpris.MediaPlayer2.Player", "Seeked") + arg = QDBusArgument() + arg.add(int(sec * 1_000_000), QMetaType.Type.LongLong.value) + msg.setArguments([arg]) + QDBusConnection.sessionBus().send(msg) + + +def _as(items: list[str]) -> QDBusArgument: + """Marshal as D-Bus 'as' (plain Python lists would become 'av', which + many MPRIS clients ignore — they then show 'Unknown artist').""" + return QDBusArgument([str(i) for i in items], QMetaType.Type.QStringList.value) + + +def _i64(v: int) -> QDBusArgument: + a = QDBusArgument() + a.add(int(v), QMetaType.Type.LongLong.value) + return a + + +def notify(summary: str, body: str, icon_path: str = "", replaces: int = 0) -> None: + """Desktop notification via org.freedesktop.Notifications (async).""" + bus = QDBusConnection.sessionBus() + if not bus.isConnected(): + return + msg = QDBusMessage.createMethodCall("org.freedesktop.Notifications", "/org/freedesktop/Notifications", + "org.freedesktop.Notifications", "Notify") + hints = {"desktop-entry": APP_ID, "transient": True} + if icon_path: + hints["image-path"] = Path(icon_path).as_uri() + rid = QDBusArgument() + rid.add(int(replaces), QMetaType.Type.UInt.value) + timeout = QDBusArgument() + timeout.add(5000, QMetaType.Type.Int.value) + msg.setArguments([APP_NAME, rid, icon_path or "audio-x-generic", summary, body, + QDBusArgument([], QMetaType.Type.QStringList.value), hints, timeout]) + bus.asyncCall(msg) diff --git a/mulberry/nowplaying.py b/mulberry/nowplaying.py new file mode 100644 index 0000000..579ce09 --- /dev/null +++ b/mulberry/nowplaying.py @@ -0,0 +1,237 @@ +"""Tracks the current song's artwork and lyrics, loading them from tags, +folders, cache or the internet without blocking the UI.""" +from __future__ import annotations + +import os + +from PyQt6.QtCore import QObject, Qt, pyqtSignal +from PyQt6.QtGui import QImage + +from . import library as L +from . import online +from . import tags as T +from .config import run_async, settings +from .song import Song + + +class NowPlaying(QObject): + art_changed = pyqtSignal(object, str) # QImage|None, path + lyrics_changed = pyqtSignal(str, str, object) # text, source, song ('' + 'loading' while busy) + info_changed = pyqtSignal(str, str) # artist, bio text + + def __init__(self, player): + super().__init__() + self.player = player + self.song: Song | None = None + self.image: QImage | None = None + self.art_path = "" + self.lyrics = "" + self.lyrics_source = "" + self._art_key = None + self._lyr_key = None + player.song_changed.connect(self.on_song) + + # ------------------------------------------------------------------ art + def on_song(self, s: Song): + prev = self.song + self.song = s + self._load_art(s) + if prev is not s or s.is_stream: + self._load_lyrics(s) + + def _art_ident(self, s: Song): + return (s.effective_albumartist().lower(), s.album.lower(), os.path.dirname(s.path) if s.is_local else s.url) + + def _load_art(self, s: Song, force=False): + ident = self._art_ident(s) + if ident == self._art_key and not force and not s.is_stream: + return + self._art_key = ident + if s.art and os.path.exists(s.art): + self._set_art_file(s.art) + return + + def work(): + if s.is_local and os.path.exists(s.path): + d = os.path.dirname(s.path) + key = T.album_key(s.effective_albumartist(), s.album, d) + cached = T.COVER_DIR / f"{key}.jpg" + if cached.exists(): + return str(cached) + src = T.find_folder_cover(d) + data = None if src else T.extract_embedded_cover(s.path) + if src or data: + return T.store_cover(src or data, key) + key = T.album_key(s.effective_albumartist(), s.album or s.display_title(), "") + cached = T.COVER_DIR / f"{key}.jpg" + if cached.exists(): + return str(cached) + if settings.get("online/auto_covers") and (s.album or s.is_cd): + data = online.best_cover(s.effective_albumartist(), s.album) + if data: + path = T.store_cover(data, key) + if path and settings.get("online/save_covers_to_folder") and s.is_local: + try: + dst = os.path.join(os.path.dirname(s.path), "cover.jpg") + if not os.path.exists(dst): + with open(dst, "wb") as fh: + fh.write(data) + except OSError: + pass + return path + return None + + def done(path): + if self.song is not s: + return + if path: + if s.id >= 0 and s.art != path: + L.library.set_album_art(s.effective_albumartist(), s.album, path) + s.art = path + self._set_art_file(path) + else: + self._set_art_none() + self._set_art_none() + run_async(work, on_done=done, on_error=lambda e: None) + + def _set_art_file(self, path): + img = QImage(path) + if img.isNull(): + self._set_art_none() + return + self.image, self.art_path = img, path + self.art_changed.emit(img, path) + + def _set_art_none(self): + if self.image is None and not self.art_path: + self.art_changed.emit(None, "") + return + self.image, self.art_path = None, "" + self.art_changed.emit(None, "") + + def set_cover(self, s: Song, img: QImage): + """Called by the cover manager after the user picked/loaded a cover.""" + d = os.path.dirname(s.path) if s.is_local else "" + key = T.album_key(s.effective_albumartist(), s.album, d) + path = T.store_cover(T.image_to_jpeg_bytes(img), key) + if path: + s.art = path + if s.album: + L.library.set_album_art(s.effective_albumartist(), s.album, path) + if self.song is not None and self._art_ident(self.song) == self._art_ident(s): + self.song.art = path + self._art_key = None + self._set_art_file(path) + return path + + # ------------------------------------------------------------------ lyrics + def lyr_key(self, s: Song): + if s.is_stream: + return f"stream|{s.stream_title}".lower() + return f"{s.display_artist()}|{s.display_title()}|{s.album}".lower() + + def _load_lyrics(self, s: Song, force_online=False): + """Sources: auto (local .lrc → synced embedded → LRCLIB → NetEase → + plain embedded), or one specific provider chosen in the lyrics menu.""" + source = settings.get("lyrics/source") + key = self.lyr_key(s) + ckey = key if source == "auto" else f"{key}|{source}" + if ckey == self._lyr_key and not force_online: + return + self._lyr_key = ckey + self._lyr_token = token = getattr(self, "_lyr_token", 0) + 1 + if s.is_stream and not s.stream_title: + self._emit_lyrics("", "", s) + return + # lyrics the user typed/pasted always win + utxt, usrc = L.library.get_lyrics(key) + if usrc == "user" and utxt and not force_online and source == "auto": + self._emit_lyrics(utxt, "Your lyrics", s) + return + local = T.sidecar_lyrics(s.path) if s.is_local else "" + emb = T.read_embedded_lyrics(s.path) if s.is_local else "" + if source == "local": + self._emit_lyrics(local, "Local .lrc", s) if local.strip() else \ + self._emit_lyrics("", "nolocal", s) + return + if source == "embedded": + self._emit_lyrics(emb, "Embedded tags", s) + return + if source == "auto" and not force_online: + if local.strip(): + self._emit_lyrics(local, "Local .lrc", s) + return + if emb.strip() and online.LRC_RE.search(emb): + self._emit_lyrics(emb, "Embedded tags", s) + return + if not force_online: + txt, src = L.library.get_lyrics(ckey) + if txt is not None and (txt or src == "none"): + if txt: + self._emit_lyrics(txt, src or "cache", s) + else: + self._emit_lyrics(emb, "Embedded tags", s) if emb.strip() else self._emit_lyrics("", "", s) + return + if source == "auto" and not settings.get("online/auto_lyrics"): + self._emit_lyrics(emb, "Embedded tags" if emb else "", s) + return + self.lyrics_changed.emit("", "loading", s) + provider = source if source in online.ONLINE_PROVIDERS else "auto" + + def done(res): + txt, src = res + L.library.put_lyrics(ckey, txt or "", src or "none") + if self.song is not s or self._lyr_token != token: + return + if txt: + self._emit_lyrics(txt, src, s) + elif emb.strip(): + self._emit_lyrics(emb, "Embedded tags", s) + else: + self._emit_lyrics("", "", s) + + def fail(_e): + if self.song is s and self._lyr_token == token: + self._emit_lyrics(emb, "Embedded tags", s) if emb.strip() else self._emit_lyrics("", "error", s) + run_async(online.fetch_lyrics, s, provider, on_done=done, on_error=fail) + + def set_source(self, source: str): + settings.set("lyrics/source", source) + if self.song: + self._lyr_key = None + self._load_lyrics(self.song) + + def _emit_lyrics(self, txt, src, s): + self.lyrics, self.lyrics_source = txt, src + self.lyrics_changed.emit(txt or "", src or "", s) + + def refetch_lyrics(self): + if self.song: + self._lyr_key = None + self._load_lyrics(self.song, force_online=True) + + def set_lyrics(self, text: str, save_to_file=False): + s = self.song + if not s: + return + self._lyr_token = getattr(self, "_lyr_token", 0) + 1 + L.library.put_lyrics(self.lyr_key(s), text, "user") + if save_to_file and s.is_local: + try: + T.write_lyrics(s.path, text) + except Exception as e: # noqa: BLE001 + print("write lyrics failed", e) + self._emit_lyrics(text, "Your lyrics", s) + + def load_artist_info(self): + s = self.song + if not s or not s.display_artist(): + return + artist = s.display_artist() + run_async(online.artist_info, artist, on_done=lambda t: self.info_changed.emit(artist, t or ""), + on_error=lambda e: self.info_changed.emit(artist, "")) + + +def scaled_cover(img: QImage, size: int) -> QImage: + return img.scaled(size, size, Qt.AspectRatioMode.KeepAspectRatioByExpanding, + Qt.TransformationMode.SmoothTransformation) diff --git a/mulberry/online.py b/mulberry/online.py new file mode 100644 index 0000000..b25f90a --- /dev/null +++ b/mulberry/online.py @@ -0,0 +1,399 @@ +"""Online metadata: MusicBrainz tags, cover art (Cover Art Archive, iTunes, +Deezer, Last.fm), synced lyrics (LRCLIB), artist info (Last.fm / Wikipedia), +AcoustID fingerprint lookup. All functions are blocking — call via run_async.""" +from __future__ import annotations + +import json +import re +import shutil +import subprocess +import threading +import time +import urllib.error +import urllib.parse +import urllib.request + +from .config import USER_AGENT, settings +from .song import Song + +_mb_lock = threading.Lock() +_mb_last = [0.0] + + +def http_get(url: str, params: dict | None = None, timeout=12, headers=None, raw=False): + if params: + url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params) + req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Accept": "application/json", + **(headers or {})}) + with urllib.request.urlopen(req, timeout=timeout) as r: + data = r.read() + if raw: + return data + return json.loads(data.decode("utf-8", "replace")) + + +def http_post(url: str, data: dict | bytes, timeout=12, headers=None): + body = data if isinstance(data, bytes) else urllib.parse.urlencode(data).encode() + req = urllib.request.Request(url, data=body, method="POST", + headers={"User-Agent": USER_AGENT, **(headers or {})}) + with urllib.request.urlopen(req, timeout=timeout) as r: + return json.loads(r.read().decode("utf-8", "replace") or "{}") + + +def mb_get(path: str, params: dict): + with _mb_lock: # MusicBrainz: max 1 request/second + wait = 1.05 - (time.time() - _mb_last[0]) + if wait > 0: + time.sleep(wait) + _mb_last[0] = time.time() + return http_get(f"https://musicbrainz.org/ws/2/{path}", {**params, "fmt": "json"}) + + +def _clean(s: str) -> str: + s = re.sub(r"\s*[\(\[](feat\.?|ft\.?|with|remaster(ed)?|\d{4} remaster|live|explicit|bonus)[^\)\]]*[\)\]]", "", s, flags=re.I) + return s.strip() + + +def _q(s: str) -> str: + return re.sub(r'([+\-&|!(){}\[\]^"~*?:\\/])', r"\\\1", s) + + +# ------------------------------------------------------------------ MusicBrainz +def musicbrainz_search(song: Song, limit=15) -> list[dict]: + """Search recordings; returns flattened candidates (one per release).""" + parts = [] + if song.title: + parts.append(f'recording:"{_q(_clean(song.title))}"') + if song.display_artist(): + parts.append(f'artist:"{_q(song.display_artist())}"') + if song.album: + parts.append(f'release:"{_q(_clean(song.album))}"') + if not parts: + return [] + res = mb_get("recording", {"query": " AND ".join(parts[:2]) + (f" AND ({parts[2]})" if len(parts) > 2 else ""), + "limit": limit}) + out = [] + for rec in res.get("recordings", []): + artist = "".join(a.get("name", "") + a.get("joinphrase", "") for a in rec.get("artist-credit", [])) + for rel in rec.get("releases", [])[:4] or [{}]: + media = (rel.get("media") or [{}])[0] + trk = (media.get("track") or [{}])[0] + ra = "".join(a.get("name", "") + a.get("joinphrase", "") for a in rel.get("artist-credit", [])) or artist + out.append({ + "title": rec.get("title", ""), "artist": artist, "album": rel.get("title", ""), + "albumartist": ra, "year": int((rel.get("date") or "0")[:4] or 0), + "track": int(re.sub(r"\D", "", str(trk.get("number", "0"))) or 0), + "disc": int(media.get("position", 0) or 0), + "length": (rec.get("length") or 0) / 1000, + "mb_trackid": rec.get("id", ""), "mb_albumid": rel.get("id", ""), + "score": int(rec.get("score", 0)), "country": rel.get("country", ""), + "status": rel.get("status", ""), + }) + # prefer close length + official releases + if song.length: + for c in out: + if c["length"]: + c["score"] -= min(40, abs(c["length"] - song.length) * 2) + for c in out: + if c["status"] == "Official": + c["score"] += 5 + out.sort(key=lambda c: -c["score"]) + return out + + +def musicbrainz_genre(mb_albumid: str) -> str: + try: + r = mb_get(f"release/{mb_albumid}", {"inc": "genres+release-groups"}) + g = sorted(r.get("genres", []), key=lambda x: -x.get("count", 0)) + return g[0]["name"].title() if g else "" + except Exception: # noqa: BLE001 + return "" + + +def acoustid_lookup(path: str) -> list[dict]: + key = settings.get("online/acoustid_key") + fpcalc = shutil.which("fpcalc") + if not key or not fpcalc: + raise RuntimeError("AcoustID needs an API key (Settings › Metadata) and the 'fpcalc' tool (chromaprint).") + out = subprocess.run([fpcalc, "-json", path], capture_output=True, text=True, timeout=60) + fp = json.loads(out.stdout) + res = http_post("https://api.acoustid.org/v2/lookup", { + "client": key, "meta": "recordings releases", "duration": int(fp["duration"]), + "fingerprint": fp["fingerprint"]}) + cands = [] + for r in res.get("results", []): + for rec in r.get("recordings", []) or []: + artist = ", ".join(a["name"] for a in rec.get("artists", [])) + for rel in (rec.get("releases") or [{}])[:3]: + cands.append({"title": rec.get("title", ""), "artist": artist, "album": rel.get("title", ""), + "albumartist": artist, "year": (rel.get("date") or {}).get("year", 0), + "track": 0, "disc": 0, "mb_trackid": rec.get("id", ""), + "mb_albumid": rel.get("id", ""), "score": int(r.get("score", 0) * 100), + "length": rec.get("duration", 0)}) + return cands + + +# ------------------------------------------------------------------ covers +def cover_candidates(artist: str, album: str, title: str = "") -> list[dict]: + """Return [{'url','thumb','source','size'}] from several providers.""" + out: list[dict] = [] + term = f"{artist} {album or title}".strip() + errors = [] + + def itunes(): + r = http_get("https://itunes.apple.com/search", {"term": term, "entity": "album" if album else "song", "limit": 8}) + for it in r.get("results", []): + u = it.get("artworkUrl100") + if u: + out.append({"url": u.replace("100x100bb", "1200x1200bb"), "thumb": u.replace("100x100bb", "300x300bb"), + "source": "iTunes", "label": f"{it.get('artistName', '')} – {it.get('collectionName', '')}"}) + + def deezer(): + r = http_get("https://api.deezer.com/search/album", {"q": f'artist:"{artist}" album:"{album or title}"'}) + for it in (r.get("data") or [])[:8]: + if it.get("cover_xl"): + out.append({"url": it["cover_xl"], "thumb": it.get("cover_medium") or it["cover_xl"], + "source": "Deezer", "label": f"{it.get('artist', {}).get('name', '')} – {it.get('title', '')}"}) + + def caa(): + if not album: + return + r = mb_get("release", {"query": f'release:"{_q(album)}" AND artist:"{_q(artist)}"', "limit": 5}) + for rel in r.get("releases", [])[:5]: + rid = rel["id"] + out.append({"url": f"https://coverartarchive.org/release/{rid}/front", + "thumb": f"https://coverartarchive.org/release/{rid}/front-250", + "source": "Cover Art Archive", + "label": f"{rel.get('title', '')} ({(rel.get('date') or '')[:4]})"}) + + def lastfm(): + from .scrobble import LastFM + key = LastFM.key()[0] + if not key or not album: + return + r = http_get("https://ws.audioscrobbler.com/2.0/", {"method": "album.getinfo", "api_key": key, + "artist": artist, "album": album, "format": "json"}) + imgs = r.get("album", {}).get("image", []) + if imgs and imgs[-1].get("#text"): + u = imgs[-1]["#text"] + out.append({"url": re.sub(r"/\d+x\d+/", "/", u), "thumb": u, "source": "Last.fm", "label": album}) + + threads = [] + for fn in (itunes, deezer, caa, lastfm): + def wrap(f=fn): + try: + f() + except Exception as e: # noqa: BLE001 + errors.append(str(e)) + t = threading.Thread(target=wrap, daemon=True) + t.start() + threads.append(t) + for t in threads: + t.join(20) + order = {"Cover Art Archive": 0, "iTunes": 1, "Deezer": 2, "Last.fm": 3} + out.sort(key=lambda c: order.get(c["source"], 9)) + return out + + +def best_cover(artist: str, album: str, title: str = "") -> bytes | None: + """Automatic fetch: try providers in order, return image bytes.""" + if not artist and not album: + return None + for fn in (_auto_itunes, _auto_deezer): + try: + u = fn(artist, album, title) + if u: + data = http_get(u, raw=True, timeout=15) + if data and len(data) > 1000: + return data + except Exception: # noqa: BLE001 + continue + return None + + +def _norm(s): + return re.sub(r"[^a-z0-9]", "", (s or "").lower()) + + +def _auto_itunes(artist, album, title): + term = f"{artist} {album or title}" + r = http_get("https://itunes.apple.com/search", {"term": term, "entity": "album" if album else "song", "limit": 6}) + for it in r.get("results", []): + if _norm(artist) and _norm(artist) not in _norm(it.get("artistName")) and _norm(it.get("artistName")) not in _norm(artist): + continue + if album and _norm(_clean(album))[:12] not in _norm(it.get("collectionName")): + continue + u = it.get("artworkUrl100") + if u: + return u.replace("100x100bb", "1000x1000bb") + return None + + +def _auto_deezer(artist, album, title): + r = http_get("https://api.deezer.com/search/album", {"q": f'artist:"{artist}" album:"{album or title}"'}) + for it in r.get("data") or []: + if _norm(artist) in _norm(it.get("artist", {}).get("name")): + return it.get("cover_xl") + return None + + +def download(url: str) -> bytes: + return http_get(url, raw=True, timeout=20) + + +# ------------------------------------------------------------------ lyrics +def _lyr_query(song: Song): + artist = song.display_artist() + title = song.display_title() + if song.is_stream and song.stream_title and " - " in song.stream_title: + artist, title = [x.strip() for x in song.stream_title.split(" - ", 1)] + return artist, title + + +def lyrics_lrclib(song: Song) -> str: + artist, title = _lyr_query(song) + if not title: + return "" + params = {"artist_name": artist, "track_name": _clean(title)} + if song.album and not song.is_stream: + params["album_name"] = song.album + if song.duration() and not song.is_stream: + params["duration"] = int(round(song.duration())) + try: + r = http_get("https://lrclib.net/api/get", params) + if r.get("instrumental"): + return "[instrumental]" + txt = r.get("syncedLyrics") or r.get("plainLyrics") or "" + if txt: + return txt + except urllib.error.HTTPError: + pass + r = http_get("https://lrclib.net/api/search", {"track_name": _clean(title), "artist_name": artist}) + best = None + for it in r or []: + if song.duration() and it.get("duration") and abs(it["duration"] - song.duration()) > 6: + continue + if it.get("syncedLyrics"): + best = it + break + best = best or it + return (best.get("syncedLyrics") or best.get("plainLyrics") or "") if best else "" + + +_NE_HEADERS = {"Referer": "https://music.163.com/", + "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/124.0 Safari/537.36"} +_NE_CREDIT = re.compile(r"^\s*\[[^\]]*\]\s*(作词|作曲|编曲|制作人|监制|混音|母带|和声|吉他|贝斯|鼓|词|曲|" + r"Lyricist|Lyrics by|Composer|Composed by|Arranger|Producer|Written by)\s*[::]", re.I) + + +def lyrics_netease(song: Song) -> str: + artist, title = _lyr_query(song) + if not title: + return "" + q = f"{_clean(title)} {artist}".strip() + r = http_get("https://music.163.com/api/search/get/web", + {"s": q, "type": 1, "offset": 0, "limit": 10}, headers=_NE_HEADERS) + songs = (r.get("result") or {}).get("songs") or [] + best, best_score = None, -1e9 + for it in songs: + score = 0.0 + names = " ".join(a.get("name", "") for a in it.get("artists", [])) + if _norm(artist) and (_norm(artist) in _norm(names) or _norm(names) in _norm(artist)): + score += 50 + if _norm(_clean(title)) == _norm(_clean(it.get("name", ""))): + score += 30 + if song.duration() and it.get("duration"): + score -= min(40, abs(it["duration"] / 1000 - song.duration()) * 4) + if score > best_score: + best, best_score = it, score + if not best or best_score < 0: + return "" + lr = http_get("https://music.163.com/api/song/lyric", + {"id": best["id"], "lv": 1, "kv": 1, "tv": -1}, headers=_NE_HEADERS) + txt = ((lr.get("lrc") or {}).get("lyric") or "").strip() + if lr.get("nolyric") or lr.get("uncollected"): + return "" + return "\n".join(ln for ln in txt.splitlines() if not _NE_CREDIT.match(ln)) + + +ONLINE_PROVIDERS = {"lrclib": ("LRCLIB", lyrics_lrclib), "netease": ("NetEase", lyrics_netease)} + + +def fetch_lyrics(song: Song, source: str = "auto") -> tuple[str, str]: + """Return (lyrics_text, provider label). In auto mode synced results win: + LRCLIB first, then NetEase; a plain result is kept only as a fallback.""" + order = ["lrclib", "netease"] if source == "auto" else [source] + fallback = ("", "") + errors = [] + for key in order: + if key not in ONLINE_PROVIDERS: + continue + label, fn = ONLINE_PROVIDERS[key] + try: + txt = fn(song) + except Exception as e: # noqa: BLE001 + errors.append(str(e)) + continue + if not txt: + continue + if txt == "[instrumental]" or LRC_RE.search(txt): + return txt, label + if not fallback[0]: + fallback = (txt, label) + if fallback[0]: + return fallback + if errors and len(errors) == len(order): + raise RuntimeError(errors[0]) + return "", "" + + +LRC_RE = re.compile(r"\[(\d+):(\d+(?:[.:]\d+)?)\]") + + +def parse_lrc(text: str) -> tuple[list[tuple[float, str]], bool]: + """Return ([(time, line)], synced). Unsynced text -> times are -1.""" + lines = [] + offset = 0.0 + m = re.search(r"\[offset:\s*([-+]?\d+)\]", text or "", re.I) + if m: + offset = int(m.group(1)) / 1000 + synced = False + for raw in (text or "").splitlines(): + stamps = LRC_RE.findall(raw) + content = LRC_RE.sub("", raw).strip() + content = re.sub(r"<\d+:\d+(?:\.\d+)?>", "", content) # enhanced LRC word stamps + if stamps: + synced = True + for mm, ss in stamps: + t = int(mm) * 60 + float(ss.replace(":", ".")) - offset + lines.append((max(t, 0.0), content)) + elif not re.match(r"^\[[a-z]+:.*\]$", raw.strip(), re.I): + lines.append((-1.0, raw.strip())) + if synced: + lines = sorted([x for x in lines if x[0] >= 0], key=lambda x: x[0]) + return lines, synced + + +# ------------------------------------------------------------------ artist info +def artist_info(artist: str) -> str: + from .scrobble import LastFM + key = LastFM.key()[0] + if key: + try: + r = http_get("https://ws.audioscrobbler.com/2.0/", {"method": "artist.getinfo", "artist": artist, + "api_key": key, "format": "json", "autocorrect": 1}) + txt = r.get("artist", {}).get("bio", {}).get("content", "") + txt = re.sub(r"\.?", "", txt).strip() + if txt: + return txt + except Exception: # noqa: BLE001 + pass + try: + r = http_get("https://en.wikipedia.org/api/rest_v1/page/summary/" + urllib.parse.quote(artist.replace(" ", "_"))) + if r.get("type") == "disambiguation": + r = http_get("https://en.wikipedia.org/api/rest_v1/page/summary/" + + urllib.parse.quote(artist.replace(" ", "_") + "_(band)")) + return r.get("extract", "") + except Exception: # noqa: BLE001 + return "" diff --git a/mulberry/player.py b/mulberry/player.py new file mode 100644 index 0000000..9b887cd --- /dev/null +++ b/mulberry/player.py @@ -0,0 +1,743 @@ +"""Audio backends (libmpv preferred, Qt Multimedia/FFmpeg fallback) and the +playback controller that drives playlists, queue, stats and scrobbling.""" +from __future__ import annotations + +import ctypes.util +import math +import time + +import numpy as np +from PyQt6.QtCore import QObject, QTimer, QUrl, pyqtSignal + +from . import library as L +from .config import settings +from .playlist import PlaylistManager, PlaylistModel +from .song import Song + +EQ_FREQS = (31, 62, 125, 250, 500, 1000, 2000, 4000, 8000, 16000) +EQ_PRESETS = { + "Flat": [0] * 10, + "Rock": [5, 4, 3, 1, -1, -1, 1, 3, 4, 5], + "Metal": [5, 4, 1, 0, -2, -1, 2, 4, 5, 5], + "Pop": [-1, 1, 3, 4, 3, 0, -1, -1, 0, 1], + "Jazz": [3, 2, 1, 2, -1, -1, 0, 1, 2, 3], + "Classical": [4, 3, 2, 1, -1, -1, 0, 2, 3, 4], + "Electronic": [5, 4, 1, 0, -2, 2, 1, 1, 4, 5], + "Hip-Hop": [5, 4, 1, 3, -1, -1, 1, 0, 2, 3], + "Bass boost": [6, 5, 4, 2, 0, 0, 0, 0, 0, 0], + "Treble boost": [0, 0, 0, 0, 0, 1, 2, 4, 5, 6], + "Vocal": [-2, -3, -3, 1, 4, 4, 3, 1, 0, -2], + "Loudness": [6, 4, 0, 0, -2, 0, -1, -5, 5, 1], +} + + +def _prepare_mpv_search_path(): + """Let python-mpv find libmpv-2.dll shipped next to the app on Windows.""" + import os + import sys + from .config import BUNDLE_DIR, IS_WIN + if not IS_WIN: + return + dirs = [str(BUNDLE_DIR), os.path.dirname(sys.executable), str(BUNDLE_DIR / "mpv")] + for d in dirs: + if os.path.isdir(d): + os.environ["PATH"] = d + os.pathsep + os.environ.get("PATH", "") + try: + os.add_dll_directory(d) + except (AttributeError, OSError): + pass + + +_mpv_ok = None + + +def mpv_available() -> bool: + global _mpv_ok + if _mpv_ok is not None: + return _mpv_ok + try: + import sys + if sys.platform != "win32" and not ctypes.util.find_library("mpv"): + _mpv_ok = False + return False + _prepare_mpv_search_path() + import mpv # noqa: F401 + _mpv_ok = True + except Exception: # noqa: BLE001 (OSError: dll not found, ImportError…) + _mpv_ok = False + return _mpv_ok + + +def preferred_backend() -> str: + """auto → mpv on Linux (gapless, EQ, CD; visualizer via the sink monitor); + Qt on Windows/macOS, where the visualizer needs Qt's own audio buffers.""" + import sys + want = settings.get("playback/backend") + if want == "auto": + return "mpv" if sys.platform.startswith("linux") and mpv_available() else "qt" + if want == "mpv" and mpv_available(): + return "mpv" + return "qt" + + +class Backend(QObject): + position = pyqtSignal(float) + duration = pyqtSignal(float) + state = pyqtSignal(str) + ended = pyqtSignal() + advanced = pyqtSignal() + error = pyqtSignal(str) + stream_meta = pyqtSignal(dict) + pcm = pyqtSignal(object) + name = "none" + supports_eq = supports_gapless = supports_cd = False + provides_pcm = False + + def load(self, song: Song, next_song: Song | None = None, start: float = 0.0, paused=False): ... + def set_next(self, song: Song | None): ... + def play(self): ... + def pause(self): ... + def stop(self): ... + def seek(self, sec: float): ... + def set_volume(self, v: int): ... + def set_gain(self, db: float): ... + def devices(self) -> list[tuple[str, str]]: return [] + def set_device(self, dev: str): ... + def set_eq(self, enabled: bool, preamp: float, bands: list[float]): ... + def set_replaygain(self, mode: str, preamp: float): ... + def shutdown(self): ... + + +# ---------------------------------------------------------------------- mpv +class MpvBackend(Backend): + name = "mpv" + supports_eq = supports_gapless = supports_cd = True + _sig_pos = pyqtSignal(float) + _sig_dur = pyqtSignal(float) + _sig_pause = pyqtSignal(bool) + _sig_idle = pyqtSignal(bool) + _sig_end = pyqtSignal(int) + _sig_start = pyqtSignal(int) + _sig_meta = pyqtSignal(object) + + def __init__(self): + super().__init__() + import mpv + self.mpv = mpv + self.m = mpv.MPV(video=False, ytdl=False, terminal=False, input_default_bindings=False, + input_vo_keyboard=False, idle=True, keep_open=False, + gapless_audio="weak" if settings.get("playback/gapless") else "no", + prefetch_playlist=True, audio_client_name="mulberry", + audio_display="no", cache="auto", demuxer_max_bytes="64MiB") + self._has_next = False + self._last_pos = -1.0 + self._loading = False + self._gain_db = 0.0 + self._eq = "" + self._sig_pos.connect(self.position) + self._sig_dur.connect(self.duration) + self._sig_pause.connect(lambda p: self.state.emit("paused" if p else "playing")) + self._sig_idle.connect(self._on_idle) + self._sig_end.connect(self._on_end) + self._sig_start.connect(self._on_start) + self._sig_meta.connect(self._on_meta) + + @self.m.property_observer("time-pos") + def _tp(_n, v): + if v is not None and abs(v - self._last_pos) >= 0.05: + self._last_pos = v + self._sig_pos.emit(float(v)) + + @self.m.property_observer("duration") + def _du(_n, v): + if v: + self._sig_dur.emit(float(v)) + + @self.m.property_observer("pause") + def _pa(_n, v): + self._sig_pause.emit(bool(v)) + + @self.m.property_observer("idle-active") + def _id(_n, v): + self._sig_idle.emit(bool(v)) + + @self.m.property_observer("metadata") + def _md(_n, v): + if v: + self._sig_meta.emit(dict(v)) + + @self.m.event_callback("end-file") + def _ef(ev): + try: + reason = ev.data.reason + reason = int(reason.value if hasattr(reason, "value") else reason) + except Exception: # noqa: BLE001 + reason = 0 + self._sig_end.emit(reason) + + @self.m.event_callback("start-file") + def _sf(ev): + try: + pos = self.m.playlist_pos + except Exception: # noqa: BLE001 + pos = 0 + self._sig_start.emit(pos if pos is not None else 0) + + @staticmethod + def _opts(song: Song, start=0.0): + o = {} + b = song.begin + start + if b: + o["start"] = f"{b:.3f}" + if song.end: + o["end"] = f"{song.end:.3f}" + if song.is_cd and song.cd_device: + o["cdrom-device"] = song.cd_device + return o + + @staticmethod + def _url(song: Song): + if song.is_cd: + return "cdda://" + return song.path if song.is_local else song.url + + def load(self, song, next_song=None, start=0.0, paused=False): + self._has_next = False + self._last_pos = -1 + self._loading = True + self.m.pause = paused + self.m.loadfile(self._url(song), "replace", **self._opts(song, start)) + self.state.emit("loading") + self.set_next(next_song) + + def set_next(self, song): + try: + pos = self.m.playlist_pos or 0 + count = self.m.playlist_count or 0 + for _ in range(count - pos - 1): + self.m.playlist_remove(pos + 1) + except Exception: # noqa: BLE001 + pass + self._has_next = False + if song is None or not settings.get("playback/gapless") or song.is_stream: + return + try: + self.m.loadfile(self._url(song), "append", **self._opts(song)) + self._has_next = True + except Exception: # noqa: BLE001 + self._has_next = False + + def _on_start(self, pos): + if pos >= 1: + # mpv moved on to the prefetched entry -> gapless advance + try: + self.m.playlist_remove(0) + except Exception: # noqa: BLE001 + pass + self._has_next = False + self._last_pos = -1 + self.advanced.emit() + + def _on_end(self, reason): + if reason == 0: # EOF + if not self._has_next: + self.ended.emit() + elif reason == 4: # error + self.error.emit("Playback error (unsupported or unreadable media)") + if not self._has_next: + self.ended.emit() + + def _on_idle(self, idle): + if idle: + self.state.emit("stopped") + else: + self.state.emit("paused" if self.m.pause else "playing") + + def _on_meta(self, md): + lower = {str(k).lower(): v for k, v in md.items()} + title = lower.get("icy-title") or "" + out = {} + if title: + out["stream_title"] = title + if lower.get("icy-name"): + out["station"] = lower["icy-name"] + if out: + self.stream_meta.emit(out) + + def play(self): + self.m.pause = False + + def pause(self): + self.m.pause = True + + def stop(self): + self._has_next = False + self.m.command("stop") + + def seek(self, sec): + try: + self.m.seek(sec, "absolute+exact") + except Exception: # noqa: BLE001 + pass + + def set_volume(self, v): + self.m.volume = max(0, min(100, v)) + + def devices(self): + try: + return [(d["name"], d["description"]) for d in self.m.audio_device_list] + except Exception: # noqa: BLE001 + return [] + + def set_device(self, dev): + try: + self.m.audio_device = dev or "auto" + except Exception: # noqa: BLE001 + pass + + def set_eq(self, enabled, preamp, bands): + if enabled: + chain = ",".join(f"equalizer=f={f}:t=o:w=1:g={g:.1f}" for f, g in zip(EQ_FREQS, bands) if g) + if preamp: + chain = (chain + "," if chain else "") + f"volume={preamp:.1f}dB" + self.m.af = f"lavfi=[{chain}]" if chain else "" + else: + self.m.af = "" + + def set_replaygain(self, mode, preamp): + self.m.replaygain = {"track": "track", "album": "album"}.get(mode, "no") + self.m.replaygain_preamp = preamp + + def shutdown(self): + try: + self.m.terminate() + except Exception: # noqa: BLE001 + pass + + +# ---------------------------------------------------------------------- Qt +class QtBackend(Backend): + name = "qt" + provides_pcm = True + + def __init__(self): + super().__init__() + from PyQt6.QtMultimedia import QAudioOutput, QMediaDevices, QMediaPlayer + self.QMediaPlayer = QMediaPlayer + self.QMediaDevices = QMediaDevices + self.p = QMediaPlayer(self) + self.out = QAudioOutput(self) + self.p.setAudioOutput(self.out) + self._song: Song | None = None + self._pending_seek = 0.0 + self._vol = 70 + self._gain = 1.0 + self._end_sent = False + self.p.positionChanged.connect(self._pos) + self.p.durationChanged.connect(lambda ms: self.duration.emit(ms / 1000)) + self.p.playbackStateChanged.connect(self._st) + self.p.mediaStatusChanged.connect(self._ms) + self.p.errorOccurred.connect(lambda e, s: self.error.emit(s or str(e))) + self.p.metaDataChanged.connect(self._meta) + try: + from PyQt6.QtMultimedia import QAudioBufferOutput, QAudioFormat + fmt = QAudioFormat() + fmt.setSampleRate(44100) + fmt.setChannelCount(1) + fmt.setSampleFormat(QAudioFormat.SampleFormat.Float) + self.abo = QAudioBufferOutput(fmt, self) + self.p.setAudioBufferOutput(self.abo) + self.abo.audioBufferReceived.connect(self._buf) + except Exception: # noqa: BLE001 + self.abo = None + self.provides_pcm = False + + def _buf(self, buf): + try: + n = buf.byteCount() + if n <= 0: + return + data = np.frombuffer(buf.constData().asstring(n), dtype=np.float32) + self.pcm.emit(data) + except Exception: # noqa: BLE001 + pass + + def _pos(self, ms): + sec = ms / 1000 + s = self._song + if s and s.end and sec >= s.end and not self._end_sent: + self._end_sent = True + self.p.pause() + self.ended.emit() + return + self.position.emit(sec) + + def _st(self, st): + P = self.QMediaPlayer.PlaybackState + self.state.emit({P.PlayingState: "playing", P.PausedState: "paused"}.get(st, "stopped")) + + def _ms(self, ms): + S = self.QMediaPlayer.MediaStatus + if ms in (S.LoadedMedia, S.BufferedMedia) and self._pending_seek: + self.p.setPosition(int(self._pending_seek * 1000)) + self._pending_seek = 0.0 + elif ms == S.EndOfMedia and not self._end_sent: + self._end_sent = True + self.ended.emit() + elif ms == S.InvalidMedia: + self.error.emit("Cannot play this media") + if not self._end_sent: + self._end_sent = True + self.ended.emit() + + def _meta(self): + from PyQt6.QtMultimedia import QMediaMetaData + md = self.p.metaData() + t = md.stringValue(QMediaMetaData.Key.Title) + if t and self._song and self._song.is_stream: + self.stream_meta.emit({"stream_title": t}) + + def load(self, song, next_song=None, start=0.0, paused=False): + if song.is_cd: + self.error.emit("Audio CD playback needs the mpv backend (install libmpv / mpv).") + self.ended.emit() + return + self._song = song + self._end_sent = False + self._pending_seek = song.begin + start + url = QUrl.fromLocalFile(song.path) if song.is_local else QUrl(song.url) + self.p.setSource(url) + if paused: + self.p.pause() + else: + self.p.play() + + def play(self): + self.p.play() + + def pause(self): + self.p.pause() + + def stop(self): + self.p.stop() + + def seek(self, sec): + self.p.setPosition(int(sec * 1000)) + + def _apply_vol(self): + v = (self._vol / 100.0) ** 2 * self._gain + self.out.setVolume(max(0.0, min(1.0, v))) + + def set_volume(self, v): + self._vol = v + self._apply_vol() + + def set_gain(self, db): + self._gain = 10 ** (db / 20) + self._apply_vol() + + def devices(self): + return [(bytes(d.id()).decode(errors="replace"), d.description()) + for d in self.QMediaDevices.audioOutputs()] + + def set_device(self, dev): + for d in self.QMediaDevices.audioOutputs(): + if bytes(d.id()).decode(errors="replace") == dev: + self.out.setDevice(d) + return + self.out.setDevice(self.QMediaDevices.defaultAudioOutput()) + + def shutdown(self): + self.p.stop() + + +# ---------------------------------------------------------------------- controller +class Player(QObject): + instance: "Player" = None + song_changed = pyqtSignal(object) + state_changed = pyqtSignal(str) + position_changed = pyqtSignal(float, float) + volume_changed = pyqtSignal(int) + stream_title = pyqtSignal(str) + seeked = pyqtSignal(float) + message = pyqtSignal(str) + track_started = pyqtSignal(object) # for scrobblers + track_finished = pyqtSignal(object, float, int) # song, listened seconds, start ts + + def __init__(self, manager: PlaylistManager): + super().__init__() + Player.instance = self + self.mgr = manager + self.backend: Backend + if preferred_backend() == "mpv": + try: + self.backend = MpvBackend() + except Exception as e: # noqa: BLE001 + print("mpv backend failed, using Qt:", e) + self.backend = QtBackend() + else: + self.backend = QtBackend() + b = self.backend + b.position.connect(self._on_pos) + b.duration.connect(self._on_dur) + b.state.connect(self._on_state) + b.ended.connect(self._on_ended) + b.advanced.connect(self._on_advanced) + b.error.connect(self._on_error) + self._errors = 0 + b.stream_meta.connect(self._on_stream_meta) + self.song: Song | None = None + self.playlist: PlaylistModel | None = None + self.state = "stopped" + self.pos = 0.0 + self.dur = 0.0 + self.volume = settings.get("playback/volume") + self._muted_vol = None + self._played_marked = False + self._listen = 0.0 + self._last_tick = None + self._start_ts = 0 + self._next_planned: tuple | None = None + b.set_volume(self.volume) + dev = settings.get("playback/device") + if dev: + b.set_device(dev) + self.apply_audio_settings() + manager.queue_changed.connect(self.refresh_next) + + # ---------------------------------------------------------------- settings + def apply_audio_settings(self): + b = self.backend + b.set_eq(settings.get("playback/eq_enabled"), settings.get("playback/eq_preamp"), + settings.get("playback/eq_bands")) + if b.name == "mpv": + b.set_replaygain(settings.get("playback/replaygain"), settings.get("playback/rg_preamp")) + self._apply_rg() + + def _apply_rg(self): + if self.backend.name != "qt": + return + mode = settings.get("playback/replaygain") + s = self.song + g = 0.0 + if s and mode != "off": + g = (s.rg_album if mode == "album" and s.rg_album is not None else s.rg_track) or 0.0 + g += settings.get("playback/rg_preamp") + self.backend.set_gain(min(g, 0.0) if g else 0.0) + + # ---------------------------------------------------------------- commands + def play_song(self, pl: PlaylistModel, song: Song, start=0.0, paused=False): + self._finish_current(skipped=self.state != "stopped") + self.mgr.set_active(pl) + self.playlist = pl + pl.set_current(song) + self.song = song + self.pos, self.dur = start, song.duration() + self._played_marked = False + self._listen = 0.0 + self._start_ts = int(time.time()) + self._apply_rg() + nxt = self.mgr.peek_next(auto=True) + self._next_planned = nxt + self.backend.load(song, nxt[1] if nxt else None, start, paused) + self.song_changed.emit(song) + if not paused: + self.track_started.emit(song) + self.mgr.schedule_save() + + def refresh_next(self): + if self.song is None or self.state == "stopped": + return + nxt = self.mgr.peek_next(auto=True) + if nxt != self._next_planned: + self._next_planned = nxt + self.backend.set_next(nxt[1] if nxt else None) + + def play(self): + if self.state == "paused": + self.backend.play() + elif self.state == "stopped" or self.song is None: + pl = self.mgr.current + if pl is None or not pl.songs: + return + song = pl.current_song if pl.current_song in pl.songs else None + if song is None: + sel = getattr(pl, "selected_song", None) + song = sel or (pl.next_song(self.mgr.shuffle, "off") if self.mgr.shuffle else pl.songs[0]) + self.play_song(pl, song) + + def pause(self): + self.backend.pause() + + def play_pause(self): + if self.state == "playing": + self.pause() + else: + self.play() + + def stop(self): + self._finish_current(skipped=False) + self.backend.stop() + self.state = "stopped" + self.pos = 0 + self.state_changed.emit("stopped") + self.position_changed.emit(0, self.dur) + + def next(self): + res = self.mgr.take_next(auto=False) + if res: + self.play_song(*res) + else: + self.stop() + + def prev(self): + if self.pos > 4 and self.song: + self.seek(0) + return + res = self.mgr.prev() + if res: + self.play_song(*res) + + def seek(self, sec): + if not self.song: + return + sec = max(0.0, min(sec, self.dur or sec)) + self.backend.seek(self.song.begin + sec) + self.pos = sec + self.position_changed.emit(self.pos, self.dur) + self.seeked.emit(sec) + + def seek_relative(self, delta): + self.seek(self.pos + delta) + + def set_volume(self, v): + v = int(max(0, min(100, v))) + self.volume = v + self.backend.set_volume(v) + settings.set("playback/volume", v) + self.volume_changed.emit(v) + + def toggle_mute(self): + if self._muted_vol is None: + self._muted_vol = self.volume + self.set_volume(0) + else: + self.set_volume(self._muted_vol) + self._muted_vol = None + + def set_device(self, dev): + settings.set("playback/device", dev) + self.backend.set_device(dev) + + # ---------------------------------------------------------------- backend events + def _on_pos(self, sec): + if not self.song: + return + rel = max(0.0, sec - self.song.begin) + now = time.monotonic() + if self.state == "playing" and self._last_tick is not None: + dt = now - self._last_tick + if 0 < dt < 2: + self._listen += dt + self._last_tick = now + self.pos = rel + if rel > 1.0: + self._errors = 0 + self.position_changed.emit(rel, self.dur) + if not self._played_marked and self.dur > 0 and (rel > self.dur * 0.5 or rel > 240): + self._played_marked = True + L.library.mark_played(self.song) + + def _on_dur(self, d): + if self.song and not self.song.end: + d = d - self.song.begin + if d > 0: + self.dur = d + if not self.song.length or abs(self.song.length - d) > 2: + self.song.length = d + self.position_changed.emit(self.pos, self.dur) + + def _on_state(self, st): + if st == "loading": + return + if st == "stopped" and self.state == "stopped": + return + self._last_tick = time.monotonic() if st == "playing" else None + self.state = st + if self.playlist: + self.playlist.playing = st == "playing" + r = self.playlist.current_row() + if r >= 0: + self.playlist.dataChanged.emit(self.playlist.index(r, 0), self.playlist.index(r, 0)) + self.state_changed.emit(st) + + def _finish_current(self, skipped: bool): + if self.song is None: + return + if skipped and not self._played_marked and self.dur and self.pos < self.dur * 0.5: + L.library.mark_skipped(self.song) + if self._listen > 1: + self.track_finished.emit(self.song, self._listen, self._start_ts) + self._listen = 0.0 + + def _on_error(self, msg): + self._errors += 1 + self.message.emit(msg) + + def _on_ended(self): + if self._errors >= 5: + self._errors = 0 + self.message.emit("Stopped after several tracks failed to play") + self.song_ended_stop() + return + self._finish_current(skipped=False) + res = self.mgr.take_next(auto=True) + if res: + self.song = None + self.play_song(*res) + else: + self.song_ended_stop() + + def song_ended_stop(self): + self.backend.stop() + self.state = "stopped" + self.pos = 0 + self.state_changed.emit("stopped") + self.position_changed.emit(0, self.dur) + + def _on_advanced(self): + self._finish_current(skipped=False) + res = self.mgr.take_next(auto=True) + if not res: + return + pl, song = res + self.mgr.set_active(pl) + self.playlist = pl + pl.set_current(song) + self.song = song + self.pos, self.dur = 0.0, song.duration() + self._played_marked = False + self._start_ts = int(time.time()) + self._apply_rg() + self.song_changed.emit(song) + self.track_started.emit(song) + nxt = self.mgr.peek_next(auto=True) + self._next_planned = nxt + self.backend.set_next(nxt[1] if nxt else None) + + def _on_stream_meta(self, md): + if self.song and self.song.is_stream: + t = md.get("stream_title", "") + if t and t != self.song.stream_title: + self.song.stream_title = t + self.stream_title.emit(t) + self.song_changed.emit(self.song) + self.track_started.emit(self.song) + + def shutdown(self): + self._finish_current(skipped=False) + self.backend.shutdown() + + +def db_to_lin(db): + return math.pow(10, db / 20) diff --git a/mulberry/playlist.py b/mulberry/playlist.py new file mode 100644 index 0000000..30bdc6a --- /dev/null +++ b/mulberry/playlist.py @@ -0,0 +1,700 @@ +"""Playlist models (multi-tab), queue, shuffle/repeat logic and undo.""" +from __future__ import annotations + +import json +import os +import random +import time +import urllib.parse + +from PyQt6.QtCore import (QAbstractTableModel, QMimeData, QModelIndex, QObject, Qt, QTimer, + QUrl, pyqtSignal) +from PyQt6.QtGui import QFont, QUndoCommand, QUndoStack + +from . import library as L +from .config import fmt_time, settings +from .song import Song + +ROWS_MIME = "application/x-mulberry-rows" +SONGS_MIME = "application/x-mulberry-songs" + +# key, header, default visible, width +COLUMNS = [ + ("track", "#", True, 44), + ("title", "Title", True, 240), + ("artist", "Artist", True, 170), + ("album", "Album", True, 220), + ("albumartist", "Album artist", False, 150), + ("year", "Year", False, 56), + ("genre", "Genre", False, 110), + ("composer", "Composer", False, 120), + ("disc", "Disc", False, 44), + ("length", "Length", True, 64), + ("bitrate", "Bitrate", False, 70), + ("samplerate", "Sample rate", False, 86), + ("bitdepth", "Bit depth", False, 64), + ("filetype", "File type", True, 84), + ("filesize", "Size", False, 74), + ("playcount", "Plays", False, 54), + ("skipcount", "Skips", False, 54), + ("lastplayed", "Last played", False, 120), + ("rating", "Rating", False, 96), + ("added", "Date added", False, 110), + ("source", "Source", True, 64), + ("url", "Path", False, 300), +] +COL_KEYS = [c[0] for c in COLUMNS] +COL = {k: i for i, k in enumerate(COL_KEYS)} + + +def _size(n): + for unit in ("B", "KB", "MB", "GB"): + if n < 1024: + return f"{n:.0f} {unit}" if unit == "B" else f"{n:.1f} {unit}" + n /= 1024 + return f"{n:.1f} TB" + + +def _date(ts): + return time.strftime("%Y-%m-%d %H:%M", time.localtime(ts)) if ts else "" + + +class _Snapshot(QUndoCommand): + def __init__(self, model, before, after, text): + super().__init__(text) + self.model, self.before, self.after = model, before, after + self._first = True + + def redo(self): + if self._first: + self._first = False + return + self.model._set_songs(list(self.after)) + + def undo(self): + self.model._set_songs(list(self.before)) + + +class PlaylistModel(QAbstractTableModel): + changed = pyqtSignal() # content changed (for persistence/status) + + def __init__(self, name="Playlist", songs=None, pid=-1, favorite=False): + super().__init__() + self.name = name + self.pid = pid + self.favorite = favorite + self.songs: list[Song] = list(songs or []) + self.current_song: Song | None = None + self.playing = False + self.undo = QUndoStack(self) + self.undo.setUndoLimit(40) + self.queue_pos: dict[int, int] = {} # id(song) -> queue position (1-based) + self._shuffle: list[Song] = [] + self.filter_text = "" + self.dirty = pid < 0 + self.changed.connect(lambda: setattr(self, "dirty", True)) + + # ---------------------------------------------------------- Qt model api + def rowCount(self, parent=QModelIndex()): + return 0 if parent.isValid() else len(self.songs) + + def columnCount(self, parent=QModelIndex()): + return len(COLUMNS) + + def headerData(self, section, orient, role=Qt.ItemDataRole.DisplayRole): + if orient == Qt.Orientation.Horizontal and role == Qt.ItemDataRole.DisplayRole: + return COLUMNS[section][1] + return None + + def data(self, index, role=Qt.ItemDataRole.DisplayRole): + if not index.isValid(): + return None + s = self.songs[index.row()] + key = COL_KEYS[index.column()] + if role == Qt.ItemDataRole.DisplayRole: + return self.display(s, key) + if role == Qt.ItemDataRole.UserRole: + return s + if role == Qt.ItemDataRole.TextAlignmentRole: + if key in ("track", "disc", "year", "length", "bitrate", "samplerate", "bitdepth", + "filesize", "playcount", "skipcount"): + return int(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter) + return int(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter) + if role == Qt.ItemDataRole.FontRole and s is self.current_song: + f = QFont() + f.setWeight(QFont.Weight.DemiBold) + return f + if role == Qt.ItemDataRole.ToolTipRole and key in ("title", "url"): + return s.url + return None + + def display(self, s: Song, key: str): + if key == "title": + t = s.display_title() + q = self.queue_pos.get(id(s)) + return f"({q}) {t}" if q else t + if key == "track": + return str(s.track) if s.track else "" + if key == "disc": + return str(s.disc) if s.disc else "" + if key == "year": + return str(s.year) if s.year else "" + if key == "length": + d = s.duration() + return fmt_time(d) if d else "" + if key == "bitrate": + return f"{s.bitrate} kbps" if s.bitrate else "" + if key == "samplerate": + return f"{s.samplerate / 1000:g} kHz" if s.samplerate else "" + if key == "bitdepth": + return f"{s.bitdepth}-bit" if s.bitdepth else "" + if key == "filesize": + return _size(s.filesize) if s.filesize else "" + if key in ("lastplayed", "added"): + return _date(getattr(s, key)) + if key in ("playcount", "skipcount"): + v = getattr(s, key) + return str(v) if v else "" + if key == "rating": + return "" + if key == "source": + return "" + if key == "url": + return s.path if s.is_local else s.url + return getattr(s, key, "") + + def flags(self, index): + f = Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsDropEnabled + if index.isValid(): + f |= Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsDragEnabled + return f + + def supportedDropActions(self): + return Qt.DropAction.MoveAction | Qt.DropAction.CopyAction + + def mimeTypes(self): + return [ROWS_MIME, SONGS_MIME, "text/uri-list"] + + def mimeData(self, indexes): + rows = sorted({i.row() for i in indexes}) + md = QMimeData() + md.setData(ROWS_MIME, json.dumps({"model": id(self), "rows": rows}).encode()) + urls = [QUrl.fromLocalFile(self.songs[r].path) if self.songs[r].is_local else QUrl(self.songs[r].url) + for r in rows] + md.setUrls(urls) + return md + + def canDropMimeData(self, data, action, row, column, parent): + return any(data.hasFormat(m) for m in (ROWS_MIME, SONGS_MIME, "text/uri-list")) + + def dropMimeData(self, data, action, row, column, parent): + if row < 0: + row = parent.row() if parent.isValid() else len(self.songs) + if data.hasFormat(ROWS_MIME): + info = json.loads(bytes(data.data(ROWS_MIME)).decode()) + if info.get("model") == id(self): + self.move_rows(info["rows"], row) + return True + if data.hasFormat(SONGS_MIME): + dicts = json.loads(bytes(data.data(SONGS_MIME)).decode()) + self.insert_songs([Song.from_dict(d) for d in dicts], row) + return True + if data.hasUrls(): + paths, streams = [], [] + for u in data.urls(): + if u.isLocalFile(): + paths.append(u.toLocalFile()) + else: + streams.append(Song(url=u.toString())) + if streams: + self.insert_songs(streams, row) + if paths: + PlaylistManager.instance.add_paths(paths, self, row) + return True + return False + + # ---------------------------------------------------------- mutation + def _set_songs(self, songs): + self.beginResetModel() + self.songs = songs + self._shuffle = [] + self.endResetModel() + self.changed.emit() + + def _commit(self, before, text): + self.undo.push(_Snapshot(self, before, list(self.songs), text)) + self._shuffle = [] + self.changed.emit() + + def insert_songs(self, songs: list[Song], row: int = -1): + if not songs: + return + if row < 0 or row > len(self.songs): + row = len(self.songs) + before = list(self.songs) + self.beginInsertRows(QModelIndex(), row, row + len(songs) - 1) + self.songs[row:row] = songs + self.endInsertRows() + self._commit(before, f"Add {len(songs)} songs") + + def remove_rows(self, rows): + rows = sorted(set(rows), reverse=True) + if not rows: + return + before = list(self.songs) + for r in rows: + if 0 <= r < len(self.songs): + self.beginRemoveRows(QModelIndex(), r, r) + del self.songs[r] + self.endRemoveRows() + self._commit(before, f"Remove {len(rows)} songs") + + def move_rows(self, rows, dest): + rows = sorted(set(rows)) + before = list(self.songs) + moving = [self.songs[r] for r in rows] + dest -= sum(1 for r in rows if r < dest) + rest = [s for i, s in enumerate(self.songs) if i not in set(rows)] + rest[dest:dest] = moving + self.beginResetModel() + self.songs = rest + self.endResetModel() + self._commit(before, "Move songs") + + def clear(self): + if not self.songs: + return + before = list(self.songs) + self.beginResetModel() + self.songs = [] + self.endResetModel() + self._commit(before, "Clear playlist") + + def replace(self, songs): + before = list(self.songs) + self.beginResetModel() + self.songs = list(songs) + self.endResetModel() + self._commit(before, "Replace playlist") + + def sort(self, column, order=Qt.SortOrder.AscendingOrder): + key = COL_KEYS[column] + before = list(self.songs) + + def k(s: Song): + if key in ("title",): + return s.display_title().lower() + if key in ("album",): + return (s.album.lower(), s.disc, s.track) + if key in ("artist", "albumartist"): + return (getattr(s, key).lower(), s.album.lower(), s.disc, s.track) + if key == "length": + return s.duration() + if key == "url": + return s.url.lower() + if key == "source": + return s.source + v = getattr(s, key, "") + return v.lower() if isinstance(v, str) else (v or 0) + self.layoutAboutToBeChanged.emit() + self.songs.sort(key=k, reverse=order == Qt.SortOrder.DescendingOrder) + self.layoutChanged.emit() + self._commit(before, "Sort") + + def shuffle_items(self): + before = list(self.songs) + self.beginResetModel() + random.shuffle(self.songs) + self.endResetModel() + self._commit(before, "Shuffle playlist") + + def remove_duplicates(self): + seen, keep = set(), [] + for s in self.songs: + k = s.key() + if k not in seen: + seen.add(k) + keep.append(s) + if len(keep) != len(self.songs): + self.replace(keep) + + def remove_unavailable(self): + keep = [s for s in self.songs if not s.is_local or os.path.exists(s.path)] + if len(keep) != len(self.songs): + self.replace(keep) + + def refresh_song(self, song: Song): + for i, s in enumerate(self.songs): + if s is song or (song.id >= 0 and s.id == song.id) or (s.url == song.url and s.begin == song.begin): + if s is not song: + self.songs[i] = song + if self.current_song is s: + self.current_song = song + self.dataChanged.emit(self.index(i, 0), self.index(i, len(COLUMNS) - 1)) + + # ---------------------------------------------------------- current / order + def row_of(self, song: Song | None) -> int: + if song is None: + return -1 + for i, s in enumerate(self.songs): + if s is song: + return i + return -1 + + def current_row(self) -> int: + return self.row_of(self.current_song) + + def set_current(self, song: Song | None): + old = self.current_row() + self.current_song = song + new = self.current_row() + for r in (old, new): + if r >= 0: + self.dataChanged.emit(self.index(r, 0), self.index(r, len(COLUMNS) - 1)) + + def _ensure_shuffle(self): + if len(self._shuffle) != len(self.songs) or set(map(id, self._shuffle)) != set(map(id, self.songs)): + order = list(self.songs) + random.shuffle(order) + if self.current_song in order: + order.remove(self.current_song) + order.insert(0, self.current_song) + self._shuffle = order + + def next_song(self, shuffle: bool, repeat: str) -> Song | None: + if not self.songs: + return None + if shuffle: + self._ensure_shuffle() + seq = self._shuffle + else: + seq = self.songs + cur = self.current_song + idx = -1 + if cur is not None: + for i, s in enumerate(seq): + if s is cur: + idx = i + break + nxt = idx + 1 + if nxt >= len(seq): + if repeat == "playlist": + if shuffle: + self._shuffle = [] + self._ensure_shuffle() + seq = self._shuffle + nxt = 0 + else: + return None + return seq[nxt] + + def prev_song(self, shuffle: bool) -> Song | None: + if not self.songs: + return None + seq = self._shuffle if shuffle and self._shuffle else self.songs + cur = self.current_song + for i, s in enumerate(seq): + if s is cur: + return seq[i - 1] if i > 0 else seq[-1] + return seq[0] + + def total_length(self) -> float: + return sum(s.duration() for s in self.songs) + + +class PlaylistManager(QObject): + instance: "PlaylistManager" = None + added = pyqtSignal(object) + removed = pyqtSignal(object) + renamed = pyqtSignal(object) + current_changed = pyqtSignal(object) # visible playlist + active_changed = pyqtSignal(object) # playing playlist + queue_changed = pyqtSignal() + summary_changed = pyqtSignal() + busy = pyqtSignal(bool) + + def __init__(self): + super().__init__() + PlaylistManager.instance = self + self.playlists: list[PlaylistModel] = [] + self.current: PlaylistModel | None = None + self.active: PlaylistModel | None = None + self.queue: list[tuple[PlaylistModel, Song]] = [] + self.shuffle = settings.get("playback/shuffle") + self.repeat = settings.get("playback/repeat") + self.stop_after: Song | None = None + self._save_timer = QTimer(self, singleShot=True, interval=1500) + self._save_timer.timeout.connect(self.save_all) + + # ---------------------------------------------------------- persistence + @staticmethod + def _refresh_from_library(songs: list[Song]) -> list[Song]: + """Library songs in saved playlists get fresh tags/stats from the DB.""" + ids = [s.id for s in songs if s.id >= 0 and not s.begin] + if not ids: + return songs + fresh = {} + for i in range(0, len(ids), 900): + chunk = ids[i:i + 900] + for r in L.library.query(f"SELECT * FROM songs WHERE id IN ({','.join('?' * len(chunk))})", chunk): + fresh[r["id"]] = L.row_to_song(r) + return [fresh.get(s.id, s) if s.id >= 0 and not s.begin else s for s in songs] + + def restore(self): + rows = L.library.load_playlists() + for r in rows: + if not r["is_open"]: + continue + try: + songs = self._refresh_from_library([Song.from_dict(d) for d in json.loads(r["items"] or "[]")]) + except (ValueError, TypeError): + songs = [] + pl = self._make(r["name"], songs, r["id"], bool(r["favorite"])) + if 0 <= r["current"] < len(songs): + pl.current_song = songs[r["current"]] + if not self.playlists: + self.new_playlist("Playlist") + active_id = L.library.kv("active_playlist") + cur_id = L.library.kv("current_playlist") + self.active = next((p for p in self.playlists if str(p.pid) == active_id), self.playlists[0]) + self.set_current(next((p for p in self.playlists if str(p.pid) == cur_id), self.playlists[0])) + + def schedule_save(self): + self._save_timer.start() + + def save_all(self): + for i, p in enumerate(self.playlists): + if p.dirty or p.pid < 0: + p.pid = L.library.save_playlist(p.pid, p.name, p.songs, ui_order=i, is_open=1, + current=p.current_row(), favorite=int(p.favorite)) + p.dirty = False + else: + L.library.update_playlist_meta(p.pid, p.name, i, p.current_row(), int(p.favorite)) + if self.active: + L.library.set_kv("active_playlist", self.active.pid) + if self.current: + L.library.set_kv("current_playlist", self.current.pid) + + # ---------------------------------------------------------- playlists + def _make(self, name, songs=None, pid=-1, favorite=False) -> PlaylistModel: + pl = PlaylistModel(name, songs, pid, favorite) + pl.changed.connect(self.schedule_save) + pl.changed.connect(self.summary_changed) + self.playlists.append(pl) + self.added.emit(pl) + return pl + + def new_playlist(self, name=None, songs=None, activate=True) -> PlaylistModel: + if not name: + n = len(self.playlists) + 1 + name = f"Playlist {n}" + pl = self._make(name, songs) + pl.pid = L.library.save_playlist(None, pl.name, pl.songs, ui_order=len(self.playlists)) + if activate: + self.set_current(pl) + return pl + + def close_playlist(self, pl: PlaylistModel, keep_saved: bool | None = None): + if pl not in self.playlists: + return + if keep_saved is None: + keep_saved = pl.favorite + if keep_saved: + L.library.save_playlist(pl.pid, pl.name, pl.songs, is_open=0, favorite=1, + current=pl.current_row()) + else: + L.library.delete_playlist(pl.pid) + idx = self.playlists.index(pl) + self.playlists.remove(pl) + self.queue = [q for q in self.queue if q[0] is not pl] + self.removed.emit(pl) + if not self.playlists: + self.new_playlist("Playlist") + if self.current is pl: + self.set_current(self.playlists[min(idx, len(self.playlists) - 1)]) + if self.active is pl: + self.active = self.current + self.schedule_save() + + def reopen_saved(self, pid: int): + for p in self.playlists: + if p.pid == pid: + self.set_current(p) + return p + r = L.library.query("SELECT * FROM playlists WHERE id=?", (pid,)) + if not r: + return None + r = r[0] + songs = self._refresh_from_library([Song.from_dict(d) for d in json.loads(r["items"] or "[]")]) + pl = self._make(r["name"], songs, r["id"], bool(r["favorite"])) + if 0 <= (r["current"] or -1) < len(songs): + pl.current_song = songs[r["current"]] + self.set_current(pl) + self.schedule_save() + return pl + + def rename(self, pl, name): + pl.name = name + self.renamed.emit(pl) + self.schedule_save() + + def set_current(self, pl): + if pl is self.current: + return + self.current = pl + self.current_changed.emit(pl) + self.summary_changed.emit() + + def set_active(self, pl): + if pl is not self.active: + if self.active: + self.active.playing = False + self.active = pl + self.active_changed.emit(pl) + + def move_playlist(self, frm, to): + pl = self.playlists.pop(frm) + self.playlists.insert(to, pl) + self.schedule_save() + + # ---------------------------------------------------------- adding + def add_paths(self, paths, pl=None, row=-1, play=False, replace=False): + pl = pl or self.current + self.busy.emit(True) + + def work(): + from .playlistio import import_playlist + out = [] + plain = [] + for p in paths: + ext = os.path.splitext(p)[1].lower().lstrip(".") + if ext in PLAYLIST_EXTS_SET and os.path.isfile(p): + if plain: + out += L.scan_paths(plain) + plain = [] + out += enrich(import_playlist(p)) + else: + plain.append(p) + if plain: + out += L.scan_paths(plain) + return out + + def done(songs): + self.busy.emit(False) + if pl not in self.playlists: + return + if replace: + pl.replace(songs) + else: + pl.insert_songs(songs, row) + if play and songs: + from .player import Player + self.set_current(pl) + Player.instance.play_song(pl, songs[0]) + from .config import run_async + run_async(work, on_done=done, on_error=lambda e: self.busy.emit(False)) + + def add_songs(self, songs, pl=None, play=False, replace=False, row=-1): + pl = pl or self.current + if replace: + pl.replace(songs) + else: + pl.insert_songs(songs, row) + if play and songs: + from .player import Player + Player.instance.play_song(pl, songs[0]) + + # ---------------------------------------------------------- queue + def enqueue(self, pl, songs, front=False): + items = [(pl, s) for s in songs] + self.queue = items + self.queue if front else self.queue + items + self._update_queue_marks() + + def dequeue(self, song): + self.queue = [q for q in self.queue if q[1] is not song] + self._update_queue_marks() + + def clear_queue(self): + self.queue = [] + self._update_queue_marks() + + def _update_queue_marks(self): + for p in self.playlists: + p.queue_pos = {} + for i, (p, s) in enumerate(self.queue, 1): + p.queue_pos[id(s)] = i + for p in self.playlists: + if p.songs: + p.dataChanged.emit(p.index(0, COL["title"]), p.index(len(p.songs) - 1, COL["title"])) + self.queue_changed.emit() + + # ---------------------------------------------------------- navigation + def peek_next(self, auto=True): + """Return (playlist, song) that would play next, without consuming the queue.""" + pl = self.active or self.current + if pl is None: + return None + cur = pl.current_song + if auto and self.stop_after is not None and cur is self.stop_after: + return None + if auto and self.repeat == "track" and cur is not None: + return pl, cur + for qpl, s in self.queue: + if qpl in self.playlists and qpl.row_of(s) >= 0: + return qpl, s + nxt = pl.next_song(self.shuffle, self.repeat) + return (pl, nxt) if nxt else None + + def take_next(self, auto=True): + res = self.peek_next(auto) + if res and self.queue and self.queue[0][1] is res[1]: + self.queue.pop(0) + self._update_queue_marks() + elif res: + # skip stale queue entries + while self.queue and (self.queue[0][0] not in self.playlists or self.queue[0][0].row_of(self.queue[0][1]) < 0): + self.queue.pop(0) + if auto and self.stop_after is not None and res is None: + self.stop_after = None + return res + + def prev(self): + pl = self.active or self.current + if not pl: + return None + s = pl.prev_song(self.shuffle) + return (pl, s) if s else None + + def set_shuffle(self, on: bool): + self.shuffle = on + settings.set("playback/shuffle", on) + for p in self.playlists: + p._shuffle = [] + + def set_repeat(self, mode: str): + self.repeat = mode + settings.set("playback/repeat", mode) + + +PLAYLIST_EXTS_SET = {"m3u", "m3u8", "pls", "xspf", "wpl", "asx", "cue"} + + +def enrich(songs: list[Song]) -> list[Song]: + """Replace bare playlist entries with full tag info (library or file).""" + plain = [s for s in songs if s.is_local and not s.begin and not s.end] + if not plain: + return songs + found = {s.url: s for s in L.scan_paths([s.path for s in plain if os.path.exists(s.path)])} + out = [] + for s in songs: + if s.is_local and not s.begin and not s.end and s.path in found: + out.append(found[s.path]) + else: + out.append(s) + return out + + +def url_to_path(u: str) -> str: + if u.startswith("file://"): + return urllib.parse.unquote(urllib.parse.urlparse(u).path) + return u diff --git a/mulberry/playlistio.py b/mulberry/playlistio.py new file mode 100644 index 0000000..3bd5fe6 --- /dev/null +++ b/mulberry/playlistio.py @@ -0,0 +1,286 @@ +"""Playlist import/export: M3U, M3U8, PLS, XSPF, WPL, ASX (import), CUE (import).""" +from __future__ import annotations + +import os +import re +import urllib.parse +import xml.etree.ElementTree as ET +from pathlib import Path +from xml.sax.saxutils import escape + +from .song import Song + +EXPORT_FILTERS = ("M3U8 playlist (*.m3u8);;M3U playlist (*.m3u);;PLS playlist (*.pls);;" + "XSPF playlist (*.xspf);;Windows Media playlist (*.wpl)") +IMPORT_FILTER = "Playlists (*.m3u *.m3u8 *.pls *.xspf *.wpl *.asx *.cue);;All files (*)" + + +def _resolve(entry: str, base: Path) -> str: + entry = entry.strip() + if not entry: + return "" + if entry.startswith("file://"): + return urllib.parse.unquote(urllib.parse.urlparse(entry).path) + if re.match(r"^[a-z][a-z0-9+.-]*://", entry, re.I): + return entry + entry = entry.replace("\\", "/") + p = Path(entry) + if not p.is_absolute(): + p = (base / p) + try: + return str(p.resolve()) + except OSError: + return str(p) + + +def _read_text(path: str) -> str: + raw = Path(path).read_bytes() + for enc in ("utf-8-sig", "utf-16", "cp1252", "latin-1"): + try: + return raw.decode(enc) + except UnicodeDecodeError: + continue + return raw.decode("utf-8", "replace") + + +def import_playlist(path: str) -> list[Song]: + ext = Path(path).suffix.lower() + base = Path(path).parent + text = _read_text(path) + if ext in (".m3u", ".m3u8"): + return _m3u(text, base) + if ext == ".pls": + return _pls(text, base) + if ext == ".xspf": + return _xspf(text, base) + if ext in (".wpl", ".asx"): + return _xmlrefs(text, base) + if ext == ".cue": + return parse_cue(text, base) + # guess + if text.lstrip().startswith("<"): + return _xspf(text, base) or _xmlrefs(text, base) + return _m3u(text, base) + + +def _m3u(text, base): + out, info = [], None + for line in text.splitlines(): + line = line.strip() + if not line: + continue + if line.startswith("#EXTINF:"): + m = re.match(r"#EXTINF:\s*(-?\d+(?:\.\d+)?)[^,]*,(.*)", line) + if m: + info = (float(m.group(1)), m.group(2).strip()) + continue + if line.startswith("#"): + continue + s = Song(url=_resolve(line, base)) + if info: + s.length = max(info[0], 0) + if " - " in info[1]: + s.artist, s.title = [x.strip() for x in info[1].split(" - ", 1)] + else: + s.title = info[1] + info = None + out.append(s) + return out + + +def _pls(text, base): + files, titles, lengths = {}, {}, {} + for line in text.splitlines(): + m = re.match(r"\s*(File|Title|Length)(\d+)\s*=\s*(.*)", line, re.I) + if not m: + continue + kind, n, val = m.group(1).lower(), int(m.group(2)), m.group(3).strip() + {"file": files, "title": titles, "length": lengths}[kind][n] = val + out = [] + for n in sorted(files): + s = Song(url=_resolve(files[n], base), title=titles.get(n, "")) + try: + s.length = max(float(lengths.get(n, 0)), 0) + except ValueError: + pass + out.append(s) + return out + + +def _strip_ns(root): + for el in root.iter(): + if isinstance(el.tag, str) and "}" in el.tag: + el.tag = el.tag.split("}", 1)[1] + return root + + +def _xspf(text, base): + try: + root = _strip_ns(ET.fromstring(text)) + except ET.ParseError: + return [] + out = [] + for tr in root.iter("track"): + loc = tr.findtext("location") + if not loc: + continue + s = Song(url=_resolve(loc, base), title=tr.findtext("title") or "", + artist=tr.findtext("creator") or "", album=tr.findtext("album") or "") + try: + s.length = int(tr.findtext("duration") or 0) / 1000 + s.track = int(tr.findtext("trackNum") or 0) + except ValueError: + pass + out.append(s) + return out + + +def _xmlrefs(text, base): + try: + root = _strip_ns(ET.fromstring(text)) + except ET.ParseError: + # ASX is often not valid XML (uppercase tags); fall back to regex + return [Song(url=_resolve(u, base)) for u in re.findall(r'(?:href|src)\s*=\s*"([^"]+)"', text, re.I)] + out = [] + for el in root.iter(): + tag = el.tag.lower() if isinstance(el.tag, str) else "" + if tag == "media" and el.get("src"): + out.append(Song(url=_resolve(el.get("src"), base))) + elif tag == "ref": + href = el.get("href") or el.get("HREF") + if href: + out.append(Song(url=_resolve(href, base))) + return out + + +def parse_cue(text: str, base: Path) -> list[Song]: + """Parse a cue sheet into songs with begin/end offsets.""" + album = performer = genre = "" + year = 0 + cur_file = "" + tracks = [] # dicts + cur = None + for raw in text.splitlines(): + line = raw.strip() + m = re.match(r'(\w+)\s+(.*)', line) + if not m: + continue + cmd, rest = m.group(1).upper(), m.group(2) + val = rest.strip() + if val.startswith('"'): + val = val[1:val.find('"', 1)] if '"' in val[1:] else val.strip('"') + if cmd == "REM": + mm = re.match(r'(GENRE|DATE)\s+"?([^"]*)"?', rest, re.I) + if mm and mm.group(1).upper() == "GENRE": + genre = mm.group(2) + elif mm: + year = int(re.sub(r"\D", "", mm.group(2))[:4] or 0) + elif cmd == "FILE": + q = re.match(r'"([^"]+)"|(\S+)', rest) + cur_file = _resolve(q.group(1) or q.group(2), base) + elif cmd == "TRACK": + cur = {"file": cur_file, "track": int(re.match(r"\d+", val).group()), "title": "", + "performer": "", "begin": None} + tracks.append(cur) + elif cmd == "TITLE": + if cur is None: + album = val + else: + cur["title"] = val + elif cmd == "PERFORMER": + if cur is None: + performer = val + else: + cur["performer"] = val + elif cmd == "INDEX" and cur is not None: + mm = re.match(r"(\d+)\s+(\d+):(\d+):(\d+)", val) + if mm and int(mm.group(1)) == 1: + cur["begin"] = int(mm.group(2)) * 60 + int(mm.group(3)) + int(mm.group(4)) / 75 + out = [] + for i, t in enumerate(tracks): + if t["begin"] is None: + continue + end = 0.0 + if i + 1 < len(tracks) and tracks[i + 1]["file"] == t["file"] and tracks[i + 1]["begin"] is not None: + end = tracks[i + 1]["begin"] + s = Song(url=t["file"], title=t["title"], artist=t["performer"] or performer, album=album, + albumartist=performer, genre=genre, year=year, track=t["track"], begin=t["begin"], end=end) + if end: + s.length = end - t["begin"] + out.append(s) + # fill length of last track(s) from the file + if out: + try: + import mutagen + lens = {} + for s in out: + if not s.end and s.url not in lens and os.path.exists(s.url): + f = mutagen.File(s.url) + lens[s.url] = float(f.info.length) if f else 0 + if not s.end and lens.get(s.url): + s.length = lens[s.url] - s.begin + s.filetype = Path(s.url).suffix.lstrip(".").upper() + except Exception: # noqa: BLE001 + pass + return out + + +# ------------------------------------------------------------------ export +def _entry(s: Song, base: Path, relative: bool) -> str: + if not s.is_local: + return s.url + if relative: + try: + return os.path.relpath(s.path, base) + except ValueError: + return s.path + return s.path + + +def export_playlist(path: str, songs: list[Song], relative=True): + ext = Path(path).suffix.lower() + base = Path(path).parent + songs = [s for s in songs if not s.is_cd] + if ext in (".m3u", ".m3u8", ""): + lines = ["#EXTM3U"] + for s in songs: + lines.append(f"#EXTINF:{int(s.duration() or -1)},{s.display_artist()} - {s.display_title()}" + if s.display_artist() else f"#EXTINF:{int(s.duration() or -1)},{s.display_title()}") + lines.append(_entry(s, base, relative)) + enc = "utf-8" if ext != ".m3u" else "utf-8" + Path(path).write_text("\n".join(lines) + "\n", encoding=enc) + elif ext == ".pls": + lines = ["[playlist]"] + for i, s in enumerate(songs, 1): + lines += [f"File{i}={_entry(s, base, relative)}", f"Title{i}={s.display_title()}", + f"Length{i}={int(s.duration() or -1)}"] + lines += [f"NumberOfEntries={len(songs)}", "Version=2"] + Path(path).write_text("\n".join(lines) + "\n", encoding="utf-8") + elif ext == ".xspf": + parts = ['', + '', " "] + for s in songs: + loc = Path(s.path).as_uri() if s.is_local and os.path.isabs(s.path) else s.url + parts.append(" ") + parts.append(f" {escape(loc)}") + for tag, val in (("title", s.display_title()), ("creator", s.display_artist()), ("album", s.album)): + if val: + parts.append(f" <{tag}>{escape(val)}") + if s.track: + parts.append(f" {s.track}") + if s.duration(): + parts.append(f" {int(s.duration() * 1000)}") + if s.art and os.path.exists(s.art): + parts.append(f" {escape(Path(s.art).as_uri())}") + parts.append(" ") + parts += [" ", ""] + Path(path).write_text("\n".join(parts) + "\n", encoding="utf-8") + elif ext == ".wpl": + parts = ['', "", " ", + f" {escape(Path(path).stem)}", " ", " ", " "] + for s in songs: + parts.append(f' ') + parts += [" ", " ", ""] + Path(path).write_text("\n".join(parts) + "\n", encoding="utf-8") + else: + raise ValueError(f"Unknown playlist format: {ext}") diff --git a/mulberry/scrobble.py b/mulberry/scrobble.py new file mode 100644 index 0000000..6bc6777 --- /dev/null +++ b/mulberry/scrobble.py @@ -0,0 +1,272 @@ +"""Last.fm and ListenBrainz scrobbling with an offline cache.""" +from __future__ import annotations + +import hashlib +import json +import threading +import time + +from PyQt6.QtCore import QObject, QTimer, pyqtSignal + +from .config import SCROBBLE_CACHE, run_async, settings +from .online import http_get, http_post +from .song import Song + +LFM_API = "https://ws.audioscrobbler.com/2.0/" + + +class LastFMError(RuntimeError): + code = 0 + + +def app_credentials() -> tuple[str, str]: + """Bundled application key (see lastfm_app.py), env vars, or json file.""" + import os + from . import lastfm_app + from .config import CONFIG_DIR + key = os.environ.get("MULBERRY_LASTFM_KEY") or lastfm_app.API_KEY + sec = os.environ.get("MULBERRY_LASTFM_SECRET") or lastfm_app.API_SECRET + if not (key and sec): + try: + d = json.loads((CONFIG_DIR / "lastfm_app.json").read_text()) + key, sec = d.get("key", ""), d.get("secret", "") + except (OSError, ValueError): + pass + return key or "", sec or "" + + +class LastFM: + @staticmethod + def key(): + own = settings.get("lastfm/use_own_key") + uk, us = settings.get("lastfm/api_key"), settings.get("lastfm/api_secret") + if own and uk and us: + return uk, us + ak, asec = app_credentials() + if ak and asec: + return ak, asec + return uk, us + + @staticmethod + def has_key() -> bool: + k, s = LastFM.key() + return bool(k and s) + + @classmethod + def sign(cls, params: dict) -> dict: + _, secret = cls.key() + s = "".join(f"{k}{params[k]}" for k in sorted(params) if k not in ("format", "callback")) + params["api_sig"] = hashlib.md5((s + secret).encode("utf-8")).hexdigest() + return params + + @classmethod + def call(cls, method: str, params: dict, post=True, auth=True): + key, _ = cls.key() + p = {"method": method, "api_key": key, **{k: str(v) for k, v in params.items() if v not in (None, "")}} + if auth: + p["sk"] = settings.get("lastfm/session") + cls.sign(p) + p["format"] = "json" + import urllib.error + try: + res = http_post(LFM_API, p) if post else http_get(LFM_API, p) + except urllib.error.HTTPError as e: + try: + res = json.loads(e.read().decode("utf-8", "replace")) + except (ValueError, OSError): + raise RuntimeError(f"Last.fm: HTTP {e.code}") from e + if "error" in res: + err = LastFMError(f"Last.fm: {res.get('message', res['error'])}") + err.code = int(res.get("error", 0)) + raise err + return res + + # ------------------------------------------------ desktop auth flow + @classmethod + def begin_auth(cls) -> str: + res = cls.call("auth.getToken", {}, post=False, auth=False) + return res["token"] + + @classmethod + def auth_url(cls, token: str) -> str: + key, _ = cls.key() + return f"https://www.last.fm/api/auth/?api_key={key}&token={token}" + + @classmethod + def finish_auth(cls, token: str) -> tuple[str, str]: + res = cls.call("auth.getSession", {"token": token}, post=False, auth=False) + sess = res["session"] + return sess["key"], sess["name"] + + @staticmethod + def track_params(s: Song, prefix="", idx=None): + sfx = f"[{idx}]" if idx is not None else "" + artist, title = s.display_artist(), s.display_title() + if s.is_stream and s.stream_title and " - " in s.stream_title: + artist, title = [x.strip() for x in s.stream_title.split(" - ", 1)] + p = {f"artist{sfx}": artist, f"track{sfx}": title} + if s.album and not s.is_stream: + p[f"album{sfx}"] = s.album + if s.albumartist and s.albumartist != s.artist: + p[f"albumArtist{sfx}"] = s.albumartist + if s.track: + p[f"trackNumber{sfx}"] = s.track + if s.duration(): + p[f"duration{sfx}"] = int(s.duration()) + if s.mb_trackid: + p[f"mbid{sfx}"] = s.mb_trackid + return p + + +class Scrobbler(QObject): + status = pyqtSignal(str) + loved_changed = pyqtSignal(bool) + + def __init__(self, player): + super().__init__() + self.player = player + self.lock = threading.Lock() + self.cache: list[dict] = self._load_cache() + player.track_started.connect(self._now_playing) + player.track_finished.connect(self._finished) + self.flush_timer = QTimer(self, interval=5 * 60 * 1000) + self.flush_timer.timeout.connect(self.flush) + self.flush_timer.start() + QTimer.singleShot(10_000, self.flush) + + # ------------------------------------------------ cache + def _load_cache(self): + try: + return json.loads(SCROBBLE_CACHE.read_text()) + except (OSError, ValueError): + return [] + + def _save_cache(self): + try: + SCROBBLE_CACHE.write_text(json.dumps(self.cache)) + except OSError: + pass + + @staticmethod + def lfm_on(): + return bool(settings.get("lastfm/enabled") and settings.get("lastfm/session") and LastFM.has_key()) + + @staticmethod + def lb_on(): + return settings.get("listenbrainz/enabled") and settings.get("listenbrainz/token") + + # ------------------------------------------------ events + def _now_playing(self, s: Song): + if s.is_cd and not s.title: + return + if self.lfm_on(): + run_async(LastFM.call, "track.updateNowPlaying", LastFM.track_params(s), + on_error=lambda e: self.status.emit(e)) + if self.lb_on(): + run_async(self._lb_submit, "playing_now", [self._lb_payload(s, None)], + on_error=lambda e: self.status.emit(e)) + + def _finished(self, s: Song, listened: float, started: int): + dur = s.duration() or 0 + if s.is_stream: + ok = listened >= 30 + else: + ok = dur >= 30 and (listened >= min(dur / 2, 240)) + if not ok: + return + if not s.display_artist() or not s.display_title(): + return + entry = {"song": s.to_dict(), "ts": started, "stream_title": s.stream_title} + with self.lock: + if self.lfm_on(): + self.cache.append({**entry, "svc": "lastfm"}) + if self.lb_on(): + self.cache.append({**entry, "svc": "listenbrainz"}) + self._save_cache() + self.flush() + + def flush(self): + if not self.cache: + return + run_async(self._flush_work, on_done=lambda n: n and self.status.emit(f"Scrobbled {n} track(s)"), + on_error=lambda e: self.status.emit(f"Scrobbling deferred: {e}")) + + def _flush_work(self): + sent = 0 + with self.lock: + pending = list(self.cache) + lfm = [e for e in pending if e["svc"] == "lastfm"][:50] + lb = [e for e in pending if e["svc"] == "listenbrainz"][:100] + done_ids = set() + if lfm and self.lfm_on(): + params = {} + for i, e in enumerate(lfm): + s = Song.from_dict(e["song"]) + s.stream_title = e.get("stream_title", "") + params.update(LastFM.track_params(s, idx=i)) + params[f"timestamp[{i}]"] = e["ts"] + LastFM.call("track.scrobble", params) + done_ids |= {id(e) for e in lfm} + sent += len(lfm) + if lb and self.lb_on(): + payload = [] + for e in lb: + s = Song.from_dict(e["song"]) + s.stream_title = e.get("stream_title", "") + payload.append(self._lb_payload(s, e["ts"])) + self._lb_submit("import" if len(payload) > 1 else "single", payload) + done_ids |= {id(e) for e in lb} + sent += len(lb) + with self.lock: + self.cache = [e for e in self.cache if id(e) not in done_ids] + self._save_cache() + return sent + + # ------------------------------------------------ ListenBrainz + @staticmethod + def _lb_payload(s: Song, ts): + artist, title = s.display_artist(), s.display_title() + if s.is_stream and s.stream_title and " - " in s.stream_title: + artist, title = [x.strip() for x in s.stream_title.split(" - ", 1)] + meta = {"artist_name": artist, "track_name": title} + if s.album: + meta["release_name"] = s.album + info = {"media_player": "Mulberry", "submission_client": "Mulberry", "submission_client_version": "1.0"} + if s.duration(): + info["duration_ms"] = int(s.duration() * 1000) + if s.mb_trackid: + info["recording_mbid"] = s.mb_trackid + if s.mb_albumid: + info["release_mbid"] = s.mb_albumid + meta["additional_info"] = info + p = {"track_metadata": meta} + if ts: + p["listened_at"] = int(ts) + return p + + @staticmethod + def _lb_submit(kind, payload): + body = json.dumps({"listen_type": kind, "payload": payload}).encode() + return http_post("https://api.listenbrainz.org/1/submit-listens", body, + headers={"Authorization": f"Token {settings.get('listenbrainz/token')}", + "Content-Type": "application/json"}) + + # ------------------------------------------------ love + def love(self, s: Song, loved: bool): + if self.lfm_on(): + run_async(LastFM.call, "track.love" if loved else "track.unlove", + {"artist": s.display_artist(), "track": s.display_title()}, + on_done=lambda _: self.status.emit("Loved on Last.fm" if loved else "Unloved on Last.fm"), + on_error=lambda e: self.status.emit(e)) + if self.lb_on() and s.mb_trackid: + body = json.dumps({"recording_mbid": s.mb_trackid, "score": 1 if loved else 0}).encode() + run_async(http_post, "https://api.listenbrainz.org/1/feedback/recording-feedback", body, + headers={"Authorization": f"Token {settings.get('listenbrainz/token')}", + "Content-Type": "application/json"}) + + def pending(self) -> int: + return len(self.cache) + + +def now() -> int: + return int(time.time()) diff --git a/mulberry/song.py b/mulberry/song.py new file mode 100644 index 0000000..7459aba --- /dev/null +++ b/mulberry/song.py @@ -0,0 +1,107 @@ +"""Song record shared by the library, playlists and the player.""" +from __future__ import annotations + +from dataclasses import asdict, dataclass, field, fields +from pathlib import Path + + +@dataclass(slots=True, eq=False) +class Song: + url: str = "" # local path, http(s)://, cdda:// + title: str = "" + artist: str = "" + album: str = "" + albumartist: str = "" + genre: str = "" + composer: str = "" + comment: str = "" + year: int = 0 + track: int = 0 + disc: int = 0 + length: float = 0.0 + bitrate: int = 0 + samplerate: int = 0 + bitdepth: int = 0 + channels: int = 0 + filetype: str = "" + filesize: int = 0 + mtime: float = 0.0 + art: str = "" # path to cover image (cache or folder) + id: int = -1 # library id + playcount: int = 0 + skipcount: int = 0 + lastplayed: int = 0 + rating: int = 0 # 0-5 + added: int = 0 + rg_track: float | None = None + rg_album: float | None = None + mb_trackid: str = "" + mb_albumid: str = "" + begin: float = 0.0 # cue / cd start (s) + end: float = 0.0 # cue / cd end (s), 0 = to end + cd_track: int = 0 + cd_device: str = "" + stream_title: str = field(default="", compare=False) + + # ---------------------------------------------------------------- helpers + @property + def is_local(self) -> bool: + return not ("://" in self.url) or self.url.startswith("file://") + + @property + def is_stream(self) -> bool: + return self.url.startswith(("http://", "https://", "mms://", "rtsp://", "rtmp://")) + + @property + def is_cd(self) -> bool: + return self.url.startswith("cdda://") + + @property + def path(self) -> str: + if self.url.startswith("file://"): + import urllib.parse + import urllib.request + p = urllib.parse.urlparse(self.url) + return urllib.request.url2pathname(urllib.parse.unquote(p.path)) + return self.url + + @property + def source(self) -> str: + if self.is_cd: + return "cd" + if self.is_stream: + return "stream" + return "collection" if self.id >= 0 else "file" + + def display_title(self) -> str: + if self.title: + return self.title + if self.stream_title: + return self.stream_title + if self.is_local: + return Path(self.path).stem + return self.url + + def display_artist(self) -> str: + return self.artist or self.albumartist + + def effective_albumartist(self) -> str: + return self.albumartist or self.artist + + def duration(self) -> float: + if self.end and self.end > self.begin: + return self.end - self.begin + return self.length + + def to_dict(self) -> dict: + d = asdict(self) + # keep the stored json compact + return {k: v for k, v in d.items() if v not in ("", 0, 0.0, None, -1) or k == "url"} + + @classmethod + def from_dict(cls, d: dict) -> "Song": + names = {f.name for f in fields(cls)} + return cls(**{k: v for k, v in d.items() if k in names}) + + def key(self) -> str: + return f"{self.url}|{self.begin}" diff --git a/mulberry/spectrum.py b/mulberry/spectrum.py new file mode 100644 index 0000000..8fc5923 --- /dev/null +++ b/mulberry/spectrum.py @@ -0,0 +1,254 @@ +"""Spectrum analysis for the radial visualizer, the bar analyzer and the +floating bass shape. + +PCM comes from the Qt backend (QAudioBufferOutput) or, with mpv, from the +PipeWire/PulseAudio monitor of the output device. Samples go into a ring +buffer and a *read cursor* advances at real time every frame, so the FFT +window slides smoothly even when audio arrives in big chunks. + +Levels are processed like cava: automatic sensitivity (so quiet and loud +songs both use the full range), gravity fall-off (bars drop all the way down +between hits) and light neighbour smoothing. A bass-onset detector emits +`beat` for the floating shape. +""" +from __future__ import annotations + +import time + +import numpy as np +from PyQt6.QtCore import QObject, pyqtSignal + +from .clock import FrameClock + +FFT_SIZE = 4096 +RATE = 44100 +RING = RATE * 2 + + +class Spectrum(QObject): + updated = pyqtSignal() + beat = pyqtSignal(float) # strength 0..1 + + use_monitor = False + + def __init__(self, bands=64): + super().__init__() + self.nbands = bands + self.ring = np.zeros(RING, dtype=np.float32) + self.written = 0 # total samples written + self.cursor = 0.0 # read position (absolute samples) + self.levels = np.zeros(bands, dtype=np.float32) + self.peaks = np.zeros(bands, dtype=np.float32) + self._mem = np.zeros(bands, dtype=np.float32) # gravity peak memory + self._fall = np.zeros(bands, dtype=np.float32) + self.sens = 1.0 + self.bass = 0.0 # smoothed processed bass 0..1 + self.pulse = 0.0 # decaying beat envelope 0..1 + self._bass_avg = 0.0 + self._bass_var = 0.0 + self._last_beat = 0.0 + self.window = np.hanning(FFT_SIZE).astype(np.float32) + freqs = np.fft.rfftfreq(FFT_SIZE, 1 / RATE) + edges = np.geomspace(40, 15000, bands + 1) + self.los = np.array([int(np.searchsorted(freqs, e)) for e in edges[:-1]], dtype=np.int64) + self.los = np.maximum.accumulate(np.maximum(self.los, 1)) + self.end_bin = int(np.searchsorted(freqs, edges[-1])) + 1 + # equaliser so highs aren't dwarfed by bass (pink-ish tilt) + centers = np.sqrt(edges[:-1] * edges[1:]) + self.weight = (centers / 1000.0) ** 0.42 + self.weight = (self.weight / self.weight.mean()).astype(np.float32) + self.consumers = 0 + self.playing = False + self.enabled = True + self.source = None + self._io = None + self._running = False + self._last_push = 0.0 + + # ---------------------------------------------------------- input + def push(self, data: np.ndarray): + n = len(data) + if n == 0: + return + if n >= RING: + data = data[-RING:] + n = RING + start = self.written % RING + end = start + n + if end <= RING: + self.ring[start:end] = data + else: + k = RING - start + self.ring[start:] = data[:k] + self.ring[:n - k] = data[k:] + self.written += n + self._last_push = time.monotonic() + + def start_monitor(self): + """Capture the default sink monitor (used with the mpv backend).""" + if self.source is not None: + return + try: + from PyQt6.QtMultimedia import QAudioFormat, QAudioSource, QMediaDevices + except ImportError: + return + outs = QMediaDevices.defaultAudioOutput().description().lower() + dev = None + for d in QMediaDevices.audioInputs(): + desc = d.description().lower() + if "monitor" in desc and (outs in desc or dev is None): + dev = d + if dev is None: + return + fmt = QAudioFormat() + fmt.setSampleRate(RATE) + fmt.setChannelCount(1) + fmt.setSampleFormat(QAudioFormat.SampleFormat.Float) + self.source = QAudioSource(dev, fmt, self) + self.source.setBufferSize(2048 * 4) + self._io = self.source.start() + if self._io is None: + self.source = None + return + self._io.readyRead.connect(self._read_monitor) + + def stop_monitor(self): + if self.source is not None: + self.source.stop() + self.source = None + self._io = None + + def _read_monitor(self): + if self._io is None: + return + data = self._io.readAll() + if data.size(): + self.push(np.frombuffer(bytes(data), dtype=np.float32)) + + # ---------------------------------------------------------- lifecycle + def set_playing(self, playing: bool): + self.playing = playing + self._update_monitor() + self._update_running() + + def _update_monitor(self): + """Only capture the monitor while playing (no permanent mic indicator).""" + if not self.use_monitor: + if self.source is not None: + self.stop_monitor() + return + want = self.enabled and self.playing and self.consumers > 0 + if want and self.source is None: + self.start_monitor() + elif not want and self.source is not None: + self.stop_monitor() + + def acquire(self): + self.consumers += 1 + self._update_monitor() + self._update_running() + + def release(self): + self.consumers = max(0, self.consumers - 1) + self._update_monitor() + self._update_running() + + @property + def active(self) -> bool: + return self._running + + def _update_running(self): + want = self.enabled and self.consumers > 0 and (self.playing or self.levels.max() > 0.002) + if want and not self._running: + self._running = True + FrameClock.subscribe(self._tick, pre=True) + elif not want and self._running: + self._running = False + FrameClock.unsubscribe(self._tick) + + # ---------------------------------------------------------- analysis + def _window(self, dt: float): + lag_target = 1536 # keep ~35 ms behind the newest sample + self.cursor += dt * RATE + newest = self.written - lag_target + # drift-correct toward the target lag; snap if far away + if abs(newest - self.cursor) > RATE * 0.4: + self.cursor = float(newest) + else: + self.cursor += (newest - self.cursor) * min(1.0, dt * 4) + self.cursor = min(self.cursor, float(self.written)) + end = int(self.cursor) + if end < FFT_SIZE: + return None + s = (end - FFT_SIZE) % RING + if s + FFT_SIZE <= RING: + return self.ring[s:s + FFT_SIZE] + k = RING - s + return np.concatenate((self.ring[s:], self.ring[:FFT_SIZE - k])) + + def _tick(self, dt: float): + stale = time.monotonic() - self._last_push > 0.35 + buf = self._window(dt) if (self.playing and not stale) else None + k60 = dt * 60.0 + if buf is not None: + mag = np.abs(np.fft.rfft(buf * self.window)) * (2.0 / FFT_SIZE) + raw = np.maximum.reduceat(mag[: self.end_bin], self.los)[: self.nbands] * self.weight + energy = float(raw.mean()) + v = (raw ** 0.62) * self.sens * 6.0 + # auto sensitivity (cava-like): shrink fast on overshoot, grow slowly + if v.max() > 1.0: + self.sens *= 0.985 ** k60 + elif energy > 1e-5: + self.sens *= 1.0018 ** k60 + self.sens = float(min(max(self.sens, 0.02), 60.0)) + v = np.clip(v, 0.0, 1.0) + # light neighbour smoothing for a fluid silhouette + v = np.maximum(v, 0.55 * np.maximum(np.roll(v, 1), np.roll(v, -1))) + v[0] = max(v[0], v[1] * 0.8) + v[-1] = min(v[-1], 1.0) + # bass onset detection on unscaled low-band energy + b_raw = float(raw[: max(2, self.nbands // 10)].mean()) + a = min(1.0, dt * 2.5) + self._bass_avg += (b_raw - self._bass_avg) * a + self._bass_var += ((b_raw - self._bass_avg) ** 2 - self._bass_var) * a + now = time.monotonic() + thr = self._bass_avg + 1.6 * (self._bass_var ** 0.5) + if b_raw > thr and b_raw > self._bass_avg * 1.25 and b_raw > 1e-4 and now - self._last_beat > 0.16: + self._last_beat = now + strength = float(min(1.0, (b_raw / max(self._bass_avg, 1e-6) - 1.0) / 1.5)) + self.pulse = max(self.pulse, 0.45 + 0.55 * strength) + self.beat.emit(strength) + else: + v = np.zeros(self.nbands, dtype=np.float32) + # gravity: rise instantly, fall with accelerating speed down to zero + rise = v >= self._mem + self._fall = np.where(rise, 0.0, self._fall + dt).astype(np.float32) + self._mem = np.where(rise, v, self._mem).astype(np.float32) + grav = self._mem * (1.0 - (self._fall * 2.6) ** 2) + lv = np.maximum(v, np.maximum(grav, 0.0)) + caught = grav <= v + self._mem = np.where(caught, v, self._mem).astype(np.float32) + self._fall = np.where(caught, 0.0, self._fall).astype(np.float32) + # a touch of attack smoothing so peaks don't flicker + self.levels = (self.levels + (lv - self.levels) * min(1.0, 0.75 * k60)).astype(np.float32) + self.peaks = np.maximum(self.peaks - 0.6 * dt, self.levels) + self.bass += (float(self.levels[: max(2, self.nbands // 10)].mean()) - self.bass) * min(1.0, 0.5 * k60) + self.pulse = max(0.0, self.pulse - dt * 2.4) + self.updated.emit() + if not self.playing and self.levels.max() < 0.002 and self.pulse <= 0: + self.levels[:] = 0 + self.peaks[:] = 0 + self.bass = 0.0 + self.updated.emit() + self._update_running() + + # ---------------------------------------------------------- helpers + def resample(self, n: int) -> np.ndarray: + if n == self.nbands: + return self.levels + x = np.linspace(0, self.nbands - 1, n) + return np.interp(x, np.arange(self.nbands), self.levels).astype(np.float32) + + def resample_peaks(self, n: int) -> np.ndarray: + x = np.linspace(0, self.nbands - 1, n) + return np.interp(x, np.arange(self.nbands), self.peaks).astype(np.float32) diff --git a/mulberry/tags.py b/mulberry/tags.py new file mode 100644 index 0000000..4ae3ecb --- /dev/null +++ b/mulberry/tags.py @@ -0,0 +1,455 @@ +"""Tag reading/writing with mutagen (covers every common audio format).""" +from __future__ import annotations + +import base64 +import hashlib +import os +import re +from pathlib import Path + +import mutagen +from PyQt6.QtCore import QBuffer, QByteArray, QIODevice, Qt +from PyQt6.QtGui import QImage + +from .config import COVER_DIR, THUMB_DIR +from .song import Song + +ALIASES = { + "title": ("title", "tit2", "©nam", "wm/title", "inam"), + "artist": ("artist", "tpe1", "©art", "author", "wm/author", "iart"), + "album": ("album", "talb", "©alb", "wm/albumtitle", "iprd"), + "albumartist": ("albumartist", "album artist", "album_artist", "tpe2", "aart", "wm/albumartist", "ensemble"), + "genre": ("genre", "tcon", "©gen", "wm/genre", "ignr"), + "composer": ("composer", "tcom", "©wrt", "wm/composer"), + "comment": ("comment", "description", "©cmt", "wm/description", "icmt"), + "date": ("date", "year", "originaldate", "tdrc", "tyer", "©day", "wm/year", "icrd"), + "track": ("tracknumber", "track", "trck", "trkn", "wm/tracknumber"), + "disc": ("discnumber", "disc", "tpos", "disk", "wm/partofset"), + "rg_track": ("replaygain_track_gain", "txxx:replaygain_track_gain", + "----:com.apple.itunes:replaygain_track_gain"), + "rg_album": ("replaygain_album_gain", "txxx:replaygain_album_gain", + "----:com.apple.itunes:replaygain_album_gain"), + "mb_trackid": ("musicbrainz_trackid", "musicbrainz track id", "ufid:http://musicbrainz.org", + "----:com.apple.itunes:musicbrainz track id"), + "mb_albumid": ("musicbrainz_albumid", "musicbrainz album id", "txxx:musicbrainz album id", + "----:com.apple.itunes:musicbrainz album id"), + "lyrics": ("lyrics", "unsyncedlyrics", "uslt", "©lyr", "wm/lyrics", "lyrics:"), +} + +FOLDER_COVERS = ("cover", "folder", "front", "album", "albumart", "albumartsmall", "thumb", "art") +IMG_EXTS = (".jpg", ".jpeg", ".png", ".webp", ".bmp", ".gif") + + +def _txt(v) -> str: + if v is None: + return "" + if isinstance(v, (list, tuple)): + if not v: + return "" + v = v[0] + if isinstance(v, tuple): # mp4 trkn (n, total) + return str(v[0]) + if hasattr(v, "text"): + t = v.text + if isinstance(t, (list, tuple)): + return str(t[0]) if t else "" + return str(t) + if hasattr(v, "value"): + return str(v.value) + if isinstance(v, bytes): + try: + return v.decode("utf-8", "replace") + except Exception: # noqa: BLE001 + return "" + if hasattr(v, "data") and isinstance(getattr(v, "data"), bytes): + return v.data.decode("utf-8", "replace") + return str(v) + + +def _lower_map(tags) -> dict: + out = {} + if tags is None: + return out + try: + items = tags.items() + except Exception: # noqa: BLE001 + return out + for k, v in items: + lk = str(k).lower() + out.setdefault(lk, v) + # ID3 frames like 'TXXX:replaygain_track_gain' / 'USLT::eng' + if ":" in lk: + out.setdefault(lk.split(":")[0] + ":" + lk.split(":")[1] if lk.count(":") >= 1 else lk, v) + out.setdefault(lk.split(":")[0], v) + return out + + +def _first(m: dict, field: str) -> str: + for a in ALIASES[field]: + if a in m: + s = _txt(m[a]).strip() + if s: + return s + return "" + + +def _int(s: str) -> int: + mm = re.match(r"\s*(\d+)", s or "") + return int(mm.group(1)) if mm else 0 + + +def _gain(s: str): + mm = re.match(r"\s*([-+]?\d+(?:\.\d+)?)", s or "") + return float(mm.group(1)) if mm else None + + +def read_song(path: str) -> Song | None: + """Read metadata + stream info. Returns None if the file isn't audio.""" + try: + st = os.stat(path) + except OSError: + return None + s = Song(url=path, filesize=st.st_size, mtime=st.st_mtime) + s.filetype = Path(path).suffix.lower().lstrip(".") + try: + f = mutagen.File(path) + except Exception: # noqa: BLE001 + f = None + if f is not None: + info = getattr(f, "info", None) + if info is not None: + s.length = float(getattr(info, "length", 0) or 0) + br = getattr(info, "bitrate", 0) or 0 + s.bitrate = int(br // 1000) if br > 10000 else int(br) + s.samplerate = int(getattr(info, "sample_rate", 0) or 0) + s.bitdepth = int(getattr(info, "bits_per_sample", 0) or getattr(info, "bits_per_raw_sample", 0) or 0) + s.channels = int(getattr(info, "channels", 0) or 0) + if not s.bitrate and s.length > 0: + s.bitrate = int(st.st_size * 8 / s.length / 1000) + m = _lower_map(f.tags) + s.title = _first(m, "title") + s.artist = _first(m, "artist") + s.album = _first(m, "album") + s.albumartist = _first(m, "albumartist") + s.genre = _first(m, "genre") + s.composer = _first(m, "composer") + s.comment = _first(m, "comment")[:500] + s.year = _int(_first(m, "date")) + s.track = _int(_first(m, "track")) + s.disc = _int(_first(m, "disc")) + s.rg_track = _gain(_first(m, "rg_track")) + s.rg_album = _gain(_first(m, "rg_album")) + s.mb_trackid = _first(m, "mb_trackid")[:64] + s.mb_albumid = _first(m, "mb_albumid")[:64] + if s.genre.startswith("(") and s.genre[1:].split(")")[0].isdigit(): + try: + from mutagen.id3 import TCON + s.genre = TCON(text=[s.genre]).genres[0] + except Exception: # noqa: BLE001 + pass + s.filetype = _filetype(f, s.filetype) + elif s.filetype not in ("mod", "xm", "it", "s3m", "mid", "midi", "sid", "spc", "vgm", "nsf", "ac3", "dts"): + return None + return s + + +def _filetype(f, ext) -> str: + n = type(f).__name__.lower() + table = { + "mp3": "MP3", "easymp3": "MP3", "flac": "FLAC", "oggvorbis": "Ogg Vorbis", "oggopus": "Ogg Opus", + "oggflac": "Ogg FLAC", "oggspeex": "Ogg Speex", "oggtheora": "Ogg Theora", "mp4": "MPEG-4", + "easymp4": "MPEG-4", "asf": "WMA", "monkeysaudio": "APE", "wavpack": "WavPack", + "musepack": "Musepack", "trueaudio": "TTA", "optimfrog": "OptimFROG", "aiff": "AIFF", + "wave": "WAV", "dsf": "DSF", "dsdiff": "DSDIFF", "tak": "TAK", "aac": "AAC", "ac3": "AC3", + "smf": "MIDI", + } + t = table.get(n, ext.upper()) + if t == "MPEG-4": + codec = getattr(getattr(f, "info", None), "codec", "") or "" + t = "ALAC" if codec.startswith("alac") else "AAC" + return t + + +# ------------------------------------------------------------------ covers +def extract_embedded_cover(path: str) -> bytes | None: + try: + f = mutagen.File(path) + except Exception: # noqa: BLE001 + return None + if f is None: + return None + pics = getattr(f, "pictures", None) + if pics: + front = [p for p in pics if getattr(p, "type", 0) == 3] + return (front or pics)[0].data + tags = f.tags + if tags is None: + return None + try: + keys = list(tags.keys()) + except Exception: # noqa: BLE001 + return None + # ID3 + apic = [tags[k] for k in keys if str(k).startswith("APIC")] + if apic: + front = [a for a in apic if getattr(a, "type", 0) == 3] + return (front or apic)[0].data + # MP4 + if "covr" in tags and tags["covr"]: + return bytes(tags["covr"][0]) + # Vorbis comment METADATA_BLOCK_PICTURE + for k in keys: + lk = str(k).lower() + if lk == "metadata_block_picture": + try: + from mutagen.flac import Picture + return Picture(base64.b64decode(_txt(tags[k]))).data + except Exception: # noqa: BLE001 + pass + if lk.startswith("cover art"): + v = tags[k] + data = getattr(v, "value", None) + if isinstance(data, bytes) and b"\x00" in data: + return data.split(b"\x00", 1)[1] + if lk == "wm/picture": + try: + v = tags[k][0].value + # ASF picture: type(1) size(4) mime(utf16z) desc(utf16z) data + i = 5 + for _ in range(2): + j = v.find(b"\x00\x00", i) + while j != -1 and (j - i) % 2: + j = v.find(b"\x00\x00", j + 1) + i = j + 2 + return v[i:] + except Exception: # noqa: BLE001 + pass + return None + + +def find_folder_cover(directory: str) -> str | None: + try: + entries = os.listdir(directory) + except OSError: + return None + imgs = [e for e in entries if e.lower().endswith(IMG_EXTS)] + if not imgs: + return None + for pref in FOLDER_COVERS: + for e in imgs: + if os.path.splitext(e)[0].lower() == pref: + return os.path.join(directory, e) + for e in imgs: + if any(p in e.lower() for p in ("cover", "front", "folder")): + return os.path.join(directory, e) + return os.path.join(directory, imgs[0]) if len(imgs) == 1 else None + + +def album_key(artist: str, album: str, directory: str = "") -> str: + base = f"{(artist or '').lower()}|{(album or '').lower()}" + if not album: + base += "|" + directory + return hashlib.sha1(base.encode()).hexdigest() + + +def store_cover(data_or_path, key: str) -> str | None: + """Save a normalised cover (≤1000px) and 160px thumb into the cache.""" + img = QImage() + if isinstance(data_or_path, (bytes, bytearray)): + img.loadFromData(bytes(data_or_path)) + else: + img.load(str(data_or_path)) + if img.isNull(): + return None + out = COVER_DIR / f"{key}.jpg" + if max(img.width(), img.height()) > 1000: + img = img.scaled(1000, 1000, Qt.AspectRatioMode.KeepAspectRatio, + Qt.TransformationMode.SmoothTransformation) + img.save(str(out), "JPG", 92) + thumb = img.scaled(160, 160, Qt.AspectRatioMode.KeepAspectRatioByExpanding, + Qt.TransformationMode.SmoothTransformation) + thumb.save(str(THUMB_DIR / f"{key}.jpg"), "JPG", 85) + return str(out) + + +def thumb_for(art_path: str) -> str | None: + if not art_path: + return None + p = Path(art_path) + t = THUMB_DIR / p.name + if p.parent == COVER_DIR and t.exists(): + return str(t) + key = hashlib.sha1(art_path.encode()).hexdigest() + ".jpg" + t = THUMB_DIR / key + if t.exists(): + return str(t) + img = QImage(art_path) + if img.isNull(): + return None + img.scaled(160, 160, Qt.AspectRatioMode.KeepAspectRatioByExpanding, + Qt.TransformationMode.SmoothTransformation).save(str(t), "JPG", 85) + return str(t) + + +def image_to_jpeg_bytes(img: QImage, quality=92) -> bytes: + ba = QByteArray() + buf = QBuffer(ba) + buf.open(QIODevice.OpenModeFlag.WriteOnly) + img.save(buf, "JPG", quality) + return bytes(ba) + + +# ------------------------------------------------------------------ lyrics +def read_embedded_lyrics(path: str) -> str: + try: + f = mutagen.File(path) + except Exception: # noqa: BLE001 + return "" + if f is None or f.tags is None: + return "" + try: + for k in f.tags.keys(): + lk = str(k).lower() + if lk.startswith("uslt") or lk in ("lyrics", "unsyncedlyrics", "©lyr", "wm/lyrics"): + return _txt(f.tags[k]) + if lk.startswith("sylt"): + fr = f.tags[k] + return "\n".join(f"[{_lrc_ts(t / 1000)}]{txt}" for txt, t in fr.text) + except Exception: # noqa: BLE001 + pass + return "" + + +def _lrc_ts(sec: float) -> str: + m, s = divmod(sec, 60) + return f"{int(m):02d}:{s:05.2f}" + + +def sidecar_lyrics(path: str) -> str: + p = Path(path) + for cand in (p.with_suffix(".lrc"), p.with_suffix(".LRC"), p.with_suffix(".txt")): + if cand.exists(): + try: + return cand.read_text(encoding="utf-8", errors="replace") + except OSError: + pass + return "" + + +# ------------------------------------------------------------------ writing +EASY_KEYS = { + "title": "title", "artist": "artist", "album": "album", "albumartist": "albumartist", + "genre": "genre", "composer": "composer", "year": "date", "track": "tracknumber", + "disc": "discnumber", "comment": "comment", "mb_trackid": "musicbrainz_trackid", + "mb_albumid": "musicbrainz_albumid", +} +APE_KEYS = {"title": "Title", "artist": "Artist", "album": "Album", "albumartist": "Album Artist", + "genre": "Genre", "composer": "Composer", "year": "Year", "track": "Track", + "disc": "Disc", "comment": "Comment"} +ASF_KEYS = {"title": "Title", "artist": "Author", "album": "WM/AlbumTitle", + "albumartist": "WM/AlbumArtist", "genre": "WM/Genre", "composer": "WM/Composer", + "year": "WM/Year", "track": "WM/TrackNumber", "disc": "WM/PartOfSet", + "comment": "Description"} + + +def write_tags(path: str, values: dict) -> None: + """values: field -> str/int (empty string removes).""" + f = mutagen.File(path, easy=True) + if f is None: + raise ValueError("Unsupported file") + if f.tags is None: + try: + f.add_tags() + except Exception: # noqa: BLE001 + pass + cls = type(f).__name__ + if cls == "ASF": + table = ASF_KEYS + elif cls in ("MonkeysAudio", "WavPack", "Musepack", "OptimFROG", "TrueAudio", "TAK"): + table = APE_KEYS + else: + table = EASY_KEYS + for field_, val in values.items(): + key = table.get(field_) + if not key: + continue + sval = "" if val in (None, 0, "0") else str(val) + if sval: + try: + f.tags[key] = [sval] if table is not ASF_KEYS else sval + except Exception: # noqa: BLE001 + pass + else: + try: + del f.tags[key] + except Exception: # noqa: BLE001 + pass + f.save() + + +def write_lyrics(path: str, text: str) -> None: + f = mutagen.File(path) + if f is None: + raise ValueError("Unsupported file") + if f.tags is None: + f.add_tags() + from mutagen.id3 import ID3, USLT + if isinstance(f.tags, ID3): + f.tags.delall("USLT") + f.tags.add(USLT(encoding=3, lang="eng", desc="", text=text)) + elif type(f).__name__ in ("MP4",): + f.tags["©lyr"] = [text] + else: + try: + f.tags["LYRICS"] = [text] + except Exception: # noqa: BLE001 + f.tags["Lyrics"] = text + f.save() + + +def embed_cover(path: str, data: bytes | None, mime="image/jpeg") -> None: + f = mutagen.File(path) + if f is None: + raise ValueError("Unsupported file") + if f.tags is None: + try: + f.add_tags() + except Exception: # noqa: BLE001 + pass + name = type(f).__name__ + from mutagen.flac import Picture + if name in ("FLAC",): + f.clear_pictures() + if data: + pic = Picture() + pic.type, pic.mime, pic.data = 3, mime, data + f.add_picture(pic) + elif name in ("MP3", "AIFF", "WAVE", "DSF", "TrueAudio"): + from mutagen.id3 import APIC + f.tags.delall("APIC") + if data: + f.tags.add(APIC(encoding=3, mime=mime, type=3, desc="Cover", data=data)) + elif name == "MP4": + from mutagen.mp4 import MP4Cover + if data: + fmt = MP4Cover.FORMAT_PNG if mime.endswith("png") else MP4Cover.FORMAT_JPEG + f.tags["covr"] = [MP4Cover(data, imageformat=fmt)] + elif "covr" in f.tags: + del f.tags["covr"] + elif name.startswith("Ogg"): + for k in list(f.tags.keys()): + if k.lower() == "metadata_block_picture": + del f.tags[k] + if data: + pic = Picture() + pic.type, pic.mime, pic.data = 3, mime, data + f.tags["metadata_block_picture"] = [base64.b64encode(pic.write()).decode("ascii")] + elif name in ("MonkeysAudio", "WavPack", "Musepack", "OptimFROG"): + from mutagen.apev2 import APEValue, BINARY + if data: + f.tags["Cover Art (Front)"] = APEValue(b"cover.jpg\x00" + data, BINARY) + elif "Cover Art (Front)" in f.tags: + del f.tags["Cover Art (Front)"] + else: + raise ValueError(f"Embedding covers in {name} is not supported") + f.save() diff --git a/mulberry/theme.py b/mulberry/theme.py new file mode 100644 index 0000000..223cff9 --- /dev/null +++ b/mulberry/theme.py @@ -0,0 +1,601 @@ +"""Material You colour scheme generated from the user's KDE colours. + +Reads ~/.config/kdeglobals (accent, window background, font), builds tonal +palettes in OKLCH space (tone == CIE L*), produces the Material 3 colour roles +and a Qt stylesheet. The file is watched, so changing the KDE colour scheme or +accent recolours the player live. +""" +from __future__ import annotations + +import configparser +import math +import os +import sys +from pathlib import Path + +from PyQt6.QtCore import QFileSystemWatcher, QObject, QTimer, pyqtSignal +from PyQt6.QtGui import QColor, QFont, QFontDatabase, QImage, QPalette +from PyQt6.QtWidgets import QApplication + +from .config import settings + + +# ------------------------------------------------------------------ colour math +def _srgb_to_lin(c): + return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4 + + +def _lin_to_srgb(c): + return 12.92 * c if c <= 0.0031308 else 1.055 * (c ** (1 / 2.4)) - 0.055 + + +def rgb_to_oklch(r, g, b): + r, g, b = (_srgb_to_lin(x / 255) for x in (r, g, b)) + l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b + m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b + s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b + l, m, s = (math.copysign(abs(x) ** (1 / 3), x) for x in (l, m, s)) + L = 0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s + A = 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s + B = 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s + return L, math.hypot(A, B), math.degrees(math.atan2(B, A)) % 360 + + +def _oklch_to_lin(L, C, H): + a = C * math.cos(math.radians(H)) + b = C * math.sin(math.radians(H)) + l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3 + m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3 + s = (L - 0.0894841775 * a - 1.2914855480 * b) ** 3 + r = 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s + g = -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s + bb = -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s + return r, g, bb + + +def oklch_to_qcolor(L, C, H) -> QColor: + """Convert with gamut mapping (reduce chroma until it fits sRGB).""" + lo, hi = 0.0, C + rgb = _oklch_to_lin(L, C, H) + if not all(-1e-4 <= x <= 1.0001 for x in rgb): + for _ in range(18): + mid = (lo + hi) / 2 + rgb2 = _oklch_to_lin(L, mid, H) + if all(-1e-4 <= x <= 1.0001 for x in rgb2): + lo = mid + else: + hi = mid + rgb = _oklch_to_lin(L, lo, H) + r, g, b = (max(0, min(255, round(_lin_to_srgb(max(0.0, min(1.0, x))) * 255))) for x in rgb) + return QColor(r, g, b) + + +def tone_to_L(t: float) -> float: + """CIE L* tone (0-100) to OKLab lightness (achromatic identity).""" + if t <= 8: + y = t / 903.2963 + return y ** (1 / 3) + return (t + 16) / 116 + + +def L_to_tone(L: float) -> float: + y = L ** 3 + return 903.2963 * y if y <= 0.008856 else 116 * L - 16 + + +class Tonal: + def __init__(self, hue: float, chroma: float): + self.h, self.c = hue, chroma + + def __call__(self, tone: float) -> QColor: + return oklch_to_qcolor(tone_to_L(tone), self.c, self.h) + + +def mix(a: QColor, b: QColor, t: float) -> QColor: + return QColor(round(a.red() + (b.red() - a.red()) * t), + round(a.green() + (b.green() - a.green()) * t), + round(a.blue() + (b.blue() - a.blue()) * t), + round(a.alpha() + (b.alpha() - a.alpha()) * t)) + + +def alpha(c: QColor, a: float) -> QColor: + q = QColor(c) + q.setAlphaF(max(0.0, min(1.0, a))) + return q + + +def rgba(c: QColor, a: float | None = None) -> str: + a = c.alphaF() if a is None else a + return f"rgba({c.red()},{c.green()},{c.blue()},{a:.3f})" + + +def dominant_color(img: QImage) -> QColor | None: + """Pick a vivid representative colour from artwork (Material 'score' style).""" + if img is None or img.isNull(): + return None + small = img.scaled(48, 48).convertToFormat(QImage.Format.Format_RGB32) + buckets: dict[int, list] = {} + for y in range(small.height()): + for x in range(small.width()): + c = small.pixelColor(x, y) + L, C, H = rgb_to_oklch(c.red(), c.green(), c.blue()) + if C < 0.03 or L < 0.2 or L > 0.95: + continue + key = int(H // 15) + b = buckets.setdefault(key, [0.0, 0.0, 0.0, 0.0]) + w = C * C + b[0] += w + b[1] += math.cos(math.radians(H)) * w + b[2] += math.sin(math.radians(H)) * w + b[3] += C * w + if not buckets: + return None + best = max(buckets.values(), key=lambda b: b[0]) + hue = math.degrees(math.atan2(best[2], best[1])) % 360 + chroma = best[3] / best[0] + return oklch_to_qcolor(0.65, max(chroma, 0.1), hue) + + +# ------------------------------------------------------------------ KDE reading +def _kdeglobals_path() -> Path: + base = os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config") + return Path(base) / "kdeglobals" + + +def _parse_rgb(s: str | None) -> QColor | None: + if not s: + return None + try: + parts = [int(p) for p in s.split(",")[:3]] + return QColor(*parts) + except ValueError: + c = QColor(s.strip()) + return c if c.isValid() else None + + +def read_kde() -> dict: + p = _kdeglobals_path() + out = {} + if not p.exists(): + return out + cp = configparser.ConfigParser(interpolation=None, strict=False) + cp.optionxform = str + try: + cp.read(p, encoding="utf-8") + except configparser.Error: + return out + + def g(sec, key): + try: + return cp.get(sec, key) + except (configparser.NoSectionError, configparser.NoOptionError): + return None + + out["accent"] = _parse_rgb(g("General", "AccentColor")) or _parse_rgb(g("Colors:Selection", "BackgroundNormal")) + out["window_bg"] = _parse_rgb(g("Colors:Window", "BackgroundNormal")) + out["view_bg"] = _parse_rgb(g("Colors:View", "BackgroundNormal")) + out["window_fg"] = _parse_rgb(g("Colors:Window", "ForegroundNormal")) + font = g("General", "font") + if font: + out["font"] = font.split(",")[0] + try: + out["font_size"] = float(font.split(",")[1]) + except (IndexError, ValueError): + pass + return out + + +def read_windows() -> dict: + """Windows accent colour (DWM) and app light/dark mode from the registry.""" + out = {} + try: + import winreg + except ImportError: + return out + + def val(path, name): + try: + with winreg.OpenKey(winreg.HKEY_CURRENT_USER, path) as k: + return winreg.QueryValueEx(k, name)[0] + except OSError: + return None + acc = val(r"Software\Microsoft\Windows\DWM", "AccentColor") + if acc is None: + acc = val(r"Software\Microsoft\Windows\DWM", "ColorizationColor") + if acc is not None: # 0xAARRGGBB + out["accent"] = QColor((acc >> 16) & 0xFF, (acc >> 8) & 0xFF, acc & 0xFF) + else: # 0xAABBGGRR + out["accent"] = QColor(acc & 0xFF, (acc >> 8) & 0xFF, (acc >> 16) & 0xFF) + light = val(r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize", "AppsUseLightTheme") + dark = (light == 0) if light is not None else True + out["window_bg"] = QColor(32, 32, 32) if dark else QColor(243, 243, 243) + fams = set(QFontDatabase.families()) + out["font"] = next((f for f in ("Segoe UI Variable Text", "Segoe UI") if f in fams), "") + out["font_size"] = 9.5 + return out + + +def read_generic() -> dict: + """Any other desktop: Qt's own idea of accent + light/dark.""" + out = {} + app = QApplication.instance() + if app is None: + return out + pal = app.palette() + try: + acc = pal.color(QPalette.ColorRole.Accent) + except AttributeError: + acc = pal.color(QPalette.ColorRole.Highlight) + if acc.isValid(): + out["accent"] = acc + try: + from PyQt6.QtCore import Qt as _Qt + scheme = app.styleHints().colorScheme() + if scheme == _Qt.ColorScheme.Dark: + out["window_bg"] = QColor(28, 27, 31) + elif scheme == _Qt.ColorScheme.Light: + out["window_bg"] = QColor(250, 248, 252) + except AttributeError: + pass + return out + + +def read_system() -> dict: + if sys.platform == "win32": + return read_windows() + kde = read_kde() + return kde if kde else read_generic() + + +# ------------------------------------------------------------------ theme object +ROLES = ( + "primary onPrimary primaryContainer onPrimaryContainer secondary onSecondary " + "secondaryContainer onSecondaryContainer tertiary onTertiary tertiaryContainer " + "onTertiaryContainer error onError surface surfaceDim surfaceBright " + "surfaceContainerLowest surfaceContainerLow surfaceContainer surfaceContainerHigh " + "surfaceContainerHighest onSurface onSurfaceVariant outline outlineVariant " + "inverseSurface inverseOnSurface inversePrimary scrim" +).split() + + +class Theme(QObject): + changed = pyqtSignal() + + def __init__(self): + super().__init__() + self.c: dict[str, QColor] = {} + self.dark = True + self.font_family = "" + self.display_family = "" + self.font_size = 10.0 + self.album_seed: QColor | None = None + self._watcher = QFileSystemWatcher(self) + self._watcher.fileChanged.connect(self._on_file) + self._watcher.directoryChanged.connect(self._on_file) + self._debounce = QTimer(self, singleShot=True, interval=300) + self._debounce.timeout.connect(self.rebuild) + p = _kdeglobals_path() + if p.exists(): + self._watcher.addPath(str(p)) + if p.parent.exists(): + self._watcher.addPath(str(p.parent)) + # Windows has no file to watch: poll the registry cheaply; everywhere + # also follow Qt's colour-scheme signal (GNOME, Windows, macOS). + self._snapshot = None + if sys.platform == "win32": + self._poll = QTimer(self, interval=2500) + self._poll.timeout.connect(self._poll_system) + self._poll.start() + try: + QApplication.instance().styleHints().colorSchemeChanged.connect(lambda *_: self._debounce.start()) + except AttributeError: + pass + self.rebuild(emit=False) + + def _poll_system(self): + snap = tuple((k, v.rgb() if isinstance(v, QColor) else v) for k, v in sorted(read_windows().items())) + if self._snapshot is not None and snap != self._snapshot: + self._debounce.start() + self._snapshot = snap + + def __getitem__(self, role) -> QColor: + return self.c[role] + + def _on_file(self, *_): + p = _kdeglobals_path() + if p.exists() and str(p) not in self._watcher.files(): + self._watcher.addPath(str(p)) + self._debounce.start() + + def set_album_seed(self, col: QColor | None): + if settings.get("appearance/color_source") != "album": + self.album_seed = col + return + if col is None and self.album_seed is None: + return + if col is not None and self.album_seed is not None and col.rgb() == self.album_seed.rgb(): + return + self.album_seed = col + self.rebuild() + + # -------------------------------------------------------------- generation + def rebuild(self, emit=True): + kde = read_system() + src_mode = settings.get("appearance/color_source") + seed = None + if src_mode == "album" and self.album_seed is not None: + seed = self.album_seed + elif src_mode == "custom": + seed = QColor(settings.get("appearance/custom_color")) + if seed is None or not seed.isValid(): + seed = kde.get("accent") or QColor("#9a7fd1") + + win = kde.get("window_bg") + mode = settings.get("appearance/mode") + if mode == "dark": + dark = True + elif mode == "light": + dark = False + elif win is not None: + dark = win.lightnessF() < 0.5 + else: + dark = True + self.dark = dark + + _, sc, sh = rgb_to_oklch(seed.red(), seed.green(), seed.blue()) + pc = min(max(sc, 0.085), 0.15) + primary = Tonal(sh, pc) + secondary = Tonal(sh, 0.04) + tertiary = Tonal((sh + 60) % 360, 0.075) + err = Tonal(25, 0.17) + + # neutrals follow the KDE window background (hue/chroma/tone) + base_tone = None + if win is not None and src_mode == "kde": + wl, wc, wh = rgb_to_oklch(win.red(), win.green(), win.blue()) + nh = wh if wc > 0.006 else sh + nc = min(max(wc, 0.008), 0.035) + base_tone = L_to_tone(wl) + else: + nh, nc = sh, 0.014 + neutral = Tonal(nh, nc) + nvar = Tonal(nh, max(nc * 1.8, 0.022)) + + if dark: + st = 6 if base_tone is None else max(3.0, min(base_tone, 16.0)) + c = dict( + primary=primary(80), onPrimary=primary(20), primaryContainer=primary(30), + onPrimaryContainer=primary(90), secondary=secondary(80), onSecondary=secondary(20), + secondaryContainer=secondary(30), onSecondaryContainer=secondary(90), + tertiary=tertiary(80), onTertiary=tertiary(20), tertiaryContainer=tertiary(30), + onTertiaryContainer=tertiary(90), error=err(80), onError=err(20), + surface=neutral(st), surfaceDim=neutral(st), surfaceBright=neutral(st + 18), + surfaceContainerLowest=neutral(max(st - 2, 1)), surfaceContainerLow=neutral(st + 4), + surfaceContainer=neutral(st + 6), surfaceContainerHigh=neutral(st + 11), + surfaceContainerHighest=neutral(st + 16), onSurface=neutral(90), + onSurfaceVariant=nvar(80), outline=nvar(60), outlineVariant=nvar(30), + inverseSurface=neutral(90), inverseOnSurface=neutral(20), inversePrimary=primary(40), + scrim=QColor(0, 0, 0), + ) + else: + st = 98 if base_tone is None else max(90.0, min(base_tone, 99.0)) + c = dict( + primary=primary(40), onPrimary=primary(100), primaryContainer=primary(90), + onPrimaryContainer=primary(10), secondary=secondary(40), onSecondary=secondary(100), + secondaryContainer=secondary(90), onSecondaryContainer=secondary(10), + tertiary=tertiary(40), onTertiary=tertiary(100), tertiaryContainer=tertiary(90), + onTertiaryContainer=tertiary(10), error=err(40), onError=err(100), + surface=neutral(st), surfaceDim=neutral(st - 11), surfaceBright=neutral(st), + surfaceContainerLowest=neutral(100), surfaceContainerLow=neutral(st - 2), + surfaceContainer=neutral(st - 4), surfaceContainerHigh=neutral(st - 6), + surfaceContainerHighest=neutral(st - 8), onSurface=neutral(10), + onSurfaceVariant=nvar(30), outline=nvar(50), outlineVariant=nvar(80), + inverseSurface=neutral(20), inverseOnSurface=neutral(95), inversePrimary=primary(80), + scrim=QColor(0, 0, 0), + ) + self.c = c + + fam = settings.get("appearance/font") or kde.get("font") or QApplication.font().family() + self.font_family = fam + self.font_size = kde.get("font_size", QApplication.font().pointSizeF() or 10.0) + fams = set(QFontDatabase.families()) + self.display_family = next( + (f for f in ("Google Sans", "Google Sans Text", "Product Sans", "Rubik", "Outfit", + "Lexend", "Inter Display", "Inter", "Segoe UI Variable Display", + "Segoe UI Semibold") if f in fams), fam) + if settings.get("appearance/font"): + self.display_family = fam + if emit: + self.apply() + self.changed.emit() + + def display_font(self, px: int, weight=QFont.Weight.Medium) -> QFont: + f = QFont(self.display_family) + f.setPixelSize(px) + f.setWeight(weight) + return f + + # -------------------------------------------------------------- applying + def apply(self): + app = QApplication.instance() + if app is None: + return + c = self.c + pal = QPalette() + for grp in (QPalette.ColorGroup.Active, QPalette.ColorGroup.Inactive, QPalette.ColorGroup.Disabled): + dis = grp == QPalette.ColorGroup.Disabled + fg = alpha(c["onSurface"], 0.38) if dis else c["onSurface"] + pal.setColor(grp, QPalette.ColorRole.Window, c["surface"]) + pal.setColor(grp, QPalette.ColorRole.WindowText, fg) + pal.setColor(grp, QPalette.ColorRole.Base, c["surfaceContainerLow"]) + pal.setColor(grp, QPalette.ColorRole.AlternateBase, c["surfaceContainer"]) + pal.setColor(grp, QPalette.ColorRole.Text, fg) + pal.setColor(grp, QPalette.ColorRole.Button, c["surfaceContainerHigh"]) + pal.setColor(grp, QPalette.ColorRole.ButtonText, fg) + pal.setColor(grp, QPalette.ColorRole.Highlight, c["secondaryContainer"]) + pal.setColor(grp, QPalette.ColorRole.HighlightedText, c["onSecondaryContainer"]) + pal.setColor(grp, QPalette.ColorRole.ToolTipBase, c["inverseSurface"]) + pal.setColor(grp, QPalette.ColorRole.ToolTipText, c["inverseOnSurface"]) + pal.setColor(grp, QPalette.ColorRole.PlaceholderText, alpha(c["onSurfaceVariant"], 0.7)) + pal.setColor(grp, QPalette.ColorRole.Link, c["primary"]) + pal.setColor(grp, QPalette.ColorRole.BrightText, c["error"]) + pal.setColor(grp, QPalette.ColorRole.Mid, c["outlineVariant"]) + pal.setColor(grp, QPalette.ColorRole.Dark, c["surfaceContainerLowest"]) + pal.setColor(grp, QPalette.ColorRole.Light, c["surfaceContainerHighest"]) + pal.setColor(grp, QPalette.ColorRole.Accent, c["primary"]) + app.setPalette(pal) + f = QFont(self.font_family) + f.setPointSizeF(self.font_size) + app.setFont(f) + app.setStyleSheet(self.stylesheet()) + + def _asset(self, name: str, color: QColor) -> str: + from .config import CACHE_DIR + from .icondata import PATHS + d = CACHE_DIR / "qss" + d.mkdir(parents=True, exist_ok=True) + f = d / f"{name}-{color.name()[1:]}.svg" + if not f.exists(): + f.write_text(f'' + f'') + return f.as_posix() + + def stylesheet(self) -> str: + c = {k: v.name() for k, v in self.c.items()} + a_close = self._asset("close", self.c["onSurfaceVariant"]) + a_close_h = self._asset("close", self.c["onSurface"]) + a_check = self._asset("check", self.c["onPrimary"]) + a_down = self._asset("expand_more", self.c["onSurfaceVariant"]) + a_up = self._asset("expand_less", self.c["onSurfaceVariant"]) + a_left = self._asset("chevron_left", self.c["onSurfaceVariant"]) + a_right = self._asset("chevron_right", self.c["onSurfaceVariant"]) + a_bc = self._asset("chevron_right", self.c["onSurfaceVariant"]) + a_bo = self._asset("expand_more", self.c["onSurfaceVariant"]) + hov = rgba(self.c["onSurface"], 0.08) + prs = rgba(self.c["onSurface"], 0.12) + sel = c["secondaryContainer"] + return f""" +* {{ outline: none; }} +QMainWindow, QDialog {{ background: {c['surface']}; }} +QWidget {{ color: {c['onSurface']}; }} +QToolTip {{ background: {c['inverseSurface']}; color: {c['inverseOnSurface']}; border: none; + border-radius: 6px; padding: 5px 8px; }} +QMenuBar {{ background: transparent; padding: 2px 6px; }} +QMenuBar::item {{ padding: 6px 12px; border-radius: 14px; background: transparent; }} +QMenuBar::item:selected {{ background: {hov}; }} +QMenuBar::item:pressed {{ background: {sel}; color: {c['onSecondaryContainer']}; }} +QMenu {{ background: {c['surfaceContainer']}; border: 1px solid {rgba(self.c['outlineVariant'], 0.5)}; + border-radius: 14px; padding: 8px 0; }} +QMenu::item {{ padding: 8px 28px 8px 14px; margin: 0 6px; border-radius: 10px; }} +QMenu::item:selected {{ background: {hov}; }} +QMenu::item:disabled {{ color: {rgba(self.c['onSurface'], 0.38)}; }} +QMenu::icon {{ padding-left: 10px; }} +QMenu::separator {{ height: 1px; background: {c['outlineVariant']}; margin: 6px 14px; }} +QMenu::indicator {{ width: 16px; height: 16px; margin-left: 8px; }} +QScrollBar:vertical {{ background: transparent; width: 10px; margin: 4px 2px; }} +QScrollBar:horizontal {{ background: transparent; height: 10px; margin: 2px 4px; }} +QScrollBar::handle {{ background: {rgba(self.c['onSurfaceVariant'], 0.35)}; border-radius: 3px; min-height: 32px; min-width: 32px; }} +QScrollBar::handle:hover {{ background: {rgba(self.c['onSurfaceVariant'], 0.6)}; }} +QScrollBar::add-line, QScrollBar::sub-line {{ width: 0; height: 0; }} +QScrollBar::add-page, QScrollBar::sub-page {{ background: transparent; }} +QLineEdit, QSpinBox, QDoubleSpinBox, QPlainTextEdit, QTextEdit, QDateEdit {{ + background: {c['surfaceContainerHighest']}; border: none; border-bottom: 1px solid {c['onSurfaceVariant']}; + border-top-left-radius: 6px; border-top-right-radius: 6px; padding: 7px 10px; + selection-background-color: {c['primary']}; selection-color: {c['onPrimary']}; }} +QLineEdit:focus, QSpinBox:focus, QDoubleSpinBox:focus, QPlainTextEdit:focus, QTextEdit:focus {{ + border-bottom: 2px solid {c['primary']}; }} +QLineEdit#search {{ background: {c['surfaceContainerHigh']}; border: none; border-radius: 19px; + padding: 0px 14px 0px 38px; }} +QLineEdit#search:focus {{ background: {c['surfaceContainerHighest']}; border: none; }} +QPushButton {{ background: {c['secondaryContainer']}; color: {c['onSecondaryContainer']}; border: none; + border-radius: 17px; padding: 8px 18px; min-height: 20px; font-weight: 500; }} +QPushButton:hover {{ background: {rgba(self.c['secondaryContainer'], 0.85)}; }} +QPushButton:pressed {{ background: {c['secondary']}; color: {c['onSecondary']}; }} +QPushButton:disabled {{ background: {rgba(self.c['onSurface'], 0.12)}; color: {rgba(self.c['onSurface'], 0.38)}; }} +QPushButton[primary="true"] {{ background: {c['primary']}; color: {c['onPrimary']}; }} +QPushButton[primary="true"]:hover {{ background: {rgba(self.c['primary'], 0.88)}; }} +QPushButton[flat="true"] {{ background: transparent; color: {c['primary']}; }} +QPushButton[flat="true"]:hover {{ background: {rgba(self.c['primary'], 0.08)}; }} +QPushButton::menu-indicator {{ width: 0; }} +QToolButton {{ background: transparent; border: none; border-radius: 18px; padding: 6px; }} +QToolButton:hover {{ background: {hov}; }} +QToolButton:pressed {{ background: {prs}; }} +QToolButton:checked {{ background: {sel}; color: {c['onSecondaryContainer']}; }} +QToolButton::menu-indicator {{ image: none; width: 0; }} +QComboBox {{ background: {c['surfaceContainerHighest']}; border: none; border-radius: 10px; + padding: 7px 12px; min-height: 20px; }} +QComboBox:hover {{ background: {rgba(self.c['surfaceContainerHighest'], 0.8)}; }} +QComboBox::drop-down {{ border: none; width: 26px; }} +QComboBox::down-arrow {{ image: url({a_down}); width: 18px; height: 18px; }} +QSpinBox::up-button, QSpinBox::down-button, QDoubleSpinBox::up-button, QDoubleSpinBox::down-button {{ border: none; width: 18px; background: transparent; }} +QSpinBox::up-arrow, QDoubleSpinBox::up-arrow {{ image: url({a_up}); width: 14px; height: 14px; }} +QSpinBox::down-arrow, QDoubleSpinBox::down-arrow {{ image: url({a_down}); width: 14px; height: 14px; }} +QComboBox QAbstractItemView {{ background: {c['surfaceContainer']}; border: none; border-radius: 10px; + padding: 6px; selection-background-color: {sel}; selection-color: {c['onSecondaryContainer']}; }} +QCheckBox, QRadioButton {{ spacing: 10px; }} +QCheckBox::indicator, QRadioButton::indicator {{ width: 18px; height: 18px; border-radius: 4px; + border: 2px solid {c['onSurfaceVariant']}; background: transparent; }} +QRadioButton::indicator {{ border-radius: 11px; }} +QCheckBox::indicator:checked {{ background: {c['primary']}; border-color: {c['primary']}; image: url({a_check}); }} +QRadioButton::indicator:checked {{ background: {c['primary']}; border: 5px solid {c['surfaceContainerHighest']}; outline: none; }} +QGroupBox {{ background: {c['surfaceContainerLow']}; border: none; border-radius: 16px; + margin-top: 26px; padding: 14px 12px 10px 12px; font-weight: 600; }} +QGroupBox::title {{ subcontrol-origin: margin; left: 14px; top: 4px; color: {c['primary']}; }} +QTabWidget::pane {{ border: none; }} +QTabBar {{ background: transparent; qproperty-drawBase: 0; }} +QTabBar::tab {{ background: transparent; color: {c['onSurfaceVariant']}; padding: 8px 14px; margin: 4px 2px; + border-radius: 16px; min-width: 40px; }} +QTabBar::tab:hover {{ background: {hov}; color: {c['onSurface']}; }} +QTabBar::tab:selected {{ background: {sel}; color: {c['onSecondaryContainer']}; font-weight: 600; }} +QTabBar::close-button {{ subcontrol-position: right; image: url({a_close}); width: 14px; height: 14px; + border-radius: 7px; padding: 1px; }} +QTabBar::close-button:hover {{ image: url({a_close_h}); background: {hov}; }} +QTabBar::scroller {{ width: 28px; }} +QTabBar QToolButton {{ background: {c['surface']}; border-radius: 12px; }} +QTabBar QToolButton::left-arrow {{ image: url({a_left}); }} +QTabBar QToolButton::right-arrow {{ image: url({a_right}); }} +QTreeView, QListView, QTableView {{ background: transparent; border: none; + selection-background-color: {sel}; selection-color: {c['onSecondaryContainer']}; + alternate-background-color: {rgba(self.c['onSurface'], 0.025)}; }} +QTreeView::item, QListView::item {{ padding: 4px 4px; border-radius: 10px; }} +QTreeView::item:hover, QListView::item:hover {{ background: {hov}; }} +QTreeView::item:selected, QListView::item:selected {{ background: {sel}; color: {c['onSecondaryContainer']}; }} +QTreeView::branch {{ background: transparent; }} +QTreeView::branch:has-children:closed {{ image: url({a_bc}); }} +QTreeView::branch:has-children:open {{ image: url({a_bo}); }} +QTableView {{ gridline-color: transparent; }} +QHeaderView {{ background: transparent; border: none; }} +QHeaderView::section {{ background: transparent; color: {c['onSurfaceVariant']}; border: none; + border-bottom: 1px solid {c['outlineVariant']}; padding: 6px 8px; font-weight: 600; }} +QHeaderView::section:hover {{ background: {hov}; }} +QHeaderView::down-arrow {{ image: url({a_down}); width: 14px; height: 14px; }} +QHeaderView::up-arrow {{ image: url({a_up}); width: 14px; height: 14px; }} +QSplitter::handle {{ background: transparent; }} +QSplitter::handle:hover {{ background: {rgba(self.c['primary'], 0.25)}; }} +QProgressBar {{ background: {c['secondaryContainer']}; border: none; border-radius: 3px; max-height: 6px; text-align: center; }} +QProgressBar::chunk {{ background: {c['primary']}; border-radius: 3px; }} +QSlider::groove:horizontal {{ height: 6px; background: {c['secondaryContainer']}; border-radius: 3px; }} +QSlider::sub-page:horizontal {{ background: {c['primary']}; border-radius: 3px; }} +QSlider::handle:horizontal {{ background: {c['primary']}; width: 4px; margin: -8px 2px; border-radius: 2px; }} +QSlider::groove:vertical {{ width: 6px; background: {c['secondaryContainer']}; border-radius: 3px; }} +QSlider::add-page:vertical {{ background: {c['primary']}; border-radius: 3px; }} +QSlider::handle:vertical {{ background: {c['primary']}; height: 4px; margin: 2px -8px; border-radius: 2px; }} +QListWidget#navlist {{ background: transparent; }} +QListWidget#navlist::item {{ padding: 10px 14px; border-radius: 22px; margin: 2px 6px; }} +QListWidget#navlist::item:selected {{ background: {sel}; color: {c['onSecondaryContainer']}; font-weight: 600; }} +QFrame#card {{ background: {c['surfaceContainerLow']}; border-radius: 20px; }} +QLabel#muted {{ color: {c['onSurfaceVariant']}; }} +QLabel#heading {{ font-size: 15pt; font-weight: 600; }} +QStatusBar {{ background: transparent; }} +QDialogButtonBox QPushButton {{ min-width: 72px; }} +""" + + +theme: Theme | None = None + + +def init_theme() -> Theme: + global theme + theme = Theme() + theme.apply() + return theme diff --git a/mulberry/widgets/__init__.py b/mulberry/widgets/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/mulberry/widgets/analyzer.py b/mulberry/widgets/analyzer.py new file mode 100644 index 0000000..926127f --- /dev/null +++ b/mulberry/widgets/analyzer.py @@ -0,0 +1,108 @@ +"""Strawberry-style block spectrum analyzer for the bottom bar. + +Drawn in three batched passes per frame (cached dim grid, one gradient bar per +band, gap mask, peaks) instead of hundreds of individual blocks. +""" +from __future__ import annotations + +from PyQt6.QtCore import QRectF, Qt +from PyQt6.QtGui import QLinearGradient, QPainter, QPixmap +from PyQt6.QtWidgets import QSizePolicy, QWidget + +from .. import theme as Th +from .m3 import C, with_alpha + +BW, GAP, BH, BGAP = 6, 2, 3, 1 + + +class Analyzer(QWidget): + def __init__(self, spectrum, parent=None): + super().__init__(parent) + self.spectrum = spectrum + self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed) + self.setFixedHeight(38) + self._acq = False + self._grid: QPixmap | None = None + self._mask: QPixmap | None = None + self._key = None + spectrum.updated.connect(self._upd) + self.setToolTip("Spectrum analyzer") + + def _upd(self): + if self.isVisible(): + self.update() + + def showEvent(self, e): + if not self._acq: + self.spectrum.acquire() + self._acq = True + + def hideEvent(self, e): + if self._acq: + self.spectrum.release() + self._acq = False + + def _layout(self): + n = max(4, (self.width() + GAP) // (BW + GAP)) + rows = max(2, (self.height() + BGAP) // (BH + BGAP)) + return n, rows + + def _build(self, n, rows): + dpr = self.devicePixelRatioF() + w, h = self.width(), self.height() + grid = QPixmap(int(w * dpr), int(h * dpr)) + grid.setDevicePixelRatio(dpr) + grid.fill(Qt.GlobalColor.transparent) + p = QPainter(grid) + dim = with_alpha(C("onSurfaceVariant"), 0.10) + for i in range(n): + for j in range(rows): + p.fillRect(QRectF(i * (BW + GAP), h - (j + 1) * (BH + BGAP) + BGAP, BW, BH), dim) + p.end() + # mask = horizontal gaps painted in the bar's background colour + mask = QPixmap(int(w * dpr), int(h * dpr)) + mask.setDevicePixelRatio(dpr) + mask.fill(Qt.GlobalColor.transparent) + p = QPainter(mask) + bg = Th.theme.c["surface"] + for j in range(rows + 1): + y = h - j * (BH + BGAP) + p.fillRect(QRectF(0, y, w, BGAP), bg) + p.fillRect(QRectF(0, 0, w, max(0, h - rows * (BH + BGAP))), bg) + p.end() + self._grid, self._mask = grid, mask + + def paintEvent(self, e): + n, rows = self._layout() + key = (self.width(), self.height(), self.devicePixelRatioF(), Th.theme.c["surface"].rgb(), + Th.theme.c["onSurfaceVariant"].rgb()) + if key != self._key: + self._build(n, rows) + self._key = key + p = QPainter(self) + p.drawPixmap(0, 0, self._grid) + h = self.height() + unit = BH + BGAP + lv = self.spectrum.resample(n) + pk = self.spectrum.resample_peaks(n) + prim = C("primary") + g = QLinearGradient(0, h, 0, 0) + g.setColorAt(0, with_alpha(prim, 0.38)) + g.setColorAt(1, with_alpha(prim, 1.0)) + bars, peaks = [], [] + for i in range(n): + lit = int(round(float(lv[i]) * rows)) + x = i * (BW + GAP) + if lit: + bars.append(QRectF(x, h - lit * unit, BW, lit * unit)) + pki = int(round(float(pk[i]) * rows)) + if pki > lit and pki > 0: + peaks.append(QRectF(x, h - pki * unit + BGAP, BW, BH)) + p.setPen(Qt.PenStyle.NoPen) + if bars: + p.setBrush(g) + p.drawRects(bars) + p.drawPixmap(0, 0, self._mask) + if peaks: + p.setBrush(with_alpha(C("tertiary"), 0.95)) + p.drawRects(peaks) diff --git a/mulberry/widgets/bassshape.py b/mulberry/widgets/bassshape.py new file mode 100644 index 0000000..9e3291b --- /dev/null +++ b/mulberry/widgets/bassshape.py @@ -0,0 +1,222 @@ +"""Floating bass-reactive shape (bottom-left). + +A Material 3 Expressive style blob that morphs between shapes — circle, +rounded square, cookies, clover, burst, pill, organic blob — on bass hits, +spins, pulses in size with the low end and glides through the theme colours. +""" +from __future__ import annotations + +import math +import random + +import numpy as np +from PyQt6.QtCore import QPointF, QRectF, Qt, pyqtSignal +from PyQt6.QtGui import QPainter, QPainterPath, QRadialGradient +from PyQt6.QtWidgets import QMenu, QWidget + +from .. import theme as Th +from ..clock import FrameClock +from ..theme import mix +from .m3 import with_alpha + +N = 144 +_T = np.linspace(0, 2 * np.pi, N, endpoint=False) + + +def _norm(r): + return r / r.mean() + + +def _superellipse(n): + c, s = np.abs(np.cos(_T)), np.abs(np.sin(_T)) + return (c ** n + s ** n) ** (-1.0 / n) + + +def _polygon(k, roundness=0.45): + seg = 2 * np.pi / k + poly = np.cos(np.pi / k) / np.cos((_T % seg) - np.pi / k) + return poly * (1 - roundness) + roundness * poly.mean() + + +SHAPES = { + "circle": _norm(np.ones(N)), + "square": _norm(_superellipse(4.2)), + "cookie4": _norm(1 + 0.13 * np.cos(4 * _T)), + "cookie6": _norm(1 + 0.09 * np.cos(6 * _T)), + "cookie9": _norm(1 + 0.065 * np.cos(9 * _T)), + "cookie12": _norm(1 + 0.05 * np.cos(12 * _T)), + "clover": _norm(1 + 0.26 * np.abs(np.cos(2 * _T))), + "burst": _norm(1 + 0.1 * np.cos(8 * _T)), + "pentagon": _norm(_polygon(5)), + "triangle": _norm(_polygon(3, 0.55)), + "pill": _norm(1 / np.sqrt((np.cos(_T) / 1.0) ** 2 + (np.sin(_T) / 0.74) ** 2)), + "blob": _norm(1 + 0.08 * np.cos(3 * _T + 1.1) + 0.05 * np.cos(5 * _T + 2.3)), +} +COLOR_ROLES = ("primary", "tertiary", "secondary", "mix") + + +def _ease(t): + # emphasized-decelerate feel with a little overshoot + t = max(0.0, min(1.0, t)) + c1, c3 = 1.4, 2.4 + return 1 + c3 * (t - 1) ** 3 + c1 * (t - 1) ** 2 + + +class BassShape(QWidget): + hide_requested = pyqtSignal() + + def __init__(self, spectrum, player, parent=None): + super().__init__(parent) + self.spectrum, self.player = spectrum, player + self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground) + self.setFixedSize(96, 96) + self.setCursor(Qt.CursorShape.PointingHandCursor) + self.setToolTip("Click: play / pause · Right-click: options") + self.cur_name = "cookie9" + self.r_from = SHAPES["circle"].copy() + self.r_to = SHAPES[self.cur_name].copy() + self.r = self.r_to.copy() + self.morph_t = 1.0 + self.rot = 0.0 + self.spin = 0.0 + self.kick = 0.0 # scale spring position + self.kick_v = 0.0 # spring velocity + self.since_morph = 0.0 + self.time = 0.0 + self.color_idx = 0 + self.col_t = 1.0 + self.col_from = None + self._ticking = False + self._acquired = False + spectrum.beat.connect(self._on_beat) + player.state_changed.connect(lambda *_: self._sync()) + Th.theme.changed.connect(self.update) + + # ------------------------------------------------------------ lifecycle + def _sync(self): + vis = self.isVisible() + if vis and not self._acquired: + self.spectrum.acquire() + self._acquired = True + elif not vis and self._acquired: + self.spectrum.release() + self._acquired = False + need = vis + if need and not self._ticking: + FrameClock.subscribe(self._tick) + self._ticking = True + elif not need and self._ticking: + FrameClock.unsubscribe(self._tick) + self._ticking = False + + def showEvent(self, e): + self._sync() + + def hideEvent(self, e): + self._sync() + + # ------------------------------------------------------------ behaviour + def _color(self, idx): + role = COLOR_ROLES[idx % len(COLOR_ROLES)] + c = Th.theme.c + if role == "mix": + return mix(c["primary"], c["tertiary"], 0.5) + return c[role] + + def _morph_to(self, name=None): + names = [n for n in SHAPES if n != self.cur_name] + name = name or random.choice(names) + self.r_from = self.r.copy() + self.r_to = SHAPES[name] + self.cur_name = name + self.morph_t = 0.0 + self.since_morph = 0.0 + + def _on_beat(self, strength): + if not self.isVisible(): + return + self.kick_v += 2.2 + 3.0 * strength + self.spin += 90 + 160 * strength + if self.since_morph > 0.32: + self._morph_to() + self.col_from = self._current_color() + self.color_idx += 1 + self.col_t = 0.0 + + def _current_color(self): + target = self._color(self.color_idx) + if self.col_from is None or self.col_t >= 1: + return target + return mix(self.col_from, target, self.col_t) + + def _tick(self, dt): + playing = self.player.state == "playing" + self.time += dt + self.since_morph += dt + # morph progress + if self.morph_t < 1: + self.morph_t = min(1.0, self.morph_t + dt / 0.5) + e = _ease(self.morph_t) + self.r = self.r_from + (self.r_to - self.r_from) * e + # idle morph every few seconds while playing so it never feels stuck + if playing and self.since_morph > 4.5: + self._morph_to() + self.col_from = self._current_color() + self.color_idx += 1 + self.col_t = 0.0 + if self.col_t < 1: + self.col_t = min(1.0, self.col_t + dt / 0.7) + # spring for the size kick (critically-ish damped) + k, damp = 90.0, 11.0 + acc = -k * self.kick - damp * self.kick_v + self.kick_v += acc * dt + self.kick += self.kick_v * dt + # spin: steady drift + decaying kicks + base = 24.0 if playing else 6.0 + self.spin += (0.0 - self.spin) * min(1.0, dt * 2.2) + self.rot = (self.rot + (base + self.spin) * dt) % 360 + self.update() + + # ------------------------------------------------------------ input + def mouseReleaseEvent(self, e): + if e.button() == Qt.MouseButton.LeftButton: + self.player.play_pause() + self.kick_v += 3 + self._morph_to() + + def contextMenuEvent(self, e): + m = QMenu(self) + m.addAction("Change shape", self._morph_to) + m.addAction("Hide floating shape", self.hide_requested.emit) + m.exec(e.globalPos()) + + # ------------------------------------------------------------ paint + def paintEvent(self, e): + p = QPainter(self) + p.setRenderHint(QPainter.RenderHint.Antialiasing) + cx, cy = self.width() / 2, self.height() / 2 + bass = self.spectrum.bass if self.player.state == "playing" else 0.0 + breathe = 0.025 * math.sin(self.time * 1.7) + scale = 0.62 + 0.16 * bass + 0.12 * max(-0.5, self.kick) + breathe + R = (min(self.width(), self.height()) / 2 - 6) * max(0.35, min(scale, 1.0)) + rot = math.radians(self.rot) + rr = self.r * R + ang = _T + rot + xs, ys = cx + rr * np.cos(ang), cy + rr * np.sin(ang) + path = QPainterPath(QPointF(xs[0], ys[0])) + for i in range(1, N): + path.lineTo(xs[i], ys[i]) + path.closeSubpath() + col = self._current_color() + # soft glow + glow = QRadialGradient(QPointF(cx, cy), R * 1.45) + glow.setColorAt(0.55, with_alpha(col, 0.28 + 0.25 * bass)) + glow.setColorAt(1.0, with_alpha(col, 0.0)) + p.setPen(Qt.PenStyle.NoPen) + p.setBrush(glow) + p.drawEllipse(QRectF(cx - R * 1.45, cy - R * 1.45, R * 2.9, R * 2.9)) + # body with a gentle top-left highlight + g = QRadialGradient(QPointF(cx - R * 0.35, cy - R * 0.4), R * 1.6) + g.setColorAt(0.0, mix(col, Th.theme["onPrimary"] if not Th.theme.dark else col.lighter(125), 0.18)) + g.setColorAt(1.0, col) + p.fillPath(path, g) diff --git a/mulberry/widgets/dialogs.py b/mulberry/widgets/dialogs.py new file mode 100644 index 0000000..274b5af --- /dev/null +++ b/mulberry/widgets/dialogs.py @@ -0,0 +1,1069 @@ +"""Settings, tag editor, MusicBrainz lookup, cover manager, equalizer, +CD ripper, lyrics editor and about dialogs.""" +from __future__ import annotations + +import os + +from PyQt6.QtCore import QSize, Qt, QTimer +from PyQt6.QtGui import QColor, QFont, QIcon, QImage, QPixmap +from PyQt6.QtWidgets import (QCheckBox, QColorDialog, QComboBox, QDialog, QDialogButtonBox, + QDoubleSpinBox, QFileDialog, QFontComboBox, QFormLayout, QGridLayout, + QGroupBox, QHBoxLayout, QLabel, QLineEdit, QListWidget, + QListWidgetItem, QMessageBox, QPlainTextEdit, QProgressBar, + QPushButton, QSlider, QSpinBox, QStackedWidget, QTableWidget, + QTableWidgetItem, QVBoxLayout, QWidget, QAbstractItemView, + QHeaderView) + +from .. import cd as CD +from .. import library as L +from .. import online +from .. import tags as T +from .. import theme as Th +from ..config import APP_NAME, VERSION, fmt_time, run_async, settings +from ..icons import icon +from ..player import EQ_FREQS, EQ_PRESETS, Player, mpv_available +from ..scrobble import LastFM +from ..song import Song + + +def _primary(btn): + btn.setProperty("primary", True) + return btn + + +def _buttons(dlg, ok_text="Save"): + bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) + bb.button(QDialogButtonBox.StandardButton.Ok).setText(ok_text) + _primary(bb.button(QDialogButtonBox.StandardButton.Ok)) + bb.accepted.connect(dlg.accept) + bb.rejected.connect(dlg.reject) + return bb + + +# ====================================================================== settings +class SettingsDialog(QDialog): + def __init__(self, window, page=0): + super().__init__(window) + self.w = window + self.setWindowTitle("Settings") + self.resize(820, 600) + lay = QHBoxLayout(self) + lay.setContentsMargins(12, 12, 12, 12) + self.nav = QListWidget() + self.nav.setObjectName("navlist") + self.nav.setFixedWidth(200) + self.nav.setIconSize(QSize(22, 22)) + self.stack = QStackedWidget() + pages = [("Library", "library_music", self._p_library), ("Playback", "graphic_eq", self._p_playback), + ("Appearance", "palette", self._p_appearance), ("Scrobbling", "scrobble", self._p_scrobble), + ("Metadata", "cloud_download", self._p_meta), ("Audio CD", "album", self._p_cd)] + for name, ic, fn in pages: + it = QListWidgetItem(icon(ic), name, self.nav) + it.setSizeHint(QSize(0, 46)) + pg = QWidget() + pl = QVBoxLayout(pg) + pl.setContentsMargins(12, 0, 4, 0) + fn(pl) + pl.addStretch(1) + self.stack.addWidget(pg) + self.nav.currentRowChanged.connect(self.stack.setCurrentIndex) + self.nav.setCurrentRow(page) + right = QVBoxLayout() + right.addWidget(self.stack, 1) + right.addWidget(_buttons(self)) + lay.addWidget(self.nav) + lay.addLayout(right, 1) + + # ------------------------------------------------------------ pages + def _p_library(self, lay): + g = QGroupBox("Music folders") + gl = QVBoxLayout(g) + self.folders = QListWidget() + self.folders.setMinimumHeight(140) + for f in settings.get("library/folders"): + QListWidgetItem(icon("folder"), f, self.folders) + gl.addWidget(self.folders) + row = QHBoxLayout() + add = QPushButton(icon("add", "onSecondaryContainer"), " Add folder…") + rem = QPushButton(icon("delete", "onSecondaryContainer"), " Remove") + add.clicked.connect(self._add_folder) + rem.clicked.connect(lambda: [self.folders.takeItem(self.folders.row(i)) for i in self.folders.selectedItems()]) + row.addWidget(add) + row.addWidget(rem) + row.addStretch(1) + gl.addLayout(row) + lay.addWidget(g) + g2 = QGroupBox("Scanning") + g2l = QVBoxLayout(g2) + self.scan_start = QCheckBox("Update the library when Mulberry starts") + self.scan_start.setChecked(settings.get("library/scan_on_start")) + g2l.addWidget(self.scan_start) + row = QHBoxLayout() + b1 = QPushButton(icon("refresh", "onSecondaryContainer"), " Update now") + b2 = QPushButton(icon("sync", "onSecondaryContainer"), " Full rescan") + b1.clicked.connect(lambda: (self._save_folders(), L.library.scan(False))) + b2.clicked.connect(lambda: (self._save_folders(), L.library.scan(True))) + row.addWidget(b1) + row.addWidget(b2) + row.addStretch(1) + g2l.addLayout(row) + lay.addWidget(g2) + + def _add_folder(self): + d = QFileDialog.getExistingDirectory(self, "Add music folder", os.path.expanduser("~/Music")) + if d: + QListWidgetItem(icon("folder"), d, self.folders) + + def _save_folders(self): + settings.set("library/folders", [self.folders.item(i).text() for i in range(self.folders.count())]) + + def _p_playback(self, lay): + g = QGroupBox("Engine") + f = QFormLayout(g) + self.backend = QComboBox() + self.backend.addItem("Automatic (mpv on Linux, Qt on Windows)", "auto") + self.backend.addItem("mpv / libmpv — gapless, EQ, ReplayGain, CD", "mpv") + self.backend.addItem("Qt Multimedia (FFmpeg)", "qt") + self.backend.setCurrentIndex(max(0, self.backend.findData(settings.get("playback/backend")))) + f.addRow("Backend", self.backend) + cur = Player.instance.backend.name + note = QLabel(f"In use: {cur}" + ("" if mpv_available() else + " — libmpv not found; install mpv for gapless, EQ and CD playback.") + + "
Backend changes apply after restart.") + note.setObjectName("muted") + note.setWordWrap(True) + f.addRow("", note) + self.device = QComboBox() + self.device.addItem("System default", "") + for dev, desc in Player.instance.backend.devices(): + if dev in ("auto",): + continue + self.device.addItem(desc, dev) + i = self.device.findData(settings.get("playback/device")) + self.device.setCurrentIndex(max(0, i)) + f.addRow("Output device", self.device) + lay.addWidget(g) + g2 = QGroupBox("Playback") + f2 = QFormLayout(g2) + self.gapless = QCheckBox("Gapless playback (mpv)") + self.gapless.setChecked(settings.get("playback/gapless")) + f2.addRow(self.gapless) + self.rg = QComboBox() + for k, t in (("off", "Off"), ("track", "Track gain"), ("album", "Album gain")): + self.rg.addItem(t, k) + self.rg.setCurrentIndex(max(0, self.rg.findData(settings.get("playback/replaygain")))) + f2.addRow("ReplayGain", self.rg) + self.rg_pre = QDoubleSpinBox() + self.rg_pre.setRange(-15, 15) + self.rg_pre.setSuffix(" dB") + self.rg_pre.setValue(settings.get("playback/rg_preamp")) + f2.addRow("ReplayGain pre-amp", self.rg_pre) + self.resume = QCheckBox("Resume the last track on start") + self.resume.setChecked(settings.get("playback/resume")) + f2.addRow(self.resume) + lay.addWidget(g2) + + def _p_appearance(self, lay): + g = QGroupBox("Colours") + f = QFormLayout(g) + self.csrc = QComboBox() + for k, t in (("kde", "Follow system accent & colours (KDE / Windows)"), ("album", "Dynamic — from album art"), + ("custom", "Custom colour")): + self.csrc.addItem(t, k) + self.csrc.setCurrentIndex(max(0, self.csrc.findData(settings.get("appearance/color_source")))) + f.addRow("Colour source", self.csrc) + self.custom = QPushButton() + self._custom_col = QColor(settings.get("appearance/custom_color")) + self._paint_custom() + self.custom.clicked.connect(self._pick_color) + f.addRow("Custom colour", self.custom) + self.mode = QComboBox() + for k, t in (("kde", "Follow system (light/dark)"), ("dark", "Dark"), ("light", "Light")): + self.mode.addItem(t, k) + self.mode.setCurrentIndex(max(0, self.mode.findData(settings.get("appearance/mode")))) + f.addRow("Mode", self.mode) + self.font = QFontComboBox() + self.font_default = QCheckBox("Use system font") + fam = settings.get("appearance/font") + self.font_default.setChecked(not fam) + if fam: + self.font.setCurrentFont(QFont(fam)) + self.font.setEnabled(bool(fam)) + self.font_default.toggled.connect(lambda on: self.font.setEnabled(not on)) + frow = QHBoxLayout() + frow.addWidget(self.font_default) + frow.addWidget(self.font, 1) + f.addRow("Font", frow) + lay.addWidget(g) + g2 = QGroupBox("Layout") + f2 = QFormLayout(g2) + self.hero = QComboBox() + for k, t in (("full", "Large (cover, visualizer, lyrics)"), ("compact", "Compact bar"), ("hidden", "Hidden")): + self.hero.addItem(t, k) + self.hero.setCurrentIndex(max(0, self.hero.findData(settings.get("appearance/hero")))) + f2.addRow("Now playing panel", self.hero) + self.vis = QCheckBox("Radial visualizer around the cover") + self.vis.setChecked(settings.get("appearance/visualizer")) + self.ana = QCheckBox("Spectrum analyzer in the bottom bar") + self.ana.setChecked(settings.get("appearance/analyzer")) + self.artbg = QCheckBox("Album art behind the playlist") + self.artbg.setChecked(settings.get("appearance/playlist_art_bg")) + self.notif = QCheckBox("Desktop notification on track change") + self.notif.setChecked(settings.get("appearance/notifications")) + self.shape = QCheckBox("Floating bass shape (bottom-left) — morphs, spins and pulses with the beat") + self.shape.setChecked(settings.get("appearance/floating_shape")) + self.tray = QCheckBox("System tray icon (close to tray)") + self.tray.setChecked(settings.get("appearance/tray")) + for w in (self.vis, self.ana, self.shape, self.artbg, self.notif, self.tray): + f2.addRow(w) + lay.addWidget(g2) + + def _paint_custom(self): + pm = QPixmap(18, 18) + pm.fill(self._custom_col) + self.custom.setIcon(QIcon(pm)) + self.custom.setText(" " + self._custom_col.name()) + + def _pick_color(self): + c = QColorDialog.getColor(self._custom_col, self, "Seed colour") + if c.isValid(): + self._custom_col = c + self._paint_custom() + self.csrc.setCurrentIndex(self.csrc.findData("custom")) + + def _p_scrobble(self, lay): + g = QGroupBox("Last.fm") + v = QVBoxLayout(g) + top = QHBoxLayout() + self.lfm_avatar = QLabel() + self.lfm_avatar.setPixmap(icon("person", "primary").pixmap(40, 40)) + self.lfm_status = QLabel() + self.lfm_status.setWordWrap(True) + self.lfm_btn = _primary(QPushButton(icon("link", "onPrimary"), " Log in with Last.fm")) + self.lfm_btn.clicked.connect(self._lfm_login_clicked) + top.addWidget(self.lfm_avatar) + top.addWidget(self.lfm_status, 1) + top.addWidget(self.lfm_btn) + v.addLayout(top) + self.lfm_on = QCheckBox("Scrobble what I play and send “now playing”") + self.lfm_on.setChecked(settings.get("lastfm/enabled")) + v.addWidget(self.lfm_on) + self.lfm_own = QCheckBox("Use my own API key (manual / advanced)") + self.lfm_own.setChecked(settings.get("lastfm/use_own_key")) + v.addWidget(self.lfm_own) + self.lfm_keys = QWidget() + kf = QFormLayout(self.lfm_keys) + kf.setContentsMargins(26, 0, 0, 0) + hint = QLabel('Get a free key at
' + 'last.fm/api/account/create — any app name works, leave the callback empty.') + hint.setOpenExternalLinks(True) + hint.setWordWrap(True) + hint.setObjectName("muted") + kf.addRow(hint) + self.lfm_key = QLineEdit(settings.get("lastfm/api_key")) + self.lfm_key.setPlaceholderText("32-character API key") + self.lfm_secret = QLineEdit(settings.get("lastfm/api_secret")) + self.lfm_secret.setPlaceholderText("Shared secret") + self.lfm_secret.setEchoMode(QLineEdit.EchoMode.Password) + kf.addRow("API key", self.lfm_key) + kf.addRow("Shared secret", self.lfm_secret) + v.addWidget(self.lfm_keys) + self.lfm_own.toggled.connect(self.lfm_keys.setVisible) + self.lfm_keys.setVisible(self.lfm_own.isChecked()) + self._lfm_poll = QTimer(self, interval=3000) + self._lfm_poll.timeout.connect(self._lfm_poll_tick) + self._lfm_token = None + self._lfm_deadline = 0.0 + self._lfm_status() + lay.addWidget(g) + g2 = QGroupBox("ListenBrainz") + f2 = QFormLayout(g2) + self.lb_on = QCheckBox("Submit listens to ListenBrainz") + self.lb_on.setChecked(settings.get("listenbrainz/enabled")) + self.lb_token = QLineEdit(settings.get("listenbrainz/token")) + self.lb_token.setEchoMode(QLineEdit.EchoMode.Password) + self.lb_token.setPlaceholderText("User token from listenbrainz.org/settings") + f2.addRow(self.lb_on) + f2.addRow("User token", self.lb_token) + lay.addWidget(g2) + pend = self.w.scrobbler.pending() + if pend: + lbl = QLabel(f"{pend} scrobble(s) waiting to be sent.") + lbl.setObjectName("muted") + lay.addWidget(lbl) + + def _lfm_status(self, waiting=False): + user = settings.get("lastfm/user") + if waiting: + self.lfm_status.setText("Waiting for you to approve Mulberry in your browser…
" + "This updates by itself once you click “Yes, allow access”.") + self.lfm_btn.setText(" Cancel") + return + if settings.get("lastfm/session"): + self.lfm_status.setText(f"Logged in as {user}") + self.lfm_btn.setText(" Log out") + self.lfm_btn.setIcon(icon("close", "onPrimary")) + else: + self.lfm_status.setText("Not logged in") + self.lfm_btn.setText(" Log in with Last.fm") + self.lfm_btn.setIcon(icon("link", "onPrimary")) + + def _lfm_login_clicked(self): + if self._lfm_poll.isActive(): + self._lfm_poll.stop() + self._lfm_status() + return + if settings.get("lastfm/session"): + settings.set("lastfm/session", "") + settings.set("lastfm/user", "") + self._lfm_status() + return + settings.set("lastfm/use_own_key", self.lfm_own.isChecked()) + settings.set("lastfm/api_key", self.lfm_key.text().strip()) + settings.set("lastfm/api_secret", self.lfm_secret.text().strip()) + if not LastFM.has_key(): + self.lfm_own.setChecked(True) + self.lfm_key.setFocus() + QMessageBox.information( + self, "Last.fm", + "This copy of Mulberry has no built-in Last.fm app key yet.\n\n" + "Last.fm gives keys per application, so paste one once: open the link under " + "“Use my own API key”, create a key (takes a minute), paste the key and secret, " + "then press Log in again.") + return + + def got_token(token): + from PyQt6.QtCore import QUrl + from PyQt6.QtGui import QDesktopServices + import time as _t + self._lfm_token = token + self._lfm_deadline = _t.monotonic() + 300 + QDesktopServices.openUrl(QUrl(LastFM.auth_url(token))) + self._lfm_status(waiting=True) + self._lfm_poll.start() + run_async(LastFM.begin_auth, on_done=got_token, + on_error=lambda e: QMessageBox.warning(self, "Last.fm", e)) + + def _lfm_poll_tick(self): + import time as _t + if not self._lfm_token or _t.monotonic() > self._lfm_deadline: + self._lfm_poll.stop() + self._lfm_status() + return + token = self._lfm_token + + def ok(res): + if not self._lfm_poll.isActive(): + return + self._lfm_poll.stop() + sk, name = res + settings.set("lastfm/session", sk) + settings.set("lastfm/user", name) + settings.set("lastfm/enabled", True) + self.lfm_on.setChecked(True) + self._lfm_status() + self.w.toast(f"Logged in to Last.fm as {name}") + + def err(msg): + # 14 = token not yet authorised: keep waiting; anything else stops + if "not been authorized" in msg.lower() or "unauthorized token" in msg.lower() or "14" in msg: + return + self._lfm_poll.stop() + self._lfm_status() + QMessageBox.warning(self, "Last.fm", msg) + run_async(LastFM.finish_auth, token, on_done=ok, on_error=err) + + def _p_meta(self, lay): + g = QGroupBox("Automatic fetching") + f = QFormLayout(g) + self.auto_lyr = QCheckBox("Fetch synced lyrics (LRCLIB) for the playing song") + self.auto_lyr.setChecked(settings.get("online/auto_lyrics")) + self.auto_cov = QCheckBox("Fetch missing album covers (iTunes, Deezer, Cover Art Archive)") + self.auto_cov.setChecked(settings.get("online/auto_covers")) + self.save_cov = QCheckBox("Also save fetched covers as cover.jpg in the album folder") + self.save_cov.setChecked(settings.get("online/save_covers_to_folder")) + for w in (self.auto_lyr, self.auto_cov, self.save_cov): + f.addRow(w) + lay.addWidget(g) + g2 = QGroupBox("Tag lookup") + f2 = QFormLayout(g2) + self.acoustid = QLineEdit(settings.get("online/acoustid_key")) + self.acoustid.setPlaceholderText("Optional — enables audio fingerprint matching (needs fpcalc)") + f2.addRow("AcoustID key", self.acoustid) + note = QLabel("Tag lookups use MusicBrainz. Right-click songs › Fetch tags.") + note.setObjectName("muted") + f2.addRow(note) + lay.addWidget(g2) + + def _p_cd(self, lay): + g = QGroupBox("Ripping") + f = QFormLayout(g) + self.rip_fmt = QComboBox() + for k, (label, _, _) in CD.FORMATS.items(): + self.rip_fmt.addItem(label, k) + self.rip_fmt.setCurrentIndex(max(0, self.rip_fmt.findData(settings.get("cd/rip_format")))) + self.rip_q = QSpinBox() + self.rip_q.setRange(0, 12) + self.rip_q.setValue(settings.get("cd/rip_quality")) + self.rip_dir = QLineEdit(settings.get("cd/rip_dir")) + browse = QPushButton("Browse…") + browse.clicked.connect(lambda: (d := QFileDialog.getExistingDirectory(self, "Rip to", self.rip_dir.text())) + and self.rip_dir.setText(d)) + drow = QHBoxLayout() + drow.addWidget(self.rip_dir, 1) + drow.addWidget(browse) + self.rip_pat = QLineEdit(settings.get("cd/rip_pattern")) + f.addRow("Format", self.rip_fmt) + f.addRow("Quality / level", self.rip_q) + f.addRow("Destination", drow) + f.addRow("File name pattern", self.rip_pat) + tools = CD.rip_tools() + lbl = QLabel("Tools: " + ", ".join(f"{k} {'✓' if v else '✗'}" for k, v in tools.items()) + + "
Fields: {albumartist} {artist} {album} {title} {track:02d} {disc} {year}") + lbl.setObjectName("muted") + lbl.setWordWrap(True) + f.addRow(lbl) + lay.addWidget(g) + + # ------------------------------------------------------------ apply + def accept(self): + self._save_folders() + s = settings + s.set("library/scan_on_start", self.scan_start.isChecked()) + s.set("playback/backend", self.backend.currentData()) + s.set("playback/gapless", self.gapless.isChecked()) + s.set("playback/replaygain", self.rg.currentData()) + s.set("playback/rg_preamp", self.rg_pre.value()) + s.set("playback/resume", self.resume.isChecked()) + dev = self.device.currentData() + if dev != s.get("playback/device"): + Player.instance.set_device(dev) + s.set("appearance/color_source", self.csrc.currentData()) + s.set("appearance/custom_color", self._custom_col.name()) + s.set("appearance/mode", self.mode.currentData()) + s.set("appearance/font", "" if self.font_default.isChecked() else self.font.currentFont().family()) + s.set("appearance/hero", self.hero.currentData()) + s.set("appearance/visualizer", self.vis.isChecked()) + s.set("appearance/analyzer", self.ana.isChecked()) + s.set("appearance/playlist_art_bg", self.artbg.isChecked()) + s.set("appearance/notifications", self.notif.isChecked()) + s.set("appearance/tray", self.tray.isChecked()) + s.set("appearance/floating_shape", self.shape.isChecked()) + s.set("lastfm/enabled", self.lfm_on.isChecked()) + s.set("lastfm/use_own_key", self.lfm_own.isChecked()) + s.set("lastfm/api_key", self.lfm_key.text().strip()) + s.set("lastfm/api_secret", self.lfm_secret.text().strip()) + s.set("listenbrainz/enabled", self.lb_on.isChecked()) + s.set("listenbrainz/token", self.lb_token.text().strip()) + s.set("online/auto_lyrics", self.auto_lyr.isChecked()) + s.set("online/auto_covers", self.auto_cov.isChecked()) + s.set("online/save_covers_to_folder", self.save_cov.isChecked()) + s.set("online/acoustid_key", self.acoustid.text().strip()) + s.set("cd/rip_format", self.rip_fmt.currentData()) + s.set("cd/rip_quality", self.rip_q.value()) + s.set("cd/rip_dir", self.rip_dir.text()) + s.set("cd/rip_pattern", self.rip_pat.text()) + Player.instance.apply_audio_settings() + if s.get("appearance/color_source") == "album" and self.w.np.image is not None: + Th.theme.album_seed = Th.dominant_color(self.w.np.image) + Th.theme.rebuild() + self.w.apply_layout_settings() + super().accept() + + +# ====================================================================== tag editor +FIELDS = [("title", "Title"), ("artist", "Artist"), ("album", "Album"), ("albumartist", "Album artist"), + ("genre", "Genre"), ("composer", "Composer"), ("year", "Year"), ("track", "Track"), + ("disc", "Disc"), ("comment", "Comment")] + + +class TagEditor(QDialog): + def __init__(self, songs: list[Song], window): + super().__init__(window) + self.w = window + self.songs = [s for s in songs if s.is_local and os.path.exists(s.path)] + self.setWindowTitle(f"Edit tags — {len(self.songs)} file(s)") + self.resize(760, 520) + self.new_cover: bytes | None = None + self.remove_cover = False + lay = QHBoxLayout(self) + left = QVBoxLayout() + self.cover = QLabel() + self.cover.setFixedSize(220, 220) + self.cover.setAlignment(Qt.AlignmentFlag.AlignCenter) + self.cover.setStyleSheet(f"background:{Th.theme['surfaceContainerHigh'].name()}; border-radius: 20px;") + left.addWidget(self.cover) + for text, ic, fn in (("Load image…", "image", self._load_img), ("Search online…", "travel_explore", self._search_cover), + ("Remove cover", "delete", self._rm_cover)): + b = QPushButton(icon(ic, "onSecondaryContainer"), " " + text) + b.clicked.connect(fn) + left.addWidget(b) + left.addStretch(1) + mb = _primary(QPushButton(icon("cloud_download", "onPrimary"), " Fetch from MusicBrainz")) + mb.clicked.connect(self._mb) + mb.setEnabled(len(self.songs) >= 1) + left.addWidget(mb) + lay.addLayout(left) + right = QVBoxLayout() + form = QFormLayout() + self.edits = {} + for key, label in FIELDS: + vals = {str(getattr(s, key) or "") for s in self.songs} + e = QLineEdit() + if len(vals) == 1: + e.setText(vals.pop()) + else: + e.setPlaceholderText("(multiple values — leave empty to keep)") + e.setProperty("orig", e.text()) + self.edits[key] = e + form.addRow(label, e) + right.addLayout(form) + if len(self.songs) == 1: + s = self.songs[0] + info = QLabel(f"{s.filetype} · {fmt_time(s.length)} · {s.bitrate} kbps · {s.samplerate} Hz\n{s.path}") + info.setObjectName("muted") + info.setWordWrap(True) + right.addWidget(info) + right.addStretch(1) + right.addWidget(_buttons(self)) + lay.addLayout(right, 1) + self._show_cover() + + def _show_cover(self): + img = QImage() + if self.new_cover: + img.loadFromData(self.new_cover) + elif not self.remove_cover and self.songs: + s = self.songs[0] + data = T.extract_embedded_cover(s.path) + if data: + img.loadFromData(data) + elif s.art: + img.load(s.art) + if img.isNull(): + self.cover.setPixmap(icon("album").pixmap(96, 96)) + else: + self.cover.setPixmap(QPixmap.fromImage(img.scaled(220, 220, Qt.AspectRatioMode.KeepAspectRatio, + Qt.TransformationMode.SmoothTransformation))) + + def _load_img(self): + p, _ = QFileDialog.getOpenFileName(self, "Choose cover", os.path.dirname(self.songs[0].path) if self.songs else "", + "Images (*.jpg *.jpeg *.png *.webp *.bmp)") + if p: + img = QImage(p) + if not img.isNull(): + self.new_cover = T.image_to_jpeg_bytes(img) + self.remove_cover = False + self._show_cover() + + def _search_cover(self): + if not self.songs: + return + dlg = CoverManager(self.songs[0], self, apply_immediately=False) + if dlg.exec() and dlg.result_image is not None: + self.new_cover = T.image_to_jpeg_bytes(dlg.result_image) + self.remove_cover = False + self._show_cover() + + def _rm_cover(self): + self.new_cover = None + self.remove_cover = True + self._show_cover() + + def _mb(self): + dlg = MusicBrainzDialog(self.songs[0], self) + if dlg.exec() and dlg.choice: + c = dlg.choice + single = len(self.songs) == 1 + for k in ("artist", "album", "albumartist", "year"): + if c.get(k): + self.edits[k].setText(str(c[k])) + if single: + for k in ("title", "track", "disc"): + if c.get(k): + self.edits[k].setText(str(c[k])) + if c.get("genre"): + self.edits["genre"].setText(c["genre"]) + self._mb_ids = (c.get("mb_trackid", "") if single else "", c.get("mb_albumid", "")) + + def accept(self): + changes = {} + for key, e in self.edits.items(): + if e.text() != e.property("orig") or (e.placeholderText() and e.text()): + changes[key] = e.text().strip() + ids = getattr(self, "_mb_ids", None) + if ids: + if ids[0]: + changes["mb_trackid"] = ids[0] + if ids[1]: + changes["mb_albumid"] = ids[1] + cover, rm = self.new_cover, self.remove_cover + songs = list(self.songs) + if not changes and cover is None and not rm: + super().accept() + return + + def work(): + errs = [] + for s in songs: + try: + if changes: + T.write_tags(s.path, changes) + if cover is not None or rm: + T.embed_cover(s.path, cover) + except Exception as ex: # noqa: BLE001 + errs.append(f"{os.path.basename(s.path)}: {ex}") + return errs + + def done(errs): + for s in songs: + ns = L.library.reread(s.path) + if ns is None: + from .. import tags as TT + ns = TT.read_song(s.path) + if ns: + if cover is not None: + ns.art = T.store_cover(cover, T.album_key(ns.effective_albumartist(), ns.album, + os.path.dirname(ns.path))) or ns.art + if ns.art: + L.library.set_album_art(ns.effective_albumartist(), ns.album, ns.art) + self.w.song_replaced(s, ns) + if errs: + QMessageBox.warning(self.w, "Some files were not saved", "\n".join(errs[:20])) + else: + self.w.toast(f"Saved tags for {len(songs)} file(s)") + run_async(work, on_done=done, on_error=lambda e: QMessageBox.warning(self.w, "Tag editor", e)) + super().accept() + + +# ====================================================================== musicbrainz +class MusicBrainzDialog(QDialog): + def __init__(self, song: Song, parent): + super().__init__(parent) + self.song = song + self.choice = None + self.cands = [] + self.setWindowTitle("Fetch tags from MusicBrainz") + self.resize(880, 460) + lay = QVBoxLayout(self) + row = QHBoxLayout() + self.q_artist = QLineEdit(song.display_artist()) + self.q_title = QLineEdit(song.display_title()) + self.q_album = QLineEdit(song.album) + for w, ph in ((self.q_artist, "Artist"), (self.q_title, "Title"), (self.q_album, "Album")): + w.setPlaceholderText(ph) + row.addWidget(w) + b = QPushButton(icon("search", "onSecondaryContainer"), " Search") + b.clicked.connect(self.search) + row.addWidget(b) + fp = QPushButton(icon("fingerprint", "onSecondaryContainer"), " Fingerprint") + fp.setToolTip("Identify by audio fingerprint (AcoustID)") + fp.clicked.connect(self.fingerprint) + row.addWidget(fp) + lay.addLayout(row) + self.status = QLabel("Searching…") + self.status.setObjectName("muted") + lay.addWidget(self.status) + self.table = QTableWidget(0, 7) + self.table.setHorizontalHeaderLabels(["Title", "Artist", "Album", "Album artist", "Year", "Track", "Score"]) + self.table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows) + self.table.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection) + self.table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers) + self.table.verticalHeader().hide() + self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch) + self.table.doubleClicked.connect(self.accept) + lay.addWidget(self.table, 1) + self.genre = QCheckBox("Also fetch genre from MusicBrainz") + self.genre.setChecked(True) + lay.addWidget(self.genre) + lay.addWidget(_buttons(self, "Use selected")) + QTimer.singleShot(0, self.search) + + def search(self): + s = Song(title=self.q_title.text(), artist=self.q_artist.text(), album=self.q_album.text(), + length=self.song.length) + self.status.setText("Searching MusicBrainz…") + run_async(online.musicbrainz_search, s, on_done=self._fill, on_error=lambda e: self.status.setText(e)) + + def fingerprint(self): + self.status.setText("Fingerprinting…") + run_async(online.acoustid_lookup, self.song.path, on_done=self._fill, + on_error=lambda e: self.status.setText(e)) + + def _fill(self, cands): + self.cands = cands + self.table.setRowCount(len(cands)) + for r, c in enumerate(cands): + for col, k in enumerate(("title", "artist", "album", "albumartist", "year", "track", "score")): + self.table.setItem(r, col, QTableWidgetItem(str(c.get(k) or ""))) + self.status.setText(f"{len(cands)} result(s)" if cands else "No matches — try editing the search.") + if cands: + self.table.selectRow(0) + + def accept(self): + r = self.table.currentRow() + if 0 <= r < len(self.cands): + self.choice = dict(self.cands[r]) + if self.genre.isChecked() and self.choice.get("mb_albumid"): + self.choice["genre"] = online.musicbrainz_genre(self.choice["mb_albumid"]) + super().accept() + + +class BatchTagFetch: + """Apply best MusicBrainz match to many songs (album-wise) without prompts.""" + + @staticmethod + def run(window, songs: list[Song]): + songs = [s for s in songs if s.is_local] + if not songs: + return + window.toast(f"Fetching tags for {len(songs)} song(s)…") + + def work(): + done = [] + for s in songs: + c = online.musicbrainz_search(s, limit=5) + if not c or c[0]["score"] < 80: + continue + best = c[0] + vals = {k: best[k] for k in ("title", "artist", "album", "albumartist", "year", "track", "disc", + "mb_trackid", "mb_albumid") if best.get(k)} + try: + T.write_tags(s.path, vals) + done.append(s) + except Exception: # noqa: BLE001 + pass + return done + + def fin(done): + for s in done: + ns = L.library.reread(s.path) or T.read_song(s.path) + if ns: + ns.art = ns.art or s.art + window.song_replaced(s, ns) + window.toast(f"Updated tags for {len(done)} of {len(songs)} song(s)") + run_async(work, on_done=fin, on_error=window.toast) + + +# ====================================================================== covers +class CoverManager(QDialog): + def __init__(self, song: Song, parent, apply_immediately=True): + super().__init__(parent) + self.song = song + self.apply_immediately = apply_immediately + self.result_image: QImage | None = None + self.cands = [] + self.setWindowTitle("Album cover") + self.resize(860, 600) + lay = QVBoxLayout(self) + row = QHBoxLayout() + self.q_artist = QLineEdit(song.effective_albumartist()) + self.q_album = QLineEdit(song.album or song.display_title()) + row.addWidget(self.q_artist) + row.addWidget(self.q_album) + b = QPushButton(icon("search", "onSecondaryContainer"), " Search") + b.clicked.connect(self.search) + row.addWidget(b) + f = QPushButton(icon("image", "onSecondaryContainer"), " From file…") + f.clicked.connect(self._file) + row.addWidget(f) + lay.addLayout(row) + self.status = QLabel() + self.status.setObjectName("muted") + lay.addWidget(self.status) + self.grid = QListWidget() + self.grid.setViewMode(QListWidget.ViewMode.IconMode) + self.grid.setIconSize(QSize(180, 180)) + self.grid.setGridSize(QSize(206, 236)) + self.grid.setResizeMode(QListWidget.ResizeMode.Adjust) + self.grid.setMovement(QListWidget.Movement.Static) + self.grid.setWordWrap(True) + self.grid.itemDoubleClicked.connect(lambda *_: self.accept()) + lay.addWidget(self.grid, 1) + opts = QHBoxLayout() + self.embed = QCheckBox("Embed into the album's files") + self.to_folder = QCheckBox("Save cover.jpg in the album folder") + self.to_folder.setChecked(settings.get("online/save_covers_to_folder")) + opts.addWidget(self.embed) + opts.addWidget(self.to_folder) + opts.addStretch(1) + if apply_immediately: + lay.addLayout(opts) + lay.addWidget(_buttons(self, "Use cover")) + QTimer.singleShot(0, self.search) + + def search(self): + self.grid.clear() + self.status.setText("Searching cover providers…") + run_async(online.cover_candidates, self.q_artist.text(), self.q_album.text(), + on_done=self._fill, on_error=lambda e: self.status.setText(e)) + + def _fill(self, cands): + self.cands = cands + self.status.setText(f"{len(cands)} cover(s) found" if cands else "No covers found.") + for i, c in enumerate(cands): + it = QListWidgetItem(icon("image"), f"{c['source']}\n{c.get('label', '')}") + it.setData(Qt.ItemDataRole.UserRole, i) + self.grid.addItem(it) + + def got(data, it=it): + img = QImage() + img.loadFromData(data) + if not img.isNull(): + try: + it.setIcon(QIcon(QPixmap.fromImage(img.scaled(180, 180, Qt.AspectRatioMode.KeepAspectRatio, + Qt.TransformationMode.SmoothTransformation)))) + it.setText(f"{c['source']} · {img.width()}×{img.height()}\n{c.get('label', '')}") + except RuntimeError: + pass + run_async(online.download, c["thumb"], on_done=got) + + def _file(self): + p, _ = QFileDialog.getOpenFileName(self, "Choose cover", os.path.dirname(self.song.path) if self.song.is_local else "", + "Images (*.jpg *.jpeg *.png *.webp *.bmp)") + if p: + img = QImage(p) + if not img.isNull(): + self._finish(img) + + def accept(self): + it = self.grid.currentItem() + if it is None: + return + c = self.cands[it.data(Qt.ItemDataRole.UserRole)] + self.status.setText("Downloading full-size cover…") + + def got(data): + img = QImage() + img.loadFromData(data) + if img.isNull(): + self.status.setText("Download failed.") + return + self._finish(img) + run_async(online.download, c["url"], on_done=got, on_error=lambda e: self.status.setText(e)) + + def _finish(self, img: QImage): + self.result_image = img + if self.apply_immediately: + w = self.parent() + path = w.np.set_cover(self.song, img) + data = T.image_to_jpeg_bytes(img) + album_songs = [self.song] + if self.song.album and self.song.id >= 0: + album_songs = L.library.songs_where( + "album = ? AND (albumartist = ? OR (COALESCE(albumartist,'')='' AND artist = ?))", + (self.song.album, self.song.effective_albumartist(), self.song.effective_albumartist())) + if self.to_folder.isChecked() and self.song.is_local: + try: + with open(os.path.join(os.path.dirname(self.song.path), "cover.jpg"), "wb") as fh: + fh.write(data) + except OSError as e: + QMessageBox.warning(self, "Cover", str(e)) + if self.embed.isChecked(): + run_async(lambda: [T.embed_cover(s.path, data) for s in album_songs if s.is_local], + on_done=lambda _: w.toast("Cover embedded"), on_error=w.toast) + for s in album_songs: + s.art = path or s.art + w.refresh_art(album_songs) + super().accept() + + +# ====================================================================== equalizer +class EqualizerDialog(QDialog): + def __init__(self, parent): + super().__init__(parent) + self.setWindowTitle("Equalizer") + self.resize(640, 380) + lay = QVBoxLayout(self) + top = QHBoxLayout() + self.enable = QCheckBox("Enable equalizer") + self.enable.setChecked(settings.get("playback/eq_enabled")) + top.addWidget(self.enable) + top.addStretch(1) + self.preset = QComboBox() + self.preset.addItem("Presets…") + for name in EQ_PRESETS: + self.preset.addItem(name) + self.preset.activated.connect(self._preset) + top.addWidget(self.preset) + lay.addLayout(top) + if Player.instance.backend.name != "mpv": + n = QLabel("The equalizer needs the mpv backend (install mpv/libmpv). Settings are kept for later.") + n.setObjectName("muted") + n.setWordWrap(True) + lay.addWidget(n) + grid = QGridLayout() + self.sliders = [] + bands = settings.get("playback/eq_bands") + labels = ["Pre"] + [f"{f // 1000}k" if f >= 1000 else str(f) for f in EQ_FREQS] + vals = [settings.get("playback/eq_preamp")] + list(bands) + for i, (lab, v) in enumerate(zip(labels, vals)): + s = QSlider(Qt.Orientation.Vertical) + s.setRange(-120, 120) + s.setValue(int(v * 10)) + s.setMinimumHeight(200) + val = QLabel(f"{v:+.1f}") + val.setAlignment(Qt.AlignmentFlag.AlignCenter) + val.setObjectName("muted") + s.valueChanged.connect(lambda x, l=val: (l.setText(f"{x / 10:+.1f}"), self._apply())) + grid.addWidget(val, 0, i) + grid.addWidget(s, 1, i, Qt.AlignmentFlag.AlignHCenter) + lb = QLabel(lab) + lb.setAlignment(Qt.AlignmentFlag.AlignCenter) + grid.addWidget(lb, 2, i) + self.sliders.append(s) + lay.addLayout(grid, 1) + self.enable.toggled.connect(self._apply) + close = QDialogButtonBox(QDialogButtonBox.StandardButton.Close) + close.rejected.connect(self.accept) + lay.addWidget(close) + + def _preset(self, i): + if i <= 0: + return + vals = EQ_PRESETS[self.preset.itemText(i)] + for s, v in zip(self.sliders[1:], vals): + s.blockSignals(True) + s.setValue(int(v * 10)) + s.blockSignals(False) + s.valueChanged.emit(s.value()) + self.enable.setChecked(True) + self._apply() + + def _apply(self): + settings.set("playback/eq_enabled", self.enable.isChecked()) + settings.set("playback/eq_preamp", self.sliders[0].value() / 10) + settings.set("playback/eq_bands", [s.value() / 10 for s in self.sliders[1:]]) + Player.instance.apply_audio_settings() + + +# ====================================================================== ripper +class RipDialog(QDialog): + def __init__(self, songs: list[Song], cover: bytes | None, parent): + super().__init__(parent) + self.songs, self.cover = songs, cover + self.ripper = None + self.setWindowTitle(f"Rip {len(songs)} track(s)") + self.resize(560, 360) + lay = QVBoxLayout(self) + f = QFormLayout() + self.fmt = QComboBox() + for k, (label, _, _) in CD.FORMATS.items(): + self.fmt.addItem(label, k) + self.fmt.setCurrentIndex(max(0, self.fmt.findData(settings.get("cd/rip_format")))) + self.q = QSpinBox() + self.q.setRange(0, 12) + self.q.setValue(settings.get("cd/rip_quality")) + self.q.setToolTip("FLAC: compression 0-12 · Opus: 0-5 (64-256 kbps) · Vorbis 0-10 · MP3 0-9 (9 = best)") + self.dir = QLineEdit(settings.get("cd/rip_dir")) + self.pat = QLineEdit(settings.get("cd/rip_pattern")) + f.addRow("Format", self.fmt) + f.addRow("Quality", self.q) + f.addRow("Destination", self.dir) + f.addRow("Pattern", self.pat) + lay.addLayout(f) + self.add_lib = QCheckBox("Add ripped files to the library") + self.add_lib.setChecked(True) + lay.addWidget(self.add_lib) + self.bar = QProgressBar() + self.bar.setMaximum(len(songs)) + self.msg = QLabel("Ready") + self.msg.setObjectName("muted") + lay.addWidget(self.bar) + lay.addWidget(self.msg) + lay.addStretch(1) + row = QHBoxLayout() + row.addStretch(1) + self.cancel = QPushButton("Close") + self.start = _primary(QPushButton(icon("download", "onPrimary"), " Start ripping")) + row.addWidget(self.cancel) + row.addWidget(self.start) + lay.addLayout(row) + self.start.clicked.connect(self._start) + self.cancel.clicked.connect(self._cancel) + + def _start(self): + settings.set("cd/rip_format", self.fmt.currentData()) + settings.set("cd/rip_quality", self.q.value()) + settings.set("cd/rip_dir", self.dir.text()) + settings.set("cd/rip_pattern", self.pat.text()) + self.ripper = CD.Ripper(self.songs, self.fmt.currentData(), self.q.value(), self.dir.text(), + self.pat.text(), self.cover) + self.ripper.progress.connect(lambda i, n, m: (self.bar.setValue(i), self.msg.setText(m))) + self.ripper.finished_rip.connect(self._done) + self.start.setEnabled(False) + self.cancel.setText("Cancel") + self.ripper.start() + + def _done(self, ok, msg): + self.msg.setText(msg) + self.cancel.setText("Close") + self.start.setEnabled(True) + if ok and self.add_lib.isChecked(): + folders = settings.get("library/folders") + d = self.dir.text() + if not any(d.startswith(f) for f in folders): + settings.set("library/folders", folders + [d]) + L.library.scan(False) + self.ripper = None + + def _cancel(self): + if self.ripper is not None: + self.ripper.cancel() + else: + self.reject() + + def closeEvent(self, e): + if self.ripper is not None: + self.ripper.cancel() + self.ripper.wait(3000) + super().closeEvent(e) + + +# ====================================================================== lyrics/about +class LyricsEditor(QDialog): + def __init__(self, text, parent): + super().__init__(parent) + self.setWindowTitle("Edit lyrics") + self.resize(520, 560) + lay = QVBoxLayout(self) + tip = QLabel("Plain text or LRC ([mm:ss.xx] line) for synced lyrics.") + tip.setObjectName("muted") + lay.addWidget(tip) + self.edit = QPlainTextEdit(text or "") + lay.addWidget(self.edit, 1) + self.to_file = QCheckBox("Also save into the audio file's tags") + lay.addWidget(self.to_file) + lay.addWidget(_buttons(self)) + + def text(self): + return self.edit.toPlainText() + + def save_to_file(self): + return self.to_file.isChecked() + + +class AboutDialog(QDialog): + def __init__(self, parent): + super().__init__(parent) + self.setWindowTitle(f"About {APP_NAME}") + lay = QVBoxLayout(self) + lay.setContentsMargins(28, 24, 28, 18) + logo = QLabel() + logo.setPixmap(icon("graphic_eq", "primary").pixmap(72, 72)) + logo.setAlignment(Qt.AlignmentFlag.AlignCenter) + lay.addWidget(logo) + t = QLabel(f"

{APP_NAME} {VERSION}

") + t.setAlignment(Qt.AlignmentFlag.AlignCenter) + lay.addWidget(t) + b = QLabel("A Material You music player for KDE, built with PyQt6.
" + f"Playback engine: {Player.instance.backend.name}

" + "Icons: Material Symbols (Apache 2.0). Lyrics: LRCLIB. Metadata: MusicBrainz, " + "Cover Art Archive, iTunes, Deezer, Last.fm, Wikipedia.") + b.setWordWrap(True) + b.setAlignment(Qt.AlignmentFlag.AlignCenter) + b.setObjectName("muted") + lay.addWidget(b) + bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Close) + bb.rejected.connect(self.accept) + lay.addWidget(bb) diff --git a/mulberry/widgets/hero.py b/mulberry/widgets/hero.py new file mode 100644 index 0000000..699b84d --- /dev/null +++ b/mulberry/widgets/hero.py @@ -0,0 +1,811 @@ +"""The 'now playing' hero: cookie-shaped cover with a radial visualizer, +wavy seek bar, expressive transport buttons and a synced lyrics card.""" +from __future__ import annotations + +import math +import time + +import numpy as np + +from PyQt6.QtCore import QLineF, QPointF, QRectF, QSize, Qt, pyqtSignal +from PyQt6.QtGui import (QBrush, QColor, QFont, QFontMetrics, QImage, QLinearGradient, QPainter, + QPainterPath, QPen, QPixmap, QTransform) +from PyQt6.QtWidgets import (QHBoxLayout, QLabel, QMenu, QSizePolicy, QVBoxLayout, QWidget) + +from .. import online +from .. import theme as Th +from ..config import fmt_time, settings +from ..icons import icon, paint_icon +from .m3 import C, ElideLabel, FrameClock, IconButton, PillButton, WavySlider, with_alpha + + +def blur_image(img: QImage, w: int, h: int) -> QImage: + small = img.scaled(18, 18, Qt.AspectRatioMode.IgnoreAspectRatio, Qt.TransformationMode.SmoothTransformation) + mid = small.scaled(64, 64, Qt.AspectRatioMode.IgnoreAspectRatio, Qt.TransformationMode.SmoothTransformation) + return mid.scaled(max(1, w), max(1, h), Qt.AspectRatioMode.KeepAspectRatioByExpanding, + Qt.TransformationMode.SmoothTransformation) + + +# ---------------------------------------------------------------------- cookie cover +class CookieCover(QWidget): + """Album art clipped to a spinning M3 'cookie'. The visualizer bars are + anchored to the cookie's own outline, so they follow its scallops and spin + with it.""" + clicked = pyqtSignal() + NBARS = 72 + + def __init__(self, spectrum, parent=None): + super().__init__(parent) + self.spectrum = spectrum + self.image: QImage | None = None + self._pm: QPixmap | None = None + self.playing = False + self.rot = 0.0 # degrees + self.show_bars = True + self.lobes = 9 + self._ticking = False + self._acquired = False + self._spin = 7.0 + self.setCursor(Qt.CursorShape.PointingHandCursor) + base = np.arange(self.NBARS) / self.NBARS * 2 * np.pi + self._base = base + self._shape = 1.0 + np.cos(self.lobes * base) # 0..2 scallop factor per bar + + def set_image(self, img: QImage | None): + self.image = img + self._pm = None + self.update() + + def set_playing(self, on): + self.playing = on + self._sync() + + def _sync(self): + vis = self.isVisible() and self.show_bars + if vis and not self._acquired: + self.spectrum.acquire() + self._acquired = True + elif not vis and self._acquired: + self.spectrum.release() + self._acquired = False + need = self.isVisible() and (self.playing or self.spectrum.levels.max() > 0.002) + if need and not self._ticking: + FrameClock.subscribe(self._tick) + self._ticking = True + elif not need and self._ticking: + FrameClock.unsubscribe(self._tick) + self._ticking = False + self.update() + + def showEvent(self, e): + self._sync() + + def hideEvent(self, e): + self._sync() + + def _tick(self, dt=1 / 60): + target = (7.0 + 55.0 * self.spectrum.pulse) if self.playing else 0.0 + self._spin += (target - self._spin) * min(1.0, dt * 4) + self.rot = (self.rot + self._spin * dt) % 360 + self.update() + if not self.playing and self._spin < 0.05 and self.spectrum.levels.max() <= 0.002: + self._sync() + + def resizeEvent(self, e): + self._pm = None + + def mouseReleaseEvent(self, e): + if e.button() == Qt.MouseButton.LeftButton: + self.clicked.emit() + + def _cover_pm(self, d: int) -> QPixmap: + """Cached at a fixed size; per-frame size changes are done with the + brush transform (no rescaling every frame).""" + dpr = self.devicePixelRatioF() + if self._pm is None or self._pm.width() != int(d * dpr): + if self.image is not None and not self.image.isNull(): + img = self.image.scaled(int(d * dpr), int(d * dpr), Qt.AspectRatioMode.KeepAspectRatioByExpanding, + Qt.TransformationMode.SmoothTransformation) + self._pm = QPixmap.fromImage(img) + else: + self._pm = QPixmap() + return self._pm + + def paintEvent(self, e): + p = QPainter(self) + p.setRenderHint(QPainter.RenderHint.Antialiasing) + p.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform) + size = min(self.width(), self.height()) + cx, cy = self.width() / 2, self.height() / 2 + Ro = size / 2 - 2 + bars = self.show_bars and size > 120 + sp = self.spectrum + pulse = sp.pulse if bars else 0.0 + R0 = Ro * (0.70 if bars else 0.98) + amp = 0.06 if bars else 0.045 + R = R0 * (1 + 0.045 * pulse + 0.015 * sp.bass) + rot = math.radians(self.rot) + # ---- bars glued to the cookie outline + if bars: + n = self.NBARS + half = sp.resample(n // 2) + lv = np.concatenate((half, half[::-1])) + ang = self._base + rot + edge = R * (1 - amp + amp * (self._shape - 1.0)) # cookie radius under each bar + gap = Ro * 0.035 + maxlen = Ro - (R0 * 1.05) - gap - 3 + r1 = edge + gap + r2 = r1 + 2.5 + lv * maxlen + ca, sa = np.cos(ang), np.sin(ang) + x1, y1 = cx + ca * r1, cy + sa * r1 + x2, y2 = cx + ca * r2, cy + sa * r2 + prim = C("primary") + width = max(2.6, size / 80) + buckets = np.minimum(3, (lv * 4.5).astype(int)) + for b in range(4): + idx = np.nonzero(buckets == b)[0] + if not len(idx): + continue + p.setPen(QPen(with_alpha(prim, 0.42 + 0.19 * b), width, Qt.PenStyle.SolidLine, + Qt.PenCapStyle.RoundCap)) + p.drawLines([QLineF(x1[i], y1[i], x2[i], y2[i]) for i in idx]) + # ---- cookie + steps = 160 + t = np.linspace(0, 2 * np.pi, steps, endpoint=False) + r = R * (1 - amp + amp * np.cos(self.lobes * (t - rot))) + xs, ys = cx + r * np.cos(t), cy + r * np.sin(t) + path = QPainterPath(QPointF(xs[0], ys[0])) + for i in range(1, steps): + path.lineTo(xs[i], ys[i]) + path.closeSubpath() + dmax = int(R0 * 2.12) + pm = self._cover_pm(dmax) + if not pm.isNull(): + br = QBrush(pm) + tr = QTransform() + tr.translate(cx - R, cy - R) + k = (2 * R) / (pm.width()) + tr.scale(k, k) + br.setTransform(tr) + p.fillPath(path, br) + else: + p.fillPath(path, C("primaryContainer")) + s2 = R * 0.7 + paint_icon(p, QRectF(cx - s2 / 2, cy - s2 / 2, s2, s2), "album", C("onPrimaryContainer")) + + +# ---------------------------------------------------------------------- lyrics view +class LyricsView(QWidget): + """Synced lyrics: the active line glows and pops, the list glides to keep + it in view, and clicking any line seeks there (like Spotify).""" + seek_requested = pyqtSignal(float) + + def __init__(self, parent=None): + super().__init__(parent) + self.lines: list[tuple[float, str]] = [] + self.synced = False + self.state = "empty" + self.message = "No lyrics" + self.offset = 0.0 + self.target = 0.0 + self.current = -1 + self._layout: list[tuple[float, float]] = [] # y, h per line + self._act: np.ndarray = np.zeros(0) # animated highlight per line + self._manual_until = 0.0 + self._animating = False + self._hover = -1 + self.time_offset = 0.0 + self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding) + self.setMinimumHeight(80) + self.setMouseTracking(True) + + def _font(self, active=False): + return Th.theme.display_font(15, QFont.Weight.DemiBold) + + def set_message(self, msg, state="empty"): + self.lines, self.synced, self.state, self.message = [], False, state, msg + self._layout = [] + self._act = np.zeros(0) + self.offset = self.target = 0 + self.current = -1 + self._hover = -1 + self.setCursor(Qt.CursorShape.ArrowCursor) + self.update() + + def set_text(self, text: str, plain_only=False): + if plain_only: + parsed, _ = online.parse_lrc(text) + lines, synced = [(-1.0, t) for _, t in parsed], False + else: + lines, synced = online.parse_lrc(text) + while lines and not lines[0][1].strip() and not synced: + lines.pop(0) + if not lines or all(not t.strip() for _, t in lines): + self.set_message("No lyrics found") + return + if len(lines) == 1 and lines[0][1].strip().lower() == "[instrumental]": + self.set_message("♪ Instrumental ♪") + return + self.lines, self.synced, self.state = lines, synced, "text" + self.offset = self.target = 0 + self.current = -1 + self._act = np.zeros(len(lines)) + self._relayout() + self.update() + + def _relayout(self): + self._layout = [] + y = 0.0 + w = max(50, self.width() - 16) + fm = QFontMetrics(self._font(True)) + for _, txt in self.lines: + if not txt.strip(): + h = fm.height() * (0.6 if self.synced else 0.5) + else: + h = fm.boundingRect(0, 0, w, 10000, Qt.TextFlag.TextWordWrap, txt).height() + self._layout.append((y, h)) + y += h + 12 + self._content_h = y + + def resizeEvent(self, e): + if self.lines: + self._relayout() + self._retarget(jump=True) + + def set_position(self, sec): + if not self.synced or not self.lines: + return + sec += self.time_offset + idx = -1 + lo, hi = 0, len(self.lines) - 1 + while lo <= hi: + mid = (lo + hi) // 2 + if self.lines[mid][0] <= sec + 0.15: + idx = mid + lo = mid + 1 + else: + hi = mid - 1 + if idx != self.current: + self.current = idx + self._retarget() + self._start() + + def _retarget(self, jump=False): + if time.monotonic() < self._manual_until: + return + if self.synced and 0 <= self.current < len(self._layout): + y, h = self._layout[self.current] + self.target = max(0.0, y + h / 2 - self.height() * 0.34) + elif self.synced: + self.target = 0.0 + if jump: + self.offset = self.target + self.update() + else: + self._start() + + def _start(self): + if not self._animating and self.isVisible(): + self._animating = True + FrameClock.subscribe(self._tick) + + def _tick(self, dt=1 / 60): + k = 1 - math.exp(-dt * 9.0) # frame-rate independent easing + self.offset += (self.target - self.offset) * k + settled = abs(self.target - self.offset) < 0.3 + if len(self._act): + goal = np.zeros(len(self._act)) + if 0 <= self.current < len(goal): + goal[self.current] = 1.0 + self._act += (goal - self._act) * (1 - math.exp(-dt * 10.0)) + settled = settled and float(np.abs(goal - self._act).max()) < 0.01 + if settled: + self.offset = self.target + FrameClock.unsubscribe(self._tick) + self._animating = False + self.update() + + def hideEvent(self, e): + if self._animating: + FrameClock.unsubscribe(self._tick) + self._animating = False + self.offset = self.target + + def wheelEvent(self, e): + if not self.lines: + return + maxo = max(0.0, getattr(self, "_content_h", 0) - self.height() * 0.5) + self.target = max(0.0, min(maxo, self.target - e.angleDelta().y() / 1.5)) + self._manual_until = time.monotonic() + 4 + self._start() + + def _line_at(self, y): + y += self.offset + for i, (ly, h) in enumerate(self._layout): + if ly - 6 <= y <= ly + h + 6 and self.lines[i][1].strip(): + return i + return -1 + + def mouseMoveEvent(self, e): + i = self._line_at(e.position().y()) if self.synced else -1 + if i != self._hover: + self._hover = i + self.setCursor(Qt.CursorShape.PointingHandCursor if i >= 0 else Qt.CursorShape.ArrowCursor) + self.setToolTip(f"Jump to {fmt_time(self.lines[i][0] - self.time_offset)}" if i >= 0 else "") + self.update() + + def leaveEvent(self, e): + if self._hover != -1: + self._hover = -1 + self.update() + + def mouseReleaseEvent(self, e): + if not self.synced or e.button() != Qt.MouseButton.LeftButton: + return + i = self._line_at(e.position().y()) + if i >= 0: + self._manual_until = 0 + self.current = i + self._retarget() + self.seek_requested.emit(max(0.0, self.lines[i][0] - self.time_offset + 0.01)) + + def paintEvent(self, e): + W, H = self.width(), self.height() + dpr = self.devicePixelRatioF() + pm = QPixmap(int(W * dpr), int(H * dpr)) + pm.setDevicePixelRatio(dpr) + pm.fill(Qt.GlobalColor.transparent) + p = QPainter(pm) + p.setRenderHint(QPainter.RenderHint.Antialiasing) + p.setRenderHint(QPainter.RenderHint.TextAntialiasing) + p.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform) + if self.state != "text": + p.setFont(Th.theme.display_font(15, QFont.Weight.Medium)) + p.setPen(with_alpha(C("onSurfaceVariant"), 0.8)) + p.drawText(QRectF(8, 0, W - 8, H * 0.6), Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter + | Qt.TextFlag.TextWordWrap, self.message) + p.end() + QPainter(self).drawPixmap(0, 0, pm) + return + prim = C("primary") + var = C("onSurfaceVariant") + onsurf = C("onSurface") + w = W - 16 + p.setFont(self._font()) + for i, ((t, txt), (y, h)) in enumerate(zip(self.lines, self._layout)): + yy = y - self.offset + if yy + h < -14 or yy > H + 14: + continue + if self.synced: + a = float(self._act[i]) if i < len(self._act) else 0.0 + dist = abs(i - self.current) if self.current >= 0 else i + 1 + base = with_alpha(var, max(0.36, 0.9 - dist * 0.09)) + col = Th.mix(base, prim, a) + if i == self._hover: + hp = QPainterPath() + hp.addRoundedRect(QRectF(0, yy - 5, W, h + 10), 12, 12) + p.fillPath(hp, with_alpha(onsurf, 0.07)) + if a < 0.5: + col = Th.mix(col, onsurf, 0.6) + scale = 1.0 + 0.045 * a + else: + col, scale = onsurf, 1.0 + p.save() + p.translate(8, yy + h / 2) + p.scale(scale, scale) + p.setPen(col) + p.drawText(QRectF(0, -h / 2 - 1, w / scale, h + 2), Qt.TextFlag.TextWordWrap | Qt.AlignmentFlag.AlignLeft, txt) + p.restore() + # fade edges + p.setCompositionMode(QPainter.CompositionMode.CompositionMode_DestinationIn) + g = QLinearGradient(0, 0, 0, H) + fade = min(0.18, 28 / max(H, 1)) + g.setColorAt(0, QColor(0, 0, 0, 0 if self.offset > 2 else 255)) + g.setColorAt(fade, QColor(0, 0, 0, 255)) + g.setColorAt(1 - fade * 1.4, QColor(0, 0, 0, 255)) + g.setColorAt(1, QColor(0, 0, 0, 0)) + p.fillRect(QRectF(0, 0, W, H), g) + p.end() + QPainter(self).drawPixmap(0, 0, pm) + + +# ---------------------------------------------------------------------- hero +class Hero(QWidget): + open_menu = pyqtSignal(object) # QPoint for the song actions menu + cover_clicked = pyqtSignal() + + def __init__(self, player, nowplaying, spectrum, scrobbler, parent=None): + super().__init__(parent) + self.player, self.np, self.scrobbler = player, nowplaying, scrobbler + self.mode = "full" + self._bg: QPixmap | None = None + self._bg_img: QImage | None = None + self._show_info = False + self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred) + + self.cover = CookieCover(spectrum) + self.cover.clicked.connect(self.cover_clicked) + self.title = ElideLabel("Nothing playing") + self.artist = ElideLabel("") + self.album = ElideLabel("") + self.meta = ElideLabel("") + self.meta.setObjectName("muted") + self.pos_lbl = QLabel("0:00") + self.dur_lbl = QLabel("0:00") + for lbl in (self.pos_lbl, self.dur_lbl): + lbl.setMinimumWidth(40) + self.dur_lbl.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter) + self.wave = WavySlider() + self.wave.seek_requested.connect(lambda v: player.seek(v * player.dur)) + self.wave.dragging.connect(lambda v: self.pos_lbl.setText(fmt_time(v * player.dur))) + + self.b_shuffle = IconButton("shuffle", "tonal", 44, 22, tooltip="Shuffle") + self.b_shuffle.setCheckable(True) + self.b_prev = IconButton("skip_previous_fill", "tonal", 44, 24, tooltip="Previous") + self.b_play = IconButton("play_arrow_fill", "filled", 56, 30, wide=104, tooltip="Play / Pause") + self.b_next = IconButton("skip_next_fill", "tonal", 44, 24, tooltip="Next") + self.b_repeat = IconButton("repeat", "tonal", 44, 22, tooltip="Repeat") + self.b_repeat.setCheckable(True) + self.b_prev.clicked.connect(player.prev) + self.b_next.clicked.connect(player.next) + self.b_play.clicked.connect(player.play_pause) + self.b_shuffle.clicked.connect(self._toggle_shuffle) + self.b_repeat.clicked.connect(self._cycle_repeat) + + # ---- layout: cover | info | lyrics + info = QVBoxLayout() + info.setSpacing(2) + info.addStretch(1) + info.addWidget(self.title) + info.addWidget(self.artist) + info.addWidget(self.album) + info.addWidget(self.meta) + info.addSpacing(12) + prow = QHBoxLayout() + prow.setSpacing(6) + prow.addWidget(self.pos_lbl) + prow.addWidget(self.wave, 1) + prow.addWidget(self.dur_lbl) + info.addLayout(prow) + info.addSpacing(6) + self.controls = QWidget() + brow = QHBoxLayout(self.controls) + brow.setContentsMargins(0, 0, 0, 0) + brow.setSpacing(6) + brow.addStretch(1) + for b in (self.b_shuffle, self.b_prev, self.b_play, self.b_next, self.b_repeat): + brow.addWidget(b) + brow.addStretch(1) + info.addWidget(self.controls) + info.addStretch(1) + self.info_lay = info + self.info_w = QWidget() + self.info_w.setLayout(info) + self.info_w.setMinimumWidth(300) + + # lyrics card + self.lcard = QWidget() + self.lcard.setMinimumWidth(280) + self.lcard.setMaximumWidth(460) + lc = QVBoxLayout(self.lcard) + lc.setContentsMargins(0, 0, 0, 0) + lc.setSpacing(8) + hdr = QHBoxLayout() + self.l_icon = QLabel() + self.l_title = QLabel("Lyrics") + self.l_menu = IconButton("more_vert", "tonal", 36, 20, tooltip="Lyrics options") + self.l_menu.clicked.connect(self._lyrics_menu) + hdr.addWidget(self.l_icon) + hdr.addWidget(self.l_title) + self.l_src = QLabel("") + self.l_src.setObjectName("muted") + hdr.addWidget(self.l_src) + hdr.addStretch(1) + hdr.addWidget(self.l_menu) + lc.addLayout(hdr) + self.lyrics = LyricsView() + self.lyrics.seek_requested.connect(player.seek) + lc.addWidget(self.lyrics, 1) + self.love = PillButton("favorite", "Love", split=True) + self.love.setCheckable(True) + self.love.clicked.connect(self._toggle_love) + self.love.menu_requested.connect(lambda: self.open_menu.emit( + self.love.mapToGlobal(self.love.rect().bottomRight()))) + lc.addWidget(self.love) + + lay = QHBoxLayout(self) + lay.setContentsMargins(18, 14, 18, 14) + lay.setSpacing(22) + lay.addWidget(self.cover) + lay.addWidget(self.info_w, 3) + lay.addWidget(self.lcard, 2) + self.main_lay = lay + self.restyle() + self.set_mode(settings.get("appearance/hero")) + + player.song_changed.connect(self.on_song) + player.state_changed.connect(self.on_state) + player.position_changed.connect(self.on_pos) + nowplaying.art_changed.connect(self.on_art) + nowplaying.lyrics_changed.connect(self.on_lyrics) + nowplaying.info_changed.connect(self.on_info) + Th.theme.changed.connect(self.restyle) + self.sync_modes() + + # -------------------------------------------------------------- style/mode + def restyle(self): + t = Th.theme + big = self.mode == "full" + self.title.setFont(t.display_font(28 if big else 18, QFont.Weight.DemiBold)) + self.artist.setFont(t.display_font(17 if big else 14, QFont.Weight.DemiBold)) + self.album.setFont(t.display_font(17 if big else 13, QFont.Weight.DemiBold)) + self.l_title.setFont(t.display_font(18, QFont.Weight.DemiBold)) + self.title.setStyleSheet(f"color: {t['onSurface'].name()};") + self.artist.setStyleSheet(f"color: {t['onSurface'].name()};") + self.album.setStyleSheet(f"color: {t['primary'].name()};") + self.meta.setStyleSheet(f"color: {t['onSurfaceVariant'].name()}; font-size: 9pt;") + mono = t.display_font(13, QFont.Weight.Medium) + for lbl in (self.pos_lbl, self.dur_lbl): + lbl.setFont(mono) + lbl.setStyleSheet(f"color: {t['onSurfaceVariant'].name()};") + self.l_icon.setPixmap(icon("lyrics", "onSurface").pixmap(QSize(24, 24), self.devicePixelRatioF())) + self._bg = None + self.update() + + def set_mode(self, mode): + self.mode = mode if mode in ("full", "compact") else "full" + full = self.mode == "full" + self.cover.show_bars = full and settings.get("appearance/visualizer") + self.cover.setFixedSize(QSize(250, 250) if full else QSize(92, 92)) + self.lcard.setVisible(full) + self.album.setVisible(full) + self.meta.setVisible(full) + self.layout().setContentsMargins(*(18, 14, 18, 14) if full else (16, 8, 18, 8)) + # compact: transport moves to the right of the info column (one row) + if full and self.main_lay.indexOf(self.controls) >= 0: + self.main_lay.removeWidget(self.controls) + self.info_lay.insertWidget(self.info_lay.count() - 1, self.controls) + elif not full and self.info_lay.indexOf(self.controls) >= 0: + self.info_lay.removeWidget(self.controls) + self.main_lay.insertWidget(2, self.controls) + self.info_lay.setSpacing(2 if full else 0) + self.cover._sync() + self.restyle() + + def sync_modes(self): + mgr = self.player.mgr + self.b_shuffle.setChecked(mgr.shuffle) + self.b_repeat.setChecked(mgr.repeat != "off") + self.b_repeat.set_icon("repeat_one" if mgr.repeat == "track" else "repeat") + self.b_repeat.setToolTip({"off": "Repeat: off", "playlist": "Repeat: playlist", + "track": "Repeat: track"}[mgr.repeat]) + + def _toggle_shuffle(self): + self.player.mgr.set_shuffle(self.b_shuffle.isChecked()) + self.player.refresh_next() + self.window().sync_modes() + + def _cycle_repeat(self): + mgr = self.player.mgr + nxt = {"off": "playlist", "playlist": "track", "track": "off"}[mgr.repeat] + mgr.set_repeat(nxt) + self.player.refresh_next() + self.window().sync_modes() + + def _toggle_love(self): + s = self.player.song + if not s: + self.love.setChecked(False) + return + loved = self.love.isChecked() + from .. import library as L + L.library.set_rating(s, 5 if loved else 0) + self.love.setText("Loved" if loved else "Love") + self.love.icon_name = "favorite_fill" if loved else "favorite" + self.scrobbler.love(s, loved) + + # -------------------------------------------------------------- player events + def on_song(self, s): + if s is None: + return + if s.is_stream: + st = s.stream_title + if st and " - " in st: + a, t = st.split(" - ", 1) + self.title.setText(t) + self.artist.setText(a) + else: + self.title.setText(st or s.title or "Radio stream") + self.artist.setText(s.title if st else "") + self.album.setText(s.title if st else s.url) + else: + self.title.setText(s.display_title()) + self.artist.setText(s.display_artist()) + self.album.setText(s.album + (f" · {s.year}" if s.year else "")) + bits = [s.filetype] + if s.bitdepth and s.samplerate: + bits.append(f"{s.bitdepth}-bit / {s.samplerate / 1000:g} kHz") + elif s.samplerate: + bits.append(f"{s.samplerate / 1000:g} kHz") + if s.bitrate: + bits.append(f"{s.bitrate} kbps") + if s.playcount: + bits.append(f"played {s.playcount}×") + self.meta.setText(" · ".join(b for b in bits if b)) + loved = s.rating >= 5 + self.love.setChecked(loved) + self.love.setText("Loved" if loved else "Love") + self.love.icon_name = "favorite_fill" if loved else "favorite" + self.love.update() + self.dur_lbl.setText(fmt_time(s.duration()) if not s.is_stream else "LIVE") + if self._show_info: + self.np.load_artist_info() + + def on_state(self, st): + playing = st == "playing" + self.b_play.set_icon("pause_fill" if playing else "play_arrow_fill") + self.b_play.set_morph(playing) + self.wave.set_playing(playing) + self.cover.set_playing(playing) + if st == "stopped": + self.wave.set_value(0) + self.pos_lbl.setText("0:00") + + def on_pos(self, pos, dur): + if self.wave._drag is None: + self.pos_lbl.setText(fmt_time(pos)) + if dur > 0: + self.wave.set_value(pos / dur, dur) + self.dur_lbl.setText(fmt_time(dur)) + if not self._show_info: + self.lyrics.set_position(pos) + + def on_art(self, img, path): + self.cover.set_image(img) + self._bg_img = img + self._bg = None + self.update() + + def on_lyrics(self, text, source, song): + if self._show_info: + return + if source == "loading": + self.lyrics.set_message("Searching for lyrics…", "loading") + elif source == "error": + self.lyrics.set_message("Couldn't reach the lyrics service") + elif source == "nolocal": + self.lyrics.set_message("No .lrc file next to this song.\nUse LRCGET to download them, " + "or pick another source in ⋮.") + elif not text: + self.lyrics.set_message("No lyrics found" if song and not song.is_stream else "No lyrics") + else: + self.lyrics.set_text(text, plain_only=settings.get("lyrics/plain")) + self.lyrics.set_position(self.player.pos) + self.l_title.setText("Lyrics") + shown = source if source not in ("loading", "error", "nolocal", "") else "" + if shown and settings.get("lyrics/plain"): + shown += " · plain" + self.l_src.setText(shown) + + def on_info(self, artist, text): + if not self._show_info: + return + self.l_title.setText(artist or "Artist") + if text: + self.lyrics.set_text(text, plain_only=True) + else: + self.lyrics.set_message("No artist information found") + + def _lyrics_menu(self): + m = QMenu(self) + if self._show_info: + m.addAction(icon("lyrics"), "Show lyrics", lambda: self._set_info(False)) + else: + m.addAction(icon("person"), "Show artist info", lambda: self._set_info(True)) + m.addSeparator() + src_menu = m.addMenu(icon("cloud_download"), "Lyrics source") + cur = settings.get("lyrics/source") + for key, label in (("auto", "Auto (local → LRCLIB → NetEase)"), ("lrclib", "LRCLIB"), + ("netease", "NetEase Cloud Music"), ("local", "Local .lrc files (LRCGET)"), + ("embedded", "Embedded in the audio file")): + a = src_menu.addAction(label) + a.setCheckable(True) + a.setChecked(key == cur) + a.triggered.connect(lambda _c, k=key: self.np.set_source(k)) + plain = m.addAction(icon("text_snippet"), "Show as plain text (no sync)") + plain.setCheckable(True) + plain.setChecked(settings.get("lyrics/plain")) + plain.toggled.connect(self._toggle_plain) + m.addSeparator() + m.addAction(icon("refresh"), "Search again", self.np.refetch_lyrics) + m.addAction(icon("file_open"), "Load .lrc / text file…", self._load_lrc) + m.addAction(icon("edit"), "Edit lyrics…", self._edit_lyrics) + m.addSeparator() + m.addAction("Lyrics earlier (−0.5 s)", lambda: self._shift(-0.5)) + m.addAction("Lyrics later (+0.5 s)", lambda: self._shift(0.5)) + m.addAction("Reset timing", lambda: self._shift(None)) + m.exec(self.l_menu.mapToGlobal(self.l_menu.rect().bottomLeft())) + + def _toggle_plain(self, on): + settings.set("lyrics/plain", on) + self.on_lyrics(self.np.lyrics, self.np.lyrics_source, self.np.song) + + def _shift(self, d): + self.lyrics.time_offset = 0.0 if d is None else self.lyrics.time_offset - d + self.lyrics.set_position(self.player.pos) + + def _set_info(self, on): + self._show_info = on + if on: + self.lyrics.set_message("Loading artist info…", "loading") + self.np.load_artist_info() + else: + self.on_lyrics(self.np.lyrics, self.np.lyrics_source, self.np.song) + + def _load_lrc(self): + from PyQt6.QtWidgets import QFileDialog + path, _ = QFileDialog.getOpenFileName(self, "Load lyrics", "", "Lyrics (*.lrc *.txt);;All files (*)") + if path: + with open(path, encoding="utf-8", errors="replace") as fh: + self.np.set_lyrics(fh.read()) + + def _edit_lyrics(self): + from .dialogs import LyricsEditor + dlg = LyricsEditor(self.np.lyrics, self) + if dlg.exec(): + self.np.set_lyrics(dlg.text(), dlg.save_to_file()) + + # -------------------------------------------------------------- painting + def resizeEvent(self, e): + self._bg = None + self._cache = None + + def _render_bg(self) -> QPixmap: + """Card background (blurred art, gradient, lyrics panel) rendered once + and reused every frame — animated children no longer force a full + repaint of the blur.""" + dpr = self.devicePixelRatioF() + pm = QPixmap(int(self.width() * dpr), int(self.height() * dpr)) + pm.setDevicePixelRatio(dpr) + pm.fill(Qt.GlobalColor.transparent) + p = QPainter(pm) + p.setRenderHint(QPainter.RenderHint.Antialiasing) + p.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform) + r = QRectF(self.rect()).adjusted(6, 4, -6, -2) + rad = 28 if self.mode == "full" else 22 + path = QPainterPath() + path.addRoundedRect(r, rad, rad) + p.fillPath(path, C("surfaceContainerLow")) + if self._bg_img is not None and not self._bg_img.isNull(): + bg = QPixmap.fromImage(blur_image(self._bg_img, self.width(), self.height())) + p.save() + p.setClipPath(path) + p.setOpacity(0.30 if Th.theme.dark else 0.22) + p.drawPixmap(QRectF(self.rect()), bg, QRectF(bg.rect())) + p.setOpacity(1.0) + g = QLinearGradient(0, 0, self.width(), 0) + base = C("surfaceContainerLow") + g.setColorAt(0, with_alpha(base, 0.15)) + g.setColorAt(0.55, with_alpha(base, 0.55)) + g.setColorAt(1, with_alpha(base, 0.8)) + p.fillPath(path, g) + p.restore() + if self.mode == "full" and self.lcard.isVisible(): + lr = QRectF(self.lcard.geometry()).adjusted(-12, -8, 10, 6) + lp = QPainterPath() + lp.addRoundedRect(lr, 22, 22) + p.fillPath(lp, with_alpha(C("surfaceContainerHigh"), 0.55)) + p.end() + return pm + + def paintEvent(self, e): + key = (self.width(), self.height(), self.devicePixelRatioF(), self.mode, + self.lcard.geometry().getRect() if self.lcard.isVisible() else None, + id(self._bg_img), Th.theme.c["surfaceContainerLow"].rgb(), Th.theme.dark) + if getattr(self, "_cache", None) is None or self._cache_key != key: + self._cache = self._render_bg() + self._cache_key = key + p = QPainter(self) + dpr = self._cache.devicePixelRatio() + r = e.rect() + p.drawPixmap(r, self._cache, QRectF(r.x() * dpr, r.y() * dpr, r.width() * dpr, r.height() * dpr).toRect()) diff --git a/mulberry/widgets/m3.py b/mulberry/widgets/m3.py new file mode 100644 index 0000000..e1ab9c1 --- /dev/null +++ b/mulberry/widgets/m3.py @@ -0,0 +1,569 @@ +"""Hand-painted Material 3 (Expressive) components.""" +from __future__ import annotations + +import math + +from PyQt6.QtCore import (QEasingCurve, QPointF, QRectF, QSize, Qt, QTimer, QVariantAnimation, + pyqtProperty, pyqtSignal) +from PyQt6.QtGui import QColor, QFontMetrics, QPainter, QPainterPath, QPen +from PyQt6.QtWidgets import QAbstractButton, QLabel, QLineEdit, QSizePolicy, QWidget + +from .. import theme as Th +from ..icons import paint_icon + + +def C(role) -> QColor: + return QColor(Th.theme.c[role]) + + +def with_alpha(c: QColor, a: float) -> QColor: + c = QColor(c) + c.setAlphaF(a) + return c + + +from ..clock import FrameClock # noqa: E402 (shared display-rate clock) + + +# ---------------------------------------------------------------------- buttons +class IconButton(QAbstractButton): + """M3 icon button. variant: standard | tonal | filled | outlined. + `wide` gives the expressive rounded-rect play button that morphs on toggle.""" + + def __init__(self, icon_name: str, variant="standard", size=40, icon_size=24, wide=0, + checked_icon: str | None = None, tooltip="", parent=None): + super().__init__(parent) + self.icon_name, self.checked_icon = icon_name, checked_icon + self.variant, self.btn_size, self.icon_px, self.wide = variant, size, icon_size, wide + self._hover = 0.0 + self._press = 0.0 + self._morph = 0.0 + self.toggle_style = False + self.setCursor(Qt.CursorShape.PointingHandCursor) + self.setFixedSize(QSize(wide or size, size)) + if tooltip: + self.setToolTip(tooltip) + self._anim = QVariantAnimation(self, duration=220, easingCurve=QEasingCurve.Type.OutCubic) + self._anim.valueChanged.connect(self._set_morph) + self._hanim = QVariantAnimation(self, duration=120) + self._hanim.valueChanged.connect(lambda v: (setattr(self, "_hover", v), self.update())) + self.toggled.connect(self._on_toggled) + + def set_icon(self, name): + self.icon_name = name + self.update() + + def _set_morph(self, v): + self._morph = v + self.update() + + def set_morph(self, on: bool, animate=True): + target = 1.0 if on else 0.0 + if animate: + self._anim.stop() + self._anim.setStartValue(self._morph) + self._anim.setEndValue(target) + self._anim.start() + else: + self._set_morph(target) + + def _on_toggled(self, on): + if self.toggle_style: + self.set_morph(on) + self.update() + + def enterEvent(self, e): + self._hanim.stop() + self._hanim.setStartValue(self._hover) + self._hanim.setEndValue(1.0) + self._hanim.start() + + def leaveEvent(self, e): + self._hanim.stop() + self._hanim.setStartValue(self._hover) + self._hanim.setEndValue(0.0) + self._hanim.start() + + def sizeHint(self): + return QSize(self.wide or self.btn_size, self.btn_size) + + def colors(self): + on = self.isChecked() + v = self.variant + if v == "filled": + return C("primary"), C("onPrimary") + if v == "tonal": + if self.isCheckable() and on: + return C("primary"), C("onPrimary") + return C("secondaryContainer"), C("onSecondaryContainer") + if v == "outlined": + return QColor(0, 0, 0, 0), C("onSurfaceVariant") + if self.isCheckable() and on: + return QColor(0, 0, 0, 0), C("primary") + return QColor(0, 0, 0, 0), C("onSurfaceVariant") + + def paintEvent(self, e): + p = QPainter(self) + p.setRenderHint(QPainter.RenderHint.Antialiasing) + r = QRectF(self.rect()).adjusted(1, 1, -1, -1) + bg, fg = self.colors() + if not self.isEnabled(): + fg = with_alpha(C("onSurface"), 0.38) + if bg.alpha(): + bg = with_alpha(C("onSurface"), 0.12) + h = r.height() + if self.wide: + # expressive: square-ish when "on" (playing), pill when off + rad = h / 2 - (h / 2 - h * 0.3) * self._morph + elif self.toggle_style: + rad = h / 2 - (h / 2 - h * 0.3) * self._morph + else: + rad = h / 2 + path = QPainterPath() + path.addRoundedRect(r, rad, rad) + if bg.alpha(): + p.fillPath(path, bg) + if self.variant == "outlined": + p.setPen(QPen(C("outlineVariant"), 1)) + p.drawPath(path) + state = self._hover * 0.08 + (0.1 if self.isDown() else 0) + if state > 0 and self.isEnabled(): + p.fillPath(path, with_alpha(fg, state)) + name = self.checked_icon if (self.isChecked() and self.checked_icon) else self.icon_name + s = self.icon_px + ir = QRectF(r.center().x() - s / 2, r.center().y() - s / 2, s, s) + paint_icon(p, ir, name, fg) + + +class PillButton(QAbstractButton): + """Tonal pill with icon + text (+ optional split dropdown).""" + menu_requested = pyqtSignal() + + def __init__(self, icon_name, text, split=False, parent=None): + super().__init__(parent) + self.icon_name, self.split = icon_name, split + self.setText(text) + self._hover_part = 0 + self.setMouseTracking(True) + self.setCursor(Qt.CursorShape.PointingHandCursor) + self.setFixedHeight(40) + self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed) + + def sizeHint(self): + fm = QFontMetrics(self.font()) + return QSize(fm.horizontalAdvance(self.text()) + 80 + (44 if self.split else 0), 40) + + def mouseMoveEvent(self, e): + part = 2 if self.split and e.position().x() > self.width() - 44 else 1 + if part != self._hover_part: + self._hover_part = part + self.update() + + def leaveEvent(self, e): + self._hover_part = 0 + self.update() + + def mouseReleaseEvent(self, e): + if self.split and e.position().x() > self.width() - 44 and self.rect().contains(e.position().toPoint()): + self.setDown(False) + self.menu_requested.emit() + return + super().mouseReleaseEvent(e) + + def paintEvent(self, e): + p = QPainter(self) + p.setRenderHint(QPainter.RenderHint.Antialiasing) + r = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5) + bg = C("primaryContainer") if self.isChecked() else C("secondaryContainer") + fg = C("onPrimaryContainer") if self.isChecked() else C("onSecondaryContainer") + main = QRectF(r.left(), r.top(), r.width() - (46 if self.split else 0), r.height()) + mainpath = QPainterPath() + if self.split: + self._split_left(mainpath, main) + else: + mainpath.addRoundedRect(main, 20, 20) + p.fillPath(mainpath, bg) + if self._hover_part == 1: + p.fillPath(mainpath, with_alpha(fg, 0.08)) + fm = QFontMetrics(self.font()) + tw = fm.horizontalAdvance(self.text()) + total = 20 + 8 + tw + x = main.center().x() - total / 2 + paint_icon(p, QRectF(x, main.center().y() - 10, 20, 20), self.icon_name, fg) + p.setPen(fg) + p.drawText(QRectF(x + 28, main.top(), tw + 4, main.height()), + Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft, self.text()) + if self.split: + dr = QRectF(r.right() - 44, r.top(), 44, r.height()) + dpath = QPainterPath() + self._split_right(dpath, dr) + p.fillPath(dpath, bg) + if self._hover_part == 2: + p.fillPath(dpath, with_alpha(fg, 0.08)) + paint_icon(p, QRectF(dr.center().x() - 11, dr.center().y() - 11, 22, 22), "expand_more", fg) + + @staticmethod + def _split_left(path: QPainterPath, r: QRectF): + R, rr = 20, 5 + path.moveTo(r.left() + R, r.top()) + path.lineTo(r.right() - rr, r.top()) + path.quadTo(r.right(), r.top(), r.right(), r.top() + rr) + path.lineTo(r.right(), r.bottom() - rr) + path.quadTo(r.right(), r.bottom(), r.right() - rr, r.bottom()) + path.lineTo(r.left() + R, r.bottom()) + path.arcTo(QRectF(r.left(), r.bottom() - 2 * R, 2 * R, 2 * R), 270, -180) + path.closeSubpath() + + @staticmethod + def _split_right(path: QPainterPath, r: QRectF): + R, rr = 20, 5 + path.moveTo(r.left() + rr, r.top()) + path.lineTo(r.right() - R, r.top()) + path.arcTo(QRectF(r.right() - 2 * R, r.top(), 2 * R, 2 * R), 90, -180) + path.lineTo(r.left() + rr, r.bottom()) + path.quadTo(r.left(), r.bottom(), r.left(), r.bottom() - rr) + path.lineTo(r.left(), r.top() + rr) + path.quadTo(r.left(), r.top(), r.left() + rr, r.top()) + path.closeSubpath() + + +# ---------------------------------------------------------------------- wavy slider +class WavySlider(QWidget): + """M3 Expressive wavy progress/seek bar.""" + seek_requested = pyqtSignal(float) # 0..1 + dragging = pyqtSignal(float) + + def __init__(self, parent=None): + super().__init__(parent) + self.value = 0.0 + self.playing = False + self._amp = 0.0 + self._phase = 0.0 + self._drag = None + self._hover = False + self.setMinimumHeight(28) + self.setMouseTracking(True) + self.setCursor(Qt.CursorShape.PointingHandCursor) + self._ticking = False + self.duration = 0.0 + self._target = None + + def set_value(self, v, duration: float = 0.0): + """Reported position. Between reports the thumb is extrapolated each + frame so it glides instead of stepping.""" + v = max(0.0, min(1.0, v)) + if duration > 0: + self.duration = duration + if self._drag is not None: + return + if not self._ticking or abs(v - self.value) * max(self.duration, 1) > 0.6: + self.value = v # seek / big jump: snap + if not self._ticking: + self.update() + else: + self._target = v + + def set_playing(self, on): + self.playing = on + self._ensure_tick() + + def _ensure_tick(self): + need = self.isVisible() and (self.playing or self._amp > 0.01) + if need and not self._ticking: + FrameClock.subscribe(self._tick) + self._ticking = True + elif not need and self._ticking: + FrameClock.unsubscribe(self._tick) + self._ticking = False + + def showEvent(self, e): + self._ensure_tick() + + def hideEvent(self, e): + if self._ticking: + FrameClock.unsubscribe(self._tick) + self._ticking = False + + def _tick(self, dt=1 / 60): + target = 1.0 if self.playing else 0.0 + self._amp += (target - self._amp) * min(1.0, dt * 7) + self._phase = (self._phase + dt * 6.6) % (2 * math.pi) + if self.playing and self.duration > 0 and self._drag is None: + self.value = min(1.0, self.value + dt / self.duration) + if self._target is not None: + self.value += (self._target - self.value) * min(1.0, dt * 3) + self._target = None if abs(self._target - self.value) < 1e-5 else self._target + self.update() + if not self.playing and self._amp < 0.01: + self._amp = 0.0 + self._ensure_tick() + + def _val_at(self, x): + m = 8 + return max(0.0, min(1.0, (x - m) / max(1, self.width() - 2 * m))) + + def mousePressEvent(self, e): + if e.button() == Qt.MouseButton.LeftButton: + self._drag = self._val_at(e.position().x()) + self.dragging.emit(self._drag) + self.update() + + def mouseMoveEvent(self, e): + if self._drag is not None: + self._drag = self._val_at(e.position().x()) + self.dragging.emit(self._drag) + self.update() + + def mouseReleaseEvent(self, e): + if self._drag is not None: + v = self._drag + self._drag = None + self.value = v + self.seek_requested.emit(v) + self.update() + + def enterEvent(self, e): + self._hover = True + self.update() + + def leaveEvent(self, e): + self._hover = False + self.update() + + def paintEvent(self, e): + p = QPainter(self) + p.setRenderHint(QPainter.RenderHint.Antialiasing) + m = 8.0 + w = self.width() - 2 * m + cy = self.height() / 2 + v = self._drag if self._drag is not None else self.value + tx = m + w * v + gap = 6.0 + stroke = 4.0 + prim = C("primary") + track = C("secondaryContainer") + # remaining track + if tx + gap < m + w: + p.setPen(QPen(track, stroke, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap)) + p.drawLine(QPointF(tx + gap, cy), QPointF(m + w, cy)) + # stop indicator + p.setPen(Qt.PenStyle.NoPen) + p.setBrush(prim) + p.drawEllipse(QPointF(m + w - 2, cy), 2, 2) + # wavy active part: amplitude eases in from a flat start and eases + # out before the thumb, so the line never starts on a sharp point + if tx - gap > m: + amp = 3.4 * self._amp + wl = 34.0 + x_end = tx - gap + ramp = 14.0 + path = QPainterPath(QPointF(m, cy)) + x = m + step = 1.5 + while x < x_end: + x = min(x + step, x_end) + env = min(1.0, (x - m) / ramp, (x_end - x) / ramp) + env = env * env * (3 - 2 * env) # smoothstep + y = cy + amp * env * math.sin((x - m) / wl * 2 * math.pi - self._phase) + path.lineTo(QPointF(x, y)) + p.setPen(QPen(prim, stroke, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap, Qt.PenJoinStyle.RoundJoin)) + p.setBrush(Qt.BrushStyle.NoBrush) + p.drawPath(path) + # thumb (vertical bar) + th = 22 if (self._hover or self._drag is not None) else 18 + p.setPen(Qt.PenStyle.NoPen) + p.setBrush(prim) + p.drawRoundedRect(QRectF(tx - 2.5, cy - th / 2, 5, th), 2.5, 2.5) + + +class VolumeSlider(QWidget): + changed = pyqtSignal(int) + + def __init__(self, parent=None): + super().__init__(parent) + self.value = 70 + self.setFixedHeight(28) + self.setMinimumWidth(90) + self.setCursor(Qt.CursorShape.PointingHandCursor) + self._drag = False + + def set_value(self, v): + self.value = int(v) + self.update() + + def _set_from(self, x): + v = int(round(max(0.0, min(1.0, (x - 6) / max(1, self.width() - 12))) * 100)) + if v != self.value: + self.value = v + self.changed.emit(v) + self.update() + + def mousePressEvent(self, e): + self._drag = True + self._set_from(e.position().x()) + + def mouseMoveEvent(self, e): + if self._drag: + self._set_from(e.position().x()) + + def mouseReleaseEvent(self, e): + self._drag = False + + def wheelEvent(self, e): + d = 5 if e.angleDelta().y() > 0 else -5 + self.value = max(0, min(100, self.value + d)) + self.changed.emit(self.value) + self.update() + + def paintEvent(self, e): + p = QPainter(self) + p.setRenderHint(QPainter.RenderHint.Antialiasing) + m = 6 + w = self.width() - 2 * m + cy = self.height() / 2 + x = m + w * self.value / 100 + h = 16.0 + p.setPen(Qt.PenStyle.NoPen) + p.setBrush(C("secondaryContainer")) + if x + 5 < m + w: + p.drawRoundedRect(QRectF(x + 5, cy - h / 2 + 2, m + w - x - 5, h - 4), 4, 4) + p.setBrush(C("primary")) + if x - 5 > m: + p.drawRoundedRect(QRectF(m, cy - h / 2, x - 5 - m, h), 7, 7) + p.drawRoundedRect(QRectF(x - 2, cy - 12, 4, 24), 2, 2) + + +# ---------------------------------------------------------------------- labels/fields +class ElideLabel(QLabel): + def __init__(self, text="", parent=None): + super().__init__(text, parent) + self._full = text + self.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred) + self.setMinimumWidth(10) + + def setText(self, t): + self._full = t or "" + self.setToolTip(self._full if len(self._full) > 30 else "") + self._elide() + + def text(self): + return self._full + + def resizeEvent(self, e): + self._elide() + + def _elide(self): + fm = QFontMetrics(self.font()) + super().setText(fm.elidedText(self._full, Qt.TextElideMode.ElideRight, max(10, self.width()))) + + +class SearchField(QLineEdit): + def __init__(self, placeholder="Search", parent=None): + super().__init__(parent) + self.setObjectName("search") + self.setFixedHeight(40) + self.setPlaceholderText(placeholder) + self.setClearButtonEnabled(True) + + def paintEvent(self, e): + super().paintEvent(e) + p = QPainter(self) + p.setRenderHint(QPainter.RenderHint.Antialiasing) + paint_icon(p, QRectF(12, self.height() / 2 - 10, 20, 20), "search", C("onSurfaceVariant")) + + +class NavTabs(QWidget): + """Icon-over-label tabs with a short pill indicator (like the M3 shell bar).""" + changed = pyqtSignal(int) + + def __init__(self, items: list[tuple[str, str]], parent=None): + super().__init__(parent) + self.items = items + self.current = 0 + self._hover = -1 + self._ind = 0.0 + self.setFixedHeight(58) + self.setMouseTracking(True) + self.setCursor(Qt.CursorShape.PointingHandCursor) + self._anim = QVariantAnimation(self, duration=260, easingCurve=QEasingCurve.Type.OutCubic) + self._anim.valueChanged.connect(lambda v: (setattr(self, "_ind", v), self.update())) + + def set_current(self, i, animate=True): + if i == self.current and animate: + return + self._anim.stop() + if animate: + self._anim.setStartValue(float(self._ind)) + self._anim.setEndValue(float(i)) + self._anim.start() + else: + self._ind = float(i) + self.current = i + self.update() + self.changed.emit(i) + + def _idx(self, x): + n = len(self.items) + return max(0, min(n - 1, int(x / (self.width() / n)))) + + def mouseMoveEvent(self, e): + i = self._idx(e.position().x()) + if i != self._hover: + self._hover = i + self.update() + + def leaveEvent(self, e): + self._hover = -1 + self.update() + + def mousePressEvent(self, e): + self.set_current(self._idx(e.position().x())) + + def paintEvent(self, e): + p = QPainter(self) + p.setRenderHint(QPainter.RenderHint.Antialiasing) + n = len(self.items) + cw = self.width() / n + f = self.font() + f.setPointSizeF(max(7.5, f.pointSizeF() * 0.86)) + p.setFont(f) + fm = QFontMetrics(f) + for i, (icon_name, label) in enumerate(self.items): + r = QRectF(i * cw, 0, cw, self.height() - 6) + active = i == self.current + col = C("primary") if active else C("onSurfaceVariant") + if i == self._hover and not active: + hp = QPainterPath() + hp.addRoundedRect(r.adjusted(4, 4, -4, 0), 12, 12) + p.fillPath(hp, with_alpha(C("onSurface"), 0.06)) + paint_icon(p, QRectF(r.center().x() - 11, 8, 22, 22), icon_name, col) + p.setPen(col) + p.drawText(QRectF(r.left(), 32, r.width(), 18), Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignTop, + fm.elidedText(label, Qt.TextElideMode.ElideRight, int(cw - 4))) + # indicator + iw = 28 + x = self._ind * cw + cw / 2 - iw / 2 + p.setPen(Qt.PenStyle.NoPen) + p.setBrush(C("primary")) + p.drawRoundedRect(QRectF(x, self.height() - 5, iw, 3), 1.5, 1.5) + p.setPen(QPen(C("outlineVariant"), 1)) + p.drawLine(QPointF(4, self.height() - 0.5), QPointF(self.width() - 4, self.height() - 0.5)) + + +class Card(QWidget): + """Rounded surface container.""" + + def __init__(self, role="surfaceContainerLow", radius=24, parent=None): + super().__init__(parent) + self.role, self.radius = role, radius + + def paintEvent(self, e): + p = QPainter(self) + p.setRenderHint(QPainter.RenderHint.Antialiasing) + path = QPainterPath() + path.addRoundedRect(QRectF(self.rect()), self.radius, self.radius) + p.fillPath(path, C(self.role)) + + +def make_alpha_prop(): + return pyqtProperty(float) diff --git a/mulberry/widgets/playlistview.py b/mulberry/widgets/playlistview.py new file mode 100644 index 0000000..e3b7b99 --- /dev/null +++ b/mulberry/widgets/playlistview.py @@ -0,0 +1,519 @@ +"""Strawberry-style tabbed playlists with Material styling and the album art +watermark behind the track list.""" +from __future__ import annotations + +import os +import subprocess + +from PyQt6.QtCore import QModelIndex, QPointF, QRectF, QSize, Qt, QTimer, pyqtSignal +from PyQt6.QtGui import (QAction, QColor, QFont, QKeySequence, QLinearGradient, QPainter, + QPainterPath, QPixmap) +from PyQt6.QtWidgets import (QAbstractItemView, QHBoxLayout, QHeaderView, QInputDialog, QMenu, + QStackedWidget, QStyle, QStyledItemDelegate, QTabBar, QToolButton, + QTreeView, QVBoxLayout, QWidget) + +from .. import library as L +from .. import theme as Th +from ..config import settings +from ..icons import icon, paint_icon +from ..playlist import COL, COL_KEYS, COLUMNS, PlaylistManager, PlaylistModel +from ..theme import mix +from .m3 import C, SearchField, with_alpha + + +class PlaylistDelegate(QStyledItemDelegate): + def __init__(self, view): + super().__init__(view) + self.view = view + + def sizeHint(self, option, index): + s = super().sizeHint(option, index) + return QSize(s.width(), max(30, s.height() + 6)) + + def paint(self, p: QPainter, opt, index): + model: PlaylistModel = index.model() + song = model.songs[index.row()] + key = COL_KEYS[index.column()] + current = song is model.current_song + selected = bool(opt.state & QStyle.StateFlag.State_Selected) + if current: + fg = C("onPrimary") + elif selected: + fg = C("onSecondaryContainer") + else: + fg = C("onSurface") if key in ("title",) else C("onSurfaceVariant") if key in ( + "track", "length", "filetype", "bitrate", "samplerate", "filesize", "year", "disc") else C("onSurface") + r = QRectF(opt.rect).adjusted(8, 0, -6, 0) + p.save() + p.setRenderHint(QPainter.RenderHint.Antialiasing) + if key == "source": + name = {"cd": "album", "stream": "radio", "collection": "music_note", "file": "folder"}[song.source] + s = 18 + paint_icon(p, QRectF(r.center().x() - s / 2, r.center().y() - s / 2, s, s), name, + fg if current else C("primary") if song.source == "collection" else C("onSurfaceVariant")) + p.restore() + return + if key == "rating": + for i in range(5): + on = i < song.rating + paint_icon(p, QRectF(r.left() + i * 16, r.center().y() - 8, 16, 16), + "star_fill" if on else "star", + (fg if current else C("primary")) if on else with_alpha(fg, 0.4)) + p.restore() + return + text = index.data(Qt.ItemDataRole.DisplayRole) or "" + if key == "track" and current: + ic = "graphic_eq" if model.playing else "pause_fill" + paint_icon(p, QRectF(r.left() - 2, r.center().y() - 9, 18, 18), ic, fg) + r = r.adjusted(18, 0, 0, 0) + f = QFont(opt.font) + if current: + f.setWeight(QFont.Weight.DemiBold) + p.setFont(f) + p.setPen(fg) + align = index.data(Qt.ItemDataRole.TextAlignmentRole) or int(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter) + txt = p.fontMetrics().elidedText(str(text), Qt.TextElideMode.ElideRight, int(r.width())) + p.drawText(r, Qt.AlignmentFlag(align), txt) + p.restore() + + def editorEvent(self, event, model, option, index): + if COL_KEYS[index.column()] == "rating" and event.type() == event.Type.MouseButtonRelease: + x = event.position().x() - option.rect.left() - 8 + rating = max(0, min(5, int(x // 16) + 1)) + song = model.songs[index.row()] + if song.rating == rating: + rating = 0 + L.library.set_rating(song, rating) + model.dataChanged.emit(index, index) + return True + return False + + +class PlaylistView(QTreeView): + play_requested = pyqtSignal(object, object) # model, song + context_requested = pyqtSignal(object, object) + + def __init__(self, model: PlaylistModel, parent=None): + super().__init__(parent) + self.pl = model + self.setModel(model) + self.setObjectName("playlist") + self.setRootIsDecorated(False) + self.setItemsExpandable(False) + self.setUniformRowHeights(True) + self.setAllColumnsShowFocus(True) + self.setAlternatingRowColors(False) + self.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection) + self.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows) + self.setDragDropMode(QAbstractItemView.DragDropMode.DragDrop) + self.setDefaultDropAction(Qt.DropAction.MoveAction) + self.setDropIndicatorShown(True) + self.setDragEnabled(True) + self.setAcceptDrops(True) + self.setSortingEnabled(False) + self.setItemDelegate(PlaylistDelegate(self)) + self.setVerticalScrollMode(QAbstractItemView.ScrollMode.ScrollPerPixel) + self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) + self.customContextMenuRequested.connect(lambda pos: self.context_requested.emit(self, self.viewport().mapToGlobal(pos))) + self.doubleClicked.connect(self._dbl) + self.verticalScrollBar().valueChanged.connect(lambda *_: self.viewport().update()) + self.art: QPixmap | None = None + self._art_scaled: QPixmap | None = None + h = self.header() + h.setSectionsMovable(True) + h.setStretchLastSection(False) + h.setSectionsClickable(True) + h.setSortIndicatorShown(False) + h.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) + h.customContextMenuRequested.connect(self._header_menu) + h.sectionClicked.connect(self._sort) + h.sectionResized.connect(lambda *_: self._save_header()) + h.sectionMoved.connect(lambda *_: self._save_header()) + self._sort_state = {} + self._restore_header() + self.setStyleSheet("QTreeView#playlist::item, QTreeView#playlist::item:selected, " + "QTreeView#playlist::item:hover { background: transparent; }") + model.modelReset.connect(self._filter_again) + model.rowsInserted.connect(self._filter_again) + + # -------------------------------------------------------------- header + def _restore_header(self): + h = self.header() + st = settings.raw().value("playlist/header") + for i, (_, _, vis, w) in enumerate(COLUMNS): + h.resizeSection(i, w) + h.setSectionHidden(i, not vis) + if st is not None: + h.restoreState(st) + h.setSectionResizeMode(COL["title"], QHeaderView.ResizeMode.Interactive) + + def _save_header(self): + if self.isVisible(): + settings.raw().setValue("playlist/header", self.header().saveState()) + PlaylistArea.instance and PlaylistArea.instance.sync_headers(self) + + def _header_menu(self, pos): + m = QMenu(self) + h = self.header() + for i, (_, name, _, _) in enumerate(COLUMNS): + a = m.addAction(name) + a.setCheckable(True) + a.setChecked(not h.isSectionHidden(i)) + a.toggled.connect(lambda on, i=i: (h.setSectionHidden(i, not on), self._save_header())) + m.addSeparator() + m.addAction("Reset columns", self._reset_cols) + m.exec(h.mapToGlobal(pos)) + + def _reset_cols(self): + settings.raw().remove("playlist/header") + h = self.header() + for i, (_, _, vis, w) in enumerate(COLUMNS): + h.moveSection(h.visualIndex(i), i) + h.resizeSection(i, w) + h.setSectionHidden(i, not vis) + self._save_header() + + def _sort(self, col): + order = self._sort_state.get(col, Qt.SortOrder.DescendingOrder) + order = Qt.SortOrder.AscendingOrder if order == Qt.SortOrder.DescendingOrder else Qt.SortOrder.DescendingOrder + self._sort_state = {col: order} + self.pl.sort(col, order) + + # -------------------------------------------------------------- interaction + def _dbl(self, idx): + if idx.isValid(): + self.play_requested.emit(self.pl, self.pl.songs[idx.row()]) + + def keyPressEvent(self, e): + if e.key() in (Qt.Key.Key_Return, Qt.Key.Key_Enter): + idx = self.currentIndex() + if idx.isValid(): + self.play_requested.emit(self.pl, self.pl.songs[idx.row()]) + return + if e.matches(QKeySequence.StandardKey.Delete) or e.key() == Qt.Key.Key_Backspace: + self.remove_selected() + return + super().keyPressEvent(e) + + def selected_rows(self): + return sorted({i.row() for i in self.selectionModel().selectedRows()}) + + def selected_songs(self): + return [self.pl.songs[r] for r in self.selected_rows()] + + def remove_selected(self): + rows = self.selected_rows() + if rows: + self.pl.remove_rows(rows) + + def currentChanged(self, cur, prev): + super().currentChanged(cur, prev) + self.pl.selected_song = self.pl.songs[cur.row()] if cur.isValid() and cur.row() < len(self.pl.songs) else None + + def scroll_to_current(self): + r = self.pl.current_row() + if r >= 0: + self.scrollTo(self.pl.index(r, 0), QAbstractItemView.ScrollHint.PositionAtCenter) + + # -------------------------------------------------------------- filter + def set_filter(self, text): + self.pl.filter_text = text.lower().strip() + self._filter_again() + + def _filter_again(self, *_): + t = self.pl.filter_text + if not t: + if getattr(self, "_filtered", False): + for r in range(len(self.pl.songs)): + self.setRowHidden(r, QModelIndex(), False) + self._filtered = False + return + self._filtered = True + toks = t.split() + for r, s in enumerate(self.pl.songs): + hay = f"{s.display_title()} {s.artist} {s.album} {s.albumartist} {s.genre} {s.year}".lower() + self.setRowHidden(r, QModelIndex(), not all(tok in hay for tok in toks)) + + # -------------------------------------------------------------- painting + def set_art(self, pm: QPixmap | None): + self.art = pm + self._art_scaled = None + self.viewport().update() + + def resizeEvent(self, e): + super().resizeEvent(e) + self._art_scaled = None + + def paintEvent(self, e): + if self.art is not None and not self.art.isNull() and settings.get("appearance/playlist_art_bg"): + vp = self.viewport() + p = QPainter(vp) + if self._art_scaled is None: + side = int(min(vp.height() * 0.95, vp.width() * 0.6) * self.devicePixelRatioF()) + self._art_scaled = self.art.scaled(side, side, Qt.AspectRatioMode.KeepAspectRatio, + Qt.TransformationMode.SmoothTransformation) + self._art_scaled.setDevicePixelRatio(self.devicePixelRatioF()) + pm = self._art_scaled + w = pm.width() / pm.devicePixelRatio() + h = pm.height() / pm.devicePixelRatio() + x = (vp.width() - w) / 2 + y = (vp.height() - h) / 2 + p.setOpacity(0.11 if Th.theme.dark else 0.09) + path = QPainterPath() + path.addRoundedRect(QRectF(x, y, w, h), 28, 28) + p.setClipPath(path) + p.drawPixmap(QPointF(x, y), pm) + p.end() + super().paintEvent(e) + + def drawRow(self, p: QPainter, opt, index): + row = index.row() + song = self.pl.songs[row] + hs = self.horizontalScrollBar().value() + total = max(self.header().length(), self.viewport().width()) + r = QRectF(4 - hs, opt.rect.top() + 1, total - 8, opt.rect.height() - 2) + p.save() + p.setRenderHint(QPainter.RenderHint.Antialiasing) + path = QPainterPath() + path.addRoundedRect(r, 12, 12) + if song is self.pl.current_song: + g = QLinearGradient(r.left(), 0, r.right(), 0) + prim = C("primary") + g.setColorAt(0, with_alpha(prim, 0.95)) + g.setColorAt(1, with_alpha(mix(prim, C("tertiary"), 0.55), 0.72)) + p.fillPath(path, g) + elif self.selectionModel().isRowSelected(row, QModelIndex()): + p.fillPath(path, C("secondaryContainer")) + elif row % 2: + p.fillPath(path, with_alpha(C("onSurface"), 0.028)) + p.restore() + super().drawRow(p, opt, index) + + +class PlaylistArea(QWidget): + """Tab strip + toolbar + one PlaylistView per playlist.""" + instance: "PlaylistArea" = None + play_requested = pyqtSignal(object, object) + context_requested = pyqtSignal(object, object) + + def __init__(self, mgr: PlaylistManager, parent=None): + super().__init__(parent) + PlaylistArea.instance = self + self.mgr = mgr + self.views: dict[int, PlaylistView] = {} + self._art: QPixmap | None = None + lay = QVBoxLayout(self) + lay.setContentsMargins(6, 0, 6, 0) + lay.setSpacing(2) + + top = QHBoxLayout() + top.setSpacing(4) + self.tabs = QTabBar() + self.tabs.setMovable(True) + self.tabs.setTabsClosable(True) + self.tabs.setExpanding(False) + self.tabs.setUsesScrollButtons(True) + self.tabs.setDocumentMode(True) + self.tabs.setElideMode(Qt.TextElideMode.ElideRight) + self.tabs.setIconSize(QSize(18, 18)) + self.tabs.currentChanged.connect(self._tab_changed) + self.tabs.tabCloseRequested.connect(self._close_tab) + self.tabs.tabMoved.connect(self._tab_moved) + self.tabs.tabBarDoubleClicked.connect(self._rename) + self.tabs.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) + self.tabs.customContextMenuRequested.connect(self._tab_menu) + top.addWidget(self.tabs, 1) + addb = QToolButton() + addb.setIcon(icon("add")) + addb.setToolTip("New playlist (Ctrl+T)") + addb.clicked.connect(lambda: mgr.new_playlist()) + top.addWidget(addb) + lay.addLayout(top) + + tb = QHBoxLayout() + tb.setSpacing(2) + self.tool = {} + for key, ic, tip in (("new", "playlist_add", "New playlist"), + ("import", "file_open", "Import playlist…"), + ("export", "save", "Export playlist…"), + ("clear", "clear_all", "Clear playlist"), + ("undo", "undo", "Undo"), ("redo", "redo", "Redo"), + ("shuffle", "shuffle", "Shuffle playlist order"), + ("dedupe", "content_copy", "Remove duplicates"), + ("jump", "my_location", "Jump to playing track")): + b = QToolButton() + b.setIcon(icon(ic if ic != "my_location" else "queue_play_next")) + b.setToolTip(tip) + b.setIconSize(QSize(20, 20)) + tb.addWidget(b) + self.tool[key] = b + tb.addStretch(1) + self.filter = SearchField("Filter playlist (artist, album, title…)") + self.filter.setMaximumWidth(340) + self._ft = QTimer(self, singleShot=True, interval=180) + self._ft.timeout.connect(lambda: self.view() and self.view().set_filter(self.filter.text())) + self.filter.textChanged.connect(lambda: self._ft.start()) + tb.addWidget(self.filter) + lay.addLayout(tb) + + self.stack = QStackedWidget() + lay.addWidget(self.stack, 1) + + self.tool["new"].clicked.connect(lambda: mgr.new_playlist()) + self.tool["clear"].clicked.connect(lambda: self.model() and self.model().clear()) + self.tool["undo"].clicked.connect(lambda: self.model() and self.model().undo.undo()) + self.tool["redo"].clicked.connect(lambda: self.model() and self.model().undo.redo()) + self.tool["shuffle"].clicked.connect(lambda: self.model() and self.model().shuffle_items()) + self.tool["dedupe"].clicked.connect(lambda: self.model() and self.model().remove_duplicates()) + self.tool["jump"].clicked.connect(self.jump_to_current) + + mgr.added.connect(self._added) + mgr.removed.connect(self._removed) + mgr.renamed.connect(self._refresh_tabs) + mgr.current_changed.connect(self._show) + mgr.active_changed.connect(self._refresh_tabs) + for pl in mgr.playlists: + self._added(pl) + + # -------------------------------------------------------------- tabs + def _added(self, pl): + v = PlaylistView(pl) + v.play_requested.connect(self.play_requested) + v.context_requested.connect(self.context_requested) + v.set_art(self._art) + self.views[id(pl)] = v + self.stack.addWidget(v) + self.tabs.blockSignals(True) + self.tabs.addTab(pl.name) + self.tabs.blockSignals(False) + self._refresh_tabs() + + def _removed(self, pl): + v = self.views.pop(id(pl), None) + if v: + self.stack.removeWidget(v) + v.deleteLater() + self._refresh_tabs() + + def _refresh_tabs(self, *_): + self.tabs.blockSignals(True) + while self.tabs.count() > len(self.mgr.playlists): + self.tabs.removeTab(self.tabs.count() - 1) + while self.tabs.count() < len(self.mgr.playlists): + self.tabs.addTab("") + for i, pl in enumerate(self.mgr.playlists): + self.tabs.setTabText(i, pl.name) + if pl is self.mgr.active and self.mgr.active is not None and pl.current_song is not None: + self.tabs.setTabIcon(i, icon("graphic_eq", "primary")) + elif pl.favorite: + self.tabs.setTabIcon(i, icon("star_fill", "primary")) + else: + self.tabs.setTabIcon(i, icon("queue_music")) + if self.mgr.current in self.mgr.playlists: + self.tabs.setCurrentIndex(self.mgr.playlists.index(self.mgr.current)) + self.tabs.blockSignals(False) + + def _tab_changed(self, i): + if 0 <= i < len(self.mgr.playlists): + self.mgr.set_current(self.mgr.playlists[i]) + + def _show(self, pl): + v = self.views.get(id(pl)) + if v: + self.stack.setCurrentWidget(v) + self.filter.blockSignals(True) + self.filter.setText(pl.filter_text) + self.filter.blockSignals(False) + self._refresh_tabs() + + def _close_tab(self, i): + self.mgr.close_playlist(self.mgr.playlists[i]) + + def _tab_moved(self, frm, to): + self.mgr.move_playlist(frm, to) + + def _rename(self, i): + if i < 0: + self.mgr.new_playlist() + return + pl = self.mgr.playlists[i] + name, ok = QInputDialog.getText(self, "Rename playlist", "Name:", text=pl.name) + if ok and name.strip(): + self.mgr.rename(pl, name.strip()) + + def _tab_menu(self, pos): + i = self.tabs.tabAt(pos) + if i < 0: + return + pl = self.mgr.playlists[i] + m = QMenu(self) + m.addAction(icon("edit"), "Rename…", lambda: self._rename(i)) + fav = m.addAction(icon("star_fill" if pl.favorite else "star"), + "Unpin from saved playlists" if pl.favorite else "Keep in saved playlists") + fav.triggered.connect(lambda: self._toggle_fav(pl)) + m.addAction(icon("save"), "Export…", lambda: self.window().export_playlist(pl)) + m.addAction(icon("content_copy"), "Duplicate", lambda: self.mgr.new_playlist(pl.name + " (copy)", list(pl.songs))) + m.addSeparator() + m.addAction(icon("close"), "Close", lambda: self.mgr.close_playlist(pl)) + m.addAction("Close other playlists", + lambda: [self.mgr.close_playlist(p) for p in list(self.mgr.playlists) if p is not pl]) + m.exec(self.tabs.mapToGlobal(pos)) + + def _toggle_fav(self, pl): + pl.favorite = not pl.favorite + self.mgr.save_all() + self._refresh_tabs() + self.window().refresh_saved_playlists() + + # -------------------------------------------------------------- misc + def view(self) -> PlaylistView | None: + return self.stack.currentWidget() + + def model(self) -> PlaylistModel | None: + return self.mgr.current + + def view_for(self, pl) -> PlaylistView | None: + return self.views.get(id(pl)) + + def jump_to_current(self): + pl = self.mgr.active + if pl: + self.mgr.set_current(pl) + v = self.view_for(pl) + v and v.scroll_to_current() + + def set_art(self, pm: QPixmap | None): + self._art = pm + for v in self.views.values(): + v.set_art(pm) + + def sync_headers(self, src): + st = src.header().saveState() + for v in self.views.values(): + if v is not src: + v.header().blockSignals(True) + v.header().restoreState(st) + v.header().blockSignals(False) + + +def show_in_file_manager(path: str): + if not path or not os.path.exists(path): + return + import sys + if sys.platform == "win32": + subprocess.Popen(["explorer", "/select,", os.path.normpath(path)]) + return + if sys.platform == "darwin": + subprocess.Popen(["open", "-R", path]) + return + try: + from PyQt6.QtDBus import QDBusConnection, QDBusMessage + from pathlib import Path + msg = QDBusMessage.createMethodCall("org.freedesktop.FileManager1", "/org/freedesktop/FileManager1", + "org.freedesktop.FileManager1", "ShowItems") + msg.setArguments([[Path(path).as_uri()], ""]) + if QDBusConnection.sessionBus().send(msg): + return + except Exception: # noqa: BLE001 + pass + subprocess.Popen(["xdg-open", os.path.dirname(path)]) diff --git a/mulberry/widgets/sidebar.py b/mulberry/widgets/sidebar.py new file mode 100644 index 0000000..92466f7 --- /dev/null +++ b/mulberry/widgets/sidebar.py @@ -0,0 +1,742 @@ +"""Left side panels: Library (collection), Files, Playlists, Radio and CD.""" +from __future__ import annotations + +import json +import os + +from PyQt6.QtCore import QDir, QModelIndex, QMimeData, QSize, Qt, QTimer, pyqtSignal +from PyQt6.QtGui import QFileSystemModel, QIcon, QStandardItem, QStandardItemModel +from PyQt6.QtWidgets import (QAbstractItemView, QComboBox, QHBoxLayout, QInputDialog, QLabel, + QLineEdit, QListWidget, QListWidgetItem, QMenu, QMessageBox, + QProgressBar, QPushButton, QStackedWidget, QToolButton, QTreeView, + QVBoxLayout, QWidget) + +from .. import cd as CD +from .. import library as L +from .. import tags as T +from ..config import AUDIO_EXTS, PLAYLIST_EXTS, fmt_time, run_async, settings +from ..icons import icon +from ..playlist import SONGS_MIME +from ..song import Song +from .m3 import NavTabs, SearchField + +GROUPINGS = { + "albumartist_album": ("Album artist › Album", ["albumartist", "album"]), + "artist_album": ("Artist › Album", ["artist", "album"]), + "genre_albumartist_album": ("Genre › Album artist › Album", ["genre", "albumartist", "album"]), + "year_album": ("Year › Album", ["year", "album"]), + "album": ("Album", ["album"]), + "genre_album": ("Genre › Album", ["genre", "album"]), + "artist": ("Artist", ["artist"]), +} +ROLE_FILTER = Qt.ItemDataRole.UserRole + 1 +ROLE_SONG = Qt.ItemDataRole.UserRole + 2 +ROLE_LOADED = Qt.ItemDataRole.UserRole + 3 + + +def _col_expr(field): + if field == "albumartist": + return "CASE WHEN albumartist IS NULL OR albumartist='' THEN artist ELSE albumartist END" + return field + + +def _cond(where, args, f, v): + ce = _col_expr(f) + if v in ("", None): + where.append(f"COALESCE({ce},'') = ''") + elif f == "year" and v == 0: + where.append("COALESCE(year,0) = 0") + else: + where.append(f"{ce} = ?") + args.append(v) + + +class LibraryModel(QStandardItemModel): + def mimeTypes(self): + return [SONGS_MIME, "text/uri-list"] + + def mimeData(self, indexes): + panel = LibraryPanel.instance + songs = panel.songs_for_indexes(indexes) if panel else [] + md = QMimeData() + md.setData(SONGS_MIME, json.dumps([s.to_dict() for s in songs]).encode()) + return md + + +class LibraryPanel(QWidget): + instance: "LibraryPanel" = None + add_songs = pyqtSignal(list, str) # songs, mode: append|replace|new|play|queue|next + context = pyqtSignal(list, object) # songs, global pos + + def __init__(self, parent=None): + super().__init__(parent) + LibraryPanel.instance = self + self.lib = L.library + lay = QVBoxLayout(self) + lay.setContentsMargins(8, 8, 8, 4) + lay.setSpacing(6) + row = QHBoxLayout() + self.search = SearchField("Search library") + self.search.setToolTip("Tips: artist:name album:x genre:rock year:>2000 rating:>3") + row.addWidget(self.search, 1) + self.group_btn = QToolButton() + self.group_btn.setIcon(icon("filter_list")) + self.group_btn.setToolTip("Group by") + self.group_btn.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup) + gm = QMenu(self) + for key, (label, _) in GROUPINGS.items(): + a = gm.addAction(label) + a.setCheckable(True) + a.setChecked(key == settings.get("library/grouping")) + a.triggered.connect(lambda _c, k=key: self.set_grouping(k)) + self.group_menu = gm + self.group_btn.setMenu(gm) + row.addWidget(self.group_btn) + lay.addLayout(row) + + self.progress = QProgressBar() + self.progress.setTextVisible(False) + self.progress.hide() + self.status = QLabel() + self.status.setObjectName("muted") + self.status.hide() + lay.addWidget(self.progress) + lay.addWidget(self.status) + + self.empty = QWidget() + el = QVBoxLayout(self.empty) + el.addStretch(1) + msg = QLabel("Your library is empty.\nAdd a music folder to get started.") + msg.setAlignment(Qt.AlignmentFlag.AlignCenter) + msg.setObjectName("muted") + el.addWidget(msg) + btn = QPushButton(icon("library_add", "onPrimary"), " Add music folder") + btn.setProperty("primary", True) + btn.clicked.connect(lambda: self.window().add_library_folder()) + el.addWidget(btn, 0, Qt.AlignmentFlag.AlignCenter) + el.addStretch(2) + + self.tree = QTreeView() + self.model = LibraryModel(self) + self.tree.setModel(self.model) + self.tree.setHeaderHidden(True) + self.tree.setIconSize(QSize(36, 36)) + self.tree.setUniformRowHeights(False) + self.tree.setAnimated(True) + self.tree.setIndentation(14) + self.tree.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection) + self.tree.setDragEnabled(True) + self.tree.setDragDropMode(QAbstractItemView.DragDropMode.DragOnly) + self.tree.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers) + self.tree.expanded.connect(self._expand) + self.tree.doubleClicked.connect(self._dbl) + self.tree.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) + self.tree.customContextMenuRequested.connect(self._menu) + self.stack = QStackedWidget() + self.stack.addWidget(self.tree) + self.stack.addWidget(self.empty) + lay.addWidget(self.stack, 1) + + self._t = QTimer(self, singleShot=True, interval=280) + self._t.timeout.connect(self.reload) + self.search.textChanged.connect(lambda: self._t.start()) + self.lib.changed.connect(lambda: self._t.start()) + self.lib.scan_progress.connect(self._progress) + self.lib.scan_finished.connect(self._scan_done) + self.reload() + + # ------------------------------------------------------------ build + def set_grouping(self, key): + settings.set("library/grouping", key) + for a in self.group_menu.actions(): + a.setChecked(a.text() == GROUPINGS[key][0]) + self.reload() + + def fields(self): + return GROUPINGS.get(settings.get("library/grouping"), GROUPINGS["albumartist_album"])[1] + + def reload(self): + n, _ = self.lib.count() + self.stack.setCurrentIndex(0 if n or self.search.text() else 1) + expanded = self._expanded_keys() + self.model.clear() + self._where, self._args = self.lib.filter_clause(self.search.text()) + self._fill(self.model.invisibleRootItem(), {}, 0) + if self.search.text().strip() and self.model.rowCount() <= 12: + for r in range(self.model.rowCount()): + self.tree.expand(self.model.index(r, 0)) + else: + self._restore_expanded(expanded) + + def _expanded_keys(self): + keys = set() + for r in range(self.model.rowCount()): + idx = self.model.index(r, 0) + if self.tree.isExpanded(idx): + keys.add(idx.data()) + return keys + + def _restore_expanded(self, keys): + if not keys: + return + for r in range(self.model.rowCount()): + idx = self.model.index(r, 0) + if idx.data() in keys: + self.tree.expand(idx) + + def _fill(self, parent: QStandardItem, flt: dict, level: int): + fields = self.fields() + where = [self._where] + args = list(self._args) + for f, v in flt.items(): + _cond(where, args, f, v) + wsql = " AND ".join(f"({w})" for w in where) + if level < len(fields): + f = fields[level] + ce = _col_expr(f) + extra = ", MIN(year) AS y, MAX(art) AS art, COUNT(*) AS n" if f == "album" else ", COUNT(*) AS n" + order = "y, v COLLATE NOCASE" if (f == "album" and level > 0) else ( + "v DESC" if f == "year" else "v COLLATE NOCASE") + rows = self.lib.query(f"SELECT {ce} AS v{extra} FROM songs WHERE unavailable=0 AND {wsql} " + f"GROUP BY {ce} ORDER BY {order}", args) + items = [] + for r in rows: + v = r["v"] + label = str(v) if v not in (None, "", 0) else {"year": "Unknown year", "genre": "Unknown genre", + "album": "Unknown album"}.get(f, "Unknown artist") + if f == "album" and r["y"]: + label = f"{label}" + it = QStandardItem(label) + it.setData({**flt, f: v if v is not None else ""}, ROLE_FILTER) + if f == "album": + sub = f"{r['y']} · {r['n']} tracks" if r["y"] else f"{r['n']} tracks" + it.setToolTip(sub) + it.setText(f"{label}\n{sub}") + th = T.thumb_for(r["art"]) if r["art"] else None + it.setIcon(QIcon(th) if th else icon("album")) + it.setSizeHint(QSize(0, 46)) + elif f in ("artist", "albumartist"): + it.setIcon(icon("artist")) + elif f == "genre": + it.setIcon(icon("label")) + elif f == "year": + it.setIcon(icon("history")) + it.setEditable(False) + it.appendRow(QStandardItem("…")) + items.append(it) + for it in items: + parent.appendRow(it) + else: + songs = self.lib.songs_where(wsql, args, order="disc, track, title COLLATE NOCASE") + multi_disc = len({s.disc for s in songs}) > 1 + for s in songs: + num = (f"{s.disc}." if multi_disc and s.disc else "") + (f"{s.track:02d}" if s.track else "") + txt = f"{num} {s.display_title()}" if num else s.display_title() + if "artist" not in fields and "albumartist" not in fields or ( + s.artist and s.albumartist and s.artist != s.albumartist): + txt += f" — {s.artist}" + it = QStandardItem(txt) + it.setData(s, ROLE_SONG) + it.setToolTip(f"{s.display_title()}\n{s.display_artist()} · {fmt_time(s.duration())}\n{s.path}") + it.setEditable(False) + parent.appendRow(it) + parent.setData(True, ROLE_LOADED) + + def _expand(self, idx): + it = self.model.itemFromIndex(idx) + if it is None or it.data(ROLE_LOADED): + return + it.removeRows(0, it.rowCount()) + flt = it.data(ROLE_FILTER) or {} + self._fill(it, flt, len(flt)) + + # ------------------------------------------------------------ songs for selection + def songs_for_indexes(self, indexes) -> list[Song]: + out, seen = [], set() + for idx in indexes: + if idx.column() != 0: + continue + it = self.model.itemFromIndex(idx) + if it is None: + continue + # skip children whose ancestor is also selected + par = idx.parent() + skip = False + while par.isValid(): + if par in indexes: + skip = True + break + par = par.parent() + if skip: + continue + s = it.data(ROLE_SONG) + if s is not None: + if s.url not in seen: + out.append(s) + seen.add(s.url) + continue + flt = it.data(ROLE_FILTER) or {} + where, args = [self._where], list(self._args) + for f, v in flt.items(): + _cond(where, args, f, v) + for s in self.lib.songs_where(" AND ".join(f"({w})" for w in where), args): + if s.url not in seen: + out.append(s) + seen.add(s.url) + return out + + def selected_songs(self): + return self.songs_for_indexes(self.tree.selectionModel().selectedIndexes()) + + def _dbl(self, idx): + it = self.model.itemFromIndex(idx) + if it is not None and it.data(ROLE_SONG) is not None: + self.add_songs.emit(self.songs_for_indexes([idx]), "play") + + def _menu(self, pos): + songs = self.selected_songs() + if not songs: + return + self.context.emit(songs, self.tree.viewport().mapToGlobal(pos)) + + # ------------------------------------------------------------ scan feedback + def _progress(self, done, total, path): + self.progress.show() + self.status.show() + self.progress.setMaximum(max(1, total)) + self.progress.setValue(done) + self.status.setText(f"Scanning… {done}/{total}") + + def _scan_done(self, a, u, r): + self.progress.hide() + self.status.setText(f"Library updated: {a} added, {u} updated, {r} removed") + QTimer.singleShot(5000, self.status.hide) + + +# ---------------------------------------------------------------------- files +class FilesPanel(QWidget): + add_paths = pyqtSignal(list, str) + + def __init__(self, parent=None): + super().__init__(parent) + lay = QVBoxLayout(self) + lay.setContentsMargins(8, 8, 8, 4) + row = QHBoxLayout() + self.up = QToolButton() + self.up.setIcon(icon("arrow_back")) + self.up.setToolTip("Up") + self.home = QToolButton() + self.home.setIcon(icon("library_music")) + self.home.setToolTip("Music folder") + self.path = QLineEdit() + row.addWidget(self.up) + row.addWidget(self.home) + row.addWidget(self.path, 1) + lay.addLayout(row) + self.fs = QFileSystemModel(self) + self.fs.setFilter(QDir.Filter.AllDirs | QDir.Filter.Files | QDir.Filter.NoDotAndDotDot) + self.fs.setNameFilters([f"*.{e}" for e in sorted(AUDIO_EXTS | PLAYLIST_EXTS)] + + [f"*.{e.upper()}" for e in sorted(AUDIO_EXTS | PLAYLIST_EXTS)]) + self.fs.setNameFilterDisables(False) + self.fs.setRootPath("") + self.tree = QTreeView() + self.tree.setModel(self.fs) + for c in (1, 2, 3): + self.tree.hideColumn(c) + self.tree.setHeaderHidden(True) + self.tree.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection) + self.tree.setDragEnabled(True) + self.tree.setDragDropMode(QAbstractItemView.DragDropMode.DragOnly) + self.tree.doubleClicked.connect(self._dbl) + self.tree.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) + self.tree.customContextMenuRequested.connect(self._menu) + lay.addWidget(self.tree, 1) + self.up.clicked.connect(lambda: self.set_root(os.path.dirname(self.path.text().rstrip("/")) or "/")) + self.home.clicked.connect(self.go_home) + self.path.returnPressed.connect(lambda: self.set_root(self.path.text())) + self.go_home() + + def go_home(self): + folders = settings.get("library/folders") + d = folders[0] if folders else os.path.expanduser("~/Music") + self.set_root(d if os.path.isdir(d) else os.path.expanduser("~")) + + def set_root(self, d): + if os.path.isdir(d): + self.tree.setRootIndex(self.fs.index(d)) + self.path.setText(d) + + def _sel(self): + return [self.fs.filePath(i) for i in self.tree.selectionModel().selectedRows(0)] + + def _dbl(self, idx): + p = self.fs.filePath(idx) + if os.path.isdir(p): + self.set_root(p) + else: + self.add_paths.emit([p], "play") + + def _menu(self, pos): + paths = self._sel() + if not paths: + return + m = QMenu(self) + m.addAction(icon("playlist_add"), "Append to playlist", lambda: self.add_paths.emit(paths, "append")) + m.addAction(icon("play_arrow"), "Append and play", lambda: self.add_paths.emit(paths, "play")) + m.addAction(icon("playlist_play"), "Replace current playlist", lambda: self.add_paths.emit(paths, "replace")) + m.addAction(icon("queue_music"), "Open in new playlist", lambda: self.add_paths.emit(paths, "new")) + if len(paths) == 1 and os.path.isdir(paths[0]): + m.addSeparator() + m.addAction(icon("library_add"), "Add folder to library", + lambda: self.window().add_library_folder(paths[0])) + m.exec(self.tree.viewport().mapToGlobal(pos)) + + +# ---------------------------------------------------------------------- playlists +SMART = [ + ("Recently added", "history", "added > 0", "added DESC", 200), + ("Most played", "trending_up", "playcount > 0", "playcount DESC, lastplayed DESC", 100), + ("Recently played", "history", "lastplayed > 0", "lastplayed DESC", 100), + ("Loved & top rated", "favorite_fill", "rating >= 4", "rating DESC, playcount DESC", 500), + ("Never played", "visibility", "playcount = 0", "RANDOM()", 100), + ("Random 100", "shuffle", "1", "RANDOM()", 100), + ("Most skipped", "skip_next", "skipcount > 0", "skipcount DESC", 100), +] + + +class PlaylistsPanel(QWidget): + open_smart = pyqtSignal(str, list) + open_saved = pyqtSignal(int) + + def __init__(self, parent=None): + super().__init__(parent) + lay = QVBoxLayout(self) + lay.setContentsMargins(8, 8, 8, 4) + h1 = QLabel("Smart playlists") + h1.setObjectName("muted") + lay.addWidget(h1) + self.smart = QListWidget() + self.smart.setIconSize(QSize(22, 22)) + for name, ic, *_ in SMART: + QListWidgetItem(icon(ic, "primary"), name, self.smart) + for i in range(self.smart.count()): + self.smart.item(i).setSizeHint(QSize(0, 36)) + self.smart.setFixedHeight(len(SMART) * 36 + 12) + self.smart.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) + self.smart.itemClicked.connect(self._smart) + lay.addWidget(self.smart) + h2 = QLabel("Saved playlists") + h2.setObjectName("muted") + lay.addWidget(h2) + self.saved = QListWidget() + self.saved.setIconSize(QSize(22, 22)) + self.saved.setWordWrap(True) + self.saved.itemClicked.connect(self._saved_click) + self.saved.itemDoubleClicked.connect(self._saved_dbl) + self.saved.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) + self.saved.customContextMenuRequested.connect(self._saved_menu) + lay.addWidget(self.saved, 1) + tip = QLabel("Click: jump to an open playlist · Double-click: reopen a closed one") + tip.setObjectName("muted") + tip.setWordWrap(True) + lay.addWidget(tip) + self._rt = QTimer(self, singleShot=True, interval=250) + self._rt.timeout.connect(self.refresh) + from ..playlist import PlaylistManager + mgr = PlaylistManager.instance + if mgr is not None: + for sig in (mgr.added, mgr.removed, mgr.renamed, mgr.current_changed, mgr.summary_changed): + sig.connect(lambda *_: self._rt.start()) + self.refresh() + + @staticmethod + def _mgr(): + from ..playlist import PlaylistManager + return PlaylistManager.instance + + def _open_pl(self, pid): + mgr = self._mgr() + if mgr is None: + return None + return next((p for p in mgr.playlists if p.pid == pid), None) + + def refresh(self): + mgr = self._mgr() + sel = self.saved.currentItem().data(Qt.ItemDataRole.UserRole) if self.saved.currentItem() else None + self.saved.clear() + rows = list(L.library.load_playlists()) + seen = set() + for r in rows: + pl = self._open_pl(r["id"]) + fav = bool(pl.favorite) if pl is not None else bool(r["favorite"]) + if not fav: + continue + seen.add(r["id"]) + if pl is not None: + n, name, is_open = len(pl.songs), pl.name, True + else: + try: + n = len(json.loads(r["items"] or "[]")) + except ValueError: + n = 0 + name, is_open = r["name"], False + current = mgr is not None and pl is not None and pl is mgr.current + state = "showing" if current else ("open" if is_open else "closed · double-click to reopen") + it = QListWidgetItem(icon("playlist_play" if is_open else "star_fill", "primary"), + f"{name}\n{n} track{'s' if n != 1 else ''} · {state}") + it.setData(Qt.ItemDataRole.UserRole, r["id"]) + it.setSizeHint(QSize(0, 48)) + if current: + f = it.font() + f.setBold(True) + it.setFont(f) + self.saved.addItem(it) + if r["id"] == sel: + self.saved.setCurrentItem(it) + if not self.saved.count(): + it = QListWidgetItem("Right-click a playlist tab › Keep in saved playlists") + it.setFlags(Qt.ItemFlag.NoItemFlags) + self.saved.addItem(it) + + def _saved_click(self, it): + pid = it.data(Qt.ItemDataRole.UserRole) + pl = self._open_pl(pid) if pid is not None else None + if pl is not None: + self._mgr().set_current(pl) + + def _saved_dbl(self, it): + pid = it.data(Qt.ItemDataRole.UserRole) + if pid is not None: + self.open_saved.emit(pid) + + def _smart(self, it): + name, _, where, order, limit = SMART[self.smart.row(it)] + songs = L.library.songs_where(where, (), order=f"{order} LIMIT {limit}") + self.open_smart.emit(name, songs) + + def _saved_menu(self, pos): + it = self.saved.itemAt(pos) + if not it or it.data(Qt.ItemDataRole.UserRole) is None: + return + pid = it.data(Qt.ItemDataRole.UserRole) + pl = self._open_pl(pid) + m = QMenu(self) + m.addAction(icon("playlist_play"), "Show" if pl else "Reopen", lambda: self.open_saved.emit(pid)) + + def remove(): + if pl is not None: + pl.favorite = False + self._mgr().save_all() + self.window().area._refresh_tabs() + else: + L.library.delete_playlist(pid) + self.refresh() + m.addAction(icon("delete"), "Remove from saved" if pl else "Delete", remove) + m.exec(self.saved.viewport().mapToGlobal(pos)) + + +# ---------------------------------------------------------------------- radio +class RadioPanel(QWidget): + play_stream = pyqtSignal(object, str) # Song, mode + + def __init__(self, parent=None): + super().__init__(parent) + lay = QVBoxLayout(self) + lay.setContentsMargins(8, 8, 8, 4) + row = QHBoxLayout() + add = QPushButton(icon("add", "onSecondaryContainer"), " Add station") + add.clicked.connect(self._add) + row.addWidget(add) + row.addStretch(1) + lay.addLayout(row) + self.list = QListWidget() + self.list.setIconSize(QSize(22, 22)) + self.list.itemDoubleClicked.connect(lambda it: self.play_stream.emit(self._song(it), "play")) + self.list.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) + self.list.customContextMenuRequested.connect(self._menu) + lay.addWidget(self.list, 1) + self.refresh() + + def refresh(self): + self.list.clear() + for r in L.library.radios(): + it = QListWidgetItem(icon("radio", "primary"), r["name"]) + it.setData(Qt.ItemDataRole.UserRole, (r["id"], r["name"], r["url"])) + it.setToolTip(r["url"]) + self.list.addItem(it) + + def _song(self, it): + _, name, url = it.data(Qt.ItemDataRole.UserRole) + return Song(url=url, title=name, filetype="Stream") + + def _add(self): + url, ok = QInputDialog.getText(self, "Add radio station", "Stream URL (http/https, .pls/.m3u also OK):") + if not ok or not url.strip(): + return + name, ok = QInputDialog.getText(self, "Add radio station", "Name:", text=url.split("/")[2] if "//" in url else url) + if ok: + L.library.add_radio(name.strip() or url, url.strip()) + self.refresh() + + def _menu(self, pos): + it = self.list.itemAt(pos) + if not it: + return + rid = it.data(Qt.ItemDataRole.UserRole)[0] + m = QMenu(self) + m.addAction(icon("play_arrow"), "Play", lambda: self.play_stream.emit(self._song(it), "play")) + m.addAction(icon("playlist_add"), "Add to playlist", lambda: self.play_stream.emit(self._song(it), "append")) + m.addSeparator() + m.addAction(icon("delete"), "Remove", lambda: (L.library.remove_radio(rid), self.refresh())) + m.exec(self.list.viewport().mapToGlobal(pos)) + + +# ---------------------------------------------------------------------- CD +class CDPanel(QWidget): + add_songs = pyqtSignal(list, str) + rip = pyqtSignal(list, object) + + def __init__(self, parent=None): + super().__init__(parent) + self.toc = None + self.releases = [] + self.songs: list[Song] = [] + self.cover: bytes | None = None + lay = QVBoxLayout(self) + lay.setContentsMargins(8, 8, 8, 4) + row = QHBoxLayout() + self.drive = QComboBox() + self.refresh_btn = QToolButton() + self.refresh_btn.setIcon(icon("refresh")) + self.refresh_btn.setToolTip("Read disc") + self.eject_btn = QToolButton() + self.eject_btn.setIcon(icon("eject")) + self.eject_btn.setToolTip("Eject") + row.addWidget(self.drive, 1) + row.addWidget(self.refresh_btn) + row.addWidget(self.eject_btn) + lay.addLayout(row) + self.release = QComboBox() + self.release.hide() + self.release.currentIndexChanged.connect(self._release_changed) + lay.addWidget(self.release) + self.info = QLabel("Insert an audio CD and press refresh.") + self.info.setWordWrap(True) + self.info.setObjectName("muted") + lay.addWidget(self.info) + self.list = QListWidget() + self.list.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection) + self.list.itemDoubleClicked.connect(lambda it: self.add_songs.emit([self.songs[self.list.row(it)]], "play")) + lay.addWidget(self.list, 1) + brow = QHBoxLayout() + self.play_btn = QPushButton(icon("play_arrow", "onSecondaryContainer"), " Play disc") + self.rip_btn = QPushButton(icon("download", "onPrimary"), " Rip…") + self.rip_btn.setProperty("primary", True) + self.play_btn.clicked.connect(lambda: self.songs and self.add_songs.emit(self.songs, "new")) + self.rip_btn.clicked.connect(self._rip) + brow.addWidget(self.play_btn) + brow.addWidget(self.rip_btn) + lay.addLayout(brow) + for b in (self.play_btn, self.rip_btn): + b.setEnabled(False) + self.refresh_btn.clicked.connect(self.read_disc) + self.eject_btn.clicked.connect(lambda: self.drive.currentText() and CD.eject(self.drive.currentText())) + self.populate_drives() + + def populate_drives(self): + self.drive.clear() + drives = CD.list_drives() + pref = settings.get("cd/device") + for d in drives: + self.drive.addItem(icon("album"), d) + if pref in drives: + self.drive.setCurrentText(pref) + if not drives: + self.info.setText("No optical drive detected.") + + def read_disc(self): + dev = self.drive.currentText() + if not dev: + return + settings.set("cd/device", dev) + self.info.setText("Reading disc…") + self.list.clear() + + def work(): + toc = CD.read_toc(dev) + rels = CD.musicbrainz_lookup(toc) + cover = None + if rels and rels[0].get("mb_albumid"): + try: + from .. import online + cover = online.download(f"https://coverartarchive.org/release/{rels[0]['mb_albumid']}/front-500") + except Exception: # noqa: BLE001 + cover = None + return toc, rels, cover + + def done(res): + self.toc, self.releases, self.cover = res + self.release.blockSignals(True) + self.release.clear() + for r in self.releases: + self.release.addItem(f"{r['albumartist']} – {r['album']} ({r['year'] or '?'}) {r['country']}") + self.release.setVisible(len(self.releases) > 1) + self.release.blockSignals(False) + self._release_changed(0) + run_async(work, on_done=done, on_error=lambda e: self.info.setText(e)) + + def _release_changed(self, i): + if not self.toc: + return + rel = self.releases[i] if 0 <= i < len(self.releases) else None + art = "" + if self.cover: + art = T.store_cover(self.cover, T.album_key(rel["albumartist"] if rel else "", rel["album"] if rel else self.toc["discid"])) or "" + self.songs = CD.songs_for(self.toc, rel, art) + self.list.clear() + for s in self.songs: + QListWidgetItem(icon("music_note"), f"{s.track:02d} {s.title} · {fmt_time(s.length)}", self.list) + total = sum(s.length for s in self.songs) + head = f"{rel['albumartist']} — {rel['album']}" if rel else "Unknown disc (not found on MusicBrainz)" + self.info.setText(f"{head}\n{len(self.songs)} tracks · {fmt_time(total)} · disc id {self.toc['discid']}") + for b in (self.play_btn, self.rip_btn): + b.setEnabled(bool(self.songs)) + + def _rip(self): + rows = sorted({self.list.row(i) for i in self.list.selectedItems()}) + songs = [self.songs[r] for r in rows] if rows else list(self.songs) + self.rip.emit(songs, self.cover) + + +class Sidebar(QWidget): + def __init__(self, parent=None): + super().__init__(parent) + lay = QVBoxLayout(self) + lay.setContentsMargins(4, 0, 0, 0) + lay.setSpacing(0) + self.nav = NavTabs([("library_music", "Library"), ("folder", "Files"), ("queue_music", "Lists"), + ("radio", "Radio"), ("album", "CD")]) + lay.addWidget(self.nav) + self.stack = QStackedWidget() + self.library = LibraryPanel() + self.files = FilesPanel() + self.playlists = PlaylistsPanel() + self.radio = RadioPanel() + self.cd = CDPanel() + for w in (self.library, self.files, self.playlists, self.radio, self.cd): + self.stack.addWidget(w) + lay.addWidget(self.stack, 1) + self.nav.changed.connect(self._changed) + self.setMinimumWidth(240) + + def _changed(self, i): + self.stack.setCurrentIndex(i) + settings.set("ui/sidebar_tab", i) + if i == 2: + self.playlists.refresh() + if i == 4 and not self.cd.toc and self.cd.drive.count(): + self.cd.read_disc() + + +def confirm(parent, title, text) -> bool: + return QMessageBox.question(parent, title, text) == QMessageBox.StandardButton.Yes diff --git a/mulberry/winmedia.py b/mulberry/winmedia.py new file mode 100644 index 0000000..03cf82e --- /dev/null +++ b/mulberry/winmedia.py @@ -0,0 +1,63 @@ +"""Windows: global media keys (play/pause, next, previous, stop) via +RegisterHotKey, so the keyboard media keys work even when Mulberry is not +focused. Linux uses MPRIS instead (see mpris.py).""" +from __future__ import annotations + +import ctypes +import ctypes.wintypes + +from PyQt6.QtCore import QAbstractNativeEventFilter, QCoreApplication + +WM_HOTKEY = 0x0312 +VK_MEDIA_NEXT_TRACK = 0xB0 +VK_MEDIA_PREV_TRACK = 0xB1 +VK_MEDIA_STOP = 0xB2 +VK_MEDIA_PLAY_PAUSE = 0xB3 + + +class _Filter(QAbstractNativeEventFilter): + def __init__(self, handlers): + super().__init__() + self.handlers = handlers + + def nativeEventFilter(self, event_type, message): + try: + if event_type in (b"windows_generic_MSG", "windows_generic_MSG"): + msg = ctypes.wintypes.MSG.from_address(int(message)) + if msg.message == WM_HOTKEY: + fn = self.handlers.get(int(msg.wParam)) + if fn: + fn() + return True, 0 + except Exception: # noqa: BLE001 + pass + return False, 0 + + +class WindowsMediaKeys: + def __init__(self, player): + self.ok = False + self.ids = [] + try: + user32 = ctypes.windll.user32 + except AttributeError: + return + handlers = {} + for i, (vk, fn) in enumerate(((VK_MEDIA_PLAY_PAUSE, player.play_pause), (VK_MEDIA_NEXT_TRACK, player.next), + (VK_MEDIA_PREV_TRACK, player.prev), (VK_MEDIA_STOP, player.stop)), start=0xB100): + # hwnd NULL -> WM_HOTKEY is posted to this thread's queue, which Qt's + # native event filter sees as a generic MSG + if user32.RegisterHotKey(None, i, 0, vk): + handlers[i] = fn + self.ids.append(i) + if handlers: + self.filter = _Filter(handlers) + QCoreApplication.instance().installNativeEventFilter(self.filter) + self.ok = True + + def close(self): + try: + for i in self.ids: + ctypes.windll.user32.UnregisterHotKey(None, i) + except Exception: # noqa: BLE001 + pass diff --git a/packaging/launcher.py b/packaging/launcher.py new file mode 100644 index 0000000..ad980df --- /dev/null +++ b/packaging/launcher.py @@ -0,0 +1,7 @@ +"""PyInstaller entry point.""" +import sys + +from mulberry.__main__ import main + +if __name__ == "__main__": + sys.exit(main()) diff --git a/packaging/linux/AppRun b/packaging/linux/AppRun new file mode 100755 index 0000000..bba8ef4 --- /dev/null +++ b/packaging/linux/AppRun @@ -0,0 +1,3 @@ +#!/bin/sh +HERE="$(dirname "$(readlink -f "$0")")" +exec "$HERE/usr/lib/mulberry/mulberry" "$@" diff --git a/packaging/make_icons.py b/packaging/make_icons.py new file mode 100644 index 0000000..2732a32 --- /dev/null +++ b/packaging/make_icons.py @@ -0,0 +1,52 @@ +"""Render mulberry/assets/mulberry.svg into PNG sizes and a Windows .ico.""" +import sys +from pathlib import Path + +from PyQt6.QtCore import QBuffer, QByteArray, QIODevice +from PyQt6.QtGui import QGuiApplication, QImage, QPainter +from PyQt6.QtSvg import QSvgRenderer + +ROOT = Path(__file__).resolve().parent.parent +OUT = ROOT / "packaging" / "build-icons" + + +def render(r, size): + img = QImage(size, size, QImage.Format.Format_ARGB32) + img.fill(0) + p = QPainter(img) + r.render(p) + p.end() + return img + + +def main(): + QGuiApplication(sys.argv[:1] + ["-platform", "offscreen"]) + OUT.mkdir(parents=True, exist_ok=True) + r = QSvgRenderer(str(ROOT / "mulberry" / "assets" / "mulberry.svg")) + pngs = {} + for s in (16, 24, 32, 48, 64, 128, 256, 512): + img = render(r, s) + img.save(str(OUT / f"mulberry-{s}.png")) + ba = QByteArray() + buf = QBuffer(ba) + buf.open(QIODevice.OpenModeFlag.WriteOnly) + img.save(buf, "PNG") + pngs[s] = bytes(ba) + # ICO with embedded PNGs (Vista+ format) + sizes = [16, 24, 32, 48, 64, 128, 256] + header = (0).to_bytes(2, "little") + (1).to_bytes(2, "little") + len(sizes).to_bytes(2, "little") + entries, data = b"", b"" + offset = 6 + 16 * len(sizes) + for s in sizes: + d = pngs[s] + dim = 0 if s >= 256 else s + entries += bytes([dim, dim, 0, 0]) + (1).to_bytes(2, "little") + (32).to_bytes(2, "little") \ + + len(d).to_bytes(4, "little") + offset.to_bytes(4, "little") + data += d + offset += len(d) + (OUT / "mulberry.ico").write_bytes(header + entries + data) + print("icons written to", OUT) + + +if __name__ == "__main__": + main() diff --git a/packaging/mulberry.spec b/packaging/mulberry.spec new file mode 100644 index 0000000..19290ff --- /dev/null +++ b/packaging/mulberry.spec @@ -0,0 +1,78 @@ +# PyInstaller spec — build with: pyinstaller packaging/mulberry.spec --noconfirm +import os +import re +import sys +from pathlib import Path + +ROOT = Path(SPECPATH).resolve().parent +IS_WIN = sys.platform == "win32" +icon_dir = ROOT / "packaging" / "build-icons" + +datas = [(str(ROOT / "mulberry" / "assets"), "mulberry/assets")] +binaries = [] +# libmpv for Windows (CI downloads it into packaging/windows/mpv/) +mpv_dir = ROOT / "packaging" / "windows" / "mpv" +if IS_WIN and mpv_dir.is_dir(): + for f in mpv_dir.glob("*.dll"): + binaries.append((str(f), ".")) + +hidden = ["mulberry.winmedia", "mulberry.mpris", "mutagen", "numpy", "mpv", + "PyQt6.QtMultimedia", "PyQt6.QtSvg", "PyQt6.QtNetwork"] +if not IS_WIN: + hidden.append("PyQt6.QtDBus") + +excludes = ["PyQt6.QtWebEngineCore", "PyQt6.QtWebEngineWidgets", "PyQt6.QtQuick", "PyQt6.QtQml", + "PyQt6.Qt3DCore", "PyQt6.QtCharts", "PyQt6.QtDataVisualization", "PyQt6.QtBluetooth", + "PyQt6.QtPdf", "PyQt6.QtSql", "PyQt6.QtTest", "PyQt6.QtDesigner", "tkinter", + "matplotlib", "PIL", "scipy"] + +a = Analysis( + [str(ROOT / "packaging" / "launcher.py")], + pathex=[str(ROOT)], + binaries=binaries, + datas=datas, + hiddenimports=hidden, + excludes=excludes, + noarchive=False, +) +# On Linux, libmpv (and its ~100 codec deps) must come from the system, not +# the bundle: drop it and everything only it pulls in. +if not IS_WIN: + import re + import subprocess + keep_basic = re.compile(r"^(libz|libssl|libcrypto|libffi|libexpat|liblzma|libbz2|libstdc|libgcc|" + r"libpython|libuuid|libreadline|libncurses|libtinfo|libsqlite|libmpdec)") + mpv_deps = set() + try: + import ctypes.util + lib = ctypes.util.find_library("mpv") + if lib: + out = subprocess.run(["bash", "-c", f"ldd $(ldconfig -p | grep -m1 '{lib}' | awk '{{print $NF}}')"], + capture_output=True, text=True).stdout + mpv_deps = {ln.split()[0] for ln in out.splitlines() if "=>" in ln} + except Exception: + pass + + def unwanted(name): + base = os.path.basename(name) + if base.startswith("libmpv"): + return True + return base in mpv_deps and not keep_basic.match(base) + a.binaries = [b for b in a.binaries if not (unwanted(b[0]) and "PyQt6" not in b[1] and "numpy" not in b[1])] + +# Qt modules Mulberry never uses (pulled in by plugins) — keeps the bundle lean +_drop = re.compile(r"(Qt6(Quick|Qml|Pdf|VirtualKeyboard|ShaderTools|3D|WebEngine|Designer)|libqgtk3|qpdf|" + r"qmltooling|libgtk-3|libgdk-3)", re.I) if True else None +a.binaries = [b for b in a.binaries if not _drop.search(b[0])] +a.datas = [d for d in a.datas if not _drop.search(d[0])] + +pyz = PYZ(a.pure) +exe = EXE( + pyz, a.scripts, [], + exclude_binaries=True, + name="Mulberry" if IS_WIN else "mulberry", + console=False, + icon=str(icon_dir / "mulberry.ico") if (IS_WIN and (icon_dir / "mulberry.ico").exists()) else None, + version=str(ROOT / "packaging" / "windows" / "version.txt") if IS_WIN else None, +) +coll = COLLECT(exe, a.binaries, a.datas, strip=False, upx=False, name="Mulberry") diff --git a/packaging/windows/mulberry.iss b/packaging/windows/mulberry.iss new file mode 100644 index 0000000..dab5832 --- /dev/null +++ b/packaging/windows/mulberry.iss @@ -0,0 +1,62 @@ +; Inno Setup script — built by CI: iscc /DAppVersion=1.1.0 packaging\windows\mulberry.iss +#ifndef AppVersion + #define AppVersion "1.1.0" +#endif + +[Setup] +AppId={{6B8E2F1A-4C3D-4E7B-9A51-2D9F0C8B7A11} +AppName=Mulberry +AppVersion={#AppVersion} +AppVerName=Mulberry {#AppVersion} +AppPublisher=Mulberry +DefaultDirName={autopf}\Mulberry +DefaultGroupName=Mulberry +UninstallDisplayIcon={app}\Mulberry.exe +OutputDir=..\..\dist +OutputBaseFilename=Mulberry-{#AppVersion}-Windows-Setup +SetupIconFile=..\build-icons\mulberry.ico +Compression=lzma2/max +SolidCompression=yes +WizardStyle=modern +ArchitecturesAllowed=x64compatible +ArchitecturesInstallIn64BitMode=x64compatible +PrivilegesRequiredOverridesAllowed=dialog +ChangesAssociations=yes + +[Tasks] +Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked +Name: "openwith"; Description: "Show Mulberry in ""Open with"" for audio files and playlists"; GroupDescription: "Integration:" + +[Files] +Source: "..\..\build\dist\Mulberry\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs + +[Icons] +Name: "{group}\Mulberry"; Filename: "{app}\Mulberry.exe" +Name: "{group}\Uninstall Mulberry"; Filename: "{uninstallexe}" +Name: "{autodesktop}\Mulberry"; Filename: "{app}\Mulberry.exe"; Tasks: desktopicon + +[Registry] +Root: HKA; Subkey: "Software\Classes\Mulberry.Audio"; ValueType: string; ValueData: "Audio file (Mulberry)"; Flags: uninsdeletekey; Tasks: openwith +Root: HKA; Subkey: "Software\Classes\Mulberry.Audio\DefaultIcon"; ValueType: string; ValueData: "{app}\Mulberry.exe,0"; Tasks: openwith +Root: HKA; Subkey: "Software\Classes\Mulberry.Audio\shell\open\command"; ValueType: string; ValueData: """{app}\Mulberry.exe"" ""%1"""; Tasks: openwith +Root: HKA; Subkey: "Software\Classes\Applications\Mulberry.exe\shell\open\command"; ValueType: string; ValueData: """{app}\Mulberry.exe"" ""%1"""; Flags: uninsdeletekey; Tasks: openwith +Root: HKA; Subkey: "Software\Classes\.mp3\OpenWithProgids"; ValueType: string; ValueName: "Mulberry.Audio"; ValueData: ""; Flags: uninsdeletevalue; Tasks: openwith +Root: HKA; Subkey: "Software\Classes\.flac\OpenWithProgids"; ValueType: string; ValueName: "Mulberry.Audio"; ValueData: ""; Flags: uninsdeletevalue; Tasks: openwith +Root: HKA; Subkey: "Software\Classes\.ogg\OpenWithProgids"; ValueType: string; ValueName: "Mulberry.Audio"; ValueData: ""; Flags: uninsdeletevalue; Tasks: openwith +Root: HKA; Subkey: "Software\Classes\.opus\OpenWithProgids"; ValueType: string; ValueName: "Mulberry.Audio"; ValueData: ""; Flags: uninsdeletevalue; Tasks: openwith +Root: HKA; Subkey: "Software\Classes\.m4a\OpenWithProgids"; ValueType: string; ValueName: "Mulberry.Audio"; ValueData: ""; Flags: uninsdeletevalue; Tasks: openwith +Root: HKA; Subkey: "Software\Classes\.aac\OpenWithProgids"; ValueType: string; ValueName: "Mulberry.Audio"; ValueData: ""; Flags: uninsdeletevalue; Tasks: openwith +Root: HKA; Subkey: "Software\Classes\.wav\OpenWithProgids"; ValueType: string; ValueName: "Mulberry.Audio"; ValueData: ""; Flags: uninsdeletevalue; Tasks: openwith +Root: HKA; Subkey: "Software\Classes\.wma\OpenWithProgids"; ValueType: string; ValueName: "Mulberry.Audio"; ValueData: ""; Flags: uninsdeletevalue; Tasks: openwith +Root: HKA; Subkey: "Software\Classes\.ape\OpenWithProgids"; ValueType: string; ValueName: "Mulberry.Audio"; ValueData: ""; Flags: uninsdeletevalue; Tasks: openwith +Root: HKA; Subkey: "Software\Classes\.wv\OpenWithProgids"; ValueType: string; ValueName: "Mulberry.Audio"; ValueData: ""; Flags: uninsdeletevalue; Tasks: openwith +Root: HKA; Subkey: "Software\Classes\.aiff\OpenWithProgids"; ValueType: string; ValueName: "Mulberry.Audio"; ValueData: ""; Flags: uninsdeletevalue; Tasks: openwith +Root: HKA; Subkey: "Software\Classes\.dsf\OpenWithProgids"; ValueType: string; ValueName: "Mulberry.Audio"; ValueData: ""; Flags: uninsdeletevalue; Tasks: openwith +Root: HKA; Subkey: "Software\Classes\.m3u\OpenWithProgids"; ValueType: string; ValueName: "Mulberry.Audio"; ValueData: ""; Flags: uninsdeletevalue; Tasks: openwith +Root: HKA; Subkey: "Software\Classes\.m3u8\OpenWithProgids"; ValueType: string; ValueName: "Mulberry.Audio"; ValueData: ""; Flags: uninsdeletevalue; Tasks: openwith +Root: HKA; Subkey: "Software\Classes\.pls\OpenWithProgids"; ValueType: string; ValueName: "Mulberry.Audio"; ValueData: ""; Flags: uninsdeletevalue; Tasks: openwith +Root: HKA; Subkey: "Software\Classes\.xspf\OpenWithProgids"; ValueType: string; ValueName: "Mulberry.Audio"; ValueData: ""; Flags: uninsdeletevalue; Tasks: openwith +Root: HKA; Subkey: "Software\Classes\.cue\OpenWithProgids"; ValueType: string; ValueName: "Mulberry.Audio"; ValueData: ""; Flags: uninsdeletevalue; Tasks: openwith + +[Run] +Filename: "{app}\Mulberry.exe"; Description: "{cm:LaunchProgram,Mulberry}"; Flags: nowait postinstall skipifsilent diff --git a/packaging/windows/version.txt b/packaging/windows/version.txt new file mode 100644 index 0000000..88558a8 --- /dev/null +++ b/packaging/windows/version.txt @@ -0,0 +1,15 @@ +VSVersionInfo( + ffi=FixedFileInfo(filevers=(1, 1, 0, 0), prodvers=(1, 1, 0, 0), mask=0x3f, flags=0x0, OS=0x40004, + fileType=0x1, subtype=0x0, date=(0, 0)), + kids=[ + StringFileInfo([StringTable('040904B0', [ + StringStruct('CompanyName', 'Mulberry'), + StringStruct('FileDescription', 'Mulberry Music Player'), + StringStruct('FileVersion', '1.1.0'), + StringStruct('InternalName', 'Mulberry'), + StringStruct('OriginalFilename', 'Mulberry.exe'), + StringStruct('ProductName', 'Mulberry'), + StringStruct('ProductVersion', '1.1.0')])]), + VarFileInfo([VarStruct('Translation', [1033, 1200])]) + ] +) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..61b535e --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +PyQt6>=6.6 +mutagen>=1.47 +numpy>=1.24 +python-mpv>=1.0 diff --git a/run.bat b/run.bat new file mode 100644 index 0000000..c6c940a --- /dev/null +++ b/run.bat @@ -0,0 +1,5 @@ +@echo off +rem Run Mulberry from source on Windows (needs Python 3.10+): +rem py -m pip install -r requirements.txt +cd /d "%~dp0" +py -m mulberry %* diff --git a/run.sh b/run.sh new file mode 100755 index 0000000..1c07ea4 --- /dev/null +++ b/run.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Run straight from the source folder (needs: pip install -r requirements.txt) +cd "$(dirname "${BASH_SOURCE[0]}")" && exec python3 -m mulberry "$@"