forked from trav/lintunes
Three things that only ever hurt new users.
The startup font modal is gone. _ensure_now_playing_font ran before
MainWindow existed, so on a machine without Century Gothic the very first
thing LinTunes did was open a parentless dialog demanding a font decision.
theme.NOW_PLAYING_FALLBACKS now picks the closest geometric sans installed
(URW Gothic, the Avant Garde clone CG derives from, leads the chain), and
the choice moved to Preferences ▸ Now-playing font. An uninstalled saved
family falls back to automatic instead of the app default.
A non-iTunes user can finally set their music folder. library.music_folder
was written in exactly one place — the iTunes importer — and with it unset
_music_import_dir fell back to a *relative* Path("Music"), resolved against
a working directory GNOME's dash does not set predictably (see
packaging/install-desktop.sh). Music scattered somewhere unfindable. Now
the first launch asks one plain-language question, Preferences can change
it later, and an import with no folder set refuses rather than guessing.
Picking ~/Music files into ~/Music, not ~/Music/Music.
music_folder is portable at last. It was the only path in the library
stored raw absolute in the *synced* metadata, so machine 2 inherited
machine 1's paths. It is now also stored relative to the data dir, the
same trick Track.location has used all along. The absolute key stays
forever as the shared floor between versions: old code reads it and
behaves exactly as before, and old code that writes the file just drops
the new keys, so no version combination hard-fails.
Two traps worth naming. set_music_folder must call
mark_library_settings_dirty() or reload_from_disk reverts the change on
the next sync tick. And the dirty flag only guards until flush, so a
music_folder_set_at stamp decides adoption semantically — _merge_metadata
picks the whole file by mtime, which moves when someone resizes a column
(the Round 39 lesson, applied to metadata).
Also: correct CLAUDE.md's claim that the importer skips smart playlists —
it imports them; system playlists are what's skipped. README gains a
"never used a terminal?" on-ramp and loses the instruction to hand-write
library_metadata.json before first launch.
Verified against the live 21,490-track library: still resolves (via the
legacy key), metadata untouched, 646 tests pass.
Claude-Session: https://claude.ai/code/session_01G4Z46BMQYS57bcbxWbSS3C
185 lines
7.1 KiB
Python
185 lines
7.1 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())
|
|
|
|
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.track_table import ClickToJumpScrollStyle
|
|
from lintunes.mpris import setup_mpris
|
|
from lintunes.sync_watcher import LibrarySyncWatcher
|
|
|
|
startup_conflicts = resolve_conflicts(data_dir)
|
|
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)
|
|
manager = LibraryManager(library, data_dir)
|
|
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()
|
|
# 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
|
|
sys.exit(exit_code)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|