Files
lintunes/lintunes/main.py
T
trav d93a265c33 v0.87.1: one app icon (lint.jpg, wave's corner radius) on desktop and andTunes 0.4.2; quitting no longer segfaults
The swap-a-PNG icon is gone: scripts/make_icons.py renders packaging/lint.jpg
into packaging/lintunes.png and the andTunes launcher. Quitting ends with
os._exit once aboutToQuit has saved everything — Python's teardown of the
QApplication wrapper segfaulted on every quit.
2026-11-06 02:01:06 -08:00

216 lines
8.5 KiB
Python

import argparse
import os
import sys
from pathlib import Path
from lintunes.config import load_config, save_config
def main():
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:
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):
# 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)
app = QApplication([sys.argv[0]] + (qt_args or []))
app.setApplicationName("LinTunes")
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())
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)
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)
exit_code = app.exec()
if window.restart_requested:
return True # caller re-execs the updated code
leave(exit_code)
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()