From 7d0803481ba2e602c445bb6b609b3cf38c1a65e0 Mon Sep 17 00:00:00 2001 From: Elijah Kuntz Date: Mon, 2 Nov 2026 15:14:40 -0700 Subject: [PATCH] Port Kaleido Desktop to macOS MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit macOS (Apple silicon) now plays, browses and updates like Windows: - Video: libmpv's render API draws into a CAOpenGLLayer beneath the WKWebView, with the miniplayer rectangle, HDR passthrough through extended dynamic range (PQ/BT.2020) and display-sleep prevention. - Window: native traffic lights on the top bar's centre line, hidden with the player's controls; the page's caption buttons are Windows-only. - Interface: macOS shortcut labels (⌘K, ⌘[, ⌃⌘F), Plex identifies the player as a Mac, and header values are kept ASCII (Mac computer names usually contain a curly apostrophe). - The window appears without waiting for an animation frame, which WKWebView doesn't run in a hidden window. - Credentials: release builds use the Keychain and are signed with a lasting self-signed certificate so access survives updates; debug builds keep tokens in a private file to avoid prompts on every rebuild. - Bundling: scripts/fetch-libmpv.sh makes Homebrew's libmpv and its libraries self-contained; scripts/build.sh builds the .app, .dmg and signed update archive. Releases now carry both platforms: publish-release.mjs uploads each machine's build into one release, and update-manifest.mjs writes the feed from that release's assets, refusing while a platform is missing. The updater uses a new signing key (public key in tauri.conf.json), so existing installs must be reinstalled once. Co-Authored-By: Claude Opus 5.5 --- .forgejo/workflows/build-installers.yml | 11 +- .gitignore | 1 + AGENTS.md | 19 +- README.md | 26 +- docs/architecture.md | 42 +- docs/development.md | 96 +++-- scripts/build.sh | 54 +++ scripts/fetch-libmpv.sh | 33 +- scripts/publish-release.mjs | 58 ++- scripts/release-common.mjs | 49 +++ scripts/update-manifest.mjs | 81 ++-- src-tauri/Cargo.lock | 55 +++ src-tauri/Cargo.toml | 8 + src-tauri/src/lib.rs | 1 + src-tauri/src/mpv.rs | 15 + src-tauri/src/platform/linux.rs | 17 +- src-tauri/src/platform/macos.rs | 538 +++++++++++++++++++++++- src-tauri/src/platform/mod.rs | 4 +- src-tauri/src/platform/windows.rs | 21 +- src-tauri/src/player.rs | 16 +- src-tauri/src/system.rs | 67 ++- src-tauri/tauri.conf.json | 2 +- src-tauri/tauri.macos.conf.json | 34 +- src/app/App.tsx | 19 +- src/app/TopBar.tsx | 9 +- src/app/session.ts | 2 +- src/main.tsx | 10 + src/platform/native.ts | 17 +- src/player/PlayerOverlay.tsx | 8 + src/plex/account.ts | 6 +- src/plex/client.ts | 34 +- src/plex/plex.test.ts | 8 + src/screens/Downloads.tsx | 2 +- src/screens/WindowDrag.tsx | 16 +- src/screens/settings/AppSettings.tsx | 18 +- src/styles/app.css | 8 + src/styles/player.css | 3 + updates/README.md | 11 +- vendor/mpv/README.md | 2 +- 39 files changed, 1191 insertions(+), 230 deletions(-) create mode 100644 scripts/build.sh create mode 100644 scripts/release-common.mjs diff --git a/.forgejo/workflows/build-installers.yml b/.forgejo/workflows/build-installers.yml index 2c8d973..135517d 100644 --- a/.forgejo/workflows/build-installers.yml +++ b/.forgejo/workflows/build-installers.yml @@ -1,8 +1,8 @@ name: Build Kaleido Desktop installers # Started by hand (Actions, then this workflow, then Run). Each platform needs a runner # with its label; without one the job would wait indefinitely, so this never runs on -# push. Releases can instead be built with scripts/build.ps1 and published with -# scripts/publish-release.mjs. +# push. Releases can instead be built with scripts/build.ps1 (Windows) or +# scripts/build.sh (macOS) and published with scripts/publish-release.mjs. on: workflow_dispatch: @@ -29,11 +29,14 @@ jobs: TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }} run: ./scripts/build.ps1 - - name: Build (macOS / Linux) - if: matrix.os != 'windows' + - name: Build (macOS) + if: matrix.os == 'macos' env: TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }} + run: sh scripts/build.sh + - name: Build (Linux) + if: matrix.os == 'linux' run: | sh scripts/fetch-libmpv.sh npm ci diff --git a/.gitignore b/.gitignore index 71072a7..4b74645 100644 --- a/.gitignore +++ b/.gitignore @@ -10,5 +10,6 @@ vendor/mpv/*/ .env .env.* evidence/ +.DS_Store *.log .claude/ diff --git a/AGENTS.md b/AGENTS.md index 0ebe3a8..cf3a139 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,7 +11,7 @@ - Keep the interface restrained: no redundant buttons or navigation. - `.env` (`PLEX_SERVER_URL`, `PLEX_TOKEN`) is for local testing only. Never print, commit or embed credentials. `.tools/updater.key` signs updates; never commit or - replace it. + replace it. `.tools/macos-signing.*` backs up the macOS signing certificate; same rules. - Shared code goes in `src/` and `src-tauri/src/`; anything OS-specific goes in `src-tauri/src/platform/.rs` or `tauri..conf.json`. @@ -19,19 +19,20 @@ - `npm run typecheck`, `npm test`, `cargo check --manifest-path src-tauri/Cargo.toml`. - UI: `npm run dev` and a browser at http://localhost:1420 (signs in from `.env`). -- Native: `npm run tauri dev` with `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9333`; - `window.__kaleido` exposes the stores in development. +- Native: `npm run tauri dev` (on Windows with `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9333`); + `window.__kaleido` exposes the stores in development. On macOS the Rust toolchain is + Homebrew's keg-only `rustup` (`export PATH=/opt/homebrew/opt/rustup/bin:$PATH`). - Mute before playback tests (`__kaleido.useSettings.getState().set('volume', 0)`). Playback changes real Plex progress and track selections; restore them. ## Releases -Built and published locally (CI only validates). In short: bump the version in -`package.json`, `src-tauri/Cargo.toml`, `src-tauri/tauri.conf.json` (+ lockfile), add a -`CHANGELOG.md` section, `.\scripts\build.ps1`, commit + tag `vX.Y.Z` + push, -`node scripts/publish-release.mjs X.Y.Z [--prerelease]`, then -`node scripts/update-manifest.mjs X.Y.Z ` and commit/push -`updates/latest.json`. Full checklist: `docs/development.md` → Releases. Only push or +Built and published locally, Windows and macOS each on their own machine, into one +release (CI only validates). In short: bump the version in `package.json`, +`src-tauri/Cargo.toml`, `src-tauri/tauri.conf.json` (+ lockfile), add a `CHANGELOG.md` +section, commit + tag `vX.Y.Z` + push; on each OS build (`.\scripts\build.ps1` / +`sh scripts/build.sh`) and `node scripts/publish-release.mjs X.Y.Z [--prerelease]`; then +`node scripts/update-manifest.mjs X.Y.Z` and commit/push `updates/latest.json`. Full checklist: `docs/development.md` → Releases. Only push or publish when the user asks. `FORGEJO_TOKEN` lives in the ignored `.env`. See `docs/architecture.md` and `docs/development.md`. diff --git a/README.md b/README.md index 65ea395..198e1d8 100644 --- a/README.md +++ b/README.md @@ -4,9 +4,10 @@ A cinematic Plex client for the desktop, built in the same artwork-led style as [Kaleido for Android TV](https://git.elijahkuntz.com/Elijah/Kaleido), and designed for mouse and keyboard. -Windows is supported today. The repository is structured for Windows, macOS and Linux: -the interface and nearly all of the native core are shared, and each platform's -differences live in one place (see [Architecture](docs/architecture.md)). +Kaleido runs on Windows and macOS (Apple silicon) with the same interface and features; +each release carries both, and installed copies update themselves. The interface and +nearly all of the native core are shared, and each platform's differences live in one +place (see [Architecture](docs/architecture.md)). Linux builds browse but don't play yet. ## What's in the app @@ -61,18 +62,20 @@ differences live in one place (see [Architecture](docs/architecture.md)). | Browsing | | Player | | | --- | --- | --- | --- | -| Ctrl+K | Search | Space / K | Play/pause | +| Ctrl+K (⌘K) | Search | Space / K | Play/pause | | Arrow keys | Move between titles | ← / → | Seek (Shift: 1 min) | | Enter / Space | Open / play | ↑ / ↓, wheel | Volume | | Menu or Shift+F10 | Title actions | F, double-click | Full screen | -| Alt+← / mouse back | Back | C | Next subtitle | +| Alt+← (⌘[) / mouse back | Back | C | Next subtitle | | / | Focus search | Shift+N | Next episode | -| F11 | Full screen | Esc | Exit full screen, then player | +| F11 (⌃⌘F) | Full screen | Esc | Exit full screen, then player | + +Keys in brackets are the macOS equivalents. ## Build from source -Requirements: Node 22+, Rust (stable), and on Windows the Visual Studio C++ build tools -and 7-Zip. +Requirements: Node 22+, Rust (stable); on Windows the Visual Studio C++ build tools and +7-Zip, on macOS the Xcode command line tools and Homebrew. ```powershell npm ci @@ -81,6 +84,13 @@ npm run tauri dev # development app .\scripts\build.ps1 # signed release installer (NSIS) ``` +```bash +npm ci +sh scripts/fetch-libmpv.sh # libmpv and its libraries into vendor/mpv/macos +npm run tauri dev # development app +sh scripts/build.sh # .app, .dmg and the signed update archive +``` + During development the app signs in automatically from an ignored `.env` in the repository root (`PLEX_SERVER_URL`, `PLEX_TOKEN`). Release builds never read it. `npm run dev` serves the interface alone in a browser for UI work (no playback or diff --git a/docs/architecture.md b/docs/architecture.md index bf61031..3deb7b4 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -35,21 +35,34 @@ updates/latest.json Signed update feed for every platform `src-tauri/src/platform/mod.rs` selects one of `windows.rs`, `macos.rs` or `linux.rs`. Each exposes the same items: -| Item | Windows implementation | -| --- | --- | -| `VideoSurface` | mpv renders with `d3d11-output-mode=composition`; its swapchain (`display-swapchain`) is set as the content of a DirectComposition visual targeted at the window with `topmost = false`, i.e. behind the web view's child windows. For the miniplayer the visual is offset and mpv's composition size shrunk to a corner rectangle (`player_rect`). | -| `MPV_LIBRARIES` | `libmpv-2.dll` | -| `hold_awake` | `SetThreadExecutionState` while video plays | +| Item | Windows | macOS | +| --- | --- | --- | +| `VideoSurface` | mpv renders with `d3d11-output-mode=composition`; its swapchain (`display-swapchain`) is set as the content of a DirectComposition visual targeted at the window with `topmost = false`, i.e. behind the web view's child windows. For the miniplayer the visual is offset and mpv's composition size shrunk to a corner rectangle (`player_rect`). | mpv's render API (`vo=libmpv`, OpenGL) draws into a `CAOpenGLLayer` hosted by a view inserted beneath the WKWebView, whose background is turned off (`drawsBackground`). `start` creates the render context once mpv is initialized; a render thread redraws the layer whenever mpv reports a new frame. For the miniplayer the view is moved to the corner rectangle. | +| `MPV_LIBRARIES` | `libmpv-2.dll` | `libmpv.2.dylib` (in `Contents/Frameworks` with the libraries it links) | +| `hold_awake` | `SetThreadExecutionState` | an IOKit `PreventUserIdleDisplaySleep` assertion | +| Window buttons | drawn by the page (`WindowControls`) | the native traffic lights (`titleBarStyle: Overlay`, placed on the top bar's centre line); `set_window_buttons` hides them with the player's controls | +| `device_name` | `COMPUTERNAME` | the computer name from Sharing settings | -macOS and Linux currently provide stubs for `VideoSurface` (browsing, downloads, -settings and updates work; playback reports that it is unavailable). To add playback -there, render through mpv's render API into a layer beneath the web view and implement -the same methods (`set_rect` places the video in part of the window for the miniplayer). Per-OS bundling (libmpv, targets, dependencies) lives in -`tauri.macos.conf.json` and `tauri.linux.conf.json`. Credentials use the platform's -keychain through the `keyring` crate with per-OS features in `Cargo.toml`. +Linux provides stubs for `VideoSurface` (browsing, downloads, settings and updates +work; playback reports that it is unavailable); the macOS approach (render API beneath +the web view) applies there with an OpenGL surface under WebKitGTK. Per-OS bundling +(libmpv, targets, window style) lives in `tauri..conf.json`. Credentials use the +platform's keychain through the `keyring` crate with per-OS features in `Cargo.toml`; +macOS debug builds keep them in a private file instead, because each unsigned rebuild +would make the Keychain ask again. -On Windows the main window is created transparent and the page background turns -transparent only while video is visible (`html.video-active`), so browsing is opaque. +The page background turns transparent only while video is visible +(`html.video-active`), so browsing is opaque. The page knows its OS synchronously +(`hostOS` in `platform/native.ts`, from the web view's user agent) and tags the root +element (`html.os-macos`) for the few styles that differ, such as room for the traffic +lights. + +HDR passthrough (`target-colorspace-hint`) works differently on each OS. On Windows mpv +switches its swapchain's colour space itself. On macOS the surface watches +`video-params/gamma`: for PQ or HLG video it has mpv output PQ in BT.2020 +(`target-trc`, `target-prim`) into the 16-bit float framebuffer and turns on the layer's +extended dynamic range with the BT.2100 PQ colour space, so macOS maps the picture +into the display's HDR headroom; SDR video returns both to their defaults. ## Interface @@ -85,4 +98,5 @@ transparent only while video is visible (`html.video-active`), so browsing is op cached in the app cache folder (`gpu-shader-cache-dir`), so a slow first Direct3D compile happens once per shader set, mpv version and GPU driver. - **Updates**: `app/updater.ts` checks the signed feed on start; installs need the - user's confirmation and then relaunch. + user's confirmation and then relaunch. One release carries every platform's build and + the feed lists each of them (`windows-x86_64`, `darwin-aarch64`). diff --git a/docs/development.md b/docs/development.md index 3719501..e7a98a0 100644 --- a/docs/development.md +++ b/docs/development.md @@ -11,6 +11,22 @@ debug builds and the Vite dev server. Never commit or print it. 5. `npm run tauri dev` +## Setup (macOS) + +1. Node 22+, Rust stable (`brew install rustup && rustup default stable`), the Xcode + command line tools and Homebrew. +2. `npm ci` +3. `sh scripts/fetch-libmpv.sh` installs Homebrew's `mpv` and copies libmpv with every + library it links into `vendor/mpv/macos`, rewritten to find each other there + (`@loader_path`) and signed, so the bundle doesn't depend on Homebrew. Homebrew + builds for the macOS it runs on, so the app's minimum macOS is that of the build + machine (`scripts/build.sh` sets it from the libraries). +4. `.env` as on Windows, then `npm run tauri dev`. + +Debug builds on macOS keep the Plex token in `dev-secrets.json` in the app data folder +rather than the Keychain: every rebuild is a new unsigned binary, which the Keychain +would ask about again. Release builds always use the Keychain. + The interface alone runs in a browser with `npm run dev` (port 1420), which is handy for layout work; playback, downloads and native dialogs need the desktop app. In development builds the stores are available as `window.__kaleido` for debugging. @@ -39,43 +55,67 @@ and copy back only the files already in `src-tauri/icons` (the Android and iOS s ## Releases -Releases are built and published from this Windows machine. CI only validates; it never -builds installers on push (there are no Windows/macOS runners). Versions follow SemVer; -betas use a prerelease suffix (`0.1.0-beta.1`) and are published as pre-releases. +Releases are built and published locally: Windows on the Windows machine, macOS on the +Mac. CI only validates; it never builds installers on push (there are no Windows/macOS +runners). Versions follow SemVer; betas use a prerelease suffix (`0.1.0-beta.1`) and are +published as pre-releases. **Each release carries both platforms**, and the update feed +is written only once both are uploaded. Checklist for version `X.Y.Z` (run from the repository root): -1. **Version**: set `X.Y.Z` in `package.json`, `src-tauri/Cargo.toml` and - `src-tauri/tauri.conf.json`, then `npm install --package-lock-only` to update +1. **Version** (either machine): set `X.Y.Z` in `package.json`, `src-tauri/Cargo.toml` + and `src-tauri/tauri.conf.json`, then `npm install --package-lock-only` to update `package-lock.json`. 2. **Changelog**: add a `## X.Y.Z` section at the top of `CHANGELOG.md`. It becomes the release notes and the in-app update notes. 3. **Check**: `npm run typecheck`, `npm test`, `cargo check --manifest-path src-tauri/Cargo.toml`. -4. **Build**: `.\scripts\build.ps1` → `src-tauri/target/release/bundle/nsis/Kaleido_X.Y.Z_x64-setup.exe` - and its `.sig`. The updater key is read from `.tools/updater.key` (ignored; keep it - safe — replacing it breaks in-app updates for existing installs) or from - `TAURI_SIGNING_PRIVATE_KEY`. -5. **Commit and tag**: commit as `Release Kaleido Desktop X.Y.Z`, then +4. **Commit and tag**: commit as `Release Kaleido Desktop X.Y.Z`, then `git tag -a vX.Y.Z -m "Kaleido Desktop X.Y.Z"` and `git push origin main vX.Y.Z` - (SSH remote `origin`, already configured). -6. **Publish**: `node scripts/publish-release.mjs X.Y.Z` (add `--prerelease` for betas) - creates the Forgejo release with the notes from `CHANGELOG.md` and uploads the - installer and `.sig`. It reads `FORGEJO_TOKEN` (repository read/write) from the - environment or the ignored `.env`, and never prints it. Re-running it replaces the - assets. -7. **Update feed**: `node scripts/update-manifest.mjs X.Y.Z https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/releases/download/vX.Y.Z` - rewrites `updates/latest.json`; commit it (`Publish the X.Y.Z update feed`) and push. - Installed copies offer the update on their next start. Publish the feed only after - the release assets exist, or clients would be sent to a missing file. -8. **Verify**: download the installer from the release URL and compare its SHA-256 with - the local file; `https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/raw/branch/main/updates/latest.json` - should show the new version; CI on Actions should finish green. + (SSH remote `origin`, already configured). Pull it on the other machine. +5. **Build and publish on Windows**: `.\scripts\build.ps1` → + `src-tauri/target/release/bundle/nsis/Kaleido_X.Y.Z_x64-setup.exe` and its `.sig`; + then `node scripts/publish-release.mjs X.Y.Z` (add `--prerelease` for betas) creates + the Forgejo release with the notes from `CHANGELOG.md` and uploads them. +6. **Build and publish on macOS**: `sh scripts/build.sh` → `bundle/dmg/Kaleido_X.Y.Z_aarch64.dmg` + (first installs) and `bundle/macos/Kaleido_X.Y.Z_aarch64.app.tar.gz` with its `.sig` + (updates); then `node scripts/publish-release.mjs X.Y.Z [--prerelease]` adds them to + the same release. The order of 5 and 6 doesn't matter. +7. **Update feed** (either machine): `node scripts/update-manifest.mjs X.Y.Z` reads the + release's assets (downloading each `.sig`) and rewrites `updates/latest.json`; commit + it (`Publish the X.Y.Z update feed`) and push. Installed copies offer the update on + their next start. The script refuses while a platform's build is missing from the + release, so neither OS is ever pointed at an older build; `--allow-missing` publishes + the feed without it (that OS then sees no update until the feed is regenerated). +8. **Verify**: download each artifact from the release and compare its SHA-256 with the + local file; `https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/raw/branch/main/updates/latest.json` + should list both platforms at the new version; CI on Actions should finish green. -The installer is per user (`%LOCALAPPDATA%\Kaleido`, no admin) and is not code-signed, -so SmartScreen warns on first run. In-app updates run it in passive mode and relaunch. +Both publishing scripts read `FORGEJO_TOKEN` (repository read/write) from the +environment or the ignored `.env`, and never print it. Re-running `publish-release.mjs` +replaces that machine's assets. -For macOS and Linux, build on those systems (`scripts/fetch-libmpv.sh`, then -`npx tauri build`) and merge their bundles into the same feed with `KALEIDO_BUNDLES`. -`.forgejo/workflows/release.yml` validates every push and tag; +**Update signing**: both build scripts sign update artifacts with the updater key from +`.tools/updater.key` (ignored; keep it safe — replacing it breaks in-app updates for +existing installs) or `TAURI_SIGNING_PRIVATE_KEY`. Both build machines need the same +key in `.tools/`; without it a build has no update archive. + +**Windows** installs per user (`%LOCALAPPDATA%\Kaleido`, no admin) and is not +code-signed, so SmartScreen warns on first run. In-app updates run the installer in +passive mode and relaunch. + +**macOS** builds are signed with a self-signed certificate, "Kaleido Self-Signed", in +the build Mac's login keychain (backed up, with its password, as +`.tools/macos-signing.p12` and `.tools/macos-signing.password`). A lasting signature +keeps the app's identity across updates, so the Keychain keeps trusting it with the +Plex token; ad hoc signatures change with every build and would make macOS ask again +after each update. To build on another Mac, import the backup: +`security import .tools/macos-signing.p12 -k ~/Library/Keychains/login.keychain-db -P "$(cat .tools/macos-signing.password)" -T /usr/bin/codesign`. +The app isn't notarized, so the first launch of a downloaded `.dmg` needs +System Settings → Privacy & Security → Open Anyway (or right-click → Open); in-app +updates aren't quarantined and install without that. Building runs Finder through +AppleScript to lay out the disk image window; set `CI=true` to skip that step. + +Linux can be built with `sh scripts/fetch-libmpv.sh` and `npx tauri build` but isn't +published. `.forgejo/workflows/release.yml` validates every push and tag; `.forgejo/workflows/build-installers.yml` can build installers in CI once runners exist for each platform, and only runs when started by hand. diff --git a/scripts/build.sh b/scripts/build.sh new file mode 100644 index 0000000..4fcb158 --- /dev/null +++ b/scripts/build.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env sh +# Builds Kaleido for macOS: the .app, a .dmg for first installs and the signed updater +# archive, renamed Kaleido__.app.tar.gz for the release. +# sh scripts/build.sh # release build +# sh scripts/build.sh --debug # faster unoptimized build +set -eu +root=$(cd "$(dirname "$0")/.." && pwd) +cd "$root" +profile=release +[ "${1:-}" = "--debug" ] && profile=debug + +sh scripts/fetch-libmpv.sh + +# The bundled libraries decide the oldest macOS Kaleido runs on (Homebrew builds them +# for the macOS of the machine that installed them). +minos=$(for f in vendor/mpv/macos/*.dylib; do otool -l "$f" | awk '/LC_BUILD_VERSION/{b=1} b&&/minos/{print $2; b=0}'; done | sort -V | tail -1) + +# Signing with one lasting certificate keeps the app's identity across updates, so the +# Keychain keeps trusting it with the Plex token (ad hoc signatures change every build). +# "Kaleido Self-Signed" lives in the login keychain; .tools/macos-signing.p12 backs it up. +identity=${KALEIDO_SIGNING_IDENTITY:-Kaleido Self-Signed} +if security find-identity -p codesigning | grep -q "\"$identity\""; then + codesign --force --sign "$identity" vendor/mpv/macos/*.dylib 2>/dev/null +else + echo "warning: no \"$identity\" signing certificate; signing ad hoc (the Keychain will ask again after updates)." >&2 + identity=- +fi + +# The updater signing key stays outside git (.tools/), as on Windows. +updater=true +if [ -z "${TAURI_SIGNING_PRIVATE_KEY:-}" ]; then + if [ -f .tools/updater.key ]; then + TAURI_SIGNING_PRIVATE_KEY=$(cat .tools/updater.key) + TAURI_SIGNING_PRIVATE_KEY_PASSWORD=${TAURI_SIGNING_PRIVATE_KEY_PASSWORD:-} + export TAURI_SIGNING_PRIVATE_KEY TAURI_SIGNING_PRIVATE_KEY_PASSWORD + else + echo "warning: no updater signing key (.tools/updater.key); building without update artifacts." >&2 + updater=false + fi +fi +config="{\"bundle\":{\"createUpdaterArtifacts\":$updater,\"macOS\":{\"minimumSystemVersion\":\"$minos\",\"signingIdentity\":\"$identity\"}}}" + +[ -d node_modules ] || npm ci +if [ "$profile" = debug ]; then npx tauri build --debug --config "$config"; else npx tauri build --config "$config"; fi + +version=$(node -p "require('./package.json').version") +arch=$(uname -m | sed 's/arm64/aarch64/; s/x86_64/x64/') +bundle="src-tauri/target/$profile/bundle" +if [ -f "$bundle/macos/Kaleido.app.tar.gz" ]; then + cp "$bundle/macos/Kaleido.app.tar.gz" "$bundle/macos/Kaleido_${version}_${arch}.app.tar.gz" + cp "$bundle/macos/Kaleido.app.tar.gz.sig" "$bundle/macos/Kaleido_${version}_${arch}.app.tar.gz.sig" +fi +echo "Built for macOS $minos or later:" +ls -l "$bundle/dmg" "$bundle/macos" diff --git a/scripts/fetch-libmpv.sh b/scripts/fetch-libmpv.sh index da866db..da68416 100644 --- a/scripts/fetch-libmpv.sh +++ b/scripts/fetch-libmpv.sh @@ -1,14 +1,39 @@ #!/usr/bin/env sh -# macOS: copies Homebrew's libmpv into vendor/mpv/macos for bundling. +# macOS: copies Homebrew's libmpv and every library it links (ffmpeg, libplacebo, ...) +# into vendor/mpv/macos, pointing them at each other with @loader_path so the folder is +# self-contained; the bundle ships it as Contents/Frameworks. # Linux: libmpv comes from the system package (libmpv2); nothing to copy. set -eu root=$(cd "$(dirname "$0")/.." && pwd) case "$(uname -s)" in Darwin) + out="$root/vendor/mpv/macos" + if [ -f "$out/libmpv.2.dylib" ] && [ "${1:-}" != "--force" ]; then + echo "libmpv already in vendor/mpv/macos (pass --force to refresh)" + exit 0 + fi brew list mpv >/dev/null 2>&1 || brew install mpv - mkdir -p "$root/vendor/mpv/macos" - cp "$(brew --prefix mpv)/lib/libmpv.2.dylib" "$root/vendor/mpv/macos/" - echo "libmpv copied to vendor/mpv/macos" ;; + command -v dylibbundler >/dev/null 2>&1 || brew install dylibbundler + rm -rf "$out" && mkdir -p "$out" + cp "$(brew --prefix mpv)/lib/libmpv.2.dylib" "$out/" + chmod u+w "$out/libmpv.2.dylib" + install_name_tool -id @loader_path/libmpv.2.dylib "$out/libmpv.2.dylib" + # -of: overwrite, -b: bundle dependencies, -x: fix this file, -d: where they go, + # -p: how they're referenced, -s: also search Homebrew's lib folder for @rpath names. + dylibbundler -of -b -x "$out/libmpv.2.dylib" -d "$out" -p @loader_path/ -s "$(brew --prefix)/lib" >/dev/null + for f in "$out"/*.dylib; do + # dylibbundler can repeat an rpath, which dyld refuses to load; keep one of each. + for rpath in $(otool -l "$f" | awk '/cmd LC_RPATH/{getline; getline; print $2}' | sort | uniq -d); do + while [ "$(otool -l "$f" | awk '/cmd LC_RPATH/{getline; getline; print $2}' | grep -cx "$rpath")" -gt 1 ]; do + install_name_tool -delete_rpath "$rpath" "$f" 2>/dev/null + done + done + # Rewriting load commands invalidates signatures; Apple silicon refuses unsigned code. + codesign --force --sign - "$f" 2>/dev/null + done + # Homebrew builds for the macOS it runs on: the oldest macOS these libraries load on. + minos=$(for f in "$out"/*.dylib; do otool -l "$f" | awk '/LC_BUILD_VERSION/{b=1} b&&/minos/{print $2; b=0}'; done | sort -V | tail -1) + echo "libmpv and $(($(ls "$out" | wc -l) - 1)) libraries copied to vendor/mpv/macos (need macOS $minos or later)" ;; Linux) echo "Install libmpv from your distribution (e.g. apt install libmpv2 libmpv-dev)." ;; *) echo "Use scripts/fetch-libmpv.ps1 on Windows." ;; diff --git a/scripts/publish-release.mjs b/scripts/publish-release.mjs index 111b094..3e5f5e8 100644 --- a/scripts/publish-release.mjs +++ b/scripts/publish-release.mjs @@ -1,11 +1,12 @@ -// Creates (or reuses) a Forgejo release for a tag and uploads the Windows installer and -// its updater signature. Reads FORGEJO_TOKEN from the environment or the ignored .env. +// Creates (or reuses) a Forgejo release for a tag and uploads this machine's build of it: +// the Windows installer, or the macOS disk image and updater archive, each with its +// updater signature. Run it on each OS after building; both land in the same release. +// Reads FORGEJO_TOKEN from the environment or the ignored .env. // Usage: node scripts/publish-release.mjs [--prerelease] import fs from 'node:fs'; import path from 'node:path'; +import { api, bundleDir, releaseNotes, token } from './release-common.mjs'; -const API = 'https://git.elijahkuntz.com/api/v1/repos/Elijah/Kaleido-Desktop'; -const root = path.resolve(import.meta.dirname, '..'); const version = process.argv[2]; const prerelease = process.argv.includes('--prerelease'); if (!version) { @@ -13,43 +14,38 @@ if (!version) { process.exit(1); } -let token = process.env.FORGEJO_TOKEN; -if (!token && fs.existsSync(path.join(root, '.env'))) { - token = fs.readFileSync(path.join(root, '.env'), 'utf8').match(/^FORGEJO_TOKEN=(.*)$/m)?.[1]?.trim().replace(/^"|"$/g, ''); +/** This version's release files as built on this OS (scripts/build.ps1 or scripts/build.sh). */ +function builtFiles() { + if (process.platform === 'win32') { + const dir = path.join(bundleDir, 'nsis'); + return [`Kaleido_${version}_x64-setup.exe`, `Kaleido_${version}_x64-setup.exe.sig`].map((n) => path.join(dir, n)); + } + if (process.platform === 'darwin') { + const arch = process.arch === 'arm64' ? 'aarch64' : 'x64'; + return [ + path.join(bundleDir, 'dmg', `Kaleido_${version}_${arch}.dmg`), + path.join(bundleDir, 'macos', `Kaleido_${version}_${arch}.app.tar.gz`), + path.join(bundleDir, 'macos', `Kaleido_${version}_${arch}.app.tar.gz.sig`), + ]; + } + throw new Error('Publish releases from Windows or macOS.'); } -if (!token) { - console.error('FORGEJO_TOKEN is not set.'); - process.exit(1); -} -const headers = { Authorization: `token ${token}`, Accept: 'application/json' }; -async function api(method, url, body) { - const r = await fetch(url.startsWith('http') ? url : API + url, { - method, - headers: body instanceof FormData ? headers : { ...headers, 'Content-Type': 'application/json' }, - body: body === undefined ? undefined : body instanceof FormData ? body : JSON.stringify(body), - }); - const text = await r.text(); - if (!r.ok) throw new Error(`${method} ${url} → ${r.status} ${text.slice(0, 300)}`); - return text ? JSON.parse(text) : null; +token(true); +const files = builtFiles(); +for (const file of files) { + if (!fs.existsSync(file)) throw new Error(`Missing ${file}; build this version first.`); } const tag = `v${version}`; -const changelog = fs.readFileSync(path.join(root, 'CHANGELOG.md'), 'utf8'); -const section = changelog.split(/^## /m).find((s) => s.startsWith(version)); -const notes = section ? section.slice(version.length).trim() : ''; - let release = await api('GET', `/releases/tags/${tag}`).catch(() => null); if (!release) { - release = await api('POST', '/releases', { tag_name: tag, name: `Kaleido Desktop ${version}`, body: notes, prerelease, draft: false }); + release = await api('POST', '/releases', { tag_name: tag, name: `Kaleido Desktop ${version}`, body: releaseNotes(version), prerelease, draft: false }); console.log(`Created release ${release.name}`); } else console.log(`Using existing release ${release.name}`); -const dir = path.join(root, 'src-tauri/target/release/bundle/nsis'); -const files = [`Kaleido_${version}_x64-setup.exe`, `Kaleido_${version}_x64-setup.exe.sig`]; -for (const name of files) { - const file = path.join(dir, name); - if (!fs.existsSync(file)) throw new Error(`Missing ${file}; run scripts/build.ps1 first.`); +for (const file of files) { + const name = path.basename(file); const existing = release.assets?.find((a) => a.name === name); if (existing) await api('DELETE', `/releases/${release.id}/assets/${existing.id}`); const form = new FormData(); diff --git a/scripts/release-common.mjs b/scripts/release-common.mjs new file mode 100644 index 0000000..f20824b --- /dev/null +++ b/scripts/release-common.mjs @@ -0,0 +1,49 @@ +// Shared by the release scripts: the Forgejo API (FORGEJO_TOKEN from the environment or +// the ignored .env, never printed), release notes and the bundle folder. +import fs from 'node:fs'; +import path from 'node:path'; + +export const API = 'https://git.elijahkuntz.com/api/v1/repos/Elijah/Kaleido-Desktop'; +export const root = path.resolve(import.meta.dirname, '..'); +export const bundleDir = path.join(root, 'src-tauri/target/release/bundle'); + +/** FORGEJO_TOKEN; reads of a public repository work without it, uploads don't. */ +export function token(required = false) { + let t = process.env.FORGEJO_TOKEN; + if (!t && fs.existsSync(path.join(root, '.env'))) { + t = fs.readFileSync(path.join(root, '.env'), 'utf8').match(/^FORGEJO_TOKEN=(.*)$/m)?.[1]?.trim().replace(/^"|"$/g, ''); + } + if (!t && required) { + console.error('FORGEJO_TOKEN is not set.'); + process.exit(1); + } + return t; +} + +const auth = () => (token() ? { Authorization: `token ${token()}` } : {}); + +export async function api(method, url, body) { + const headers = { ...auth(), Accept: 'application/json' }; + const r = await fetch(url.startsWith('http') ? url : API + url, { + method, + headers: body instanceof FormData ? headers : { ...headers, 'Content-Type': 'application/json' }, + body: body === undefined ? undefined : body instanceof FormData ? body : JSON.stringify(body), + }); + const text = await r.text(); + if (!r.ok) throw new Error(`${method} ${url} → ${r.status} ${text.slice(0, 300)}`); + return text ? JSON.parse(text) : null; +} + +/** Downloads a release asset's text (an updater signature). */ +export async function download(url) { + const r = await fetch(url, { headers: auth() }); + if (!r.ok) throw new Error(`GET ${url} → ${r.status}`); + return r.text(); +} + +/** The version's section of CHANGELOG.md. */ +export function releaseNotes(version) { + const changelog = fs.readFileSync(path.join(root, 'CHANGELOG.md'), 'utf8'); + const section = changelog.split(/^## /m).find((s) => s.startsWith(version)); + return section ? section.slice(version.length).trim() : ''; +} diff --git a/scripts/update-manifest.mjs b/scripts/update-manifest.mjs index 8e7f20c..c1cf28e 100644 --- a/scripts/update-manifest.mjs +++ b/scripts/update-manifest.mjs @@ -1,53 +1,56 @@ -// Writes updates/latest.json, the feed Kaleido's updater reads, from built bundles. -// Usage: node scripts/update-manifest.mjs [notesFile] -// Notes come from the version's CHANGELOG.md section unless a notes file is given. -// Each platform's signed artifact (and its .sig) must be in src-tauri/target/release/bundle, -// or pass several bundle folders via KALEIDO_BUNDLES (path;path) when collecting CI outputs. +// Writes updates/latest.json, the feed Kaleido's updater reads, from a published release: +// each platform's updater artifact and signature are taken from the release's assets, so +// the feed only ever points at this version's files, whichever machine runs it. +// Usage: node scripts/update-manifest.mjs [--allow-missing] [notesFile] +// Every platform in PLATFORMS must be in the release (publish from each OS first); +// --allow-missing writes the feed anyway, leaving the missing platforms out of it, so +// their installs simply see no update until the feed is regenerated. import fs from 'node:fs'; import path from 'node:path'; +import { api, download, releaseNotes, root } from './release-common.mjs'; -const [version, baseUrl, notesFile] = process.argv.slice(2); -if (!version || !baseUrl) { - console.error('usage: node scripts/update-manifest.mjs [notesFile]'); +const args = process.argv.slice(2); +const allowMissing = args.includes('--allow-missing'); +const [version, notesFile] = args.filter((a) => !a.startsWith('--')); +if (!version) { + console.error('usage: node scripts/update-manifest.mjs [--allow-missing] [notesFile]'); process.exit(1); } -const root = path.resolve(import.meta.dirname, '..'); -const bundles = (process.env.KALEIDO_BUNDLES ?? path.join(root, 'src-tauri/target/release/bundle')).split(';'); -/** Tauri updater platform keys and the artifact each one installs. */ +/** Tauri updater platform keys and the release asset each one installs. */ const PLATFORMS = [ - { key: 'windows-x86_64', dir: 'nsis', match: /-setup\.exe$/ }, - { key: 'darwin-aarch64', dir: 'macos', match: /aarch64.*\.app\.tar\.gz$/ }, - { key: 'darwin-x86_64', dir: 'macos', match: /x64.*\.app\.tar\.gz$/ }, - { key: 'linux-x86_64', dir: 'appimage', match: /\.AppImage$/ }, + { key: 'windows-x86_64', match: (f) => f === `Kaleido_${version}_x64-setup.exe` }, + { key: 'darwin-aarch64', match: (f) => f === `Kaleido_${version}_aarch64.app.tar.gz` }, ]; -const manifestPath = path.join(root, 'updates/latest.json'); -const manifest = fs.existsSync(manifestPath) ? JSON.parse(fs.readFileSync(manifestPath, 'utf8')) : { platforms: {} }; -manifest.version = version; -// Notes default to this version's section of CHANGELOG.md. -const changelogNotes = () => { - const section = fs.readFileSync(path.join(root, 'CHANGELOG.md'), 'utf8').split(/^## /m).find((x) => x.startsWith(version)); - return section ? section.slice(version.length).trim() : ''; -}; -manifest.notes = notesFile ? fs.readFileSync(notesFile, 'utf8').trim() : changelogNotes(); -manifest.pub_date = new Date().toISOString(); -manifest.platforms ??= {}; +const release = await api('GET', `/releases/tags/v${version}`).catch(() => null); +if (!release) throw new Error(`No release v${version}; publish it with scripts/publish-release.mjs first.`); +const assets = release.assets ?? []; -for (const bundle of bundles) { - for (const p of PLATFORMS) { - const dir = path.join(bundle, p.dir); - if (!fs.existsSync(dir)) continue; - const file = fs.readdirSync(dir).find((f) => p.match.test(f) && f.includes(version)); - if (!file || !fs.existsSync(path.join(dir, `${file}.sig`))) continue; - manifest.platforms[p.key] = { - signature: fs.readFileSync(path.join(dir, `${file}.sig`), 'utf8').trim(), - url: `${baseUrl.replace(/\/$/, '')}/${encodeURIComponent(file)}`, - }; - console.log(`${p.key}: ${file}`); +const platforms = {}; +const missing = []; +for (const p of PLATFORMS) { + const artifact = assets.find((a) => p.match(a.name)); + const sig = artifact && assets.find((a) => a.name === `${artifact.name}.sig`); + if (!artifact || !sig) { + missing.push(p.key); + continue; } + platforms[p.key] = { signature: (await download(sig.browser_download_url)).trim(), url: artifact.browser_download_url }; + console.log(`${p.key}: ${artifact.name}`); } +if (missing.length && !allowMissing) { + console.error(`v${version} has no build for ${missing.join(', ')}. Publish it from that OS, or pass --allow-missing.`); + process.exit(1); +} +if (!Object.keys(platforms).length) throw new Error(`v${version} has no updater artifacts.`); -fs.mkdirSync(path.dirname(manifestPath), { recursive: true }); +const manifest = { + version, + notes: notesFile ? fs.readFileSync(notesFile, 'utf8').trim() : releaseNotes(version), + pub_date: new Date().toISOString(), + platforms, +}; +const manifestPath = path.join(root, 'updates/latest.json'); fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + '\n'); -console.log(`Wrote ${path.relative(root, manifestPath)}`); +console.log(`Wrote ${path.relative(root, manifestPath)}${missing.length ? ` (without ${missing.join(', ')})` : ''}`); diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index f2b45c1..e18b6a1 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -2180,6 +2180,14 @@ dependencies = [ "keyring", "libloading 0.8.9", "log", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-video", + "objc2-foundation", + "objc2-open-gl", + "objc2-quartz-core", "once_cell", "parking_lot", "reqwest 0.12.28", @@ -2605,8 +2613,15 @@ checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" dependencies = [ "bitflags 2.13.2", "block2", + "libc", "objc2", + "objc2-cloud-kit", + "objc2-core-data", "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-image", + "objc2-core-text", + "objc2-core-video", "objc2-foundation", "objc2-quartz-core", ] @@ -2628,6 +2643,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa" dependencies = [ + "bitflags 2.13.2", "objc2", "objc2-foundation", ] @@ -2688,6 +2704,19 @@ dependencies = [ "objc2-core-graphics", ] +[[package]] +name = "objc2-core-video" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-io-surface", +] + [[package]] name = "objc2-encode" version = "4.1.0" @@ -2727,6 +2756,26 @@ dependencies = [ "objc2-core-foundation", ] +[[package]] +name = "objc2-metal" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-open-gl" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ecc7fd7519a189d9ba9ed9de51af81e41d096aea1d08cca59fd9d8c65d8f585" +dependencies = [ + "objc2", +] + [[package]] name = "objc2-osa-kit" version = "0.3.2" @@ -2746,9 +2795,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" dependencies = [ "bitflags 2.13.2", + "block2", + "libc", "objc2", "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-video", "objc2-foundation", + "objc2-metal", + "objc2-open-gl", ] [[package]] diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 4d48089..76a9ff1 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -34,6 +34,14 @@ log = "0.4" # Credentials use each OS's native store: Credential Manager, Keychain, Secret Service. [target.'cfg(target_os = "macos")'.dependencies] keyring = { version = "3", features = ["apple-native"] } +objc2 = "0.6" +objc2-foundation = { version = "0.3", features = ["NSGeometry", "NSString", "NSValue", "NSHost", "NSProcessInfo", "NSKeyValueCoding"] } +objc2-core-foundation = { version = "0.3", default-features = false, features = ["std", "CFDate", "CFString"] } +objc2-app-kit = { version = "0.3", features = ["NSView", "NSWindow", "NSResponder", "NSButton", "NSControl", "NSGraphics"] } +objc2-quartz-core = { version = "0.3", features = ["CALayer", "CAOpenGLLayer", "CATransaction", "CAMediaTiming", "objc2-open-gl", "objc2-core-video", "objc2-core-graphics"] } +objc2-core-graphics = { version = "0.3", default-features = false, features = ["std", "CGColorSpace"] } +objc2-open-gl = { version = "0.3", default-features = false, features = ["std", "CGLTypes", "CGLCurrent"] } +objc2-core-video = { version = "0.3", default-features = false, features = ["std", "CVBase"] } [target.'cfg(target_os = "linux")'.dependencies] keyring = { version = "3", features = ["sync-secret-service", "crypto-rust"] } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index dba919c..4ca19e2 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -44,6 +44,7 @@ pub fn run() { player::player_command, player::player_set, player::player_get, + player::window_buttons, system::secret_get, system::secret_set, system::secret_delete, diff --git a/src-tauri/src/mpv.rs b/src-tauri/src/mpv.rs index 3e9a3f2..9ab9934 100644 --- a/src-tauri/src/mpv.rs +++ b/src-tauri/src/mpv.rs @@ -192,6 +192,21 @@ impl Mpv { } } + /// The raw client handle, for platform code using parts of libmpv this + /// binding doesn't wrap (the render API). + pub fn raw_handle(&self) -> *mut c_void { + self.handle + } + + /// Looks up another libmpv function by name. + /// + /// # Safety + /// `T` must be the function's exact pointer type. + pub unsafe fn symbol(&self, name: &str) -> Option { + let name = CString::new(name).ok()?; + self.api._lib.get::(name.as_bytes_with_nul()).ok().map(|s| *s) + } + fn error(&self, code: c_int) -> String { unsafe { CStr::from_ptr((self.api.error_string)(code)).to_string_lossy().into_owned() } } diff --git a/src-tauri/src/platform/linux.rs b/src-tauri/src/platform/linux.rs index 4841ead..c5bf0a1 100644 --- a/src-tauri/src/platform/linux.rs +++ b/src-tauri/src/platform/linux.rs @@ -1,5 +1,5 @@ //! Linux: render mpv through its render API (OpenGL) beneath the WebKitGTK -//! view, then implement `VideoSurface` here. +//! view, then implement `VideoSurface` here (see macos.rs for the same idea). //! //! Browsing, downloads, settings and updates already work here; only native //! video composition remains to be written. @@ -20,8 +20,11 @@ impl VideoSurface { pub fn mpv_options(&self) -> Vec<(&'static str, String)> { Vec::new() } + pub fn start(&mut self, _: &std::sync::Arc) -> Result<(), String> { + Ok(()) + } pub fn on_property(&mut self, _: &str, _: &serde_json::Value) {} - pub fn show(&mut self, _: bool) {} + pub fn show(&mut self, _: &WebviewWindow, _: bool) {} pub fn fit(&mut self, _: &WebviewWindow, _: Option<&Mpv>) {} pub fn set_rect(&mut self, _: &WebviewWindow, _: Option<&Mpv>, _: Option<(i32, i32, i32, i32)>) {} } @@ -31,6 +34,16 @@ pub fn gpu_names() -> Vec { Vec::new() } +pub fn device_name() -> String { + std::fs::read_to_string("/etc/hostname").map(|h| h.trim().to_string()).ok().filter(|h| !h.is_empty()).unwrap_or_else(|| "Linux PC".into()) +} + +pub fn os_version() -> String { + String::new() +} + +pub fn set_window_buttons(_: &WebviewWindow, _: bool) {} + pub fn hold_awake(rx: std::sync::mpsc::Receiver<()>) { // TODO(Linux): org.freedesktop.ScreenSaver.Inhibit over D-Bus. let _ = rx.recv(); diff --git a/src-tauri/src/platform/macos.rs b/src-tauri/src/platform/macos.rs index 9ff4bf8..d9334f6 100644 --- a/src-tauri/src/platform/macos.rs +++ b/src-tauri/src/platform/macos.rs @@ -1,37 +1,531 @@ -//! macOS: render mpv through its render API (libplacebo) into a CAMetalLayer -//! placed beneath the WKWebView, then implement `VideoSurface` here. +//! macOS: libmpv's render API (OpenGL) draws into a CAOpenGLLayer hosted by a +//! view placed beneath the WKWebView; libmpv names, power assertions, window +//! buttons and host details. //! -//! Browsing, downloads, settings and updates already work here; only native -//! video composition remains to be written. +//! OpenGL is deprecated on macOS but still supported (on Metal); it is the +//! render API libmpv offers, and what IINA and other mpv front ends use. +#![allow(deprecated)] +use std::ffi::{c_char, c_int, c_void, CStr}; +use std::ptr::{self, NonNull}; +use std::sync::mpsc::{sync_channel, Receiver, SyncSender}; +use std::sync::Arc; + +use objc2::rc::Retained; +use objc2::{define_class, msg_send, AllocAnyThread, DefinedClass, MainThreadMarker}; +use objc2_app_kit::{NSAutoresizingMaskOptions, NSView, NSWindow, NSWindowButton, NSWindowOrderingMode}; +use objc2_core_foundation::CFTimeInterval; +use objc2_core_graphics::{kCGColorSpaceITUR_2100_PQ, CGColorSpace}; +use objc2_core_video::CVTimeStamp; +use objc2_foundation::{NSNumber, NSPoint, NSRect, NSSize, NSString}; +use objc2_open_gl::*; +use objc2_quartz_core::{CALayer, CAOpenGLLayer, CATransaction}; +use parking_lot::Mutex; use tauri::{Runtime, WebviewWindow}; use crate::mpv::Mpv; -pub const SURFACE_PROPERTIES: &[&str] = &[]; -pub const MPV_LIBRARIES: &[&str] = &["libmpv.2.dylib", "libmpv.dylib"]; +// —— OpenGL ———————————————————————————————————————————————————————————— -pub struct VideoSurface; +const GL_COLOR_BUFFER_BIT: u32 = 0x4000; +const GL_VIEWPORT: u32 = 0x0BA2; +const GL_DRAW_FRAMEBUFFER_BINDING: u32 = 0x8CA6; +const GL_RGBA16F: c_int = 0x881A; +const RTLD_LAZY: c_int = 0x1; -impl VideoSurface { - pub fn create(_: &WebviewWindow) -> Result { - Err("Video playback is not available on this platform yet.".into()) - } - pub fn mpv_options(&self) -> Vec<(&'static str, String)> { - Vec::new() - } - pub fn on_property(&mut self, _: &str, _: &serde_json::Value) {} - pub fn show(&mut self, _: bool) {} - pub fn fit(&mut self, _: &WebviewWindow, _: Option<&Mpv>) {} - pub fn set_rect(&mut self, _: &WebviewWindow, _: Option<&Mpv>, _: Option<(i32, i32, i32, i32)>) {} +#[link(name = "OpenGL", kind = "framework")] +extern "C" { + fn glGetIntegerv(pname: u32, data: *mut i32); + fn glClearColor(r: f32, g: f32, b: f32, a: f32); + fn glClear(mask: u32); + fn glFlush(); } -/// Not needed yet: the only GPU-specific tier (RTX Video) is Windows-only. +extern "C" { + fn dlopen(path: *const c_char, mode: c_int) -> *mut c_void; + fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void; +} + +/// mpv resolves OpenGL functions through this (`ctx` is OpenGL.framework's handle). +extern "C" fn get_proc_address(ctx: *mut c_void, name: *const c_char) -> *mut c_void { + unsafe { dlsym(ctx, name) } +} + +/// A 3.2 core context; 16-bit float colour (needed for HDR) when the renderer +/// offers it. Returns whether it got float colour. +unsafe fn create_gl_context() -> Result<(CGLContextObj, CGLPixelFormatObj, bool), String> { + let base = [ + CGLPixelFormatAttribute::CGLPFAOpenGLProfile.0, + CGLOpenGLProfile::CGLOGLPVersion_3_2_Core.0, + CGLPixelFormatAttribute::CGLPFAAccelerated.0, + CGLPixelFormatAttribute::CGLPFADoubleBuffer.0, + CGLPixelFormatAttribute::CGLPFAAllowOfflineRenderers.0, + CGLPixelFormatAttribute::CGLPFASupportsAutomaticGraphicsSwitching.0, + ]; + let deep = [CGLPixelFormatAttribute::CGLPFAColorSize.0, 64, CGLPixelFormatAttribute::CGLPFAColorFloat.0]; + for extra in [&deep[..], &[]] { + let mut attrs: Vec = base.iter().chain(extra).map(|&a| CGLPixelFormatAttribute(a)).collect(); + attrs.push(CGLPixelFormatAttribute(0)); + let mut pf: CGLPixelFormatObj = ptr::null_mut(); + let mut count = 0; + CGLChoosePixelFormat(NonNull::new_unchecked(attrs.as_mut_ptr()), NonNull::from(&mut pf), NonNull::from(&mut count)); + if pf.is_null() { + continue; + } + let mut ctx: CGLContextObj = ptr::null_mut(); + CGLCreateContext(pf, ptr::null_mut(), NonNull::from(&mut ctx)); + if !ctx.is_null() { + return Ok((ctx, pf, !extra.is_empty())); + } + CGLReleasePixelFormat(pf); + } + Err("OpenGL is unavailable, so video can't be shown.".into()) +} + +// —— mpv render API ———————————————————————————————————————————————————— + +const RENDER_PARAM_API_TYPE: c_int = 1; +const RENDER_PARAM_OPENGL_INIT_PARAMS: c_int = 2; +const RENDER_PARAM_OPENGL_FBO: c_int = 3; +const RENDER_PARAM_FLIP_Y: c_int = 4; +const RENDER_UPDATE_FRAME: u64 = 1; + +#[repr(C)] +struct RenderParam { + kind: c_int, + data: *mut c_void, +} + +#[repr(C)] +struct OpenGlInitParams { + get_proc_address: extern "C" fn(*mut c_void, *const c_char) -> *mut c_void, + get_proc_address_ctx: *mut c_void, +} + +#[repr(C)] +struct OpenGlFbo { + fbo: c_int, + w: c_int, + h: c_int, + internal_format: c_int, +} + +type RenderCtx = *mut c_void; + +/// An mpv render context and the functions that drive it. Every call happens +/// with the layer's OpenGL context locked and current, as libmpv requires. +struct Render { + ctx: RenderCtx, + render: unsafe extern "C" fn(RenderCtx, *mut RenderParam) -> c_int, + update: unsafe extern "C" fn(RenderCtx) -> u64, + report_swap: unsafe extern "C" fn(RenderCtx), +} + +unsafe impl Send for Render {} +unsafe impl Sync for Render {} + +/// libmpv calls this from its own threads when a frame is ready; it may not +/// call back into libmpv, so it only wakes the render thread. +extern "C" fn on_update(wake: *mut c_void) { + let wake = unsafe { &*(wake as *const SyncSender<()>) }; + let _ = wake.try_send(()); +} + +// —— The video layer ——————————————————————————————————————————————————— + +struct LayerIvars { + cgl: CGLContextObj, + pixel_format: CGLPixelFormatObj, + /// The framebuffer holds 16-bit floats (so mpv needn't dither to 8 bits). + float: bool, + render: Mutex>>, +} + +define_class!( + #[unsafe(super(CAOpenGLLayer, CALayer))] + #[name = "KaleidoVideoLayer"] + #[ivars = LayerIvars] + struct VideoLayer; + + impl VideoLayer { + #[unsafe(method(copyCGLPixelFormatForDisplayMask:))] + fn copy_pixel_format(&self, _mask: u32) -> CGLPixelFormatObj { + unsafe { CGLRetainPixelFormat(self.ivars().pixel_format) } + } + + #[unsafe(method(copyCGLContextForPixelFormat:))] + fn copy_context(&self, _pf: CGLPixelFormatObj) -> CGLContextObj { + unsafe { CGLRetainContext(self.ivars().cgl) } + } + + #[unsafe(method(releaseCGLContext:))] + fn release_context(&self, ctx: CGLContextObj) { + unsafe { CGLReleaseContext(ctx) } + } + + #[unsafe(method(canDrawInCGLContext:pixelFormat:forLayerTime:displayTime:))] + fn can_draw(&self, _ctx: CGLContextObj, _pf: CGLPixelFormatObj, _t: CFTimeInterval, _ts: *const CVTimeStamp) -> bool { + true + } + + #[unsafe(method(drawInCGLContext:pixelFormat:forLayerTime:displayTime:))] + fn draw(&self, ctx: CGLContextObj, _pf: CGLPixelFormatObj, _t: CFTimeInterval, _ts: *const CVTimeStamp) { + let render = self.ivars().render.lock().clone(); + unsafe { + CGLLockContext(ctx); + CGLSetCurrentContext(ctx); + match render { + Some(r) => { + let mut fbo = 0; + let mut viewport = [0i32; 4]; + glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &mut fbo); + glGetIntegerv(GL_VIEWPORT, viewport.as_mut_ptr()); + let mut target = OpenGlFbo { fbo, w: viewport[2], h: viewport[3], internal_format: if self.ivars().float { GL_RGBA16F } else { 0 } }; + let mut flip: c_int = 1; + let mut params = [ + RenderParam { kind: RENDER_PARAM_OPENGL_FBO, data: &mut target as *mut _ as *mut c_void }, + RenderParam { kind: RENDER_PARAM_FLIP_Y, data: &mut flip as *mut _ as *mut c_void }, + RenderParam { kind: 0, data: ptr::null_mut() }, + ]; + (r.render)(r.ctx, params.as_mut_ptr()); + } + None => { + glClearColor(0.0, 0.0, 0.0, 1.0); + glClear(GL_COLOR_BUFFER_BIT); + } + } + glFlush(); + CGLUnlockContext(ctx); + } + } + } +); + +// The layer is drawn from the render thread as well as by Core Animation; +// its mutable state is behind a mutex and the CGL context lock. +unsafe impl Send for VideoLayer {} +unsafe impl Sync for VideoLayer {} + +impl VideoLayer { + fn new(cgl: CGLContextObj, pixel_format: CGLPixelFormatObj, float: bool) -> Retained { + let this = VideoLayer::alloc().set_ivars(LayerIvars { cgl, pixel_format, float, render: Mutex::new(None) }); + let layer: Retained = unsafe { msg_send![super(this), init] }; + layer.setAsynchronous(false); + layer.setNeedsDisplayOnBoundsChange(true); + layer.setOpaque(true); + layer + } +} + +/// Redraws whenever mpv has a new frame. Drawing off the main thread needs an +/// explicit flush for Core Animation to pick the frame up. +fn render_loop(layer: Retained, wake: Receiver<()>) { + let cgl = layer.ivars().cgl; + while wake.recv().is_ok() { + let Some(render) = layer.ivars().render.lock().clone() else { continue }; + let flags = unsafe { + CGLLockContext(cgl); + CGLSetCurrentContext(cgl); + let flags = (render.update)(render.ctx); + CGLUnlockContext(cgl); + flags + }; + if flags & RENDER_UPDATE_FRAME != 0 { + layer.display(); + CATransaction::flush(); + unsafe { + CGLLockContext(cgl); + CGLSetCurrentContext(cgl); + (render.report_swap)(render.ctx); + CGLUnlockContext(cgl); + } + } + } +} + +// —— VideoSurface —————————————————————————————————————————————————————— + +/// The view is only touched on the main thread; the layer is also drawn by the +/// render thread and reconfigured for HDR inside explicit transactions. +struct Ui { + view: Retained, + layer: Retained, +} + +unsafe impl Send for Ui {} +unsafe impl Sync for Ui {} + +pub struct VideoSurface { + ui: Arc, + wake: &'static SyncSender<()>, + wake_rx: Option>, + /// Where the video is drawn, in physical pixels; `None` fills the window. + rect: Option<(i32, i32, i32, i32)>, + mpv: Option>, + /// HDR passthrough is on (the `target-colorspace-hint` option, as on Windows). + passthrough: bool, + /// The layer is showing HDR in extended dynamic range. + edr: bool, +} + +/// Runs `f` on the main thread with the window's web view and waits for it. +fn on_main( + window: &WebviewWindow, + f: impl FnOnce(&NSView, &NSWindow) -> T + Send + 'static, +) -> Result { + let (tx, rx) = std::sync::mpsc::channel(); + window + .with_webview(move |webview| unsafe { + let view = &*(webview.inner() as *const NSView); + let window = &*(webview.ns_window() as *const NSWindow); + let _ = tx.send(f(view, window)); + }) + .map_err(|e| e.to_string())?; + rx.recv().map_err(|e| e.to_string()) +} + +/// Places the video view: the whole web view, or a rectangle of it given in +/// physical pixels from the top left (the web page's coordinates). +fn place(ui: &Ui, webview: &NSView, window: &NSWindow, rect: Option<(i32, i32, i32, i32)>) { + let bounds = webview.frame(); + let scale = window.backingScaleFactor(); + let frame = match rect { + None => bounds, + Some((x, y, w, h)) => { + let (x, y, w, h) = (x as f64 / scale, y as f64 / scale, (w.max(16)) as f64 / scale, (h.max(16)) as f64 / scale); + let flipped = unsafe { webview.superview() }.is_some_and(|s| s.isFlipped()); + let top = if flipped { bounds.origin.y + y } else { bounds.origin.y + bounds.size.height - y - h }; + NSRect::new(NSPoint::new(bounds.origin.x + x, top), NSSize::new(w, h)) + } + }; + ui.view.setFrame(frame); + ui.view.setAutoresizingMask(if rect.is_none() { + NSAutoresizingMaskOptions::ViewWidthSizable | NSAutoresizingMaskOptions::ViewHeightSizable + } else { + NSAutoresizingMaskOptions::ViewNotSizable + }); + if ui.layer.contentsScale() != scale { + ui.layer.setContentsScale(scale); + } +} + +impl VideoSurface { + pub fn create(window: &WebviewWindow) -> Result { + let (cgl, pixel_format, float) = unsafe { create_gl_context()? }; + let layer = VideoLayer::new(cgl, pixel_format, float); + let ui = on_main(window, move |webview, window| unsafe { + let view = NSView::initWithFrame(MainThreadMarker::new_unchecked().alloc(), webview.frame()); + // Layer-hosting: set the layer before asking for one. + view.setLayer(Some(&layer)); + view.setWantsLayer(true); + view.setHidden(true); + // Let the video show through wherever the page is transparent. + let no = NSNumber::new_bool(false); + let _: () = msg_send![webview, setValue: &*no, forKey: &*NSString::from_str("drawsBackground")]; + if let Some(parent) = webview.superview() { + parent.addSubview_positioned_relativeTo(&view, NSWindowOrderingMode::Below, Some(webview)); + } + let ui = Ui { view, layer }; + place(&ui, webview, window, None); + ui + })?; + let (wake, wake_rx) = sync_channel::<()>(1); + Ok(VideoSurface { + ui: Arc::new(ui), + wake: Box::leak(Box::new(wake)), + wake_rx: Some(wake_rx), + rect: None, + mpv: None, + passthrough: false, + edr: false, + }) + } + + /// mpv renders through the render API (`vo=libmpv`). Its window is forced + /// open only once the render context exists (`start`). + pub fn mpv_options(&self) -> Vec<(&'static str, String)> { + vec![("vo", "libmpv".into()), ("force-window", "no".into())] + } + + /// Creates mpv's render context on the layer's OpenGL context and starts + /// the render thread. Runs once, after `mpv_initialize`. + pub fn start(&mut self, mpv: &Arc) -> Result<(), String> { + let Some(wake_rx) = self.wake_rx.take() else { return Ok(()) }; + let hint = mpv.get_property("target-colorspace-hint").unwrap_or_default(); + self.passthrough = (hint == serde_json::Value::Bool(true) || hint == "yes") && self.ui.layer.ivars().float; + self.mpv = Some(mpv.clone()); + type Create = unsafe extern "C" fn(*mut RenderCtx, *mut c_void, *mut RenderParam) -> c_int; + type SetCallback = unsafe extern "C" fn(RenderCtx, extern "C" fn(*mut c_void), *mut c_void); + unsafe { + let missing = |name: &str| format!("libmpv is missing {name}"); + let create: Create = mpv.symbol("mpv_render_context_create").ok_or_else(|| missing("mpv_render_context_create"))?; + let set_callback: SetCallback = mpv.symbol("mpv_render_context_set_update_callback").ok_or_else(|| missing("the render API"))?; + let render = mpv.symbol("mpv_render_context_render").ok_or_else(|| missing("the render API"))?; + let update = mpv.symbol("mpv_render_context_update").ok_or_else(|| missing("the render API"))?; + let report_swap = mpv.symbol("mpv_render_context_report_swap").ok_or_else(|| missing("the render API"))?; + + let gl = dlopen(c"/System/Library/Frameworks/OpenGL.framework/OpenGL".as_ptr(), RTLD_LAZY); + let mut init = OpenGlInitParams { get_proc_address, get_proc_address_ctx: gl }; + let mut params = [ + RenderParam { kind: RENDER_PARAM_API_TYPE, data: c"opengl".as_ptr() as *mut c_void }, + RenderParam { kind: RENDER_PARAM_OPENGL_INIT_PARAMS, data: &mut init as *mut _ as *mut c_void }, + RenderParam { kind: 0, data: ptr::null_mut() }, + ]; + let cgl = self.ui.layer.ivars().cgl; + let mut ctx: RenderCtx = ptr::null_mut(); + CGLLockContext(cgl); + CGLSetCurrentContext(cgl); + let code = create(&mut ctx, mpv.raw_handle(), params.as_mut_ptr()); + CGLUnlockContext(cgl); + if code < 0 || ctx.is_null() { + return Err(format!("The video renderer couldn't start ({code}).")); + } + set_callback(ctx, on_update, self.wake as *const SyncSender<()> as *mut c_void); + *self.ui.layer.ivars().render.lock() = Some(Arc::new(Render { ctx, render, update, report_swap })); + } + let layer = self.ui.layer.clone(); + std::thread::Builder::new() + .name("mpv-render".into()) + .spawn(move || render_loop(layer, wake_rx)) + .map_err(|e| e.to_string())?; + mpv.set_property("force-window", &serde_json::Value::Bool(true)) + } + + /// HDR passthrough: for PQ or HLG video, mpv outputs PQ (BT.2020) instead of + /// tone-mapping to SDR, and the layer shows it in extended dynamic range, so + /// macOS maps it to the display's HDR headroom. SDR video uses the defaults. + pub fn on_property(&mut self, name: &str, value: &serde_json::Value) { + if name != "video-params/gamma" { + return; + } + let edr = self.passthrough && matches!(value.as_str(), Some("pq" | "hlg")); + if edr == self.edr { + return; + } + self.edr = edr; + if let Some(mpv) = &self.mpv { + let target = |v: &str| serde_json::Value::String(v.into()); + let (trc, prim) = if edr { ("pq", "bt.2020") } else { ("auto", "auto") }; + let _ = mpv.set_property("target-trc", &target(trc)); + let _ = mpv.set_property("target-prim", &target(prim)); + } + // Layer properties may change off the main thread inside a transaction. + let layer = &self.ui.layer; + CATransaction::begin(); + layer.setWantsExtendedDynamicRangeContent(edr); + let pq = if edr { CGColorSpace::with_name(Some(unsafe { kCGColorSpaceITUR_2100_PQ })) } else { None }; + layer.setColorspace(pq.as_deref()); + CATransaction::commit(); + } + + pub fn show(&mut self, window: &WebviewWindow, visible: bool) { + let ui = self.ui.clone(); + let _ = window.run_on_main_thread(move || { + ui.view.setHidden(!visible); + if visible { + ui.layer.setNeedsDisplay(); + } + }); + } + + /// Keeps the video view matched to the web view, or to the miniplayer + /// rectangle when one is set. + pub fn fit(&mut self, window: &WebviewWindow, _: Option<&Mpv>) { + let ui = self.ui.clone(); + let rect = self.rect; + let _ = window.with_webview(move |webview| unsafe { + let view = &*(webview.inner() as *const NSView); + let window = &*(webview.ns_window() as *const NSWindow); + place(&ui, view, window, rect); + }); + } + + pub fn set_rect(&mut self, window: &WebviewWindow, mpv: Option<&Mpv>, rect: Option<(i32, i32, i32, i32)>) { + self.rect = rect; + self.fit(window, mpv); + } +} + +/// mpv properties the surface needs to observe. +pub const SURFACE_PROPERTIES: &[&str] = &["video-params/gamma"]; + +/// File names libmpv may have on this platform. +pub const MPV_LIBRARIES: &[&str] = &["libmpv.2.dylib", "libmpv.dylib"]; + +/// Not needed: the only GPU-specific tier (RTX Video) is Windows-only. pub fn gpu_names() -> Vec { Vec::new() } -pub fn hold_awake(rx: std::sync::mpsc::Receiver<()>) { - // TODO(macOS): IOPMAssertionCreateWithName(PreventUserIdleDisplaySleep). - let _ = rx.recv(); +/// The Mac's name as set in System Settings → General → Sharing. +pub fn device_name() -> String { + objc2_foundation::NSHost::currentHost() + .localizedName() + .map(|n| n.to_string()) + .filter(|n| !n.is_empty()) + .unwrap_or_else(|| "Mac".into()) +} + +/// macOS version, e.g. "15.4". +pub fn os_version() -> String { + let v = objc2_foundation::NSProcessInfo::processInfo().operatingSystemVersion(); + if v.patchVersion > 0 { + format!("{}.{}.{}", v.majorVersion, v.minorVersion, v.patchVersion) + } else { + format!("{}.{}", v.majorVersion, v.minorVersion) + } +} + +/// Shows or hides the traffic lights (they fade with the player's controls). +pub fn set_window_buttons(window: &WebviewWindow, visible: bool) { + let Ok(ns_window) = window.ns_window() else { return }; + let ns_window = ns_window as usize; + let _ = window.run_on_main_thread(move || unsafe { + let window = &*(ns_window as *const NSWindow); + for kind in [NSWindowButton::CloseButton, NSWindowButton::MiniaturizeButton, NSWindowButton::ZoomButton] { + if let Some(button) = window.standardWindowButton(kind) { + button.setHidden(!visible); + } + } + // AppKit lays the buttons out again at their default place; the window's + // view restores the configured position (trafficLightPosition) when drawn. + if let Some(view) = window.contentView() { + view.setNeedsDisplay(true); + } + }); +} + +// —— Power ————————————————————————————————————————————————————————————— + +type CFStringRef = *const c_void; +const CF_STRING_ENCODING_UTF8: u32 = 0x0800_0100; +const IOPM_ASSERTION_LEVEL_ON: u32 = 255; + +#[link(name = "CoreFoundation", kind = "framework")] +extern "C" { + fn CFStringCreateWithCString(alloc: *const c_void, s: *const c_char, encoding: u32) -> CFStringRef; + fn CFRelease(cf: *const c_void); +} + +#[link(name = "IOKit", kind = "framework")] +extern "C" { + fn IOPMAssertionCreateWithName(kind: CFStringRef, level: u32, name: CFStringRef, id: *mut u32) -> i32; + fn IOPMAssertionRelease(id: u32) -> i32; +} + +/// Keeps the display awake until `rx` closes or receives. +pub fn hold_awake(rx: Receiver<()>) { + let cf = |s: &CStr| unsafe { CFStringCreateWithCString(ptr::null(), s.as_ptr(), CF_STRING_ENCODING_UTF8) }; + let kind = cf(c"PreventUserIdleDisplaySleep"); + let name = cf(c"Kaleido is playing video"); + let mut id = 0u32; + let held = unsafe { IOPMAssertionCreateWithName(kind, IOPM_ASSERTION_LEVEL_ON, name, &mut id) } == 0; + let _ = rx.recv(); + unsafe { + if held { + IOPMAssertionRelease(id); + } + CFRelease(kind); + CFRelease(name); + } } diff --git a/src-tauri/src/platform/mod.rs b/src-tauri/src/platform/mod.rs index 90c2617..4e013d7 100644 --- a/src-tauri/src/platform/mod.rs +++ b/src-tauri/src/platform/mod.rs @@ -2,11 +2,13 @@ //! Each platform file exposes the same items: //! //! - `VideoSurface`: composes mpv's output beneath the web view -//! (`create`, `mpv_options`, `on_property`, `show`, `fit`, `set_rect`). +//! (`create`, `mpv_options`, `start`, `on_property`, `show`, `fit`, `set_rect`). //! - `SURFACE_PROPERTIES`: mpv properties the surface observes. //! - `MPV_LIBRARIES`: libmpv file names to look for. //! - `hold_awake`: prevents display sleep until the receiver closes. //! - `gpu_names`: the graphics adapters, by name. +//! - `device_name`, `os_version`: how the computer identifies itself to Plex. +//! - `set_window_buttons`: shows or hides native window buttons (macOS). #[cfg(target_os = "windows")] mod windows; diff --git a/src-tauri/src/platform/windows.rs b/src-tauri/src/platform/windows.rs index 242cdb7..76e96ee 100644 --- a/src-tauri/src/platform/windows.rs +++ b/src-tauri/src/platform/windows.rs @@ -69,6 +69,11 @@ impl VideoSurface { ] } + /// Nothing to set up once mpv is initialized: it creates its swapchain itself. + pub fn start(&mut self, _: &std::sync::Arc) -> Result<(), String> { + Ok(()) + } + pub fn on_property(&mut self, name: &str, value: &serde_json::Value) { if name == "display-swapchain" { self.attach(value.as_i64().unwrap_or(0) as usize); @@ -94,7 +99,7 @@ impl VideoSurface { } } - pub fn show(&mut self, visible: bool) { + pub fn show(&mut self, _: &WebviewWindow, visible: bool) { if self.visible == visible { return; } @@ -141,7 +146,6 @@ pub const SURFACE_PROPERTIES: &[&str] = &["display-swapchain"]; /// File names libmpv may have on this platform. pub const MPV_LIBRARIES: &[&str] = &["libmpv-2.dll", "mpv-2.dll"]; -/// Keeps the display awake until `rx` closes or receives. /// Hardware graphics adapters as DXGI names them (e.g. "NVIDIA GeForce RTX 4080"). pub fn gpu_names() -> Vec { use ::windows::Win32::Graphics::Dxgi::*; @@ -165,6 +169,19 @@ pub fn gpu_names() -> Vec { names } +/// The computer's name, as Plex shows it. +pub fn device_name() -> String { + std::env::var("COMPUTERNAME").unwrap_or_else(|_| "Windows PC".into()) +} + +pub fn os_version() -> String { + "11".into() +} + +/// Windows draws its own caption buttons in the page. +pub fn set_window_buttons(_: &WebviewWindow, _: bool) {} + +/// Keeps the display awake until `rx` closes or receives. pub fn hold_awake(rx: std::sync::mpsc::Receiver<()>) { use ::windows::Win32::System::Power::*; unsafe { diff --git a/src-tauri/src/player.rs b/src-tauri/src/player.rs index 2b687c3..f9dea39 100644 --- a/src-tauri/src/player.rs +++ b/src-tauri/src/player.rs @@ -71,7 +71,9 @@ fn create_player(app: &AppHandle, window: &WebviewWindow, opts set("hwdec", opts.hwdec.as_deref().unwrap_or("auto-safe"))?; set("keep-open", "yes")?; set("idle", "yes")?; - set("force-window", "yes")?; + if !render_options.iter().any(|(k, _)| *k == "force-window") { + set("force-window", "yes")?; + } set("osc", "no")?; set("osd-level", "0")?; set("input-default-bindings", "no")?; @@ -107,6 +109,9 @@ fn create_player(app: &AppHandle, window: &WebviewWindow, opts } mpv.request_log_messages("warn"); mpv.initialize()?; + if let Some(surface) = app.state::().surface.lock().as_mut() { + surface.start(&mpv)?; + } for (i, name) in OBSERVED.iter().chain(crate::platform::SURFACE_PROPERTIES).enumerate() { mpv.observe(i as u64 + 1, name); } @@ -183,7 +188,7 @@ pub async fn player_show(app: AppHandle, window: WebviewWindow let mut surface = state.surface.lock(); if let Some(surface) = surface.as_mut() { surface.fit(&window, mpv.as_deref()); - surface.show(visible); + surface.show(&window, visible); } Ok(()) } @@ -225,6 +230,13 @@ pub async fn player_get(app: AppHandle, name: String) -> Result(window: WebviewWindow, visible: bool) { + crate::platform::set_window_buttons(&window, visible); +} + /// Keeps the video surface matched to the window's client area. pub fn on_resize(window: &WebviewWindow) { let app = window.app_handle(); diff --git a/src-tauri/src/system.rs b/src-tauri/src/system.rs index e404d08..bd7fe33 100644 --- a/src-tauri/src/system.rs +++ b/src-tauri/src/system.rs @@ -13,9 +13,14 @@ fn entry(key: &str) -> Result { keyring::Entry::new(SERVICE, key).map_err(|e| e.to_string()) } -/// Secrets (Plex tokens) live in Windows Credential Manager, never in plain files. +/// Secrets (Plex tokens) live in the OS's credential store (Windows Credential +/// Manager, the macOS Keychain), never in plain files; except in macOS debug +/// builds, see `dev_secrets`. #[tauri::command] -pub fn secret_get(key: String) -> Result, String> { +pub fn secret_get(app: AppHandle, key: String) -> Result, String> { + if let Some(path) = dev_secrets(&app) { + return Ok(read_dev_secrets(&path).get(&key).and_then(|v| v.as_str()).map(String::from)); + } match entry(&key)?.get_password() { Ok(v) => Ok(Some(v)), Err(keyring::Error::NoEntry) => Ok(None), @@ -24,18 +29,66 @@ pub fn secret_get(key: String) -> Result, String> { } #[tauri::command] -pub fn secret_set(key: String, value: String) -> Result<(), String> { - entry(&key)?.set_password(&value).map_err(|e| e.to_string()) +pub fn secret_set(app: AppHandle, key: String, value: String) -> Result<(), String> { + if let Some(path) = dev_secrets(&app) { + let mut all = read_dev_secrets(&path); + all.insert(key, Value::String(value)); + return write_dev_secrets(&path, &all); + } + let entry = entry(&key)?; + match entry.set_password(&value) { + Ok(()) => Ok(()), + // A Keychain item left by a differently signed build can be impossible to + // update yet still block adding; replacing it recovers. + Err(keyring::Error::PlatformFailure(_)) if cfg!(target_os = "macos") => { + let _ = entry.delete_credential(); + entry.set_password(&value).map_err(|e| e.to_string()) + } + Err(e) => Err(e.to_string()), + } } #[tauri::command] -pub fn secret_delete(key: String) -> Result<(), String> { +pub fn secret_delete(app: AppHandle, key: String) -> Result<(), String> { + if let Some(path) = dev_secrets(&app) { + let mut all = read_dev_secrets(&path); + all.remove(&key); + return write_dev_secrets(&path, &all); + } match entry(&key)?.delete_credential() { Ok(()) | Err(keyring::Error::NoEntry) => Ok(()), Err(e) => Err(e.to_string()), } } +/// macOS ties Keychain access to the app's code signature, and every debug +/// build is a new unsigned binary, so the Keychain would ask for permission +/// after each rebuild. Debug builds there keep secrets in a private file in the +/// app data folder instead (development only, like the `.env` sign-in). +fn dev_secrets(app: &AppHandle) -> Option { + if !(cfg!(debug_assertions) && cfg!(target_os = "macos")) { + return None; + } + app.path().app_data_dir().ok().map(|d| d.join("dev-secrets.json")) +} + +fn read_dev_secrets(path: &std::path::Path) -> serde_json::Map { + std::fs::read_to_string(path).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default() +} + +fn write_dev_secrets(path: &std::path::Path, all: &serde_json::Map) -> Result<(), String> { + use std::io::Write; + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).map_err(|e| e.to_string())?; + } + let mut options = std::fs::OpenOptions::new(); + options.write(true).create(true).truncate(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + let mut file = options.open(path).map_err(|e| e.to_string())?; + file.write_all(Value::Object(all.clone()).to_string().as_bytes()).map_err(|e| e.to_string()) +} + #[derive(Serialize)] #[serde(rename_all = "camelCase")] pub struct AppInfo { @@ -43,6 +96,7 @@ pub struct AppInfo { data_dir: String, default_download_dir: String, platform: String, + os_version: String, device_name: String, /// Graphics adapters by name (decides which upscaling tiers are offered). gpus: Vec, @@ -63,7 +117,8 @@ pub fn app_info(app: AppHandle) -> AppInfo { data_dir: data, default_download_dir: downloads, platform: std::env::consts::OS.to_string(), - device_name: std::env::var("COMPUTERNAME").unwrap_or_else(|_| "Windows PC".into()), + os_version: crate::platform::os_version(), + device_name: crate::platform::device_name(), gpus: crate::platform::gpu_names(), } } diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index f1d889b..3cc53f2 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -58,7 +58,7 @@ }, "plugins": { "updater": { - "pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEU0MTA2RjI0OUFFQzU1QzUKUldURlZleWFKRzhRNUlqTTR3U095STFYS3BsUXd2UnZMYlRrQmt3aUk5YU5WSjdqcUxVcHllU1EK", + "pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEUxQjk1OTExMzBCRTRENEUKUldST1RiNHdFVm01NFFMQ1EvYm9CYlhhNU9jNTZXb254dVZOQW8relJYRlQ4ZjdLQll3cHR3VE4K", "endpoints": [ "https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/raw/branch/main/updates/latest.json" ] diff --git a/src-tauri/tauri.macos.conf.json b/src-tauri/tauri.macos.conf.json index 3f75d23..08b6016 100644 --- a/src-tauri/tauri.macos.conf.json +++ b/src-tauri/tauri.macos.conf.json @@ -1,15 +1,39 @@ { "$schema": "https://schema.tauri.app/config/2", + "app": { + "windows": [ + { + "label": "main", + "title": "Kaleido", + "width": 1480, + "height": 900, + "minWidth": 900, + "minHeight": 580, + "center": true, + "decorations": true, + "titleBarStyle": "Overlay", + "hiddenTitle": true, + "trafficLightPosition": { "x": 22, "y": 35 }, + "backgroundColor": "#090a0c", + "transparent": false, + "shadow": true, + "visible": false, + "dragDropEnabled": false + } + ] + }, "bundle": { "targets": [ "app", "dmg" ], "macOS": { - "minimumSystemVersion": "12.0", - "frameworks": [ - "../vendor/mpv/macos/libmpv.2.dylib" - ] + "minimumSystemVersion": "26.0", + "signingIdentity": "-", + "hardenedRuntime": false, + "files": { + "Frameworks": "../vendor/mpv/macos" + } } } -} \ No newline at end of file +} diff --git a/src/app/App.tsx b/src/app/App.tsx index 7c98113..6623697 100644 --- a/src/app/App.tsx +++ b/src/app/App.tsx @@ -11,7 +11,7 @@ import { PageLoader } from '../ui/primitives'; import { Splash } from '../screens/Splash'; import { SignIn } from '../screens/SignIn'; import { ServerPicker } from '../screens/ServerPicker'; -import { win } from '../platform/native'; +import { isMac, win } from '../platform/native'; import { usePlayer } from '../player/store'; import { PlayerOverlay } from '../player/PlayerOverlay'; import { DialogHost } from '../screens/dialogs/DialogHost'; @@ -100,13 +100,13 @@ function useGlobalShortcuts() { if ((e.ctrlKey || e.metaKey) && (e.key === 'k' || e.key === 'f')) { e.preventDefault(); navigate({ name: 'search' }); - } else if (e.altKey && e.key === 'ArrowLeft') { + } else if ((e.altKey && e.key === 'ArrowLeft') || (isMac && e.metaKey && e.key === '[')) { e.preventDefault(); useRouter.getState().back(); - } else if (e.altKey && e.key === 'ArrowRight') { + } else if ((e.altKey && e.key === 'ArrowRight') || (isMac && e.metaKey && e.key === ']')) { e.preventDefault(); useRouter.getState().forward(); - } else if (e.key === 'F11') { + } else if (e.key === 'F11' || (isMac && e.metaKey && e.ctrlKey && e.key.toLowerCase() === 'f')) { e.preventDefault(); win.isFullscreen().then((fs) => win.setFullscreen(!fs)); } else if ((e.key === 'Escape' || e.key === 'Backspace') && !isTyping(e.target) && !document.querySelector('.menu-layer, .dialog-layer')) { @@ -225,7 +225,16 @@ export function App() { useEffect(() => { useSession.getState().init(); // The window appears once the first frame is painted (no white flash). - requestAnimationFrame(() => win.show()); + // WKWebView runs no animation frames until its window is shown, so a + // timeout stands in there. + let shown = false; + const show = () => { + if (!shown) win.show(); + shown = true; + }; + requestAnimationFrame(show); + const fallback = setTimeout(show, 150); + return () => clearTimeout(fallback); }, []); useEffect(() => { diff --git a/src/app/TopBar.tsx b/src/app/TopBar.tsx index 33e7b80..3c538fc 100644 --- a/src/app/TopBar.tsx +++ b/src/app/TopBar.tsx @@ -5,7 +5,7 @@ import { useSettings } from './settings'; import { Icon } from '../ui/Icon'; import { KaleidoMark } from '../ui/primitives'; import { openMenu, type MenuItem } from '../ui/overlays'; -import { isNative, win } from '../platform/native'; +import { isMac, isNative, shortcut, win } from '../platform/native'; import { useDownloads } from '../downloads/store'; import { useHomeUsers } from './useHomeUsers'; @@ -16,17 +16,18 @@ const NAV = [ { id: 'downloads', label: 'Downloads', route: { name: 'downloads' } as const }, ]; +/** Caption buttons drawn by the page; macOS shows its own traffic lights instead. */ export function WindowControls() { const [maximized, setMaximized] = useState(false); useEffect(() => { - if (!isNative) return; + if (!isNative || isMac) return; let off: (() => void) | undefined; const sync = () => win.isMaximized().then(setMaximized); sync(); win.onResized(sync).then((u) => (off = u)); return () => off?.(); }, []); - if (!isNative) return null; + if (!isNative || isMac) return null; return (
- - - -
+ ); } diff --git a/src/screens/settings/AppSettings.tsx b/src/screens/settings/AppSettings.tsx index 3d2afae..3c68016 100644 --- a/src/screens/settings/AppSettings.tsx +++ b/src/screens/settings/AppSettings.tsx @@ -5,7 +5,7 @@ import { useSections, useServerQuery } from '../../app/queries'; import * as api from '../../plex/api'; import { art } from '../../app/format'; import { useDownloads } from '../../downloads/store'; -import { appInfo, isNative, openExternal, pickFolder, revealPath, type AppInfo } from '../../platform/native'; +import { appInfo, fullscreenShortcut, isMac, isNative, openExternal, pickFolder, revealPath, shortcut, type AppInfo } from '../../platform/native'; import { checkForUpdate, installUpdate, useUpdater } from '../../app/updater'; import { Button, Segmented, Select, Switch } from '../../ui/primitives'; import { confirmDialog } from '../../ui/overlays'; @@ -42,14 +42,16 @@ const skipOptions: { value: SkipMode; label: string }[] = [ { value: 'off', label: 'Off' }, ]; +const OS_NAMES: Record = { windows: 'Windows', macos: 'macOS', linux: 'Linux' }; + const SHORTCUTS: [string, string][][] = [ [ - ['Ctrl + K', 'Search'], - ['Alt + ← / Mouse back', 'Go back'], - ['Alt + → / Mouse forward', 'Go forward'], + [shortcut('K'), 'Search'], + [isMac ? '⌘[ / Mouse back' : 'Alt + ← / Mouse back', 'Go back'], + [isMac ? '⌘] / Mouse forward' : 'Alt + → / Mouse forward', 'Go forward'], ['Esc', 'Go back or close a dialog'], - ['F11', 'Full screen'], - ['Ctrl + ,', 'Settings'], + [fullscreenShortcut, 'Full screen'], + [shortcut(','), 'Settings'], ['Right-click a title', 'Title actions'], ], [ @@ -182,7 +184,7 @@ export function AppSettings({ tab }: { tab: string }) { set('hwdec', v)} /> - + set('hdrPassthrough', v)} /> @@ -374,7 +376,7 @@ export function AppSettings({ tab }: { tab: string }) {

Kaleido

- Version {info?.version ?? '—'} · {info?.platform === 'windows' ? 'Windows' : info?.platform} + Version {info?.version ?? '—'} · {OS_NAMES[info?.platform ?? ''] ?? info?.platform}

diff --git a/src/styles/app.css b/src/styles/app.css index 8a1771b..b96315d 100644 --- a/src/styles/app.css +++ b/src/styles/app.css @@ -248,6 +248,14 @@ display: flex; justify-content: flex-end; } +/* macOS draws its traffic lights at the top left (tauri.macos.conf.json places + them in the bar's centre line); keep the bar's content clear of them. */ +html.os-macos:not(.window-fullscreen) { + --traffic-lights: 92px; +} +html.os-macos:not(.window-fullscreen) .topbar { + padding-left: max(calc(var(--gutter) - 10px), var(--traffic-lights)); +} /* —— Splash ————————————————————————————————————————————————— */ .splash { diff --git a/src/styles/player.css b/src/styles/player.css index b70b182..c4bc27b 100644 --- a/src/styles/player.css +++ b/src/styles/player.css @@ -69,6 +69,9 @@ transition: opacity 400ms var(--ease); } /* The window's own buttons, top right, fading with the rest of the chrome. */ +html.os-macos:not(.window-fullscreen) .player-top { + padding-left: var(--traffic-lights); +} .player-top .window-controls { position: absolute; top: 0; diff --git a/updates/README.md b/updates/README.md index e579a92..b079f2e 100644 --- a/updates/README.md +++ b/updates/README.md @@ -2,14 +2,11 @@ `latest.json` is the feed the in-app updater reads (see `plugins.updater.endpoints` in `src-tauri/tauri.conf.json`). It lists one signed build per platform: -`windows-x86_64`, `darwin-aarch64`, `darwin-x86_64` and `linux-x86_64`. +`windows-x86_64` and `darwin-aarch64`. -Regenerate it after building a release, pointing at the release's download folder: +Regenerate it once a release has every platform's build uploaded (see +`docs/development.md` → Releases); it reads the release's assets on Forgejo: ```bash -node scripts/update-manifest.mjs 0.2.0 https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/releases/download/v0.2.0 +node scripts/update-manifest.mjs 0.2.0 ``` - -Platforms built elsewhere can be merged in by listing their bundle folders in -`KALEIDO_BUNDLES` (separated by `;`). Existing platform entries are kept, so each OS -can publish independently. diff --git a/vendor/mpv/README.md b/vendor/mpv/README.md index ae19881..c153b45 100644 --- a/vendor/mpv/README.md +++ b/vendor/mpv/README.md @@ -6,7 +6,7 @@ folder, which is ignored by git and fetched by a script: | OS | Folder | How to fetch | | --- | --- | --- | | Windows | `windows/libmpv-2.dll` | `scripts/fetch-libmpv.ps1` (shinchiro `mpv-dev-x86_64` build) | -| macOS | `macos/libmpv.2.dylib` | `scripts/fetch-libmpv.sh` (Homebrew `mpv`) | +| macOS | `macos/libmpv.2.dylib` and the libraries it links | `scripts/fetch-libmpv.sh` (Homebrew `mpv`, made self-contained) | | Linux | system `libmpv.so.2` | Install your distribution's `libmpv2` package | At runtime Kaleido looks in the app's resources, beside the executable, here, and