v0.97.0: macOS port (Round 129): OS-aware paths, config and cookies; Mac now-playing, packaging (PyInstaller .app, dmg build, signing notes, CI workflow) and docs
macOS / Tests (AppleSilicon) (push) Canceled after 0s
macOS / Tests (Intel) (push) Canceled after 0s
macOS / Build (AppleSilicon) (push) Canceled after 0s
macOS / Build (Intel) (push) Canceled after 0s
macOS / Publish the GitHub Release (push) Canceled after 0s
macOS / Tests (AppleSilicon) (push) Canceled after 0s
macOS / Tests (Intel) (push) Canceled after 0s
macOS / Build (AppleSilicon) (push) Canceled after 0s
macOS / Build (Intel) (push) Canceled after 0s
macOS / Publish the GitHub Release (push) Canceled after 0s
This commit is contained in:
@@ -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
|
||||||
@@ -25,3 +25,6 @@ itunes-test-library/
|
|||||||
# andTunes build output (andtunes/build.py); the shipped APK lives in
|
# andTunes build output (andtunes/build.py); the shipped APK lives in
|
||||||
# lintunes/android/ and *is* committed
|
# lintunes/android/ and *is* committed
|
||||||
/andtunes/build/
|
/andtunes/build/
|
||||||
|
|
||||||
|
# Mac build output (packaging/mac/build.sh)
|
||||||
|
/build/
|
||||||
|
|||||||
@@ -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
|
Fedora, enable [RPM Fusion](https://rpmfusion.org/Configuration), then run
|
||||||
`sudo dnf swap ffmpeg-free ffmpeg --allowerasing`.
|
`sudo dnf swap ffmpeg-free ffmpeg --allowerasing`.
|
||||||
|
|
||||||
|
## macOS
|
||||||
|
|
||||||
|
There's a Mac version: download `LinTunes-<version>-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
|
## Keys
|
||||||
|
|
||||||
_(written by LLM, cleaned up by me)_
|
_(written by LLM, cleaned up by me)_
|
||||||
|
|||||||
@@ -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/<owner>/<name>.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 = "<owner>/<name>"
|
||||||
|
```
|
||||||
|
|
||||||
|
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 <origin> 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.
|
||||||
@@ -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 | |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<!-- OTHER AGENTS' CHECKLISTS: the coordinator merges the OS-integration
|
||||||
|
and Cassette/DJ/AirPlay checklists here. Keep the table shape. -->
|
||||||
|
## 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":
|
||||||
|
|
||||||
|
-
|
||||||
+142
@@ -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-<version>-AppleSilicon.dmg` |
|
||||||
|
| Intel | `LinTunes-<version>-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
|
||||||
|
```
|
||||||
@@ -1,3 +1,3 @@
|
|||||||
"""LinTunes — iTunes-style music library manager and player for Linux."""
|
"""LinTunes — iTunes-style music library manager and player for Linux."""
|
||||||
|
|
||||||
__version__ = "0.96.1"
|
__version__ = "0.97.0"
|
||||||
|
|||||||
+71
-27
@@ -26,15 +26,21 @@ import tempfile
|
|||||||
import urllib.request
|
import urllib.request
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
from lintunes import paths
|
||||||
|
|
||||||
VERSION = "0.5.4"
|
VERSION = "0.5.4"
|
||||||
_RELEASE = ("https://github.com/music-assistant/airplay-cli/releases/download/"
|
_RELEASE = ("https://github.com/music-assistant/airplay-cli/releases/download/"
|
||||||
f"v{VERSION}/")
|
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 = {
|
_SHA256 = {
|
||||||
"x86_64": "1ac56a15fb548f07a1dae94be16d4bea308420a0ec0cd04238023e44345fc1c9",
|
"x86_64": "1ac56a15fb548f07a1dae94be16d4bea308420a0ec0cd04238023e44345fc1c9",
|
||||||
"aarch64": "1ce9160a8a9abb1b2263dfbf5ed59551dd1205b2336a024e9e33c903c201a310",
|
"aarch64": "1ce9160a8a9abb1b2263dfbf5ed59551dd1205b2336a024e9e33c903c201a310",
|
||||||
|
"macos-arm64": "5b99e3bf76d20cb31a2f6946e0c9d8bc12e0845d7d66a0ec22a49b5ebbac14b4",
|
||||||
|
"macos-x86_64": "09fd5925787db0cea530d380656b06fa6da89f0da11ef86e1cba1139b3c828fd",
|
||||||
}
|
}
|
||||||
_ARCH_ALIASES = {"amd64": "x86_64", "arm64": "aarch64"}
|
_ARCH_ALIASES = {"amd64": "x86_64", "arm64": "aarch64"}
|
||||||
|
_MAC_ARCH_ALIASES = {"aarch64": "arm64", "amd64": "x86_64"}
|
||||||
|
|
||||||
DOWNLOAD_TIMEOUT_S = 60
|
DOWNLOAD_TIMEOUT_S = 60
|
||||||
|
|
||||||
@@ -44,18 +50,28 @@ class CliUnavailable(RuntimeError):
|
|||||||
|
|
||||||
|
|
||||||
def _arch() -> str | None:
|
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":
|
if platform.system() != "Linux":
|
||||||
return None
|
return None
|
||||||
machine = platform.machine().lower()
|
|
||||||
machine = _ARCH_ALIASES.get(machine, machine)
|
machine = _ARCH_ALIASES.get(machine, machine)
|
||||||
return machine if machine in _SHA256 else None
|
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:
|
def binary_dir() -> Path:
|
||||||
"""Machine-local: a binary for this CPU, never the synced data dir."""
|
"""Machine-local: a binary for this CPU, never the synced data dir."""
|
||||||
base = os.environ.get("XDG_DATA_HOME") or os.path.expanduser(
|
return paths.data_dir() / "bin"
|
||||||
"~/.local/share")
|
|
||||||
return Path(base) / "lintunes" / "bin"
|
|
||||||
|
|
||||||
|
|
||||||
def binary_path() -> Path | None:
|
def binary_path() -> Path | None:
|
||||||
@@ -81,6 +97,37 @@ def _sha256(data: bytes) -> str:
|
|||||||
return hashlib.sha256(data).hexdigest()
|
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:
|
def ensure_binary(fetch=None) -> Path:
|
||||||
"""The helper's path, downloading and verifying it first if needed.
|
"""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:
|
if arch is None:
|
||||||
raise CliUnavailable(
|
raise CliUnavailable(
|
||||||
f"no AirPlay helper for {platform.system()} {platform.machine()}")
|
f"no AirPlay helper for {platform.system()} {platform.machine()}")
|
||||||
fetch = fetch or _fetch
|
return download_verified(_RELEASE + _asset(arch), _SHA256[arch],
|
||||||
name = f"cliairplay-linux-{arch}"
|
binary_path(), fetch, "AirPlay helper")
|
||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
def _fetch(url: str) -> bytes:
|
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()
|
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 ----
|
# ---- the command line ----
|
||||||
|
|
||||||
# RAOP TXT keys the binary takes as their own flags (Music Assistant's set).
|
# RAOP TXT keys the binary takes as their own flags (Music Assistant's set).
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ from pathlib import Path
|
|||||||
from PyQt6.QtCore import QBuffer, QByteArray, QIODevice, Qt
|
from PyQt6.QtCore import QBuffer, QByteArray, QIODevice, Qt
|
||||||
from PyQt6.QtGui import QImage
|
from PyQt6.QtGui import QImage
|
||||||
|
|
||||||
from .. import tagging
|
from .. import paths, tagging
|
||||||
from .layout import album_key
|
from .layout import album_key
|
||||||
|
|
||||||
# The panel is 480 px wide, so a cover never needs to be bigger than that;
|
# 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:
|
def _cache_dir() -> Path:
|
||||||
base = os.environ.get("XDG_CACHE_HOME", str(Path.home() / ".cache"))
|
return paths.cache_dir() / "andtunes-art"
|
||||||
return Path(base) / "lintunes" / "andtunes-art"
|
|
||||||
|
|
||||||
|
|
||||||
def render_jpeg(data: bytes) -> bytes | None:
|
def render_jpeg(data: bytes) -> bytes | None:
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ from pathlib import Path
|
|||||||
|
|
||||||
from PyQt6.QtCore import QObject, pyqtSignal
|
from PyQt6.QtCore import QObject, pyqtSignal
|
||||||
|
|
||||||
from .. import __version__
|
from .. import __version__, paths
|
||||||
from ..device_sync import CHUNK, build_m3u, track_display
|
from ..device_sync import CHUNK, build_m3u, track_display
|
||||||
from ..export import web_support
|
from ..export import web_support
|
||||||
from . import art as art_mod
|
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
|
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.
|
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 paths.cache_dir() / "andtunes-flac" / f"{track.track_id}.flac"
|
||||||
return Path(base) / "lintunes" / "andtunes-flac" / f"{track.track_id}.flac"
|
|
||||||
|
|
||||||
|
|
||||||
def _fresh(cache: Path, src: Path) -> bool:
|
def _fresh(cache: Path, src: Path) -> bool:
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import socket
|
import socket
|
||||||
|
|
||||||
|
from lintunes import paths
|
||||||
from lintunes.config import load_config, save_config
|
from lintunes.config import load_config, save_config
|
||||||
from lintunes.storage.play_journal import machine_id
|
from lintunes.storage.play_journal import machine_id
|
||||||
|
|
||||||
@@ -29,9 +30,13 @@ UNCLAIMED = "unclaimed"
|
|||||||
|
|
||||||
def hostname() -> str:
|
def hostname() -> str:
|
||||||
try:
|
try:
|
||||||
return socket.gethostname() or "this computer"
|
name = socket.gethostname() or "this computer"
|
||||||
except OSError:
|
except OSError:
|
||||||
return "this computer"
|
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]:
|
def host_status(prefs) -> tuple[str, str]:
|
||||||
|
|||||||
@@ -14,6 +14,8 @@ from __future__ import annotations
|
|||||||
import json
|
import json
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
from lintunes import paths
|
||||||
|
|
||||||
FORMAT_VERSION = 1
|
FORMAT_VERSION = 1
|
||||||
INFO_FILE = "cassette.json"
|
INFO_FILE = "cassette.json"
|
||||||
AVATAR_FILE = "avatar.png"
|
AVATAR_FILE = "avatar.png"
|
||||||
@@ -23,6 +25,17 @@ STIGNORE = ".stignore"
|
|||||||
# own .syncthing.*.tmp already.)
|
# own .syncthing.*.tmp already.)
|
||||||
STIGNORE_TEXT = "// written by LinTunes\n*.tmp\n*.part\n"
|
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:
|
def write_bytes_if_changed(path: Path, data: bytes) -> bool:
|
||||||
"""Atomically write ``data`` unless ``path`` already holds exactly it.
|
"""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):
|
def prepare_out_dir(out: Path):
|
||||||
out.mkdir(parents=True, exist_ok=True)
|
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):
|
def publish_intro(out: Path, display_name: str, avatar_source: Path | None):
|
||||||
|
|||||||
@@ -24,12 +24,14 @@ from __future__ import annotations
|
|||||||
import logging
|
import logging
|
||||||
import shutil
|
import shutil
|
||||||
import threading
|
import threading
|
||||||
|
import unicodedata
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import datetime, timedelta, timezone
|
from datetime import datetime, timedelta, timezone
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from PyQt6.QtCore import QObject, pyqtSignal
|
from PyQt6.QtCore import QObject, pyqtSignal
|
||||||
|
|
||||||
|
from lintunes import paths
|
||||||
from lintunes.config import load_config
|
from lintunes.config import load_config
|
||||||
from lintunes.cassette import invite as inv
|
from lintunes.cassette import invite as inv
|
||||||
from lintunes.cassette import publish
|
from lintunes.cassette import publish
|
||||||
@@ -315,6 +317,10 @@ class CassetteService(QObject):
|
|||||||
try:
|
try:
|
||||||
client = self.client()
|
client = self.client()
|
||||||
relative = path.relative_to(in_dir(self.root, token)).as_posix()
|
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)
|
info = client.file_info(friend.in_folder, relative)
|
||||||
except (st.SyncthingError, ValueError):
|
except (st.SyncthingError, ValueError):
|
||||||
return True
|
return True
|
||||||
@@ -480,7 +486,9 @@ class CassetteService(QObject):
|
|||||||
"Syncthing's config.")
|
"Syncthing's config.")
|
||||||
else:
|
else:
|
||||||
status = Status(SYNCTHING_DOWN, "Syncthing isn't running",
|
status = Status(SYNCTHING_DOWN, "Syncthing isn't running",
|
||||||
"Start Syncthing, then press Retry in Sync "
|
st.not_running_hint(
|
||||||
|
"press Retry in Sync Settings ▸ General")
|
||||||
|
or "Start Syncthing, then press Retry in Sync "
|
||||||
"Settings ▸ General.")
|
"Settings ▸ General.")
|
||||||
with self._lock:
|
with self._lock:
|
||||||
changed = self._api.code != status.code
|
changed = self._api.code != status.code
|
||||||
@@ -541,7 +549,7 @@ class CassetteService(QObject):
|
|||||||
and friend.device_id == device_id
|
and friend.device_id == device_id
|
||||||
and client.folder(folder_id) is None):
|
and client.folder(folder_id) is None):
|
||||||
in_path = in_dir(self.root, token)
|
in_path = in_dir(self.root, token)
|
||||||
in_path.mkdir(parents=True, exist_ok=True)
|
publish.prepare_in_dir(in_path)
|
||||||
client.add_folder(
|
client.add_folder(
|
||||||
folder_id, f"LinTunes: from {friend.name}", in_path,
|
folder_id, f"LinTunes: from {friend.name}", in_path,
|
||||||
"receiveonly", [device_id],
|
"receiveonly", [device_id],
|
||||||
@@ -561,7 +569,7 @@ class CassetteService(QObject):
|
|||||||
client.share_folder(invite.folder_id, device_id,
|
client.share_folder(invite.folder_id, device_id,
|
||||||
step="Sharing your folder with your friend")
|
step="Sharing your folder with your friend")
|
||||||
in_path = in_dir(self.root, token)
|
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",
|
client.add_folder(inv.invitee_folder(token), "LinTunes: from a friend",
|
||||||
in_path, "receiveonly", [device_id],
|
in_path, "receiveonly", [device_id],
|
||||||
step="Accepting your friend's folder")
|
step="Accepting your friend's folder")
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
"""Cassette's own state: who my friends are, what I share with each, what I've
|
"""Cassette's own state: who my friends are, what I share with each, what I've
|
||||||
asked each of them for.
|
asked each of them for.
|
||||||
|
|
||||||
It lives in the machine-local cassette root (``~/.local/share/lintunes/
|
It lives in the machine-local cassette root (``paths.data_dir()/cassette/
|
||||||
cassette/state.json``), **not** in the synced data dir: only the host machine
|
state.json``; ``~/.local/share/lintunes/…`` on Linux), **not** in the synced
|
||||||
runs Cassette, the friend folders it describes exist only here, and a second
|
data dir: only the host machine runs Cassette, the friend folders it
|
||||||
copy riding Syncthing would just be a conflict waiting to happen.
|
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``;
|
Plain dataclasses with ``to_dict``/``from_dict``, like ``lintunes/models``;
|
||||||
``save`` is atomic (``json_storage.write_json``).
|
``save`` is atomic (``json_storage.write_json``).
|
||||||
@@ -13,11 +13,11 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import copy
|
import copy
|
||||||
import getpass
|
import getpass
|
||||||
import os
|
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
from lintunes import paths
|
||||||
from lintunes.config import load_config
|
from lintunes.config import load_config
|
||||||
from lintunes.storage.json_storage import read_json, write_json
|
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()
|
override = (load_config().get(ROOT_KEY) or "").strip()
|
||||||
if override:
|
if override:
|
||||||
return Path(override).expanduser()
|
return Path(override).expanduser()
|
||||||
base = os.environ.get("XDG_DATA_HOME", str(Path.home() / ".local/share"))
|
return paths.data_dir() / "cassette"
|
||||||
return Path(base) / "lintunes" / "cassette"
|
|
||||||
|
|
||||||
|
|
||||||
def default_display_name() -> str:
|
def default_display_name() -> str:
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ from pathlib import Path
|
|||||||
|
|
||||||
import requests
|
import requests
|
||||||
|
|
||||||
from lintunes import sync_identity
|
from lintunes import paths, sync_identity
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
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
|
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):
|
class SyncthingError(Exception):
|
||||||
"""A step that failed, and what Syncthing (or the socket) said."""
|
"""A step that failed, and what Syncthing (or the socket) said."""
|
||||||
|
|
||||||
|
|||||||
+3
-3
@@ -1,11 +1,11 @@
|
|||||||
import json
|
import json
|
||||||
import os
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
from lintunes import paths
|
||||||
|
|
||||||
|
|
||||||
def config_path() -> Path:
|
def config_path() -> Path:
|
||||||
base = os.environ.get("XDG_CONFIG_HOME", str(Path.home() / ".config"))
|
return paths.config_dir() / "config.json"
|
||||||
return Path(base) / "lintunes" / "config.json"
|
|
||||||
|
|
||||||
|
|
||||||
def load_config() -> dict:
|
def load_config() -> dict:
|
||||||
|
|||||||
+27
-13
@@ -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
|
The original ``spleeter`` package needs TensorFlow and Python ≤3.11, so this
|
||||||
runs Spleeter's own weights as ONNX through **sherpa-onnx** (onnxruntime, a
|
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
|
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
|
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
|
``airplay/cli.py`` rule. The release's own checksum.txt is stale for this
|
||||||
@@ -18,7 +18,6 @@ import hashlib
|
|||||||
import os
|
import os
|
||||||
import shutil
|
import shutil
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
|
||||||
import tarfile
|
import tarfile
|
||||||
import tempfile
|
import tempfile
|
||||||
import threading
|
import threading
|
||||||
@@ -27,6 +26,10 @@ from pathlib import Path
|
|||||||
|
|
||||||
from PyQt6.QtCore import QObject, pyqtSignal
|
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"
|
SHERPA_VERSION = "2.0.1"
|
||||||
MODEL_URL = ("https://github.com/k2-fsa/sherpa-onnx/releases/download/"
|
MODEL_URL = ("https://github.com/k2-fsa/sherpa-onnx/releases/download/"
|
||||||
"source-separation-models/sherpa-onnx-spleeter-2stems-fp16.tar.bz2")
|
"source-separation-models/sherpa-onnx-spleeter-2stems-fp16.tar.bz2")
|
||||||
@@ -41,8 +44,7 @@ class Cancelled(Exception):
|
|||||||
|
|
||||||
|
|
||||||
def venv_dir() -> Path:
|
def venv_dir() -> Path:
|
||||||
base = os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share")
|
return paths.data_dir() / "spleeter"
|
||||||
return Path(base) / "lintunes" / "spleeter"
|
|
||||||
|
|
||||||
|
|
||||||
def python() -> Path:
|
def python() -> Path:
|
||||||
@@ -66,7 +68,8 @@ def remove():
|
|||||||
|
|
||||||
|
|
||||||
def _fetch(url: str) -> bytes:
|
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()
|
return response.read()
|
||||||
|
|
||||||
|
|
||||||
@@ -114,13 +117,19 @@ class InstantSetup(QObject):
|
|||||||
def _run(self):
|
def _run(self):
|
||||||
try:
|
try:
|
||||||
venv = venv_dir()
|
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():
|
if not python().is_file():
|
||||||
self.progress.emit("Making its own Python environment…")
|
self.progress.emit("Making its own Python environment…")
|
||||||
venv.parent.mkdir(parents=True, exist_ok=True)
|
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.progress.emit("Downloading sherpa-onnx…")
|
||||||
self._call([str(python()), "-m", "pip", "install", "--quiet",
|
self._call(venv_tool.install_command(
|
||||||
f"sherpa-onnx=={SHERPA_VERSION}", "numpy"])
|
venv, [f"sherpa-onnx=={SHERPA_VERSION}", "numpy"]), env)
|
||||||
self.progress.emit("Downloading the Spleeter models…")
|
self.progress.emit("Downloading the Spleeter models…")
|
||||||
install_models()
|
install_models()
|
||||||
except (OSError, subprocess.SubprocessError) as e:
|
except (OSError, subprocess.SubprocessError) as e:
|
||||||
@@ -129,8 +138,9 @@ class InstantSetup(QObject):
|
|||||||
self.finished.emit()
|
self.finished.emit()
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _call(cmd):
|
def _call(cmd, env=None):
|
||||||
done = subprocess.run(cmd, capture_output=True, text=True, timeout=1800)
|
done = subprocess.run(cmd, capture_output=True, text=True, timeout=1800,
|
||||||
|
env=env)
|
||||||
if done.returncode != 0:
|
if done.returncode != 0:
|
||||||
lines = (done.stderr or done.stdout).strip().splitlines()
|
lines = (done.stderr or done.stdout).strip().splitlines()
|
||||||
raise OSError(lines[-1] if lines else f"{cmd[2]} failed")
|
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."""
|
``out_dir`` (blocking). Raises OSError, or Cancelled."""
|
||||||
if not available():
|
if not available():
|
||||||
raise OSError("instant vocal splitting isn't set up on this computer")
|
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)],
|
[str(python()), "-I", str(RUNNER), str(model_dir()), str(threads()), path, str(out_dir)],
|
||||||
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True,
|
5)
|
||||||
preexec_fn=lambda: os.nice(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:
|
if cancel is not None:
|
||||||
def watch():
|
def watch():
|
||||||
while process.poll() is None:
|
while process.poll() is None:
|
||||||
|
|||||||
+12
-1
@@ -13,6 +13,7 @@ import numpy as np
|
|||||||
from PyQt6.QtCore import QObject, QThread, QTimer, pyqtSignal, pyqtSlot
|
from PyQt6.QtCore import QObject, QThread, QTimer, pyqtSignal, pyqtSlot
|
||||||
from PyQt6.QtMultimedia import QAudio, QAudioFormat, QAudioSink, QMediaDevices
|
from PyQt6.QtMultimedia import QAudio, QAudioFormat, QAudioSink, QMediaDevices
|
||||||
|
|
||||||
|
from lintunes import paths
|
||||||
from lintunes.dj.audio import CHANNELS, RATE
|
from lintunes.dj.audio import CHANNELS, RATE
|
||||||
|
|
||||||
BUFFER_MS = 100
|
BUFFER_MS = 100
|
||||||
@@ -20,6 +21,15 @@ TICK_MS = 5
|
|||||||
BYTES_PER_FRAME = 2 * CHANNELS
|
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):
|
class _Pump(QObject):
|
||||||
failed = pyqtSignal(str)
|
failed = pyqtSignal(str)
|
||||||
|
|
||||||
@@ -52,7 +62,8 @@ class _Pump(QObject):
|
|||||||
fmt.setChannelCount(CHANNELS)
|
fmt.setChannelCount(CHANNELS)
|
||||||
fmt.setSampleFormat(QAudioFormat.SampleFormat.Int16)
|
fmt.setSampleFormat(QAudioFormat.SampleFormat.Int16)
|
||||||
device = QMediaDevices.defaultAudioOutput()
|
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")
|
self.failed.emit("this computer's sound output can't play 44.1 kHz stereo")
|
||||||
return False
|
return False
|
||||||
self.sink = QAudioSink(device, fmt)
|
self.sink = QAudioSink(device, fmt)
|
||||||
|
|||||||
+99
-12
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Nothing separates a voice from a mix in real time on a laptop, so a song is
|
Nothing separates a voice from a mix in real time on a laptop, so a song is
|
||||||
split once, in the background, and kept:
|
split once, in the background, and kept:
|
||||||
``$XDG_CACHE_HOME/lintunes/stems/<key>/<model>/{vocals,no_vocals}.flac``
|
``paths.cache_dir()/stems/<key>/<model>/{vocals,no_vocals}.opus``
|
||||||
(machine-local, never the synced data dir). A cached song's slider works the
|
(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
|
moment it loads, and a deck uses the best split it finds whatever model made
|
||||||
it. (Round 93's first splits sit directly in ``<key>/``; they were htdemucs.)
|
it. (Round 93's first splits sit directly in ``<key>/``; they were htdemucs.)
|
||||||
@@ -20,8 +20,8 @@ set; this machine's disk, so not a synced pref): after each split, the songs
|
|||||||
used longest ago go first. Using a split (``cached``) counts as using it.
|
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
|
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``
|
~1 GB, so it lives in its own venv at ``paths.data_dir()/demucs``
|
||||||
(``setup_command`` makes it), and LinTunes runs ``<venv>/bin/python -m
|
(``setup_command`` makes it on Linux; on a Mac ``DemucsSetup``, with uv), and LinTunes runs ``<venv>/bin/python -m
|
||||||
demucs``. It is *the* CPU hog in LinTunes (Round 94: htdemucs took 29 s for
|
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
|
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
|
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 hashlib
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
|
import platform
|
||||||
import re
|
import re
|
||||||
import shutil
|
import shutil
|
||||||
import subprocess
|
import subprocess
|
||||||
@@ -49,8 +50,9 @@ from pathlib import Path
|
|||||||
|
|
||||||
from PyQt6.QtCore import QObject, pyqtSignal
|
from PyQt6.QtCore import QObject, pyqtSignal
|
||||||
|
|
||||||
|
from lintunes import paths
|
||||||
from lintunes.config import load_config
|
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.
|
# 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
|
# Measured on this laptop (Round 94, 40 s of audio, 2 threads): htdemucs
|
||||||
@@ -82,8 +84,7 @@ class Cancelled(Exception):
|
|||||||
|
|
||||||
|
|
||||||
def venv_dir() -> Path:
|
def venv_dir() -> Path:
|
||||||
base = os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share")
|
return paths.data_dir() / "demucs"
|
||||||
return Path(base) / "lintunes" / "demucs"
|
|
||||||
|
|
||||||
|
|
||||||
def python() -> Path:
|
def python() -> Path:
|
||||||
@@ -96,11 +97,96 @@ def available() -> bool:
|
|||||||
|
|
||||||
def setup_command() -> str:
|
def setup_command() -> str:
|
||||||
"""What makes the venv, for the "not set up" message."""
|
"""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()
|
v = venv_dir()
|
||||||
return (f"python3 -m venv {v} && {v}/bin/pip install torch --index-url "
|
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")
|
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:
|
def instant_available() -> bool:
|
||||||
return instant.available()
|
return instant.available()
|
||||||
|
|
||||||
@@ -146,8 +232,7 @@ def threads(gentle: bool) -> int:
|
|||||||
|
|
||||||
|
|
||||||
def cache_root() -> Path:
|
def cache_root() -> Path:
|
||||||
base = os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache")
|
return paths.cache_dir() / "stems"
|
||||||
return Path(base) / "lintunes" / "stems"
|
|
||||||
|
|
||||||
|
|
||||||
CACHE_LIMIT_KEY = "dj_stem_cache_gb"
|
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
|
model = model if model in MODELS else DEFAULT_MODEL
|
||||||
work = Path(tempfile.mkdtemp(prefix="lintunes-stems-"))
|
work = Path(tempfile.mkdtemp(prefix="lintunes-stems-"))
|
||||||
count = str(threads(gentle))
|
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
|
niceness = 19 if gentle else 10
|
||||||
try:
|
try:
|
||||||
cmd = ([str(python()), "-m", "demucs", "--two-stems=vocals"] + _ARGS[model]
|
cmd, preexec = venv_tool.niced(
|
||||||
+ ["--flac", "-o", str(work), path])
|
[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,
|
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:
|
if cancel is not None:
|
||||||
def watch():
|
def watch():
|
||||||
# Demucs can go seconds without a progress line (loading the
|
# Demucs can go seconds without a progress line (loading the
|
||||||
|
|||||||
@@ -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))
|
||||||
@@ -11,12 +11,20 @@ import logging
|
|||||||
import time
|
import time
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
from lintunes import paths
|
||||||
|
|
||||||
log = logging.getLogger("lintunes.control")
|
log = logging.getLogger("lintunes.control")
|
||||||
|
|
||||||
_MAX_BYTES = 1_000_000
|
_MAX_BYTES = 1_000_000
|
||||||
|
|
||||||
|
|
||||||
def _log_path() -> Path:
|
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"
|
return Path.home() / ".cache" / "lintunes" / "control-events.log"
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -33,6 +33,8 @@ from pathlib import Path
|
|||||||
|
|
||||||
from PyQt6.QtCore import QObject, pyqtSignal
|
from PyQt6.QtCore import QObject, pyqtSignal
|
||||||
|
|
||||||
|
from lintunes import paths
|
||||||
|
|
||||||
HOST_KEY = "webmix_host"
|
HOST_KEY = "webmix_host"
|
||||||
PATH_KEY = "webmix_path"
|
PATH_KEY = "webmix_path"
|
||||||
|
|
||||||
@@ -83,8 +85,7 @@ def remote_dir(path: str, slug: str) -> str:
|
|||||||
|
|
||||||
|
|
||||||
def staging_root() -> Path:
|
def staging_root() -> Path:
|
||||||
base = os.environ.get("XDG_CACHE_HOME", str(Path.home() / ".cache"))
|
return paths.cache_dir() / "webmix"
|
||||||
return Path(base) / "lintunes" / "webmix"
|
|
||||||
|
|
||||||
|
|
||||||
def reset_staging(slug: str) -> Path:
|
def reset_staging(slug: str) -> Path:
|
||||||
@@ -128,6 +129,37 @@ def _missing_tool(name: str) -> str:
|
|||||||
f"the server.")
|
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):
|
class _ProcessWorker(QObject):
|
||||||
"""One subprocess on a daemon thread; cancel() kills it."""
|
"""One subprocess on a daemon thread; cancel() kills it."""
|
||||||
|
|
||||||
@@ -224,6 +256,10 @@ class UploadWorker(_ProcessWorker):
|
|||||||
if shutil.which("rsync") is None:
|
if shutil.which("rsync") is None:
|
||||||
self.failed.emit(_missing_tool("rsync"))
|
self.failed.emit(_missing_tool("rsync"))
|
||||||
return
|
return
|
||||||
|
problem = mac_rsync_problem()
|
||||||
|
if problem:
|
||||||
|
self.failed.emit(problem)
|
||||||
|
return
|
||||||
proc = self._spawn(rsync_command(self._host, self._local, self._rdir))
|
proc = self._spawn(rsync_command(self._host, self._local, self._rdir))
|
||||||
if proc is None:
|
if proc is None:
|
||||||
self.cancelled.emit()
|
self.cancelled.emit()
|
||||||
|
|||||||
@@ -21,6 +21,9 @@ def failure_text(exc: Exception) -> str:
|
|||||||
return str(exc)
|
return str(exc)
|
||||||
if isinstance(exc, st.SyncthingError):
|
if isinstance(exc, st.SyncthingError):
|
||||||
if exc.kind == st.NOT_RUNNING:
|
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 "
|
return (f"{exc.step} failed: Syncthing isn't running. Start "
|
||||||
f"Syncthing and try again.")
|
f"Syncthing and try again.")
|
||||||
if exc.kind in (st.BAD_KEY, st.NO_KEY):
|
if exc.kind in (st.BAD_KEY, st.NO_KEY):
|
||||||
|
|||||||
@@ -126,8 +126,8 @@ def _check_svg() -> str:
|
|||||||
if _CHECK_SVG is None:
|
if _CHECK_SVG is None:
|
||||||
import os
|
import os
|
||||||
import tempfile
|
import tempfile
|
||||||
base = os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache")
|
from lintunes import paths
|
||||||
folder = os.path.join(base, "lintunes")
|
folder = str(paths.cache_dir())
|
||||||
try:
|
try:
|
||||||
os.makedirs(folder, exist_ok=True)
|
os.makedirs(folder, exist_ok=True)
|
||||||
except OSError:
|
except OSError:
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ from lintunes import tagging
|
|||||||
from lintunes.gui.art_ops import embed_artwork
|
from lintunes.gui.art_ops import embed_artwork
|
||||||
from lintunes.player import VOLUME_ADJUSTMENT_MAX
|
from lintunes.player import VOLUME_ADJUSTMENT_MAX
|
||||||
from lintunes.gui.file_filters import IMAGE_FILTER
|
from lintunes.gui.file_filters import IMAGE_FILTER
|
||||||
|
from lintunes.gui.track_table import key_hint
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -30,7 +31,7 @@ PASTE_RETRY_MS = 300
|
|||||||
# compare covers; it just offers the paste.
|
# compare covers; it just offers the paste.
|
||||||
MULTI_ART_READ_LIMIT = 100
|
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"
|
HINT_STAGED = "New artwork — saved when you click OK"
|
||||||
|
|
||||||
|
|
||||||
@@ -196,7 +197,7 @@ class ArtSquare(QLabel):
|
|||||||
|
|
||||||
def _show_menu(self, pos):
|
def _show_menu(self, pos):
|
||||||
menu = QMenu(self)
|
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…")
|
choose = menu.addAction("Choose File…")
|
||||||
chosen = menu.exec(self.mapToGlobal(pos))
|
chosen = menu.exec(self.mapToGlobal(pos))
|
||||||
if chosen is paste:
|
if chosen is paste:
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ from PyQt6.QtWidgets import (
|
|||||||
from PyQt6.QtCore import QRect, Qt, QEvent, QObject, QTimer, pyqtSignal
|
from PyQt6.QtCore import QRect, Qt, QEvent, QObject, QTimer, pyqtSignal
|
||||||
from PyQt6.QtGui import QAction, QKeySequence
|
from PyQt6.QtGui import QAction, QKeySequence
|
||||||
|
|
||||||
|
from lintunes import paths as os_paths
|
||||||
from lintunes import (bpm_detect, device_sync, loudness, music_folder, shazam,
|
from lintunes import (bpm_detect, device_sync, loudness, music_folder, shazam,
|
||||||
tagging, theme, url_import)
|
tagging, theme, url_import)
|
||||||
from lintunes import playlist_art
|
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_export_action)
|
||||||
file_menu.aboutToShow.connect(self._refresh_url_import_action)
|
file_menu.aboutToShow.connect(self._refresh_url_import_action)
|
||||||
file_menu.addSeparator()
|
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")
|
edit_menu = bar.addMenu("&Edit")
|
||||||
self._undo_action = self._add_action(
|
self._undo_action = self._add_action(
|
||||||
@@ -538,7 +542,9 @@ class MainWindow(QMainWindow):
|
|||||||
QKeySequence("Ctrl+Shift+Z"),
|
QKeySequence("Ctrl+Shift+Z"),
|
||||||
])
|
])
|
||||||
edit_menu.addSeparator()
|
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._manager.undo_stack.changed.connect(self._refresh_undo_actions)
|
||||||
self._refresh_undo_actions()
|
self._refresh_undo_actions()
|
||||||
|
|
||||||
@@ -590,7 +596,8 @@ class MainWindow(QMainWindow):
|
|||||||
self._full_sync_action = self._add_action(
|
self._full_sync_action = self._add_action(
|
||||||
connections_menu, "Full Rabbit Sync", "", self._full_rabbit_sync)
|
connections_menu, "Full Rabbit Sync", "", self._full_rabbit_sync)
|
||||||
self._full_sync_action.setEnabled(False)
|
self._full_sync_action.setEnabled(False)
|
||||||
self._add_action(connections_menu, "Rabbit Sync Settings…", "",
|
self._sync_settings_action = self._add_action(
|
||||||
|
connections_menu, "Rabbit Sync Settings…", "",
|
||||||
self._show_device_sync_settings)
|
self._show_device_sync_settings)
|
||||||
self._install_action = self._add_action(
|
self._install_action = self._add_action(
|
||||||
connections_menu, "Install andTunes on Rabbit…", "",
|
connections_menu, "Install andTunes on Rabbit…", "",
|
||||||
@@ -598,6 +605,14 @@ class MainWindow(QMainWindow):
|
|||||||
self._shazam_action = self._add_action(
|
self._shazam_action = self._add_action(
|
||||||
connections_menu, "Import Shazams…", "",
|
connections_menu, "Import Shazams…", "",
|
||||||
lambda: self._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
|
# "Sync Playlist to Rabbit (Auxio)" was retired in Round 51, once
|
||||||
# andTunes could play what it syncs. device_sync's helpers stay: the
|
# andTunes could play what it syncs. device_sync's helpers stay: the
|
||||||
# export and andTunes code import them.
|
# export and andTunes code import them.
|
||||||
@@ -669,12 +684,14 @@ class MainWindow(QMainWindow):
|
|||||||
def _refresh_connection_actions(self):
|
def _refresh_connection_actions(self):
|
||||||
# An export in flight owns the same status-bar widgets, so it blocks
|
# An export in flight owns the same status-bar widgets, so it blocks
|
||||||
# a sync just as another sync would.
|
# a sync just as another sync would.
|
||||||
|
if not os_paths.IS_MAC: # no Rabbit on a Mac: never probe for one
|
||||||
self._devices.probe()
|
self._devices.probe()
|
||||||
self._refresh_device_actions()
|
self._refresh_device_actions()
|
||||||
self._cassette.refresh_menu()
|
self._cassette.refresh_menu()
|
||||||
|
if not os_paths.IS_MAC:
|
||||||
# Enabled whenever there's an APK to offer; the click finds the
|
# 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
|
# Rabbit (adb or MTP) and says so if it can't — cheaper than
|
||||||
# adb on every menu open.
|
# asking adb on every menu open.
|
||||||
self._install_action.setEnabled(
|
self._install_action.setEnabled(
|
||||||
andtunes_install.bundled_apk() is not None
|
andtunes_install.bundled_apk() is not None
|
||||||
and not (self._install_worker is not None
|
and not (self._install_worker is not None
|
||||||
@@ -848,6 +865,8 @@ class MainWindow(QMainWindow):
|
|||||||
def _refresh_device_actions(self):
|
def _refresh_device_actions(self):
|
||||||
"""Sync Music / Full Rabbit Sync from the watcher's cached answer — never a fresh
|
"""Sync Music / Full Rabbit Sync from the watcher's cached answer — never a fresh
|
||||||
look at the mount, which is what froze the menu."""
|
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
|
busy = self._busy_worker() is not None
|
||||||
if self._devices.state == device_sync.STUCK:
|
if self._devices.state == device_sync.STUCK:
|
||||||
# Enabled: the click explains and offers the reset.
|
# 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"
|
where = "moved to Trash" if delete_files else "file kept"
|
||||||
self.statusBar().showMessage(
|
self.statusBar().showMessage(
|
||||||
f"Removed {len(removed)} song(s) from your library "
|
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:
|
if failures:
|
||||||
QMessageBox.warning(
|
QMessageBox.warning(
|
||||||
self, "Couldn't delete",
|
self, "Couldn't delete",
|
||||||
@@ -2660,8 +2680,10 @@ class MainWindow(QMainWindow):
|
|||||||
QMessageBox.warning(
|
QMessageBox.warning(
|
||||||
self, "Identify Track",
|
self, "Identify Track",
|
||||||
"Track identification needs the fpcalc tool from Chromaprint.\n\n"
|
"Track identification needs the fpcalc tool from Chromaprint.\n\n"
|
||||||
|
+ ("Install it (Homebrew: brew install chromaprint) and try "
|
||||||
|
"again." if os_paths.IS_MAC else
|
||||||
"Install it (Fedora: chromaprint-tools, Debian: "
|
"Install it (Fedora: chromaprint-tools, Debian: "
|
||||||
"libchromaprint-tools) and try again.")
|
"libchromaprint-tools) and try again."))
|
||||||
return
|
return
|
||||||
api_key = self._prefs.acoustid.get("api_key", "").strip()
|
api_key = self._prefs.acoustid.get("api_key", "").strip()
|
||||||
if not api_key:
|
if not api_key:
|
||||||
|
|||||||
@@ -7,21 +7,37 @@ follow on Linux. Alt+<letter> while it's hidden opens that menu at once.
|
|||||||
Qt disables a hidden menu bar's shortcuts along with it, so every action in
|
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
|
it is also added to the window (`register_shortcuts`), or Ctrl+N and the rest
|
||||||
would stop working the moment the bar hides.
|
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.QtCore import QEvent, QObject, Qt, QTimer
|
||||||
from PyQt6.QtWidgets import QApplication, QMenu
|
from PyQt6.QtWidgets import QApplication, QMenu
|
||||||
|
|
||||||
|
from lintunes import paths
|
||||||
|
|
||||||
PREF = "menu_bar"
|
PREF = "menu_bar"
|
||||||
ALWAYS = "always"
|
ALWAYS = "always"
|
||||||
ALT = "alt"
|
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:
|
def hidden_by_pref(prefs) -> bool:
|
||||||
|
if not available():
|
||||||
|
return False
|
||||||
return prefs.get(PREF, ALWAYS) == ALT
|
return prefs.get(PREF, ALWAYS) == ALT
|
||||||
|
|
||||||
|
|
||||||
def register_shortcuts(window, bar):
|
def register_shortcuts(window, bar):
|
||||||
"""Add every action in `bar`'s menus, submenus included, to `window`."""
|
"""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):
|
def walk(menu):
|
||||||
for action in menu.actions():
|
for action in menu.actions():
|
||||||
if action.menu() is not None:
|
if action.menu() is not None:
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ from PyQt6.QtCore import Qt, QTimer, pyqtSignal
|
|||||||
from PyQt6.QtGui import QDoubleValidator, QFont, QColor, QFontInfo
|
from PyQt6.QtGui import QDoubleValidator, QFont, QColor, QFontInfo
|
||||||
|
|
||||||
from lintunes import loudness, theme
|
from lintunes import loudness, theme
|
||||||
|
from lintunes import paths as os_paths
|
||||||
from lintunes.config import load_config, save_config
|
from lintunes.config import load_config, save_config
|
||||||
from lintunes.export import upload
|
from lintunes.export import upload
|
||||||
from lintunes.gui import visualizer_styles
|
from lintunes.gui import visualizer_styles
|
||||||
@@ -418,10 +419,19 @@ class PreferencesDialog(QDialog):
|
|||||||
gentle.setChecked(stems.gentle_choice(self._prefs))
|
gentle.setChecked(stems.gentle_choice(self._prefs))
|
||||||
gentle.toggled.connect(lambda on: self._prefs.set("dj_stem_gentle", on))
|
gentle.toggled.connect(lambda on: self._prefs.set("dj_stem_gentle", on))
|
||||||
form.addRow("", gentle)
|
form.addRow("", gentle)
|
||||||
|
self._demucs_setup = None
|
||||||
if stems.available():
|
if stems.available():
|
||||||
note = QLabel("Demucs is set up. Songs are split when they load onto "
|
note = QLabel("Demucs is set up. Songs are split when they load onto "
|
||||||
"a deck, or ahead of time with a playlist's or "
|
"a deck, or ahead of time with a playlist's or "
|
||||||
"song's “Prepare for DJ”.")
|
"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:
|
else:
|
||||||
note = QLabel("Demucs isn't set up on this computer (a one-time ~1 GB "
|
note = QLabel("Demucs isn't set up on this computer (a one-time ~1 GB "
|
||||||
"download). In a terminal:\n" + stems.setup_command())
|
"download). In a terminal:\n" + stems.setup_command())
|
||||||
@@ -432,6 +442,30 @@ class PreferencesDialog(QDialog):
|
|||||||
self._dj_gentle_check = gentle
|
self._dj_gentle_check = gentle
|
||||||
return group
|
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:
|
def _build_dj_cache_group(self) -> QGroupBox:
|
||||||
"""How much disk the saved vocal splits (both engines) may take,
|
"""How much disk the saved vocal splits (both engines) may take,
|
||||||
and how much they take now."""
|
and how much they take now."""
|
||||||
@@ -507,8 +541,9 @@ class PreferencesDialog(QDialog):
|
|||||||
self._history_check.setChecked(bool(wrapped.get("track_history")))
|
self._history_check.setChecked(bool(wrapped.get("track_history")))
|
||||||
column.addWidget(self._history_check)
|
column.addWidget(self._history_check)
|
||||||
column.addWidget(self._note(
|
column.addWidget(self._note(
|
||||||
"Every song you listen to, here and on the Rabbit: when, for how "
|
("Every song you listen to: when, for how " if os_paths.IS_MAC
|
||||||
"long, and whether you finished it. Kept in the library folder; "
|
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."))
|
"nothing leaves your machines."))
|
||||||
self._share_history_check = QCheckBox(
|
self._share_history_check = QCheckBox(
|
||||||
"Share this year's play history with friends")
|
"Share this year's play history with friends")
|
||||||
@@ -580,6 +615,11 @@ class PreferencesDialog(QDialog):
|
|||||||
self._menu_bar_check.setChecked(self._prefs.get("menu_bar", "always") == "alt")
|
self._menu_bar_check.setChecked(self._prefs.get("menu_bar", "always") == "alt")
|
||||||
self._menu_bar_check.toggled.connect(
|
self._menu_bar_check.toggled.connect(
|
||||||
lambda on: self._prefs.set("menu_bar", "alt" if on else "always"))
|
lambda on: self._prefs.set("menu_bar", "alt" if on else "always"))
|
||||||
|
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)
|
form.addRow("Menu bar:", self._menu_bar_check)
|
||||||
|
|
||||||
# Highlight color: a radio per slot, and beside it the slot's swatch,
|
# Highlight color: a radio per slot, and beside it the slot's swatch,
|
||||||
|
|||||||
@@ -101,7 +101,9 @@ def status_text(result) -> tuple[str, str]:
|
|||||||
if result.state == probe_mod.OK:
|
if result.state == probe_mod.OK:
|
||||||
return f"Syncthing {result.version} is running.", ""
|
return f"Syncthing {result.version} is running.", ""
|
||||||
if result.state == probe_mod.NOT_RUNNING:
|
if result.state == probe_mod.NOT_RUNNING:
|
||||||
|
from lintunes.cassette import syncthing_api
|
||||||
return ("Syncthing isn't running.",
|
return ("Syncthing isn't running.",
|
||||||
|
syncthing_api.not_running_hint("press Retry") or
|
||||||
"Start it (for example: systemctl --user start syncthing, or "
|
"Start it (for example: systemctl --user start syncthing, or "
|
||||||
"open the Syncthing app), then press Retry.")
|
"open the Syncthing app), then press Retry.")
|
||||||
return ("Can't reach Syncthing's API.",
|
return ("Can't reach Syncthing's API.",
|
||||||
|
|||||||
@@ -38,6 +38,8 @@ from PyQt6.QtGui import (QBrush, QColor, QLinearGradient, QPainter,
|
|||||||
QPainterPath, QPalette, QPen, QRegion)
|
QPainterPath, QPalette, QPen, QRegion)
|
||||||
from PyQt6.QtWidgets import QAbstractButton, QLayout, QWidget
|
from PyQt6.QtWidgets import QAbstractButton, QLayout, QWidget
|
||||||
|
|
||||||
|
from lintunes import paths
|
||||||
|
|
||||||
OPT_OUT = "lintunes_system_frame"
|
OPT_OUT = "lintunes_system_frame"
|
||||||
BLANK_TITLE = "lintunes_blank_title"
|
BLANK_TITLE = "lintunes_blank_title"
|
||||||
SQUARE = "lintunes_square_corners" # stays opaque: square corners, same rim
|
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]]:
|
def button_layout() -> tuple[list[str], list[str]]:
|
||||||
"""The desktop's button layout, read once; GNOME's default without one."""
|
"""The desktop's button layout, read once; GNOME's default without one."""
|
||||||
global _layout_cache
|
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:
|
if _layout_cache is None:
|
||||||
try:
|
try:
|
||||||
text = subprocess.run(
|
text = subprocess.run(
|
||||||
|
|||||||
+39
-10
@@ -14,12 +14,18 @@ from PyQt6.QtGui import (
|
|||||||
QDrag, QKeySequence, QShortcut, QPixmap, QPainter, QPen, QPolygonF, QColor,
|
QDrag, QKeySequence, QShortcut, QPixmap, QPainter, QPen, QPolygonF, QColor,
|
||||||
QFontMetrics, QDesktopServices, QCursor, QPalette,
|
QFontMetrics, QDesktopServices, QCursor, QPalette,
|
||||||
)
|
)
|
||||||
from PyQt6.QtDBus import (
|
try:
|
||||||
|
from PyQt6.QtDBus import (
|
||||||
QDBusConnection, QDBusInterface, QDBusMessage, QDBusArgument,
|
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 pathlib import Path
|
||||||
|
|
||||||
|
from lintunes import paths as os_paths
|
||||||
from lintunes.models import Track
|
from lintunes.models import Track
|
||||||
from lintunes.gui import drag_ghost
|
from lintunes.gui import drag_ghost
|
||||||
from lintunes.importers.lossless import LOSSLESS_SUFFIXES
|
from lintunes.importers.lossless import LOSSLESS_SUFFIXES
|
||||||
@@ -30,6 +36,17 @@ LOSSLESS_MENU_SUFFIXES = LOSSLESS_SUFFIXES | {".m4a"}
|
|||||||
|
|
||||||
TRACKS_MIME = "application/x-lintunes-tracks"
|
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,
|
# 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.
|
# the list auto-scrolls so off-screen rows can be reached.
|
||||||
AUTOSCROLL_MARGIN = 28
|
AUTOSCROLL_MARGIN = 28
|
||||||
@@ -512,8 +529,19 @@ def reveal_paths(paths: list[str]) -> None:
|
|||||||
"""
|
"""
|
||||||
if not paths:
|
if not paths:
|
||||||
return
|
return
|
||||||
bus = QDBusConnection.sessionBus()
|
if os_paths.IS_MAC:
|
||||||
if bus.isConnected():
|
# 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
|
# 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).
|
# Python list goes over as "av" and Nautilus rejects it (InvalidArgs).
|
||||||
uris = QDBusArgument()
|
uris = QDBusArgument()
|
||||||
@@ -1094,20 +1122,21 @@ class TrackTableView(QTableView):
|
|||||||
self._show_read_only_menu(pos)
|
self._show_read_only_menu(pos)
|
||||||
return
|
return
|
||||||
menu = QMenu(self)
|
menu = QMenu(self)
|
||||||
info_action = menu.addAction("Get Info\tCtrl+I")
|
info_action = menu.addAction("Get Info\t" + key_hint("Ctrl+I"))
|
||||||
copy_action = menu.addAction("Copy\tCtrl+C")
|
copy_action = menu.addAction("Copy\t" + key_hint("Ctrl+C"))
|
||||||
cut_action = menu.addAction("Cut\tCtrl+X")
|
cut_action = menu.addAction("Cut\t" + key_hint("Ctrl+X"))
|
||||||
paste_action = None
|
paste_action = None
|
||||||
if (self._playlist_mode and self._content_editable
|
if (self._playlist_mode and self._content_editable
|
||||||
and parse_tracks_mime(QApplication.clipboard().mimeData())):
|
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()
|
locations = self.selected_locations()
|
||||||
reveal_action = copy_path_action = download_art_action = None
|
reveal_action = copy_path_action = download_art_action = None
|
||||||
identify_action = bpm_action = dj_action = convert_action = None
|
identify_action = bpm_action = dj_action = convert_action = None
|
||||||
if locations:
|
if locations:
|
||||||
menu.addSeparator()
|
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")
|
copy_path_action = menu.addAction("Copy File Path")
|
||||||
download_art_action = menu.addAction("Download Album Art…")
|
download_art_action = menu.addAction("Download Album Art…")
|
||||||
# Fingerprinting reads the audio, so this needs a file on disk.
|
# Fingerprinting reads the audio, so this needs a file on disk.
|
||||||
@@ -1146,7 +1175,7 @@ class TrackTableView(QTableView):
|
|||||||
remove_action = None
|
remove_action = None
|
||||||
if self._playlist_mode and self._content_editable:
|
if self._playlist_mode and self._content_editable:
|
||||||
menu.addSeparator()
|
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
|
# Library removal is offered in both modes (unlike the playlist-only
|
||||||
# remove above) and has no keyboard shortcut — Del stays "remove from
|
# remove above) and has no keyboard shortcut — Del stays "remove from
|
||||||
|
|||||||
@@ -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
|
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 →
|
the button face shows under the cursor and sinks while held: click → confirm →
|
||||||
git pull → the main window restarts the app on `update_applied`.
|
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.QtCore import Qt, QTimer, QUrl, pyqtSignal
|
||||||
from PyQt6.QtGui import QPalette
|
from PyQt6.QtGui import QDesktopServices, QPalette
|
||||||
from PyQt6.QtWidgets import QApplication, QMessageBox, QPushButton
|
from PyQt6.QtWidgets import QApplication, QMessageBox, QPushButton
|
||||||
|
|
||||||
from lintunes import __version__, theme
|
from lintunes import __version__, theme
|
||||||
@@ -21,6 +25,7 @@ class VersionButton(QPushButton):
|
|||||||
super().__init__(parent)
|
super().__init__(parent)
|
||||||
self._updater = updater
|
self._updater = updater
|
||||||
self._update_ready = False
|
self._update_ready = False
|
||||||
|
self._release_page = None # the frozen app's update: a web page
|
||||||
self.setFlat(True)
|
self.setFlat(True)
|
||||||
self.setFocusPolicy(Qt.FocusPolicy.NoFocus)
|
self.setFocusPolicy(Qt.FocusPolicy.NoFocus)
|
||||||
self.refresh_theme()
|
self.refresh_theme()
|
||||||
@@ -33,6 +38,9 @@ class VersionButton(QPushButton):
|
|||||||
|
|
||||||
updater.update_available.connect(self._on_update_available)
|
updater.update_available.connect(self._on_update_available)
|
||||||
updater.update_failed.connect(self._on_update_failed)
|
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)
|
self.clicked.connect(self._on_clicked)
|
||||||
|
|
||||||
def _load_commit_tooltip(self):
|
def _load_commit_tooltip(self):
|
||||||
@@ -70,15 +78,31 @@ class VersionButton(QPushButton):
|
|||||||
self.setToolTip(f"Update available ({commits} {noun}) — "
|
self.setToolTip(f"Update available ({commits} {noun}) — "
|
||||||
"click to update and restart")
|
"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):
|
def _on_clicked(self):
|
||||||
if not self._update_ready or not self.isEnabled():
|
if not self._update_ready or not self.isEnabled():
|
||||||
return
|
return
|
||||||
|
if self._release_page:
|
||||||
|
self.open_release_page()
|
||||||
|
return
|
||||||
if not self._confirm():
|
if not self._confirm():
|
||||||
return
|
return
|
||||||
self.setEnabled(False)
|
self.setEnabled(False)
|
||||||
self.setText("updating…")
|
self.setText("updating…")
|
||||||
self._updater.update_async()
|
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:
|
def _confirm(self) -> bool:
|
||||||
answer = QMessageBox.question(
|
answer = QMessageBox.question(
|
||||||
self.window(), "Update LinTunes",
|
self.window(), "Update LinTunes",
|
||||||
|
|||||||
@@ -20,7 +20,6 @@ unevenly, and the art must arrive as an ID3 front cover.
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
import os
|
|
||||||
import shutil
|
import shutil
|
||||||
import subprocess
|
import subprocess
|
||||||
import tempfile
|
import tempfile
|
||||||
@@ -29,7 +28,7 @@ from pathlib import Path
|
|||||||
|
|
||||||
from PyQt6.QtCore import QObject, pyqtSignal
|
from PyQt6.QtCore import QObject, pyqtSignal
|
||||||
|
|
||||||
from lintunes import tagging
|
from lintunes import paths, tagging
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -41,8 +40,7 @@ LOSSLESS_SUFFIXES = {".flac", ".wav", ".aiff", ".aif"}
|
|||||||
def staging_root() -> Path:
|
def staging_root() -> Path:
|
||||||
"""Where conversions are written before they're filed: the cache, on
|
"""Where conversions are written before they're filed: the cache, on
|
||||||
disk — /tmp is often RAM, and a batch of songs can be gigabytes."""
|
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 paths.cache_dir() / "converting"
|
||||||
return Path(base) / "lintunes" / "converting"
|
|
||||||
|
|
||||||
|
|
||||||
def ffmpeg_available() -> bool:
|
def ffmpeg_available() -> bool:
|
||||||
|
|||||||
+89
-2
@@ -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
|
hold inhibitors simultaneously without stepping on each other. On non-GNOME
|
||||||
desktops the interface won't be available; every method then no-ops silently
|
desktops the interface won't be available; every method then no-ops silently
|
||||||
rather than failing.
|
rather than failing.
|
||||||
|
|
||||||
|
On macOS there is no session bus to ask: an inhibitor is a ``caffeinate``
|
||||||
|
child process held for as long as the inhibit lasts (``-i`` for suspend,
|
||||||
|
plus ``-s``/``-m`` keeping disks and the system up for logout-class
|
||||||
|
syncs). ``-w <our pid>`` makes it exit on its own if LinTunes dies, so a
|
||||||
|
crash can never leave the Mac unable to sleep.
|
||||||
"""
|
"""
|
||||||
|
import atexit
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import weakref
|
||||||
|
|
||||||
from PyQt6.QtCore import QMetaType
|
from PyQt6.QtCore import QMetaType
|
||||||
from PyQt6.QtDBus import (QDBusArgument, QDBusConnection, QDBusInterface,
|
|
||||||
|
try:
|
||||||
|
from PyQt6.QtDBus import (QDBusArgument, QDBusConnection, QDBusInterface,
|
||||||
QDBusReply)
|
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"
|
SERVICE = "org.gnome.SessionManager"
|
||||||
@@ -33,19 +55,82 @@ def _uint(value: int) -> QDBusArgument:
|
|||||||
return QDBusArgument(value, QMetaType.Type.UInt.value)
|
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:
|
class SleepInhibitor:
|
||||||
def __init__(self, reason: str = REASON, flags: int = INHIBIT_SUSPEND):
|
def __init__(self, reason: str = REASON, flags: int = INHIBIT_SUSPEND):
|
||||||
self._cookie: int | None = None
|
self._cookie: int | None = None
|
||||||
self._reason = reason
|
self._reason = reason
|
||||||
self._flags = flags
|
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()
|
bus = QDBusConnection.sessionBus()
|
||||||
self._iface = QDBusInterface(SERVICE, PATH, SERVICE, bus)
|
self._iface = QDBusInterface(SERVICE, PATH, SERVICE, bus)
|
||||||
|
|
||||||
def _available(self) -> bool:
|
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):
|
def inhibit(self):
|
||||||
"""Take the inhibitor. No-op if already inhibiting or unavailable."""
|
"""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():
|
if self._cookie is not None or not self._available():
|
||||||
return
|
return
|
||||||
reply = QDBusReply(self._iface.call(
|
reply = QDBusReply(self._iface.call(
|
||||||
@@ -55,6 +140,8 @@ class SleepInhibitor:
|
|||||||
|
|
||||||
def release(self):
|
def release(self):
|
||||||
"""Release a held inhibitor, if any."""
|
"""Release a held inhibitor, if any."""
|
||||||
|
if self._proc is not None:
|
||||||
|
self._mac_release()
|
||||||
if self._cookie is None:
|
if self._cookie is None:
|
||||||
return
|
return
|
||||||
if self._available():
|
if self._available():
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import logging
|
import logging
|
||||||
|
import os
|
||||||
import secrets
|
import secrets
|
||||||
import unicodedata
|
import unicodedata
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
@@ -944,6 +945,14 @@ class LibraryManager(QObject):
|
|||||||
unicodedata.normalize("NFC", src.name))
|
unicodedata.normalize("NFC", src.name))
|
||||||
if dest == src:
|
if dest == src:
|
||||||
return None
|
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:
|
try:
|
||||||
return str(self._move_file(src, dest))
|
return str(self._move_file(src, dest))
|
||||||
except OSError as e:
|
except OSError as e:
|
||||||
|
|||||||
@@ -27,6 +27,8 @@ from pathlib import Path
|
|||||||
|
|
||||||
from PyQt6.QtCore import QObject, QTimer, pyqtSignal
|
from PyQt6.QtCore import QObject, QTimer, pyqtSignal
|
||||||
|
|
||||||
|
from lintunes import paths
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
TARGET_LUFS = -14.0 # Spotify's and YouTube's level: loud enough for a party
|
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:
|
def default_cache_path() -> Path:
|
||||||
base = os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache"
|
return paths.cache_dir() / "loudness.json"
|
||||||
return Path(base) / "lintunes" / "loudness.json"
|
|
||||||
|
|
||||||
|
|
||||||
def _stamp(path: str):
|
def _stamp(path: str):
|
||||||
|
|||||||
+93
-1
@@ -3,10 +3,33 @@ import os
|
|||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
from PyQt6.QtCore import QEvent, QObject, QTimer
|
||||||
|
|
||||||
|
from lintunes import paths
|
||||||
from lintunes.config import load_config, save_config
|
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():
|
def main():
|
||||||
|
add_mac_tool_dirs()
|
||||||
parser = argparse.ArgumentParser(
|
parser = argparse.ArgumentParser(
|
||||||
prog="lintunes",
|
prog="lintunes",
|
||||||
description="LinTunes — iTunes library manager for Linux",
|
description="LinTunes — iTunes library manager for Linux",
|
||||||
@@ -50,6 +73,11 @@ def main():
|
|||||||
save_config(config)
|
save_config(config)
|
||||||
print(f"Saved 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:
|
if not data_dir:
|
||||||
print("Error: no data directory configured.\n"
|
print("Error: no data directory configured.\n"
|
||||||
"Run with --data-dir DIR (add --save-config to remember it).")
|
"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)
|
run_import(Path(args.import_file), music_root, data_dir)
|
||||||
else:
|
else:
|
||||||
if run_gui(data_dir, [Path(f) for f in args.files], qt_args):
|
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
|
# A self-update just pulled new code; replace this process with a
|
||||||
# fresh launch running the updated source. -m works whether we
|
# fresh launch running the updated source. -m works whether we
|
||||||
# started as `lintunes` or `python -m lintunes.main`. Positional
|
# 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()
|
new_library = not (data_dir / "library.json").exists()
|
||||||
library = load_library(data_dir)
|
library = load_library(data_dir)
|
||||||
|
|
||||||
|
if paths.IS_MAC:
|
||||||
|
_name_mac_app_menu()
|
||||||
app = QApplication([sys.argv[0]] + (qt_args or []))
|
app = QApplication([sys.argv[0]] + (qt_args or []))
|
||||||
app.setApplicationName("LinTunes")
|
app.setApplicationName("LinTunes")
|
||||||
|
if paths.IS_MAC:
|
||||||
|
app.setApplicationDisplayName("LinTunes")
|
||||||
|
else:
|
||||||
app.setDesktopFileName("lintunes")
|
app.setDesktopFileName("lintunes")
|
||||||
# Click anywhere on a scrollbar trough to jump there, not page a step at a
|
# 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
|
# time. Set app-wide (before apply_theme's stylesheet wraps the style) so
|
||||||
# the hint is honored everywhere, including the track list and sidebar.
|
# 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)
|
prefs = Preferences(data_dir)
|
||||||
theme.apply_theme(app, prefs)
|
theme.apply_theme(app, prefs)
|
||||||
@@ -162,6 +202,10 @@ def run_gui(data_dir: Path, files: list[Path],
|
|||||||
lastfm = LastFm(prefs, data_dir)
|
lastfm = LastFm(prefs, data_dir)
|
||||||
window = MainWindow(manager, prefs, lastfm)
|
window = MainWindow(manager, prefs, lastfm)
|
||||||
app.installEventFilter(window)
|
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
|
mpris = setup_mpris(window.player, window) # noqa: F841 — keep alive
|
||||||
# Tear the multimedia pipeline down before Qt destroys objects (exit
|
# Tear the multimedia pipeline down before Qt destroys objects (exit
|
||||||
# segfault in the FFmpeg backend otherwise); shutdown() is idempotent so
|
# 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)
|
window.show_conflict_summary(startup_conflicts)
|
||||||
if files:
|
if files:
|
||||||
window.import_files(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()
|
exit_code = app.exec()
|
||||||
if window.restart_requested:
|
if window.restart_requested:
|
||||||
return True # caller re-execs the updated code
|
return True # caller re-execs the updated code
|
||||||
leave(exit_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):
|
def leave(exit_code: int):
|
||||||
"""End the process once the event loop is done, without Python tearing
|
"""End the process once the event loop is done, without Python tearing
|
||||||
down the Qt objects. Everything is already saved by then (aboutToQuit
|
down the Qt objects. Everything is already saved by then (aboutToQuit
|
||||||
|
|||||||
+31
-6
@@ -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
|
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).
|
(mpris:artUrl must be a file the notification daemon can read).
|
||||||
"""
|
"""
|
||||||
import os
|
import logging
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from PyQt6.QtCore import QMetaType, QObject, pyqtSlot, pyqtProperty, pyqtClassInfo
|
from PyQt6.QtCore import QMetaType, QObject, pyqtSlot, pyqtProperty, pyqtClassInfo
|
||||||
from PyQt6.QtDBus import (
|
|
||||||
|
try:
|
||||||
|
from PyQt6.QtDBus import (
|
||||||
QDBusConnection, QDBusAbstractAdaptor, QDBusArgument, QDBusObjectPath,
|
QDBusConnection, QDBusAbstractAdaptor, QDBusArgument, QDBusObjectPath,
|
||||||
QDBusMessage,
|
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 tagging
|
from lintunes import paths, tagging
|
||||||
from lintunes.eventlog import log_control
|
from lintunes.eventlog import log_control
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
SERVICE_NAME = "org.mpris.MediaPlayer2.lintunes"
|
SERVICE_NAME = "org.mpris.MediaPlayer2.lintunes"
|
||||||
OBJECT_PATH = "/org/mpris/MediaPlayer2"
|
OBJECT_PATH = "/org/mpris/MediaPlayer2"
|
||||||
@@ -25,8 +37,7 @@ ART_CACHE_LIMIT = 50
|
|||||||
|
|
||||||
|
|
||||||
def _art_cache_dir() -> Path:
|
def _art_cache_dir() -> Path:
|
||||||
base = os.environ.get("XDG_CACHE_HOME", str(Path.home() / ".cache"))
|
return paths.cache_dir() / "artwork"
|
||||||
return Path(base) / "lintunes" / "artwork"
|
|
||||||
|
|
||||||
|
|
||||||
def export_artwork(track) -> str | None:
|
def export_artwork(track) -> str | None:
|
||||||
@@ -50,6 +61,9 @@ def export_artwork(track) -> str | None:
|
|||||||
def invalidate_artwork(track):
|
def invalidate_artwork(track):
|
||||||
"""Drop a track's cached art so the next export re-reads the file (call
|
"""Drop a track's cached art so the next export re-reads the file (call
|
||||||
after embedding new artwork)."""
|
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:
|
if track is None or not track.persistent_id:
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
@@ -68,6 +82,15 @@ def _prune_cache(cache_dir: Path):
|
|||||||
|
|
||||||
|
|
||||||
def setup_mpris(player, main_window) -> "MprisService | None":
|
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()
|
bus = QDBusConnection.sessionBus()
|
||||||
if not bus.isConnected():
|
if not bus.isConnected():
|
||||||
return None
|
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
|
"""A D-Bus string array ("as"). A plain Python list of str marshals as
|
||||||
"av", which GDBus consumers validate and reject — see
|
"av", which GDBus consumers validate and reject — see
|
||||||
build_properties_changed and xesam:artist in _metadata."""
|
build_properties_changed and xesam:artist in _metadata."""
|
||||||
|
if not HAVE_DBUS:
|
||||||
|
return list(values)
|
||||||
string_id = QMetaType(QMetaType.Type.QString.value).id()
|
string_id = QMetaType(QMetaType.Type.QString.value).id()
|
||||||
arg = QDBusArgument()
|
arg = QDBusArgument()
|
||||||
arg.beginArray(string_id)
|
arg.beginArray(string_id)
|
||||||
|
|||||||
@@ -0,0 +1,233 @@
|
|||||||
|
"""macOS Now Playing and media keys: the Mac's answer to ``mpris.py``.
|
||||||
|
|
||||||
|
``MPNowPlayingInfoCenter`` is what Control Centre's Now Playing tile and
|
||||||
|
the menu-bar widget read (title, artist, album, length, where the song is
|
||||||
|
up to, artwork), and ``MPRemoteCommandCenter`` is where the keyboard's
|
||||||
|
play/pause/next/previous keys, AirPods and the tile's own buttons land.
|
||||||
|
A Mac sends those keys to whichever app last claimed Now Playing, so this
|
||||||
|
is the whole of media-key support there; ``MainWindow.eventFilter``'s
|
||||||
|
in-window keys stay as they are.
|
||||||
|
|
||||||
|
pyobjc (``pyobjc-framework-MediaPlayer`` + ``-Cocoa``) is a Mac-only
|
||||||
|
dependency, imported inside ``setup``: if it is missing the app logs once
|
||||||
|
and runs without, exactly as Linux does without a session bus.
|
||||||
|
|
||||||
|
The command handlers may run on a thread of the system's choosing, so they
|
||||||
|
only emit ``_command``; the Player is driven from the GUI thread by the
|
||||||
|
queued slot. The adaptor routes to the same Player methods MPRIS does.
|
||||||
|
"""
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from PyQt6.QtCore import QObject, pyqtSignal
|
||||||
|
|
||||||
|
from lintunes import tagging
|
||||||
|
from lintunes.eventlog import log_control
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# The one live instance, so mpris.invalidate_artwork can reach it.
|
||||||
|
_live = None
|
||||||
|
|
||||||
|
# MPRemoteCommandHandlerStatus / MPNowPlayingPlaybackState
|
||||||
|
STATUS_SUCCESS = 0
|
||||||
|
STATUS_NO_SUCH_CONTENT = 100
|
||||||
|
STATE_PLAYING = 1
|
||||||
|
STATE_PAUSED = 2
|
||||||
|
STATE_STOPPED = 3
|
||||||
|
|
||||||
|
# (MPRemoteCommandCenter accessor, the name the handler emits)
|
||||||
|
COMMANDS = (
|
||||||
|
("playCommand", "play"),
|
||||||
|
("pauseCommand", "pause"),
|
||||||
|
("togglePlayPauseCommand", "toggle"),
|
||||||
|
("stopCommand", "stop"),
|
||||||
|
("nextTrackCommand", "next"),
|
||||||
|
("previousTrackCommand", "previous"),
|
||||||
|
("changePlaybackPositionCommand", "seek"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def setup(player, main_window):
|
||||||
|
"""A live ``MacNowPlaying``, or None when pyobjc isn't installed or the
|
||||||
|
framework refuses (the app carries on either way)."""
|
||||||
|
try:
|
||||||
|
import MediaPlayer # noqa: F401 — pyobjc-framework-MediaPlayer
|
||||||
|
except Exception as e: # noqa: BLE001 — ImportError, or a broken install
|
||||||
|
log.info("Now Playing: pyobjc's MediaPlayer isn't available (%s); "
|
||||||
|
"media keys are off", e)
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
import AppKit
|
||||||
|
except Exception: # noqa: BLE001 — artwork is optional
|
||||||
|
AppKit = None
|
||||||
|
global _live
|
||||||
|
try:
|
||||||
|
_live = MacNowPlaying(player, main_window, MediaPlayer, AppKit)
|
||||||
|
return _live
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
log.info("Now Playing: couldn't register with the system: %s", e)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class MacNowPlaying(QObject):
|
||||||
|
"""Mirrors the Player into the system's Now Playing and routes the
|
||||||
|
remote commands back. ``mp``/``appkit`` are the pyobjc modules, passed
|
||||||
|
in so tests can hand it fakes."""
|
||||||
|
|
||||||
|
_command = pyqtSignal(str, float)
|
||||||
|
|
||||||
|
def __init__(self, player, main_window, mp, appkit=None):
|
||||||
|
super().__init__()
|
||||||
|
self._player = player
|
||||||
|
self._window = main_window
|
||||||
|
self._mp = mp
|
||||||
|
self._appkit = appkit
|
||||||
|
self._handlers = [] # keep the Python callables alive
|
||||||
|
self._art_track = None # whose artwork object we built
|
||||||
|
self._artwork = None
|
||||||
|
self._command.connect(self._run)
|
||||||
|
|
||||||
|
center = mp.MPRemoteCommandCenter.sharedCommandCenter()
|
||||||
|
for accessor, name in COMMANDS:
|
||||||
|
command = getattr(center, accessor, None)
|
||||||
|
if command is None:
|
||||||
|
continue
|
||||||
|
command = command()
|
||||||
|
handler = self._handler_for(name)
|
||||||
|
self._handlers.append(handler)
|
||||||
|
try:
|
||||||
|
command.setEnabled_(True)
|
||||||
|
command.addTargetWithHandler_(handler)
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
log.info("Now Playing: %s unavailable: %s", accessor, e)
|
||||||
|
|
||||||
|
player.track_changed.connect(lambda _t: self.update())
|
||||||
|
player.playing_changed.connect(lambda _p: self.update())
|
||||||
|
# A seek moves the elapsed time; Now Playing extrapolates the rest
|
||||||
|
# from the rate, so a jump is the only position change it needs.
|
||||||
|
self._last_pos = 0
|
||||||
|
player.position_changed.connect(self._on_position)
|
||||||
|
self.update()
|
||||||
|
|
||||||
|
# -- commands (any thread) -> GUI thread --
|
||||||
|
|
||||||
|
def _handler_for(self, name):
|
||||||
|
def handler(event):
|
||||||
|
seconds = 0.0
|
||||||
|
if name == "seek":
|
||||||
|
try:
|
||||||
|
seconds = float(event.positionTime())
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
return STATUS_NO_SUCH_CONTENT
|
||||||
|
self._command.emit(name, seconds)
|
||||||
|
return STATUS_SUCCESS
|
||||||
|
return handler
|
||||||
|
|
||||||
|
def _run(self, name: str, seconds: float):
|
||||||
|
log_control("nowplaying", name)
|
||||||
|
player = self._player
|
||||||
|
if name == "play":
|
||||||
|
player.play()
|
||||||
|
elif name == "pause":
|
||||||
|
player.pause()
|
||||||
|
elif name == "toggle":
|
||||||
|
player.toggle_play()
|
||||||
|
elif name == "stop":
|
||||||
|
player.stop()
|
||||||
|
elif name == "next":
|
||||||
|
player.next()
|
||||||
|
elif name == "previous":
|
||||||
|
player.previous()
|
||||||
|
elif name == "seek":
|
||||||
|
player.seek(int(seconds * 1000))
|
||||||
|
self.update()
|
||||||
|
|
||||||
|
# -- Player -> Now Playing --
|
||||||
|
|
||||||
|
def _on_position(self, ms):
|
||||||
|
ms = int(ms)
|
||||||
|
# Normal playback steps a few hundred ms at a time; only a jump
|
||||||
|
# (a seek, a restart) needs telling.
|
||||||
|
if abs(ms - self._last_pos) > 2000:
|
||||||
|
self._last_pos = ms
|
||||||
|
self.update()
|
||||||
|
else:
|
||||||
|
self._last_pos = ms
|
||||||
|
|
||||||
|
def info(self) -> dict | None:
|
||||||
|
"""The nowPlayingInfo dictionary for the current state (None when
|
||||||
|
nothing is loaded)."""
|
||||||
|
mp = self._mp
|
||||||
|
track = self._player.current_track
|
||||||
|
if track is None:
|
||||||
|
return None
|
||||||
|
playing = self._player.is_playing()
|
||||||
|
info = {
|
||||||
|
mp.MPMediaItemPropertyTitle: track.name or "",
|
||||||
|
mp.MPMediaItemPropertyArtist: track.artist or "",
|
||||||
|
mp.MPMediaItemPropertyAlbumTitle: track.album or "",
|
||||||
|
mp.MPNowPlayingInfoPropertyElapsedPlaybackTime:
|
||||||
|
self._player.position_ms() / 1000.0,
|
||||||
|
mp.MPNowPlayingInfoPropertyPlaybackRate: 1.0 if playing else 0.0,
|
||||||
|
}
|
||||||
|
length = track.total_time or self._player.duration_ms()
|
||||||
|
if length:
|
||||||
|
info[mp.MPMediaItemPropertyPlaybackDuration] = length / 1000.0
|
||||||
|
artwork = self._artwork_for(track)
|
||||||
|
if artwork is not None:
|
||||||
|
info[mp.MPMediaItemPropertyArtwork] = artwork
|
||||||
|
return info
|
||||||
|
|
||||||
|
def update(self):
|
||||||
|
try:
|
||||||
|
center = self._mp.MPNowPlayingInfoCenter.defaultCenter()
|
||||||
|
info = self.info()
|
||||||
|
center.setNowPlayingInfo_(info)
|
||||||
|
if info is None:
|
||||||
|
state = STATE_STOPPED
|
||||||
|
elif self._player.is_playing():
|
||||||
|
state = STATE_PLAYING
|
||||||
|
else:
|
||||||
|
state = STATE_PAUSED
|
||||||
|
# macOS only routes the media keys to an app that says it's
|
||||||
|
# playing (or paused), so this matters as much as the info.
|
||||||
|
if hasattr(center, "setPlaybackState_"):
|
||||||
|
center.setPlaybackState_(state)
|
||||||
|
except Exception as e: # noqa: BLE001 — never break playback for this
|
||||||
|
log.info("Now Playing: update failed: %s", e)
|
||||||
|
|
||||||
|
def _artwork_for(self, track):
|
||||||
|
if self._appkit is None or not track.location:
|
||||||
|
return None
|
||||||
|
if self._art_track == track.track_id:
|
||||||
|
return self._artwork
|
||||||
|
self._art_track = track.track_id
|
||||||
|
self._artwork = None
|
||||||
|
try:
|
||||||
|
data = tagging.read_embedded_artwork(track.location)
|
||||||
|
if not data:
|
||||||
|
return None
|
||||||
|
appkit = self._appkit
|
||||||
|
image = appkit.NSImage.alloc().initWithData_(
|
||||||
|
appkit.NSData.dataWithBytes_length_(data, len(data)))
|
||||||
|
if image is None:
|
||||||
|
return None
|
||||||
|
self._artwork = self._mp.MPMediaItemArtwork.alloc() \
|
||||||
|
.initWithBoundsSize_requestHandler_(
|
||||||
|
image.size(), lambda _size: image)
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
log.info("Now Playing: no artwork for %s: %s", track.location, e)
|
||||||
|
self._artwork = None
|
||||||
|
return self._artwork
|
||||||
|
|
||||||
|
def invalidate_artwork(self, track=None):
|
||||||
|
"""Forget the built artwork (after new art is embedded)."""
|
||||||
|
if track is None or self._art_track == getattr(track, "track_id", None):
|
||||||
|
self._art_track = None
|
||||||
|
self._artwork = None
|
||||||
|
self.update()
|
||||||
|
|
||||||
|
|
||||||
|
def invalidate_artwork(track):
|
||||||
|
if _live is not None:
|
||||||
|
_live.invalidate_artwork(track)
|
||||||
+69
-7
@@ -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
|
Linux follows the XDG base directories, exactly as every module did by
|
||||||
all expect real paths), but on disk they are stored **relative to the data dir**.
|
hand before the Mac port. macOS uses ``~/Library``. An XDG variable that
|
||||||
The data dir and the music live inside one Syncthing-shared tree and move together,
|
is set wins on either system, which is how the tests (and anyone who
|
||||||
so a relative path resolves correctly on every machine no matter where the tree is
|
wants to) point the app somewhere else.
|
||||||
mounted — no per-machine ``music_root`` config is needed at load time.
|
|
||||||
|
Nothing here is the synced library data dir: that is ``--data-dir``.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
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:
|
def to_relative(location: str, data_dir) -> str:
|
||||||
"""Convert an absolute track location to a path relative to ``data_dir``.
|
"""Convert an absolute track location to a path relative to ``data_dir``.
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -20,6 +20,8 @@ import os
|
|||||||
import ssl
|
import ssl
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
from lintunes import paths
|
||||||
|
|
||||||
# Where Syncthing keeps config.xml + cert.pem. Newer builds use XDG state, older
|
# Where Syncthing keeps config.xml + cert.pem. Newer builds use XDG state, older
|
||||||
# ones ~/.config; the last two are for people who never migrated.
|
# ones ~/.config; the last two are for people who never migrated.
|
||||||
_CONFIG_DIRS = (
|
_CONFIG_DIRS = (
|
||||||
@@ -29,13 +31,31 @@ _CONFIG_DIRS = (
|
|||||||
"~/.syncthing",
|
"~/.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
|
_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:
|
def _config_dir() -> Path | None:
|
||||||
for raw in _CONFIG_DIRS:
|
for raw in config_dirs():
|
||||||
expanded = Path(os.path.expandvars(raw)).expanduser()
|
text = os.path.expandvars(raw)
|
||||||
if "$" in str(expanded): # unset XDG_STATE_HOME
|
if not text.strip(): # a variable set to nothing
|
||||||
|
continue
|
||||||
|
expanded = Path(text).expanduser()
|
||||||
|
if "$" in str(expanded): # unset XDG_STATE_HOME / STCONFDIR
|
||||||
continue
|
continue
|
||||||
if (expanded / "config.xml").is_file():
|
if (expanded / "config.xml").is_file():
|
||||||
return expanded
|
return expanded
|
||||||
|
|||||||
@@ -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
|
manager's "Restore" can't put back, because the recorded original path would sit
|
||||||
on a different filesystem than the trash holding it.
|
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.
|
Nothing here knows about the library; ``LibraryManager`` is the only caller.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -17,6 +22,8 @@ from datetime import datetime
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from urllib.parse import quote, unquote
|
from urllib.parse import quote, unquote
|
||||||
|
|
||||||
|
from lintunes import paths
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
@@ -29,6 +36,27 @@ def _home_trash() -> Path:
|
|||||||
return Path(base) / "Trash"
|
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:
|
def _topdir(path: Path) -> Path:
|
||||||
"""The mount point the path lives on."""
|
"""The mount point the path lives on."""
|
||||||
current = path if path.is_dir() else path.parent
|
current = path if path.is_dir() else path.parent
|
||||||
@@ -120,6 +148,8 @@ def send_to_trash(path: Path) -> Path:
|
|||||||
path = Path(path)
|
path = Path(path)
|
||||||
if not path.exists():
|
if not path.exists():
|
||||||
raise TrashError(f"{path} does not exist")
|
raise TrashError(f"{path} does not exist")
|
||||||
|
if paths.IS_MAC:
|
||||||
|
return _mac_send_to_trash(path)
|
||||||
|
|
||||||
trash_dir, top = trash_dir_for(path)
|
trash_dir, top = trash_dir_for(path)
|
||||||
files_dir, info_dir = _ensure_trash(trash_dir)
|
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)
|
os.rename(trashed, original)
|
||||||
except OSError as e:
|
except OSError as e:
|
||||||
raise TrashError(f"Could not restore {trashed} to {original}: {e}") from 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 = trashed.parent.parent / "info" / f"{trashed.name}.trashinfo"
|
||||||
info_path.unlink(missing_ok=True)
|
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
|
Only used by tests and diagnostics; restoring uses the location the library
|
||||||
already knows.
|
already knows.
|
||||||
"""
|
"""
|
||||||
|
if paths.IS_MAC:
|
||||||
|
return None
|
||||||
info_path = Path(trashed).parent.parent / "info" / f"{Path(trashed).name}.trashinfo"
|
info_path = Path(trashed).parent.parent / "info" / f"{Path(trashed).name}.trashinfo"
|
||||||
try:
|
try:
|
||||||
text = info_path.read_text(encoding="utf-8")
|
text = info_path.read_text(encoding="utf-8")
|
||||||
|
|||||||
+67
-2
@@ -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
|
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.
|
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 subprocess
|
||||||
import threading
|
import threading
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from PyQt6.QtCore import QObject, QTimer, pyqtSignal
|
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
|
FIRST_CHECK_MS = 10 * 1000 # shortly after launch, off the startup path
|
||||||
RECHECK_INTERVAL_MS = 4 * 3600 * 1000 # then every 4 hours
|
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_available = pyqtSignal(int) # commits behind upstream
|
||||||
update_applied = pyqtSignal() # pull succeeded; caller restarts the app
|
update_applied = pyqtSignal() # pull succeeded; caller restarts the app
|
||||||
update_failed = pyqtSignal(str)
|
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)
|
super().__init__(parent)
|
||||||
self._root = str(Path(__file__).resolve().parents[1])
|
self._root = str(Path(__file__).resolve().parents[1])
|
||||||
self._busy = False
|
self._busy = False
|
||||||
self._timer = None
|
self._timer = None
|
||||||
self._enabled = None # probed lazily — see enabled
|
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
|
@property
|
||||||
def enabled(self) -> bool:
|
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
|
that stall on the main thread before the window was up. First use is
|
||||||
now `_check`, on a background thread.
|
now `_check`, on a background thread.
|
||||||
"""
|
"""
|
||||||
|
if self.release_mode:
|
||||||
|
return release_info.latest_release_url() is not None
|
||||||
if self._enabled is None:
|
if self._enabled is None:
|
||||||
self._enabled = (
|
self._enabled = (
|
||||||
self._git("rev-parse", "--show-toplevel") is not None
|
self._git("rev-parse", "--show-toplevel") is not None
|
||||||
@@ -51,10 +70,14 @@ class Updater(QObject):
|
|||||||
|
|
||||||
def short_hash(self) -> str | None:
|
def short_hash(self) -> str | None:
|
||||||
"""The checkout's current commit, for telling builds apart."""
|
"""The checkout's current commit, for telling builds apart."""
|
||||||
|
if self.release_mode:
|
||||||
|
return None
|
||||||
return self._git("rev-parse", "--short", "HEAD")
|
return self._git("rev-parse", "--short", "HEAD")
|
||||||
|
|
||||||
def start_checking(self):
|
def start_checking(self):
|
||||||
"""First check shortly after launch, then every few hours."""
|
"""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)
|
QTimer.singleShot(FIRST_CHECK_MS, self.check_async)
|
||||||
self._timer = QTimer(self)
|
self._timer = QTimer(self)
|
||||||
self._timer.setInterval(RECHECK_INTERVAL_MS)
|
self._timer.setInterval(RECHECK_INTERVAL_MS)
|
||||||
@@ -68,7 +91,8 @@ class Updater(QObject):
|
|||||||
threading.Thread(target=self._check, daemon=True).start()
|
threading.Thread(target=self._check, daemon=True).start()
|
||||||
|
|
||||||
def update_async(self):
|
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
|
return
|
||||||
self._busy = True
|
self._busy = True
|
||||||
threading.Thread(target=self._update, daemon=True).start()
|
threading.Thread(target=self._update, daemon=True).start()
|
||||||
@@ -76,6 +100,8 @@ class Updater(QObject):
|
|||||||
# ---- internals (run on daemon threads) ----
|
# ---- internals (run on daemon threads) ----
|
||||||
|
|
||||||
def _check(self):
|
def _check(self):
|
||||||
|
if self.release_mode:
|
||||||
|
return self._check_release()
|
||||||
try:
|
try:
|
||||||
if not self.enabled:
|
if not self.enabled:
|
||||||
return
|
return
|
||||||
@@ -87,6 +113,15 @@ class Updater(QObject):
|
|||||||
finally:
|
finally:
|
||||||
self._busy = False
|
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):
|
def _update(self):
|
||||||
try:
|
try:
|
||||||
proc = subprocess.run(
|
proc = subprocess.run(
|
||||||
@@ -120,3 +155,33 @@ class Updater(QObject):
|
|||||||
if proc.returncode != 0:
|
if proc.returncode != 0:
|
||||||
return None
|
return None
|
||||||
return proc.stdout.strip()
|
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
|
||||||
|
|||||||
+13
-3
@@ -56,7 +56,7 @@ from urllib.parse import parse_qs, urlsplit
|
|||||||
|
|
||||||
from PyQt6.QtCore import QObject, pyqtSignal
|
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
|
from lintunes.models.playlist import PlaylistType
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
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
|
"""The browser whose cookies to borrow: the first one with a profile on
|
||||||
this machine, or None when there's nothing to borrow from."""
|
this machine, or None when there's nothing to borrow from."""
|
||||||
home = Path.home()
|
home = Path.home()
|
||||||
|
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")))
|
config = Path(os.environ.get("XDG_CONFIG_HOME", str(home / ".config")))
|
||||||
for browser, profile in (("firefox", home / ".mozilla" / "firefox"),
|
candidates = (("firefox", home / ".mozilla" / "firefox"),
|
||||||
("chromium", config / "chromium"),
|
("chromium", config / "chromium"),
|
||||||
("chrome", config / "google-chrome")):
|
("chrome", config / "google-chrome"))
|
||||||
|
for browser, profile in candidates:
|
||||||
if profile.is_dir():
|
if profile.is_dir():
|
||||||
return browser
|
return browser
|
||||||
return None
|
return None
|
||||||
|
|||||||
Binary file not shown.
@@ -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 <package>/../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),
|
||||||
|
)
|
||||||
@@ -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, <https://ffmpeg.martin-riedl.de>, 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, <https://github.com/acoustid/chromaprint/releases/tag/v1.6.2> | 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
|
||||||
|
<https://ffmpeg.org/releases/> (`ffmpeg-9.0.2.tar.xz`), and the script that
|
||||||
|
built this binary, with every library version it used, is at
|
||||||
|
<https://git.martin-riedl.de/ffmpeg/build-script>. 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.
|
||||||
Executable
+217
@@ -0,0 +1,217 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Build LinTunes.app and LinTunes-<version>-<AppleSilicon|Intel>.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-<version>-<label>.dmg and a .sha256 beside it.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
PYINSTALLER_VERSION="6.22.3"
|
||||||
|
HOOKS_CONTRIB_VERSION="2026.10"
|
||||||
|
|
||||||
|
die() { echo "build.sh: $*" >&2; exit 1; }
|
||||||
|
step() { echo; echo "==> $*"; }
|
||||||
|
|
||||||
|
[ "$(uname -s)" = "Darwin" ] || die "this builds a macOS app; run it on a Mac"
|
||||||
|
|
||||||
|
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
ROOT="$(cd "$HERE/../.." && pwd)"
|
||||||
|
BUILD="$ROOT/build/mac"
|
||||||
|
VENV="$BUILD/venv"
|
||||||
|
PYTHON="${PYTHON:-python3}"
|
||||||
|
|
||||||
|
ARCH="$(uname -m)"
|
||||||
|
case "$ARCH" in
|
||||||
|
arm64) LABEL="AppleSilicon" ;;
|
||||||
|
x86_64) LABEL="Intel" ;;
|
||||||
|
*) die "unknown architecture $ARCH" ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
VERSION="$(sed -n 's/^__version__ = "\(.*\)"$/\1/p' "$ROOT/lintunes/__init__.py")"
|
||||||
|
[ -n "$VERSION" ] || die "couldn't read __version__ from lintunes/__init__.py"
|
||||||
|
APP_NAME="LinTunes"
|
||||||
|
DMG="$BUILD/$APP_NAME-$VERSION-$LABEL.dmg"
|
||||||
|
|
||||||
|
step "LinTunes $VERSION for $LABEL ($ARCH)"
|
||||||
|
|
||||||
|
# A Python running under Rosetta (or a universal one started as the other
|
||||||
|
# arch) would build an app for the wrong kind of Mac.
|
||||||
|
PY_ARCH="$("$PYTHON" -c 'import platform; print(platform.machine())')"
|
||||||
|
[ "$PY_ARCH" = "$ARCH" ] || die "$PYTHON runs as $PY_ARCH on this $ARCH Mac"
|
||||||
|
"$PYTHON" -c 'import sys; sys.exit(sys.version_info < (3, 11))' \
|
||||||
|
|| die "$PYTHON is older than 3.11"
|
||||||
|
|
||||||
|
step "Virtual environment ($("$PYTHON" --version))"
|
||||||
|
mkdir -p "$BUILD"
|
||||||
|
"$PYTHON" -m venv --clear "$VENV"
|
||||||
|
PY="$VENV/bin/python"
|
||||||
|
"$PY" -m pip install --quiet --upgrade pip
|
||||||
|
# Compiled dependencies as wheels only: newer cryptography and zeroconf
|
||||||
|
# releases stopped publishing Intel Mac wheels, and pip would otherwise try
|
||||||
|
# (and fail) to build them from source. With --only-binary it picks the
|
||||||
|
# newest release that has a wheel for this Mac.
|
||||||
|
"$PY" -m pip install --quiet --prefer-binary \
|
||||||
|
--only-binary=PyQt6,PyQt6-Qt6,PyQt6-sip,numpy,cryptography,zeroconf,pydantic-core,aiohttp,miniaudio,protobuf \
|
||||||
|
-e "$ROOT" \
|
||||||
|
"pyinstaller==$PYINSTALLER_VERSION" \
|
||||||
|
"pyinstaller-hooks-contrib==$HOOKS_CONTRIB_VERSION"
|
||||||
|
"$PY" -m pip list --format=freeze > "$BUILD/pip-freeze-$LABEL.txt"
|
||||||
|
export SSL_CERT_FILE="${SSL_CERT_FILE:-$("$PY" -m certifi)}"
|
||||||
|
|
||||||
|
step "Bundled tools"
|
||||||
|
"$PY" -I "$HERE/fetch_tools.py" --arch "$ARCH" --out "$BUILD/tools"
|
||||||
|
for tool in ffmpeg ffprobe fpcalc; do
|
||||||
|
[[ " $(lipo -archs "$BUILD/tools/$tool") " == *" $ARCH "* ]] \
|
||||||
|
|| die "$tool isn't built for $ARCH"
|
||||||
|
done
|
||||||
|
# What the app needs from ffmpeg (loudness, BPM, DJ decode, AirPlay,
|
||||||
|
# lossless conversion, stems as Opus, stem cache keys). Listed into
|
||||||
|
# variables first: grep -q closing a pipe early would trip pipefail.
|
||||||
|
FF="$BUILD/tools/ffmpeg"
|
||||||
|
ENCODERS="$("$FF" -hide_banner -encoders 2>/dev/null)"
|
||||||
|
DECODERS="$("$FF" -hide_banner -decoders 2>/dev/null)"
|
||||||
|
FILTERS="$("$FF" -hide_banner -filters 2>/dev/null)"
|
||||||
|
MUXERS="$("$FF" -hide_banner -muxers 2>/dev/null)"
|
||||||
|
has() { grep -Eq "^ [A-Z.]{6} $2 " <<<"$1"; }
|
||||||
|
for enc in libmp3lame libopus flac alac pcm_s16be; do
|
||||||
|
has "$ENCODERS" "$enc" || die "ffmpeg lacks the $enc encoder"
|
||||||
|
done
|
||||||
|
for dec in mp3 aac alac flac opus vorbis pcm_s16le pcm_s16be; do
|
||||||
|
has "$DECODERS" "$dec" || die "ffmpeg lacks the $dec decoder"
|
||||||
|
done
|
||||||
|
grep -Eq " ebur128 " <<<"$FILTERS" || die "ffmpeg lacks the ebur128 filter"
|
||||||
|
grep -Eq " hash " <<<"$MUXERS" || die "ffmpeg lacks the hash muxer"
|
||||||
|
"$BUILD/tools/ffprobe" -version >/dev/null || die "ffprobe doesn't run"
|
||||||
|
"$BUILD/tools/fpcalc" -version >/dev/null || die "fpcalc doesn't run"
|
||||||
|
|
||||||
|
step "PyInstaller $PYINSTALLER_VERSION"
|
||||||
|
rm -rf "$BUILD/dist" "$BUILD/work"
|
||||||
|
(cd "$ROOT" && LINTUNES_ARCH="$ARCH" "$VENV/bin/pyinstaller" --noconfirm --clean \
|
||||||
|
--distpath "$BUILD/dist" --workpath "$BUILD/work" "$HERE/LinTunes.spec")
|
||||||
|
APP="$BUILD/dist/$APP_NAME.app"
|
||||||
|
[ -x "$APP/Contents/MacOS/$APP_NAME" ] || die "PyInstaller made no $APP"
|
||||||
|
|
||||||
|
# The helpers sit beside the app's own executable: where Apple wants
|
||||||
|
# nested command-line tools, and the first folder paths.mac_tool_dirs()
|
||||||
|
# puts on PATH.
|
||||||
|
install -m 755 "$BUILD/tools/ffmpeg" "$BUILD/tools/ffprobe" "$BUILD/tools/fpcalc" "$APP/Contents/MacOS/"
|
||||||
|
|
||||||
|
# Nothing of the Rabbit R1's may ride along.
|
||||||
|
if find "$APP" -name '*.apk' -o -name 'andTunes.json' | grep -q .; then
|
||||||
|
die "the R1 app ended up in the bundle"
|
||||||
|
fi
|
||||||
|
xattr -cr "$APP"
|
||||||
|
|
||||||
|
sign_adhoc() {
|
||||||
|
step "Ad-hoc signing"
|
||||||
|
codesign --force --deep --sign - "$APP"
|
||||||
|
echo "Developer ID signing skipped (no MACOS_CERTIFICATE): users will need \"Open Anyway\" once."
|
||||||
|
}
|
||||||
|
|
||||||
|
sign_developer_id() {
|
||||||
|
step "Developer ID signing"
|
||||||
|
KEYCHAIN="$BUILD/signing.keychain-db"
|
||||||
|
KEYCHAIN_PASSWORD="$(uuidgen)"
|
||||||
|
P12="$BUILD/certificate.p12"
|
||||||
|
trap 'security delete-keychain "$KEYCHAIN" >/dev/null 2>&1 || true; rm -f "$P12"' EXIT
|
||||||
|
echo "$MACOS_CERTIFICATE" | base64 --decode > "$P12"
|
||||||
|
security create-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN"
|
||||||
|
security set-keychain-settings -lut 21600 "$KEYCHAIN"
|
||||||
|
security unlock-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN"
|
||||||
|
security import "$P12" -k "$KEYCHAIN" -P "$MACOS_CERTIFICATE_PASSWORD" \
|
||||||
|
-T /usr/bin/codesign
|
||||||
|
security set-key-partition-list -S apple-tool:,apple: -s \
|
||||||
|
-k "$KEYCHAIN_PASSWORD" "$KEYCHAIN" >/dev/null
|
||||||
|
security list-keychains -d user -s "$KEYCHAIN" \
|
||||||
|
$(security list-keychains -d user | tr -d '"')
|
||||||
|
local sign=(codesign --force --timestamp --options runtime
|
||||||
|
--entitlements "$HERE/entitlements.plist"
|
||||||
|
--keychain "$KEYCHAIN" --sign "$MACOS_SIGNING_IDENTITY")
|
||||||
|
# Inside out: every Mach-O file, deepest first, then the frameworks,
|
||||||
|
# then the app. (--deep is not trusted for a Developer ID signature.)
|
||||||
|
while IFS= read -r f; do
|
||||||
|
if file -b "$f" | grep -q "Mach-O"; then "${sign[@]}" "$f"; fi
|
||||||
|
done < <(find "$APP/Contents" -type f ! -path "*/MacOS/$APP_NAME" \
|
||||||
|
| awk '{ print length, $0 }' | sort -rn | cut -d' ' -f2-)
|
||||||
|
while IFS= read -r fw; do "${sign[@]}" "$fw"; done \
|
||||||
|
< <(find "$APP/Contents" -type d -name '*.framework' \
|
||||||
|
| awk '{ print length, $0 }' | sort -rn | cut -d' ' -f2-)
|
||||||
|
"${sign[@]}" "$APP"
|
||||||
|
}
|
||||||
|
|
||||||
|
notarize() {
|
||||||
|
step "Notarizing"
|
||||||
|
codesign --force --timestamp --keychain "$KEYCHAIN" \
|
||||||
|
--sign "$MACOS_SIGNING_IDENTITY" "$DMG"
|
||||||
|
xcrun notarytool submit "$DMG" --wait \
|
||||||
|
--apple-id "$MACOS_NOTARY_APPLE_ID" \
|
||||||
|
--team-id "$MACOS_NOTARY_TEAM_ID" \
|
||||||
|
--password "$MACOS_NOTARY_PASSWORD"
|
||||||
|
xcrun stapler staple "$DMG"
|
||||||
|
xcrun stapler validate "$DMG"
|
||||||
|
}
|
||||||
|
|
||||||
|
DEVELOPER_ID=0
|
||||||
|
if [ -n "${MACOS_CERTIFICATE:-}" ] && [ -n "${MACOS_CERTIFICATE_PASSWORD:-}" ] \
|
||||||
|
&& [ -n "${MACOS_SIGNING_IDENTITY:-}" ]; then
|
||||||
|
DEVELOPER_ID=1
|
||||||
|
sign_developer_id
|
||||||
|
else
|
||||||
|
sign_adhoc
|
||||||
|
fi
|
||||||
|
codesign --verify --deep --strict --verbose=1 "$APP"
|
||||||
|
|
||||||
|
step "Disk image"
|
||||||
|
STAGE="$BUILD/dmg-stage"
|
||||||
|
rm -rf "$STAGE" "$DMG"
|
||||||
|
mkdir -p "$STAGE"
|
||||||
|
ditto "$APP" "$STAGE/$APP_NAME.app"
|
||||||
|
ln -s /Applications "$STAGE/Applications"
|
||||||
|
# hdiutil sometimes fails with "Resource busy" on CI runners; it's
|
||||||
|
# harmless to try again.
|
||||||
|
for attempt in 1 2 3 4 5; do
|
||||||
|
if hdiutil create -volname "$APP_NAME" -srcfolder "$STAGE" -ov \
|
||||||
|
-fs HFS+ -format UDZO "$DMG"; then
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
[ "$attempt" -lt 5 ] || die "hdiutil create failed"
|
||||||
|
echo "hdiutil failed; retrying in 5 s"
|
||||||
|
sleep 5
|
||||||
|
done
|
||||||
|
rm -rf "$STAGE"
|
||||||
|
|
||||||
|
if [ "$DEVELOPER_ID" = 1 ]; then
|
||||||
|
if [ -n "${MACOS_NOTARY_APPLE_ID:-}" ] && [ -n "${MACOS_NOTARY_TEAM_ID:-}" ] \
|
||||||
|
&& [ -n "${MACOS_NOTARY_PASSWORD:-}" ]; then
|
||||||
|
notarize
|
||||||
|
else
|
||||||
|
echo "Notarization skipped (no MACOS_NOTARY_* secrets)."
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
(cd "$BUILD" && shasum -a 256 "$(basename "$DMG")" > "$(basename "$DMG").sha256")
|
||||||
|
step "Done"
|
||||||
|
echo "$DMG"
|
||||||
|
cat "$DMG.sha256"
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
|
<!--
|
||||||
|
Hardened-runtime exceptions for the Developer ID build only (build.sh
|
||||||
|
uses this file when signing secrets are present; the default ad-hoc
|
||||||
|
build has no hardened runtime and ignores it). No App Sandbox: LinTunes
|
||||||
|
reads and moves music anywhere the user keeps it.
|
||||||
|
|
||||||
|
allow-unsigned-executable-memory: libffi closures (ctypes, pyobjc's
|
||||||
|
callbacks into Python for Now Playing's remote commands) write code
|
||||||
|
pages at run time.
|
||||||
|
disable-library-validation: PyInstaller's bootloader loads the bundled
|
||||||
|
Python and Qt libraries; with a Developer ID they are all signed by the
|
||||||
|
same team, but numpy/pyobjc extension modules are sometimes rejected
|
||||||
|
without it. Remove it once a signed build is shown to run without.
|
||||||
|
-->
|
||||||
|
<plist version="1.0">
|
||||||
|
<dict>
|
||||||
|
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
|
||||||
|
<true/>
|
||||||
|
<key>com.apple.security.cs.disable-library-validation</key>
|
||||||
|
<true/>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
||||||
Executable
+121
@@ -0,0 +1,121 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Download the command-line tools LinTunes.app carries, and verify them.
|
||||||
|
|
||||||
|
python3 -I packaging/mac/fetch_tools.py --arch arm64 --out build/tools
|
||||||
|
|
||||||
|
Reads ``tools.json`` beside this file. Each archive is downloaded to a
|
||||||
|
fresh temporary directory, its SHA-256 compared with the pinned one, and
|
||||||
|
only then is the one named member pulled out to ``<out>/<tool>`` (mode
|
||||||
|
755). A mismatch stops everything with a non-zero exit: a build never
|
||||||
|
ships a tool nobody checked. Downloads are cached by hash in
|
||||||
|
``<out>/.cache`` so a rebuild doesn't fetch again.
|
||||||
|
|
||||||
|
Stdlib only, and runs anywhere (the tests check the manifest on Linux).
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import platform
|
||||||
|
import shutil
|
||||||
|
import sys
|
||||||
|
import tarfile
|
||||||
|
import tempfile
|
||||||
|
import urllib.request
|
||||||
|
import zipfile
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
HERE = Path(__file__).resolve().parent
|
||||||
|
MANIFEST = HERE / "tools.json"
|
||||||
|
ARCHES = ("arm64", "x86_64")
|
||||||
|
USER_AGENT = "LinTunes-build"
|
||||||
|
|
||||||
|
|
||||||
|
class VerifyError(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def load_manifest(path: Path = MANIFEST) -> dict:
|
||||||
|
return json.loads(path.read_text())["tools"]
|
||||||
|
|
||||||
|
|
||||||
|
def sha256_of(path: Path) -> str:
|
||||||
|
digest = hashlib.sha256()
|
||||||
|
with open(path, "rb") as f:
|
||||||
|
for block in iter(lambda: f.read(1 << 20), b""):
|
||||||
|
digest.update(block)
|
||||||
|
return digest.hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def verify(path: Path, expected: str) -> None:
|
||||||
|
actual = sha256_of(path)
|
||||||
|
if actual != expected.lower():
|
||||||
|
raise VerifyError(f"{path.name}: SHA-256 {actual}, expected {expected}")
|
||||||
|
|
||||||
|
|
||||||
|
def extract_member(archive: Path, member: str, dest: Path) -> None:
|
||||||
|
"""Copy one named file out of a .zip or .tar.gz — never extractall,
|
||||||
|
so nothing in the archive can land anywhere but ``dest``."""
|
||||||
|
if archive.suffix == ".zip" or zipfile.is_zipfile(archive):
|
||||||
|
with zipfile.ZipFile(archive) as z, z.open(member) as src, \
|
||||||
|
open(dest, "wb") as out:
|
||||||
|
shutil.copyfileobj(src, out)
|
||||||
|
else:
|
||||||
|
with tarfile.open(archive) as t:
|
||||||
|
info = t.getmember(member)
|
||||||
|
if not info.isfile():
|
||||||
|
raise VerifyError(f"{member} is not a regular file")
|
||||||
|
with t.extractfile(info) as src, open(dest, "wb") as out:
|
||||||
|
shutil.copyfileobj(src, out)
|
||||||
|
dest.chmod(0o755)
|
||||||
|
|
||||||
|
|
||||||
|
def download(url: str, dest: Path) -> None:
|
||||||
|
if not url.startswith("https://"):
|
||||||
|
raise VerifyError(f"refusing a non-https download: {url}")
|
||||||
|
request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
|
||||||
|
with urllib.request.urlopen(request, timeout=300) as response, \
|
||||||
|
open(dest, "wb") as out:
|
||||||
|
shutil.copyfileobj(response, out)
|
||||||
|
|
||||||
|
|
||||||
|
def fetch(arch: str, out: Path, manifest: dict | None = None) -> list[Path]:
|
||||||
|
manifest = load_manifest() if manifest is None else manifest
|
||||||
|
out.mkdir(parents=True, exist_ok=True)
|
||||||
|
cache = out / ".cache"
|
||||||
|
cache.mkdir(exist_ok=True)
|
||||||
|
made = []
|
||||||
|
for name, tool in manifest.items():
|
||||||
|
entry = tool["arch"][arch]
|
||||||
|
suffix = ".zip" if entry["url"].endswith(".zip") else ".tar.gz"
|
||||||
|
cached = cache / (entry["sha256"] + suffix)
|
||||||
|
if not (cached.is_file() and sha256_of(cached) == entry["sha256"]):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
part = Path(tmp) / ("download" + suffix)
|
||||||
|
print(f" {name} {tool['version']} ({arch}): {entry['url']}")
|
||||||
|
download(entry["url"], part)
|
||||||
|
verify(part, entry["sha256"])
|
||||||
|
shutil.move(str(part), cached)
|
||||||
|
verify(cached, entry["sha256"])
|
||||||
|
dest = out / name
|
||||||
|
extract_member(cached, entry["member"], dest)
|
||||||
|
print(f" {name}: verified {entry['sha256'][:16]}…, {dest}")
|
||||||
|
made.append(dest)
|
||||||
|
return made
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
native = "arm64" if platform.machine() in ("arm64", "aarch64") else "x86_64"
|
||||||
|
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
||||||
|
ap.add_argument("--arch", choices=ARCHES, default=native)
|
||||||
|
ap.add_argument("--out", type=Path, required=True)
|
||||||
|
args = ap.parse_args()
|
||||||
|
try:
|
||||||
|
fetch(args.arch, args.out)
|
||||||
|
except (VerifyError, OSError, KeyError) as e:
|
||||||
|
print(f"fetch_tools: {e}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
"""LinTunes.app's entry point (PyInstaller runs this file as __main__).
|
||||||
|
|
||||||
|
`lintunes/main.py` is a module of the package, so it can't be the frozen
|
||||||
|
script itself: as __main__ it would be a second copy of lintunes.main
|
||||||
|
beside the one everything else imports.
|
||||||
|
"""
|
||||||
|
from lintunes.main import main
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,674 @@
|
|||||||
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
the GNU General Public License is intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users. We, the Free Software Foundation, use the
|
||||||
|
GNU General Public License for most of our software; it applies also to
|
||||||
|
any other work released this way by its authors. You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to prevent others from denying you
|
||||||
|
these rights or asking you to surrender the rights. Therefore, you have
|
||||||
|
certain responsibilities if you distribute copies of the software, or if
|
||||||
|
you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether
|
||||||
|
gratis or for a fee, you must pass on to the recipients the same
|
||||||
|
freedoms that you received. You must make sure that they, too, receive
|
||||||
|
or can get the source code. And you must show them these terms so they
|
||||||
|
know their rights.
|
||||||
|
|
||||||
|
Developers that use the GNU GPL protect your rights with two steps:
|
||||||
|
(1) assert copyright on the software, and (2) offer you this License
|
||||||
|
giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
|
For the developers' and authors' protection, the GPL clearly explains
|
||||||
|
that there is no warranty for this free software. For both users' and
|
||||||
|
authors' sake, the GPL requires that modified versions be marked as
|
||||||
|
changed, so that their problems will not be attributed erroneously to
|
||||||
|
authors of previous versions.
|
||||||
|
|
||||||
|
Some devices are designed to deny users access to install or run
|
||||||
|
modified versions of the software inside them, although the manufacturer
|
||||||
|
can do so. This is fundamentally incompatible with the aim of
|
||||||
|
protecting users' freedom to change the software. The systematic
|
||||||
|
pattern of such abuse occurs in the area of products for individuals to
|
||||||
|
use, which is precisely where it is most unacceptable. Therefore, we
|
||||||
|
have designed this version of the GPL to prohibit the practice for those
|
||||||
|
products. If such problems arise substantially in other domains, we
|
||||||
|
stand ready to extend this provision to those domains in future versions
|
||||||
|
of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents.
|
||||||
|
States should not allow patents to restrict development and use of
|
||||||
|
software on general-purpose computers, but in those that do, we wish to
|
||||||
|
avoid the special danger that patents applied to a free program could
|
||||||
|
make it effectively proprietary. To prevent this, the GPL assures that
|
||||||
|
patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU Affero General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the special requirements of the GNU Affero General Public License,
|
||||||
|
section 13, concerning interaction through a network will apply to the
|
||||||
|
combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU General Public License from time to time. Such new versions will
|
||||||
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short
|
||||||
|
notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
<program> Copyright (C) <year> <name of author>
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||||
|
parts of the General Public License. Of course, your program's commands
|
||||||
|
might be different; for a GUI interface, you would use an "about box".
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU GPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program
|
||||||
|
into proprietary programs. If your program is a subroutine library, you
|
||||||
|
may consider it more useful to permit linking proprietary applications with
|
||||||
|
the library. If this is what you want to do, use the GNU Lesser General
|
||||||
|
Public License instead of this License. But first, please read
|
||||||
|
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||||
@@ -0,0 +1,501 @@
|
|||||||
|
GNU LESSER GENERAL PUBLIC LICENSE
|
||||||
|
Version 2.1, February 1999
|
||||||
|
|
||||||
|
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
|
||||||
|
<https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
[This is the first released version of the Lesser GPL. It also counts
|
||||||
|
as the successor of the GNU Library Public License, version 2, hence
|
||||||
|
the version number 2.1.]
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The licenses for most software are designed to take away your
|
||||||
|
freedom to share and change it. By contrast, the GNU General Public
|
||||||
|
Licenses are intended to guarantee your freedom to share and change
|
||||||
|
free software--to make sure the software is free for all its users.
|
||||||
|
|
||||||
|
This license, the Lesser General Public License, applies to some
|
||||||
|
specially designated software packages--typically libraries--of the
|
||||||
|
Free Software Foundation and other authors who decide to use it. You
|
||||||
|
can use it too, but we suggest you first think carefully about whether
|
||||||
|
this license or the ordinary General Public License is the better
|
||||||
|
strategy to use in any particular case, based on the explanations below.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom of use,
|
||||||
|
not price. Our General Public Licenses are designed to make sure that
|
||||||
|
you have the freedom to distribute copies of free software (and charge
|
||||||
|
for this service if you wish); that you receive source code or can get
|
||||||
|
it if you want it; that you can change the software and use pieces of
|
||||||
|
it in new free programs; and that you are informed that you can do
|
||||||
|
these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to make restrictions that forbid
|
||||||
|
distributors to deny you these rights or to ask you to surrender these
|
||||||
|
rights. These restrictions translate to certain responsibilities for
|
||||||
|
you if you distribute copies of the library or if you modify it.
|
||||||
|
|
||||||
|
For example, if you distribute copies of the library, whether gratis
|
||||||
|
or for a fee, you must give the recipients all the rights that we gave
|
||||||
|
you. You must make sure that they, too, receive or can get the source
|
||||||
|
code. If you link other code with the library, you must provide
|
||||||
|
complete object files to the recipients, so that they can relink them
|
||||||
|
with the library after making changes to the library and recompiling
|
||||||
|
it. And you must show them these terms so they know their rights.
|
||||||
|
|
||||||
|
We protect your rights with a two-step method: (1) we copyright the
|
||||||
|
library, and (2) we offer you this license, which gives you legal
|
||||||
|
permission to copy, distribute and/or modify the library.
|
||||||
|
|
||||||
|
To protect each distributor, we want to make it very clear that
|
||||||
|
there is no warranty for the free library. Also, if the library is
|
||||||
|
modified by someone else and passed on, the recipients should know
|
||||||
|
that what they have is not the original version, so that the original
|
||||||
|
author's reputation will not be affected by problems that might be
|
||||||
|
introduced by others.
|
||||||
|
|
||||||
|
Finally, software patents pose a constant threat to the existence of
|
||||||
|
any free program. We wish to make sure that a company cannot
|
||||||
|
effectively restrict the users of a free program by obtaining a
|
||||||
|
restrictive license from a patent holder. Therefore, we insist that
|
||||||
|
any patent license obtained for a version of the library must be
|
||||||
|
consistent with the full freedom of use specified in this license.
|
||||||
|
|
||||||
|
Most GNU software, including some libraries, is covered by the
|
||||||
|
ordinary GNU General Public License. This license, the GNU Lesser
|
||||||
|
General Public License, applies to certain designated libraries, and
|
||||||
|
is quite different from the ordinary General Public License. We use
|
||||||
|
this license for certain libraries in order to permit linking those
|
||||||
|
libraries into non-free programs.
|
||||||
|
|
||||||
|
When a program is linked with a library, whether statically or using
|
||||||
|
a shared library, the combination of the two is legally speaking a
|
||||||
|
combined work, a derivative of the original library. The ordinary
|
||||||
|
General Public License therefore permits such linking only if the
|
||||||
|
entire combination fits its criteria of freedom. The Lesser General
|
||||||
|
Public License permits more lax criteria for linking other code with
|
||||||
|
the library.
|
||||||
|
|
||||||
|
We call this license the "Lesser" General Public License because it
|
||||||
|
does Less to protect the user's freedom than the ordinary General
|
||||||
|
Public License. It also provides other free software developers Less
|
||||||
|
of an advantage over competing non-free programs. These disadvantages
|
||||||
|
are the reason we use the ordinary General Public License for many
|
||||||
|
libraries. However, the Lesser license provides advantages in certain
|
||||||
|
special circumstances.
|
||||||
|
|
||||||
|
For example, on rare occasions, there may be a special need to
|
||||||
|
encourage the widest possible use of a certain library, so that it becomes
|
||||||
|
a de-facto standard. To achieve this, non-free programs must be
|
||||||
|
allowed to use the library. A more frequent case is that a free
|
||||||
|
library does the same job as widely used non-free libraries. In this
|
||||||
|
case, there is little to gain by limiting the free library to free
|
||||||
|
software only, so we use the Lesser General Public License.
|
||||||
|
|
||||||
|
In other cases, permission to use a particular library in non-free
|
||||||
|
programs enables a greater number of people to use a large body of
|
||||||
|
free software. For example, permission to use the GNU C Library in
|
||||||
|
non-free programs enables many more people to use the whole GNU
|
||||||
|
operating system, as well as its variant, the GNU/Linux operating
|
||||||
|
system.
|
||||||
|
|
||||||
|
Although the Lesser General Public License is Less protective of the
|
||||||
|
users' freedom, it does ensure that the user of a program that is
|
||||||
|
linked with the Library has the freedom and the wherewithal to run
|
||||||
|
that program using a modified version of the Library.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow. Pay close attention to the difference between a
|
||||||
|
"work based on the library" and a "work that uses the library". The
|
||||||
|
former contains code derived from the library, whereas the latter must
|
||||||
|
be combined with the library in order to run.
|
||||||
|
|
||||||
|
GNU LESSER GENERAL PUBLIC LICENSE
|
||||||
|
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||||
|
|
||||||
|
0. This License Agreement applies to any software library or other
|
||||||
|
program which contains a notice placed by the copyright holder or
|
||||||
|
other authorized party saying it may be distributed under the terms of
|
||||||
|
this Lesser General Public License (also called "this License").
|
||||||
|
Each licensee is addressed as "you".
|
||||||
|
|
||||||
|
A "library" means a collection of software functions and/or data
|
||||||
|
prepared so as to be conveniently linked with application programs
|
||||||
|
(which use some of those functions and data) to form executables.
|
||||||
|
|
||||||
|
The "Library", below, refers to any such software library or work
|
||||||
|
which has been distributed under these terms. A "work based on the
|
||||||
|
Library" means either the Library or any derivative work under
|
||||||
|
copyright law: that is to say, a work containing the Library or a
|
||||||
|
portion of it, either verbatim or with modifications and/or translated
|
||||||
|
straightforwardly into another language. (Hereinafter, translation is
|
||||||
|
included without limitation in the term "modification".)
|
||||||
|
|
||||||
|
"Source code" for a work means the preferred form of the work for
|
||||||
|
making modifications to it. For a library, complete source code means
|
||||||
|
all the source code for all modules it contains, plus any associated
|
||||||
|
interface definition files, plus the scripts used to control compilation
|
||||||
|
and installation of the library.
|
||||||
|
|
||||||
|
Activities other than copying, distribution and modification are not
|
||||||
|
covered by this License; they are outside its scope. The act of
|
||||||
|
running a program using the Library is not restricted, and output from
|
||||||
|
such a program is covered only if its contents constitute a work based
|
||||||
|
on the Library (independent of the use of the Library in a tool for
|
||||||
|
writing it). Whether that is true depends on what the Library does
|
||||||
|
and what the program that uses the Library does.
|
||||||
|
|
||||||
|
1. You may copy and distribute verbatim copies of the Library's
|
||||||
|
complete source code as you receive it, in any medium, provided that
|
||||||
|
you conspicuously and appropriately publish on each copy an
|
||||||
|
appropriate copyright notice and disclaimer of warranty; keep intact
|
||||||
|
all the notices that refer to this License and to the absence of any
|
||||||
|
warranty; and distribute a copy of this License along with the
|
||||||
|
Library.
|
||||||
|
|
||||||
|
You may charge a fee for the physical act of transferring a copy,
|
||||||
|
and you may at your option offer warranty protection in exchange for a
|
||||||
|
fee.
|
||||||
|
|
||||||
|
2. You may modify your copy or copies of the Library or any portion
|
||||||
|
of it, thus forming a work based on the Library, and copy and
|
||||||
|
distribute such modifications or work under the terms of Section 1
|
||||||
|
above, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The modified work must itself be a software library.
|
||||||
|
|
||||||
|
b) You must cause the files modified to carry prominent notices
|
||||||
|
stating that you changed the files and the date of any change.
|
||||||
|
|
||||||
|
c) You must cause the whole of the work to be licensed at no
|
||||||
|
charge to all third parties under the terms of this License.
|
||||||
|
|
||||||
|
d) If a facility in the modified Library refers to a function or a
|
||||||
|
table of data to be supplied by an application program that uses
|
||||||
|
the facility, other than as an argument passed when the facility
|
||||||
|
is invoked, then you must make a good faith effort to ensure that,
|
||||||
|
in the event an application does not supply such function or
|
||||||
|
table, the facility still operates, and performs whatever part of
|
||||||
|
its purpose remains meaningful.
|
||||||
|
|
||||||
|
(For example, a function in a library to compute square roots has
|
||||||
|
a purpose that is entirely well-defined independent of the
|
||||||
|
application. Therefore, Subsection 2d requires that any
|
||||||
|
application-supplied function or table used by this function must
|
||||||
|
be optional: if the application does not supply it, the square
|
||||||
|
root function must still compute square roots.)
|
||||||
|
|
||||||
|
These requirements apply to the modified work as a whole. If
|
||||||
|
identifiable sections of that work are not derived from the Library,
|
||||||
|
and can be reasonably considered independent and separate works in
|
||||||
|
themselves, then this License, and its terms, do not apply to those
|
||||||
|
sections when you distribute them as separate works. But when you
|
||||||
|
distribute the same sections as part of a whole which is a work based
|
||||||
|
on the Library, the distribution of the whole must be on the terms of
|
||||||
|
this License, whose permissions for other licensees extend to the
|
||||||
|
entire whole, and thus to each and every part regardless of who wrote
|
||||||
|
it.
|
||||||
|
|
||||||
|
Thus, it is not the intent of this section to claim rights or contest
|
||||||
|
your rights to work written entirely by you; rather, the intent is to
|
||||||
|
exercise the right to control the distribution of derivative or
|
||||||
|
collective works based on the Library.
|
||||||
|
|
||||||
|
In addition, mere aggregation of another work not based on the Library
|
||||||
|
with the Library (or with a work based on the Library) on a volume of
|
||||||
|
a storage or distribution medium does not bring the other work under
|
||||||
|
the scope of this License.
|
||||||
|
|
||||||
|
3. You may opt to apply the terms of the ordinary GNU General Public
|
||||||
|
License instead of this License to a given copy of the Library. To do
|
||||||
|
this, you must alter all the notices that refer to this License, so
|
||||||
|
that they refer to the ordinary GNU General Public License, version 2,
|
||||||
|
instead of to this License. (If a newer version than version 2 of the
|
||||||
|
ordinary GNU General Public License has appeared, then you can specify
|
||||||
|
that version instead if you wish.) Do not make any other change in
|
||||||
|
these notices.
|
||||||
|
|
||||||
|
Once this change is made in a given copy, it is irreversible for
|
||||||
|
that copy, so the ordinary GNU General Public License applies to all
|
||||||
|
subsequent copies and derivative works made from that copy.
|
||||||
|
|
||||||
|
This option is useful when you wish to copy part of the code of
|
||||||
|
the Library into a program that is not a library.
|
||||||
|
|
||||||
|
4. You may copy and distribute the Library (or a portion or
|
||||||
|
derivative of it, under Section 2) in object code or executable form
|
||||||
|
under the terms of Sections 1 and 2 above provided that you accompany
|
||||||
|
it with the complete corresponding machine-readable source code, which
|
||||||
|
must be distributed under the terms of Sections 1 and 2 above on a
|
||||||
|
medium customarily used for software interchange.
|
||||||
|
|
||||||
|
If distribution of object code is made by offering access to copy
|
||||||
|
from a designated place, then offering equivalent access to copy the
|
||||||
|
source code from the same place satisfies the requirement to
|
||||||
|
distribute the source code, even though third parties are not
|
||||||
|
compelled to copy the source along with the object code.
|
||||||
|
|
||||||
|
5. A program that contains no derivative of any portion of the
|
||||||
|
Library, but is designed to work with the Library by being compiled or
|
||||||
|
linked with it, is called a "work that uses the Library". Such a
|
||||||
|
work, in isolation, is not a derivative work of the Library, and
|
||||||
|
therefore falls outside the scope of this License.
|
||||||
|
|
||||||
|
However, linking a "work that uses the Library" with the Library
|
||||||
|
creates an executable that is a derivative of the Library (because it
|
||||||
|
contains portions of the Library), rather than a "work that uses the
|
||||||
|
library". The executable is therefore covered by this License.
|
||||||
|
Section 6 states terms for distribution of such executables.
|
||||||
|
|
||||||
|
When a "work that uses the Library" uses material from a header file
|
||||||
|
that is part of the Library, the object code for the work may be a
|
||||||
|
derivative work of the Library even though the source code is not.
|
||||||
|
Whether this is true is especially significant if the work can be
|
||||||
|
linked without the Library, or if the work is itself a library. The
|
||||||
|
threshold for this to be true is not precisely defined by law.
|
||||||
|
|
||||||
|
If such an object file uses only numerical parameters, data
|
||||||
|
structure layouts and accessors, and small macros and small inline
|
||||||
|
functions (ten lines or less in length), then the use of the object
|
||||||
|
file is unrestricted, regardless of whether it is legally a derivative
|
||||||
|
work. (Executables containing this object code plus portions of the
|
||||||
|
Library will still fall under Section 6.)
|
||||||
|
|
||||||
|
Otherwise, if the work is a derivative of the Library, you may
|
||||||
|
distribute the object code for the work under the terms of Section 6.
|
||||||
|
Any executables containing that work also fall under Section 6,
|
||||||
|
whether or not they are linked directly with the Library itself.
|
||||||
|
|
||||||
|
6. As an exception to the Sections above, you may also combine or
|
||||||
|
link a "work that uses the Library" with the Library to produce a
|
||||||
|
work containing portions of the Library, and distribute that work
|
||||||
|
under terms of your choice, provided that the terms permit
|
||||||
|
modification of the work for the customer's own use and reverse
|
||||||
|
engineering for debugging such modifications.
|
||||||
|
|
||||||
|
You must give prominent notice with each copy of the work that the
|
||||||
|
Library is used in it and that the Library and its use are covered by
|
||||||
|
this License. You must supply a copy of this License. If the work
|
||||||
|
during execution displays copyright notices, you must include the
|
||||||
|
copyright notice for the Library among them, as well as a reference
|
||||||
|
directing the user to the copy of this License. Also, you must do one
|
||||||
|
of these things:
|
||||||
|
|
||||||
|
a) Accompany the work with the complete corresponding
|
||||||
|
machine-readable source code for the Library including whatever
|
||||||
|
changes were used in the work (which must be distributed under
|
||||||
|
Sections 1 and 2 above); and, if the work is an executable linked
|
||||||
|
with the Library, with the complete machine-readable "work that
|
||||||
|
uses the Library", as object code and/or source code, so that the
|
||||||
|
user can modify the Library and then relink to produce a modified
|
||||||
|
executable containing the modified Library. (It is understood
|
||||||
|
that the user who changes the contents of definitions files in the
|
||||||
|
Library will not necessarily be able to recompile the application
|
||||||
|
to use the modified definitions.)
|
||||||
|
|
||||||
|
b) Use a suitable shared library mechanism for linking with the
|
||||||
|
Library. A suitable mechanism is one that (1) uses at run time a
|
||||||
|
copy of the library already present on the user's computer system,
|
||||||
|
rather than copying library functions into the executable, and (2)
|
||||||
|
will operate properly with a modified version of the library, if
|
||||||
|
the user installs one, as long as the modified version is
|
||||||
|
interface-compatible with the version that the work was made with.
|
||||||
|
|
||||||
|
c) Accompany the work with a written offer, valid for at
|
||||||
|
least three years, to give the same user the materials
|
||||||
|
specified in Subsection 6a, above, for a charge no more
|
||||||
|
than the cost of performing this distribution.
|
||||||
|
|
||||||
|
d) If distribution of the work is made by offering access to copy
|
||||||
|
from a designated place, offer equivalent access to copy the above
|
||||||
|
specified materials from the same place.
|
||||||
|
|
||||||
|
e) Verify that the user has already received a copy of these
|
||||||
|
materials or that you have already sent this user a copy.
|
||||||
|
|
||||||
|
For an executable, the required form of the "work that uses the
|
||||||
|
Library" must include any data and utility programs needed for
|
||||||
|
reproducing the executable from it. However, as a special exception,
|
||||||
|
the materials to be distributed need not include anything that is
|
||||||
|
normally distributed (in either source or binary form) with the major
|
||||||
|
components (compiler, kernel, and so on) of the operating system on
|
||||||
|
which the executable runs, unless that component itself accompanies
|
||||||
|
the executable.
|
||||||
|
|
||||||
|
It may happen that this requirement contradicts the license
|
||||||
|
restrictions of other proprietary libraries that do not normally
|
||||||
|
accompany the operating system. Such a contradiction means you cannot
|
||||||
|
use both them and the Library together in an executable that you
|
||||||
|
distribute.
|
||||||
|
|
||||||
|
7. You may place library facilities that are a work based on the
|
||||||
|
Library side-by-side in a single library together with other library
|
||||||
|
facilities not covered by this License, and distribute such a combined
|
||||||
|
library, provided that the separate distribution of the work based on
|
||||||
|
the Library and of the other library facilities is otherwise
|
||||||
|
permitted, and provided that you do these two things:
|
||||||
|
|
||||||
|
a) Accompany the combined library with a copy of the same work
|
||||||
|
based on the Library, uncombined with any other library
|
||||||
|
facilities. This must be distributed under the terms of the
|
||||||
|
Sections above.
|
||||||
|
|
||||||
|
b) Give prominent notice with the combined library of the fact
|
||||||
|
that part of it is a work based on the Library, and explaining
|
||||||
|
where to find the accompanying uncombined form of the same work.
|
||||||
|
|
||||||
|
8. You may not copy, modify, sublicense, link with, or distribute
|
||||||
|
the Library except as expressly provided under this License. Any
|
||||||
|
attempt otherwise to copy, modify, sublicense, link with, or
|
||||||
|
distribute the Library is void, and will automatically terminate your
|
||||||
|
rights under this License. However, parties who have received copies,
|
||||||
|
or rights, from you under this License will not have their licenses
|
||||||
|
terminated so long as such parties remain in full compliance.
|
||||||
|
|
||||||
|
9. You are not required to accept this License, since you have not
|
||||||
|
signed it. However, nothing else grants you permission to modify or
|
||||||
|
distribute the Library or its derivative works. These actions are
|
||||||
|
prohibited by law if you do not accept this License. Therefore, by
|
||||||
|
modifying or distributing the Library (or any work based on the
|
||||||
|
Library), you indicate your acceptance of this License to do so, and
|
||||||
|
all its terms and conditions for copying, distributing or modifying
|
||||||
|
the Library or works based on it.
|
||||||
|
|
||||||
|
10. Each time you redistribute the Library (or any work based on the
|
||||||
|
Library), the recipient automatically receives a license from the
|
||||||
|
original licensor to copy, distribute, link with or modify the Library
|
||||||
|
subject to these terms and conditions. You may not impose any further
|
||||||
|
restrictions on the recipients' exercise of the rights granted herein.
|
||||||
|
You are not responsible for enforcing compliance by third parties with
|
||||||
|
this License.
|
||||||
|
|
||||||
|
11. If, as a consequence of a court judgment or allegation of patent
|
||||||
|
infringement or for any other reason (not limited to patent issues),
|
||||||
|
conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot
|
||||||
|
distribute so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you
|
||||||
|
may not distribute the Library at all. For example, if a patent
|
||||||
|
license would not permit royalty-free redistribution of the Library by
|
||||||
|
all those who receive copies directly or indirectly through you, then
|
||||||
|
the only way you could satisfy both it and this License would be to
|
||||||
|
refrain entirely from distribution of the Library.
|
||||||
|
|
||||||
|
If any portion of this section is held invalid or unenforceable under any
|
||||||
|
particular circumstance, the balance of the section is intended to apply,
|
||||||
|
and the section as a whole is intended to apply in other circumstances.
|
||||||
|
|
||||||
|
It is not the purpose of this section to induce you to infringe any
|
||||||
|
patents or other property right claims or to contest validity of any
|
||||||
|
such claims; this section has the sole purpose of protecting the
|
||||||
|
integrity of the free software distribution system which is
|
||||||
|
implemented by public license practices. Many people have made
|
||||||
|
generous contributions to the wide range of software distributed
|
||||||
|
through that system in reliance on consistent application of that
|
||||||
|
system; it is up to the author/donor to decide if he or she is willing
|
||||||
|
to distribute software through any other system and a licensee cannot
|
||||||
|
impose that choice.
|
||||||
|
|
||||||
|
This section is intended to make thoroughly clear what is believed to
|
||||||
|
be a consequence of the rest of this License.
|
||||||
|
|
||||||
|
12. If the distribution and/or use of the Library is restricted in
|
||||||
|
certain countries either by patents or by copyrighted interfaces, the
|
||||||
|
original copyright holder who places the Library under this License may add
|
||||||
|
an explicit geographical distribution limitation excluding those countries,
|
||||||
|
so that distribution is permitted only in or among countries not thus
|
||||||
|
excluded. In such case, this License incorporates the limitation as if
|
||||||
|
written in the body of this License.
|
||||||
|
|
||||||
|
13. The Free Software Foundation may publish revised and/or new
|
||||||
|
versions of the Lesser General Public License from time to time.
|
||||||
|
Such new versions will be similar in spirit to the present version,
|
||||||
|
but may differ in detail to address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the Library
|
||||||
|
specifies a version number of this License which applies to it and
|
||||||
|
"any later version", you have the option of following the terms and
|
||||||
|
conditions either of that version or of any later version published by
|
||||||
|
the Free Software Foundation. If the Library does not specify a
|
||||||
|
license version number, you may choose any version ever published by
|
||||||
|
the Free Software Foundation.
|
||||||
|
|
||||||
|
14. If you wish to incorporate parts of the Library into other free
|
||||||
|
programs whose distribution conditions are incompatible with these,
|
||||||
|
write to the author to ask for permission. For software which is
|
||||||
|
copyrighted by the Free Software Foundation, write to the Free
|
||||||
|
Software Foundation; we sometimes make exceptions for this. Our
|
||||||
|
decision will be guided by the two goals of preserving the free status
|
||||||
|
of all derivatives of our free software and of promoting the sharing
|
||||||
|
and reuse of software generally.
|
||||||
|
|
||||||
|
NO WARRANTY
|
||||||
|
|
||||||
|
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
|
||||||
|
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
|
||||||
|
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
|
||||||
|
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
|
||||||
|
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
|
||||||
|
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
|
||||||
|
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
|
||||||
|
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
|
||||||
|
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
|
||||||
|
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
|
||||||
|
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
|
||||||
|
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
|
||||||
|
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
|
||||||
|
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
|
||||||
|
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
|
||||||
|
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
|
||||||
|
DAMAGES.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Libraries
|
||||||
|
|
||||||
|
If you develop a new library, and you want it to be of the greatest
|
||||||
|
possible use to the public, we recommend making it free software that
|
||||||
|
everyone can redistribute and change. You can do so by permitting
|
||||||
|
redistribution under these terms (or, alternatively, under the terms of the
|
||||||
|
ordinary General Public License).
|
||||||
|
|
||||||
|
To apply these terms, attach the following notices to the library. It is
|
||||||
|
safest to attach them to the start of each source file to most effectively
|
||||||
|
convey the exclusion of warranty; and each file should have at least the
|
||||||
|
"copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the library's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This library is free software; you can redistribute it and/or
|
||||||
|
modify it under the terms of the GNU Lesser General Public
|
||||||
|
License as published by the Free Software Foundation; either
|
||||||
|
version 2.1 of the License, or (at your option) any later version.
|
||||||
|
|
||||||
|
This library is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||||
|
Lesser General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Lesser General Public
|
||||||
|
License along with this library; if not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or your
|
||||||
|
school, if any, to sign a "copyright disclaimer" for the library, if
|
||||||
|
necessary. Here is a sample; alter the names:
|
||||||
|
|
||||||
|
Yoyodyne, Inc., hereby disclaims all copyright interest in the
|
||||||
|
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
|
||||||
|
|
||||||
|
<signature of Moe Ghoul>, 1 April 1990
|
||||||
|
Moe Ghoul, President of Vice
|
||||||
|
|
||||||
|
That's all there is to it!
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
GNU LESSER GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
|
||||||
|
This version of the GNU Lesser General Public License incorporates
|
||||||
|
the terms and conditions of version 3 of the GNU General Public
|
||||||
|
License, supplemented by the additional permissions listed below.
|
||||||
|
|
||||||
|
0. Additional Definitions.
|
||||||
|
|
||||||
|
As used herein, "this License" refers to version 3 of the GNU Lesser
|
||||||
|
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
||||||
|
General Public License.
|
||||||
|
|
||||||
|
"The Library" refers to a covered work governed by this License,
|
||||||
|
other than an Application or a Combined Work as defined below.
|
||||||
|
|
||||||
|
An "Application" is any work that makes use of an interface provided
|
||||||
|
by the Library, but which is not otherwise based on the Library.
|
||||||
|
Defining a subclass of a class defined by the Library is deemed a mode
|
||||||
|
of using an interface provided by the Library.
|
||||||
|
|
||||||
|
A "Combined Work" is a work produced by combining or linking an
|
||||||
|
Application with the Library. The particular version of the Library
|
||||||
|
with which the Combined Work was made is also called the "Linked
|
||||||
|
Version".
|
||||||
|
|
||||||
|
The "Minimal Corresponding Source" for a Combined Work means the
|
||||||
|
Corresponding Source for the Combined Work, excluding any source code
|
||||||
|
for portions of the Combined Work that, considered in isolation, are
|
||||||
|
based on the Application, and not on the Linked Version.
|
||||||
|
|
||||||
|
The "Corresponding Application Code" for a Combined Work means the
|
||||||
|
object code and/or source code for the Application, including any data
|
||||||
|
and utility programs needed for reproducing the Combined Work from the
|
||||||
|
Application, but excluding the System Libraries of the Combined Work.
|
||||||
|
|
||||||
|
1. Exception to Section 3 of the GNU GPL.
|
||||||
|
|
||||||
|
You may convey a covered work under sections 3 and 4 of this License
|
||||||
|
without being bound by section 3 of the GNU GPL.
|
||||||
|
|
||||||
|
2. Conveying Modified Versions.
|
||||||
|
|
||||||
|
If you modify a copy of the Library, and, in your modifications, a
|
||||||
|
facility refers to a function or data to be supplied by an Application
|
||||||
|
that uses the facility (other than as an argument passed when the
|
||||||
|
facility is invoked), then you may convey a copy of the modified
|
||||||
|
version:
|
||||||
|
|
||||||
|
a) under this License, provided that you make a good faith effort to
|
||||||
|
ensure that, in the event an Application does not supply the
|
||||||
|
function or data, the facility still operates, and performs
|
||||||
|
whatever part of its purpose remains meaningful, or
|
||||||
|
|
||||||
|
b) under the GNU GPL, with none of the additional permissions of
|
||||||
|
this License applicable to that copy.
|
||||||
|
|
||||||
|
3. Object Code Incorporating Material from Library Header Files.
|
||||||
|
|
||||||
|
The object code form of an Application may incorporate material from
|
||||||
|
a header file that is part of the Library. You may convey such object
|
||||||
|
code under terms of your choice, provided that, if the incorporated
|
||||||
|
material is not limited to numerical parameters, data structure
|
||||||
|
layouts and accessors, or small macros, inline functions and templates
|
||||||
|
(ten or fewer lines in length), you do both of the following:
|
||||||
|
|
||||||
|
a) Give prominent notice with each copy of the object code that the
|
||||||
|
Library is used in it and that the Library and its use are
|
||||||
|
covered by this License.
|
||||||
|
|
||||||
|
b) Accompany the object code with a copy of the GNU GPL and this license
|
||||||
|
document.
|
||||||
|
|
||||||
|
4. Combined Works.
|
||||||
|
|
||||||
|
You may convey a Combined Work under terms of your choice that,
|
||||||
|
taken together, effectively do not restrict modification of the
|
||||||
|
portions of the Library contained in the Combined Work and reverse
|
||||||
|
engineering for debugging such modifications, if you also do each of
|
||||||
|
the following:
|
||||||
|
|
||||||
|
a) Give prominent notice with each copy of the Combined Work that
|
||||||
|
the Library is used in it and that the Library and its use are
|
||||||
|
covered by this License.
|
||||||
|
|
||||||
|
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
||||||
|
document.
|
||||||
|
|
||||||
|
c) For a Combined Work that displays copyright notices during
|
||||||
|
execution, include the copyright notice for the Library among
|
||||||
|
these notices, as well as a reference directing the user to the
|
||||||
|
copies of the GNU GPL and this license document.
|
||||||
|
|
||||||
|
d) Do one of the following:
|
||||||
|
|
||||||
|
0) Convey the Minimal Corresponding Source under the terms of this
|
||||||
|
License, and the Corresponding Application Code in a form
|
||||||
|
suitable for, and under terms that permit, the user to
|
||||||
|
recombine or relink the Application with a modified version of
|
||||||
|
the Linked Version to produce a modified Combined Work, in the
|
||||||
|
manner specified by section 6 of the GNU GPL for conveying
|
||||||
|
Corresponding Source.
|
||||||
|
|
||||||
|
1) Use a suitable shared library mechanism for linking with the
|
||||||
|
Library. A suitable mechanism is one that (a) uses at run time
|
||||||
|
a copy of the Library already present on the user's computer
|
||||||
|
system, and (b) will operate properly with a modified version
|
||||||
|
of the Library that is interface-compatible with the Linked
|
||||||
|
Version.
|
||||||
|
|
||||||
|
e) Provide Installation Information, but only if you would otherwise
|
||||||
|
be required to provide such information under section 6 of the
|
||||||
|
GNU GPL, and only to the extent that such information is
|
||||||
|
necessary to install and execute a modified version of the
|
||||||
|
Combined Work produced by recombining or relinking the
|
||||||
|
Application with a modified version of the Linked Version. (If
|
||||||
|
you use option 4d0, the Installation Information must accompany
|
||||||
|
the Minimal Corresponding Source and Corresponding Application
|
||||||
|
Code. If you use option 4d1, you must provide the Installation
|
||||||
|
Information in the manner specified by section 6 of the GNU GPL
|
||||||
|
for conveying Corresponding Source.)
|
||||||
|
|
||||||
|
5. Combined Libraries.
|
||||||
|
|
||||||
|
You may place library facilities that are a work based on the
|
||||||
|
Library side by side in a single library together with other library
|
||||||
|
facilities that are not Applications and are not covered by this
|
||||||
|
License, and convey such a combined library under terms of your
|
||||||
|
choice, if you do both of the following:
|
||||||
|
|
||||||
|
a) Accompany the combined library with a copy of the same work based
|
||||||
|
on the Library, uncombined with any other library facilities,
|
||||||
|
conveyed under the terms of this License.
|
||||||
|
|
||||||
|
b) Give prominent notice with the combined library that part of it
|
||||||
|
is a work based on the Library, and explaining where to find the
|
||||||
|
accompanying uncombined form of the same work.
|
||||||
|
|
||||||
|
6. Revised Versions of the GNU Lesser General Public License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions
|
||||||
|
of the GNU Lesser General Public License from time to time. Such new
|
||||||
|
versions will be similar in spirit to the present version, but may
|
||||||
|
differ in detail to address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Library as you received it specifies that a certain numbered version
|
||||||
|
of the GNU Lesser General Public License "or any later version"
|
||||||
|
applies to it, you have the option of following the terms and
|
||||||
|
conditions either of that published version or of any later version
|
||||||
|
published by the Free Software Foundation. If the Library as you
|
||||||
|
received it does not specify a version number of the GNU Lesser
|
||||||
|
General Public License, you may choose any version of the GNU Lesser
|
||||||
|
General Public License ever published by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Library as you received it specifies that a proxy can decide
|
||||||
|
whether future versions of the GNU Lesser General Public License shall
|
||||||
|
apply, that proxy's public statement of acceptance of any version is
|
||||||
|
permanent authorization for you to choose that version for the
|
||||||
|
Library.
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
License
|
||||||
|
=======
|
||||||
|
|
||||||
|
Chromaprint's own source code is licensed under the MIT license, but we
|
||||||
|
include some parts of the FFmpeg library, which is licensed under the
|
||||||
|
LGPL 2.1 license.
|
||||||
|
|
||||||
|
As a whole, Chromaprint should be therefore considered to be licensed
|
||||||
|
under the LGPL 2.1 license. We are hoping to remove the included
|
||||||
|
FFmpeg code and make MIT the only license used in the project.
|
||||||
|
|
||||||
|
Note that when distributing Chromaprint in binary form, you should
|
||||||
|
also take into consideration the license of the external FFT library
|
||||||
|
that you compile Chromaprint with.
|
||||||
|
|
||||||
|
## MIT License
|
||||||
|
|
||||||
|
Copyright (C) 2010-2016 Lukas Lalinsky
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
||||||
|
|
||||||
|
## GNU Lesser General Public License version 2.1 (LGPL 2.1)
|
||||||
|
|
||||||
|
You can find the full text of the license [here](https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html).
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
"""LinTunes.app's Info.plist entries, as plain data.
|
||||||
|
|
||||||
|
Kept out of the .spec so the tests can check it on Linux. The spec hands
|
||||||
|
``info_plist(version)`` to PyInstaller's BUNDLE, which adds the keys it
|
||||||
|
owns itself (executable, icon file, bundle name/identifier).
|
||||||
|
"""
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
sys.path.insert(0, str(ROOT))
|
||||||
|
from lintunes import release_info # noqa: E402 (pure Python, no Qt)
|
||||||
|
|
||||||
|
# PyQt6 6.12's macOS wheel is tagged macosx_14_0 (Sonoma); Qt itself would
|
||||||
|
# go a little lower, but the bindings decide. Raise it when PyQt6 does.
|
||||||
|
MINIMUM_MACOS = "14.0"
|
||||||
|
|
||||||
|
# Every Bonjour service the app browses for. Chromecast (pychromecast);
|
||||||
|
# AirPlay speakers through pyatv's scan of the AirPlay and RAOP protocols,
|
||||||
|
# which also reads the device-info and sleep-proxy records it finds.
|
||||||
|
BONJOUR_SERVICES = [
|
||||||
|
"_googlecast._tcp",
|
||||||
|
"_raop._tcp",
|
||||||
|
"_airplay._tcp",
|
||||||
|
"_device-info._tcp",
|
||||||
|
"_sleep-proxy._udp",
|
||||||
|
]
|
||||||
|
|
||||||
|
# Audio the app can import, so files can be dropped on the Dock icon or
|
||||||
|
# opened with "Open With". "Alternate": LinTunes never claims to be the
|
||||||
|
# default app for any of them.
|
||||||
|
AUDIO_TYPES = [
|
||||||
|
"public.mp3",
|
||||||
|
"public.mpeg-4-audio",
|
||||||
|
"com.apple.m4a-audio",
|
||||||
|
"com.apple.protected-mpeg-4-audio",
|
||||||
|
"public.aac-audio",
|
||||||
|
"org.xiph.flac",
|
||||||
|
"public.aiff-audio",
|
||||||
|
"public.aifc-audio",
|
||||||
|
"com.microsoft.waveform-audio",
|
||||||
|
"public.audio",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def version() -> str:
|
||||||
|
text = (ROOT / "lintunes" / "__init__.py").read_text()
|
||||||
|
return re.search(r'^__version__ = "([^"]+)"', text, re.MULTILINE)[1]
|
||||||
|
|
||||||
|
|
||||||
|
def info_plist(app_version: str | None = None) -> dict:
|
||||||
|
app_version = app_version or version()
|
||||||
|
return {
|
||||||
|
"CFBundleName": release_info.APP_NAME,
|
||||||
|
"CFBundleDisplayName": release_info.APP_NAME,
|
||||||
|
"CFBundleIdentifier": release_info.BUNDLE_ID,
|
||||||
|
"CFBundleShortVersionString": app_version,
|
||||||
|
"CFBundleVersion": app_version,
|
||||||
|
"CFBundlePackageType": "APPL",
|
||||||
|
"NSPrincipalClass": "NSApplication",
|
||||||
|
"NSHighResolutionCapable": True,
|
||||||
|
"NSRequiresAquaSystemAppearance": False, # dark mode allowed
|
||||||
|
"LSMinimumSystemVersion": MINIMUM_MACOS,
|
||||||
|
"LSApplicationCategoryType": "public.app-category.music",
|
||||||
|
"NSHumanReadableCopyright":
|
||||||
|
"LinTunes. Bundled tools: see Contents/Resources/licenses.",
|
||||||
|
# macOS 15+ asks before an app talks to the local network: casting
|
||||||
|
# and AirPlay find speakers with Bonjour, then stream to them.
|
||||||
|
"NSLocalNetworkUsageDescription":
|
||||||
|
"LinTunes looks for Chromecast and AirPlay speakers on your "
|
||||||
|
"network so it can play music on them.",
|
||||||
|
"NSBonjourServices": list(BONJOUR_SERVICES),
|
||||||
|
"CFBundleDocumentTypes": [{
|
||||||
|
"CFBundleTypeName": "Audio file",
|
||||||
|
"CFBundleTypeRole": "Viewer",
|
||||||
|
"LSHandlerRank": "Alternate",
|
||||||
|
"LSItemContentTypes": list(AUDIO_TYPES),
|
||||||
|
}],
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
# PyInstaller runtime hook: give the frozen app's OpenSSL a CA bundle.
|
||||||
|
#
|
||||||
|
# A Python built for macOS asks OpenSSL for certificates in its own
|
||||||
|
# framework folder, which the .app doesn't have, so every https request
|
||||||
|
# made with plain urllib (the Spleeter and cliairplay downloads) would fail
|
||||||
|
# with CERTIFICATE_VERIFY_FAILED. requests brings certifi; point OpenSSL at
|
||||||
|
# its bundle unless the user already chose one.
|
||||||
|
import os
|
||||||
|
|
||||||
|
try:
|
||||||
|
import certifi
|
||||||
|
os.environ.setdefault("SSL_CERT_FILE", certifi.where())
|
||||||
|
except Exception: # noqa: BLE001 — no certifi: leave OpenSSL's default
|
||||||
|
pass
|
||||||
Executable
+87
@@ -0,0 +1,87 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Launch the built LinTunes.app against a throwaway library and check it
|
||||||
|
# stays up, then (if the app supports it) quits cleanly.
|
||||||
|
#
|
||||||
|
# packaging/mac/smoke_test.sh build/mac/dist/LinTunes.app [seconds]
|
||||||
|
#
|
||||||
|
# The library comes from scripts/make_dev_library.py (never a real one),
|
||||||
|
# built with the app's own ffmpeg. Every per-machine folder points into a
|
||||||
|
# temporary directory (XDG_* win over ~/Library in lintunes/paths.py), so
|
||||||
|
# the runner's home is never touched.
|
||||||
|
#
|
||||||
|
# Clean exit: the app is started with LINTUNES_QUIT_AFTER_MS. If main.py
|
||||||
|
# honours it, the app must exit 0 on its own; if it doesn't (yet), the
|
||||||
|
# test only proves the app stayed up, then stops it, and says so.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
APP="${1:?usage: smoke_test.sh path/to/LinTunes.app [seconds]}"
|
||||||
|
SECONDS_UP="${2:-20}"
|
||||||
|
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||||
|
EXE="$APP/Contents/MacOS/LinTunes"
|
||||||
|
[ -x "$EXE" ] || { echo "no executable at $EXE" >&2; exit 1; }
|
||||||
|
|
||||||
|
WORK="$(mktemp -d)"
|
||||||
|
trap 'rm -rf "$WORK"' EXIT
|
||||||
|
export XDG_CONFIG_HOME="$WORK/config" XDG_DATA_HOME="$WORK/share" \
|
||||||
|
XDG_CACHE_HOME="$WORK/cache"
|
||||||
|
export QT_QPA_PLATFORM="${QT_QPA_PLATFORM:-offscreen}"
|
||||||
|
|
||||||
|
echo "==> Bundled tools run"
|
||||||
|
"$APP/Contents/MacOS/ffmpeg" -hide_banner -version | sed -n 1p
|
||||||
|
"$APP/Contents/MacOS/fpcalc" -version
|
||||||
|
|
||||||
|
echo "==> Throwaway library"
|
||||||
|
# The generator imports lintunes (mutagen): build.sh's venv has it.
|
||||||
|
PY="${PYTHON:-$ROOT/build/mac/venv/bin/python}"
|
||||||
|
[ -x "$PY" ] || PY=python3
|
||||||
|
PATH="$APP/Contents/MacOS:$PATH" "$PY" "$ROOT/scripts/make_dev_library.py" \
|
||||||
|
--out "$WORK/lib" >/dev/null
|
||||||
|
DATA="$WORK/lib/data"
|
||||||
|
[ -f "$DATA/library.json" ] || { echo "make_dev_library made no library" >&2; exit 1; }
|
||||||
|
|
||||||
|
echo "==> Launching for ${SECONDS_UP}s"
|
||||||
|
LOG="$WORK/app.log"
|
||||||
|
LINTUNES_QUIT_AFTER_MS=$((SECONDS_UP * 1000)) \
|
||||||
|
"$EXE" --data-dir "$DATA" >"$LOG" 2>&1 &
|
||||||
|
PID=$!
|
||||||
|
|
||||||
|
fail() {
|
||||||
|
echo "SMOKE TEST FAILED: $*" >&2
|
||||||
|
echo "---- app output ----" >&2
|
||||||
|
cat "$LOG" >&2
|
||||||
|
kill -9 "$PID" 2>/dev/null || true
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
for _ in $(seq "$SECONDS_UP"); do
|
||||||
|
sleep 1
|
||||||
|
kill -0 "$PID" 2>/dev/null || {
|
||||||
|
wait "$PID" && status=0 || status=$?
|
||||||
|
fail "the app exited after less than ${SECONDS_UP}s (status $status)"
|
||||||
|
}
|
||||||
|
done
|
||||||
|
echo "still running after ${SECONDS_UP}s"
|
||||||
|
|
||||||
|
# Give a self-quit up to 30 s to finish.
|
||||||
|
for _ in $(seq 30); do
|
||||||
|
kill -0 "$PID" 2>/dev/null || break
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
if kill -0 "$PID" 2>/dev/null; then
|
||||||
|
echo "NOTE: the app ignores LINTUNES_QUIT_AFTER_MS, so a clean exit wasn't tested; stopping it."
|
||||||
|
kill -TERM "$PID" 2>/dev/null || true
|
||||||
|
sleep 3
|
||||||
|
kill -9 "$PID" 2>/dev/null || true
|
||||||
|
wait "$PID" 2>/dev/null || true
|
||||||
|
else
|
||||||
|
wait "$PID" && status=0 || status=$?
|
||||||
|
[ "$status" -eq 0 ] || fail "the app quit with status $status"
|
||||||
|
echo "quit cleanly"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if grep -q "Traceback (most recent call last)" "$LOG"; then
|
||||||
|
fail "a Python traceback was logged"
|
||||||
|
fi
|
||||||
|
echo "---- app output (tail) ----"
|
||||||
|
tail -n 40 "$LOG"
|
||||||
|
echo "SMOKE TEST PASSED"
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
{
|
||||||
|
"_comment": "Command-line tools LinTunes.app carries in Contents/MacOS. Every download is checked against the SHA-256 here before it is unpacked; fetch_tools.py refuses anything else. To bump a version: download the new archive, compute its sha256 yourself, compare it with the publisher's checksum, and change url + sha256 together. See THIRD-PARTY.md for the licenses.",
|
||||||
|
"tools": {
|
||||||
|
"ffmpeg": {
|
||||||
|
"version": "9.0.2",
|
||||||
|
"source": "Martin Riedl's static macOS builds (https://ffmpeg.martin-riedl.de), configured --enable-gpl --enable-version3 with libmp3lame, libopus, libvorbis",
|
||||||
|
"license": "GPL-3.0-or-later",
|
||||||
|
"arch": {
|
||||||
|
"arm64": {
|
||||||
|
"url": "https://ffmpeg.martin-riedl.de/download/macos/arm64/1789931890_9.0.2/ffmpeg.zip",
|
||||||
|
"sha256": "c8ed4c4e6978a03c485edbfe4e0a5dc2380f8a30bba5150531b31b094492d924",
|
||||||
|
"member": "ffmpeg"
|
||||||
|
},
|
||||||
|
"x86_64": {
|
||||||
|
"url": "https://ffmpeg.martin-riedl.de/download/macos/amd64/1789931006_9.0.2/ffmpeg.zip",
|
||||||
|
"sha256": "7c6b4125b191cbf773832dc51f424cf2b6bb7da43007d1e066f95909e47cacd4",
|
||||||
|
"member": "ffmpeg"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"ffprobe": {
|
||||||
|
"version": "9.0.2",
|
||||||
|
"source": "Martin Riedl's static macOS builds (https://ffmpeg.martin-riedl.de); Demucs's own loader calls it",
|
||||||
|
"license": "GPL-3.0-or-later",
|
||||||
|
"arch": {
|
||||||
|
"arm64": {
|
||||||
|
"url": "https://ffmpeg.martin-riedl.de/download/macos/arm64/1789931890_9.0.2/ffprobe.zip",
|
||||||
|
"sha256": "fcbe839537485eaee7a7a8bc5cbc0f90d53617e80943e8a5b2e31cb851197ea6",
|
||||||
|
"member": "ffprobe"
|
||||||
|
},
|
||||||
|
"x86_64": {
|
||||||
|
"url": "https://ffmpeg.martin-riedl.de/download/macos/amd64/1789931006_9.0.2/ffprobe.zip",
|
||||||
|
"sha256": "2322438ed2f6319a691291b247d09c69dcaa3a982460d1f269a7e1af335cfdfd",
|
||||||
|
"member": "ffprobe"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"fpcalc": {
|
||||||
|
"version": "1.6.2",
|
||||||
|
"source": "Chromaprint's own release binaries (https://github.com/acoustid/chromaprint/releases/tag/v1.6.2)",
|
||||||
|
"license": "LGPL-2.1-or-later (MIT for Chromaprint's own code)",
|
||||||
|
"arch": {
|
||||||
|
"arm64": {
|
||||||
|
"url": "https://github.com/acoustid/chromaprint/releases/download/v1.6.2/chromaprint-fpcalc-1.6.2-macos-arm64.tar.gz",
|
||||||
|
"sha256": "f3bc56cb42d89a01237bb3f3629329e4ec75f7c1b0217acf6e9bf952ac47979b",
|
||||||
|
"member": "chromaprint-fpcalc-1.6.2-macos-arm64/fpcalc"
|
||||||
|
},
|
||||||
|
"x86_64": {
|
||||||
|
"url": "https://github.com/acoustid/chromaprint/releases/download/v1.6.2/chromaprint-fpcalc-1.6.2-macos-x86_64.tar.gz",
|
||||||
|
"sha256": "5f7b21964163e9e1719ca76d89e71873e2bdba87e9c01d1bcb06da67132da2bb",
|
||||||
|
"member": "chromaprint-fpcalc-1.6.2-macos-x86_64/fpcalc"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,3 +3,6 @@ mutagen>=1.46
|
|||||||
numpy>=1.24
|
numpy>=1.24
|
||||||
requests>=2.28
|
requests>=2.28
|
||||||
pychromecast>=14.0.10
|
pychromecast>=14.0.10
|
||||||
|
pyatv>=0.18.0
|
||||||
|
pyobjc-framework-Cocoa>=10.0; sys_platform == "darwin"
|
||||||
|
pyobjc-framework-MediaPlayer>=10.0; sys_platform == "darwin"
|
||||||
|
|||||||
+103
-7
@@ -4,10 +4,25 @@ from its centre with its corners rounded at wave's radius (16 % of the
|
|||||||
side), as packaging/lintunes.png (desktop, 512 px) and andTunes' launcher
|
side), as packaging/lintunes.png (desktop, 512 px) and andTunes' launcher
|
||||||
(andtunes/app/src/main/res/drawable-nodpi/ic_launcher.png, 192 px) — the
|
(andtunes/app/src/main/res/drawable-nodpi/ic_launcher.png, 192 px) — the
|
||||||
same icon on both. Re-run after changing lint.jpg; the outputs are
|
same icon on both. Re-run after changing lint.jpg; the outputs are
|
||||||
committed, and the APK needs `andtunes/build.py --ship` to carry it."""
|
committed, and the APK needs `andtunes/build.py --ship` to carry it.
|
||||||
|
|
||||||
|
The Mac's icon is the same picture in macOS' own frame (``--only mac``
|
||||||
|
makes just that one): Apple's icon grid puts the rounded square at 824 of
|
||||||
|
1024 px — about a 10 % margin on every side — with its corners at 22.5 %
|
||||||
|
of the square and a soft shadow beneath, so it sits among other Mac apps
|
||||||
|
the way theirs do. ``packaging/mac/LinTunes.icns`` is written directly
|
||||||
|
(the ICNS container is a header and PNG-encoded entries), so this runs on
|
||||||
|
Linux and the CI never has to make it; the .icns is committed too.
|
||||||
|
|
||||||
|
python3 scripts/make_icons.py # all three
|
||||||
|
python3 scripts/make_icons.py --only mac # just the .icns
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import io
|
||||||
|
import struct
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from PIL import Image, ImageDraw
|
from PIL import Image, ImageDraw, ImageFilter
|
||||||
|
|
||||||
HERE = Path(__file__).resolve().parent.parent
|
HERE = Path(__file__).resolve().parent.parent
|
||||||
SOURCE = HERE / "packaging" / "lint.jpg"
|
SOURCE = HERE / "packaging" / "lint.jpg"
|
||||||
@@ -15,28 +30,109 @@ CORNER = 0.16 # corner radius, as a fraction of the side
|
|||||||
DESKTOP = HERE / "packaging" / "lintunes.png"
|
DESKTOP = HERE / "packaging" / "lintunes.png"
|
||||||
ANDROID = (HERE / "andtunes" / "app" / "src" / "main" / "res"
|
ANDROID = (HERE / "andtunes" / "app" / "src" / "main" / "res"
|
||||||
/ "drawable-nodpi" / "ic_launcher.png")
|
/ "drawable-nodpi" / "ic_launcher.png")
|
||||||
|
MAC_ICNS = HERE / "packaging" / "mac" / "LinTunes.icns"
|
||||||
|
|
||||||
|
# Apple's macOS icon grid (1024 px canvas).
|
||||||
|
MAC_CANVAS = 1024
|
||||||
|
MAC_BODY = 824 # the rounded square; (1024-824)/2 = 100 px margin
|
||||||
|
MAC_CORNER = 0.225 # of the body's side
|
||||||
|
MAC_SHADOW_BLUR = 14
|
||||||
|
MAC_SHADOW_OFFSET = 10 # straight down
|
||||||
|
MAC_SHADOW_ALPHA = 90
|
||||||
|
|
||||||
|
# ICNS entry types holding PNG data, by pixel size. Several sizes appear
|
||||||
|
# twice: once as the 1x entry and once as the @2x of half that size.
|
||||||
|
ICNS_TYPES = [
|
||||||
|
(b"icp4", 16), (b"icp5", 32), (b"ic11", 32), # 16, 32, 16@2x
|
||||||
|
(b"icp6", 64), (b"ic12", 64), # 64, 32@2x
|
||||||
|
(b"ic07", 128), (b"ic08", 256), (b"ic13", 256), # 128, 256, 128@2x
|
||||||
|
(b"ic09", 512), (b"ic14", 512), # 512, 256@2x
|
||||||
|
(b"ic10", 1024), # 512@2x
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
def rounded(img: Image.Image, size: int) -> Image.Image:
|
def rounded(img: Image.Image, size: int, corner: float = CORNER) -> Image.Image:
|
||||||
img = img.convert("RGB").resize((size, size), Image.LANCZOS)
|
img = img.convert("RGB").resize((size, size), Image.LANCZOS)
|
||||||
# Drawn at 4x and shrunk, so the corners are smooth rather than stepped.
|
# Drawn at 4x and shrunk, so the corners are smooth rather than stepped.
|
||||||
big = size * 4
|
big = size * 4
|
||||||
mask = Image.new("L", (big, big), 0)
|
mask = Image.new("L", (big, big), 0)
|
||||||
ImageDraw.Draw(mask).rounded_rectangle(
|
ImageDraw.Draw(mask).rounded_rectangle(
|
||||||
(0, 0, big - 1, big - 1), radius=big * CORNER, fill=255)
|
(0, 0, big - 1, big - 1), radius=big * corner, fill=255)
|
||||||
out = img.convert("RGBA")
|
out = img.convert("RGBA")
|
||||||
out.putalpha(mask.resize((size, size), Image.LANCZOS))
|
out.putalpha(mask.resize((size, size), Image.LANCZOS))
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def mac_master(src: Image.Image) -> Image.Image:
|
||||||
|
"""The 1024 px Mac icon: the rounded body on Apple's grid, over a
|
||||||
|
soft shadow, on a transparent canvas."""
|
||||||
|
body = rounded(src, MAC_BODY, MAC_CORNER)
|
||||||
|
margin = (MAC_CANVAS - MAC_BODY) // 2
|
||||||
|
shadow = Image.new("RGBA", (MAC_CANVAS, MAC_CANVAS), (0, 0, 0, 0))
|
||||||
|
silhouette = Image.new("RGBA", body.size, (0, 0, 0, MAC_SHADOW_ALPHA))
|
||||||
|
shadow.paste(silhouette, (margin, margin + MAC_SHADOW_OFFSET),
|
||||||
|
body.getchannel("A"))
|
||||||
|
shadow = shadow.filter(ImageFilter.GaussianBlur(MAC_SHADOW_BLUR))
|
||||||
|
shadow.alpha_composite(body, (margin, margin))
|
||||||
|
return shadow
|
||||||
|
|
||||||
|
|
||||||
|
def icns_bytes(master: Image.Image) -> bytes:
|
||||||
|
"""An ICNS file: b'icns', the total length, then (type, length, PNG)
|
||||||
|
per entry — all big-endian, each length counting its own 8 bytes."""
|
||||||
|
pngs: dict[int, bytes] = {}
|
||||||
|
entries = b""
|
||||||
|
for kind, size in ICNS_TYPES:
|
||||||
|
if size not in pngs:
|
||||||
|
buf = io.BytesIO()
|
||||||
|
master.resize((size, size), Image.LANCZOS).save(
|
||||||
|
buf, format="PNG", optimize=True)
|
||||||
|
pngs[size] = buf.getvalue()
|
||||||
|
data = pngs[size]
|
||||||
|
entries += kind + struct.pack(">I", len(data) + 8) + data
|
||||||
|
return b"icns" + struct.pack(">I", len(entries) + 8) + entries
|
||||||
|
|
||||||
|
|
||||||
|
def read_icns(blob: bytes) -> list[tuple[bytes, bytes]]:
|
||||||
|
"""[(type, payload)] of an ICNS file — for the tests."""
|
||||||
|
if blob[:4] != b"icns" or struct.unpack(">I", blob[4:8])[0] != len(blob):
|
||||||
|
raise ValueError("not an ICNS file")
|
||||||
|
out, pos = [], 8
|
||||||
|
while pos < len(blob):
|
||||||
|
kind = blob[pos:pos + 4]
|
||||||
|
length = struct.unpack(">I", blob[pos + 4:pos + 8])[0]
|
||||||
|
if length < 8 or pos + length > len(blob):
|
||||||
|
raise ValueError("truncated ICNS entry")
|
||||||
|
out.append((kind, blob[pos + 8:pos + length]))
|
||||||
|
pos += length
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def squared_source() -> Image.Image:
|
||||||
src = Image.open(SOURCE)
|
src = Image.open(SOURCE)
|
||||||
side = min(src.size) # square it up from the centre
|
side = min(src.size) # square it up from the centre
|
||||||
left, top = (src.width - side) // 2, (src.height - side) // 2
|
left, top = (src.width - side) // 2, (src.height - side) // 2
|
||||||
src = src.crop((left, top, left + side, top + side))
|
return src.crop((left, top, left + side, top + side))
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
||||||
|
parser.add_argument("--only", choices=("desktop", "android", "mac"),
|
||||||
|
action="append", help="make only these (repeatable)")
|
||||||
|
which = set(parser.parse_args().only or ("desktop", "android", "mac"))
|
||||||
|
src = squared_source()
|
||||||
|
wrote = []
|
||||||
|
if "desktop" in which:
|
||||||
rounded(src, 512).save(DESKTOP)
|
rounded(src, 512).save(DESKTOP)
|
||||||
|
wrote.append(DESKTOP)
|
||||||
|
if "android" in which:
|
||||||
rounded(src, 192).save(ANDROID)
|
rounded(src, 192).save(ANDROID)
|
||||||
print(f"Wrote {DESKTOP.relative_to(HERE)} and {ANDROID.relative_to(HERE)}.")
|
wrote.append(ANDROID)
|
||||||
|
if "mac" in which:
|
||||||
|
MAC_ICNS.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
MAC_ICNS.write_bytes(icns_bytes(mac_master(src)))
|
||||||
|
wrote.append(MAC_ICNS)
|
||||||
|
print("Wrote " + ", ".join(str(p.relative_to(HERE)) for p in wrote) + ".")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import re
|
import re
|
||||||
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from setuptools import setup, find_packages
|
from setuptools import setup, find_packages
|
||||||
@@ -30,10 +31,14 @@ setup(
|
|||||||
"requests>=2.28",
|
"requests>=2.28",
|
||||||
"pychromecast>=14.0.10",
|
"pychromecast>=14.0.10",
|
||||||
"pyatv>=0.18.0", # AirPlay (RAOP) streaming; decodes via the ffmpeg CLI
|
"pyatv>=0.18.0", # AirPlay (RAOP) streaming; decodes via the ffmpeg CLI
|
||||||
|
# macOS: Now Playing + media keys (MediaPlayer) and the Cocoa glue
|
||||||
|
# it needs. Imported lazily, only on a Mac.
|
||||||
|
'pyobjc-framework-Cocoa>=10.0; sys_platform == "darwin"',
|
||||||
|
'pyobjc-framework-MediaPlayer>=10.0; sys_platform == "darwin"',
|
||||||
],
|
],
|
||||||
data_files=[
|
# The .desktop entry is a Linux desktop's; a Mac has LinTunes.app.
|
||||||
("share/applications", ["packaging/lintunes.desktop"]),
|
data_files=([("share/applications", ["packaging/lintunes.desktop"])]
|
||||||
],
|
if sys.platform.startswith("linux") else []),
|
||||||
entry_points={
|
entry_points={
|
||||||
"console_scripts": [
|
"console_scripts": [
|
||||||
"lintunes=lintunes.main:main",
|
"lintunes=lintunes.main:main",
|
||||||
|
|||||||
@@ -0,0 +1,464 @@
|
|||||||
|
"""Round 129: the macOS port of Cassette, DJ mode's vocal splitters, AirPlay's
|
||||||
|
helper download and the rest of their machine-local paths.
|
||||||
|
|
||||||
|
Every Mac branch keys off ``lintunes.paths.IS_MAC`` (and ``FROZEN``), so
|
||||||
|
these flip it with monkeypatch. Each Mac test has a Linux twin pinning that
|
||||||
|
nothing there changed: the same paths, words and commands as before.
|
||||||
|
"""
|
||||||
|
import hashlib
|
||||||
|
import io
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tarfile
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from lintunes import paths
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def mac(monkeypatch):
|
||||||
|
monkeypatch.setattr(paths, "IS_MAC", True)
|
||||||
|
return monkeypatch
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def home(tmp_path, monkeypatch):
|
||||||
|
home = tmp_path / "home"
|
||||||
|
home.mkdir()
|
||||||
|
monkeypatch.setenv("HOME", str(home))
|
||||||
|
for var in ("XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_DATA_HOME",
|
||||||
|
"XDG_STATE_HOME", "STCONFDIR", "STHOMEDIR"):
|
||||||
|
monkeypatch.delenv(var, raising=False)
|
||||||
|
from lintunes import sync_identity
|
||||||
|
sync_identity.reset_cache()
|
||||||
|
yield home
|
||||||
|
sync_identity.reset_cache()
|
||||||
|
|
||||||
|
|
||||||
|
def _syncthing_config(folder: Path, key="k3y", address="127.0.0.1:8384"):
|
||||||
|
folder.mkdir(parents=True, exist_ok=True)
|
||||||
|
(folder / "config.xml").write_text(
|
||||||
|
f'<configuration><device id="ABCDEFG-XYZ" name="Laptop"/>'
|
||||||
|
f'<gui><address>{address}</address><apikey>{key}</apikey></gui>'
|
||||||
|
f'</configuration>')
|
||||||
|
return folder
|
||||||
|
|
||||||
|
|
||||||
|
# ---- Syncthing's config ----
|
||||||
|
|
||||||
|
class TestSyncthingConfig:
|
||||||
|
def test_linux_looks_where_it_always_did(self, home):
|
||||||
|
from lintunes import sync_identity
|
||||||
|
assert sync_identity.config_dirs() == (
|
||||||
|
"$XDG_STATE_HOME/syncthing", "~/.local/state/syncthing",
|
||||||
|
"~/.config/syncthing", "~/.syncthing")
|
||||||
|
# A Mac-style folder means nothing on Linux.
|
||||||
|
_syncthing_config(home / "Library/Application Support/Syncthing")
|
||||||
|
assert sync_identity._config_dir() is None
|
||||||
|
|
||||||
|
def test_mac_finds_application_support(self, home, mac):
|
||||||
|
from lintunes import sync_identity
|
||||||
|
from lintunes.cassette import syncthing_api as st
|
||||||
|
folder = _syncthing_config(home / "Library/Application Support/Syncthing")
|
||||||
|
assert sync_identity._config_dir() == folder
|
||||||
|
assert st.read_gui_config() == st.Endpoint("127.0.0.1:8384", "k3y")
|
||||||
|
assert sync_identity.device_names() == {"ABCDEFG": "Laptop"}
|
||||||
|
|
||||||
|
def test_mac_honours_stconfdir_first(self, home, mac, tmp_path):
|
||||||
|
from lintunes import sync_identity
|
||||||
|
_syncthing_config(home / "Library/Application Support/Syncthing")
|
||||||
|
custom = _syncthing_config(tmp_path / "elsewhere", key="other")
|
||||||
|
mac.setenv("STCONFDIR", str(custom))
|
||||||
|
assert sync_identity._config_dir() == custom
|
||||||
|
mac.setenv("STCONFDIR", "") # set to nothing: skipped, not "."
|
||||||
|
assert sync_identity._config_dir() == (
|
||||||
|
home / "Library/Application Support/Syncthing")
|
||||||
|
|
||||||
|
def test_mac_still_finds_a_unix_style_home(self, home, mac):
|
||||||
|
from lintunes import sync_identity
|
||||||
|
folder = _syncthing_config(home / ".config/syncthing")
|
||||||
|
assert sync_identity._config_dir() == folder
|
||||||
|
|
||||||
|
def test_not_running_words(self, mac):
|
||||||
|
from lintunes.cassette import syncthing_api as st
|
||||||
|
hint = st.not_running_hint("press Retry")
|
||||||
|
assert "brew install" in hint and "syncthing.net" in hint
|
||||||
|
assert hint.startswith("Open the Syncthing app")
|
||||||
|
assert ", then press Retry." in hint
|
||||||
|
|
||||||
|
def test_not_running_words_on_linux_are_the_callers(self):
|
||||||
|
from lintunes.cassette import syncthing_api as st
|
||||||
|
assert st.not_running_hint("press Retry") is None
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("on_mac", [False, True])
|
||||||
|
def test_service_status_when_syncthing_is_down(self, qapp, tmp_path,
|
||||||
|
monkeypatch, on_mac):
|
||||||
|
from lintunes.cassette import service as svc
|
||||||
|
from lintunes.cassette import syncthing_api as st
|
||||||
|
monkeypatch.setattr(paths, "IS_MAC", on_mac)
|
||||||
|
service = svc.CassetteService.__new__(svc.CassetteService)
|
||||||
|
svc.QObject.__init__(service)
|
||||||
|
import threading
|
||||||
|
service._lock = threading.Lock()
|
||||||
|
service._api = svc.Status("x", "", "")
|
||||||
|
service._set_api_down(st.SyncthingError("s", "d", st.NOT_RUNNING))
|
||||||
|
detail = service._api.hint
|
||||||
|
if on_mac:
|
||||||
|
assert "brew install" in detail
|
||||||
|
else:
|
||||||
|
assert detail == ("Start Syncthing, then press Retry in Sync "
|
||||||
|
"Settings ▸ General.")
|
||||||
|
|
||||||
|
|
||||||
|
# ---- the cassette folders ----
|
||||||
|
|
||||||
|
class TestCassetteFolders:
|
||||||
|
def test_root_on_linux_unchanged(self, home, monkeypatch, tmp_path):
|
||||||
|
from lintunes.cassette import state
|
||||||
|
monkeypatch.setattr(state, "load_config", lambda: {})
|
||||||
|
assert state.cassette_root() == home / ".local/share/lintunes/cassette"
|
||||||
|
monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path / "xdg"))
|
||||||
|
assert state.cassette_root() == tmp_path / "xdg/lintunes/cassette"
|
||||||
|
|
||||||
|
def test_root_on_mac(self, home, mac):
|
||||||
|
from lintunes.cassette import state
|
||||||
|
mac.setattr(state, "load_config", lambda: {})
|
||||||
|
assert state.cassette_root() == (
|
||||||
|
home / "Library/Application Support/LinTunes/cassette")
|
||||||
|
mac.setattr(state, "load_config", lambda: {"cassette_root": "~/C"})
|
||||||
|
assert state.cassette_root() == home / "C"
|
||||||
|
|
||||||
|
def test_stignore_on_linux_unchanged(self, tmp_path):
|
||||||
|
from lintunes.cassette import publish
|
||||||
|
publish.prepare_out_dir(tmp_path / "out")
|
||||||
|
assert (tmp_path / "out/.stignore").read_text() == (
|
||||||
|
"// written by LinTunes\n*.tmp\n*.part\n")
|
||||||
|
publish.prepare_in_dir(tmp_path / "in")
|
||||||
|
assert (tmp_path / "in").is_dir()
|
||||||
|
assert not (tmp_path / "in/.stignore").exists()
|
||||||
|
|
||||||
|
def test_stignore_on_mac_keeps_finder_out(self, tmp_path, mac):
|
||||||
|
from lintunes.cassette import publish
|
||||||
|
publish.prepare_out_dir(tmp_path / "out")
|
||||||
|
text = (tmp_path / "out/.stignore").read_text()
|
||||||
|
assert text.startswith("// written by LinTunes\n*.tmp\n*.part\n")
|
||||||
|
assert "(?d).DS_Store" in text and "(?d)._*" in text
|
||||||
|
publish.prepare_in_dir(tmp_path / "in")
|
||||||
|
assert "(?d).DS_Store" in (tmp_path / "in/.stignore").read_text()
|
||||||
|
|
||||||
|
def test_finder_litter_is_never_a_delivery(self, tmp_path):
|
||||||
|
from lintunes.cassette import delivery
|
||||||
|
outbox = tmp_path / "outbox"
|
||||||
|
outbox.mkdir()
|
||||||
|
(outbox / ".DS_Store").write_bytes(b"x")
|
||||||
|
(outbox / "._12 ~ song.mp3").write_bytes(b"x")
|
||||||
|
(outbox / "12 ~ song.mp3").write_bytes(b"x")
|
||||||
|
assert list(delivery.list_outbox(outbox)) == [12]
|
||||||
|
|
||||||
|
def test_mac_hostname_drops_dot_local(self, mac):
|
||||||
|
from lintunes.cassette import host
|
||||||
|
mac.setattr(host.socket, "gethostname", lambda: "Travs-MacBook.local")
|
||||||
|
assert host.hostname() == "Travs-MacBook"
|
||||||
|
|
||||||
|
def test_linux_hostname_unchanged(self, monkeypatch):
|
||||||
|
from lintunes.cassette import host
|
||||||
|
monkeypatch.setattr(host.socket, "gethostname", lambda: "box.local")
|
||||||
|
assert host.hostname() == "box.local"
|
||||||
|
|
||||||
|
def test_mac_asks_syncthing_by_its_nfc_name(self, tmp_path, mac):
|
||||||
|
import unicodedata
|
||||||
|
from lintunes.cassette import service as svc
|
||||||
|
from lintunes.cassette.state import Friend, in_dir
|
||||||
|
asked = []
|
||||||
|
|
||||||
|
class Client:
|
||||||
|
def file_info(self, folder, name):
|
||||||
|
asked.append(name)
|
||||||
|
return None
|
||||||
|
service = svc.CassetteService.__new__(svc.CassetteService)
|
||||||
|
import threading
|
||||||
|
service._lock = threading.Lock()
|
||||||
|
service.root = tmp_path
|
||||||
|
friend = Friend(token="t", device_id="D", name="F", role="inviter",
|
||||||
|
out_folder="o", in_folder="i", added="")
|
||||||
|
service._state = type("S", (), {"friends": {"t": friend}})()
|
||||||
|
service.client = lambda: Client()
|
||||||
|
nfd = unicodedata.normalize("NFD", "Beyoncé.mp3")
|
||||||
|
assert service.is_complete("t", in_dir(tmp_path, "t") / nfd)
|
||||||
|
assert asked == [unicodedata.normalize("NFC", "Beyoncé.mp3")]
|
||||||
|
|
||||||
|
|
||||||
|
# ---- AirPlay's helper ----
|
||||||
|
|
||||||
|
class TestCliAirPlay:
|
||||||
|
@pytest.mark.parametrize("machine, key", [("arm64", "macos-arm64"),
|
||||||
|
("x86_64", "macos-x86_64")])
|
||||||
|
def test_mac_builds_are_pinned(self, mac, machine, key):
|
||||||
|
from lintunes.airplay import cli
|
||||||
|
mac.setattr(cli.platform, "machine", lambda: machine)
|
||||||
|
assert cli._arch() == key and cli.supported()
|
||||||
|
assert cli._asset(key) == f"cliairplay-{key}"
|
||||||
|
assert len(cli._SHA256[key]) == 64
|
||||||
|
|
||||||
|
def test_mac_download_uses_the_mac_asset(self, mac, tmp_path):
|
||||||
|
from lintunes.airplay import cli
|
||||||
|
data = b"pretend mac binary"
|
||||||
|
mac.setenv("XDG_DATA_HOME", str(tmp_path))
|
||||||
|
mac.setattr(cli.platform, "machine", lambda: "arm64")
|
||||||
|
mac.setitem(cli._SHA256, "macos-arm64", hashlib.sha256(data).hexdigest())
|
||||||
|
urls = []
|
||||||
|
path = cli.ensure_binary(fetch=lambda url: urls.append(url) or data)
|
||||||
|
assert urls == [cli._RELEASE + "cliairplay-macos-arm64"]
|
||||||
|
assert path == tmp_path / "lintunes/bin" / f"cliairplay-{cli.VERSION}-macos-arm64"
|
||||||
|
assert os.access(path, os.X_OK)
|
||||||
|
|
||||||
|
def test_linux_binary_dir_unchanged(self, home):
|
||||||
|
from lintunes.airplay import cli
|
||||||
|
assert cli.binary_dir() == home / ".local/share/lintunes/bin"
|
||||||
|
|
||||||
|
def test_https_context(self, monkeypatch):
|
||||||
|
import ssl
|
||||||
|
from lintunes.airplay import cli
|
||||||
|
assert cli.https_context() is None
|
||||||
|
monkeypatch.setattr(paths, "IS_MAC", True)
|
||||||
|
assert isinstance(cli.https_context(), ssl.SSLContext)
|
||||||
|
|
||||||
|
|
||||||
|
# ---- the splitters' venvs ----
|
||||||
|
|
||||||
|
def _uv_tarball(target: str, payload=b"#!/bin/sh\necho uv\n") -> bytes:
|
||||||
|
buf = io.BytesIO()
|
||||||
|
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
|
||||||
|
info = tarfile.TarInfo(f"uv-{target}/uv")
|
||||||
|
info.size = len(payload)
|
||||||
|
tar.addfile(info, io.BytesIO(payload))
|
||||||
|
info = tarfile.TarInfo(f"uv-{target}/uvx")
|
||||||
|
info.size = 1
|
||||||
|
tar.addfile(info, io.BytesIO(b"x"))
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
class TestVenvTool:
|
||||||
|
def test_linux_checkout_makes_venvs_as_before(self, monkeypatch):
|
||||||
|
from lintunes.dj import venv_tool
|
||||||
|
monkeypatch.setattr(paths, "FROZEN", False)
|
||||||
|
venv = Path("/v")
|
||||||
|
assert not venv_tool.uses_uv()
|
||||||
|
assert venv_tool.create_command(venv) == [sys.executable, "-m", "venv", "/v"]
|
||||||
|
assert venv_tool.install_command(venv, ["a", "b"]) == [
|
||||||
|
"/v/bin/python", "-m", "pip", "install", "--quiet", "a", "b"]
|
||||||
|
assert venv_tool.run_env() is None
|
||||||
|
assert venv_tool.child_env() is None
|
||||||
|
env = {"X": "1"}
|
||||||
|
assert venv_tool.child_env(env) is env
|
||||||
|
cmd, pre = venv_tool.niced(["x"], 5)
|
||||||
|
assert cmd == ["x"] and callable(pre)
|
||||||
|
|
||||||
|
def test_mac_makes_venvs_with_uv(self, mac, home):
|
||||||
|
from lintunes.dj import venv_tool
|
||||||
|
venv = Path("/v")
|
||||||
|
assert venv_tool.uses_uv()
|
||||||
|
uv = str(venv_tool.uv_path())
|
||||||
|
assert uv == str(home / "Library/Application Support/LinTunes/bin"
|
||||||
|
/ f"uv-{venv_tool.UV_VERSION}")
|
||||||
|
assert venv_tool.create_command(venv) == [
|
||||||
|
uv, "venv", "--quiet", "--python", venv_tool.PYTHON_VERSION, "/v"]
|
||||||
|
assert venv_tool.install_command(venv, ["a"], "https://idx") == [
|
||||||
|
uv, "pip", "install", "--quiet", "--python", "/v/bin/python",
|
||||||
|
"--index-url", "https://idx", "a"]
|
||||||
|
cmd, pre = venv_tool.niced(["x"], 19)
|
||||||
|
assert cmd == ["/usr/bin/nice", "-n", "19", "x"] and pre is None
|
||||||
|
|
||||||
|
def test_frozen_linux_uses_uv_too(self, monkeypatch):
|
||||||
|
from lintunes.dj import venv_tool
|
||||||
|
monkeypatch.setattr(paths, "FROZEN", True)
|
||||||
|
assert venv_tool.uses_uv()
|
||||||
|
|
||||||
|
def test_uv_env_is_ours_and_clean(self, mac, home):
|
||||||
|
from lintunes.dj import venv_tool
|
||||||
|
env = venv_tool.uv_env({"PYTHONHOME": "/app", "PYTHONPATH": "/app",
|
||||||
|
"VIRTUAL_ENV": "/x", "PATH": "/bin"})
|
||||||
|
assert "PYTHONHOME" not in env and "PYTHONPATH" not in env
|
||||||
|
assert "VIRTUAL_ENV" not in env and env["PATH"] == "/bin"
|
||||||
|
assert env["UV_MANAGED_PYTHON"] == "1"
|
||||||
|
assert env["UV_PYTHON_INSTALL_DIR"].startswith(str(home / "Library"))
|
||||||
|
assert env["UV_CACHE_DIR"] == str(home / "Library/Caches/LinTunes/uv")
|
||||||
|
assert os.path.isfile(env["SSL_CERT_FILE"])
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("machine, target", [
|
||||||
|
("arm64", "aarch64-apple-darwin"), ("x86_64", "x86_64-apple-darwin")])
|
||||||
|
def test_uv_targets(self, mac, machine, target):
|
||||||
|
from lintunes.dj import venv_tool
|
||||||
|
mac.setattr(venv_tool.platform, "machine", lambda: machine)
|
||||||
|
assert venv_tool.uv_target() == target
|
||||||
|
assert len(venv_tool._UV_SHA256[target]) == 64
|
||||||
|
|
||||||
|
def test_ensure_uv_verifies_then_unpacks(self, mac, tmp_path):
|
||||||
|
from lintunes.dj import venv_tool
|
||||||
|
mac.setenv("XDG_DATA_HOME", str(tmp_path))
|
||||||
|
mac.setattr(venv_tool.platform, "machine", lambda: "arm64")
|
||||||
|
target = "aarch64-apple-darwin"
|
||||||
|
archive = _uv_tarball(target)
|
||||||
|
with pytest.raises(venv_tool.VenvError):
|
||||||
|
venv_tool.ensure_uv(fetch=lambda url: archive) # real pin: mismatch
|
||||||
|
assert not venv_tool.uv_path().exists()
|
||||||
|
mac.setitem(venv_tool._UV_SHA256, target, hashlib.sha256(archive).hexdigest())
|
||||||
|
urls = []
|
||||||
|
path = venv_tool.ensure_uv(fetch=lambda url: urls.append(url) or archive)
|
||||||
|
assert urls == [venv_tool._UV_RELEASE + f"uv-{target}.tar.gz"]
|
||||||
|
assert path.read_bytes() == b"#!/bin/sh\necho uv\n"
|
||||||
|
assert os.access(path, os.X_OK)
|
||||||
|
assert venv_tool.ensure_uv(fetch=lambda url: 1 / 0) == path # kept
|
||||||
|
|
||||||
|
def test_an_archive_without_uv_is_refused(self, mac, tmp_path):
|
||||||
|
from lintunes.dj import venv_tool
|
||||||
|
mac.setenv("XDG_DATA_HOME", str(tmp_path))
|
||||||
|
mac.setattr(venv_tool.platform, "machine", lambda: "arm64")
|
||||||
|
target = "aarch64-apple-darwin"
|
||||||
|
archive = _uv_tarball("something-else")
|
||||||
|
mac.setitem(venv_tool._UV_SHA256, target, hashlib.sha256(archive).hexdigest())
|
||||||
|
with pytest.raises(venv_tool.VenvError):
|
||||||
|
venv_tool.ensure_uv(fetch=lambda url: archive)
|
||||||
|
assert not venv_tool.uv_path().exists()
|
||||||
|
|
||||||
|
|
||||||
|
class TestDemucs:
|
||||||
|
def test_linux_paths_and_words_unchanged(self, home, monkeypatch, tmp_path):
|
||||||
|
from lintunes.dj import stems
|
||||||
|
monkeypatch.setattr(paths, "FROZEN", False)
|
||||||
|
assert stems.venv_dir() == home / ".local/share/lintunes/demucs"
|
||||||
|
assert stems.cache_root() == home / ".cache/lintunes/stems"
|
||||||
|
v = stems.venv_dir()
|
||||||
|
assert stems.setup_command() == (
|
||||||
|
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")
|
||||||
|
assert not stems.setup_in_app()
|
||||||
|
monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path / "d"))
|
||||||
|
monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / "c"))
|
||||||
|
assert stems.venv_dir() == tmp_path / "d/lintunes/demucs"
|
||||||
|
assert stems.cache_root() == tmp_path / "c/lintunes/stems"
|
||||||
|
|
||||||
|
def test_mac_paths(self, home, mac):
|
||||||
|
from lintunes.dj import instant, stems
|
||||||
|
assert stems.venv_dir() == home / "Library/Application Support/LinTunes/demucs"
|
||||||
|
assert stems.cache_root() == home / "Library/Caches/LinTunes/stems"
|
||||||
|
assert instant.venv_dir() == home / "Library/Application Support/LinTunes/spleeter"
|
||||||
|
assert stems.setup_in_app()
|
||||||
|
assert "Preferences › DJ" in stems.setup_command()
|
||||||
|
|
||||||
|
def test_mac_packages(self, mac):
|
||||||
|
from lintunes.dj import stems
|
||||||
|
mac.setattr(stems.platform, "machine", lambda: "arm64")
|
||||||
|
[(_t, packages, index)] = stems.install_steps()
|
||||||
|
assert index is None and "torch==2.8.0" in packages
|
||||||
|
assert "torchaudio==2.8.0" in packages and "soundfile" in packages
|
||||||
|
mac.setattr(stems.platform, "machine", lambda: "x86_64")
|
||||||
|
[(_t, packages, index)] = stems.install_steps()
|
||||||
|
assert "torch==2.2.2" in packages and "numpy<2" in packages
|
||||||
|
|
||||||
|
def test_mac_setup_runs_uv(self, qapp, home, mac):
|
||||||
|
from lintunes.dj import stems, venv_tool
|
||||||
|
mac.setattr(stems.platform, "machine", lambda: "arm64")
|
||||||
|
mac.setattr(venv_tool, "ensure_uv", lambda fetch=None: venv_tool.uv_path())
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
class Done:
|
||||||
|
returncode = 0
|
||||||
|
stderr = stdout = ""
|
||||||
|
mac.setattr(stems.subprocess, "run",
|
||||||
|
lambda cmd, **kw: calls.append((cmd, kw["env"])) or Done())
|
||||||
|
setup = stems.DemucsSetup()
|
||||||
|
said, finished, failed = [], [], []
|
||||||
|
setup.progress.connect(said.append)
|
||||||
|
setup.finished.connect(lambda: finished.append(1))
|
||||||
|
setup.failed.connect(failed.append)
|
||||||
|
setup._run()
|
||||||
|
assert failed == [] and finished == [1]
|
||||||
|
uv = str(venv_tool.uv_path())
|
||||||
|
assert calls[0][0][:2] == [uv, "venv"]
|
||||||
|
assert calls[1][0][:3] == [uv, "pip", "install"]
|
||||||
|
assert "demucs==4.0.1" in calls[1][0]
|
||||||
|
assert all(env["UV_MANAGED_PYTHON"] == "1" for _c, env in calls)
|
||||||
|
|
||||||
|
def test_mac_split_is_niced_by_command(self, tmp_path, mac):
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from lintunes.dj import stems
|
||||||
|
song = tmp_path / "s.mp3"
|
||||||
|
song.write_bytes(b"x")
|
||||||
|
mac.setenv("XDG_CACHE_HOME", str(tmp_path / "c"))
|
||||||
|
mac.setattr(stems, "available", lambda: True)
|
||||||
|
mac.setattr(stems, "audio_hash", lambda path: None)
|
||||||
|
mac.setattr(stems.os, "cpu_count", lambda: 8)
|
||||||
|
seen = {}
|
||||||
|
|
||||||
|
class Proc:
|
||||||
|
stderr = SimpleNamespace(read=lambda n: b"")
|
||||||
|
|
||||||
|
def wait(self):
|
||||||
|
return 1
|
||||||
|
|
||||||
|
def popen(cmd, **kw):
|
||||||
|
seen.update(cmd=cmd, **kw)
|
||||||
|
return Proc()
|
||||||
|
mac.setattr(stems.subprocess, "Popen", popen)
|
||||||
|
mac.setenv("PYTHONHOME", "/Applications/LinTunes.app")
|
||||||
|
with pytest.raises(OSError):
|
||||||
|
stems.split(str(song), "htdemucs", True)
|
||||||
|
assert seen["cmd"][:3] == ["/usr/bin/nice", "-n", "19"]
|
||||||
|
assert seen["preexec_fn"] is None
|
||||||
|
assert "PYTHONHOME" not in seen["env"]
|
||||||
|
assert seen["env"]["OMP_NUM_THREADS"] == "2"
|
||||||
|
|
||||||
|
|
||||||
|
class TestInstant:
|
||||||
|
def test_mac_setup_runs_uv(self, qapp, home, mac):
|
||||||
|
from lintunes.dj import instant, venv_tool
|
||||||
|
mac.setattr(venv_tool, "ensure_uv", lambda fetch=None: venv_tool.uv_path())
|
||||||
|
mac.setattr(instant, "install_models", lambda fetch=None: None)
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
class Done:
|
||||||
|
returncode = 0
|
||||||
|
stderr = stdout = ""
|
||||||
|
mac.setattr(instant.subprocess, "run",
|
||||||
|
lambda cmd, **kw: calls.append(cmd) or Done())
|
||||||
|
setup = instant.InstantSetup()
|
||||||
|
failed = []
|
||||||
|
setup.failed.connect(failed.append)
|
||||||
|
setup._run()
|
||||||
|
assert failed == []
|
||||||
|
uv = str(venv_tool.uv_path())
|
||||||
|
assert calls[0][:2] == [uv, "venv"]
|
||||||
|
assert calls[1][:3] == [uv, "pip", "install"]
|
||||||
|
assert f"sherpa-onnx=={instant.SHERPA_VERSION}" in calls[1]
|
||||||
|
|
||||||
|
def test_linux_setup_unchanged(self, qapp, home, monkeypatch):
|
||||||
|
from lintunes.dj import instant
|
||||||
|
monkeypatch.setattr(paths, "FROZEN", False)
|
||||||
|
monkeypatch.setattr(instant, "install_models", lambda fetch=None: None)
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
class Done:
|
||||||
|
returncode = 0
|
||||||
|
stderr = stdout = ""
|
||||||
|
monkeypatch.setattr(instant.subprocess, "run",
|
||||||
|
lambda cmd, **kw: calls.append((cmd, kw.get("env"))) or Done())
|
||||||
|
instant.InstantSetup()._run()
|
||||||
|
venv = instant.venv_dir()
|
||||||
|
assert calls == [
|
||||||
|
([sys.executable, "-m", "venv", str(venv)], None),
|
||||||
|
([str(venv / "bin/python"), "-m", "pip", "install", "--quiet",
|
||||||
|
f"sherpa-onnx=={instant.SHERPA_VERSION}", "numpy"], None)]
|
||||||
|
|
||||||
|
def test_the_runner_ships_beside_the_module(self):
|
||||||
|
from lintunes.dj import instant
|
||||||
|
assert instant.RUNNER.is_file()
|
||||||
|
|
||||||
|
|
||||||
|
def test_dj_output_tries_any_rate_only_on_a_mac(monkeypatch):
|
||||||
|
from lintunes.dj import output
|
||||||
|
assert not output._converts_any_rate()
|
||||||
|
monkeypatch.setattr(paths, "IS_MAC", True)
|
||||||
|
assert output._converts_any_rate()
|
||||||
@@ -0,0 +1,579 @@
|
|||||||
|
"""Round 129: the macOS port, as far as it can be checked on Linux.
|
||||||
|
|
||||||
|
Every Mac branch keys off ``lintunes.paths.IS_MAC``, so these tests flip it
|
||||||
|
with monkeypatch and fake whatever macOS would supply (pyobjc, caffeinate,
|
||||||
|
``open``, ``QFile.moveToTrash``). They also pin that Linux is unchanged:
|
||||||
|
the same paths, with and without the XDG variables set.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import types
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from lintunes import paths
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def mac(monkeypatch):
|
||||||
|
monkeypatch.setattr(paths, "IS_MAC", True)
|
||||||
|
return monkeypatch
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def home(tmp_path, monkeypatch):
|
||||||
|
home = tmp_path / "home"
|
||||||
|
home.mkdir()
|
||||||
|
monkeypatch.setenv("HOME", str(home))
|
||||||
|
for var in ("XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_DATA_HOME"):
|
||||||
|
monkeypatch.delenv(var, raising=False)
|
||||||
|
return home
|
||||||
|
|
||||||
|
|
||||||
|
# ---- paths: Linux unchanged, Mac under ~/Library ----
|
||||||
|
|
||||||
|
def _machine_paths():
|
||||||
|
from lintunes import config, eventlog, loudness, mpris
|
||||||
|
from lintunes.andtunes import art, sync
|
||||||
|
from lintunes.export import upload
|
||||||
|
from lintunes.importers import lossless
|
||||||
|
track = types.SimpleNamespace(track_id=7)
|
||||||
|
return {
|
||||||
|
"config": config.config_path(),
|
||||||
|
"loudness": loudness.default_cache_path(),
|
||||||
|
"converting": lossless.staging_root(),
|
||||||
|
"webmix": upload.staging_root(),
|
||||||
|
"artwork": mpris._art_cache_dir(),
|
||||||
|
"andtunes-art": art._cache_dir(),
|
||||||
|
"andtunes-flac": sync.flac_cache(track),
|
||||||
|
"eventlog": eventlog.default_log_path(),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_linux_paths_are_the_xdg_defaults(home):
|
||||||
|
got = _machine_paths()
|
||||||
|
assert got == {
|
||||||
|
"config": home / ".config/lintunes/config.json",
|
||||||
|
"loudness": home / ".cache/lintunes/loudness.json",
|
||||||
|
"converting": home / ".cache/lintunes/converting",
|
||||||
|
"webmix": home / ".cache/lintunes/webmix",
|
||||||
|
"artwork": home / ".cache/lintunes/artwork",
|
||||||
|
"andtunes-art": home / ".cache/lintunes/andtunes-art",
|
||||||
|
"andtunes-flac": home / ".cache/lintunes/andtunes-flac/7.flac",
|
||||||
|
"eventlog": home / ".cache/lintunes/control-events.log",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_linux_paths_follow_xdg_variables(home, tmp_path, monkeypatch):
|
||||||
|
monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "cfg"))
|
||||||
|
monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / "cache"))
|
||||||
|
got = _machine_paths()
|
||||||
|
assert got["config"] == tmp_path / "cfg/lintunes/config.json"
|
||||||
|
assert got["loudness"] == tmp_path / "cache/lintunes/loudness.json"
|
||||||
|
assert got["webmix"] == tmp_path / "cache/lintunes/webmix"
|
||||||
|
assert got["andtunes-flac"] == tmp_path / "cache/lintunes/andtunes-flac/7.flac"
|
||||||
|
# The control log always lived under ~/.cache on Linux; still does.
|
||||||
|
assert got["eventlog"] == home / ".cache/lintunes/control-events.log"
|
||||||
|
|
||||||
|
|
||||||
|
def test_mac_paths_live_under_library(home, mac):
|
||||||
|
got = _machine_paths()
|
||||||
|
support = home / "Library/Application Support/LinTunes"
|
||||||
|
caches = home / "Library/Caches/LinTunes"
|
||||||
|
assert got["config"] == support / "config.json"
|
||||||
|
assert got["loudness"] == caches / "loudness.json"
|
||||||
|
assert got["webmix"] == caches / "webmix"
|
||||||
|
assert got["artwork"] == caches / "artwork"
|
||||||
|
assert got["eventlog"] == caches / "control-events.log"
|
||||||
|
|
||||||
|
|
||||||
|
# ---- PATH for the CLI tools ----
|
||||||
|
|
||||||
|
def test_tool_dirs_left_alone_on_linux():
|
||||||
|
from lintunes import main
|
||||||
|
env = {"PATH": "/usr/bin:/bin"}
|
||||||
|
main.add_mac_tool_dirs(env)
|
||||||
|
assert env == {"PATH": "/usr/bin:/bin"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_mac_prepends_homebrew_once(mac):
|
||||||
|
from lintunes import main
|
||||||
|
env = {"PATH": "/usr/bin:/bin:/usr/local/bin"}
|
||||||
|
main.add_mac_tool_dirs(env)
|
||||||
|
dirs = env["PATH"].split(os.pathsep)
|
||||||
|
assert dirs[0] == "/opt/homebrew/bin"
|
||||||
|
assert dirs.count("/usr/local/bin") == 1
|
||||||
|
assert dirs[-2:] == ["/bin", "/usr/local/bin"]
|
||||||
|
|
||||||
|
|
||||||
|
# ---- yt-dlp's cookies ----
|
||||||
|
|
||||||
|
def test_mac_cookies_browser_from_application_support(home, mac):
|
||||||
|
from lintunes import url_import
|
||||||
|
assert url_import.default_cookies_browser() is None
|
||||||
|
(home / "Library/Application Support/Google/Chrome").mkdir(parents=True)
|
||||||
|
assert url_import.default_cookies_browser() == "chrome"
|
||||||
|
(home / "Library/Application Support/Firefox/Profiles").mkdir(parents=True)
|
||||||
|
assert url_import.default_cookies_browser() == "firefox"
|
||||||
|
|
||||||
|
|
||||||
|
def test_mac_never_offers_safari(home, mac):
|
||||||
|
from lintunes import url_import
|
||||||
|
(home / "Library/Cookies").mkdir(parents=True)
|
||||||
|
(home / "Library/Safari").mkdir(parents=True)
|
||||||
|
assert url_import.default_cookies_browser() is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_linux_cookies_unchanged(home):
|
||||||
|
from lintunes import url_import
|
||||||
|
(home / ".mozilla/firefox").mkdir(parents=True)
|
||||||
|
assert url_import.default_cookies_browser() == "firefox"
|
||||||
|
|
||||||
|
|
||||||
|
# ---- trash ----
|
||||||
|
|
||||||
|
def test_mac_trash_uses_qfile(tmp_path, mac):
|
||||||
|
from PyQt6.QtCore import QFile
|
||||||
|
from lintunes import trash
|
||||||
|
song = tmp_path / "music" / "song.mp3"
|
||||||
|
song.parent.mkdir()
|
||||||
|
song.write_bytes(b"x")
|
||||||
|
bin_ = tmp_path / "Trash"
|
||||||
|
bin_.mkdir()
|
||||||
|
|
||||||
|
def fake(path):
|
||||||
|
dest = bin_ / Path(path).name
|
||||||
|
os.rename(path, dest)
|
||||||
|
return True, str(dest)
|
||||||
|
mac.setattr(QFile, "moveToTrash", staticmethod(fake))
|
||||||
|
dest = trash.send_to_trash(song)
|
||||||
|
assert dest == bin_ / "song.mp3" and dest.exists() and not song.exists()
|
||||||
|
# No freedesktop .trashinfo anywhere.
|
||||||
|
assert not list(tmp_path.rglob("*.trashinfo"))
|
||||||
|
# Undo puts it back.
|
||||||
|
trash.restore_from_trash(dest, song)
|
||||||
|
assert song.exists() and not dest.exists()
|
||||||
|
assert trash.original_path(dest) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_mac_trash_failure_leaves_the_file(tmp_path, mac):
|
||||||
|
from PyQt6.QtCore import QFile
|
||||||
|
from lintunes import trash
|
||||||
|
song = tmp_path / "song.mp3"
|
||||||
|
song.write_bytes(b"x")
|
||||||
|
mac.setattr(QFile, "moveToTrash", staticmethod(lambda p: (False, "")))
|
||||||
|
with pytest.raises(trash.TrashError):
|
||||||
|
trash.send_to_trash(song)
|
||||||
|
assert song.read_bytes() == b"x"
|
||||||
|
|
||||||
|
|
||||||
|
# ---- sleep inhibition ----
|
||||||
|
|
||||||
|
class _FakeProc:
|
||||||
|
def __init__(self, argv, **kw):
|
||||||
|
self.argv = argv
|
||||||
|
self.terminated = False
|
||||||
|
_FakeProc.made.append(self)
|
||||||
|
|
||||||
|
def poll(self):
|
||||||
|
return 0 if self.terminated else None
|
||||||
|
|
||||||
|
def terminate(self):
|
||||||
|
self.terminated = True
|
||||||
|
|
||||||
|
def wait(self, timeout=None):
|
||||||
|
return 0
|
||||||
|
|
||||||
|
def kill(self):
|
||||||
|
self.terminated = True
|
||||||
|
|
||||||
|
|
||||||
|
def test_caffeinate_flags():
|
||||||
|
from lintunes import inhibit
|
||||||
|
assert inhibit.caffeinate_command(inhibit.INHIBIT_SUSPEND, pid=42) == \
|
||||||
|
["caffeinate", "-i", "-w", "42"]
|
||||||
|
assert inhibit.caffeinate_command(
|
||||||
|
inhibit.INHIBIT_SUSPEND | inhibit.INHIBIT_LOGOUT, pid=42) == \
|
||||||
|
["caffeinate", "-i", "-s", "-m", "-w", "42"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_mac_inhibitor_holds_one_caffeinate(mac):
|
||||||
|
from lintunes import inhibit
|
||||||
|
_FakeProc.made = []
|
||||||
|
mac.setattr(inhibit.shutil, "which", lambda name: "/usr/bin/" + name)
|
||||||
|
mac.setattr(inhibit.subprocess, "Popen", _FakeProc)
|
||||||
|
inh = inhibit.SleepInhibitor()
|
||||||
|
inh.inhibit()
|
||||||
|
inh.inhibit()
|
||||||
|
assert len(_FakeProc.made) == 1
|
||||||
|
assert _FakeProc.made[0].argv[:2] == ["caffeinate", "-i"]
|
||||||
|
assert _FakeProc.made[0].argv[-2:] == ["-w", str(os.getpid())]
|
||||||
|
inh.release()
|
||||||
|
assert _FakeProc.made[0].terminated
|
||||||
|
inh.release() # twice is fine
|
||||||
|
inh.inhibit()
|
||||||
|
assert len(_FakeProc.made) == 2
|
||||||
|
inhibit._release_all() # what atexit runs
|
||||||
|
assert _FakeProc.made[1].terminated
|
||||||
|
|
||||||
|
|
||||||
|
def test_mac_inhibitor_without_caffeinate_is_a_noop(mac):
|
||||||
|
from lintunes import inhibit
|
||||||
|
mac.setattr(inhibit.shutil, "which", lambda name: None)
|
||||||
|
inh = inhibit.SleepInhibitor()
|
||||||
|
inh.inhibit()
|
||||||
|
inh.release()
|
||||||
|
|
||||||
|
|
||||||
|
# ---- Now Playing ----
|
||||||
|
|
||||||
|
def test_setup_mpris_on_mac_without_pyobjc(mac, qapp):
|
||||||
|
from lintunes import mpris
|
||||||
|
mac.setitem(sys.modules, "MediaPlayer", None) # import → ImportError
|
||||||
|
assert mpris.setup_mpris(object(), object()) is None
|
||||||
|
|
||||||
|
|
||||||
|
class _Command:
|
||||||
|
def __init__(self):
|
||||||
|
self.handlers = []
|
||||||
|
self.enabled = False
|
||||||
|
|
||||||
|
def setEnabled_(self, on):
|
||||||
|
self.enabled = on
|
||||||
|
|
||||||
|
def addTargetWithHandler_(self, handler):
|
||||||
|
self.handlers.append(handler)
|
||||||
|
|
||||||
|
|
||||||
|
class _Center:
|
||||||
|
def __init__(self):
|
||||||
|
self.info = "unset"
|
||||||
|
self.state = None
|
||||||
|
|
||||||
|
def setNowPlayingInfo_(self, info):
|
||||||
|
self.info = info
|
||||||
|
|
||||||
|
def setPlaybackState_(self, state):
|
||||||
|
self.state = state
|
||||||
|
|
||||||
|
|
||||||
|
def _fake_mediaplayer():
|
||||||
|
mp = types.SimpleNamespace()
|
||||||
|
names = ("playCommand", "pauseCommand", "togglePlayPauseCommand",
|
||||||
|
"stopCommand", "nextTrackCommand", "previousTrackCommand",
|
||||||
|
"changePlaybackPositionCommand")
|
||||||
|
commands = {n: _Command() for n in names}
|
||||||
|
remote = types.SimpleNamespace(**{n: (lambda c=c: c) for n, c in commands.items()})
|
||||||
|
center = _Center()
|
||||||
|
mp.MPRemoteCommandCenter = types.SimpleNamespace(
|
||||||
|
sharedCommandCenter=lambda: remote)
|
||||||
|
mp.MPNowPlayingInfoCenter = types.SimpleNamespace(defaultCenter=lambda: center)
|
||||||
|
for key in ("MPMediaItemPropertyTitle", "MPMediaItemPropertyArtist",
|
||||||
|
"MPMediaItemPropertyAlbumTitle", "MPMediaItemPropertyPlaybackDuration",
|
||||||
|
"MPMediaItemPropertyArtwork",
|
||||||
|
"MPNowPlayingInfoPropertyElapsedPlaybackTime",
|
||||||
|
"MPNowPlayingInfoPropertyPlaybackRate"):
|
||||||
|
setattr(mp, key, key)
|
||||||
|
return mp, commands, center
|
||||||
|
|
||||||
|
|
||||||
|
def _fake_player():
|
||||||
|
from PyQt6.QtCore import QObject, pyqtSignal
|
||||||
|
|
||||||
|
class P(QObject):
|
||||||
|
track_changed = pyqtSignal(object)
|
||||||
|
playing_changed = pyqtSignal(bool)
|
||||||
|
position_changed = pyqtSignal("qint64")
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
super().__init__()
|
||||||
|
self.calls = []
|
||||||
|
self.current_track = None
|
||||||
|
self.playing = False
|
||||||
|
self.pos = 0
|
||||||
|
|
||||||
|
def is_playing(self):
|
||||||
|
return self.playing
|
||||||
|
|
||||||
|
def position_ms(self):
|
||||||
|
return self.pos
|
||||||
|
|
||||||
|
def duration_ms(self):
|
||||||
|
return 0
|
||||||
|
|
||||||
|
def __getattr__(self, name):
|
||||||
|
if name in ("play", "pause", "toggle_play", "stop", "next",
|
||||||
|
"previous", "seek"):
|
||||||
|
return lambda *a: self.calls.append((name, *a))
|
||||||
|
raise AttributeError(name)
|
||||||
|
return P()
|
||||||
|
|
||||||
|
|
||||||
|
def test_now_playing_routes_commands_and_mirrors_state(qapp):
|
||||||
|
from lintunes import nowplaying_mac
|
||||||
|
mp, commands, center = _fake_mediaplayer()
|
||||||
|
player = _fake_player()
|
||||||
|
np = nowplaying_mac.MacNowPlaying(player, None, mp)
|
||||||
|
assert all(c.enabled and len(c.handlers) == 1 for c in commands.values())
|
||||||
|
assert center.info is None and center.state == nowplaying_mac.STATE_STOPPED
|
||||||
|
|
||||||
|
for name, expected in (("togglePlayPauseCommand", "toggle_play"),
|
||||||
|
("nextTrackCommand", "next"),
|
||||||
|
("previousTrackCommand", "previous"),
|
||||||
|
("playCommand", "play"),
|
||||||
|
("pauseCommand", "pause")):
|
||||||
|
status = commands[name].handlers[0](object())
|
||||||
|
assert status == nowplaying_mac.STATUS_SUCCESS
|
||||||
|
assert player.calls[-1] == (expected,)
|
||||||
|
event = types.SimpleNamespace(positionTime=lambda: 12.5)
|
||||||
|
commands["changePlaybackPositionCommand"].handlers[0](event)
|
||||||
|
assert player.calls[-1] == ("seek", 12500)
|
||||||
|
|
||||||
|
player.current_track = types.SimpleNamespace(
|
||||||
|
track_id=1, name="Song", artist="Artist", album="Album",
|
||||||
|
total_time=200_000, location="")
|
||||||
|
player.playing = True
|
||||||
|
player.pos = 3000
|
||||||
|
player.track_changed.emit(player.current_track)
|
||||||
|
assert center.info["MPMediaItemPropertyTitle"] == "Song"
|
||||||
|
assert center.info["MPMediaItemPropertyArtist"] == "Artist"
|
||||||
|
assert center.info["MPMediaItemPropertyAlbumTitle"] == "Album"
|
||||||
|
assert center.info["MPMediaItemPropertyPlaybackDuration"] == 200.0
|
||||||
|
assert center.info["MPNowPlayingInfoPropertyElapsedPlaybackTime"] == 3.0
|
||||||
|
assert center.info["MPNowPlayingInfoPropertyPlaybackRate"] == 1.0
|
||||||
|
assert center.state == nowplaying_mac.STATE_PLAYING
|
||||||
|
player.playing = False
|
||||||
|
player.playing_changed.emit(False)
|
||||||
|
assert center.info["MPNowPlayingInfoPropertyPlaybackRate"] == 0.0
|
||||||
|
assert center.state == nowplaying_mac.STATE_PAUSED
|
||||||
|
np.deleteLater()
|
||||||
|
|
||||||
|
|
||||||
|
def test_now_playing_handler_from_another_thread_is_queued(qapp):
|
||||||
|
import threading
|
||||||
|
from lintunes import nowplaying_mac
|
||||||
|
mp, commands, _center = _fake_mediaplayer()
|
||||||
|
player = _fake_player()
|
||||||
|
np = nowplaying_mac.MacNowPlaying(player, None, mp)
|
||||||
|
t = threading.Thread(target=lambda: commands["nextTrackCommand"].handlers[0](None))
|
||||||
|
t.start()
|
||||||
|
t.join()
|
||||||
|
assert player.calls == [] # not run on the system's thread
|
||||||
|
qapp.processEvents()
|
||||||
|
assert player.calls == [("next",)]
|
||||||
|
np.deleteLater()
|
||||||
|
|
||||||
|
|
||||||
|
# ---- Finder reveal, shortcuts shown in menus ----
|
||||||
|
|
||||||
|
def test_reveal_uses_open_r_on_mac(mac):
|
||||||
|
from lintunes.gui import track_table
|
||||||
|
seen = []
|
||||||
|
mac.setattr(track_table.subprocess, "Popen",
|
||||||
|
lambda argv, **kw: seen.append(argv))
|
||||||
|
track_table.reveal_paths(["/Music/a.mp3", "/Music/b.mp3"])
|
||||||
|
assert seen == [["open", "-R", "/Music/a.mp3", "/Music/b.mp3"]]
|
||||||
|
|
||||||
|
|
||||||
|
def test_key_hint(qapp, monkeypatch):
|
||||||
|
from lintunes.gui.track_table import key_hint
|
||||||
|
assert key_hint("Ctrl+I") == "Ctrl+I"
|
||||||
|
assert key_hint("Del") == "Del"
|
||||||
|
monkeypatch.setattr(paths, "IS_MAC", True)
|
||||||
|
assert key_hint("Del") == "⌫"
|
||||||
|
|
||||||
|
|
||||||
|
# ---- menu bar ----
|
||||||
|
|
||||||
|
class _Prefs:
|
||||||
|
def __init__(self, value):
|
||||||
|
self.value = value
|
||||||
|
|
||||||
|
def get(self, key, default=None):
|
||||||
|
return self.value if key == "menu_bar" else default
|
||||||
|
|
||||||
|
|
||||||
|
def test_menu_bar_never_hides_on_mac(mac):
|
||||||
|
from lintunes.gui import menu_bar
|
||||||
|
assert menu_bar.hidden_by_pref(_Prefs("alt")) is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_menu_bar_pref_unchanged_on_linux():
|
||||||
|
from lintunes.gui import menu_bar
|
||||||
|
assert menu_bar.hidden_by_pref(_Prefs("alt")) is True
|
||||||
|
assert menu_bar.hidden_by_pref(_Prefs("always")) is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_register_shortcuts_is_a_noop_on_mac(qapp, mac):
|
||||||
|
from PyQt6.QtWidgets import QMainWindow
|
||||||
|
from lintunes.gui import menu_bar
|
||||||
|
win = QMainWindow()
|
||||||
|
win.menuBar().addMenu("&File").addAction("New")
|
||||||
|
menu_bar.register_shortcuts(win, win.menuBar())
|
||||||
|
assert win.actions() == []
|
||||||
|
mac.setattr(paths, "IS_MAC", False)
|
||||||
|
menu_bar.register_shortcuts(win, win.menuBar())
|
||||||
|
assert len(win.actions()) == 1
|
||||||
|
win.deleteLater()
|
||||||
|
|
||||||
|
|
||||||
|
# ---- the main window on a Mac ----
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def mac_window(qapp, tmp_path, mac):
|
||||||
|
from lintunes import device_sync
|
||||||
|
from lintunes.gui.main_window import MainWindow
|
||||||
|
from lintunes.library_manager import LibraryManager
|
||||||
|
from lintunes.models import Library
|
||||||
|
from lintunes.preferences import Preferences
|
||||||
|
probes = []
|
||||||
|
mac.setattr(device_sync.DeviceWatcher, "probe",
|
||||||
|
lambda self: probes.append(1))
|
||||||
|
manager = LibraryManager(Library(), tmp_path / "data")
|
||||||
|
win = MainWindow(manager, Preferences(tmp_path / "data"))
|
||||||
|
win.probes = probes
|
||||||
|
yield win
|
||||||
|
win.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_mac_window_has_no_rabbit(mac_window):
|
||||||
|
win = mac_window
|
||||||
|
for action in (win._andtunes_action, win._full_sync_action,
|
||||||
|
win._sync_settings_action, win._install_action,
|
||||||
|
win._shazam_action):
|
||||||
|
assert not action.isVisible() and not action.isEnabled()
|
||||||
|
win._refresh_connection_actions()
|
||||||
|
win._refresh_device_actions()
|
||||||
|
assert win.probes == []
|
||||||
|
for action in (win._andtunes_action, win._install_action, win._shazam_action):
|
||||||
|
assert not action.isEnabled()
|
||||||
|
|
||||||
|
|
||||||
|
def test_preferences_and_quit_go_to_the_app_menu(mac_window):
|
||||||
|
from PyQt6.QtGui import QAction
|
||||||
|
roles = {a.text(): a.menuRole() for a in mac_window.actions()
|
||||||
|
+ [a for m in mac_window.menuBar().actions() if m.menu()
|
||||||
|
for a in m.menu().actions()]}
|
||||||
|
assert roles["Preferences…"] == QAction.MenuRole.PreferencesRole
|
||||||
|
assert roles["Quit"] == QAction.MenuRole.QuitRole
|
||||||
|
|
||||||
|
|
||||||
|
def test_preferences_hide_the_menu_bar_row_on_mac(qapp, tmp_path, mac):
|
||||||
|
from lintunes.gui.preferences_dialog import PreferencesDialog
|
||||||
|
from lintunes.preferences import Preferences
|
||||||
|
|
||||||
|
from tests.test_round40 import _FakeLastFm
|
||||||
|
dialog = PreferencesDialog(Preferences(tmp_path), _FakeLastFm())
|
||||||
|
assert dialog._menu_bar_check.isHidden()
|
||||||
|
dialog.deleteLater()
|
||||||
|
|
||||||
|
|
||||||
|
# ---- files opened on the Dock icon ----
|
||||||
|
|
||||||
|
def test_file_open_events_import_as_one_batch(qapp):
|
||||||
|
import time
|
||||||
|
from PyQt6.QtCore import QEvent
|
||||||
|
from lintunes import main
|
||||||
|
|
||||||
|
class _Open: # QFileOpenEvent can't be built from Python
|
||||||
|
def __init__(self, name):
|
||||||
|
self.name = name
|
||||||
|
|
||||||
|
def type(self):
|
||||||
|
return QEvent.Type.FileOpen
|
||||||
|
|
||||||
|
def file(self):
|
||||||
|
return self.name
|
||||||
|
got = []
|
||||||
|
filt = main.FileOpenFilter(got.append)
|
||||||
|
for name in ("/m/a.mp3", "/m/b.mp3"):
|
||||||
|
assert filt.eventFilter(None, _Open(name))
|
||||||
|
deadline = time.monotonic() + 2
|
||||||
|
while not got and time.monotonic() < deadline:
|
||||||
|
qapp.processEvents()
|
||||||
|
time.sleep(0.01)
|
||||||
|
assert got == [[Path("/m/a.mp3"), Path("/m/b.mp3")]]
|
||||||
|
|
||||||
|
|
||||||
|
# ---- rsync on a Mac ----
|
||||||
|
|
||||||
|
def test_rsync_major():
|
||||||
|
from lintunes.export import upload
|
||||||
|
assert upload.rsync_major("rsync version 3.2.7 protocol version 31") == 3
|
||||||
|
assert upload.rsync_major(
|
||||||
|
"openrsync: protocol version 29\nrsync version 2.6.9 compatible") == 2
|
||||||
|
assert upload.rsync_major("") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_mac_rsync_problem_only_on_mac(monkeypatch):
|
||||||
|
from lintunes.export import upload
|
||||||
|
assert upload.mac_rsync_problem() is None
|
||||||
|
monkeypatch.setattr(paths, "IS_MAC", True)
|
||||||
|
monkeypatch.setattr(upload.subprocess, "run", lambda *a, **k:
|
||||||
|
types.SimpleNamespace(stdout="rsync version 2.6.9 protocol version 29"))
|
||||||
|
assert "brew install rsync" in upload.mac_rsync_problem()
|
||||||
|
monkeypatch.setattr(upload.subprocess, "run", lambda *a, **k:
|
||||||
|
types.SimpleNamespace(stdout="rsync version 3.4.1 protocol version 32"))
|
||||||
|
assert upload.mac_rsync_problem() is None
|
||||||
|
|
||||||
|
|
||||||
|
# ---- D-Bus optional ----
|
||||||
|
|
||||||
|
def test_modules_import_without_qtdbus(monkeypatch):
|
||||||
|
"""With QtDBus gone, mpris/inhibit/track_table still import and the
|
||||||
|
inhibitor no-ops (re-imported fresh, then restored)."""
|
||||||
|
import importlib
|
||||||
|
saved = {n: sys.modules.pop(n) for n in
|
||||||
|
("lintunes.mpris", "lintunes.inhibit") if n in sys.modules}
|
||||||
|
monkeypatch.setitem(sys.modules, "PyQt6.QtDBus", None)
|
||||||
|
try:
|
||||||
|
mpris = importlib.import_module("lintunes.mpris")
|
||||||
|
inhibit = importlib.import_module("lintunes.inhibit")
|
||||||
|
assert not mpris.HAVE_DBUS and not inhibit.HAVE_DBUS
|
||||||
|
assert mpris.setup_mpris(object(), object()) is None
|
||||||
|
assert mpris.string_array(["a"]) == ["a"]
|
||||||
|
inh = inhibit.SleepInhibitor()
|
||||||
|
inh.inhibit()
|
||||||
|
inh.release()
|
||||||
|
finally:
|
||||||
|
import lintunes
|
||||||
|
for n in ("lintunes.mpris", "lintunes.inhibit"):
|
||||||
|
sys.modules.pop(n, None)
|
||||||
|
short = n.split(".")[1]
|
||||||
|
if hasattr(lintunes, short):
|
||||||
|
delattr(lintunes, short)
|
||||||
|
sys.modules.update(saved)
|
||||||
|
for n, module in saved.items():
|
||||||
|
setattr(lintunes, n.split(".")[1], module)
|
||||||
|
|
||||||
|
|
||||||
|
def test_case_only_rename_leaves_the_file_alone(tmp_path, monkeypatch):
|
||||||
|
"""On a filesystem that ignores case, the "new" folder is the old one:
|
||||||
|
the file must not be renamed beside itself."""
|
||||||
|
import os
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from lintunes.library_manager import LibraryManager
|
||||||
|
|
||||||
|
root = tmp_path / "Music"
|
||||||
|
src = root / "Rjd2" / "Deadringer" / "01 Song.mp3"
|
||||||
|
src.parent.mkdir(parents=True)
|
||||||
|
src.write_bytes(b"x")
|
||||||
|
dest = root / "RJD2" / "Deadringer" / "01 Song.mp3"
|
||||||
|
real_exists = type(src).exists
|
||||||
|
monkeypatch.setattr(type(src), "exists",
|
||||||
|
lambda p: p == dest or real_exists(p))
|
||||||
|
monkeypatch.setattr(os.path, "samefile", lambda a, b: True)
|
||||||
|
moved = []
|
||||||
|
fake = SimpleNamespace(
|
||||||
|
_ORGANIZE_FIELDS=LibraryManager._ORGANIZE_FIELDS,
|
||||||
|
organize_root=lambda: root,
|
||||||
|
_move_file=lambda s, d: moved.append((s, d)) or d)
|
||||||
|
track = SimpleNamespace(location=str(src), name="Song", artist="Rjd2",
|
||||||
|
album_artist="", album="Deadringer",
|
||||||
|
compilation=False)
|
||||||
|
for field in LibraryManager._ORGANIZE_FIELDS:
|
||||||
|
if not hasattr(track, field):
|
||||||
|
setattr(track, field, "")
|
||||||
|
assert LibraryManager._maybe_move_file(fake, track, {"artist": "RJD2"}) is None
|
||||||
|
assert moved == []
|
||||||
@@ -0,0 +1,448 @@
|
|||||||
|
"""Round 129: the Mac app's packaging, offline.
|
||||||
|
|
||||||
|
Nothing here needs a Mac or the network: release checks are fed canned
|
||||||
|
GitHub answers, the bundled-tool fetcher is fed local archives, and the
|
||||||
|
icon/Info.plist builders are pure. What only a Mac can check (PyInstaller,
|
||||||
|
codesign, hdiutil) runs in .github/workflows/mac.yml.
|
||||||
|
"""
|
||||||
|
import hashlib
|
||||||
|
import importlib.util
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import plistlib
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tarfile
|
||||||
|
import zipfile
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from lintunes import __version__, release_info
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
MAC = ROOT / "packaging" / "mac"
|
||||||
|
|
||||||
|
|
||||||
|
def _load(name, path):
|
||||||
|
spec = importlib.util.spec_from_file_location(name, path)
|
||||||
|
module = importlib.util.module_from_spec(spec)
|
||||||
|
sys.modules[name] = module
|
||||||
|
spec.loader.exec_module(module)
|
||||||
|
return module
|
||||||
|
|
||||||
|
|
||||||
|
# ---- versions and the release answer ----
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("text, expected", [
|
||||||
|
("v0.92.0", (0, 92, 0)),
|
||||||
|
("0.92.0", (0, 92, 0)),
|
||||||
|
("v1.2", (1, 2, 0)),
|
||||||
|
(" v10.0.3 ", (10, 0, 3)),
|
||||||
|
("v1.2.3-beta", None),
|
||||||
|
("latest", None),
|
||||||
|
("", None),
|
||||||
|
(None, None),
|
||||||
|
(123, None),
|
||||||
|
])
|
||||||
|
def test_parse_version(text, expected):
|
||||||
|
assert release_info.parse_version(text) == expected
|
||||||
|
|
||||||
|
|
||||||
|
def test_versions_compare_as_numbers_not_strings():
|
||||||
|
assert release_info.is_newer("v0.100.0", "0.99.0")
|
||||||
|
assert release_info.is_newer("v1.0.0", "0.999.999")
|
||||||
|
assert release_info.is_newer("0.92.1", "0.92.0")
|
||||||
|
assert not release_info.is_newer("v0.92.0", "0.92.0")
|
||||||
|
assert not release_info.is_newer("v0.9.0", "0.10.0")
|
||||||
|
assert not release_info.is_newer("nonsense", "0.1.0")
|
||||||
|
assert not release_info.is_newer("v1.0.0", "garbage")
|
||||||
|
|
||||||
|
|
||||||
|
GOOD = {
|
||||||
|
"tag_name": "v0.95.0",
|
||||||
|
"html_url": "https://github.com/someone/lintunes/releases/tag/v0.95.0",
|
||||||
|
"draft": False,
|
||||||
|
"prerelease": False,
|
||||||
|
"assets": [{"name": "LinTunes-0.95.0-AppleSilicon.dmg"}],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_latest_release():
|
||||||
|
assert release_info.parse_latest_release(GOOD) == (
|
||||||
|
"0.95.0", "https://github.com/someone/lintunes/releases/tag/v0.95.0")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("change", [
|
||||||
|
{"draft": True},
|
||||||
|
{"prerelease": True},
|
||||||
|
{"tag_name": "nightly"},
|
||||||
|
{"tag_name": None},
|
||||||
|
{"html_url": "https://evil.example/releases/v0.95.0"},
|
||||||
|
{"html_url": None},
|
||||||
|
])
|
||||||
|
def test_unusable_releases_are_ignored(change):
|
||||||
|
assert release_info.parse_latest_release({**GOOD, **change}) is None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("payload", [None, [], "text", {"message": "Not Found"}])
|
||||||
|
def test_garbage_answers_are_ignored(payload):
|
||||||
|
assert release_info.parse_latest_release(payload) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_repo_means_no_checks():
|
||||||
|
assert release_info.latest_release_url("") is None
|
||||||
|
assert release_info.releases_page("") is None
|
||||||
|
assert release_info.latest_release_url("not a repo") is None
|
||||||
|
assert release_info.latest_release_url("a/b/c") is None
|
||||||
|
assert (release_info.latest_release_url("owner/name")
|
||||||
|
== "https://api.github.com/repos/owner/name/releases/latest")
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_shipped_constants():
|
||||||
|
# Empty until the GitHub mirror exists; anything else must be owner/name.
|
||||||
|
assert (release_info.GITHUB_REPO == ""
|
||||||
|
or release_info.valid_repo(release_info.GITHUB_REPO))
|
||||||
|
assert release_info.BUNDLE_ID == "org.lintunes.LinTunes"
|
||||||
|
assert "@" not in release_info.USER_AGENT
|
||||||
|
|
||||||
|
|
||||||
|
# ---- the updater's release path ----
|
||||||
|
|
||||||
|
def _response(status, payload=None, raises=None):
|
||||||
|
r = MagicMock()
|
||||||
|
r.status_code = status
|
||||||
|
if raises:
|
||||||
|
r.json.side_effect = raises
|
||||||
|
else:
|
||||||
|
r.json.return_value = payload
|
||||||
|
return r
|
||||||
|
|
||||||
|
|
||||||
|
def test_fetch_latest_release():
|
||||||
|
from lintunes import updater
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def get(url, timeout, headers):
|
||||||
|
calls.append((url, headers))
|
||||||
|
return _response(200, GOOD)
|
||||||
|
|
||||||
|
assert updater.fetch_latest_release("o/n", get=get) == (
|
||||||
|
"0.95.0", GOOD["html_url"])
|
||||||
|
url, headers = calls[0]
|
||||||
|
assert url == "https://api.github.com/repos/o/n/releases/latest"
|
||||||
|
assert headers["User-Agent"] == release_info.USER_AGENT
|
||||||
|
assert "Authorization" not in headers
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("get", [
|
||||||
|
lambda *a, **k: _response(404, {"message": "Not Found"}),
|
||||||
|
lambda *a, **k: _response(403, {"message": "rate limit"}),
|
||||||
|
lambda *a, **k: _response(200, raises=ValueError("not json")),
|
||||||
|
lambda *a, **k: (_ for _ in ()).throw(OSError("offline")),
|
||||||
|
])
|
||||||
|
def test_fetch_is_quiet_on_failure(get):
|
||||||
|
from lintunes import updater
|
||||||
|
assert updater.fetch_latest_release("o/n", get=get) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_fetch_never_asks_without_a_repo():
|
||||||
|
from lintunes import updater
|
||||||
|
get = MagicMock()
|
||||||
|
assert updater.fetch_latest_release("", get=get) is None
|
||||||
|
get.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
def test_release_mode_never_runs_git(qapp, monkeypatch):
|
||||||
|
from lintunes import updater
|
||||||
|
run = MagicMock(side_effect=AssertionError("git ran"))
|
||||||
|
monkeypatch.setattr(updater.subprocess, "run", run)
|
||||||
|
u = updater.Updater(release_mode=True)
|
||||||
|
assert u.short_hash() is None
|
||||||
|
u.update_async() # a no-op: the button opens a page
|
||||||
|
monkeypatch.setattr(release_info, "GITHUB_REPO", "")
|
||||||
|
assert not u.enabled
|
||||||
|
u.start_checking() # no repo: no timers, no checks
|
||||||
|
assert u._timer is None
|
||||||
|
run.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
def test_release_mode_reports_only_a_newer_release(qapp, monkeypatch):
|
||||||
|
from lintunes import updater
|
||||||
|
u = updater.Updater(release_mode=True)
|
||||||
|
seen = []
|
||||||
|
u.release_available.connect(lambda v, page: seen.append((v, page)))
|
||||||
|
|
||||||
|
monkeypatch.setattr(updater, "fetch_latest_release",
|
||||||
|
lambda: ("999.0.0", GOOD["html_url"]))
|
||||||
|
u._check_release()
|
||||||
|
assert seen == [("999.0.0", GOOD["html_url"])]
|
||||||
|
|
||||||
|
monkeypatch.setattr(updater, "fetch_latest_release",
|
||||||
|
lambda: (__version__, GOOD["html_url"]))
|
||||||
|
u._check_release()
|
||||||
|
monkeypatch.setattr(updater, "fetch_latest_release", lambda: None)
|
||||||
|
u._check_release()
|
||||||
|
assert len(seen) == 1
|
||||||
|
assert not u._busy
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_checkout_keeps_the_git_path(qapp):
|
||||||
|
from lintunes import paths, updater
|
||||||
|
assert not paths.FROZEN
|
||||||
|
assert updater.Updater().release_mode is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_version_button_opens_the_release_page(qapp, monkeypatch):
|
||||||
|
from lintunes import updater
|
||||||
|
from lintunes.gui import version_button
|
||||||
|
|
||||||
|
u = updater.Updater(release_mode=True)
|
||||||
|
button = version_button.VersionButton(u)
|
||||||
|
opened = []
|
||||||
|
monkeypatch.setattr(version_button.QDesktopServices, "openUrl",
|
||||||
|
lambda url: opened.append(url.toString()) or True)
|
||||||
|
confirm = MagicMock(return_value=True)
|
||||||
|
monkeypatch.setattr(button, "_confirm", confirm)
|
||||||
|
monkeypatch.setattr(u, "update_async", MagicMock())
|
||||||
|
|
||||||
|
button.click() # nothing ready: nothing happens
|
||||||
|
assert opened == []
|
||||||
|
|
||||||
|
u.release_available.emit("999.0.0", GOOD["html_url"])
|
||||||
|
assert button.text() == f"v{__version__}*"
|
||||||
|
assert "999.0.0" in button.toolTip()
|
||||||
|
button.click()
|
||||||
|
assert opened == [GOOD["html_url"]]
|
||||||
|
confirm.assert_not_called() # no "pull and restart?" question
|
||||||
|
u.update_async.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
# ---- bundled tools ----
|
||||||
|
|
||||||
|
def test_tools_manifest_is_pinned():
|
||||||
|
fetch = _load("lintunes_fetch_tools", MAC / "fetch_tools.py")
|
||||||
|
tools = fetch.load_manifest()
|
||||||
|
assert set(tools) == {"ffmpeg", "ffprobe", "fpcalc"}
|
||||||
|
for name, tool in tools.items():
|
||||||
|
assert tool["version"] and tool["license"]
|
||||||
|
assert set(tool["arch"]) == set(fetch.ARCHES)
|
||||||
|
for entry in tool["arch"].values():
|
||||||
|
assert entry["url"].startswith("https://")
|
||||||
|
assert re.fullmatch(r"[0-9a-f]{64}", entry["sha256"])
|
||||||
|
assert entry["member"].endswith(name)
|
||||||
|
# The two architectures are different files.
|
||||||
|
for tool in tools.values():
|
||||||
|
assert tool["arch"]["arm64"]["sha256"] != tool["arch"]["x86_64"]["sha256"]
|
||||||
|
|
||||||
|
|
||||||
|
def _zip_with(member, data):
|
||||||
|
buf = io.BytesIO()
|
||||||
|
with zipfile.ZipFile(buf, "w") as z:
|
||||||
|
z.writestr(member, data)
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def _tar_with(member, data):
|
||||||
|
buf = io.BytesIO()
|
||||||
|
with tarfile.open(fileobj=buf, mode="w:gz") as t:
|
||||||
|
info = tarfile.TarInfo(member)
|
||||||
|
info.size = len(data)
|
||||||
|
t.addfile(info, io.BytesIO(data))
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def test_fetch_verifies_then_extracts_only_the_member(tmp_path, monkeypatch):
|
||||||
|
fetch = _load("lintunes_fetch_tools", MAC / "fetch_tools.py")
|
||||||
|
archives = {
|
||||||
|
"https://example.org/ff.zip": _zip_with("ffmpeg", b"FFMPEG"),
|
||||||
|
"https://example.org/fp.tar.gz": _tar_with("dir/fpcalc", b"FPCALC"),
|
||||||
|
}
|
||||||
|
downloads = []
|
||||||
|
|
||||||
|
def download(url, dest):
|
||||||
|
downloads.append(url)
|
||||||
|
dest.write_bytes(archives[url])
|
||||||
|
|
||||||
|
monkeypatch.setattr(fetch, "download", download)
|
||||||
|
manifest = {
|
||||||
|
"ffmpeg": {"version": "1", "arch": {"arm64": {
|
||||||
|
"url": "https://example.org/ff.zip", "member": "ffmpeg",
|
||||||
|
"sha256": hashlib.sha256(archives["https://example.org/ff.zip"]).hexdigest()}}},
|
||||||
|
"fpcalc": {"version": "1", "arch": {"arm64": {
|
||||||
|
"url": "https://example.org/fp.tar.gz", "member": "dir/fpcalc",
|
||||||
|
"sha256": hashlib.sha256(archives["https://example.org/fp.tar.gz"]).hexdigest()}}},
|
||||||
|
}
|
||||||
|
out = tmp_path / "tools"
|
||||||
|
made = fetch.fetch("arm64", out, manifest)
|
||||||
|
assert [p.name for p in made] == ["ffmpeg", "fpcalc"]
|
||||||
|
assert (out / "ffmpeg").read_bytes() == b"FFMPEG"
|
||||||
|
assert (out / "fpcalc").read_bytes() == b"FPCALC"
|
||||||
|
assert (out / "fpcalc").stat().st_mode & 0o111
|
||||||
|
assert not (out / "dir").exists()
|
||||||
|
# A second run uses the verified cache.
|
||||||
|
fetch.fetch("arm64", out, manifest)
|
||||||
|
assert len(downloads) == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_fetch_refuses_a_wrong_hash(tmp_path, monkeypatch):
|
||||||
|
fetch = _load("lintunes_fetch_tools", MAC / "fetch_tools.py")
|
||||||
|
monkeypatch.setattr(fetch, "download",
|
||||||
|
lambda url, dest: dest.write_bytes(_zip_with("ffmpeg", b"EVIL")))
|
||||||
|
manifest = {"ffmpeg": {"version": "1", "arch": {"arm64": {
|
||||||
|
"url": "https://example.org/ff.zip", "member": "ffmpeg",
|
||||||
|
"sha256": "0" * 64}}}}
|
||||||
|
with pytest.raises(fetch.VerifyError):
|
||||||
|
fetch.fetch("arm64", tmp_path / "tools", manifest)
|
||||||
|
assert not (tmp_path / "tools" / "ffmpeg").exists()
|
||||||
|
|
||||||
|
|
||||||
|
def test_fetch_refuses_plain_http(tmp_path):
|
||||||
|
fetch = _load("lintunes_fetch_tools", MAC / "fetch_tools.py")
|
||||||
|
with pytest.raises(fetch.VerifyError):
|
||||||
|
fetch.download("http://example.org/x.zip", tmp_path / "x")
|
||||||
|
|
||||||
|
|
||||||
|
# ---- icon ----
|
||||||
|
|
||||||
|
def test_icns_container_round_trips():
|
||||||
|
pytest.importorskip("PIL")
|
||||||
|
from PIL import Image
|
||||||
|
icons = _load("lintunes_make_icons", ROOT / "scripts" / "make_icons.py")
|
||||||
|
master = icons.mac_master(Image.new("RGB", (64, 64), (10, 200, 30)))
|
||||||
|
assert master.size == (1024, 1024)
|
||||||
|
# The ~10 % margin is transparent; the middle isn't.
|
||||||
|
assert master.getpixel((20, 20))[3] == 0
|
||||||
|
assert master.getpixel((512, 512))[3] == 255
|
||||||
|
entries = icons.read_icns(icons.icns_bytes(master))
|
||||||
|
assert [k for k, _ in entries] == [k for k, _ in icons.ICNS_TYPES]
|
||||||
|
for (kind, size), (_, png) in zip(icons.ICNS_TYPES, entries):
|
||||||
|
assert png[:8] == b"\x89PNG\r\n\x1a\n"
|
||||||
|
assert Image.open(io.BytesIO(png)).size == (size, size)
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_committed_icns():
|
||||||
|
icons = _load("lintunes_make_icons", ROOT / "scripts" / "make_icons.py") \
|
||||||
|
if importlib.util.find_spec("PIL") else None
|
||||||
|
blob = (MAC / "LinTunes.icns").read_bytes()
|
||||||
|
assert blob[:4] == b"icns"
|
||||||
|
if icons:
|
||||||
|
kinds = {k for k, _ in icons.read_icns(blob)}
|
||||||
|
assert {b"ic10", b"ic09", b"ic07", b"icp4"} <= kinds
|
||||||
|
|
||||||
|
|
||||||
|
# ---- Info.plist, spec, signing, workflow ----
|
||||||
|
|
||||||
|
def test_info_plist():
|
||||||
|
plist = _load("lintunes_mac_plist", MAC / "plist.py")
|
||||||
|
info = plist.info_plist()
|
||||||
|
assert info["CFBundleIdentifier"] == release_info.BUNDLE_ID
|
||||||
|
assert info["CFBundleShortVersionString"] == __version__
|
||||||
|
assert info["NSHighResolutionCapable"] is True
|
||||||
|
assert info["LSMinimumSystemVersion"] == plist.MINIMUM_MACOS
|
||||||
|
assert info["LSApplicationCategoryType"] == "public.app-category.music"
|
||||||
|
assert info["NSLocalNetworkUsageDescription"]
|
||||||
|
for service in ("_googlecast._tcp", "_raop._tcp", "_airplay._tcp"):
|
||||||
|
assert service in info["NSBonjourServices"]
|
||||||
|
doc = info["CFBundleDocumentTypes"][0]
|
||||||
|
assert doc["LSHandlerRank"] == "Alternate"
|
||||||
|
assert "public.mp3" in doc["LSItemContentTypes"]
|
||||||
|
plistlib.dumps(info) # serializable as PyInstaller will
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_spec_ships_what_the_app_reads_and_not_the_r1_app():
|
||||||
|
spec = (MAC / "LinTunes.spec").read_text()
|
||||||
|
for needed in ("tink.wav", "airhorn.mp3", '"templates"', "tables.npz",
|
||||||
|
"_spleeter_run.py", "drag-icon.png", "rthook_certifi.py",
|
||||||
|
"argv_emulation=False", "LinTunes.icns"):
|
||||||
|
assert needed in spec, needed
|
||||||
|
code = "\n".join(line.split("#")[0] for line in spec.splitlines())
|
||||||
|
assert "andTunes.apk" not in code and "buttons" not in code
|
||||||
|
assert "android" not in code
|
||||||
|
for path in ("launch.py", "rthook_certifi.py", "THIRD-PARTY.md",
|
||||||
|
"licenses/GPL-3.0.txt", "licenses/LGPL-2.1.txt",
|
||||||
|
"licenses/chromaprint-LICENSE.md"):
|
||||||
|
assert (MAC / path).is_file(), path
|
||||||
|
for path in ("lintunes/dj/_spleeter_run.py", "packaging/drag-icon.png",
|
||||||
|
"lintunes/kaleidostrobe/tables.npz",
|
||||||
|
"lintunes/sounds/tink.wav", "lintunes/sounds/airhorn.mp3"):
|
||||||
|
assert (ROOT / path).is_file(), path
|
||||||
|
|
||||||
|
|
||||||
|
def test_entitlements_parse():
|
||||||
|
ent = plistlib.loads((MAC / "entitlements.plist").read_bytes())
|
||||||
|
assert ent["com.apple.security.cs.allow-unsigned-executable-memory"] is True
|
||||||
|
assert "com.apple.security.app-sandbox" not in ent
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("script", ["build.sh", "smoke_test.sh"])
|
||||||
|
def test_shell_scripts_parse(script):
|
||||||
|
subprocess.run(["bash", "-n", str(MAC / script)], check=True)
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_pins_pyinstaller_and_refuses_linux():
|
||||||
|
text = (MAC / "build.sh").read_text()
|
||||||
|
assert re.search(r'^PYINSTALLER_VERSION="\d+\.\d+\.\d+"$', text, re.M)
|
||||||
|
if sys.platform != "darwin":
|
||||||
|
proc = subprocess.run(["bash", str(MAC / "build.sh")],
|
||||||
|
capture_output=True, text=True)
|
||||||
|
assert proc.returncode != 0 and "Mac" in proc.stderr
|
||||||
|
|
||||||
|
|
||||||
|
def test_workflow_actions_are_pinned_to_commits():
|
||||||
|
workflows = list((ROOT / ".github" / "workflows").glob("*.yml"))
|
||||||
|
assert workflows
|
||||||
|
for wf in workflows:
|
||||||
|
text = wf.read_text()
|
||||||
|
for uses in re.findall(r"uses:\s*(\S+)", text):
|
||||||
|
if uses.startswith("./"):
|
||||||
|
continue
|
||||||
|
assert re.fullmatch(r"[\w.-]+/[\w./-]+@[0-9a-f]{40}", uses), uses
|
||||||
|
assert "permissions:" in text
|
||||||
|
|
||||||
|
|
||||||
|
def test_workflow_least_privilege():
|
||||||
|
text = (ROOT / ".github" / "workflows" / "mac.yml").read_text()
|
||||||
|
top = text.split("\njobs:")[0]
|
||||||
|
assert re.search(r"^permissions:\n contents: read$", top, re.M)
|
||||||
|
assert text.count("contents: write") == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_requirements_match_setup():
|
||||||
|
reqs = (ROOT / "requirements.txt").read_text()
|
||||||
|
setup = (ROOT / "setup.py").read_text()
|
||||||
|
assert "pyatv" in reqs
|
||||||
|
for pkg in ("pyobjc-framework-Cocoa", "pyobjc-framework-MediaPlayer"):
|
||||||
|
for text in (reqs, setup):
|
||||||
|
line = next(l for l in text.splitlines() if pkg in l)
|
||||||
|
assert 'sys_platform == "darwin"' in line
|
||||||
|
|
||||||
|
|
||||||
|
def _origin_host():
|
||||||
|
"""The git host this checkout came from, read at run time so the
|
||||||
|
test itself never names it."""
|
||||||
|
try:
|
||||||
|
url = subprocess.run(["git", "-C", str(ROOT), "remote", "get-url",
|
||||||
|
"origin"], capture_output=True, text=True,
|
||||||
|
timeout=10).stdout.strip()
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
return None
|
||||||
|
m = re.match(r"^(?:\w+://)?(?:[^@/]+@)?([^/:]+)", url)
|
||||||
|
host = m[1] if m else None
|
||||||
|
return host if host and host != "github.com" else None
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_mac_files_never_name_the_private_host():
|
||||||
|
host = _origin_host()
|
||||||
|
if not host:
|
||||||
|
pytest.skip("no private origin to check against")
|
||||||
|
files = [ROOT / "docs" / d for d in ("mac.md", "mac-release.md",
|
||||||
|
"mac-testing.md")]
|
||||||
|
files += [p for p in MAC.rglob("*") if p.is_file()
|
||||||
|
and p.suffix in (".sh", ".py", ".md", ".json", ".spec", ".plist")]
|
||||||
|
files += list((ROOT / ".github").rglob("*.yml"))
|
||||||
|
files.append(ROOT / "lintunes" / "release_info.py")
|
||||||
|
for path in files:
|
||||||
|
assert host not in path.read_text(), path
|
||||||
Reference in New Issue
Block a user