Mulberry/mulberry/__main__.py
Claude a0b83cd4e3
Mulberry 1.2.1: CD fixes, web links, lyrics priority, portable playlists
- Fix crash after CD ripping (running QThread was destroyed)
- Audio CDs always use mpv (bundled on Windows) even when Qt is the main engine
  — fixes 'several tracks failed to play' on Windows
- YouTube/SoundCloud/Bandcamp links resolved with bundled yt-dlp
- Lyrics: Auto prefers synced from any source (LRCLIB > NetEase > embedded >
  local); explicit choices no longer fall back; NetEase uses cloudsearch
  (search/get/web is encrypted outside China)
- Playlist export uses absolute paths by default; import remaps paths from
  other machines/OSes via the library
- HTTPS: certificate fallback (system bundles, certifi) for packaged builds;
  cover search shows real errors, more fallbacks, Last.fm covers
- MusicBrainz: retry without album, cleaner album artist, async genre
- CI self-tests require bundled libmpv (Windows), yt-dlp and TLS certs

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01J7imThHV9BMkG24GaxPDeq
2026-10-10 00:45:03 -05:00

131 lines
4.8 KiB
Python

"""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)
selftest = os.environ.get("MULBERRY_SELFTEST")
if selftest:
# CI smoke test: start, render, write a screenshot + report, quit
from PyQt6.QtCore import QTimer
def _report():
from .player import Player, mpv_available
from . import theme as Th
try:
win.resize(1400, 860)
win.grab().save(selftest + ".png")
with open(selftest + ".txt", "w", encoding="utf-8") as fh:
sp = win.spectrum
fh.write(f"engine={Player.instance.backend.name}\nmpv_available={mpv_available()}\n"
f"state={Player.instance.state}\nposition={Player.instance.pos:.2f}\n"
f"visualizer_peak={float(sp.peaks.max()):.3f}\nvisualizer_decoded_s={sp._tlen / 22050:.1f}\n"
f"dark={Th.theme.dark}\nprimary={Th.theme['primary'].name()}\n"
f"font={Th.theme.font_family}\nmedia_keys={getattr(win.media_keys, 'ok', None)}\n"
f"mpris={win.mpris.ok}\n")
try:
import yt_dlp # noqa: F401
yt = True
except Exception: # noqa: BLE001
yt = False
from .online import ssl_context
fh.write(f"ytdlp={yt}\nssl_ca={ssl_context().cert_store_stats().get('x509_ca', 0)}\n")
finally:
win.quit_app()
play = os.environ.get("MULBERRY_SELFTEST_PLAY")
if play:
QTimer.singleShot(1500, lambda: win.add_paths([play], "play"))
QTimer.singleShot(int(os.environ.get("MULBERRY_SELFTEST_DELAY", "8000")), _report)
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())