Files
lintunes/lintunes/main.py
T
trav f21c31940f
macOS / Tests (AppleSilicon) (push) Canceled after 0s
macOS / Tests (Intel) (push) Canceled after 0s
macOS / Build (AppleSilicon) (push) Canceled after 0s
macOS / Build (Intel) (push) Canceled after 0s
macOS / Publish the GitHub Release (push) Canceled after 0s
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
2026-11-17 22:41:48 -08:00

308 lines
12 KiB
Python

import argparse
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",
)
parser.add_argument(
"--import-xml",
dest="import_file",
metavar="XML_FILE",
help="Import an iTunes Library XML file and exit",
)
parser.add_argument(
"--music-root",
help="Local directory corresponding to iTunes' Music Folder "
"(the 'iTunes Media' directory)",
)
parser.add_argument(
"--data-dir",
help="Directory holding the lintunes library JSON files",
)
parser.add_argument(
"--save-config",
action="store_true",
help="Persist --music-root/--data-dir as defaults",
)
parser.add_argument(
"files",
nargs="*",
help="Audio files to import into the library on startup",
)
# Let Qt flags like `-platform xcb` pass through to QApplication
args, qt_args = parser.parse_known_args()
config = load_config()
music_root = args.music_root or config.get("music_root")
data_dir = args.data_dir or config.get("data_dir")
if args.save_config and (args.music_root or args.data_dir):
config.update({k: v for k, v in
(("music_root", args.music_root), ("data_dir", args.data_dir))
if v})
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).")
sys.exit(1)
data_dir = Path(data_dir)
if args.import_file:
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
# files are dropped — they were imported on the first launch and
# would be re-imported (duplicated) on every restart otherwise.
argv = [a for a in sys.argv[1:] if a not in args.files]
os.execv(sys.executable,
[sys.executable, "-m", "lintunes.main", *argv])
def run_import(xml_path: Path, music_root: str | None, data_dir: Path):
from lintunes.importers.itunes_importer import import_itunes_xml
from lintunes.storage.json_storage import save_library
if not xml_path.exists():
print(f"Error: File not found: {xml_path}")
sys.exit(1)
if not music_root:
print("Error: --music-root is required for import "
"(the local path of iTunes' 'iTunes Media' folder)")
sys.exit(1)
print(f"Importing from {xml_path}...")
library, report = import_itunes_xml(xml_path, Path(music_root))
print(report.summary())
# The importer has no data dir, so the portable spelling of the music
# folder is filled in here, where we do.
from datetime import datetime, timezone
from lintunes.paths import to_relative
library.music_folder_rel = to_relative(library.music_folder, data_dir)
library.music_folder_set_at = (
datetime.now(timezone.utc).replace(tzinfo=None).isoformat())
# A fresh import is a new library, so it starts with the seed playlists.
from lintunes.seed_playlists import seed_new_library
seed_new_library(library.playlists)
if report.missing_files:
missing_log = data_dir / "import_missing_files.txt"
data_dir.mkdir(parents=True, exist_ok=True)
missing_log.write_text("\n".join(report.missing_files), encoding="utf-8")
print(f"Missing file list written to {missing_log}")
if report.unmapped_locations:
unmapped_log = data_dir / "import_unmapped_locations.txt"
data_dir.mkdir(parents=True, exist_ok=True)
unmapped_log.write_text("\n".join(report.unmapped_locations), encoding="utf-8")
print(f"Unmapped location list written to {unmapped_log}")
print(f"Saving library to {data_dir}...")
save_library(library, data_dir)
print("Import complete!")
# Long enough for the first paint to land before the smart recompute runs.
SMART_RECOMPUTE_DELAY_MS = 50
def run_gui(data_dir: Path, files: list[Path],
qt_args: list[str] | None = None) -> bool:
import logging
logging.basicConfig(level=logging.INFO)
from PyQt6.QtCore import QTimer
from PyQt6.QtWidgets import QApplication
from lintunes import theme
from lintunes.storage.json_storage import load_library
from lintunes.storage.conflict_resolver import resolve_conflicts
from lintunes.library_manager import LibraryManager
from lintunes.preferences import Preferences
from lintunes.lastfm import LastFm
from lintunes.gui.main_window import MainWindow
from lintunes.gui import titlebar
from lintunes.gui.track_table import ClickToJumpScrollStyle
from lintunes.mpris import setup_mpris
from lintunes.sync_watcher import LibrarySyncWatcher
startup_conflicts = resolve_conflicts(data_dir)
# No library.json means a library is being born here (not merely an empty
# one), which is the one moment the seed playlists are added.
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")
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.
# 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)
# Qt's own Wayland title bar is hardcoded white; draw ours instead.
if app.platformName() == "wayland":
titlebar.install(app)
manager = LibraryManager(library, data_dir)
if new_library:
manager.seed_new_library()
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
# the closeEvent path double-calling it is fine.
app.aboutToQuit.connect(window.player.shutdown)
app.aboutToQuit.connect(manager.flush)
# Watch the data dir so another machine's synced-in changes appear live.
watcher = LibrarySyncWatcher(data_dir, window) # noqa: F841 — kept alive by parent
watcher.changed.connect(manager.check_for_external_changes)
window.show()
# Friend sharing's handshake loop — only on the machine that hosts it.
window.cassette.start_if_host()
# Ask where the music goes only once the window is up, so a new user is
# never met by a dialog floating in front of nothing.
QTimer.singleShot(0, window.check_music_folder)
# Rebuild smart-playlist membership from criteria now that the full library
# (and any merged sync conflicts) is loaded. Deferred until after the first
# paint: it's a full pass over every track per smart playlist, and running
# it inline left the compositor without a responsive window.
QTimer.singleShot(SMART_RECOMPUTE_DELAY_MS, manager.recompute_all_smart)
if startup_conflicts:
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
flushed the library, the player shut down), but a normal exit then
frees the QApplication's wrapper in no particular order, and sip touched
a QObject Qt had already deleted: a segfault and a core dump on every
quit (2026-10-27, 2026-11-06; four out of four on the dev library)."""
import logging
logging.shutdown()
for stream in (sys.stdout, sys.stderr):
try:
stream.flush()
except (OSError, ValueError):
pass
os._exit(exit_code)
if __name__ == "__main__":
main()