diff --git a/.github/workflows/mac.yml b/.github/workflows/mac.yml new file mode 100644 index 0000000..2bc1641 --- /dev/null +++ b/.github/workflows/mac.yml @@ -0,0 +1,176 @@ +# Build LinTunes.app for both kinds of Mac, and publish a release on tags. +# +# tag vX.Y.Z pushed -> test, build both .dmg files, smoke-test them, +# and attach them + SHA256SUMS to the GitHub Release +# manual dispatch -> the same; publishes only when run on a vX.Y.Z tag +# pull request, or a push to master touching the Mac packaging +# -> test and build, artifacts only, nothing published +# +# macOS minutes are expensive on a private repository (docs/mac-release.md), +# which is why an ordinary push to master doesn't build. +name: macOS + +on: + push: + tags: ["v*"] + branches: [master] + paths: + - "packaging/mac/**" + - ".github/workflows/mac.yml" + pull_request: + paths: + - "packaging/mac/**" + - ".github/workflows/mac.yml" + - "setup.py" + - "requirements.txt" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: mac-${{ github.ref }} + cancel-in-progress: ${{ !startsWith(github.ref, 'refs/tags/') }} + +env: + PYTHON_VERSION: "3.13" + +jobs: + test: + name: Tests (${{ matrix.label }}) + strategy: + fail-fast: false + matrix: + include: + - runner: macos-15 # Apple Silicon (arm64) + label: AppleSilicon + - runner: macos-15-intel # Intel (x86_64) + label: Intel + runs-on: ${{ matrix.runner }} + # The suite grew up on Linux, and until the Linux-only tests carry a + # `linux_only` marker that conftest skips on macOS, some will fail + # here. Reported, not blocking: the build below doesn't wait on it. + continue-on-error: true + timeout-minutes: 45 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: ${{ env.PYTHON_VERSION }} + - name: Install + run: | + python -m pip install --upgrade pip + python -m pip install --prefer-binary \ + --only-binary=PyQt6,PyQt6-Qt6,PyQt6-sip,numpy,cryptography,zeroconf,pydantic-core,aiohttp,miniaudio,protobuf \ + -e . pytest + - name: ffmpeg and fpcalc (the pinned ones the app ships) + run: | + export SSL_CERT_FILE="$(python -m certifi)" + python -I packaging/mac/fetch_tools.py --out "$RUNNER_TEMP/tools" + echo "$RUNNER_TEMP/tools" >> "$GITHUB_PATH" + - name: Test suite (headless) + env: + QT_QPA_PLATFORM: offscreen + XDG_CONFIG_HOME: ${{ runner.temp }}/xdg/config + XDG_DATA_HOME: ${{ runner.temp }}/xdg/share + XDG_CACHE_HOME: ${{ runner.temp }}/xdg/cache + run: python -m pytest -q -m "not linux_only" -p no:cacheprovider + + build: + name: Build (${{ matrix.label }}) + strategy: + fail-fast: false + matrix: + include: + - runner: macos-15 + label: AppleSilicon + - runner: macos-15-intel + label: Intel + runs-on: ${{ matrix.runner }} + timeout-minutes: 60 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: ${{ env.PYTHON_VERSION }} + - name: Tag matches __version__ + if: startsWith(github.ref, 'refs/tags/v') + run: | + version="$(sed -n 's/^__version__ = "\(.*\)"$/\1/p' lintunes/__init__.py)" + if [ "v$version" != "$GITHUB_REF_NAME" ]; then + echo "::error::tag $GITHUB_REF_NAME but lintunes/__init__.py says $version" + exit 1 + fi + - name: Build LinTunes.app and the .dmg + env: + PYTHON: python + # Developer ID signing + notarization: inactive until these + # secrets exist (docs/mac-release.md). Empty = ad-hoc signing. + MACOS_CERTIFICATE: ${{ secrets.MACOS_CERTIFICATE }} + MACOS_CERTIFICATE_PASSWORD: ${{ secrets.MACOS_CERTIFICATE_PASSWORD }} + MACOS_SIGNING_IDENTITY: ${{ secrets.MACOS_SIGNING_IDENTITY }} + MACOS_NOTARY_APPLE_ID: ${{ secrets.MACOS_NOTARY_APPLE_ID }} + MACOS_NOTARY_TEAM_ID: ${{ secrets.MACOS_NOTARY_TEAM_ID }} + MACOS_NOTARY_PASSWORD: ${{ secrets.MACOS_NOTARY_PASSWORD }} + run: packaging/mac/build.sh + - name: Launch smoke test + run: packaging/mac/smoke_test.sh build/mac/dist/LinTunes.app 20 + - name: Mount the .dmg and check what's inside + run: | + dmg="$(ls build/mac/LinTunes-*-${{ matrix.label }}.dmg)" + mnt="$(mktemp -d)" + hdiutil attach -nobrowse -readonly -mountpoint "$mnt" "$dmg" + test -d "$mnt/LinTunes.app" + test -L "$mnt/Applications" + codesign --verify --deep --strict "$mnt/LinTunes.app" + hdiutil detach "$mnt" + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: LinTunes-${{ matrix.label }} + path: | + build/mac/LinTunes-*.dmg + build/mac/LinTunes-*.dmg.sha256 + build/mac/pip-freeze-*.txt + if-no-files-found: error + retention-days: 14 + + release: + name: Publish the GitHub Release + needs: build + if: startsWith(github.ref, 'refs/tags/v') + runs-on: ubuntu-latest + permissions: + contents: write # create the release and upload its files + steps: + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: LinTunes-* + path: dist + merge-multiple: true + - name: SHA256SUMS + working-directory: dist + run: | + sha256sum LinTunes-*.dmg > SHA256SUMS + cat SHA256SUMS + - name: Create or update the release + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + TAG: ${{ github.ref_name }} + run: | + notes="LinTunes ${TAG#v} for macOS. + + - Apple Silicon (M1 and later): LinTunes-${TAG#v}-AppleSilicon.dmg + - Intel: LinTunes-${TAG#v}-Intel.dmg + + Not sure which Mac you have? Apple menu > About This Mac: \"Chip: Apple M…\" is Apple Silicon, \"Processor: … Intel …\" is Intel. + + The app is not signed by Apple yet: the first time, macOS will refuse to open it. Open System Settings > Privacy & Security, scroll down, and click Open Anyway. Full instructions: docs/mac.md in the repository. + + Check a download with: shasum -a 256 -c SHA256SUMS --ignore-missing" + if gh release view "$TAG" >/dev/null 2>&1; then + gh release upload "$TAG" dist/LinTunes-*.dmg dist/SHA256SUMS --clobber + else + gh release create "$TAG" dist/LinTunes-*.dmg dist/SHA256SUMS \ + --title "LinTunes ${TAG#v}" --notes "$notes" --verify-tag + fi diff --git a/.gitignore b/.gitignore index 18296ea..4cdc94d 100644 --- a/.gitignore +++ b/.gitignore @@ -25,3 +25,6 @@ itunes-test-library/ # andTunes build output (andtunes/build.py); the shipped APK lives in # lintunes/android/ and *is* committed /andtunes/build/ + +# Mac build output (packaging/mac/build.sh) +/build/ diff --git a/README.md b/README.md index ebfd42c..3a0eb11 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,18 @@ If you see a little asterix in the bottom-left next to the version number it mea Fedora, enable [RPM Fusion](https://rpmfusion.org/Configuration), then run `sudo dnf swap ffmpeg-free ffmpeg --allowerasing`. +## macOS + +There's a Mac version: download `LinTunes--AppleSilicon.dmg` +or `-Intel.dmg` from the project's GitHub Releases page, then drag it to +Applications. It's unsigned, so the first launch needs **Open Anyway** +in System Settings › Privacy & Security. Everything except the Rabbit R1 +features works there. + +- [docs/mac.md](docs/mac.md): installing and using it on a Mac +- [docs/mac-release.md](docs/mac-release.md): how the Mac builds are made and released +- [docs/mac-testing.md](docs/mac-testing.md): the checklist for testing a build on a real Mac + ## Keys _(written by LLM, cleaned up by me)_ diff --git a/docs/mac-release.md b/docs/mac-release.md new file mode 100644 index 0000000..063093b --- /dev/null +++ b/docs/mac-release.md @@ -0,0 +1,209 @@ +# Releasing the Mac app + +Notes for trav. The repo still lives on the Gitea/Forgejo host +(`origin`). GitHub gets a **read-only push mirror** of it, and GitHub +Actions' macOS runners build the two `.dmg` files and attach them to a +GitHub Release. Nothing about the Linux workflow changes: Linux machines +keep updating with `git pull` from `origin`. + +``` +your push ──> origin (Gitea/Forgejo) ──push mirror──> GitHub + └─ tag vX.Y.Z → .github/workflows/mac.yml + → Release vX.Y.Z: two .dmg + SHA256SUMS +``` + +## One-time setup + +### 1. Public or private? + +Make the GitHub repo **public**, for three reasons: + +- **Downloads.** Mac users download from the Releases page. A private + repo's releases are invisible to anyone you haven't invited, and the + app's update check asks GitHub's API without logging in, so it can't see + them either. +- **Cost.** Standard GitHub-hosted runners are **free on public repos**. On + a private repo, GitHub Free includes **$12 a month** of Actions usage. + macOS runners cost **$0.062 a minute** (Linux is $0.006, so a Mac minute + costs about ten Linux minutes). $12 buys about **190 macOS minutes** a + month. One release runs tests and a build on two Macs, roughly 60–80 + minutes in all, so a private repo covers two or three releases a month. + (Prices are from GitHub's billing docs, November 2026.) +- **License.** The .dmg bundles PyQt6, which is GPL-3.0, so LinTunes as + shipped is a GPL combination. Before the first public .dmg, add a + `LICENSE` file (GPL-3.0-or-later fits) to the repo. See + `packaging/mac/THIRD-PARTY.md`. + +A private repo still works for trying the pipeline out. Builds then show +up as workflow artifacts, which only you can download. + +### 2. Create the GitHub repo + +Create an **empty** repository: no README, no license, no .gitignore. The +mirror's first push fills it. Its `owner/name` is what goes into +`GITHUB_REPO` in step 5. + +### 3. A token for the mirror + +On GitHub, go to Settings › Developer settings › **Fine-grained personal +access tokens** › Generate new token: + +- **Repository access:** only the new repo. +- **Permissions:** **Contents: Read and write**, and **Workflows: Read + and write**. GitHub refuses any push that changes a file under + `.github/workflows/` from a token without the Workflows permission. + Metadata: Read is added for you. +- **Expiration:** as long as you're comfortable with. When the token + expires, the mirror stops, so put the date in your calendar. + +(A classic token works too, with the `repo` and `workflow` scopes.) + +### 4. The push mirror on Gitea/Forgejo + +In the repo on the Gitea/Forgejo host, open **Settings › Repository › +Mirror settings** and add a **push mirror**: + +- **Git remote repository URL:** `https://github.com//.git` +- **Username:** your GitHub username. **Password:** the token. +- Tick **Sync when commits are pushed**, and leave a periodic interval as + well (say 8h) as a backstop. +- Click **Synchronize now** once, and check that the code shows up on + GitHub. + +Two things to know about push mirrors: + +- **The mirror force-pushes and prunes.** Anything that exists only on + GitHub is deleted on the next sync: commits, branches **and tags**. Never + edit, commit, tag or merge pull requests on GitHub. In particular, + never let GitHub create a tag (the "create a new tag on publish" box in + the Releases UI, or a workflow that tags). The next sync removes that + tag, and the release on it turns back into a draft. This is why tags + are made where the code lives (below). +- If the Gitea/Forgejo host runs Actions of its own, it may pick up + `.github/workflows/mac.yml` too, and those jobs then sit queued forever + waiting for a macOS runner. If that happens, turn Actions off for this + repo there (Settings › Repository › untick Actions). + +### 5. Name the repo in the app + +In `lintunes/release_info.py`, set: + +```python +GITHUB_REPO = "/" +``` + +While this is empty, the Mac app never checks for updates. Commit and +release as usual. Every Mac build made after that checks. + +## Making a release + +Releasing is **bump, commit, tag, push**. The tag is the only new step: + +```sh +# __version__ in lintunes/__init__.py is already bumped and committed +v="v$(python3 setup.py --version 2>/dev/null | tail -1)" +git tag -a "$v" -m "LinTunes $v" +git push origin master --follow-tags +``` + +Run `git config push.followTags true` once, and a plain `git push` takes +annotated tags along from then on. That keeps the existing habit (each +round ends with a commit and a push), and the round's final step only +gains the `git tag -a`. + +The mirror carries the tag to GitHub, and the tag starts **macOS** +(`.github/workflows/mac.yml`). The workflow: + +1. runs the test suite on both kinds of Mac (reported, not blocking, until + the Linux-only tests are marked); +2. builds both apps with `packaging/mac/build.sh`. It refuses to build if + the tag and `__version__` disagree; +3. starts each app against a throwaway library (`smoke_test.sh`), and + checks the disk image mounts and verifies; +4. creates the GitHub Release `vX.Y.Z` with + `LinTunes-X.Y.Z-AppleSilicon.dmg`, `LinTunes-X.Y.Z-Intel.dmg` and + `SHA256SUMS`. + +It takes around half an hour. Mac apps that are running see the new +release at their next check (a few hours at most) and show the `*`. + +Not every version has to be a Mac release. An untagged version simply +never gets a .dmg. To rebuild a release (say, after a failed run), go to +**Actions › macOS › Run workflow** and pick the tag as the ref. The files +on the existing release are replaced. + +A push to master that touches `packaging/mac/` or the workflow builds +without publishing, so packaging changes get tested. A plain push to +master doesn't build at all, which keeps macOS minutes for releases. + +**Why not tag automatically when `__version__` changes?** A workflow on +GitHub could do that, but the tag would exist only on GitHub, and the next +mirror sync would delete it (see above). Tagging at the source is the only +version that survives the mirror. + +## Turning on Developer ID signing (later) + +Unsigned builds make every Mac user go through **Open Anyway** once. To +stop that: + +1. Join the Apple Developer Program ($99 a year). +2. In Xcode or on developer.apple.com, create a **Developer ID + Application** certificate, and export it with its private key as a + `.p12` with a password. +3. Create an **app-specific password** for your Apple ID at + account.apple.com › Sign-In and Security. +4. On GitHub, add these under Settings › Secrets and variables › Actions: + + | Secret | Value | + |---|---| + | `MACOS_CERTIFICATE` | `base64 -i DeveloperID.p12` (the whole output) | + | `MACOS_CERTIFICATE_PASSWORD` | the .p12's password | + | `MACOS_SIGNING_IDENTITY` | `Developer ID Application: Your Name (TEAMID)` | + | `MACOS_NOTARY_APPLE_ID` | your Apple ID email | + | `MACOS_NOTARY_TEAM_ID` | the 10-character team ID | + | `MACOS_NOTARY_PASSWORD` | the app-specific password | + +The next tagged build signs every binary inside out, with the hardened +runtime and `packaging/mac/entitlements.plist`. It then signs the .dmg, +notarizes it with `notarytool`, and staples the ticket. Without the +secrets, `build.sh` says "Developer ID signing skipped" and signs ad hoc, +as it does today. Once a signed build is confirmed, take the "Open +Anyway" section out of `docs/mac.md`. Also try removing +`disable-library-validation` from the entitlements. + +The signing path has never been run. Expect the first signed build to +need fixes. + +## Building on a Mac by hand + +On any Mac with Python 3.11 or later for that Mac's architecture, plus +Xcode's command line tools (`xcode-select --install`): + +```sh +git clone lintunes && cd lintunes +PYTHON=python3.13 packaging/mac/build.sh +packaging/mac/smoke_test.sh build/mac/dist/LinTunes.app 20 +open build/mac/LinTunes-*.dmg +``` + +Everything goes in `build/mac/`: the venv, the downloaded tools, the +app, and the .dmg with its `.sha256`. A Mac builds only for itself: an +Apple Silicon Mac makes the AppleSilicon dmg, and an Intel Mac makes the +Intel one. + +## Updating what's bundled + +- **ffmpeg / fpcalc**: `packaging/mac/tools.json` pins each download's URL + and SHA-256. To bump one, download the new file, run + `shasum -a 256` on it yourself, compare the result with the publisher's + checksum, then change the URL and hash together. Also update the + versions in `THIRD-PARTY.md`. The ffmpeg builds' publisher stops making + **Intel** release builds from January 2027. Keep the pinned 9.0.2 for + Intel until a replacement is chosen. +- **PyInstaller**: pinned at the top of `build.sh`. +- **Python**: `PYTHON_VERSION` in the workflow. +- **Minimum macOS**: `MINIMUM_MACOS` in `packaging/mac/plist.py`. It + follows PyQt6's macOS wheel tag (14.0 for PyQt6 6.12). +- **The icon**: `python3 scripts/make_icons.py --only mac` rewrites + `packaging/mac/LinTunes.icns` from `packaging/lint.jpg`. Commit the + result. diff --git a/docs/mac-testing.md b/docs/mac-testing.md new file mode 100644 index 0000000..61ccbb2 --- /dev/null +++ b/docs/mac-testing.md @@ -0,0 +1,270 @@ +# Mac test checklist + +This is for a person with a real Mac, testing a LinTunes build from start +to finish. Use **test music only**: a few albums you don't mind being +retagged, moved or trashed. Don't point LinTunes at a music collection +you'd miss. + +Mark every line **✓** (works), **✗** (broken, and say what happened), or +**–** (skipped, and say why). A screenshot helps whenever something looks +wrong (⇧⌘4 selects an area). Send back the whole file. + +| | | +|---|---| +| Tester | | +| Date | | +| LinTunes version (bottom-left corner) | | +| Download (AppleSilicon / Intel .dmg) | | +| Mac model, chip | | +| macOS version | | +| Speakers / Chromecast / AirPlay devices available | | + +To see the app's log, quit LinTunes and start it from Terminal instead: +`/Applications/LinTunes.app/Contents/MacOS/LinTunes`. Copy whatever it +prints around a failure into the notes. + +--- + +## 1. Download and install + +| # | Step | Expect | Result / notes | +|---|---|---|---| +| 1.1 | Download the .dmg for this Mac, and `SHA256SUMS` | | | +| 1.2 | `shasum -a 256 -c SHA256SUMS --ignore-missing` in Downloads | `…dmg: OK` | | +| 1.3 | Open the .dmg | A window with LinTunes and an Applications shortcut | | +| 1.4 | Drag LinTunes to Applications, then eject | Copies, no errors | | +| 1.5 | Double-click LinTunes in Applications | macOS refuses: *"LinTunes" Not Opened*. Note the exact wording. | | +| 1.6 | System Settings › Privacy & Security › Security › **Open Anyway**, then your password | LinTunes opens | | +| 1.7 | Quit, and open it again from Launchpad/Spotlight | Opens with no warning | | +| 1.8 | Get Info on the app in Finder | Version matches, the lint-ball icon, size noted: ____ MB | | +| 1.9 | The Dock icon and the ⌘-Tab icon | The lint-ball icon, not a generic Python one | | +| 1.10 | The app menu (left of File) | Says **LinTunes**, not "Python" | | + +## 2. First run and library setup + +| # | Step | Expect | Result / notes | +|---|---|---|---| +| 2.1 | First launch | The window appears. A library is created in `~/Music/LinTunes`. You're asked where the music should go. | | +| 2.2 | Choose a music folder | Accepted. Nothing is copied yet. | | +| 2.3 | Look in `~/Library/Application Support/LinTunes` | `config.json` exists | | +| 2.4 | Quit and relaunch | Same library, no questions this time | | +| 2.5 | Window: resize, minimize, full screen (green button), zoom | Behaves like a Mac window. Corners and title bar look right in light and dark. | | +| 2.6 | System Settings › Appearance › Dark, then Light | LinTunes follows, or keeps its own theme setting. Note which. | | +| 2.7 | Menu bar: File, Edit, Controls, View, Track, Connections | Present. **Preferences…/Settings…** is in the LinTunes menu (⌘,). **Quit LinTunes** is there too (⌘Q). | | +| 2.8 | Keyboard shortcuts use ⌘ (⌘O, ⌘I, ⌘Z, ⌘B, ⌘L, ⌘N) | Each one works | | +| 2.9 | Connections menu | No Rabbit / andTunes / Shazam entries | | + +## 3. Importing + +| # | Step | Expect | Result / notes | +|---|---|---|---| +| 3.1 | Drag a folder of songs into the window | Copied into the music folder, filed as Artist/Album | | +| 3.2 | File › Add Files to Library… (⌘O) | The file picker opens, and the files are added | | +| 3.3 | Drop an audio file on LinTunes' **Dock icon** while it's running | Imported | | +| 3.4 | Right-click an mp3 in Finder › Open With › LinTunes | Imported (LinTunes may need to be running) | | +| 3.5 | Drag a song onto a playlist in the sidebar | Added at the drop point | | +| 3.6 | Importing an iTunes/Music library: `LinTunes --import-xml "Library.xml" --music-root … --data-dir …` from Terminal (optional) | Imports | | +| 3.7 | Preferences › Importing › compress lossless to MP3, then import a FLAC | Converted to MP3 | | + +## 4. Playback, one format at a time + +Play each one for a few seconds, seek in the middle, and let one play to +the end. + +| # | Format | Plays | Seeks | Duration right | Notes | +|---|---|---|---|---|---| +| 4.1 | MP3 | | | | | +| 4.2 | AAC (.m4a) | | | | | +| 4.3 | Apple Lossless (.m4a) | | | | | +| 4.4 | FLAC | | | | | +| 4.5 | WAV | | | | | +| 4.6 | AIFF | | | | | +| 4.7 | A protected iTunes .m4p (if you have one) | Refused with a message, never a crash | | | | + +| # | Step | Expect | Result / notes | +|---|---|---|---| +| 4.8 | Space, ←/→ | Play/pause, previous/next | | +| 4.9 | Volume slider; per-track volume (Get Info) | Changes the volume | | +| 4.10 | Controls › Normalize Volume on, then play two very different songs | The loudness evens out. No error about ffmpeg. | | +| 4.11 | Shuffle and repeat (off/all/one) | As on Linux | | +| 4.12 | Change the output in System Settings › Sound (e.g. headphones) while playing | Audio follows, or note what happens | | +| 4.13 | Play counts go up after a song finishes | | | + +## 5. Media keys and Now Playing + +| # | Step | Expect | Result / notes | +|---|---|---|---| +| 5.1 | Keyboard ⏯ ⏮ ⏭ keys (F7–F9) with LinTunes in the background | Control LinTunes, not Music.app | | +| 5.2 | Control Center › Now Playing | Shows title, artist, artwork and position | | +| 5.3 | Play/pause/next from Control Center | Works | | +| 5.4 | Seek using the Now Playing scrubber | Works | | +| 5.5 | AirPods/headphone controls (if any) | Work | | +| 5.6 | Lock screen Now Playing | Shows the song | | + +## 6. Trash and Put Back + +| # | Step | Expect | Result / notes | +|---|---|---|---| +| 6.1 | Delete a song from the library (and its file) | Gone from the list. The file is in the **Trash**. | | +| 6.2 | In the Trash, right-click the file › **Put Back** | Returns to its folder | | +| 6.3 | Delete a song whose file is on an external drive | Goes to the Trash (that drive's), and Put Back works | | +| 6.4 | ⌘Z after a delete | The song comes back into the library | | + +## 7. Get Info and tags + +| # | Step | Expect | Result / notes | +|---|---|---|---| +| 7.1 | ⌘I on a song, change title/artist/album/year, OK | Saved. Check the file in Finder's Get Info or another player. | | +| 7.2 | Rename an album | The file moves to the new Artist/Album folder | | +| 7.3 | Edit several songs at once | All changed | | +| 7.4 | Paste artwork (copy an image in Preview, paste in Get Info) | Embedded, shown in the sidebar | | +| 7.5 | Drag an image file onto the artwork square | Embedded | | +| 7.6 | Download Album Art… | Finds covers | | +| 7.7 | Edit the tags of the song that's **playing** | Playback doesn't glitch | | +| 7.8 | Right-click › Calculate BPM | A BPM appears | | + +## 8. Visualizers + +| # | Step | Expect | Result / notes | +|---|---|---|---| +| 8.1 | The transport-bar visualizer during playback | Moves with the music | | +| 8.2 | Each style: bars, radial, oscilloscope, Kaleidostrobe, Lint Oontz | Each draws | | +| 8.3 | Click the visualizer for the **big window**, especially Kaleidostrobe (the OpenGL one) | Smooth, no black window. Note the fps feel. | | +| 8.4 | Big window on a Retina display | Sharp, not blurry or quarter-sized | | +| 8.5 | Preferences › visualizer sync slider | Changes the lag | | + +## 9. Chromecast and AirPlay + +| # | Step | Expect | Result / notes | +|---|---|---|---| +| 9.1 | Connections › Connect to Chromecast… | macOS asks to **find devices on local networks**. Note the exact text. | | +| 9.2 | Allow | Your Chromecasts appear | | +| 9.3 | Cast a song | Plays on the TV/speaker. A firewall prompt about incoming connections may appear: allow it. | | +| 9.4 | Pause/seek/next while casting | Works | | +| 9.5 | Connections › Connect to AirPlay… | AirPlay speakers listed (Apple TV, HomePod, AirPlay speakers) | | +| 9.6 | Play to an AirPlay speaker | Sound comes out, within about 2 s | | +| 9.7 | If you denied the network prompt: System Settings › Privacy & Security › Local Network › LinTunes on | Devices appear after that | | + +## 10. Import from URL + +| # | Step | Expect | Result / notes | +|---|---|---|---| +| 10.1 | Without yt-dlp: File › Import from URL… | A clear message saying yt-dlp is needed (`brew install yt-dlp`) | | +| 10.2 | `brew install yt-dlp`, restart LinTunes, then import a song link | Downloads, imports, and Identify proposes tags | | +| 10.3 | A playlist link | The checklist of songs appears | | +| 10.4 | A Spotify link | Each song is found on YouTube | | + +## 11. Identify Track + +| # | Step | Expect | Result / notes | +|---|---|---|---| +| 11.1 | Preferences: set an AcoustID key, then right-click a song › Identify Track… | Candidates appear. No "fpcalc not found". | | +| 11.2 | Accept a candidate | Tags written | | + +## 12. Export and web mix + +| # | Step | Expect | Result / notes | +|---|---|---|---| +| 12.1 | File › Export Playlist… › folder | Files and an .m3u | | +| 12.2 | Export as a web mix, then open `index.html` in Safari | Plays; previous/next/shuffle work | | +| 12.3 | A playlist with an ALAC song, as a web mix | Converted to FLAC | | +| 12.4 | Upload to web server (only if you have one in `~/.ssh/config`) | Uploads | | +| 12.5 | Right-click › Convert to MP3… on a FLAC | Replaced by an MP3, and the original goes to the Trash | | + +## 13. DJ mode + +| # | Step | Expect | Result / notes | +|---|---|---|---| +| 13.1 | View › DJ Mode | The shelf slides open | | +| 13.2 | Drag a song onto each record | Loads, shows BPM, waveforms | | +| 13.3 | Play both, crossfader, tempo, Keep pitch, Sync, loops | Sound is clean (no crackles). Note any. | | +| 13.4 | Scratch a record; drag a waveform | Works | | +| 13.5 | Air horn, click and hold | Plays | | +| 13.6 | Preferences › DJ › set up **Instant** vocals (download) | Installs. Note how long, and any error. | | +| 13.7 | Vocals slider on a loaded song | Splits, then fades vocals | | +| 13.8 | Preferences › DJ › High quality (Demucs): follow the shown setup | Note what happens | | +| 13.9 | Close DJ mode with a song playing on deck A | The main player carries on | | +| 13.10 | Switch audio output while in DJ mode | Sound follows | | + +## 14. Cassette (sharing with a friend) + +Needs Syncthing (`brew install syncthing && brew services start syncthing`) +and a second person or computer. + +| # | Step | Expect | Result / notes | +|---|---|---|---| +| 14.1 | With Syncthing **not** running: open Cassette | A clear "Syncthing isn't running" message | | +| 14.2 | With Syncthing running: make this Mac the host, then create an invite | An invite code | | +| 14.3 | The friend accepts | Connected | | +| 14.4 | Browse the friend's library; request a song; Save and Close | The song arrives and is imported | | +| 14.5 | Follow a friend's playlist (the UFO) | Plays from the cache | | +| 14.6 | A sync conflict between two of your own computers (optional) | The merge summary shows | | + +## 15. Sleep, quitting, updates + +| # | Step | Expect | Result / notes | +|---|---|---|---| +| 15.1 | Play an album with the display set to sleep in 1–2 minutes | The **Mac** doesn't sleep while music plays (the display may). Check with `pmset -g assertions` in Terminal: a `caffeinate` assertion while playing. | | +| 15.2 | Pause for a while | The assertion goes away | | +| 15.3 | ⌘Q while playing | Quits at once, no "unexpectedly quit" report | | +| 15.4 | Close the window with the red button | Note: does it quit, or stay in the Dock like Music.app? | | +| 15.5 | Relaunch | Same library, playlists, play counts and column widths | | +| 15.6 | Version button in the bottom-left corner | `vX.Y.Z`. If a newer release exists, `*`, and a click opens the release page in your browser. | | +| 15.7 | Force-quit during an import (⌥⌘Esc), then relaunch | The library is intact | | + +--- + + +## 16. Additional checks (merged in) + +### Desktop integration + +- [ ] First launch from Finder with no settings: it starts, makes `~/Music/LinTunes`, and the app menu reads "LinTunes". +- [ ] Preferences (⌘,) and Quit (⌘Q) are in the LinTunes menu. +- [ ] Playing a song: Control Centre's Now Playing shows title, artist, album, cover and a moving progress bar; paused, the time stops. +- [ ] F8 pauses and resumes, F9 / F7 skip, the Now Playing scrubber seeks — also with another app in front. +- [ ] Embedding new art on the playing song updates the Now Playing cover. +- [ ] While playing, `pmset -g assertions` lists `caffeinate`; paused, it's gone. Force-quit while playing: `pgrep caffeinate` finds nothing. +- [ ] Right-click a song › Show in Finder selects the file. +- [ ] Delete a song (move to Trash): it's in the Trash and Put Back works; Edit › Undo brings it back into the library. +- [ ] The delete key (⌫) removes songs from a playlist; context menus show ⌘I / ⌘C / ⌫, never "Ctrl+". +- [ ] ⌘N, ⌘B, ⌘L, ⌘I, ⌘Z, ⌘⇧Z each fire once. Space and ← → play/pause and skip, but not while typing in the search box. +- [ ] Renaming an artist by capitals only ("Rjd2" → "RJD2") leaves the file where it is, with its own name. +- [ ] Connections has no Rabbit, Shazam or andTunes items; Preferences › Appearance has no "Hide the menu bar" row. +- [ ] The look is the Linux one (flat buttons, the app's own scrollbars), not native Mac controls. +- [ ] An mp3 dropped on the Dock icon is imported, with the app running and with it closed. +- [ ] Web-mix upload with only Apple's rsync says to `brew install rsync`; with Homebrew's it uploads. +- [ ] Import from URL after `brew install yt-dlp` downloads; on a YouTube bot check it retries with Firefox or Chrome cookies. + +### Cassette + +- [ ] With the Syncthing app running, Sync Settings shows its version (the key is read from `~/Library/Application Support/Syncthing/config.xml`). Same with Homebrew's `syncthing`. +- [ ] With Syncthing stopped, the status says how to open or get it. +- [ ] An invite and handshake between this Mac and a Linux friend completes. Syncthing accepts the folders under `~/Library/Application Support/LinTunes/cassette/` (the path has a space). +- [ ] Songs with accents in their names (é, ü) arrive and import, both ways. +- [ ] The disk-space verdict looks right; the host name shows without `.local`. + +### DJ mode + +- [ ] Decks play through speakers, headphones and AirPods; switching output while playing follows it. +- [ ] Activity Monitor: LinTunes' CPU with DJ mode open and nothing playing is low. +- [ ] Preferences › DJ › Download Instant Vocal Splitting finishes, and a split puts `.opus` files in `~/Library/Caches/LinTunes/stems`. +- [ ] Download High-Quality Vocal Splitting finishes; splitting an m4a and an mp3 works; the ✕ beside the vocals note stops it. +- [ ] A split is found again after editing the song's tags. BPM is detected on load. + +### AirPlay and Chromecast + +- [ ] The local-network prompt appears once; after Allow, speakers and Chromecasts are listed. +- [ ] AirPlay plays to a speaker of your own; pause, seek and next behave. +- [ ] With `"airplay_backend": "cli"` in config.json the helper downloads and plays. If macOS refuses to run it, note its exact words. +- [ ] Chromecast: the TV plays the song, seeking works, the cover shows. Note whether the firewall prompt blocked the first try. + +--- + +## Anything else + +Note anything that felt un-Mac-like, slow, ugly or confusing, even if it +"worked": + +- diff --git a/docs/mac.md b/docs/mac.md new file mode 100644 index 0000000..f418ec0 --- /dev/null +++ b/docs/mac.md @@ -0,0 +1,142 @@ +# LinTunes on a Mac + +LinTunes started on Linux, and there is now a Mac version. You install it +the usual way, by dragging it to Applications. It needs **macOS 14 Sonoma +or later**. + +## 1. Download the right one + +Every release has two disk images: + +| Your Mac | Download | +|---|---| +| Apple Silicon (M1, M2, M3, M4 and later) | `LinTunes--AppleSilicon.dmg` | +| Intel | `LinTunes--Intel.dmg` | + +To find out which Mac you have, open the Apple menu › **About This +Mac**. If it says **Chip: Apple M…**, you have Apple Silicon. If it says +**Processor: … Intel …**, you have an Intel Mac. + +Releases are on the project's GitHub **Releases** page. The newest one is +at the top. + +## 2. (Optional) Check the download + +Each release also has a file called `SHA256SUMS`. Download it to the same +folder as the .dmg, open Terminal, and run: + +```sh +cd ~/Downloads +shasum -a 256 -c SHA256SUMS --ignore-missing +``` + +If the download is intact, you'll see `LinTunes-…dmg: OK`. + +## 3. Install + +1. Double-click the `.dmg`. A window opens with **LinTunes** and an + **Applications** folder. +2. Drag **LinTunes** onto **Applications**. +3. Eject the disk image (the ⏏ next to it in the Finder sidebar). + +## 4. The first launch: "Open Anyway" + +LinTunes isn't signed by Apple (that costs a yearly fee the project doesn't +pay yet), so macOS won't open it until you say so. You only have to do this +once: + +1. Open **Applications** and double-click **LinTunes**. macOS says + *"LinTunes" Not Opened* (or *can't be opened*). Click **Done**. Don't + choose Move to Trash. +2. Open the Apple menu › **System Settings…** › **Privacy & Security**. +3. Scroll down to the **Security** section. It shows *"LinTunes" was + blocked to protect your Mac.* Click **Open Anyway**. (Some versions + label the button **Open**.) The button only appears for about an hour + after step 1. If it isn't there, do step 1 again. +4. Confirm with **Open Anyway**, then enter your login password. + +From then on LinTunes opens like any other app. + +On macOS 15 Sequoia and later, Control-click › **Open** **no longer** gets +you past this. Use System Settings as described above. + +(If you're comfortable with Terminal, `xattr -dr com.apple.quarantine +/Applications/LinTunes.app` does the same thing.) + +## 5. First run + +When LinTunes opens for the first time, it creates a new library in +**~/Music/LinTunes** and asks where your music should go. To add songs, +drag them into the window, or use **File › Add Files to Library…** (⌘O). You can also +drop audio files onto LinTunes' Dock icon. + +### "Allow LinTunes to find devices on local networks?" + +The first time you open the Chromecast or AirPlay picker (the +**Connections** menu), macOS asks whether LinTunes may use your local +network. Click **Allow**. Without it LinTunes can't see your speakers. +If you said no, change it later under System Settings › **Privacy & +Security › Local Network**. + +If your Mac's firewall is on, macOS may also ask whether LinTunes may +**accept incoming connections** when you cast. A Chromecast fetches the +song from LinTunes, so allow it. + +## What's included, and what's optional + +Included in the app, with nothing extra to install: playback (MP3, AAC/M4A, +Apple Lossless, FLAC, WAV, AIFF), the visualizers, DJ mode, Chromecast, +AirPlay, Identify Track, volume normalization, BPM detection, export, web +mixes, converting to MP3, Cassette, media keys and the Now Playing widget. +LinTunes ships with its own copies of `ffmpeg` and `fpcalc`. + +Optional extras you install yourself (easiest with [Homebrew](https://brew.sh)): + +- **Import from URL** (File menu) needs `yt-dlp`: `brew install yt-dlp`. + It isn't bundled, because YouTube changes often and yt-dlp has to keep + up. Run `brew upgrade yt-dlp` when downloads start failing. +- **Cassette** (sharing with friends) needs + [Syncthing](https://syncthing.net): `brew install syncthing`, then + `brew services start syncthing`. Syncthing is also how a library is kept + in step between computers. +- **DJ mode's vocal slider** needs Instant (Spleeter) or High quality + (Demucs). Set them up in Preferences › DJ, the same as on Linux. +- **Upload a web mix to your server** uses `ssh` and `rsync`, and macOS + already has both. + +Not on the Mac: the **Rabbit R1** features (andTunes, Sync to Rabbit, +Import Shazams). They need the R1 plugged into a Linux machine. + +## Where LinTunes keeps things + +| What | Where | +|---|---| +| Your library (songs list, playlists, play counts, preferences) | `~/Music/LinTunes` unless you chose another folder | +| This Mac's settings (`config.json`), Cassette folders, the DJ vocal-splitter downloads | `~/Library/Application Support/LinTunes` | +| Things that can be rebuilt (loudness, vocal splits, album-art cache) | `~/Library/Caches/LinTunes` | + +To remove LinTunes, drag it from Applications to the Trash. You can also +delete those two `~/Library` folders. Your library folder and your music +are never removed for you. + +## Updates + +LinTunes checks for a new release a little after it starts, and then every +few hours. When one is out, the version number in the bottom-left corner +gets a `*`. Click it and the release page opens in your browser. Download +the new `.dmg` and drag LinTunes to Applications again, replacing the old +one. Your library and settings are kept. If the new version is still +unsigned, macOS may ask for **Open Anyway** again. + +The app never downloads or installs anything by itself. + +## Something wrong? + +[mac-testing.md](mac-testing.md) is the checklist a tester goes through. +When you report a problem, include the LinTunes version (bottom-left +corner), your macOS version, and Apple Silicon or Intel. To get the log, +start LinTunes from Terminal and send what it prints: + +```sh +/Applications/LinTunes.app/Contents/MacOS/LinTunes +``` diff --git a/lintunes/__init__.py b/lintunes/__init__.py index 971d5d7..53626f6 100644 --- a/lintunes/__init__.py +++ b/lintunes/__init__.py @@ -1,3 +1,3 @@ """LinTunes — iTunes-style music library manager and player for Linux.""" -__version__ = "0.96.1" +__version__ = "0.97.0" diff --git a/lintunes/airplay/cli.py b/lintunes/airplay/cli.py index 9455f99..54dd865 100644 --- a/lintunes/airplay/cli.py +++ b/lintunes/airplay/cli.py @@ -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). diff --git a/lintunes/andtunes/art.py b/lintunes/andtunes/art.py index 30a920a..2068e24 100644 --- a/lintunes/andtunes/art.py +++ b/lintunes/andtunes/art.py @@ -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: diff --git a/lintunes/andtunes/sync.py b/lintunes/andtunes/sync.py index 8a5e6b7..202c737 100644 --- a/lintunes/andtunes/sync.py +++ b/lintunes/andtunes/sync.py @@ -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: diff --git a/lintunes/cassette/host.py b/lintunes/cassette/host.py index ea4b4ae..9f1465e 100644 --- a/lintunes/cassette/host.py +++ b/lintunes/cassette/host.py @@ -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]: diff --git a/lintunes/cassette/publish.py b/lintunes/cassette/publish.py index 9f195ba..b132c68 100644 --- a/lintunes/cassette/publish.py +++ b/lintunes/cassette/publish.py @@ -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): diff --git a/lintunes/cassette/service.py b/lintunes/cassette/service.py index 3cace45..73ea0d7 100644 --- a/lintunes/cassette/service.py +++ b/lintunes/cassette/service.py @@ -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") diff --git a/lintunes/cassette/state.py b/lintunes/cassette/state.py index 6896b68..bcdf4cc 100644 --- a/lintunes/cassette/state.py +++ b/lintunes/cassette/state.py @@ -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: diff --git a/lintunes/cassette/syncthing_api.py b/lintunes/cassette/syncthing_api.py index d8e7ea5..a5e2437 100644 --- a/lintunes/cassette/syncthing_api.py +++ b/lintunes/cassette/syncthing_api.py @@ -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.""" diff --git a/lintunes/config.py b/lintunes/config.py index 78cc792..52aa66c 100644 --- a/lintunes/config.py +++ b/lintunes/config.py @@ -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: diff --git a/lintunes/dj/instant.py b/lintunes/dj/instant.py index 7912e09..a24d7a4 100644 --- a/lintunes/dj/instant.py +++ b/lintunes/dj/instant.py @@ -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: diff --git a/lintunes/dj/output.py b/lintunes/dj/output.py index 3325ce4..2338a78 100644 --- a/lintunes/dj/output.py +++ b/lintunes/dj/output.py @@ -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) diff --git a/lintunes/dj/stems.py b/lintunes/dj/stems.py index cd8f073..7c1eb4d 100644 --- a/lintunes/dj/stems.py +++ b/lintunes/dj/stems.py @@ -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///{vocals,no_vocals}.flac`` +``paths.cache_dir()/stems///{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 ``/``; 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 ``/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 ``/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 diff --git a/lintunes/dj/venv_tool.py b/lintunes/dj/venv_tool.py new file mode 100644 index 0000000..787cc60 --- /dev/null +++ b/lintunes/dj/venv_tool.py @@ -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)) diff --git a/lintunes/eventlog.py b/lintunes/eventlog.py index 43a94fd..3a51ba8 100644 --- a/lintunes/eventlog.py +++ b/lintunes/eventlog.py @@ -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" diff --git a/lintunes/export/upload.py b/lintunes/export/upload.py index 6f5ed82..9cb1bed 100644 --- a/lintunes/export/upload.py +++ b/lintunes/export/upload.py @@ -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() diff --git a/lintunes/gui/cassette_dialogs.py b/lintunes/gui/cassette_dialogs.py index a1dc534..c301eba 100644 --- a/lintunes/gui/cassette_dialogs.py +++ b/lintunes/gui/cassette_dialogs.py @@ -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): diff --git a/lintunes/gui/dj_shelf.py b/lintunes/gui/dj_shelf.py index 73af39f..73401e1 100644 --- a/lintunes/gui/dj_shelf.py +++ b/lintunes/gui/dj_shelf.py @@ -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: diff --git a/lintunes/gui/info_dialog.py b/lintunes/gui/info_dialog.py index dd64940..2dd7c82 100644 --- a/lintunes/gui/info_dialog.py +++ b/lintunes/gui/info_dialog.py @@ -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: diff --git a/lintunes/gui/main_window.py b/lintunes/gui/main_window.py index 13a4313..718cd34 100644 --- a/lintunes/gui/main_window.py +++ b/lintunes/gui/main_window.py @@ -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: diff --git a/lintunes/gui/menu_bar.py b/lintunes/gui/menu_bar.py index a93c829..2005623 100644 --- a/lintunes/gui/menu_bar.py +++ b/lintunes/gui/menu_bar.py @@ -7,21 +7,37 @@ follow on Linux. Alt+ 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: diff --git a/lintunes/gui/preferences_dialog.py b/lintunes/gui/preferences_dialog.py index c06a49b..e099706 100644 --- a/lintunes/gui/preferences_dialog.py +++ b/lintunes/gui/preferences_dialog.py @@ -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 diff --git a/lintunes/gui/sync_settings_dialog.py b/lintunes/gui/sync_settings_dialog.py index 90752f4..727354b 100644 --- a/lintunes/gui/sync_settings_dialog.py +++ b/lintunes/gui/sync_settings_dialog.py @@ -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.", diff --git a/lintunes/gui/titlebar.py b/lintunes/gui/titlebar.py index e6e90f1..4b86e66 100644 --- a/lintunes/gui/titlebar.py +++ b/lintunes/gui/titlebar.py @@ -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( diff --git a/lintunes/gui/track_table.py b/lintunes/gui/track_table.py index 7101e1a..aedbdf1 100644 --- a/lintunes/gui/track_table.py +++ b/lintunes/gui/track_table.py @@ -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 diff --git a/lintunes/gui/version_button.py b/lintunes/gui/version_button.py index 88d438a..9f2c243 100644 --- a/lintunes/gui/version_button.py +++ b/lintunes/gui/version_button.py @@ -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", diff --git a/lintunes/importers/lossless.py b/lintunes/importers/lossless.py index c91bf14..f1aaf26 100644 --- a/lintunes/importers/lossless.py +++ b/lintunes/importers/lossless.py @@ -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: diff --git a/lintunes/inhibit.py b/lintunes/inhibit.py index 19d28fe..0377880 100644 --- a/lintunes/inhibit.py +++ b/lintunes/inhibit.py @@ -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 `` 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(): diff --git a/lintunes/library_manager.py b/lintunes/library_manager.py index 3f37b92..ae3679a 100644 --- a/lintunes/library_manager.py +++ b/lintunes/library_manager.py @@ -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: diff --git a/lintunes/loudness.py b/lintunes/loudness.py index d8da6b3..ae5a9c1 100644 --- a/lintunes/loudness.py +++ b/lintunes/loudness.py @@ -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): diff --git a/lintunes/main.py b/lintunes/main.py index 71b1a86..3644094 100644 --- a/lintunes/main.py +++ b/lintunes/main.py @@ -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 diff --git a/lintunes/mpris.py b/lintunes/mpris.py index 20cf175..d9d6080 100644 --- a/lintunes/mpris.py +++ b/lintunes/mpris.py @@ -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) diff --git a/lintunes/nowplaying_mac.py b/lintunes/nowplaying_mac.py new file mode 100644 index 0000000..43fa506 --- /dev/null +++ b/lintunes/nowplaying_mac.py @@ -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) diff --git a/lintunes/paths.py b/lintunes/paths.py index 8d391a0..86a448a 100644 --- a/lintunes/paths.py +++ b/lintunes/paths.py @@ -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``. diff --git a/lintunes/release_info.py b/lintunes/release_info.py new file mode 100644 index 0000000..31a0101 --- /dev/null +++ b/lintunes/release_info.py @@ -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 diff --git a/lintunes/sync_identity.py b/lintunes/sync_identity.py index 6d96f80..8e309cb 100644 --- a/lintunes/sync_identity.py +++ b/lintunes/sync_identity.py @@ -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 diff --git a/lintunes/trash.py b/lintunes/trash.py index c29bd00..9a59fe0 100644 --- a/lintunes/trash.py +++ b/lintunes/trash.py @@ -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") diff --git a/lintunes/updater.py b/lintunes/updater.py index 3559f3c..d5f78ae 100644 --- a/lintunes/updater.py +++ b/lintunes/updater.py @@ -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 diff --git a/lintunes/url_import.py b/lintunes/url_import.py index 98d13a5..880f520 100644 --- a/lintunes/url_import.py +++ b/lintunes/url_import.py @@ -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 diff --git a/packaging/mac/LinTunes.icns b/packaging/mac/LinTunes.icns new file mode 100644 index 0000000..6e845e3 Binary files /dev/null and b/packaging/mac/LinTunes.icns differ diff --git a/packaging/mac/LinTunes.spec b/packaging/mac/LinTunes.spec new file mode 100644 index 0000000..8f1b9a8 --- /dev/null +++ b/packaging/mac/LinTunes.spec @@ -0,0 +1,128 @@ +# -*- mode: python -*- +# PyInstaller spec for LinTunes.app (macOS, windowed, onedir). +# +# Run through packaging/mac/build.sh, which makes the venv, fetches the +# bundled tools and signs the result. By hand, from the repo root: +# pyinstaller --noconfirm --clean packaging/mac/LinTunes.spec +# +# What goes in, and why: +# * every lintunes module (some are imported only inside functions, and +# the Mac-only ones only on a Mac); +# * the package data the app reads through importlib.resources or +# Path(__file__): sounds, web-mix templates, Kaleidostrobe's tables, +# the drag icon, and dj/_spleeter_run.py, which runs *by path* in the +# Spleeter venv's own interpreter, so it must be a plain .py file; +# * NOT the Rabbit R1 parts' data (lintunes/android/andTunes.apk and the +# andtunes button art): the Mac app has no R1 features. +# The bundled ffmpeg/fpcalc are copied in by build.sh after this runs. +import os +import sys +from pathlib import Path + +from PyInstaller.utils.hooks import collect_submodules + +HERE = Path(SPECPATH).resolve() # noqa: F821 — PyInstaller's global +ROOT = HERE.parents[1] +sys.path.insert(0, str(HERE)) +sys.path.insert(0, str(ROOT)) + +import plist # noqa: E402 (packaging/mac/plist.py) +from lintunes import release_info # noqa: E402 + +VERSION = plist.version() +ARCH = os.environ.get("LINTUNES_ARCH") or None # None = this machine's + + +def _optional_submodules(package): + """collect_submodules, tolerating a package that isn't installed + (pyobjc on a machine without it).""" + try: + return collect_submodules(package) + except Exception: # noqa: BLE001 + return [] + + +hiddenimports = [] +# All of lintunes, andtunes included (main_window imports it); only the +# R1's data files are left out, below. +hiddenimports += collect_submodules("lintunes") +for pkg in ("pyatv", "pychromecast", "zeroconf", "mutagen", "casttube", + "MediaPlayer", "AppKit", "Foundation", "objc"): + hiddenimports += _optional_submodules(pkg) +hiddenimports += [ + "PyQt6.QtMultimedia", + "PyQt6.QtOpenGL", + "PyQt6.QtOpenGLWidgets", + "PyQt6.QtSvg", # the DJ shelf's check box art + "numpy", + "requests", + "certifi", +] + +L = ROOT / "lintunes" +datas = [ + (str(L / "sounds" / "tink.wav"), "lintunes/sounds"), + (str(L / "sounds" / "airhorn.mp3"), "lintunes/sounds"), + (str(L / "sounds" / "CREDITS.md"), "lintunes/sounds"), + (str(L / "export" / "templates"), "lintunes/export/templates"), + (str(L / "kaleidostrobe" / "tables.npz"), "lintunes/kaleidostrobe"), + (str(L / "dj" / "_spleeter_run.py"), "lintunes/dj"), + # gui/drag_ghost.py finds it at /../packaging/drag-icon.png + (str(ROOT / "packaging" / "drag-icon.png"), "packaging"), + (str(HERE / "licenses"), "licenses"), + (str(HERE / "THIRD-PARTY.md"), "licenses"), +] + +a = Analysis( # noqa: F821 + [str(HERE / "launch.py")], + pathex=[str(ROOT)], + binaries=[], + datas=datas, + hiddenimports=hiddenimports, + hookspath=[], + runtime_hooks=[str(HERE / "rthook_certifi.py")], + excludes=[ + "tkinter", "_tkinter", + "pytest", "IPython", + # Qt modules nothing imports, in case a hook drags them in + "PyQt6.QtWebEngineCore", "PyQt6.QtWebEngineWidgets", + "PyQt6.QtQuick", "PyQt6.QtQml", "PyQt6.Qt3DCore", + "PyQt6.QtBluetooth", "PyQt6.QtNfc", "PyQt6.QtPdf", + ], + noarchive=False, +) +pyz = PYZ(a.pure) # noqa: F821 + +exe = EXE( # noqa: F821 + pyz, + a.scripts, + [], + exclude_binaries=True, + name=release_info.APP_NAME, + debug=False, + strip=False, + upx=False, # UPX breaks Mach-O signatures + console=False, + # Qt receives the Finder's open-file Apple events itself + # (QFileOpenEvent); PyInstaller's emulation would swallow them. + argv_emulation=False, + target_arch=ARCH, + codesign_identity=None, # build.sh signs the whole bundle + entitlements_file=None, +) +coll = COLLECT( # noqa: F821 + exe, + a.binaries, + a.datas, + strip=False, + upx=False, + name=release_info.APP_NAME, +) +app = BUNDLE( # noqa: F821 + coll, + name=f"{release_info.APP_NAME}.app", + icon=str(HERE / "LinTunes.icns"), + bundle_identifier=release_info.BUNDLE_ID, + version=VERSION, + info_plist=plist.info_plist(VERSION), +) diff --git a/packaging/mac/THIRD-PARTY.md b/packaging/mac/THIRD-PARTY.md new file mode 100644 index 0000000..b6968d9 --- /dev/null +++ b/packaging/mac/THIRD-PARTY.md @@ -0,0 +1,54 @@ +# Third-party software in LinTunes.app + +LinTunes.app is built with PyInstaller and carries the Python libraries +LinTunes depends on, plus two command-line tools. Their license texts are +in `Contents/Resources/licenses/` inside the app. + +## Command-line tools (Contents/MacOS) + +| Tool | Version | Where it comes from | License | +|---|---|---|---| +| `ffmpeg`, `ffprobe` | 9.0.2 | Static build by Martin Riedl, , release builds for macOS arm64 and amd64 | **GPL-3.0-or-later** (configured `--enable-gpl --enable-version3`, with libmp3lame, libopus, libvorbis, x264, x265 and others) | +| `fpcalc` | 1.6.2 | Chromaprint's own release binaries, | LGPL-2.1-or-later as a whole; Chromaprint's own code MIT (`chromaprint-LICENSE.md`) | + +The exact download URLs and their SHA-256 hashes are pinned in +`packaging/mac/tools.json`; `packaging/mac/fetch_tools.py` refuses any file +whose hash differs. + +**Source for the GPL'd ffmpeg binary.** FFmpeg 9.0.2's source is at + (`ffmpeg-9.0.2.tar.xz`), and the script that +built this binary, with every library version it used, is at +. If either goes away, +whoever distributes LinTunes.app must still be able to provide the +corresponding source on request for three years (GPL-3.0 §6) — keep a copy +of both with each release. + +LinTunes runs these as separate programs (it never links them), so their +licenses cover the binaries themselves. + +## Python and libraries bundled by PyInstaller + +| Component | License | +|---|---| +| Python | PSF License | +| PyQt6 | **GPL-3.0** (Riverbank's GPL edition) | +| Qt 6 (from the PyQt6-Qt6 wheel), including Qt Multimedia and the FFmpeg libraries it ships | LGPL-3.0 (FFmpeg libraries in the wheel: LGPL-2.1+) | +| numpy | BSD-3-Clause | +| mutagen | GPL-2.0-or-later | +| requests, certifi | Apache-2.0, MPL-2.0 | +| pychromecast, casttube | MIT | +| pyatv, and its dependencies (aiohttp, cryptography, zeroconf, protobuf, pydantic, srptools, miniaudio, …) | MIT / Apache-2.0 / BSD / LGPL-2.1 (zeroconf) | +| pyobjc | MIT | + +Because PyQt6 and mutagen are GPL, the app as distributed is a GPL +combination: LinTunes itself must be offered under GPL-3.0-compatible terms +for the .dmg to be redistributable (see docs/mac-release.md). + +## Not bundled + +- `yt-dlp` (File › Import from URL): install it yourself, `brew install + yt-dlp`. YouTube changes often enough that a copy frozen inside the app + would stop working within weeks, and the app's own copy can't update + itself inside a signed bundle. +- Syncthing (Cassette), Demucs and Spleeter (DJ vocals): installed + separately, as on Linux. diff --git a/packaging/mac/build.sh b/packaging/mac/build.sh new file mode 100755 index 0000000..942e159 --- /dev/null +++ b/packaging/mac/build.sh @@ -0,0 +1,217 @@ +#!/usr/bin/env bash +# Build LinTunes.app and LinTunes--.dmg. +# +# Runs on a Mac only, and builds for the Mac it runs on (an Apple Silicon +# Mac makes the AppleSilicon dmg, an Intel Mac the Intel one). The same +# script runs in GitHub Actions and on a desk: +# +# packaging/mac/build.sh +# +# Needs: Python 3.11+ for this Mac's architecture (python.org, Homebrew or +# pyenv; set PYTHON=/path/to/python3 to pick one) and Xcode's command line +# tools (codesign, hdiutil, lipo come with macOS / the CLT). No Homebrew +# packages: ffmpeg and fpcalc are downloaded and checked against the +# SHA-256 pinned in tools.json. +# +# Signing. Without secrets the app is ad-hoc signed ("codesign --sign -"), +# which Apple Silicon requires before it will run anything, and users see +# Gatekeeper's "Open Anyway" once (docs/mac.md). With all of these set it +# is signed with a Developer ID, hardened runtime and entitlements.plist, +# then notarized and stapled instead (docs/mac-release.md): +# MACOS_CERTIFICATE base64 of the Developer ID Application .p12 +# MACOS_CERTIFICATE_PASSWORD that .p12's password +# MACOS_SIGNING_IDENTITY e.g. "Developer ID Application: Name (TEAMID)" +# MACOS_NOTARY_APPLE_ID Apple ID used for notarization +# MACOS_NOTARY_TEAM_ID the 10-character team id +# MACOS_NOTARY_PASSWORD an app-specific password for that Apple ID +# +# Output: build/mac/LinTunes--