v0.97.0: macOS port (Round 129): OS-aware paths, config and cookies; Mac now-playing, packaging (PyInstaller .app, dmg build, signing notes, CI workflow) and docs

This commit is contained in:
2026-11-17 22:41:48 -08:00
parent b78b6c5275
commit f21c31940f
66 changed files with 6047 additions and 164 deletions
+1 -1
View File
@@ -1,3 +1,3 @@
"""LinTunes — iTunes-style music library manager and player for Linux."""
__version__ = "0.96.1"
__version__ = "0.97.0"
+71 -27
View File
@@ -26,15 +26,21 @@ import tempfile
import urllib.request
from pathlib import Path
from lintunes import paths
VERSION = "0.5.4"
_RELEASE = ("https://github.com/music-assistant/airplay-cli/releases/download/"
f"v{VERSION}/")
# From the release's SHA256SUMS.
# From the release's SHA256SUMS. Linux keys are the bare machine; the Mac
# builds (same release, same tag) are keyed by their asset suffix.
_SHA256 = {
"x86_64": "1ac56a15fb548f07a1dae94be16d4bea308420a0ec0cd04238023e44345fc1c9",
"aarch64": "1ce9160a8a9abb1b2263dfbf5ed59551dd1205b2336a024e9e33c903c201a310",
"macos-arm64": "5b99e3bf76d20cb31a2f6946e0c9d8bc12e0845d7d66a0ec22a49b5ebbac14b4",
"macos-x86_64": "09fd5925787db0cea530d380656b06fa6da89f0da11ef86e1cba1139b3c828fd",
}
_ARCH_ALIASES = {"amd64": "x86_64", "arm64": "aarch64"}
_MAC_ARCH_ALIASES = {"aarch64": "arm64", "amd64": "x86_64"}
DOWNLOAD_TIMEOUT_S = 60
@@ -44,18 +50,28 @@ class CliUnavailable(RuntimeError):
def _arch() -> str | None:
"""The ``_SHA256`` key for this computer, or None."""
machine = platform.machine().lower()
if paths.IS_MAC:
# Under Rosetta this reads x86_64, and the x86_64 build runs there.
key = "macos-" + _MAC_ARCH_ALIASES.get(machine, machine)
return key if key in _SHA256 else None
if platform.system() != "Linux":
return None
machine = platform.machine().lower()
machine = _ARCH_ALIASES.get(machine, machine)
return machine if machine in _SHA256 else None
def _asset(arch: str) -> str:
"""The release asset's file name for an ``_arch`` key."""
if arch.startswith("macos-"):
return f"cliairplay-{arch}"
return f"cliairplay-linux-{arch}"
def binary_dir() -> Path:
"""Machine-local: a binary for this CPU, never the synced data dir."""
base = os.environ.get("XDG_DATA_HOME") or os.path.expanduser(
"~/.local/share")
return Path(base) / "lintunes" / "bin"
return paths.data_dir() / "bin"
def binary_path() -> Path | None:
@@ -81,6 +97,37 @@ def _sha256(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def download_verified(url: str, sha256: str, path: Path, fetch=None,
what: str = "the helper", error=CliUnavailable,
unpack=None) -> Path:
"""Download ``url`` to ``path`` (mode 755), refusing it unless its
SHA-256 is ``sha256``. Nothing lands at ``path`` unless it matched.
``unpack(data) -> bytes`` (after the check) picks the binary out of an
archive. Raises ``error``. Shared by every pinned runtime download
(cliairplay here, ``uv`` in ``dj/venv_tool.py``)."""
fetch = fetch or _fetch
try:
data = fetch(url)
except Exception as e: # noqa: BLE001 — reported, not raised raw
raise error(f"couldn't download {what} ({e})")
if _sha256(data) != sha256:
raise error(f"the downloaded {what} failed its checksum")
if unpack is not None:
data = unpack(data)
path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix="." + path.name + "-")
try:
with os.fdopen(fd, "wb") as out:
out.write(data)
os.chmod(tmp, 0o755)
os.replace(tmp, path)
except BaseException:
with contextlib.suppress(OSError):
os.unlink(tmp)
raise
return path
def ensure_binary(fetch=None) -> Path:
"""The helper's path, downloading and verifying it first if needed.
@@ -94,34 +141,31 @@ def ensure_binary(fetch=None) -> Path:
if arch is None:
raise CliUnavailable(
f"no AirPlay helper for {platform.system()} {platform.machine()}")
fetch = fetch or _fetch
name = f"cliairplay-linux-{arch}"
try:
data = fetch(_RELEASE + name)
except Exception as e: # noqa: BLE001 — reported, not raised raw
raise CliUnavailable(f"couldn't download the AirPlay helper ({e})")
if _sha256(data) != _SHA256[arch]:
raise CliUnavailable("the downloaded AirPlay helper failed its checksum")
path = binary_path()
path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".cliairplay-")
try:
with os.fdopen(fd, "wb") as out:
out.write(data)
os.chmod(tmp, 0o755)
os.replace(tmp, path)
except BaseException:
with contextlib.suppress(OSError):
os.unlink(tmp)
raise
return path
return download_verified(_RELEASE + _asset(arch), _SHA256[arch],
binary_path(), fetch, "AirPlay helper")
def _fetch(url: str) -> bytes:
with urllib.request.urlopen(url, timeout=DOWNLOAD_TIMEOUT_S) as response:
with urllib.request.urlopen(url, timeout=DOWNLOAD_TIMEOUT_S,
context=https_context()) as response:
return response.read()
def https_context():
"""None (urllib's default) on Linux. On a Mac, certifi's roots: the
Python inside a built LinTunes.app was compiled with an OpenSSL whose
certificate folder doesn't exist on the user's Mac, so the default
context trusts nothing and every HTTPS download fails."""
if not paths.IS_MAC:
return None
import ssl
try:
import certifi
return ssl.create_default_context(cafile=certifi.where())
except Exception: # noqa: BLE001 — fall back to the system's default
return ssl.create_default_context()
# ---- the command line ----
# RAOP TXT keys the binary takes as their own flags (Music Assistant's set).
+2 -3
View File
@@ -19,7 +19,7 @@ from pathlib import Path
from PyQt6.QtCore import QBuffer, QByteArray, QIODevice, Qt
from PyQt6.QtGui import QImage
from .. import tagging
from .. import paths, tagging
from .layout import album_key
# The panel is 480 px wide, so a cover never needs to be bigger than that;
@@ -29,8 +29,7 @@ JPEG_QUALITY = 85
def _cache_dir() -> Path:
base = os.environ.get("XDG_CACHE_HOME", str(Path.home() / ".cache"))
return Path(base) / "lintunes" / "andtunes-art"
return paths.cache_dir() / "andtunes-art"
def render_jpeg(data: bytes) -> bytes | None:
+2 -3
View File
@@ -28,7 +28,7 @@ from pathlib import Path
from PyQt6.QtCore import QObject, pyqtSignal
from .. import __version__
from .. import __version__, paths
from ..device_sync import CHUNK, build_m3u, track_display
from ..export import web_support
from . import art as art_mod
@@ -129,8 +129,7 @@ def flac_cache(track) -> Path:
Keyed by track id, so a rename doesn't orphan it; stale once the source
is newer (a re-tag rewrites the file), exactly like the art cache.
"""
base = os.environ.get("XDG_CACHE_HOME", str(Path.home() / ".cache"))
return Path(base) / "lintunes" / "andtunes-flac" / f"{track.track_id}.flac"
return paths.cache_dir() / "andtunes-flac" / f"{track.track_id}.flac"
def _fresh(cache: Path, src: Path) -> bool:
+6 -1
View File
@@ -16,6 +16,7 @@ from __future__ import annotations
import socket
from lintunes import paths
from lintunes.config import load_config, save_config
from lintunes.storage.play_journal import machine_id
@@ -29,9 +30,13 @@ UNCLAIMED = "unclaimed"
def hostname() -> str:
try:
return socket.gethostname() or "this computer"
name = socket.gethostname() or "this computer"
except OSError:
return "this computer"
# A Mac's hostname is its Bonjour name, "Travs-MacBook.local".
if paths.IS_MAC and name.lower().endswith(".local") and len(name) > 6:
name = name[:-6]
return name
def host_status(prefs) -> tuple[str, str]:
+24 -1
View File
@@ -14,6 +14,8 @@ from __future__ import annotations
import json
from pathlib import Path
from lintunes import paths
FORMAT_VERSION = 1
INFO_FILE = "cassette.json"
AVATAR_FILE = "avatar.png"
@@ -23,6 +25,17 @@ STIGNORE = ".stignore"
# own .syncthing.*.tmp already.)
STIGNORE_TEXT = "// written by LinTunes\n*.tmp\n*.part\n"
# Finder drops .DS_Store into any folder it shows (and ._* AppleDouble files
# on non-APFS disks). In a send-only folder they would travel to the friend;
# in a receive-only one they would read as "local additions". (?d) lets
# Syncthing delete them when the folder itself has to go.
MAC_IGNORES = "(?d).DS_Store\n(?d)._*\n"
def stignore_text() -> str:
"""The out folder's .stignore. On Linux exactly STIGNORE_TEXT."""
return STIGNORE_TEXT + (MAC_IGNORES if paths.IS_MAC else "")
def write_bytes_if_changed(path: Path, data: bytes) -> bool:
"""Atomically write ``data`` unless ``path`` already holds exactly it.
@@ -54,7 +67,17 @@ def read_json(path: Path, default=None):
def prepare_out_dir(out: Path):
out.mkdir(parents=True, exist_ok=True)
write_bytes_if_changed(out / STIGNORE, STIGNORE_TEXT.encode())
write_bytes_if_changed(out / STIGNORE, stignore_text().encode())
def prepare_in_dir(folder: Path):
"""Make a receive-only folder. On a Mac it also gets a .stignore for
Finder's litter; on Linux nothing is written but the directory."""
folder.mkdir(parents=True, exist_ok=True)
if paths.IS_MAC:
write_bytes_if_changed(folder / STIGNORE,
("// written by LinTunes\n"
+ MAC_IGNORES).encode())
def publish_intro(out: Path, display_name: str, avatar_source: Path | None):
+12 -4
View File
@@ -24,12 +24,14 @@ from __future__ import annotations
import logging
import shutil
import threading
import unicodedata
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from pathlib import Path
from PyQt6.QtCore import QObject, pyqtSignal
from lintunes import paths
from lintunes.config import load_config
from lintunes.cassette import invite as inv
from lintunes.cassette import publish
@@ -315,6 +317,10 @@ class CassetteService(QObject):
try:
client = self.client()
relative = path.relative_to(in_dir(self.root, token)).as_posix()
if paths.IS_MAC:
# Syncthing names files in NFC; a name listed off APFS can be
# NFD (whatever wrote it), and the lookup would miss.
relative = unicodedata.normalize("NFC", relative)
info = client.file_info(friend.in_folder, relative)
except (st.SyncthingError, ValueError):
return True
@@ -480,8 +486,10 @@ class CassetteService(QObject):
"Syncthing's config.")
else:
status = Status(SYNCTHING_DOWN, "Syncthing isn't running",
"Start Syncthing, then press Retry in Sync "
"Settings ▸ General.")
st.not_running_hint(
"press Retry in Sync Settings ▸ General")
or "Start Syncthing, then press Retry in Sync "
"Settings ▸ General.")
with self._lock:
changed = self._api.code != status.code
self._api = status
@@ -541,7 +549,7 @@ class CassetteService(QObject):
and friend.device_id == device_id
and client.folder(folder_id) is None):
in_path = in_dir(self.root, token)
in_path.mkdir(parents=True, exist_ok=True)
publish.prepare_in_dir(in_path)
client.add_folder(
folder_id, f"LinTunes: from {friend.name}", in_path,
"receiveonly", [device_id],
@@ -561,7 +569,7 @@ class CassetteService(QObject):
client.share_folder(invite.folder_id, device_id,
step="Sharing your folder with your friend")
in_path = in_dir(self.root, token)
in_path.mkdir(parents=True, exist_ok=True)
publish.prepare_in_dir(in_path)
client.add_folder(inv.invitee_folder(token), "LinTunes: from a friend",
in_path, "receiveonly", [device_id],
step="Accepting your friend's folder")
+6 -7
View File
@@ -1,10 +1,10 @@
"""Cassette's own state: who my friends are, what I share with each, what I've
asked each of them for.
It lives in the machine-local cassette root (``~/.local/share/lintunes/
cassette/state.json``), **not** in the synced data dir: only the host machine
runs Cassette, the friend folders it describes exist only here, and a second
copy riding Syncthing would just be a conflict waiting to happen.
It lives in the machine-local cassette root (``paths.data_dir()/cassette/
state.json``; ``~/.local/share/lintunes/…`` on Linux), **not** in the synced
data dir: only the host machine runs Cassette, the friend folders it
describes exist only here, and a second copy riding Syncthing would just be a conflict waiting to happen.
Plain dataclasses with ``to_dict``/``from_dict``, like ``lintunes/models``;
``save`` is atomic (``json_storage.write_json``).
@@ -13,11 +13,11 @@ from __future__ import annotations
import copy
import getpass
import os
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from lintunes import paths
from lintunes.config import load_config
from lintunes.storage.json_storage import read_json, write_json
@@ -52,8 +52,7 @@ def cassette_root() -> Path:
override = (load_config().get(ROOT_KEY) or "").strip()
if override:
return Path(override).expanduser()
base = os.environ.get("XDG_DATA_HOME", str(Path.home() / ".local/share"))
return Path(base) / "lintunes" / "cassette"
return paths.data_dir() / "cassette"
def default_display_name() -> str:
+22 -1
View File
@@ -20,7 +20,7 @@ from pathlib import Path
import requests
from lintunes import sync_identity
from lintunes import paths, sync_identity
log = logging.getLogger(__name__)
@@ -39,6 +39,27 @@ NO_KEY = "no_key" # we couldn't find a key to send at all
OTHER = "other" # it answered, and said no
# What to tell someone whose Syncthing isn't answering. Linux keeps the
# words it always had (the UI writes its own there); a Mac gets told where
# Syncthing comes from, since nothing on a Mac ships it.
MAC_START_HINT = ("Open the Syncthing app (or run: brew services start "
"syncthing)")
MAC_INSTALL_HINT = ("Don't have Syncthing? Get the Syncthing macOS app from "
"syncthing.net, or install it with Homebrew: brew install "
"--cask syncthing-app (the app) or brew install syncthing "
"(the command-line one).")
def not_running_hint(retry_where: str = "") -> str | None:
"""On a Mac, the next step for "Syncthing isn't running", ending with
``retry_where`` (e.g. "press Retry in Sync Settings ▸ General"). None on
Linux, where each caller keeps its own text."""
if not paths.IS_MAC:
return None
then = f", then {retry_where}." if retry_where else "."
return f"{MAC_START_HINT}{then} {MAC_INSTALL_HINT}"
class SyncthingError(Exception):
"""A step that failed, and what Syncthing (or the socket) said."""
+3 -3
View File
@@ -1,11 +1,11 @@
import json
import os
from pathlib import Path
from lintunes import paths
def config_path() -> Path:
base = os.environ.get("XDG_CONFIG_HOME", str(Path.home() / ".config"))
return Path(base) / "lintunes" / "config.json"
return paths.config_dir() / "config.json"
def load_config() -> dict:
+27 -13
View File
@@ -7,7 +7,7 @@ download button, and a deck can swap between the two splits of a song.
The original ``spleeter`` package needs TensorFlow and Python ≤3.11, so this
runs Spleeter's own weights as ONNX through **sherpa-onnx** (onnxruntime, a
~125 MB venv at ``$XDG_DATA_HOME/lintunes/spleeter``, never a pip dependency
~125 MB venv at ``paths.data_dir()/spleeter``, never a pip dependency
of LinTunes). The fp16 models (35 MB) come from sherpa-onnx's GitHub release
and are refused unless their SHA-256 is the one pinned here, the
``airplay/cli.py`` rule. The release's own checksum.txt is stale for this
@@ -18,7 +18,6 @@ import hashlib
import os
import shutil
import subprocess
import sys
import tarfile
import tempfile
import threading
@@ -27,6 +26,10 @@ from pathlib import Path
from PyQt6.QtCore import QObject, pyqtSignal
from lintunes import paths
from lintunes.airplay import cli
from lintunes.dj import venv_tool
SHERPA_VERSION = "2.0.1"
MODEL_URL = ("https://github.com/k2-fsa/sherpa-onnx/releases/download/"
"source-separation-models/sherpa-onnx-spleeter-2stems-fp16.tar.bz2")
@@ -41,8 +44,7 @@ class Cancelled(Exception):
def venv_dir() -> Path:
base = os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share")
return Path(base) / "lintunes" / "spleeter"
return paths.data_dir() / "spleeter"
def python() -> Path:
@@ -66,7 +68,8 @@ def remove():
def _fetch(url: str) -> bytes:
with urllib.request.urlopen(url, timeout=120) as response:
with urllib.request.urlopen(url, timeout=120,
context=cli.https_context()) as response:
return response.read()
@@ -114,13 +117,19 @@ class InstantSetup(QObject):
def _run(self):
try:
venv = venv_dir()
if venv_tool.uses_uv():
# A Mac (or the built app) has no Python to make a venv
# with; uv brings one (venv_tool's docstring).
self.progress.emit("Downloading a Python for it…")
venv_tool.ensure_uv()
env = venv_tool.run_env()
if not python().is_file():
self.progress.emit("Making its own Python environment…")
venv.parent.mkdir(parents=True, exist_ok=True)
self._call([sys.executable, "-m", "venv", str(venv)])
self._call(venv_tool.create_command(venv), env)
self.progress.emit("Downloading sherpa-onnx…")
self._call([str(python()), "-m", "pip", "install", "--quiet",
f"sherpa-onnx=={SHERPA_VERSION}", "numpy"])
self._call(venv_tool.install_command(
venv, [f"sherpa-onnx=={SHERPA_VERSION}", "numpy"]), env)
self.progress.emit("Downloading the Spleeter models…")
install_models()
except (OSError, subprocess.SubprocessError) as e:
@@ -129,8 +138,9 @@ class InstantSetup(QObject):
self.finished.emit()
@staticmethod
def _call(cmd):
done = subprocess.run(cmd, capture_output=True, text=True, timeout=1800)
def _call(cmd, env=None):
done = subprocess.run(cmd, capture_output=True, text=True, timeout=1800,
env=env)
if done.returncode != 0:
lines = (done.stderr or done.stdout).strip().splitlines()
raise OSError(lines[-1] if lines else f"{cmd[2]} failed")
@@ -142,10 +152,14 @@ def split(path: str, out_dir: Path, progress=None,
``out_dir`` (blocking). Raises OSError, or Cancelled."""
if not available():
raise OSError("instant vocal splitting isn't set up on this computer")
process = subprocess.Popen(
if not RUNNER.is_file(): # a built app that left the helper out
raise OSError(f"LinTunes is missing {RUNNER.name}")
cmd, preexec = venv_tool.niced(
[str(python()), "-I", str(RUNNER), str(model_dir()), str(threads()), path, str(out_dir)],
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True,
preexec_fn=lambda: os.nice(5))
5)
process = subprocess.Popen(
cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True,
env=venv_tool.child_env(), preexec_fn=preexec)
if cancel is not None:
def watch():
while process.poll() is None:
+12 -1
View File
@@ -13,6 +13,7 @@ import numpy as np
from PyQt6.QtCore import QObject, QThread, QTimer, pyqtSignal, pyqtSlot
from PyQt6.QtMultimedia import QAudio, QAudioFormat, QAudioSink, QMediaDevices
from lintunes import paths
from lintunes.dj.audio import CHANNELS, RATE
BUFFER_MS = 100
@@ -20,6 +21,15 @@ TICK_MS = 5
BYTES_PER_FRAME = 2 * CHANNELS
def _converts_any_rate() -> bool:
"""CoreAudio's output unit converts rate and sample format itself, and
Qt's Mac sink goes through it; a device that reports only 48 kHz (or a
Bluetooth headset in call mode) still plays 44.1 kHz stereo there. So on
a Mac an unsupported-looking format is tried anyway. Linux keeps the
check it always had."""
return paths.IS_MAC
class _Pump(QObject):
failed = pyqtSignal(str)
@@ -52,7 +62,8 @@ class _Pump(QObject):
fmt.setChannelCount(CHANNELS)
fmt.setSampleFormat(QAudioFormat.SampleFormat.Int16)
device = QMediaDevices.defaultAudioOutput()
if device.isNull() or not device.isFormatSupported(fmt):
if device.isNull() or not (device.isFormatSupported(fmt)
or _converts_any_rate()):
self.failed.emit("this computer's sound output can't play 44.1 kHz stereo")
return False
self.sink = QAudioSink(device, fmt)
+99 -12
View File
@@ -2,7 +2,7 @@
Nothing separates a voice from a mix in real time on a laptop, so a song is
split once, in the background, and kept:
``$XDG_CACHE_HOME/lintunes/stems/<key>/<model>/{vocals,no_vocals}.flac``
``paths.cache_dir()/stems/<key>/<model>/{vocals,no_vocals}.opus``
(machine-local, never the synced data dir). A cached song's slider works the
moment it loads, and a deck uses the best split it finds whatever model made
it. (Round 93's first splits sit directly in ``<key>/``; they were htdemucs.)
@@ -20,8 +20,8 @@ set; this machine's disk, so not a synced pref): after each split, the songs
used longest ago go first. Using a split (``cached``) counts as using it.
Demucs runs as a runtime tool, never a pip dependency of LinTunes: PyTorch is
~1 GB, so it lives in its own venv at ``$XDG_DATA_HOME/lintunes/demucs``
(``setup_command`` makes it), and LinTunes runs ``<venv>/bin/python -m
~1 GB, so it lives in its own venv at ``paths.data_dir()/demucs``
(``setup_command`` makes it on Linux; on a Mac ``DemucsSetup``, with uv), and LinTunes runs ``<venv>/bin/python -m
demucs``. It is *the* CPU hog in LinTunes (Round 94: htdemucs took 29 s for
40 s of audio on all 8 cores — several hot minutes a song), so it always
runs niced, and "gentle" (Preferences › DJ, the default) caps it at a
@@ -40,6 +40,7 @@ sample-aligned with the original); older FLAC splits still read.
import hashlib
import json
import os
import platform
import re
import shutil
import subprocess
@@ -49,8 +50,9 @@ from pathlib import Path
from PyQt6.QtCore import QObject, pyqtSignal
from lintunes import paths
from lintunes.config import load_config
from lintunes.dj import instant
from lintunes.dj import instant, venv_tool
# id → (label, what it costs). Best first: a deck uses the best split it has.
# Measured on this laptop (Round 94, 40 s of audio, 2 threads): htdemucs
@@ -82,8 +84,7 @@ class Cancelled(Exception):
def venv_dir() -> Path:
base = os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share")
return Path(base) / "lintunes" / "demucs"
return paths.data_dir() / "demucs"
def python() -> Path:
@@ -96,11 +97,96 @@ def available() -> bool:
def setup_command() -> str:
"""What makes the venv, for the "not set up" message."""
if setup_in_app():
return ("Preferences › DJ › Download High-Quality Vocal Splitting "
f"(Demucs, ~{DEMUCS_DOWNLOAD_GB} GB)")
v = venv_dir()
return (f"python3 -m venv {v} && {v}/bin/pip install torch --index-url "
f"https://download.pytorch.org/whl/cpu && {v}/bin/pip install numpy demucs")
# The Mac's Demucs, pinned (the Linux command above isn't). torchaudio 2.9
# hands load/save to torchcodec, which needs FFmpeg's shared libraries — a
# Mac running the built app has only the ffmpeg command — so 2.8 is the last
# that saves through soundfile (whose wheel carries libsndfile). Intel Macs
# stop at torch 2.2.2, the last x86_64 macOS wheel, built against numpy 1.
# Demucs itself stays on the CPU: its default device is CUDA-or-CPU, and
# its FFTs on MPS aren't reliable enough to make that a default.
DEMUCS_VERSION = "4.0.1"
DEMUCS_DOWNLOAD_GB = 1
_MAC_PACKAGES = {
"arm64": ["torch==2.8.0", "torchaudio==2.8.0", "numpy", "soundfile",
f"demucs=={DEMUCS_VERSION}"],
"x86_64": ["torch==2.2.2", "torchaudio==2.2.2", "numpy<2", "soundfile",
f"demucs=={DEMUCS_VERSION}"],
}
_CPU_INDEX = "https://download.pytorch.org/whl/cpu"
def setup_in_app() -> bool:
"""True where Demucs is set up by a button in Preferences (uv makes the
venv) rather than by a command typed into a terminal."""
return venv_tool.uses_uv()
def install_steps() -> list[tuple[str, list[str], str | None]]:
"""(what to say, packages, index URL) for each install, in order."""
if paths.IS_MAC:
machine = platform.machine().lower()
arch = "arm64" if machine in ("arm64", "aarch64") else "x86_64"
return [("Downloading PyTorch and Demucs…", _MAC_PACKAGES[arch], None)]
return [("Downloading PyTorch…", ["torch"], _CPU_INDEX),
("Downloading Demucs…", ["numpy", "demucs"], None)]
class DemucsSetup(QObject):
"""Preferences' Demucs download button (where ``setup_in_app``): makes
the venv with uv and installs PyTorch + Demucs, on a daemon thread."""
progress = pyqtSignal(str)
finished = pyqtSignal()
failed = pyqtSignal(str)
def __init__(self, parent=None):
super().__init__(parent)
self._thread = None
def busy(self) -> bool:
return self._thread is not None and self._thread.is_alive()
def start(self):
self._thread = threading.Thread(target=self._run, daemon=True,
name="lintunes-demucs-setup")
self._thread.start()
def _run(self):
try:
venv = venv_dir()
if venv_tool.uses_uv():
self.progress.emit("Downloading a Python for it…")
venv_tool.ensure_uv()
env = venv_tool.run_env()
if not python().is_file():
self.progress.emit("Making its own Python environment…")
venv.parent.mkdir(parents=True, exist_ok=True)
self._call(venv_tool.create_command(venv), env)
for text, packages, index in install_steps():
self.progress.emit(text)
self._call(venv_tool.install_command(venv, packages, index), env)
except (OSError, subprocess.SubprocessError) as e:
self.failed.emit(str(e) or type(e).__name__)
return
self.finished.emit()
@staticmethod
def _call(cmd, env=None):
done = subprocess.run(cmd, capture_output=True, text=True, timeout=3600,
env=env)
if done.returncode != 0:
lines = (done.stderr or done.stdout).strip().splitlines()
raise OSError(lines[-1] if lines else f"{cmd[0]} failed")
def instant_available() -> bool:
return instant.available()
@@ -146,8 +232,7 @@ def threads(gentle: bool) -> int:
def cache_root() -> Path:
base = os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache")
return Path(base) / "lintunes" / "stems"
return paths.cache_dir() / "stems"
CACHE_LIMIT_KEY = "dj_stem_cache_gb"
@@ -361,13 +446,15 @@ def split(path: str, model: str, gentle: bool, progress=None,
model = model if model in MODELS else DEFAULT_MODEL
work = Path(tempfile.mkdtemp(prefix="lintunes-stems-"))
count = str(threads(gentle))
env = dict(os.environ, OMP_NUM_THREADS=count, MKL_NUM_THREADS=count)
env = venv_tool.child_env(
dict(os.environ, OMP_NUM_THREADS=count, MKL_NUM_THREADS=count))
niceness = 19 if gentle else 10
try:
cmd = ([str(python()), "-m", "demucs", "--two-stems=vocals"] + _ARGS[model]
+ ["--flac", "-o", str(work), path])
cmd, preexec = venv_tool.niced(
[str(python()), "-m", "demucs", "--two-stems=vocals"] + _ARGS[model]
+ ["--flac", "-o", str(work), path], niceness)
process = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
env=env, preexec_fn=lambda: os.nice(niceness))
env=env, preexec_fn=preexec)
if cancel is not None:
def watch():
# Demucs can go seconds without a progress line (loading the
+185
View File
@@ -0,0 +1,185 @@
"""Making the vocal splitters' private Python environments, on any computer.
Demucs and Spleeter each live in a venv of their own (``stems.py``,
``instant.py``), never in LinTunes' own Python. On Linux from a checkout that
venv is made by the Python running LinTunes (``python -m venv``), as it always
was. That can't work on a Mac: inside the built LinTunes.app ``sys.executable``
is the app, and a stock Mac has no usable ``python3`` (``/usr/bin/python3`` is
a stub that offers to install Xcode's tools).
So on a Mac, and in any frozen build, the venv is made by Astral's **uv**,
which brings its own Python: a pinned release is downloaded once into
``paths.data_dir()/bin`` and refused unless its SHA-256 is the one pinned here
(the ``airplay/cli.py`` rule, through its ``download_verified``). uv's Python
and its download cache go under LinTunes' own folders too, so removing a
splitter's venv leaves nothing of uv's lying around in the user's home.
Pure subprocess/file work, no Qt.
"""
from __future__ import annotations
import io
import os
import platform
import sys
import tarfile
from pathlib import Path
from lintunes import paths
UV_VERSION = "0.13.6"
_UV_RELEASE = ("https://github.com/astral-sh/uv/releases/download/"
f"{UV_VERSION}/")
# From each asset's .sha256 in that release (checked against sha256.sum).
_UV_SHA256 = {
"aarch64-apple-darwin":
"60fbd5c8a1ed681845eea28d9d622fcde03c51e91a43465b64a1e17db1ed3472",
"x86_64-apple-darwin":
"63ba17fdda55ad1a230d4b37fc6017ffa10c23688c83818bd3bfdf914c652a02",
"x86_64-unknown-linux-gnu":
"f29c3e94ffabd7e6f3ba521dba169a9b7ec12100bf3257087f0f24f6123f3645",
"aarch64-unknown-linux-gnu":
"229e194255c7958d86d56e8790d969a6f74736592133f0dfd0076f754c642c1d",
}
# The splitters' Python. Every wheel they need exists for it on both Mac
# CPUs (torch 2.2.2 is the last for Intel Macs and still has cp312).
PYTHON_VERSION = "3.12"
# The Python variables that would point a child Python at LinTunes' own
# (frozen) one instead of the venv's.
_LEAKY = ("PYTHONHOME", "PYTHONPATH", "PYTHONEXECUTABLE", "PYTHONSTARTUP",
"__PYVENV_LAUNCHER__")
class VenvError(OSError):
"""The environment couldn't be made (download, checksum, uv itself)."""
def uses_uv() -> bool:
"""True where the venv must be made by uv rather than ``python -m venv``."""
return paths.IS_MAC or paths.FROZEN
def uv_target() -> str | None:
"""uv's release target for this computer, or None."""
machine = platform.machine().lower()
machine = {"arm64": "aarch64", "amd64": "x86_64"}.get(machine, machine)
if paths.IS_MAC:
target = f"{machine}-apple-darwin"
elif sys.platform.startswith("linux"):
target = f"{machine}-unknown-linux-gnu"
else:
return None
return target if target in _UV_SHA256 else None
def uv_path() -> Path:
return paths.data_dir() / "bin" / f"uv-{UV_VERSION}"
def _unpack_uv(archive: bytes, target: str) -> bytes:
"""The ``uv`` binary out of a release tarball."""
with tarfile.open(fileobj=io.BytesIO(archive), mode="r:gz") as tar:
for member in tar.getmembers():
if member.isfile() and member.name == f"uv-{target}/uv":
return tar.extractfile(member).read()
raise VenvError("the uv download had no uv in it")
def ensure_uv(fetch=None) -> Path:
"""uv's path, downloading and verifying it first if needed. Blocking.
``fetch(url) -> bytes`` is injectable so tests never touch the network."""
from lintunes.airplay import cli
path = uv_path()
if path.is_file() and os.access(path, os.X_OK):
return path
target = uv_target()
if target is None:
raise VenvError(f"no uv for {platform.system()} {platform.machine()}")
# The archive is checked exactly as published, then only its uv is kept.
return cli.download_verified(
_UV_RELEASE + f"uv-{target}.tar.gz", _UV_SHA256[target], path, fetch,
"Python installer (uv)", error=VenvError,
unpack=lambda data: _unpack_uv(data, target))
def uv_env(base: dict | None = None) -> dict:
"""The environment uv runs in: its Python and cache under our folders,
only Pythons uv manages (never Xcode's stub), no Python variables of
LinTunes' own leaking in."""
env = clean_env(base)
env["UV_PYTHON_INSTALL_DIR"] = str(paths.data_dir() / "python")
env["UV_CACHE_DIR"] = str(paths.cache_dir() / "uv")
env["UV_MANAGED_PYTHON"] = "1"
env.pop("VIRTUAL_ENV", None)
return env
def clean_env(base: dict | None = None) -> dict:
"""``base`` (default os.environ) without the variables that would point
a venv's Python back at LinTunes' own. On a Mac a Python downloaded by
uv may not find root certificates of its own, so it is handed certifi's
(which LinTunes ships, as a dependency of requests)."""
env = dict(os.environ if base is None else base)
for name in _LEAKY:
env.pop(name, None)
if paths.IS_MAC and "SSL_CERT_FILE" not in env:
bundle = certifi_bundle()
if bundle:
env["SSL_CERT_FILE"] = bundle
return env
def certifi_bundle() -> str | None:
try:
import certifi
where = certifi.where()
except Exception: # noqa: BLE001 — no certifi just means no override
return None
return where if where and os.path.isfile(where) else None
def child_env(base: dict | None = None) -> dict | None:
"""The environment for running a tool *inside* a splitter's venv:
``base`` untouched (None = inherit, as always) on Linux from a checkout,
``clean_env(base)`` elsewhere."""
return clean_env(base) if uses_uv() else base
def venv_python(venv: Path) -> Path:
return venv / "bin" / "python"
def create_command(venv: Path, uv: Path | None = None) -> list[str]:
"""The command that makes ``venv``."""
if not uses_uv():
return [sys.executable, "-m", "venv", str(venv)]
return [str(uv or uv_path()), "venv", "--quiet", "--python", PYTHON_VERSION,
str(venv)]
def install_command(venv: Path, packages: list[str], index_url: str | None = None,
uv: Path | None = None, quiet: bool = True) -> list[str]:
"""The command that installs ``packages`` into ``venv``."""
extra = ["--index-url", index_url] if index_url else []
if not uses_uv():
return ([str(venv_python(venv)), "-m", "pip", "install"]
+ (["--quiet"] if quiet else []) + extra + list(packages))
return ([str(uv or uv_path()), "pip", "install"]
+ (["--quiet"] if quiet else [])
+ ["--python", str(venv_python(venv))] + extra + list(packages))
def run_env() -> dict | None:
"""The environment ``create_command``/``install_command`` run in."""
return uv_env() if uses_uv() else None
def niced(cmd: list[str], niceness: int):
"""(command, preexec_fn) that run ``cmd`` at ``niceness``. Linux keeps
``os.nice`` in the child, as it always did; a Mac prefixes
``/usr/bin/nice``, since a ``preexec_fn`` in a threaded process (Qt's)
is unsafe there with the system's fork rules."""
if paths.IS_MAC:
return ["/usr/bin/nice", "-n", str(niceness)] + list(cmd), None
return list(cmd), (lambda: os.nice(niceness))
+8
View File
@@ -11,12 +11,20 @@ import logging
import time
from pathlib import Path
from lintunes import paths
log = logging.getLogger("lintunes.control")
_MAX_BYTES = 1_000_000
def _log_path() -> Path:
return default_log_path()
def default_log_path() -> Path:
if paths.IS_MAC:
return paths.cache_dir() / "control-events.log"
return Path.home() / ".cache" / "lintunes" / "control-events.log"
+38 -2
View File
@@ -33,6 +33,8 @@ from pathlib import Path
from PyQt6.QtCore import QObject, pyqtSignal
from lintunes import paths
HOST_KEY = "webmix_host"
PATH_KEY = "webmix_path"
@@ -83,8 +85,7 @@ def remote_dir(path: str, slug: str) -> str:
def staging_root() -> Path:
base = os.environ.get("XDG_CACHE_HOME", str(Path.home() / ".cache"))
return Path(base) / "lintunes" / "webmix"
return paths.cache_dir() / "webmix"
def reset_staging(slug: str) -> Path:
@@ -128,6 +129,37 @@ def _missing_tool(name: str) -> str:
f"the server.")
_RSYNC_VERSION = re.compile(r"rsync\s+version\s+v?(\d+)\.")
def rsync_major(version_text: str) -> int | None:
"""rsync's major version from ``rsync --version`` (None if unreadable).
macOS's own is 2.6.9 or openrsync ("rsync version 2.6.9 compatible")."""
m = _RSYNC_VERSION.search(version_text or "")
return int(m.group(1)) if m else None
def mac_rsync_problem() -> str | None:
"""On a Mac, why the rsync on PATH can't do this upload, or None.
The command line needs rsync 3 (``-s``, ``--info=progress2``); Apple
ships 2.6.9 or openrsync, so Homebrew's is required there. Linux is
never asked."""
if not paths.IS_MAC:
return None
try:
out = subprocess.run(["rsync", "--version"], capture_output=True,
text=True, errors="replace", timeout=10).stdout
except (OSError, subprocess.SubprocessError):
return None # the run itself will report it
major = rsync_major(out)
if major is not None and major < 3:
return ("The rsync that comes with macOS is too old for uploading. "
"Install a current one with Homebrew (brew install rsync) "
"and try again.")
return None
class _ProcessWorker(QObject):
"""One subprocess on a daemon thread; cancel() kills it."""
@@ -224,6 +256,10 @@ class UploadWorker(_ProcessWorker):
if shutil.which("rsync") is None:
self.failed.emit(_missing_tool("rsync"))
return
problem = mac_rsync_problem()
if problem:
self.failed.emit(problem)
return
proc = self._spawn(rsync_command(self._host, self._local, self._rdir))
if proc is None:
self.cancelled.emit()
+3
View File
@@ -21,6 +21,9 @@ def failure_text(exc: Exception) -> str:
return str(exc)
if isinstance(exc, st.SyncthingError):
if exc.kind == st.NOT_RUNNING:
hint = st.not_running_hint("try again")
if hint:
return f"{exc.step} failed: Syncthing isn't running. {hint}"
return (f"{exc.step} failed: Syncthing isn't running. Start "
f"Syncthing and try again.")
if exc.kind in (st.BAD_KEY, st.NO_KEY):
+2 -2
View File
@@ -126,8 +126,8 @@ def _check_svg() -> str:
if _CHECK_SVG is None:
import os
import tempfile
base = os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache")
folder = os.path.join(base, "lintunes")
from lintunes import paths
folder = str(paths.cache_dir())
try:
os.makedirs(folder, exist_ok=True)
except OSError:
+3 -2
View File
@@ -14,6 +14,7 @@ from lintunes import tagging
from lintunes.gui.art_ops import embed_artwork
from lintunes.player import VOLUME_ADJUSTMENT_MAX
from lintunes.gui.file_filters import IMAGE_FILTER
from lintunes.gui.track_table import key_hint
log = logging.getLogger(__name__)
@@ -30,7 +31,7 @@ PASTE_RETRY_MS = 300
# compare covers; it just offers the paste.
MULTI_ART_READ_LIMIT = 100
HINT_IDLE = "Ctrl+V or Paste Artwork to add a cover"
HINT_IDLE = key_hint("Ctrl+V") + " or Paste Artwork to add a cover"
HINT_STAGED = "New artwork — saved when you click OK"
@@ -196,7 +197,7 @@ class ArtSquare(QLabel):
def _show_menu(self, pos):
menu = QMenu(self)
paste = menu.addAction("Paste Image\tCtrl+V")
paste = menu.addAction("Paste Image\t" + key_hint("Ctrl+V"))
choose = menu.addAction("Choose File…")
chosen = menu.exec(self.mapToGlobal(pos))
if chosen is paste:
+39 -17
View File
@@ -11,6 +11,7 @@ from PyQt6.QtWidgets import (
from PyQt6.QtCore import QRect, Qt, QEvent, QObject, QTimer, pyqtSignal
from PyQt6.QtGui import QAction, QKeySequence
from lintunes import paths as os_paths
from lintunes import (bpm_detect, device_sync, loudness, music_folder, shazam,
tagging, theme, url_import)
from lintunes import playlist_art
@@ -523,7 +524,10 @@ class MainWindow(QMainWindow):
file_menu.aboutToShow.connect(self._refresh_export_action)
file_menu.aboutToShow.connect(self._refresh_url_import_action)
file_menu.addSeparator()
self._add_action(file_menu, "Quit", "Ctrl+Q", self.close)
quit_action = self._add_action(file_menu, "Quit", "Ctrl+Q", self.close)
# On a Mac these two move to the app menu ("LinTunes ▸ Settings…",
# "Quit LinTunes"); elsewhere the role does nothing.
quit_action.setMenuRole(QAction.MenuRole.QuitRole)
edit_menu = bar.addMenu("&Edit")
self._undo_action = self._add_action(
@@ -538,7 +542,9 @@ class MainWindow(QMainWindow):
QKeySequence("Ctrl+Shift+Z"),
])
edit_menu.addSeparator()
self._add_action(edit_menu, "Preferences…", "Ctrl+,", self._show_preferences)
prefs_action = self._add_action(
edit_menu, "Preferences…", "Ctrl+,", self._show_preferences)
prefs_action.setMenuRole(QAction.MenuRole.PreferencesRole)
self._manager.undo_stack.changed.connect(self._refresh_undo_actions)
self._refresh_undo_actions()
@@ -590,14 +596,23 @@ class MainWindow(QMainWindow):
self._full_sync_action = self._add_action(
connections_menu, "Full Rabbit Sync", "", self._full_rabbit_sync)
self._full_sync_action.setEnabled(False)
self._add_action(connections_menu, "Rabbit Sync Settings…", "",
self._show_device_sync_settings)
self._sync_settings_action = self._add_action(
connections_menu, "Rabbit Sync Settings…", "",
self._show_device_sync_settings)
self._install_action = self._add_action(
connections_menu, "Install andTunes on Rabbit…", "",
self._install_andtunes)
self._shazam_action = self._add_action(
connections_menu, "Import Shazams…", "",
lambda: self._import_shazams())
if os_paths.IS_MAC:
# The Rabbit R1 features never exist on a Mac. The actions are
# kept (hidden) so everything that touches them still can.
for action in (self._andtunes_action, self._full_sync_action,
self._sync_settings_action, self._install_action,
self._shazam_action):
action.setVisible(False)
action.setEnabled(False)
# "Sync Playlist to Rabbit (Auxio)" was retired in Round 51, once
# andTunes could play what it syncs. device_sync's helpers stay: the
# export and andTunes code import them.
@@ -669,17 +684,19 @@ class MainWindow(QMainWindow):
def _refresh_connection_actions(self):
# An export in flight owns the same status-bar widgets, so it blocks
# a sync just as another sync would.
self._devices.probe()
self._refresh_device_actions()
if not os_paths.IS_MAC: # no Rabbit on a Mac: never probe for one
self._devices.probe()
self._refresh_device_actions()
self._cassette.refresh_menu()
# Enabled whenever there's an APK to offer; the click finds the
# Rabbit (adb or MTP) and says so if it can't — cheaper than asking
# adb on every menu open.
self._install_action.setEnabled(
andtunes_install.bundled_apk() is not None
and not (self._install_worker is not None
and self._install_worker.busy()))
self._shazam_action.setEnabled(self._busy_worker() is None)
if not os_paths.IS_MAC:
# Enabled whenever there's an APK to offer; the click finds the
# Rabbit (adb or MTP) and says so if it can't — cheaper than
# asking adb on every menu open.
self._install_action.setEnabled(
andtunes_install.bundled_apk() is not None
and not (self._install_worker is not None
and self._install_worker.busy()))
self._shazam_action.setEnabled(self._busy_worker() is None)
# The self-updater ships code but not dependencies, so a machine that
# has pulled this round hasn't necessarily installed pychromecast (or
@@ -848,6 +865,8 @@ class MainWindow(QMainWindow):
def _refresh_device_actions(self):
"""Sync Music / Full Rabbit Sync from the watcher's cached answer — never a fresh
look at the mount, which is what froze the menu."""
if os_paths.IS_MAC:
return # the Rabbit actions are hidden there
busy = self._busy_worker() is not None
if self._devices.state == device_sync.STUCK:
# Enabled: the click explains and offers the reset.
@@ -2513,7 +2532,8 @@ class MainWindow(QMainWindow):
where = "moved to Trash" if delete_files else "file kept"
self.statusBar().showMessage(
f"Removed {len(removed)} song(s) from your library "
f"({where}) — undo with Ctrl+Z", 8000)
f"({where}) — undo with "
f"{'⌘Z' if os_paths.IS_MAC else 'Ctrl+Z'}", 8000)
if failures:
QMessageBox.warning(
self, "Couldn't delete",
@@ -2660,8 +2680,10 @@ class MainWindow(QMainWindow):
QMessageBox.warning(
self, "Identify Track",
"Track identification needs the fpcalc tool from Chromaprint.\n\n"
"Install it (Fedora: chromaprint-tools, Debian: "
"libchromaprint-tools) and try again.")
+ ("Install it (Homebrew: brew install chromaprint) and try "
"again." if os_paths.IS_MAC else
"Install it (Fedora: chromaprint-tools, Debian: "
"libchromaprint-tools) and try again."))
return
api_key = self._prefs.acoustid.get("api_key", "").strip()
if not api_key:
+16
View File
@@ -7,21 +7,37 @@ follow on Linux. Alt+<letter> while it's hidden opens that menu at once.
Qt disables a hidden menu bar's shortcuts along with it, so every action in
it is also added to the window (`register_shortcuts`), or Ctrl+N and the rest
would stop working the moment the bar hides.
On macOS the menu bar is the system's, at the top of the screen, and can't
be hidden by an app (nor does Option mean "menus" there), so the pref is
always "always" and nothing is registered twice: the native menu owns the
key equivalents.
"""
from PyQt6.QtCore import QEvent, QObject, Qt, QTimer
from PyQt6.QtWidgets import QApplication, QMenu
from lintunes import paths
PREF = "menu_bar"
ALWAYS = "always"
ALT = "alt"
def available() -> bool:
"""Whether the menu bar can be hidden at all (never on a Mac)."""
return not paths.IS_MAC
def hidden_by_pref(prefs) -> bool:
if not available():
return False
return prefs.get(PREF, ALWAYS) == ALT
def register_shortcuts(window, bar):
"""Add every action in `bar`'s menus, submenus included, to `window`."""
if not available():
return # the Mac's global menu bar is always there to fire them
def walk(menu):
for action in menu.actions():
if action.menu() is not None:
+43 -3
View File
@@ -13,6 +13,7 @@ from PyQt6.QtCore import Qt, QTimer, pyqtSignal
from PyQt6.QtGui import QDoubleValidator, QFont, QColor, QFontInfo
from lintunes import loudness, theme
from lintunes import paths as os_paths
from lintunes.config import load_config, save_config
from lintunes.export import upload
from lintunes.gui import visualizer_styles
@@ -418,10 +419,19 @@ class PreferencesDialog(QDialog):
gentle.setChecked(stems.gentle_choice(self._prefs))
gentle.toggled.connect(lambda on: self._prefs.set("dj_stem_gentle", on))
form.addRow("", gentle)
self._demucs_setup = None
if stems.available():
note = QLabel("Demucs is set up. Songs are split when they load onto "
"a deck, or ahead of time with a playlist's or "
"song's “Prepare for DJ”.")
elif stems.setup_in_app():
# A Mac (or the built app): no terminal command, a button.
note = QLabel("Demucs isn't set up on this computer (a one-time "
f"~{stems.DEMUCS_DOWNLOAD_GB} GB download).")
button = QPushButton("Download High-Quality Vocal Splitting "
f"(Demucs, ~{stems.DEMUCS_DOWNLOAD_GB} GB)")
button.clicked.connect(lambda: self._on_demucs_button(button, note))
form.addRow("", button)
else:
note = QLabel("Demucs isn't set up on this computer (a one-time ~1 GB "
"download). In a terminal:\n" + stems.setup_command())
@@ -432,6 +442,30 @@ class PreferencesDialog(QDialog):
self._dj_gentle_check = gentle
return group
def _on_demucs_button(self, button, note):
"""Set up Demucs in the background (``stems.DemucsSetup``)."""
from lintunes.dj import stems
if self._demucs_setup is not None and self._demucs_setup.busy():
return
setup = stems.DemucsSetup(self)
def done():
button.hide()
note.setText("Demucs is set up. Songs are split when they load "
"onto a deck, or ahead of time with a playlist's or "
"song's “Prepare for DJ”.")
def failed(why):
button.setEnabled(True)
note.setText(f"Couldn't set Demucs up: {why}")
setup.progress.connect(note.setText)
setup.finished.connect(done)
setup.failed.connect(failed)
self._demucs_setup = setup
button.setEnabled(False)
note.setText("Starting…")
setup.start()
def _build_dj_cache_group(self) -> QGroupBox:
"""How much disk the saved vocal splits (both engines) may take,
and how much they take now."""
@@ -507,8 +541,9 @@ class PreferencesDialog(QDialog):
self._history_check.setChecked(bool(wrapped.get("track_history")))
column.addWidget(self._history_check)
column.addWidget(self._note(
"Every song you listen to, here and on the Rabbit: when, for how "
"long, and whether you finished it. Kept in the library folder; "
("Every song you listen to: when, for how " if os_paths.IS_MAC
else "Every song you listen to, here and on the Rabbit: when, for how ")
+ "long, and whether you finished it. Kept in the library folder; "
"nothing leaves your machines."))
self._share_history_check = QCheckBox(
"Share this year's play history with friends")
@@ -580,7 +615,12 @@ class PreferencesDialog(QDialog):
self._menu_bar_check.setChecked(self._prefs.get("menu_bar", "always") == "alt")
self._menu_bar_check.toggled.connect(
lambda on: self._prefs.set("menu_bar", "alt" if on else "always"))
form.addRow("Menu bar:", self._menu_bar_check)
if os_paths.IS_MAC:
# A Mac's menu bar is the system's; it can't hide until Alt.
self._menu_bar_check.setParent(group)
self._menu_bar_check.hide()
else:
form.addRow("Menu bar:", self._menu_bar_check)
# Highlight color: a radio per slot, and beside it the slot's swatch,
# which opens a full color picker; the color picked replaces that
+2
View File
@@ -101,7 +101,9 @@ def status_text(result) -> tuple[str, str]:
if result.state == probe_mod.OK:
return f"Syncthing {result.version} is running.", ""
if result.state == probe_mod.NOT_RUNNING:
from lintunes.cassette import syncthing_api
return ("Syncthing isn't running.",
syncthing_api.not_running_hint("press Retry") or
"Start it (for example: systemctl --user start syncthing, or "
"open the Syncthing app), then press Retry.")
return ("Can't reach Syncthing's API.",
+6
View File
@@ -38,6 +38,8 @@ from PyQt6.QtGui import (QBrush, QColor, QLinearGradient, QPainter,
QPainterPath, QPalette, QPen, QRegion)
from PyQt6.QtWidgets import QAbstractButton, QLayout, QWidget
from lintunes import paths
OPT_OUT = "lintunes_system_frame"
BLANK_TITLE = "lintunes_blank_title"
SQUARE = "lintunes_square_corners" # stays opaque: square corners, same rim
@@ -71,6 +73,10 @@ def parse_button_layout(text: str) -> tuple[list[str], list[str]]:
def button_layout() -> tuple[list[str], list[str]]:
"""The desktop's button layout, read once; GNOME's default without one."""
global _layout_cache
if _layout_cache is None and paths.IS_MAC:
# Never installed on a Mac (main installs it on Wayland only), but
# there's no gsettings to ask there in any case.
_layout_cache = parse_button_layout(_FALLBACK_LAYOUT)
if _layout_cache is None:
try:
text = subprocess.run(
+40 -11
View File
@@ -14,12 +14,18 @@ from PyQt6.QtGui import (
QDrag, QKeySequence, QShortcut, QPixmap, QPainter, QPen, QPolygonF, QColor,
QFontMetrics, QDesktopServices, QCursor, QPalette,
)
from PyQt6.QtDBus import (
QDBusConnection, QDBusInterface, QDBusMessage, QDBusArgument,
)
try:
from PyQt6.QtDBus import (
QDBusConnection, QDBusInterface, QDBusMessage, QDBusArgument,
)
HAVE_DBUS = True
except ImportError: # no QtDBus in this Qt: reveal just opens the folder
HAVE_DBUS = False
import subprocess
from pathlib import Path
from lintunes import paths as os_paths
from lintunes.models import Track
from lintunes.gui import drag_ghost
from lintunes.importers.lossless import LOSSLESS_SUFFIXES
@@ -30,6 +36,17 @@ LOSSLESS_MENU_SUFFIXES = LOSSLESS_SUFFIXES | {".m4a"}
TRACKS_MIME = "application/x-lintunes-tracks"
def key_hint(keys: str) -> str:
"""The shortcut shown after a context-menu entry's tab. Linux keeps the
literal text; a Mac shows its own symbols (⌘I), and its "delete" key —
which is Backspace — as ⌫."""
if not os_paths.IS_MAC:
return keys
if keys == "Del":
return "⌫"
return QKeySequence(keys).toString(QKeySequence.SequenceFormat.NativeText)
# While dragging a track within this many pixels of the list's top/bottom edge,
# the list auto-scrolls so off-screen rows can be reached.
AUTOSCROLL_MARGIN = 28
@@ -512,8 +529,19 @@ def reveal_paths(paths: list[str]) -> None:
"""
if not paths:
return
bus = QDBusConnection.sessionBus()
if bus.isConnected():
if os_paths.IS_MAC:
# The Finder's own "reveal": opens the folder with the files selected.
try:
subprocess.Popen(["open", "-R", *paths],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
return
except OSError:
pass
QDesktopServices.openUrl(QUrl.fromLocalFile(os.path.dirname(paths[0])))
return
bus = QDBusConnection.sessionBus() if HAVE_DBUS else None
if bus is not None and bus.isConnected():
# The URIs must be marshalled as a D-Bus string array ("as"); a plain
# Python list goes over as "av" and Nautilus rejects it (InvalidArgs).
uris = QDBusArgument()
@@ -1094,20 +1122,21 @@ class TrackTableView(QTableView):
self._show_read_only_menu(pos)
return
menu = QMenu(self)
info_action = menu.addAction("Get Info\tCtrl+I")
copy_action = menu.addAction("Copy\tCtrl+C")
cut_action = menu.addAction("Cut\tCtrl+X")
info_action = menu.addAction("Get Info\t" + key_hint("Ctrl+I"))
copy_action = menu.addAction("Copy\t" + key_hint("Ctrl+C"))
cut_action = menu.addAction("Cut\t" + key_hint("Ctrl+X"))
paste_action = None
if (self._playlist_mode and self._content_editable
and parse_tracks_mime(QApplication.clipboard().mimeData())):
paste_action = menu.addAction("Paste\tCtrl+V")
paste_action = menu.addAction("Paste\t" + key_hint("Ctrl+V"))
locations = self.selected_locations()
reveal_action = copy_path_action = download_art_action = None
identify_action = bpm_action = dj_action = convert_action = None
if locations:
menu.addSeparator()
reveal_action = menu.addAction("Reveal in File Browser")
reveal_action = menu.addAction(
"Show in Finder" if os_paths.IS_MAC else "Reveal in File Browser")
copy_path_action = menu.addAction("Copy File Path")
download_art_action = menu.addAction("Download Album Art…")
# Fingerprinting reads the audio, so this needs a file on disk.
@@ -1146,7 +1175,7 @@ class TrackTableView(QTableView):
remove_action = None
if self._playlist_mode and self._content_editable:
menu.addSeparator()
remove_action = menu.addAction("Remove from Playlist\tDel")
remove_action = menu.addAction("Remove from Playlist\t" + key_hint("Del"))
# Library removal is offered in both modes (unlike the playlist-only
# remove above) and has no keyboard shortcut — Del stays "remove from
+26 -2
View File
@@ -5,10 +5,14 @@ versions on different machines are still distinguishable). When the Updater
finds upstream commits it grows a "*" and becomes a button — still flat, but
the button face shows under the cursor and sinks while held: click → confirm →
git pull → the main window restarts the app on `update_applied`.
In the built Mac app the Updater reports a newer GitHub release instead
(`release_available`); the "*" is the same, and a click opens that
release's page in the browser. The app never replaces itself.
"""
from PyQt6.QtCore import Qt, QTimer, pyqtSignal
from PyQt6.QtGui import QPalette
from PyQt6.QtCore import Qt, QTimer, QUrl, pyqtSignal
from PyQt6.QtGui import QDesktopServices, QPalette
from PyQt6.QtWidgets import QApplication, QMessageBox, QPushButton
from lintunes import __version__, theme
@@ -21,6 +25,7 @@ class VersionButton(QPushButton):
super().__init__(parent)
self._updater = updater
self._update_ready = False
self._release_page = None # the frozen app's update: a web page
self.setFlat(True)
self.setFocusPolicy(Qt.FocusPolicy.NoFocus)
self.refresh_theme()
@@ -33,6 +38,9 @@ class VersionButton(QPushButton):
updater.update_available.connect(self._on_update_available)
updater.update_failed.connect(self._on_update_failed)
release = getattr(updater, "release_available", None)
if release is not None:
release.connect(self._on_release_available)
self.clicked.connect(self._on_clicked)
def _load_commit_tooltip(self):
@@ -70,15 +78,31 @@ class VersionButton(QPushButton):
self.setToolTip(f"Update available ({commits} {noun}) — "
"click to update and restart")
def _on_release_available(self, version: str, page: str):
self._update_ready = True
self._release_page = page
self.refresh_theme()
self.setText(f"v{__version__}*")
self.setToolTip(f"LinTunes {version} is out — click to open its "
"download page")
def _on_clicked(self):
if not self._update_ready or not self.isEnabled():
return
if self._release_page:
self.open_release_page()
return
if not self._confirm():
return
self.setEnabled(False)
self.setText("updating…")
self._updater.update_async()
def open_release_page(self):
if not QDesktopServices.openUrl(QUrl(self._release_page)):
self.status_message.emit(
f"Couldn't open the browser: {self._release_page}")
def _confirm(self) -> bool:
answer = QMessageBox.question(
self.window(), "Update LinTunes",
+2 -4
View File
@@ -20,7 +20,6 @@ unevenly, and the art must arrive as an ID3 front cover.
from __future__ import annotations
import logging
import os
import shutil
import subprocess
import tempfile
@@ -29,7 +28,7 @@ from pathlib import Path
from PyQt6.QtCore import QObject, pyqtSignal
from lintunes import tagging
from lintunes import paths, tagging
log = logging.getLogger(__name__)
@@ -41,8 +40,7 @@ LOSSLESS_SUFFIXES = {".flac", ".wav", ".aiff", ".aif"}
def staging_root() -> Path:
"""Where conversions are written before they're filed: the cache, on
disk — /tmp is often RAM, and a batch of songs can be gigabytes."""
base = os.environ.get("XDG_CACHE_HOME") or str(Path.home() / ".cache")
return Path(base) / "lintunes" / "converting"
return paths.cache_dir() / "converting"
def ffmpeg_available() -> bool:
+90 -3
View File
@@ -11,10 +11,32 @@ Instances are independent (one D-Bus cookie each), so playback and sync can
hold inhibitors simultaneously without stepping on each other. On non-GNOME
desktops the interface won't be available; every method then no-ops silently
rather than failing.
On macOS there is no session bus to ask: an inhibitor is a ``caffeinate``
child process held for as long as the inhibit lasts (``-i`` for suspend,
plus ``-s``/``-m`` keeping disks and the system up for logout-class
syncs). ``-w <our pid>`` makes it exit on its own if LinTunes dies, so a
crash can never leave the Mac unable to sleep.
"""
import atexit
import logging
import os
import shutil
import subprocess
import weakref
from PyQt6.QtCore import QMetaType
from PyQt6.QtDBus import (QDBusArgument, QDBusConnection, QDBusInterface,
QDBusReply)
try:
from PyQt6.QtDBus import (QDBusArgument, QDBusConnection, QDBusInterface,
QDBusReply)
HAVE_DBUS = True
except ImportError: # no QtDBus in this Qt: every inhibitor no-ops
HAVE_DBUS = False
from lintunes import paths
log = logging.getLogger(__name__)
SERVICE = "org.gnome.SessionManager"
@@ -33,19 +55,82 @@ def _uint(value: int) -> QDBusArgument:
return QDBusArgument(value, QMetaType.Type.UInt.value)
def caffeinate_command(flags: int, pid: int | None = None) -> list[str]:
"""The macOS ``caffeinate`` line for these GsmInhibitorFlags: ``-i``
stops idle sleep (what playback needs); a logout-class inhibit (a
sync, an export) also keeps the system (``-s``, on AC) and the disks
(``-m``) awake. ``-w`` ties it to our process."""
args = ["caffeinate", "-i"]
if flags & INHIBIT_LOGOUT:
args += ["-s", "-m"]
args += ["-w", str(os.getpid() if pid is None else pid)]
return args
# Every live caffeinate, so quitting kills them even if nothing released
# them (``-w`` would end them anyway once we exit; this is belt and braces).
_LIVE: "weakref.WeakSet[SleepInhibitor]" = weakref.WeakSet()
@atexit.register
def _release_all():
for inhibitor in list(_LIVE):
try:
inhibitor.release()
except Exception: # noqa: BLE001 — exiting; nothing to report to
pass
class SleepInhibitor:
def __init__(self, reason: str = REASON, flags: int = INHIBIT_SUSPEND):
self._cookie: int | None = None
self._reason = reason
self._flags = flags
self._proc = None # macOS: the caffeinate holding the inhibit
self._iface = None
if paths.IS_MAC or not HAVE_DBUS:
return
bus = QDBusConnection.sessionBus()
self._iface = QDBusInterface(SERVICE, PATH, SERVICE, bus)
def _available(self) -> bool:
return self._iface.isValid()
return self._iface is not None and self._iface.isValid()
def _mac_inhibit(self):
if self._proc is not None and self._proc.poll() is None:
return
if shutil.which("caffeinate") is None:
return
try:
self._proc = subprocess.Popen(
caffeinate_command(self._flags),
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
except OSError as e:
log.info("inhibit: couldn't start caffeinate: %s", e)
self._proc = None
return
_LIVE.add(self)
def _mac_release(self):
proc, self._proc = self._proc, None
_LIVE.discard(self)
if proc is None:
return
try:
proc.terminate()
proc.wait(timeout=2)
except Exception: # noqa: BLE001
try:
proc.kill()
except Exception: # noqa: BLE001
pass
def inhibit(self):
"""Take the inhibitor. No-op if already inhibiting or unavailable."""
if paths.IS_MAC:
self._mac_inhibit()
return
if self._cookie is not None or not self._available():
return
reply = QDBusReply(self._iface.call(
@@ -55,6 +140,8 @@ class SleepInhibitor:
def release(self):
"""Release a held inhibitor, if any."""
if self._proc is not None:
self._mac_release()
if self._cookie is None:
return
if self._available():
+9
View File
@@ -1,4 +1,5 @@
import logging
import os
import secrets
import unicodedata
from datetime import datetime, timezone
@@ -944,6 +945,14 @@ class LibraryManager(QObject):
unicodedata.normalize("NFC", src.name))
if dest == src:
return None
# A filesystem that ignores case (a Mac's) answers "RJD2/…" with the
# file already in "Rjd2/…": it is where it belongs, and moving it
# would only rename it "song 2.mp3" beside itself.
try:
if dest.exists() and os.path.samefile(src, dest):
return None
except OSError:
pass
try:
return str(self._move_file(src, dest))
except OSError as e:
+3 -2
View File
@@ -27,6 +27,8 @@ from pathlib import Path
from PyQt6.QtCore import QObject, QTimer, pyqtSignal
from lintunes import paths
log = logging.getLogger(__name__)
TARGET_LUFS = -14.0 # Spotify's and YouTube's level: loud enough for a party
@@ -75,8 +77,7 @@ def measure_lufs(path: str) -> float | None:
def default_cache_path() -> Path:
base = os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache"
return Path(base) / "lintunes" / "loudness.json"
return paths.cache_dir() / "loudness.json"
def _stamp(path: str):
+94 -2
View File
@@ -3,10 +3,33 @@ import os
import sys
from pathlib import Path
from PyQt6.QtCore import QEvent, QObject, QTimer
from lintunes import paths
from lintunes.config import load_config, save_config
# Where a Mac with no data dir configured keeps its library: an app opened
# from the Finder has no command line to be told one with.
MAC_DEFAULT_DATA_DIR = Path.home() / "Music" / "LinTunes"
def add_mac_tool_dirs(environ=None) -> None:
"""Put Homebrew's and the app bundle's folders on PATH (macOS only).
A Finder-launched app gets a bare ``/usr/bin:/bin:/usr/sbin:/sbin``, so
without this ``shutil.which`` never finds ffmpeg, fpcalc, yt-dlp, rsync
or ssh. Runs before anything looks for them; a folder already on PATH
isn't added twice."""
if not paths.IS_MAC:
return
environ = os.environ if environ is None else environ
current = [d for d in environ.get("PATH", "").split(os.pathsep) if d]
extra = [d for d in paths.mac_tool_dirs() if d not in current]
environ["PATH"] = os.pathsep.join(extra + current)
def main():
add_mac_tool_dirs()
parser = argparse.ArgumentParser(
prog="lintunes",
description="LinTunes — iTunes library manager for Linux",
@@ -50,6 +73,11 @@ def main():
save_config(config)
print(f"Saved config: {config}")
if not data_dir and paths.IS_MAC:
data_dir = str(MAC_DEFAULT_DATA_DIR)
MAC_DEFAULT_DATA_DIR.mkdir(parents=True, exist_ok=True)
config["data_dir"] = data_dir
save_config(config)
if not data_dir:
print("Error: no data directory configured.\n"
"Run with --data-dir DIR (add --save-config to remember it).")
@@ -60,6 +88,10 @@ def main():
run_import(Path(args.import_file), music_root, data_dir)
else:
if run_gui(data_dir, [Path(f) for f in args.files], qt_args):
if paths.FROZEN:
# A built app can't re-exec "python -m"; the updater (which
# owns relaunching a frozen build) has done its part.
leave(0)
# A self-update just pulled new code; replace this process with a
# fresh launch running the updated source. -m works whether we
# started as `lintunes` or `python -m lintunes.main`. Positional
@@ -143,13 +175,21 @@ def run_gui(data_dir: Path, files: list[Path],
new_library = not (data_dir / "library.json").exists()
library = load_library(data_dir)
if paths.IS_MAC:
_name_mac_app_menu()
app = QApplication([sys.argv[0]] + (qt_args or []))
app.setApplicationName("LinTunes")
app.setDesktopFileName("lintunes")
if paths.IS_MAC:
app.setApplicationDisplayName("LinTunes")
else:
app.setDesktopFileName("lintunes")
# Click anywhere on a scrollbar trough to jump there, not page a step at a
# time. Set app-wide (before apply_theme's stylesheet wraps the style) so
# the hint is honored everywhere, including the track list and sidebar.
app.setStyle(ClickToJumpScrollStyle())
# On a Mac the default would be the native "macos" style; the whole look
# is painted on Fusion, so ask for it by name there.
app.setStyle(ClickToJumpScrollStyle("Fusion") if paths.IS_MAC
else ClickToJumpScrollStyle())
prefs = Preferences(data_dir)
theme.apply_theme(app, prefs)
@@ -162,6 +202,10 @@ def run_gui(data_dir: Path, files: list[Path],
lastfm = LastFm(prefs, data_dir)
window = MainWindow(manager, prefs, lastfm)
app.installEventFilter(window)
if paths.IS_MAC:
# Audio dropped on the Dock icon, or "Open With" in the Finder.
file_opener = FileOpenFilter(window.import_files, app)
app.installEventFilter(file_opener)
mpris = setup_mpris(window.player, window) # noqa: F841 — keep alive
# Tear the multimedia pipeline down before Qt destroys objects (exit
# segfault in the FFmpeg backend otherwise); shutdown() is idempotent so
@@ -188,12 +232,60 @@ def run_gui(data_dir: Path, files: list[Path],
window.show_conflict_summary(startup_conflicts)
if files:
window.import_files(files)
# The Mac build's smoke test: start, stay up, leave cleanly.
quit_after = os.environ.get("LINTUNES_QUIT_AFTER_MS", "")
if quit_after.isdigit():
QTimer.singleShot(int(quit_after), window.close)
exit_code = app.exec()
if window.restart_requested:
return True # caller re-execs the updated code
leave(exit_code)
def _name_mac_app_menu():
"""From a checkout the Mac's app menu would read "Python" (the bundle
is Python's); renaming the running bundle before Qt starts fixes it.
A built .app is already named by its Info.plist. Never fatal."""
if paths.FROZEN:
return
try:
from Foundation import NSBundle
info = NSBundle.mainBundle().infoDictionary()
if info is not None:
info["CFBundleName"] = "LinTunes"
except Exception: # noqa: BLE001 — pyobjc missing: the menu says Python
pass
class FileOpenFilter(QObject):
"""macOS hands files opened on the app (Dock drop, Open With) to the
application as QFileOpenEvents; import them like a drop. Several
arrive one event each, so they're gathered for a moment and imported
as one batch."""
GATHER_MS = 200
def __init__(self, import_files, parent=None):
super().__init__(parent)
self._import = import_files
self._pending: list[Path] = []
def eventFilter(self, obj, event):
if event.type() == QEvent.Type.FileOpen:
path = event.file()
if path:
if not self._pending:
QTimer.singleShot(self.GATHER_MS, self._flush)
self._pending.append(Path(path))
return True
return False
def _flush(self):
files, self._pending = self._pending, []
if files:
self._import(files)
def leave(exit_code: int):
"""End the process once the event loop is done, without Python tearing
down the Qt objects. Everything is already saved by then (aboutToQuit
+33 -8
View File
@@ -5,18 +5,30 @@ standard root and Player interfaces, backed by our Player object. Album art
is exported to a small cache dir so GNOME's media popup can show it
(mpris:artUrl must be a file the notification daemon can read).
"""
import os
import logging
from pathlib import Path
from PyQt6.QtCore import QMetaType, QObject, pyqtSlot, pyqtProperty, pyqtClassInfo
from PyQt6.QtDBus import (
QDBusConnection, QDBusAbstractAdaptor, QDBusArgument, QDBusObjectPath,
QDBusMessage,
)
from lintunes import tagging
try:
from PyQt6.QtDBus import (
QDBusConnection, QDBusAbstractAdaptor, QDBusArgument, QDBusObjectPath,
QDBusMessage,
)
HAVE_DBUS = True
except ImportError: # a Qt built without QtDBus (macOS can be): no MPRIS
HAVE_DBUS = False
# Stand-ins so the adaptor classes below still define; nothing
# registers them, because setup_mpris returns None first.
QDBusConnection = QDBusArgument = QDBusMessage = None
QDBusAbstractAdaptor = QObject
QDBusObjectPath = str
from lintunes import paths, tagging
from lintunes.eventlog import log_control
log = logging.getLogger(__name__)
SERVICE_NAME = "org.mpris.MediaPlayer2.lintunes"
OBJECT_PATH = "/org/mpris/MediaPlayer2"
@@ -25,8 +37,7 @@ ART_CACHE_LIMIT = 50
def _art_cache_dir() -> Path:
base = os.environ.get("XDG_CACHE_HOME", str(Path.home() / ".cache"))
return Path(base) / "lintunes" / "artwork"
return paths.cache_dir() / "artwork"
def export_artwork(track) -> str | None:
@@ -50,6 +61,9 @@ def export_artwork(track) -> str | None:
def invalidate_artwork(track):
"""Drop a track's cached art so the next export re-reads the file (call
after embedding new artwork)."""
if paths.IS_MAC:
from lintunes import nowplaying_mac
nowplaying_mac.invalidate_artwork(track)
if track is None or not track.persistent_id:
return
try:
@@ -68,6 +82,15 @@ def _prune_cache(cache_dir: Path):
def setup_mpris(player, main_window) -> "MprisService | None":
"""The desktop's media keys and now-playing popup. On macOS that is
the system's Now Playing (``nowplaying_mac``), not D-Bus. None when
neither is available; the app runs fine without."""
if paths.IS_MAC:
from lintunes import nowplaying_mac
return nowplaying_mac.setup(player, main_window)
if not HAVE_DBUS:
log.info("mpris: QtDBus isn't available; media keys are off")
return None
bus = QDBusConnection.sessionBus()
if not bus.isConnected():
return None
@@ -279,6 +302,8 @@ def string_array(values) -> QDBusArgument:
"""A D-Bus string array ("as"). A plain Python list of str marshals as
"av", which GDBus consumers validate and reject — see
build_properties_changed and xesam:artist in _metadata."""
if not HAVE_DBUS:
return list(values)
string_id = QMetaType(QMetaType.Type.QString.value).id()
arg = QDBusArgument()
arg.beginArray(string_id)
+233
View File
@@ -0,0 +1,233 @@
"""macOS Now Playing and media keys: the Mac's answer to ``mpris.py``.
``MPNowPlayingInfoCenter`` is what Control Centre's Now Playing tile and
the menu-bar widget read (title, artist, album, length, where the song is
up to, artwork), and ``MPRemoteCommandCenter`` is where the keyboard's
play/pause/next/previous keys, AirPods and the tile's own buttons land.
A Mac sends those keys to whichever app last claimed Now Playing, so this
is the whole of media-key support there; ``MainWindow.eventFilter``'s
in-window keys stay as they are.
pyobjc (``pyobjc-framework-MediaPlayer`` + ``-Cocoa``) is a Mac-only
dependency, imported inside ``setup``: if it is missing the app logs once
and runs without, exactly as Linux does without a session bus.
The command handlers may run on a thread of the system's choosing, so they
only emit ``_command``; the Player is driven from the GUI thread by the
queued slot. The adaptor routes to the same Player methods MPRIS does.
"""
import logging
from PyQt6.QtCore import QObject, pyqtSignal
from lintunes import tagging
from lintunes.eventlog import log_control
log = logging.getLogger(__name__)
# The one live instance, so mpris.invalidate_artwork can reach it.
_live = None
# MPRemoteCommandHandlerStatus / MPNowPlayingPlaybackState
STATUS_SUCCESS = 0
STATUS_NO_SUCH_CONTENT = 100
STATE_PLAYING = 1
STATE_PAUSED = 2
STATE_STOPPED = 3
# (MPRemoteCommandCenter accessor, the name the handler emits)
COMMANDS = (
("playCommand", "play"),
("pauseCommand", "pause"),
("togglePlayPauseCommand", "toggle"),
("stopCommand", "stop"),
("nextTrackCommand", "next"),
("previousTrackCommand", "previous"),
("changePlaybackPositionCommand", "seek"),
)
def setup(player, main_window):
"""A live ``MacNowPlaying``, or None when pyobjc isn't installed or the
framework refuses (the app carries on either way)."""
try:
import MediaPlayer # noqa: F401 — pyobjc-framework-MediaPlayer
except Exception as e: # noqa: BLE001 — ImportError, or a broken install
log.info("Now Playing: pyobjc's MediaPlayer isn't available (%s); "
"media keys are off", e)
return None
try:
import AppKit
except Exception: # noqa: BLE001 — artwork is optional
AppKit = None
global _live
try:
_live = MacNowPlaying(player, main_window, MediaPlayer, AppKit)
return _live
except Exception as e: # noqa: BLE001
log.info("Now Playing: couldn't register with the system: %s", e)
return None
class MacNowPlaying(QObject):
"""Mirrors the Player into the system's Now Playing and routes the
remote commands back. ``mp``/``appkit`` are the pyobjc modules, passed
in so tests can hand it fakes."""
_command = pyqtSignal(str, float)
def __init__(self, player, main_window, mp, appkit=None):
super().__init__()
self._player = player
self._window = main_window
self._mp = mp
self._appkit = appkit
self._handlers = [] # keep the Python callables alive
self._art_track = None # whose artwork object we built
self._artwork = None
self._command.connect(self._run)
center = mp.MPRemoteCommandCenter.sharedCommandCenter()
for accessor, name in COMMANDS:
command = getattr(center, accessor, None)
if command is None:
continue
command = command()
handler = self._handler_for(name)
self._handlers.append(handler)
try:
command.setEnabled_(True)
command.addTargetWithHandler_(handler)
except Exception as e: # noqa: BLE001
log.info("Now Playing: %s unavailable: %s", accessor, e)
player.track_changed.connect(lambda _t: self.update())
player.playing_changed.connect(lambda _p: self.update())
# A seek moves the elapsed time; Now Playing extrapolates the rest
# from the rate, so a jump is the only position change it needs.
self._last_pos = 0
player.position_changed.connect(self._on_position)
self.update()
# -- commands (any thread) -> GUI thread --
def _handler_for(self, name):
def handler(event):
seconds = 0.0
if name == "seek":
try:
seconds = float(event.positionTime())
except Exception: # noqa: BLE001
return STATUS_NO_SUCH_CONTENT
self._command.emit(name, seconds)
return STATUS_SUCCESS
return handler
def _run(self, name: str, seconds: float):
log_control("nowplaying", name)
player = self._player
if name == "play":
player.play()
elif name == "pause":
player.pause()
elif name == "toggle":
player.toggle_play()
elif name == "stop":
player.stop()
elif name == "next":
player.next()
elif name == "previous":
player.previous()
elif name == "seek":
player.seek(int(seconds * 1000))
self.update()
# -- Player -> Now Playing --
def _on_position(self, ms):
ms = int(ms)
# Normal playback steps a few hundred ms at a time; only a jump
# (a seek, a restart) needs telling.
if abs(ms - self._last_pos) > 2000:
self._last_pos = ms
self.update()
else:
self._last_pos = ms
def info(self) -> dict | None:
"""The nowPlayingInfo dictionary for the current state (None when
nothing is loaded)."""
mp = self._mp
track = self._player.current_track
if track is None:
return None
playing = self._player.is_playing()
info = {
mp.MPMediaItemPropertyTitle: track.name or "",
mp.MPMediaItemPropertyArtist: track.artist or "",
mp.MPMediaItemPropertyAlbumTitle: track.album or "",
mp.MPNowPlayingInfoPropertyElapsedPlaybackTime:
self._player.position_ms() / 1000.0,
mp.MPNowPlayingInfoPropertyPlaybackRate: 1.0 if playing else 0.0,
}
length = track.total_time or self._player.duration_ms()
if length:
info[mp.MPMediaItemPropertyPlaybackDuration] = length / 1000.0
artwork = self._artwork_for(track)
if artwork is not None:
info[mp.MPMediaItemPropertyArtwork] = artwork
return info
def update(self):
try:
center = self._mp.MPNowPlayingInfoCenter.defaultCenter()
info = self.info()
center.setNowPlayingInfo_(info)
if info is None:
state = STATE_STOPPED
elif self._player.is_playing():
state = STATE_PLAYING
else:
state = STATE_PAUSED
# macOS only routes the media keys to an app that says it's
# playing (or paused), so this matters as much as the info.
if hasattr(center, "setPlaybackState_"):
center.setPlaybackState_(state)
except Exception as e: # noqa: BLE001 — never break playback for this
log.info("Now Playing: update failed: %s", e)
def _artwork_for(self, track):
if self._appkit is None or not track.location:
return None
if self._art_track == track.track_id:
return self._artwork
self._art_track = track.track_id
self._artwork = None
try:
data = tagging.read_embedded_artwork(track.location)
if not data:
return None
appkit = self._appkit
image = appkit.NSImage.alloc().initWithData_(
appkit.NSData.dataWithBytes_length_(data, len(data)))
if image is None:
return None
self._artwork = self._mp.MPMediaItemArtwork.alloc() \
.initWithBoundsSize_requestHandler_(
image.size(), lambda _size: image)
except Exception as e: # noqa: BLE001
log.info("Now Playing: no artwork for %s: %s", track.location, e)
self._artwork = None
return self._artwork
def invalidate_artwork(self, track=None):
"""Forget the built artwork (after new art is embedded)."""
if track is None or self._art_track == getattr(track, "track_id", None):
self._art_track = None
self._artwork = None
self.update()
def invalidate_artwork(track):
if _live is not None:
_live.invalidate_artwork(track)
+69 -7
View File
@@ -1,14 +1,76 @@
"""Portable track paths.
"""Where LinTunes keeps its machine-local files, per operating system.
Track locations are kept **absolute** in memory (the player, tagging, and art code
all expect real paths), but on disk they are stored **relative to the data dir**.
The data dir and the music live inside one Syncthing-shared tree and move together,
so a relative path resolves correctly on every machine no matter where the tree is
mounted — no per-machine ``music_root`` config is needed at load time.
Linux follows the XDG base directories, exactly as every module did by
hand before the Mac port. macOS uses ``~/Library``. An XDG variable that
is set wins on either system, which is how the tests (and anyone who
wants to) point the app somewhere else.
Nothing here is the synced library data dir: that is ``--data-dir``.
"""
import os
import sys
from pathlib import Path
IS_MAC = sys.platform == "darwin"
# True inside the built LinTunes.app (PyInstaller), False from a checkout.
FROZEN = bool(getattr(sys, "frozen", False))
_MAC_NAME = "LinTunes"
def _base(variable: str, linux_default: str, mac_default: str) -> Path:
"""The app's own folder under one base directory."""
override = os.environ.get(variable)
if override:
return Path(override) / "lintunes"
if IS_MAC:
return Path.home() / mac_default / _MAC_NAME
return Path.home() / linux_default / "lintunes"
def config_dir() -> Path:
"""config.json and other per-machine settings."""
return _base("XDG_CONFIG_HOME", ".config", "Library/Application Support")
def data_dir() -> Path:
"""Things the app installs or keeps for good on this machine: the
cassette folders, the Demucs and Spleeter venvs, downloaded helpers."""
return _base("XDG_DATA_HOME", ".local/share",
"Library/Application Support")
def cache_dir() -> Path:
"""Anything that can be rebuilt: loudness, stems, staged conversions."""
return _base("XDG_CACHE_HOME", ".cache", "Library/Caches")
def mac_tool_dirs() -> list[str]:
"""Where command-line tools live on a Mac that Finder's PATH leaves out.
An app started from Finder gets ``/usr/bin:/bin:/usr/sbin:/sbin``, so
Homebrew's ffmpeg is invisible to ``shutil.which`` unless these are
added (``main`` does that at startup). The app bundle's own helpers
come first.
"""
dirs = []
if FROZEN:
dirs.append(str(Path(sys.executable).resolve().parent))
dirs.append(str(Path(sys.executable).resolve().parent.parent
/ "Resources" / "bin"))
dirs += ["/opt/homebrew/bin", "/usr/local/bin", "/opt/local/bin"]
return dirs
# -- portable track paths (the module's original job, kept as it was) --
#
# Track locations are kept **absolute** in memory (the player, tagging, and art
# code all expect real paths), but on disk they are stored **relative to the
# data dir**. The data dir and the music live inside one Syncthing-shared tree
# and move together, so a relative path resolves correctly on every machine no
# matter where the tree is mounted — no per-machine ``music_root`` config is
# needed at load time.
def to_relative(location: str, data_dir) -> str:
"""Convert an absolute track location to a path relative to ``data_dir``.
+87
View File
@@ -0,0 +1,87 @@
"""Where the Mac app's releases come from, and how versions compare.
A checkout updates itself with git (``updater.py``). The built LinTunes.app
has no checkout, so it asks GitHub's Releases API what the newest release
is, and the status-bar version button offers its page. It never downloads
or replaces the app itself: the app is unsigned, and swapping an unsigned
bundle in place is exactly what Gatekeeper exists to stop.
``GITHUB_REPO`` is the one place the release repository is named, as
``"owner/name"``. Empty means no update checks at all — the GitHub mirror
doesn't exist yet (docs/mac-release.md says how to set it).
Pure Python, no Qt: the PyInstaller spec and build.sh read the bundle id
and app name from here too.
"""
import re
# "owner/name" of the GitHub mirror whose Releases carry the .dmg files.
# Empty = the app never checks for updates.
GITHUB_REPO = ""
# The Mac app's bundle identifier. Info.plist, signing and the keychain
# all use this one string; changing it makes macOS see a different app.
BUNDLE_ID = "org.lintunes.LinTunes"
APP_NAME = "LinTunes"
# Generic on purpose: nothing about the user or this machine.
USER_AGENT = "LinTunes-update-check"
_VERSION = re.compile(r"^\s*v?(\d+)\.(\d+)(?:\.(\d+))?\s*$")
def parse_version(text) -> tuple[int, int, int] | None:
"""``"v0.92.0"`` → ``(0, 92, 0)``; None for anything else (a
pre-release suffix included — those are never offered)."""
if not isinstance(text, str):
return None
m = _VERSION.match(text)
if not m:
return None
return int(m[1]), int(m[2]), int(m[3] or 0)
def is_newer(candidate: str, current: str) -> bool:
"""True when ``candidate`` is a strictly later version than
``current``. Compared as numbers, so 0.100.0 beats 0.99.0."""
a, b = parse_version(candidate), parse_version(current)
return a is not None and b is not None and a > b
def latest_release_url(repo: str = None) -> str | None:
"""The API URL for the newest published, non-pre-release release."""
repo = GITHUB_REPO if repo is None else repo
if not valid_repo(repo):
return None
return f"https://api.github.com/repos/{repo}/releases/latest"
def releases_page(repo: str = None) -> str | None:
repo = GITHUB_REPO if repo is None else repo
if not valid_repo(repo):
return None
return f"https://github.com/{repo}/releases/latest"
def valid_repo(repo) -> bool:
return (isinstance(repo, str)
and re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repo)
is not None)
def parse_latest_release(payload) -> tuple[str, str] | None:
"""``(version, page url)`` from a /releases/latest JSON object, or
None when it isn't a usable release (a draft, a pre-release, a tag
that isn't ``vX.Y.Z``, a page that isn't on github.com)."""
if not isinstance(payload, dict):
return None
if payload.get("draft") or payload.get("prerelease"):
return None
tag = payload.get("tag_name")
version = parse_version(tag)
if version is None:
return None
page = payload.get("html_url")
if not isinstance(page, str) or not page.startswith("https://github.com/"):
return None
return "%d.%d.%d" % version, page
+23 -3
View File
@@ -20,6 +20,8 @@ import os
import ssl
from pathlib import Path
from lintunes import paths
# Where Syncthing keeps config.xml + cert.pem. Newer builds use XDG state, older
# ones ~/.config; the last two are for people who never migrated.
_CONFIG_DIRS = (
@@ -29,13 +31,31 @@ _CONFIG_DIRS = (
"~/.syncthing",
)
# macOS: Syncthing's own default, which the syncthing-macos app and
# Homebrew's syncthing both use. STCONFDIR / STHOMEDIR are how Syncthing is
# pointed elsewhere (docs.syncthing.net/users/config.html), so they come
# first; the Unix locations last, for a Syncthing started with old habits.
_MAC_CONFIG_DIRS = (
"$STCONFDIR",
"$STHOMEDIR",
"~/Library/Application Support/Syncthing",
) + _CONFIG_DIRS
_cache: dict | None = None
def config_dirs() -> tuple[str, ...]:
"""The candidate directories, unexpanded, in the order they're tried."""
return _MAC_CONFIG_DIRS if paths.IS_MAC else _CONFIG_DIRS
def _config_dir() -> Path | None:
for raw in _CONFIG_DIRS:
expanded = Path(os.path.expandvars(raw)).expanduser()
if "$" in str(expanded): # unset XDG_STATE_HOME
for raw in config_dirs():
text = os.path.expandvars(raw)
if not text.strip(): # a variable set to nothing
continue
expanded = Path(text).expanduser()
if "$" in str(expanded): # unset XDG_STATE_HOME / STCONFDIR
continue
if (expanded / "config.xml").is_file():
return expanded
+34
View File
@@ -7,6 +7,11 @@ wrong would mean a slow cross-device copy and, worse, a trashed file the file
manager's "Restore" can't put back, because the recorded original path would sit
on a different filesystem than the trash holding it.
On macOS none of that applies: the Finder's Trash is per-volume too, but it
is the system's to manage (its "Put Back" record lives in a ``.DS_Store``), so
``send_to_trash`` hands the file to ``QFile.moveToTrash``, which asks the
system and reports where the file landed.
Nothing here knows about the library; ``LibraryManager`` is the only caller.
"""
@@ -17,6 +22,8 @@ from datetime import datetime
from pathlib import Path
from urllib.parse import quote, unquote
from lintunes import paths
log = logging.getLogger(__name__)
@@ -29,6 +36,27 @@ def _home_trash() -> Path:
return Path(base) / "Trash"
def _mac_send_to_trash(path: Path) -> Path:
"""The system Trash, through Qt (NSFileManager underneath), so the
Finder's Put Back works. Same contract: TrashError, file untouched."""
from PyQt6.QtCore import QFile
original = path.resolve()
try:
ok, where = QFile.moveToTrash(str(original))
except Exception as e: # noqa: BLE001 — a binding mismatch is still "not trashed"
raise TrashError(f"Could not move {path} to the trash: {e}") from e
if not ok:
raise TrashError(f"Could not move {path} to the trash")
dest = Path(where) if where else None
if dest is None or not dest.exists():
# Trashed, but Qt couldn't say where; the file is gone from its spot
# either way, so report the user's Trash (undo then can't restore).
dest = Path.home() / ".Trash" / original.name
log.info("Trashed %s -> %s", original, dest)
return dest
def _topdir(path: Path) -> Path:
"""The mount point the path lives on."""
current = path if path.is_dir() else path.parent
@@ -120,6 +148,8 @@ def send_to_trash(path: Path) -> Path:
path = Path(path)
if not path.exists():
raise TrashError(f"{path} does not exist")
if paths.IS_MAC:
return _mac_send_to_trash(path)
trash_dir, top = trash_dir_for(path)
files_dir, info_dir = _ensure_trash(trash_dir)
@@ -155,6 +185,8 @@ def restore_from_trash(trashed: Path, original: Path) -> None:
os.rename(trashed, original)
except OSError as e:
raise TrashError(f"Could not restore {trashed} to {original}: {e}") from e
if paths.IS_MAC:
return # no .trashinfo; the Finder forgets a file that left its Trash
info_path = trashed.parent.parent / "info" / f"{trashed.name}.trashinfo"
info_path.unlink(missing_ok=True)
@@ -165,6 +197,8 @@ def original_path(trashed: Path) -> Path | None:
Only used by tests and diagnostics; restoring uses the location the library
already knows.
"""
if paths.IS_MAC:
return None
info_path = Path(trashed).parent.parent / "info" / f"{Path(trashed).name}.trashinfo"
try:
text = info_path.read_text(encoding="utf-8")
+67 -2
View File
@@ -9,14 +9,26 @@ pattern as lastfm.py — and report back through Qt signals.
When the package isn't running from a git checkout (or has no upstream), the
updater disables itself silently and the version display is just a label.
The built Mac app (``paths.FROZEN``) has no checkout, and must never run
git at all — on a Mac without the developer tools, ``/usr/bin/git`` pops
an "install the command line tools" dialog. So it asks GitHub's Releases
API instead (``release_info``) and emits ``release_available``; the version
button opens that release's page. Nothing is downloaded or replaced. With
``release_info.GITHUB_REPO`` empty the app never checks.
"""
import logging
import subprocess
import threading
from pathlib import Path
from PyQt6.QtCore import QObject, QTimer, pyqtSignal
from lintunes import __version__, paths, release_info
log = logging.getLogger(__name__)
FIRST_CHECK_MS = 10 * 1000 # shortly after launch, off the startup path
RECHECK_INTERVAL_MS = 4 * 3600 * 1000 # then every 4 hours
@@ -25,13 +37,18 @@ class Updater(QObject):
update_available = pyqtSignal(int) # commits behind upstream
update_applied = pyqtSignal() # pull succeeded; caller restarts the app
update_failed = pyqtSignal(str)
# The frozen app's path: (newer version, its release page)
release_available = pyqtSignal(str, str)
def __init__(self, parent=None):
def __init__(self, parent=None, release_mode: bool | None = None):
super().__init__(parent)
self._root = str(Path(__file__).resolve().parents[1])
self._busy = False
self._timer = None
self._enabled = None # probed lazily — see enabled
# Releases instead of git: the built app, never a checkout.
self.release_mode = (paths.FROZEN if release_mode is None
else release_mode)
@property
def enabled(self) -> bool:
@@ -42,6 +59,8 @@ class Updater(QObject):
that stall on the main thread before the window was up. First use is
now `_check`, on a background thread.
"""
if self.release_mode:
return release_info.latest_release_url() is not None
if self._enabled is None:
self._enabled = (
self._git("rev-parse", "--show-toplevel") is not None
@@ -51,10 +70,14 @@ class Updater(QObject):
def short_hash(self) -> str | None:
"""The checkout's current commit, for telling builds apart."""
if self.release_mode:
return None
return self._git("rev-parse", "--short", "HEAD")
def start_checking(self):
"""First check shortly after launch, then every few hours."""
if self.release_mode and not self.enabled:
return # no release repo named: the app never checks
QTimer.singleShot(FIRST_CHECK_MS, self.check_async)
self._timer = QTimer(self)
self._timer.setInterval(RECHECK_INTERVAL_MS)
@@ -68,7 +91,8 @@ class Updater(QObject):
threading.Thread(target=self._check, daemon=True).start()
def update_async(self):
if not self.enabled or self._busy:
# The app is never replaced from inside: the button opens the page.
if self.release_mode or not self.enabled or self._busy:
return
self._busy = True
threading.Thread(target=self._update, daemon=True).start()
@@ -76,6 +100,8 @@ class Updater(QObject):
# ---- internals (run on daemon threads) ----
def _check(self):
if self.release_mode:
return self._check_release()
try:
if not self.enabled:
return
@@ -87,6 +113,15 @@ class Updater(QObject):
finally:
self._busy = False
def _check_release(self):
"""Ask GitHub for the newest release; quiet on any failure."""
try:
found = fetch_latest_release()
if found and release_info.is_newer(found[0], __version__):
self.release_available.emit(*found)
finally:
self._busy = False
def _update(self):
try:
proc = subprocess.run(
@@ -120,3 +155,33 @@ class Updater(QObject):
if proc.returncode != 0:
return None
return proc.stdout.strip()
def fetch_latest_release(repo: str | None = None, timeout: float = 20,
get=None) -> tuple[str, str] | None:
"""``(version, page url)`` of the newest GitHub release, or None when
checks are off, the network is down, or the answer is unusable.
Through ``requests`` rather than urllib: it carries certifi's CA
bundle, and a frozen Python's own OpenSSL may know no certificates.
No auth (60 requests an hour per address is plenty for one check
every four hours) and a User-Agent that says nothing about anyone.
"""
url = release_info.latest_release_url(repo)
if url is None:
return None
try:
if get is None:
import requests
get = requests.get
response = get(url, timeout=timeout, headers={
"Accept": "application/vnd.github+json",
"User-Agent": release_info.USER_AGENT,
})
if response.status_code != 200:
log.info("update check: HTTP %s", response.status_code)
return None
return release_info.parse_latest_release(response.json())
except Exception as e: # offline, DNS, bad JSON: all just "no news"
log.info("update check failed: %s", e)
return None
+15 -5
View File
@@ -56,7 +56,7 @@ from urllib.parse import parse_qs, urlsplit
from PyQt6.QtCore import QObject, pyqtSignal
from lintunes import apple_music_link, spotify_link, tagging
from lintunes import apple_music_link, paths, spotify_link, tagging
from lintunes.models.playlist import PlaylistType
log = logging.getLogger(__name__)
@@ -95,10 +95,20 @@ def default_cookies_browser() -> str | None:
"""The browser whose cookies to borrow: the first one with a profile on
this machine, or None when there's nothing to borrow from."""
home = Path.home()
config = Path(os.environ.get("XDG_CONFIG_HOME", str(home / ".config")))
for browser, profile in (("firefox", home / ".mozilla" / "firefox"),
("chromium", config / "chromium"),
("chrome", config / "google-chrome")):
if paths.IS_MAC:
# Safari's cookies need Full Disk Access, so it is never offered.
support = home / "Library" / "Application Support"
candidates = (("firefox", support / "Firefox" / "Profiles"),
("chrome", support / "Google" / "Chrome"),
("brave", support / "BraveSoftware" / "Brave-Browser"),
("edge", support / "Microsoft Edge"),
("chromium", support / "Chromium"))
else:
config = Path(os.environ.get("XDG_CONFIG_HOME", str(home / ".config")))
candidates = (("firefox", home / ".mozilla" / "firefox"),
("chromium", config / "chromium"),
("chrome", config / "google-chrome"))
for browser, profile in candidates:
if profile.is_dir():
return browser
return None