Compare commits

14 Commits
Author SHA1 Message Date
nvrl 79f0d74e1a chore(release): bump version to 1.7.0 2026-10-28 02:43:25 +01:00
nvrl 648c35e92a fix(app): the subtitle preview is drawn in the chosen font
The preview drew every font in the app's own Inter, so picking one changed
nothing on screen. On Linux it now asks fontconfig for the face libass would
use — the family with the weight and slant wanted, or fontconfig's fallback
when it is not installed — loads it on a thread of its own and draws the
sample in it. A bold or italic the face lacks is made up, as libass does.
Windows and macOS have no fc-match and keep the app's font, as the hint there
still says.

The CJK fallback and the subtitle face are now both kept, so installing one
no longer drops the other.
2026-10-27 23:08:43 +01:00
nvrl ffd6e959bb fix(core,player,app): styled subtitles keep their size and place unless restyled
mpv's default sub-ass-override, `scale`, hands an ASS track sub-scale,
and sub-pos reaches it under every mode but `no`. So with "Restyle
styled subtitles" off, the subtitle size and position settings still
resized and moved typeset dialogue and signs.

The override is now `yes` when restyling is off, which keeps sub-scale
off ASS. A styled track also ignores the style's position, and moves
only to stay clear of the player's controls. A frame from an ASS track
rendered with every other option changed now matches the untouched one
pixel for pixel. Plain (SRT) tracks still take the whole style.
2026-10-27 22:44:35 +01:00
nvrl 69d961d7b8 feat(core,player,app): full subtitle styling, applied live, with a preview
The subtitle style was three fixed choices. It is now size, position,
font, bold and italic, free colours with opacity for the text, outline,
box and shadow, outline thickness, shadow distance and blur, and an
opt-in "Restyle styled subtitles" that repaints ASS dialogue too
(sub-ass-override=force). The defaults are mpv's own, so a viewer who
never opens the section sees no change.

Settings has a section of its own with a sample line drawn on a bright
and a dark picture. Every change also reaches the playing file at once,
and is written when the mouse is let go rather than once per frame of a
drag. The player's subtitle menu has size, position and a per-file
delay; Z and X shift subtitles by 0.1 s, as in mpv.

Every option is sent every time, so a change back to a default lands on
a live player. A refused sub-border-style still skips the border options
that depend on it, so an older libmpv loses the box rather than drawing
a smear.
2026-10-27 22:25:53 +01:00
nvrl 238ecd8220 fix(core,meta): a folder of films is one title per film
The four Rebuild of Evangelion films in one folder were one series:
`- 1.11` read as episode 1, and every file took the folder's name, so
the whole folder matched a single film. A dash followed by a decimal is
now part of the film's name, and a folder whose files are all
unnumbered, outside any grouping folder and each named differently
gives each file its own title.

AniList needs every query word in a title, and a film's version number
is not in it, so a search that finds nothing is retried without it.
All four films now match their own entries.
2026-10-27 19:50:26 +01:00
nvrl 65a669e231 feat(core,player,app): subtitle size, background and colour settings
Plain-text subtitles (SRT) were drawn in mpv's bare default, thin white
text that bright scenes swallow. Settings → Playback now picks a size,
an outline or a dark box, and white or yellow text. Styled (ASS) tracks
keep their own look and take only the size.

The box options are mpv 0.38's, so they are set best effort: an older
libmpv logs and plays on. The style syncs with the other playback
settings, and the Android bridge keeps the stored style instead of
resetting it on save.
2026-10-27 19:50:21 +01:00
nvrl 658c620c82 chore(release): bump version to 1.6.2 2026-10-17 21:05:19 +02:00
nvrl c1487c31d0 fix(packaging): centre the play mark in the desktop icon
The mark's box centred on x=73 of the 64-centred tile, so it sat visibly
right. It now centres x=70, between its box and its centroid, as the
Android and iOS icons already do. icon-256.png and the Windows .ico are
rendered again from the SVG.
2026-10-17 21:00:29 +02:00
nvrl a8a18be248 docs(readme): screenshots, install table and features up to 1.6.1
The README still described an early, public-links-only app. It now
shows the desktop and Android apps, lists what each release ships per
platform, covers sign-in, Drive folders, sync, downloads, Android TV and
dialogue-first subtitles, and points at the wiki for the details.
2026-10-17 20:46:32 +02:00
nvrl 16c2b4c9d3 docs: user guide pages, published to the GitHub wiki
docs/ gains pages for people using the app rather than building it:
getting started, installation, the user guide, account and sync,
Android and iOS, the command line, privacy, an FAQ and troubleshooting.
docs/README.md is the wiki's home page.

scripts/publish-wiki.sh, ported from proton-drive-linux, checks every
link in docs/ and README.md, rewrites links between pages to wiki page
names and copies the images they show. The Wiki workflow runs the check
on pull requests and publishes on every push to main.

images/ holds library, title and episode screenshots from the desktop
and Android apps, and the logo.
2026-10-17 20:46:09 +02:00
nvrl 2871a13ba6 Merge pull request #2 from mathieu-rahab/fix/macos-embedded-video
fix(player): resolve GL entry points from OpenGL.framework on macOS
2026-10-16 02:12:46 +02:00
nvrl 6e0be9e3c8 chore(release): bump version to 1.6.1 2026-10-15 22:50:10 +02:00
rahab.mathieu 0868c2af69 fix(player): resolve GL entry points from OpenGL.framework on macOS 2026-10-15 21:35:23 +02:00
nvrl 4a3a7291b8 chore(deps): proton-sdk and proton-drive-rs 0.9.0
Adapt sign-in to the 0.8 account API and use what it adds:

- Key passphrases are KeyPassphrases now, wiped on drop. The stored
  session keeps its JSON shape and converts on unlock.
- The mailbox password is checked with AccountClient::unlock(), one
  core/v4/users request instead of loading every address, and a wrong
  one is recognised as ProtonError::KeysLocked instead of any
  InvalidOperation.
- KeysLocked from a resumed session counts as signed out: the mailbox
  password changed, and only signing in again derives passphrases that
  unlock the keys.
- A sign-in Proton answers with code 2028 (Blocked) says so, instead of
  showing the server text that claims the app version is outdated.

Also picked up without code changes: a token refresh that outlives its
caller and is never replayed (0.8.2).
2026-10-15 19:56:56 +02:00
44 changed files with 3204 additions and 174 deletions

No files matched your search

+68
View File
@@ -0,0 +1,68 @@
name: Wiki
# docs/ is the source of the GitHub wiki. Every change to the documentation
# checks its links; a push to main publishes the result, so the wiki follows
# main. Pull requests only check: nothing unmerged reaches the wiki. Run it from
# the Actions tab to publish another ref, such as a release tag.
on:
push:
branches: [main]
paths:
- 'docs/**'
- 'images/**'
- 'README.md'
- 'scripts/publish-wiki.sh'
- '.github/workflows/wiki.yml'
pull_request:
paths:
- 'docs/**'
- 'images/**'
- 'README.md'
- 'scripts/publish-wiki.sh'
- '.github/workflows/wiki.yml'
workflow_dispatch:
inputs:
ref:
description: 'Tag or branch to publish'
required: false
default: 'main'
type: string
permissions:
contents: read
jobs:
check:
name: Check documentation links
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v7
with:
ref: ${{ inputs.ref || github.sha }}
- name: Check links
run: scripts/publish-wiki.sh --check "$RUNNER_TEMP"
publish:
name: Publish to the wiki
needs: check
# Pull requests never publish.
if: github.event_name != 'pull_request'
runs-on: ubuntu-24.04
concurrency:
group: wiki-publish
cancel-in-progress: false
permissions:
contents: write
steps:
- uses: actions/checkout@v7
with:
ref: ${{ inputs.ref || github.sha }}
- name: Publish
env:
WIKI_REMOTE: https://x-access-token:${{ github.token }}@github.com/${{ github.repository }}.wiki.git
run: |
git config --global user.name 'github-actions[bot]'
git config --global user.email '41898282+github-actions[bot]@users.noreply.github.com'
scripts/publish-wiki.sh --push "$RUNNER_TEMP"
Generated
+14 -13
View File
@@ -4844,9 +4844,9 @@ checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "pgp"
version = "0.20.0"
version = "0.21.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1cfa4743b28656065ff4c0ba09e46b357a65e8c00fc2341e89084b82f87cbdf1"
checksum = "ae70f4d9325a391db30d115d6191a7bb67cec856aa0bba131290f0c4e09a532a"
dependencies = [
"aead 0.5.2",
"aes 0.8.4",
@@ -5218,9 +5218,9 @@ checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5"
[[package]]
name = "proton-drive-rs"
version = "0.7.3"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1868294071187f6198aad10e01bd1ccaa02e70cd6b92f729f9cf7215671aa20f"
checksum = "eb9638bbcc807188ce43e6012361d0f5ce4ab70011f6160240df05e474eb3b54"
dependencies = [
"async-trait",
"base64 0.23.0",
@@ -5245,9 +5245,9 @@ dependencies = [
[[package]]
name = "proton-sdk"
version = "0.7.3"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "118e33440fcf26a05bd6cc19d544d1270ab183ece0fe535904b4767b16d5b3e0"
checksum = "79557071826330cebd39cf4081d6b75a42721134e5b442682d8e82e709584875"
dependencies = [
"aes-gcm 0.11.0",
"async-trait",
@@ -5274,11 +5274,12 @@ dependencies = [
"thiserror 2.0.19",
"tokio",
"tracing",
"zeroize",
]
[[package]]
name = "pstr-android"
version = "1.6.0"
version = "1.7.0"
dependencies = [
"android_logger",
"futures",
@@ -5298,7 +5299,7 @@ dependencies = [
[[package]]
name = "pstr-app"
version = "1.6.0"
version = "1.7.0"
dependencies = [
"anyhow",
"chrono",
@@ -5332,7 +5333,7 @@ dependencies = [
[[package]]
name = "pstr-cli"
version = "1.6.0"
version = "1.7.0"
dependencies = [
"anyhow",
"clap",
@@ -5351,7 +5352,7 @@ dependencies = [
[[package]]
name = "pstr-core"
version = "1.6.0"
version = "1.7.0"
dependencies = [
"directories",
"futures",
@@ -5371,7 +5372,7 @@ dependencies = [
[[package]]
name = "pstr-meta"
version = "1.6.0"
version = "1.7.0"
dependencies = [
"pstr-core",
"reqwest",
@@ -5384,7 +5385,7 @@ dependencies = [
[[package]]
name = "pstr-player"
version = "1.6.0"
version = "1.7.0"
dependencies = [
"async-trait",
"libloading",
@@ -5399,7 +5400,7 @@ dependencies = [
[[package]]
name = "pstr-stream"
version = "1.6.0"
version = "1.7.0"
dependencies = [
"async-trait",
"futures",
+3 -3
View File
@@ -11,7 +11,7 @@ members = [
]
[workspace.package]
version = "1.6.0"
version = "1.7.0"
edition = "2024"
license = "MIT"
repository = "https://github.com/narrrl/proton-stream"
@@ -28,8 +28,8 @@ authors = ["Nils Pukropp <contact@narl.io>"]
opt-level = 2
[workspace.dependencies]
proton-sdk = { version = "0.7.3" }
proton-drive-rs = { version = "0.7.3" }
proton-sdk = { version = "0.9.0" }
proton-drive-rs = { version = "0.9.0" }
# Internal crates.
pstr-core = { path = "crates/pstr-core" }
+144 -109
View File
@@ -1,83 +1,145 @@
<div align="center">
<img src="images/logo.svg" alt="" width="112" height="112">
# proton-stream
A Netflix-style cross-platform client for **Proton Drive public links**.
**Your Proton Drive, streaming.** A Netflix-style library for the videos in your Proton Drive and
the share links people send you, on Linux, Windows, Android, Android TV and iOS.
Paste a share URL and its password; get a browsable, streamable library. No
Proton account, no server to host, no download step — episodes start playing in
seconds and the seek bar works.
**[proton-stream.narl.io](https://proton-stream.narl.io)**
Built on [`proton-sdk-rs`](https://github.com/narrrl/proton-sdk-rs), a pure-Rust
Proton Drive SDK.
[![CI](https://github.com/narrrl/proton-stream/actions/workflows/ci.yml/badge.svg)](https://github.com/narrrl/proton-stream/actions/workflows/ci.yml)
[![Release](https://img.shields.io/github/v/release/narrrl/proton-stream?sort=semver)](https://github.com/narrrl/proton-stream/releases/latest)
[![License: MIT / GPL-3.0](https://img.shields.io/badge/license-MIT%20%2F%20GPL--3.0-blue.svg)](#license)
[![Rust 1.96+](https://img.shields.io/badge/rust-1.96%2B-orange.svg)](https://www.rust-lang.org)
[![Buy me a coffee](https://img.shields.io/badge/Buy%20me%20a%20coffee-FFDD00?logo=buymeacoffee&logoColor=black)](https://buymeacoffee.com/narl)
<img src="images/desktop-home.png" alt="The library in the desktop app" width="820">
</div>
> [!IMPORTANT]
> This is an **unofficial**, community-built client. It is not affiliated with, endorsed by, or
> supported by Proton AG. "Proton" and "Proton Drive" are trademarks of Proton AG, used here only
> to describe what the software talks to. It provides no content: it plays what you keep in
> Proton Drive or what is shared with you.
## Features
**Library**
- **Public share links or your own Drive.** Paste a share link, with its password if it has one,
or sign in and pick folders of your Drive. Any number of them merge into one library.
- **Seasons and episodes from your folders.** The folder names the show, the file name gives the
season and episode, and a file without numbers is a film.
- **Posters, synopses and shelves**, from AniList or TMDB, **off by default**: shelves such as
*Directed by* and *From MADHOUSE*, a franchise folded into one tile, and a hand-picked match
that is never overwritten.
- **Filters and sorting:** series, films, watching, not started, downloaded; by name, last watched,
last added, air date, rating or popularity.
**Player**
- **Streams, never downloads first.** Episodes start in seconds, and a seek fetches only what it
lands on.
- **libmpv inside the app's own window:** HEVC 10-bit, HDR and ASS subtitles with hardware
decoding, and no transcoding.
- **Skip the opening and the ending** by chapter, an **Up next** countdown, and next and previous
episode.
- **Subtitle files beside the video** (`.srt`, `.ass`, `.ssa`, `.vtt`), and **the dialogue track
over *Signs & Songs***. Audio and subtitle choices are remembered for each show.
**Everywhere**
- **Resume on any device.** Sign in, and your place in every episode, your shares and your
settings sync through your own Drive.
- **Downloads** of an episode, a season or a show, to play offline.
- **Android 12+ and Android TV** with Material 3, background audio and new-episode
notifications; **iOS 17+** as a SwiftUI port for SideStore and AltStore.
- **Themes:** a near-black default, four Catppuccin flavours and Persona 5, each with nine accents.
- **Full keyboard control** on the desktop, and the `pstr` command line.
<table>
<tr>
<td width="50%"><img src="images/desktop-library.png" alt="The whole library, filtered and sorted"></td>
<td width="50%">
<img src="images/android-home.png" alt="Android: home" width="24%">
<img src="images/android-library.png" alt="Android: all titles" width="24%">
<img src="images/android-title.png" alt="Android: a title page" width="24%">
<img src="images/android-episodes.png" alt="Android: episodes and downloads" width="24%">
</td>
</tr>
</table>
## Install
Every [release](https://github.com/narrrl/proton-stream/releases/latest) has:
| Platform | Download |
|---|---|
| Debian, Ubuntu | `proton-stream_<version>-1_amd64.deb` |
| Fedora | `proton-stream-<version>-1.x86_64.rpm` |
| Other Linux | `proton-stream-<version>-x86_64-unknown-linux-gnu.tar.gz` |
| Windows | `proton-stream-<version>-x64.msi`, or the portable `…-x86_64-windows.zip` |
| Android, Android TV | `proton-stream-<version>-android.apk` |
| iOS, iPadOS | `proton-stream-<version>-ios.ipa`, for SideStore or AltStore |
```bash
sudo apt install ./proton-stream_*_amd64.deb # Debian, Ubuntu
sudo dnf install ./proton-stream-*.x86_64.rpm # Fedora
cd packaging && makepkg -si # Arch, from a checkout
```
Then open **Proton Stream**, paste a share link on the **Shares** page (or press **Ctrl+V**), and
the library fills in. [Getting started](docs/GETTING_STARTED.md) walks through it, and
[Installation](docs/INSTALL.md) covers every platform, updating and uninstalling.
## Documentation
The [wiki](https://github.com/narrrl/proton-stream/wiki) is generated from [`docs/`](docs/) on
every push to `main`:
- [Getting started](docs/GETTING_STARTED.md), [Installation](docs/INSTALL.md) and the
[FAQ](docs/FAQ.md)
- [User guide](docs/USER_GUIDE.md), [Account and sync](docs/ACCOUNT_AND_SYNC.md) and
[Android and iOS](docs/MOBILE.md)
- [Command-line reference](docs/CLI.md), [Privacy](docs/PRIVACY.md) and
[Troubleshooting](docs/TROUBLESHOOTING.md)
- For contributors: [Development](docs/DEVELOPMENT.md), [Architecture](docs/ARCHITECTURE.md),
[Testing](docs/TESTING.md), [Android](docs/ANDROID.md) and [iOS](docs/IOS.md)
## Why it works
A Proton Drive file's content blocks are each a self-contained PGP packet
decrypted under one shared session key. There is no sequential streaming session
to resume, so seeking costs exactly the blocks the seek lands on — a 2 GB episode
is playable without downloading 2 GB of it.
A Proton Drive file's content blocks are each a self-contained PGP packet decrypted under one
shared session key. There is no sequential streaming session to resume, so seeking costs exactly
the blocks the seek lands on: a 2 GB episode plays without downloading 2 GB of it.
## Status
On a 761 MiB, 26-minute 1080p HEVC episode over a real password-protected link: **2.3 s to first
frame, about 1.5 s to resume after dragging to an arbitrary point, and 61 MiB fetched for the
first 38 seconds of playback.** Watch it again and the disk cache serves it with **no network at
all**: 0.3 s to first frame.
Early, but it is an app now: the picture lands **inside the window**, not in an
mpv window of its own. The SDK streaming surface, the catalog, the streaming
layer and the player are done and verified against a real share, and the app has
a library wall, a page per title with seasons and episodes,
resume-where-you-left-off, an overlay with a chapter-marked seek bar, a skip
button for openings and endings, next/previous episode with an "up next"
countdown, subtitle files beside the video, optional metadata, themes and share
management. What is left is mostly running the macOS packaging on a real Mac. See
`docs/DEVELOPMENT.md`.
The player is fed through an in-process mpv stream callback, not a local HTTP server, so there is
no port another process could ask for the plaintext. [Architecture](docs/ARCHITECTURE.md) has the
whole data flow.
A native Android 12+ client is under `android/`, sharing the Rust catalog and
streaming implementation through UniFFI. It features a modern Material 3 interface,
an immersive fullscreen player with auto-hiding controls, and offline downloads.
Its toolchain, emulator, signing, and release instructions are in [`docs/ANDROID.md`](docs/ANDROID.md).
Built on [`proton-sdk-rs`](https://github.com/narrrl/proton-sdk-rs), a pure-Rust Proton Drive
SDK.
An iOS 17+ client under `ios/` is a SwiftUI port of the Android one over the same
Rust engine, built as an unsigned `.ipa` for SideStore or AltStore; see
[`docs/IOS.md`](docs/IOS.md).
## Privacy
```bash
cargo run --release -p pstr-app # the app
proton-stream 'https://drive.proton.me/urls/TOKEN#fragment' # open the Add form with a link
```
- **No server, no telemetry.** Each app talks to Proton and to nothing else, unless you turn on
posters and descriptions, which sends your title names to AniList or TMDB.
- **The part of a share link after `#` is its decryption key.** It, any link password and your
Proton session live in the system credential store (Secret Service, Credential Manager, the
Android Keystore, the iOS Keychain), never in a config file.
- **Sync is end-to-end encrypted.** Watch history, shares and settings travel through your own
Drive, one file per device.
- **The block cache and downloads hold decrypted video** in your cache and data folders. Size or
empty the cache in **Settings → Storage**.
One window at a time: a second launch brings the open window forward and
hands it any share link it was given, then exits.
The `pstr` CLI does the same work headlessly, and is what tells you which layer
is broken:
```bash
cargo run -p pstr-cli -- add --name anime 'https://drive.proton.me/urls/TOKEN#fragment'
cargo run -p pstr-cli -- crawl
cargo run -p pstr-cli -- list
cargo run -p pstr-cli -- metadata # opt-in; off unless configured
cargo run --release -p pstr-cli -- play --file Frieren --disk-cache
cargo run --release -p pstr-cli -- bench --file Frieren --verify
```
On a 761 MiB, 26-minute 1080p HEVC episode over a real password-protected link:
**2.3 s to first frame, ~1.5 s to resume after dragging to an arbitrary point,
61 MiB fetched for the first 38 seconds of playback.** Watch it again and the
disk cache serves it with **no network at all** — 0.3 s to first frame.
`bench` measures the same file without a player, reporting cold seek latency,
sustained throughput and peak memory, and `--verify` cross-checks a mid-file read
against the SDK's own range download.
## Design
| | |
|---|---|
| Topology | Fat client. No server; each viewer's app talks to Proton directly. |
| Auth | Public links only — but several, merged into one library. |
| Player | Embedded libmpv, drawing into the app's own GL surface: HEVC 10-bit, HDR and ASS subtitles with hardware decode. Volume, audio-track, subtitle and chapter pickers; skip-the-opening; next/previous episode and autoplay. The language picked is preferred for the next file too. |
| Transcoding | None. mpv demuxes and decodes natively. |
| UI | egui/eframe on glow; mpv renders into the same GL context. |
| Themes | The shipped near-black palette, Catppuccin Latte, Frappé, Macchiato and Mocha, and a Persona 5 one — black, white and one loud red, which is what the Red accent is there for — each with a choice of nine accents, drawn as a gradient unless you turn that off. Picked on the Settings page, applied without a restart. |
| Metadata | Filename parsing, with optional AniList/TMDB enrichment — **off by default**, because enabling it sends your library's titles to a third party. It brings posters, synopses, fanart and per-episode titles and synopses (for AniList, from ani.zip, which is sent the matched ids); a title the scorer refuses to guess about can be pinned by hand, and a pinned match is never overwritten. The library sorts by name, watch, add or air date, rating and popularity, folds a franchise into one tile, and shelves titles by director, studio and genre. See [docs/METADATA.md](docs/METADATA.md). |
| Platforms | Linux and Windows; macOS packaging is written but has not been run on a Mac. A native Android 12+ client is available featuring a Material 3 UI and immersive fullscreen playback, and an iOS 17+ port of it for sideloading. |
[Privacy](docs/PRIVACY.md) lists every connection and every file.
## Building
@@ -85,53 +147,26 @@ Rust 2024, MSRV 1.96.
```bash
cargo build --release
cargo run --release -p pstr-app # the app
cargo run -p pstr-cli -- add --name anime 'URL' # the same work, headless
```
`pstr-player` needs libmpv development headers (`mpv` ≥ 2.0), and on Linux
`pstr-app` needs WebKitGTK 4.1's, for the window Proton's CAPTCHA is shown in.
On Windows the libmpv ones
come from the separate **mpv-dev** archive rather than mpv's player build, and
`libmpv-2.dll` ships next to the executable. The Proton SDK crates come from
crates.io; nothing here builds against a sibling checkout.
`pstr-player` needs libmpv development headers (`mpv` ≥ 2.0), and on Linux `pstr-app` needs
WebKitGTK 4.1's, for the CAPTCHA window. The Proton SDK crates come from crates.io.
Installable artifacts — tarball, `.deb`, `.rpm`, Arch package, `.app`/`.dmg`,
and a portable `.zip` plus an `.msi` on Windows — are produced by
`scripts/build.sh` and `scripts\build.ps1`; `packaging/README.md` has the
per-platform detail.
Android builds use JDK 17, Android SDK 36/NDK 28, Gradle 8.13, `cargo-ndk`, and
UniFFI. Run `bash scripts/build-android.sh debug` after installing that toolchain;
see [`docs/ANDROID.md`](docs/ANDROID.md) for exact setup and release signing.
iOS builds need macOS with Xcode, XcodeGen and the `aarch64-apple-ios` Rust
target: `scripts/build-ios.sh all` writes `dist/proton-stream-<version>-ios.ipa`.
## Privacy
- The share URL fragment **is** the decryption password. It and any custom
password live in the OS credential store — Secret Service on Linux, Credential
Manager on Windows — never in a config file.
- Nothing leaves your machine except requests to Proton, unless you turn metadata
enrichment on. The player is fed through an in-process mpv stream callback, not
a local HTTP server: there is no port for another process on the machine to ask
for the plaintext, and mpv is handed an opaque token rather than a URL that
would put a share secret in its log and window title.
- The block cache holds decrypted content. It lives in your cache directory,
can be deleted at any time the app is not running, and can be sized or
emptied from Settings → Storage.
- A share link given as a command-line argument is visible to other users of
the machine in the process list while that launch runs, and may land in
shell history. Pasting it into the window (Ctrl+V) does neither.
- The desktop's media widget is handed the title, the episode and a `file://`
path to artwork already on disk — never a provider URL, so the shell never
contacts a metadata provider on its own.
- **Release artifacts:** `scripts/build.sh` (tarball, `.deb`, `.rpm`, Arch, macOS) and
`scripts/build-windows.sh` or `scripts\build.ps1` (`.zip`, `.msi`). See
[`packaging/README.md`](packaging/README.md).
- **Android:** JDK 17, Android SDK 36, NDK 28, `cargo-ndk`, then
`scripts/build-android.sh debug`. See [`docs/ANDROID.md`](docs/ANDROID.md).
- **iOS:** macOS with Xcode and XcodeGen, then `scripts/build-ios.sh all`. See
[`docs/IOS.md`](docs/IOS.md).
## License
The shared Rust crates and desktop application are MIT licensed. The Android and
iOS applications and their combined native distributions are GPL-3.0-or-later; see
[`android/LICENSE.md`](android/LICENSE.md), [`ios/LICENSE.md`](ios/LICENSE.md) and
the bundled-component notices.
The desktop application embeds the Inter typeface, under the SIL Open Font
The shared Rust crates and desktop application are MIT licensed. The Android and iOS applications
and their combined native distributions are GPL-3.0-or-later; see
[`android/LICENSE.md`](android/LICENSE.md), [`ios/LICENSE.md`](ios/LICENSE.md) and the bundled
component notices. The desktop application embeds the Inter typeface, under the SIL Open Font
License 1.1 ([`crates/pstr-app/assets/fonts/Inter-OFL.txt`](crates/pstr-app/assets/fonts/Inter-OFL.txt)),
and the Phosphor icon font, under MIT.
+7 -2
View File
@@ -1909,7 +1909,11 @@ impl AndroidEngine {
pub fn set_playback_prefs(&self, prefs: PlaybackPrefsRecord) -> Result<(), BridgeError> {
// Sanitized rather than trusted: the volume arrives from a slider, and
// a language from a text field that can hold spaces and nothing else.
let prefs = playback_prefs(prefs).sanitized();
// Onto what is stored, not the defaults: the record has no subtitle
// style yet, and saving one without it would reset the desktop's and,
// through sync, every other installation's.
let stored = pstr_core::prefs::load(&self.dirs).unwrap_or_default();
let prefs = playback_prefs(prefs, stored).sanitized();
pstr_core::prefs::save(&self.dirs, &prefs).map_err(BridgeError::from_display)
}
@@ -3580,7 +3584,7 @@ fn playback_prefs_record(prefs: PlaybackPrefs) -> PlaybackPrefsRecord {
}
}
fn playback_prefs(record: PlaybackPrefsRecord) -> PlaybackPrefs {
fn playback_prefs(record: PlaybackPrefsRecord, stored: PlaybackPrefs) -> PlaybackPrefs {
PlaybackPrefs {
volume: record.volume,
muted: record.muted,
@@ -3590,6 +3594,7 @@ fn playback_prefs(record: PlaybackPrefsRecord) -> PlaybackPrefs {
autoplay_next: record.autoplay_next,
auto_skip: record.auto_skip,
speed: record.speed,
..stored
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 13 KiB

+58
View File
@@ -235,6 +235,14 @@ pub enum Action {
subtitles: bool,
subtitle: Option<String>,
},
/// How subtitles look, for the file playing and every one after. Written
/// to the preferences once the mouse is let go; see
/// [`App::save_subtitle_style`].
SetSubtitleStyle(pstr_core::prefs::SubtitleStyle),
/// Shift the playing file's subtitles by this many seconds more.
NudgeSubtitleDelay(f64),
/// Put the playing file's subtitles back on the file's own timing.
ResetSubtitleDelay,
/// Play faster or slower, and keep doing so for the next file.
SetSpeed(f64),
/// Seek past openings and credits without being asked.
@@ -654,6 +662,8 @@ pub struct App {
/// Chapters already skipped on their own in this player, so seeking back
/// into an opening on purpose is not undone a frame later.
auto_skipped: (u64, Vec<i64>),
/// The subtitle style changed and has not been written yet.
subtitle_style_unsaved: bool,
/// Whether the episode list is out on the player page.
pub episode_drawer: bool,
/// Set while the window is fullscreen, so `F` can toggle rather than only
@@ -760,6 +770,7 @@ impl App {
up_next: UpNext::default(),
warmed: 0,
auto_skipped: (0, Vec::new()),
subtitle_style_unsaved: false,
fullscreen: false,
episode_drawer: false,
opening: None,
@@ -1437,6 +1448,21 @@ impl App {
self.apply(ctx, Action::Play(target));
}
/// Write the subtitle style, once whatever is changing it has let go.
///
/// A slider or a colour wheel changes the style every frame it is dragged,
/// and each change is shown on the playing file straight away. Writing
/// each one would be a file write per frame, so it waits for the mouse —
/// which also covers a menu closed mid-drag, where the control that would
/// have said "released" is no longer drawn.
fn save_subtitle_style(&mut self, ctx: &egui::Context) {
if self.subtitle_style_unsaved && !ctx.input(|input| input.pointer.any_down()) {
self.subtitle_style_unsaved = false;
self.engine
.set_playback_prefs(self.engine.playback_prefs(), true);
}
}
fn send_player(&self, command: crate::playback::Command) {
if let Some(playback) = &self.playback {
playback.send(command);
@@ -1938,6 +1964,32 @@ impl App {
prefs.subtitle_language = subtitle;
self.engine.set_playback_prefs(prefs, true);
}
Action::SetSubtitleStyle(style) => {
let mut prefs = self.engine.playback_prefs();
prefs.subtitle_style = style;
self.engine.set_playback_prefs(prefs, false);
self.subtitle_style_unsaved = true;
let style = self.engine.playback_prefs().subtitle_style;
if let Some(playback) = &mut self.playback {
playback.restyle_subtitles(&style);
}
}
Action::NudgeSubtitleDelay(delta) => {
if let Some(playback) = &mut self.playback {
playback.set_subtitle_delay(playback.subtitle_delay + delta);
let text = format!(
"Subtitle delay {}",
ui::format_delay(playback.subtitle_delay)
);
self.flash(ctx, text);
}
}
Action::ResetSubtitleDelay => {
if let Some(playback) = &mut self.playback {
playback.set_subtitle_delay(0.0);
self.flash(ctx, "Subtitle delay 0 s");
}
}
Action::SetAppearance(appearance) => {
self.engine.set_appearance(appearance);
theme::apply(ctx, appearance);
@@ -2129,6 +2181,7 @@ impl eframe::App for App {
}
self.warm_next();
self.auto_skip(ctx);
self.save_subtitle_style(ctx);
self.window.observe(ctx);
let mut actions: Vec<Action> = Vec::new();
@@ -2909,6 +2962,8 @@ fn shortcuts(
Key::OpenBracket,
Key::CloseBracket,
Key::E,
Key::Z,
Key::X,
Key::Escape,
]
.into_iter()
@@ -2952,6 +3007,9 @@ fn shortcuts(
// Escape leaves fullscreen first and the page second, which is what
// it does everywhere else and what stops one press from both
// un-maximising the window and hiding the film.
// mpv's own keys for it, and the step mpv uses.
Key::Z => actions.push(Action::NudgeSubtitleDelay(-0.1)),
Key::X => actions.push(Action::NudgeSubtitleDelay(0.1)),
Key::E => actions.push(Action::ToggleEpisodes),
// The episode list is the innermost thing open, so it goes first.
Key::Escape if drawer => actions.push(Action::ToggleEpisodes),
+87 -3
View File
@@ -147,6 +147,10 @@ pub enum Command {
/// Move subtitles, as a percentage of the window's height. See
/// [`Playback::lift_subtitles`].
SetSubtitlePosition(f64),
/// Restyle subtitles, the line already showing included.
SetSubtitleStyle(pstr_core::prefs::SubtitleStyle),
/// Shift subtitles this many seconds later; negative is earlier.
SetSubtitleDelay(f64),
/// 1.0 is normal speed.
SetSpeed(f64),
/// Save the current frame to this file.
@@ -184,6 +188,14 @@ pub struct Playback {
/// Where subtitles were last put, so they are only moved when that changes
/// rather than once a frame.
subtitle_position: f64,
/// How the viewer has subtitles drawn, as last handed to this player.
pub subtitle_style: pstr_core::prefs::SubtitleStyle,
/// Where the controls would lift subtitles to. The higher of this and the
/// style's own position wins.
lifted_position: f64,
/// How far subtitles are shifted, in seconds. Per file rather than a
/// preference: an offset belongs to one release, not to the viewer.
pub subtitle_delay: f64,
/// What the file contains. Empty until mpv has demuxed it.
pub tracks: Vec<Track>,
/// The file's chapters, in order. Empty for a file muxed without them.
@@ -259,7 +271,10 @@ impl Playback {
paused: false,
volume: prefs.volume,
muted: prefs.muted,
subtitle_position: 100.0,
subtitle_position: prefs.subtitle_style.position,
subtitle_style: prefs.subtitle_style.clone(),
lifted_position: 100.0,
subtitle_delay: 0.0,
speed: prefs.speed,
tracks: Vec::new(),
chapters: Vec::new(),
@@ -282,17 +297,57 @@ impl Playback {
/// the mouse is moving, which is exactly when someone is looking at the
/// screen.
pub fn lift_subtitles(&mut self, covered: f32, height: f32) {
let position = if covered > 0.0 && height > 0.0 {
self.lifted_position = if covered > 0.0 && height > 0.0 {
(100.0 * (1.0 - f64::from(covered / height))).round()
} else {
100.0
};
self.place_subtitles();
}
/// Move subtitles to [`Self::subtitle_position`], when that has changed.
fn place_subtitles(&mut self) {
let position = self.subtitle_position();
if position != self.subtitle_position {
self.subtitle_position = position;
self.send(Command::SetSubtitlePosition(position));
}
}
/// Where subtitles go: where the style puts them, unless the controls
/// would cover that, in which case just above the controls.
///
/// A styled track ignores the style's position unless it is restyled:
/// mpv applies `sub-pos` to it either way, and its signs were placed by
/// hand. The lift still applies, because a line under the seek bar cannot
/// be read however carefully it was placed.
fn subtitle_position(&self) -> f64 {
let styled = self
.selected_track(TrackKind::Subtitle)
.is_some_and(|track| is_styled(track.codec.as_deref()));
let position = if styled && !self.subtitle_style.restyle_styled {
100.0
} else {
self.subtitle_style.position
};
position.min(self.lifted_position)
}
/// Restyle the subtitles of this file, now.
pub fn restyle_subtitles(&mut self, style: &pstr_core::prefs::SubtitleStyle) {
self.subtitle_style = style.clone();
self.subtitle_position = self.subtitle_position();
let mut style = style.clone();
style.position = self.subtitle_position;
self.send(Command::SetSubtitleStyle(style));
}
/// Shift subtitles to `seconds`, rounded to the tenth a keypress moves.
pub fn set_subtitle_delay(&mut self, seconds: f64) {
self.subtitle_delay = (seconds * 10.0).round() / 10.0;
self.send(Command::SetSubtitleDelay(self.subtitle_delay));
}
/// Whether the picture is drawn in this window rather than mpv's own.
pub fn is_embedded(&self) -> bool {
self.video.is_some()
@@ -372,7 +427,11 @@ impl Playback {
PlayerEvent::FileLoaded => self.loaded = true,
PlayerEvent::Volume(volume) => self.volume = *volume,
PlayerEvent::Muted(muted) => self.muted = *muted,
PlayerEvent::Tracks(tracks) => self.tracks = tracks.clone(),
PlayerEvent::Tracks(tracks) => {
self.tracks = tracks.clone();
// A switch between a plain and a styled track moves the line.
self.place_subtitles();
}
PlayerEvent::Chapters(chapters) => {
self.chapters = chapters.clone();
self.reclassify();
@@ -479,6 +538,11 @@ fn build_player(
Ok((Arc::new(player), None))
}
/// Whether a subtitle codec carries its own styling, as mpv names them.
fn is_styled(codec: Option<&str>) -> bool {
matches!(codec, Some("ass" | "ssa"))
}
/// The player defaults with the viewer's preferences folded in.
fn from_prefs(
prefs: &PlaybackPrefs,
@@ -494,6 +558,7 @@ fn from_prefs(
.and_then(|p| p.subtitle_language.clone())
.or_else(|| prefs.subtitle_language.clone()),
subtitles: show.map(|p| p.subtitles).unwrap_or(prefs.subtitles),
subtitle_style: prefs.subtitle_style.clone(),
// Carried from file to file, like the volume: somebody who watches at
// 1.25 watches the next episode at 1.25 too.
options: vec![("speed".into(), format!("{:.2}", prefs.speed))],
@@ -658,6 +723,11 @@ fn apply_command(
Command::SetVolume(volume) => player.set_volume(volume),
Command::SetMuted(muted) => player.set_muted(muted),
Command::SetSubtitlePosition(percent) => player.set_subtitle_position(percent),
Command::SetSubtitleStyle(style) => {
player.apply_subtitle_style(&style);
Ok(())
}
Command::SetSubtitleDelay(seconds) => player.set_subtitle_delay(seconds),
Command::SetSpeed(speed) => player.set_speed(speed),
Command::Screenshot(path) => player.screenshot(&path),
Command::SelectTrack(kind, track) => select_track(engine, id, player, kind, track),
@@ -820,3 +890,17 @@ fn save(
watch_state(position, duration, watched),
);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_ass_and_ssa_tracks_count_as_styled() {
assert!(is_styled(Some("ass")));
assert!(is_styled(Some("ssa")));
assert!(!is_styled(Some("subrip")));
assert!(!is_styled(Some("hdmv_pgs_subtitle")));
assert!(!is_styled(None));
}
}
+285 -15
View File
@@ -186,9 +186,48 @@ pub fn semibold() -> egui::FontFamily {
egui::FontFamily::Name("semibold".into())
}
/// The family the subtitle preview is drawn in: the face the chosen subtitle
/// font resolves to, ahead of the app's own fonts, which stand in until it has
/// loaded and for any glyph it lacks.
pub fn subtitle_family() -> egui::FontFamily {
egui::FontFamily::Name("subtitle".into())
}
/// The system fonts loaded so far. Each install builds the definitions from
/// all of them, so loading one does not drop the other.
#[derive(Default)]
struct SystemFonts {
cjk: Option<Arc<egui::FontData>>,
subtitle: Option<(SubtitleRequest, Arc<egui::FontData>, SubtitleFace)>,
/// The subtitle face last asked for, loading or loaded.
wanted: Option<SubtitleRequest>,
}
static SYSTEM_FONTS: parking_lot::Mutex<SystemFonts> = parking_lot::Mutex::new(SystemFonts {
cjk: None,
subtitle: None,
wanted: None,
});
#[derive(Debug, Clone, PartialEq, Eq)]
struct SubtitleRequest {
family: String,
bold: bool,
italic: bool,
}
/// What the loaded subtitle face draws by itself. A style it lacks is one
/// libass makes up, and so must the preview.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SubtitleFace {
pub bold: bool,
pub italic: bool,
}
/// Inter, the icon font, and egui's own fonts behind them for the emoji and
/// symbols Inter does not carry. `cjk` goes last, when there is one.
fn font_definitions(cjk: Option<egui::FontData>) -> egui::FontDefinitions {
/// symbols Inter does not carry. The CJK fallback goes last, when there is
/// one.
fn font_definitions(system: &SystemFonts) -> egui::FontDefinitions {
use egui::FontFamily::{Monospace, Proportional};
let mut fonts = egui::FontDefinitions::default();
@@ -207,21 +246,29 @@ fn font_definitions(cjk: Option<egui::FontData>) -> egui::FontDefinitions {
// Right behind Inter. The icons are in the private use area, which the
// bundled Inter no longer maps, so neither font shadows the other.
egui_phosphor::add_to_fonts(&mut fonts, egui_phosphor::Variant::Regular);
if let Some(cjk) = cjk {
if let Some(cjk) = &system.cjk {
let name = "system-cjk-fallback".to_owned();
fonts.font_data.insert(name.clone(), Arc::new(cjk));
fonts.font_data.insert(name.clone(), cjk.clone());
for family in [Proportional, Monospace] {
fonts.families.entry(family).or_default().push(name.clone());
}
}
let fallbacks = fonts.families[&Proportional]
let fallbacks: Vec<String> = fonts.families[&Proportional]
.iter()
.filter(|name| *name != "inter")
.cloned();
.cloned()
.collect();
let semibold_chain = std::iter::once("inter-semibold".to_owned())
.chain(fallbacks)
.collect();
fonts.families.insert(semibold(), semibold_chain);
let mut subtitle_chain = fonts.families[&Proportional].clone();
if let Some((_, face, _)) = &system.subtitle {
let name = "system-subtitle".to_owned();
fonts.font_data.insert(name.clone(), face.clone());
subtitle_chain.insert(0, name);
}
fonts.families.insert(subtitle_family(), subtitle_chain);
fonts
}
@@ -234,7 +281,7 @@ fn font_definitions(cjk: Option<egui::FontData>) -> egui::FontDefinitions {
/// anyway. egui deliberately does not bundle the multi-megabyte CJK families,
/// and native desktops already provide one.
pub fn install_fonts(ctx: &egui::Context) {
ctx.set_fonts(font_definitions(None));
ctx.set_fonts(font_definitions(&SYSTEM_FONTS.lock()));
let ctx = ctx.clone();
let spawned = std::thread::Builder::new()
.name("fonts".into())
@@ -251,20 +298,80 @@ fn install_cjk_fallback(ctx: &egui::Context) {
let Ok(bytes) = std::fs::read(&path) else {
return;
};
let Some(data) = cjk_font_data(bytes, index) else {
let Some(data) = system_font_data(bytes, index) else {
tracing::debug!("CJK fallback {}#{index} does not parse", path.display());
return;
};
ctx.set_fonts(font_definitions(Some(data)));
let mut system = SYSTEM_FONTS.lock();
system.cjk = Some(Arc::new(data));
ctx.set_fonts(font_definitions(&system));
ctx.request_repaint();
}
/// The fallback font, if egui can read it.
/// The face the subtitle preview should be drawn in for this font, bold and
/// italic, once [`subtitle_family`] holds it.
///
/// `None` while it loads, and for good where the system cannot say which file
/// a family is — everywhere but Linux. The first call for a font starts the
/// load on a thread of its own, since `fc-match` and reading the file are too
/// slow for a frame, and asks for a repaint when it is in.
pub fn subtitle_face(
ctx: &egui::Context,
family: &str,
bold: bool,
italic: bool,
) -> Option<SubtitleFace> {
let request = SubtitleRequest {
family: family.to_owned(),
bold,
italic,
};
let mut system = SYSTEM_FONTS.lock();
if let Some((loaded, _, face)) = &system.subtitle
&& *loaded == request
{
return Some(*face);
}
if system.wanted.as_ref() != Some(&request) {
system.wanted = Some(request.clone());
let ctx = ctx.clone();
let spawned = std::thread::Builder::new()
.name("subtitle-font".into())
.spawn(move || install_subtitle_face(&ctx, request));
if let Err(error) = spawned {
tracing::debug!("subtitle font thread: {error}");
}
}
None
}
fn install_subtitle_face(ctx: &egui::Context, request: SubtitleRequest) {
let Some((path, index, face)) = system_subtitle_font(&request) else {
return;
};
let Ok(bytes) = std::fs::read(&path) else {
return;
};
let Some(data) = system_font_data(bytes, index) else {
tracing::debug!("subtitle font {}#{index} does not parse", path.display());
return;
};
let mut system = SYSTEM_FONTS.lock();
// Another font was picked while this one loaded.
if system.wanted.as_ref() != Some(&request) {
return;
}
system.subtitle = Some((request, Arc::new(data), face));
ctx.set_fonts(font_definitions(&system));
ctx.request_repaint();
}
/// A system font, if egui can read it.
///
/// egui panics on a font it cannot parse, and this one comes from whatever the
/// system has installed. So it is parsed here first, the same way egui does,
/// and a font that fails is left out rather than taking the app down.
fn cjk_font_data(bytes: Vec<u8>, index: u32) -> Option<egui::FontData> {
fn system_font_data(bytes: Vec<u8>, index: u32) -> Option<egui::FontData> {
skrifa::FontRef::from_index(&bytes, index).ok()?;
let mut data = egui::FontData::from_owned(bytes);
data.index = index;
@@ -299,6 +406,68 @@ fn system_cjk_font() -> Option<(std::path::PathBuf, u32)> {
path.is_file().then_some((path, index))
}
/// The file fontconfig picks for a subtitle font, as libass asks for it: the
/// family with the weight and slant wanted, falling back as libass would to
/// whatever fontconfig likes best when the family is not installed.
#[cfg(target_os = "linux")]
fn system_subtitle_font(
request: &SubtitleRequest,
) -> Option<(std::path::PathBuf, u32, SubtitleFace)> {
let output = std::process::Command::new("fc-match")
.args([
"-f",
"%{file}\\n%{index}\\n%{weight}\\n%{slant}",
&fontconfig_pattern(request),
])
.output()
.ok()?;
let text = std::str::from_utf8(&output.stdout).ok()?;
let mut lines = text.lines();
let path = std::path::PathBuf::from(lines.next()?);
let mut number = || lines.next().and_then(|value| value.parse::<u32>().ok());
let index = number().unwrap_or(0);
let (weight, slant) = (number().unwrap_or(0), number().unwrap_or(0));
// A variable font's named instance is drawn by egui as the default one,
// which is upright and regular, whatever fontconfig says it matched.
let instance = index != fontconfig_face(index);
let face = SubtitleFace {
bold: !instance && weight >= FC_WEIGHT_BOLD,
italic: !instance && slant > 0,
};
path.is_file()
.then_some((path, fontconfig_face(index), face))
}
#[cfg(any(target_os = "linux", test))]
const FC_WEIGHT_BOLD: u32 = 200;
/// A fontconfig pattern for the request. A family name is free text, and `-`,
/// `:`, `,` and `\\` mean something in a pattern, so those are escaped.
#[cfg(any(target_os = "linux", test))]
fn fontconfig_pattern(request: &SubtitleRequest) -> String {
let mut pattern = String::new();
for character in request.family.chars() {
if matches!(character, '-' | ':' | ',' | '\\') {
pattern.push('\\');
}
pattern.push(character);
}
if request.bold {
pattern.push_str(&format!(":weight={FC_WEIGHT_BOLD}"));
}
if request.italic {
pattern.push_str(":slant=100");
}
pattern
}
/// Elsewhere there is no asking which file a family is, and the preview
/// stays in the app's own font.
#[cfg(not(target_os = "linux"))]
fn system_subtitle_font(_: &SubtitleRequest) -> Option<(std::path::PathBuf, u32, SubtitleFace)> {
None
}
#[cfg(target_os = "windows")]
fn system_cjk_font() -> Option<(std::path::PathBuf, u32)> {
let path = std::path::PathBuf::from(r"C:\Windows\Fonts\YuGothR.ttc");
@@ -316,6 +485,68 @@ fn system_cjk_font() -> Option<(std::path::PathBuf, u32)> {
None
}
/// The font families installed here, by name, for the subtitle font picker.
///
/// `None` until they have been read. The first call starts that on a thread
/// of its own and asks for a repaint when it is done: `fc-list` over a large
/// font collection takes long enough to be seen as a stalled frame.
pub fn font_families(ctx: &egui::Context) -> Option<&'static [String]> {
static FAMILIES: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
static STARTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
if let Some(families) = FAMILIES.get() {
return Some(families);
}
if !STARTED.swap(true, std::sync::atomic::Ordering::Relaxed) {
let ctx = ctx.clone();
let spawned = std::thread::Builder::new()
.name("font-families".into())
.spawn(move || {
let _ = FAMILIES.set(system_font_families());
ctx.request_repaint();
});
if let Err(error) = spawned {
tracing::debug!("font families thread: {error}");
}
}
None
}
#[cfg(target_os = "linux")]
fn system_font_families() -> Vec<String> {
let Ok(output) = std::process::Command::new("fc-list")
.args([":", "family"])
.output()
else {
return Vec::new();
};
font_families_from_fc_list(&String::from_utf8_lossy(&output.stdout))
}
/// Elsewhere the picker takes a typed name only. mpv's font lookup there is
/// the system's own, so any installed family's name works.
#[cfg(not(target_os = "linux"))]
fn system_font_families() -> Vec<String> {
Vec::new()
}
/// One family per line of `fc-list : family`, sorted and without repeats.
///
/// A line lists a family's names in every language it has, comma-separated,
/// and one family appears once per style. The first name is the one libass
/// matches on.
#[cfg(any(target_os = "linux", test))]
fn font_families_from_fc_list(listing: &str) -> Vec<String> {
let mut families: Vec<String> = listing
.lines()
.filter_map(|line| line.split(',').next())
.map(|family| family.trim().to_owned())
.filter(|family| !family.is_empty() && !family.starts_with('.'))
.collect();
families.sort_by_key(|family| family.to_lowercase());
families.dedup();
families
}
/// Every colour the app draws with, as egui wants them.
///
/// The *choice* of colours is `pstr_core::appearance` — one resolution shared
@@ -881,6 +1112,15 @@ const RAMP_STOPS: usize = 64;
mod tests {
use super::*;
#[test]
fn each_font_family_is_listed_once_by_its_first_name() {
let listing = "Noto Sans,Noto Sans Regular\nDejaVu Sans\nnoto sans mono\nNoto Sans,Noto Sans Bold\n\n.LastResort\n";
assert_eq!(
font_families_from_fc_list(listing),
["DejaVu Sans", "Noto Sans", "noto sans mono"]
);
}
#[test]
fn a_variable_fonts_named_instance_is_not_taken_for_a_face() {
assert_eq!(fontconfig_face(262_144), 0);
@@ -889,10 +1129,40 @@ mod tests {
}
#[test]
fn a_fallback_font_egui_cannot_read_is_left_out() {
assert!(cjk_font_data(INTER.to_vec(), 0).is_some());
assert!(cjk_font_data(INTER.to_vec(), 4).is_none());
assert!(cjk_font_data(b"not a font".to_vec(), 0).is_none());
fn a_system_font_egui_cannot_read_is_left_out() {
assert!(system_font_data(INTER.to_vec(), 0).is_some());
assert!(system_font_data(INTER.to_vec(), 4).is_none());
assert!(system_font_data(b"not a font".to_vec(), 0).is_none());
}
#[test]
fn a_subtitle_font_is_asked_of_fontconfig_with_its_style_and_escaped() {
let request = |family: &str, bold, italic| SubtitleRequest {
family: family.to_owned(),
bold,
italic,
};
assert_eq!(
fontconfig_pattern(&request("Noto Sans", false, false)),
"Noto Sans"
);
assert_eq!(
fontconfig_pattern(&request("Noto Sans", true, true)),
"Noto Sans:weight=200:slant=100"
);
assert_eq!(
fontconfig_pattern(&request("A-B:C,D\\E", false, true)),
"A\\-B\\:C\\,D\\\\E:slant=100"
);
}
#[test]
fn the_subtitle_preview_family_exists_before_any_font_has_loaded() {
let fonts = font_definitions(&SystemFonts::default());
assert_eq!(
fonts.families[&subtitle_family()],
fonts.families[&egui::FontFamily::Proportional]
);
}
#[test]
+19
View File
@@ -206,6 +206,18 @@ pub fn format_speed(speed: f64) -> String {
format!("{}×", text.trim_end_matches('0').trim_end_matches('.'))
}
/// `+0.3 s`, `−1.2 s` or `0 s`: a subtitle delay, signed so the direction
/// reads without knowing which way mpv counts.
pub fn format_delay(seconds: f64) -> String {
if seconds.abs() < 0.05 {
"0 s".to_owned()
} else if seconds > 0.0 {
format!("+{seconds:.1} s")
} else {
format!("−{:.1} s", -seconds)
}
}
/// `1.4 GiB`, for what a file costs to watch.
pub fn format_size(bytes: i64) -> String {
const UNITS: [&str; 4] = ["B", "KiB", "MiB", "GiB"];
@@ -917,6 +929,13 @@ pub fn columns_of(available: f32, minimum: f32) -> Grid {
#[cfg(test)]
mod tests {
#[test]
fn a_subtitle_delay_reads_with_its_direction() {
assert_eq!(super::format_delay(0.3), "+0.3 s");
assert_eq!(super::format_delay(-1.2), "−1.2 s");
assert_eq!(super::format_delay(0.0000001), "0 s");
}
use super::*;
#[test]
+364 -1
View File
@@ -7,7 +7,7 @@
use pstr_core::appearance::{Accent, Appearance, Flavor, Tiles};
use pstr_core::metadata::{MetadataConfig, ProviderId, TitleNames};
use pstr_core::prefs::PlaybackPrefs;
use pstr_core::prefs::{Colour, PlaybackPrefs, SubtitleBackdrop, SubtitleStyle};
use pstr_player::LANGUAGES;
use crate::app::Action;
@@ -58,6 +58,7 @@ pub fn show(
ui.add_space(theme::space::M);
appearance_form(ui, prefs.appearance, prefs.desktop, actions);
playback_form(ui, prefs, actions);
subtitle_form(ui, &prefs.playback.subtitle_style, actions);
storage_form(ui, prefs, actions);
metadata_form(ui, settings, api_key, actions);
about(ui);
@@ -428,6 +429,368 @@ fn languages(ui: &mut egui::Ui, playback: &PlaybackPrefs, actions: &mut Vec<Acti
);
}
/// How subtitles look, with a sample line to judge it by.
///
/// Every change reaches a playing file as it is made, so the film itself is
/// the other preview. A styled track takes none of it unless it is asked to;
/// see [`SubtitleStyle`].
fn subtitle_form(ui: &mut egui::Ui, style: &SubtitleStyle, actions: &mut Vec<Action>) {
ui::widgets::settings_group(
ui,
"Subtitles",
Some(
"Changes show on the playing video straight away. Plain subtitles (SRT) take all of this; styled ones (ASS) keep their own look unless you restyle them below.",
),
|ui| {
let mut chosen = style.clone();
ui.add_space(theme::space::L);
subtitle_preview(ui, &chosen);
ui.add_space(theme::space::L);
ui::widgets::settings_row(ui, "Size", None, |ui| {
percent_slider(
ui,
&mut chosen.scale,
SubtitleStyle::MIN_SCALE..=SubtitleStyle::MAX_SCALE,
);
});
ui::widgets::settings_row(
ui,
"Position",
Some("How far up the picture the line sits."),
|ui| subtitle_position_slider(ui, &mut chosen.position),
);
ui::widgets::settings_row(
ui,
"Font",
Some(if cfg!(target_os = "linux") {
"Any font installed here."
} else {
"Any font installed here. The sample above is drawn in the app's own font."
}),
|ui| {
ui::widgets::toggle(ui, &mut chosen.italic, "Italic");
ui::widgets::toggle(ui, &mut chosen.bold, "Bold");
font_picker(ui, &mut chosen.font);
},
);
ui::widgets::settings_row(ui, "Text colour", None, |ui| {
colour_button(ui, &mut chosen.colour);
});
ui::widgets::settings_row(
ui,
"Background",
Some("A box reads on bright scenes; an outline hides less of the picture."),
|ui| {
let choices =
SubtitleBackdrop::ALL.map(|backdrop| (backdrop, backdrop.label()));
if let Some(backdrop) = ui::widgets::segmented(ui, chosen.backdrop, &choices) {
chosen.backdrop = backdrop;
}
},
);
match chosen.backdrop {
SubtitleBackdrop::Outline => {
ui::widgets::settings_row(ui, "Outline", None, |ui| {
colour_button(ui, &mut chosen.outline_colour);
ui.add(
egui::Slider::new(
&mut chosen.outline_size,
0.0..=SubtitleStyle::MAX_OUTLINE,
)
.step_by(0.05)
.fixed_decimals(1),
);
});
}
SubtitleBackdrop::Box => {
ui::widgets::settings_row(
ui,
"Box colour",
Some("Its opacity is how much of the picture shows through."),
|ui| colour_button(ui, &mut chosen.box_colour),
);
}
}
ui::widgets::settings_row(ui, "Shadow", Some("How far it falls. 0 is none."), |ui| {
colour_button(ui, &mut chosen.shadow_colour);
ui.add(
egui::Slider::new(&mut chosen.shadow_offset, 0.0..=SubtitleStyle::MAX_SHADOW)
.step_by(0.1)
.fixed_decimals(1),
);
});
ui::widgets::settings_row(
ui,
"Blur",
Some("Softens the edges. Not shown in the sample."),
|ui| {
ui.add(
egui::Slider::new(&mut chosen.blur, 0.0..=SubtitleStyle::MAX_BLUR)
.step_by(0.1)
.fixed_decimals(1),
);
},
);
ui::widgets::settings_row(
ui,
"Restyle styled subtitles",
Some(
"Draw styled (ASS) dialogue in this style too, size and position included. Signs, songs and karaoke can come out wrong.",
),
|ui| {
ui::widgets::toggle(ui, &mut chosen.restyle_styled, "");
},
);
ui::widgets::settings_row(ui, "Reset", Some("Back to mpv's own look."), |ui| {
if ui
.add_enabled(
*style != SubtitleStyle::default(),
egui::Button::new("Reset"),
)
.clicked()
{
chosen = SubtitleStyle::default();
}
});
if chosen != *style {
actions.push(Action::SetSubtitleStyle(chosen.sanitized()));
}
},
);
}
/// A scale as a percentage slider, 100% being mpv's own size.
pub(crate) fn percent_slider(
ui: &mut egui::Ui,
scale: &mut f64,
range: std::ops::RangeInclusive<f64>,
) -> egui::Response {
let mut percent = *scale * 100.0;
let response = ui.add(
egui::Slider::new(&mut percent, range.start() * 100.0..=range.end() * 100.0)
.step_by(5.0)
.suffix("%")
.fixed_decimals(0),
);
*scale = percent / 100.0;
response
}
/// Where the line sits, 0 at the top of the picture and 100 at the bottom —
/// shown the other way up, as height above the bottom edge, which is how
/// anyone would describe moving subtitles up.
pub(crate) fn subtitle_position_slider(ui: &mut egui::Ui, position: &mut f64) -> egui::Response {
let mut height = 100.0 - *position;
let response = ui.add(
egui::Slider::new(&mut height, 0.0..=90.0)
.step_by(1.0)
.suffix("% up")
.fixed_decimals(0),
);
*position = 100.0 - height;
response
}
/// A swatch that opens a colour wheel with an opacity slider.
fn colour_button(ui: &mut egui::Ui, colour: &mut Colour) {
let [r, g, b, a] = colour.to_array();
let mut picked = egui::Color32::from_rgba_unmultiplied(r, g, b, a);
// The `Color32` form rather than `Hsva`, because egui remembers the hue
// behind it: rebuilt from RGB each frame, black and grey have none, and
// the wheel would snap back to red under the mouse.
let response = egui::color_picker::color_edit_button_srgba(
ui,
&mut picked,
egui::color_picker::Alpha::OnlyBlend,
);
// Only on a change: a round trip through premultiplied alpha can nudge
// an untouched colour by a step.
if response.changed() {
*colour = Colour::from(picked.to_srgba_unmultiplied());
}
}
/// The font: the installed families to pick from, and a box to type any name
/// into — the only way on a system whose families the app cannot list.
fn font_picker(ui: &mut egui::Ui, font: &mut Option<String>) {
let filter_id = egui::Id::new("subtitle-font-filter");
let mut filter: String = ui.data(|data| data.get_temp(filter_id)).unwrap_or_default();
let families = theme::font_families(ui.ctx());
egui::ComboBox::from_id_salt("subtitle-font")
.selected_text(font.as_deref().unwrap_or("Default"))
.width(200.0)
.height(320.0)
// Not on any click: the search box is clicked into.
.close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
.show_ui(ui, |ui| {
ui.add(
egui::TextEdit::singleline(&mut filter)
.hint_text("Search or type a font name")
.desired_width(f32::INFINITY),
)
.request_focus();
let typed = filter.trim();
if ui.selectable_label(font.is_none(), "Default").clicked() {
*font = None;
ui.close();
}
let wanted = typed.to_lowercase();
let mut exact = false;
for family in families.unwrap_or_default() {
if !family.to_lowercase().contains(&wanted) {
continue;
}
exact |= family.eq_ignore_ascii_case(typed);
let label = egui::RichText::new(family.as_str());
if ui
.selectable_label(font.as_deref() == Some(family.as_str()), label)
.clicked()
{
*font = Some(family.clone());
ui.close();
}
}
if families.is_none() {
ui.label(ui::muted("Reading the installed fonts…"));
}
if !typed.is_empty() && !exact && ui.button(format!("Use “{typed}”")).clicked() {
*font = Some(typed.to_owned());
ui.close();
}
});
ui.data_mut(|data| data.insert_temp(filter_id, filter));
}
/// A sample line, half on a bright sky and half on night, drawn in the
/// chosen style — so whether it reads on both is visible before a film is.
///
/// An approximation. The font is the face fontconfig picks for the chosen one,
/// as libass's is, but only on Linux; elsewhere, and while it loads, it is the
/// app's own. A bold or italic the face lacks is made up, as libass does, and
/// there is no blur. Proportions follow mpv's, where sizes are in pixels of a
/// 38-pixel font.
fn subtitle_preview(ui: &mut egui::Ui, style: &SubtitleStyle) {
const HEIGHT: f32 = 132.0;
/// mpv's `sub-font-size`, the unit every other size is relative to.
const MPV_FONT: f32 = 38.0;
let width = ui.available_width();
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, HEIGHT), egui::Sense::hover());
let painter = ui.painter_at(rect);
let radius = egui::CornerRadius::same(theme::radius::MD);
// Sky above haze on the left, a night street on the right.
let half = egui::Rect::from_min_max(rect.min, egui::pos2(rect.center().x, rect.max.y));
let mut sky = egui::Mesh::default();
sky.colored_vertex(half.left_top(), egui::Color32::from_rgb(0x8E, 0xC5, 0xF0));
sky.colored_vertex(half.right_top(), egui::Color32::from_rgb(0xB8, 0xDC, 0xF8));
sky.colored_vertex(
half.right_bottom(),
egui::Color32::from_rgb(0xFA, 0xF7, 0xEE),
);
sky.colored_vertex(
half.left_bottom(),
egui::Color32::from_rgb(0xF2, 0xF0, 0xE8),
);
sky.add_triangle(0, 1, 2);
sky.add_triangle(0, 2, 3);
painter.rect_filled(rect, radius, egui::Color32::from_rgb(0x14, 0x16, 0x22));
painter.add(sky);
let font_px = 22.0 * style.scale as f32;
let unit = font_px / MPV_FONT;
let face = theme::subtitle_face(
ui.ctx(),
style.font.as_deref().unwrap_or(SubtitleStyle::DEFAULT_FONT),
style.bold,
style.italic,
);
let (family, made_up_bold, made_up_italic) = match face {
Some(face) => (
theme::subtitle_family(),
style.bold && !face.bold,
style.italic && !face.italic,
),
None if style.bold => (theme::semibold(), false, style.italic),
None => (egui::FontFamily::Proportional, false, style.italic),
};
let job = egui::text::LayoutJob::single_section(
"Can you read this on both sides?".to_owned(),
egui::TextFormat {
font_id: egui::FontId::new(font_px, family),
color: egui::Color32::PLACEHOLDER,
italics: made_up_italic,
..Default::default()
},
);
let galley = painter.layout_job(job);
let size = galley.size();
// Bottom of the line at `position` percent down, as mpv places it, kept
// inside the strip.
let margin = 8.0;
let bottom = rect.top() + HEIGHT * style.position as f32 / 100.0 - margin;
let top = bottom
.min(rect.bottom() - margin)
.max(rect.top() + margin + size.y)
- size.y;
let at = egui::pos2(rect.center().x - size.x / 2.0, top);
let colour = |colour: Colour| {
let [r, g, b, a] = colour.to_array();
egui::Color32::from_rgba_unmultiplied(r, g, b, a)
};
let shadow = style.shadow_offset as f32 * unit;
match style.backdrop {
SubtitleBackdrop::Box => {
let padding = 6.0 * unit;
let line = egui::Rect::from_min_size(at, size).expand(padding);
if shadow > 0.0 {
painter.rect_filled(
line.translate(egui::vec2(shadow, shadow)),
0.0,
colour(style.shadow_colour),
);
}
painter.rect_filled(line, 0.0, colour(style.box_colour));
}
SubtitleBackdrop::Outline => {
let outline = style.outline_size as f32 * unit;
let rings = |offset: egui::Vec2, ink: egui::Color32| {
if outline <= 0.0 {
painter.galley_with_override_text_color(at + offset, galley.clone(), ink);
return;
}
for step in 0..8 {
let angle = step as f32 * std::f32::consts::TAU / 8.0;
let ring = egui::vec2(angle.cos(), angle.sin()) * outline;
painter.galley_with_override_text_color(
at + offset + ring,
galley.clone(),
ink,
);
}
};
if shadow > 0.0 {
rings(egui::vec2(shadow, shadow), colour(style.shadow_colour));
}
if outline > 0.0 {
rings(egui::Vec2::ZERO, colour(style.outline_colour));
}
}
}
if made_up_bold {
// libass thickens a face with no bold by a stroke of its own colour.
let thicken = (font_px / 40.0).max(0.5);
painter.galley_with_override_text_color(
at + egui::vec2(thicken, 0.0),
galley.clone(),
colour(style.colour),
);
}
painter.galley_with_override_text_color(at, galley, colour(style.colour));
}
/// The streaming cache: how big it may get, and a way to empty it.
fn storage_form(ui: &mut egui::Ui, prefs: Prefs<'_>, actions: &mut Vec<Action>) {
ui::widgets::settings_group(
+1
View File
@@ -36,6 +36,7 @@ const GROUPS: &[(&str, &[(&str, &str)])] = &[
("N / P", "Next and previous episode"),
("[ / ]", "Slower and faster"),
("S", "Skip the opening or the credits"),
("Z / X", "Subtitles 0.1 s earlier and later"),
("E", "The list of episodes"),
("F or double-click", "Fullscreen"),
("Esc", "Leave fullscreen, then the player"),
+46
View File
@@ -11,6 +11,7 @@
//! and neither mutates: this module draws.
use egui::{Color32, CornerRadius, Rect, Sense, Stroke, Vec2, pos2};
use pstr_core::prefs::SubtitleStyle;
use pstr_player::{MAX_VOLUME, Track, TrackKind};
use crate::app::{Action, Adjacent, Page};
@@ -470,6 +471,8 @@ fn track_menus(ui: &mut egui::Ui, playback: &Playback, actions: &mut Vec<Action>
}
ui.separator();
track_options(ui, &subtitles, TrackKind::Subtitle, actions);
ui.separator();
subtitle_adjustments(ui, playback, actions);
})
.response
.on_hover_text("Subtitle track");
@@ -489,6 +492,49 @@ fn track_menus(ui: &mut egui::Ui, playback: &Playback, actions: &mut Vec<Action>
}
}
/// What is worth changing mid-episode without a trip to Settings: the size and
/// place of the line, and its timing for a release that is out of step.
fn subtitle_adjustments(ui: &mut egui::Ui, playback: &Playback, actions: &mut Vec<Action>) {
let mut style = playback.subtitle_style.clone();
egui::Grid::new("subtitle-adjustments")
.num_columns(2)
.spacing([theme::space::M, theme::space::S])
.show(ui, |ui| {
ui.label("Size");
ui::settings::percent_slider(
ui,
&mut style.scale,
SubtitleStyle::MIN_SCALE..=SubtitleStyle::MAX_SCALE,
);
ui.end_row();
ui.label("Position");
ui::settings::subtitle_position_slider(ui, &mut style.position);
ui.end_row();
ui.label("Delay");
ui.horizontal(|ui| {
if ui.button("−").on_hover_text("Earlier (Z)").clicked() {
actions.push(Action::NudgeSubtitleDelay(-0.1));
}
ui.label(ui::format_delay(playback.subtitle_delay));
if ui.button("+").on_hover_text("Later (X)").clicked() {
actions.push(Action::NudgeSubtitleDelay(0.1));
}
if ui
.add_enabled(playback.subtitle_delay != 0.0, egui::Button::new("Reset"))
.clicked()
{
actions.push(Action::ResetSubtitleDelay);
}
});
ui.end_row();
});
if style != playback.subtitle_style {
actions.push(Action::SetSubtitleStyle(style.sanitized()));
}
}
fn track_options(ui: &mut egui::Ui, tracks: &[&Track], kind: TrackKind, actions: &mut Vec<Action>) {
for track in tracks {
if ui.selectable_label(track.selected, track.label()).clicked() {
+44 -12
View File
@@ -33,7 +33,8 @@ use std::collections::HashMap;
use std::sync::Arc;
use proton_drive_rs::{NodeKind, ProtonDriveClient};
use proton_sdk::api::HumanVerificationCredential;
use proton_sdk::account::KeyPassphrases;
use proton_sdk::api::{HumanVerificationCredential, ResponseCode};
use proton_sdk::error::ProtonError;
use proton_sdk::ids::NodeUid;
use proton_sdk::session::{PasswordMode, ProtonApiSession, ResumeParameters};
@@ -51,6 +52,12 @@ const SECURITY_KEY_ONLY: &str = "This account's only second factor is a security
app cannot use yet. Add an authenticator app in your Proton account settings, then sign in \
with its code.";
/// Why a sign-in Proton answered with [`ResponseCode::Blocked`] failed. The
/// server's own text says the app version is no longer supported, which is
/// not true and sends the viewer looking for an update that does not exist.
const SIGN_IN_BLOCKED: &str = "Proton has blocked sign-ins from this app for now. Wait a while \
and try again, or sign in once on proton.me first.";
/// Blocks in flight for streaming from the account, as for a public link —
/// see `ShareStore::open`.
const MAX_INFLIGHT_BLOCKS: usize = 48;
@@ -91,10 +98,10 @@ impl StoredSession {
}
}
fn unlock(&self) -> HashMap<String, Vec<u8>> {
fn unlock(&self) -> KeyPassphrases {
self.key_passphrases
.iter()
.map(|(id, passphrase)| (id.clone(), passphrase.as_bytes().to_vec()))
.map(|(id, passphrase)| (id.as_str(), passphrase.as_bytes()))
.collect()
}
@@ -424,9 +431,9 @@ impl AccountStore {
/// back the account.
///
/// The key passphrases are derived here, while the token still has the scope
/// the key salts need. Loading the addresses is what proves the mailbox
/// password: it unlocks the user keys, and a wrong password unlocks none of
/// them. Only the passphrases are stored; the password goes no further.
/// the key salts need. Unlocking the user keys is what proves the mailbox
/// password: a wrong one unlocks none of them. Only the passphrases are
/// stored; the password goes no further.
async fn finish(
secrets: Arc<dyn SecretStore>,
session: ProtonApiSession,
@@ -435,10 +442,10 @@ async fn finish(
let probe = ProtonDriveClient::new(&session, mailbox_password.as_bytes().to_vec());
probe
.account()
.addresses()
.unlock()
.await
.map_err(|error| match error {
ProtonError::InvalidOperation(_) => {
ProtonError::KeysLocked => {
Error::SignIn("that mailbox password did not unlock the account".to_owned())
}
other => other.into(),
@@ -447,10 +454,10 @@ async fn finish(
.account()
.key_passphrases()
.await?
.into_iter()
.iter()
.map(|(id, passphrase)| {
String::from_utf8(passphrase)
.map(|passphrase| (id, passphrase))
std::str::from_utf8(passphrase)
.map(|passphrase| (id.to_owned(), passphrase.to_owned()))
.map_err(|_| Error::Config("a derived key passphrase is not text".to_owned()))
})
.collect::<Result<HashMap<_, _>>>()?;
@@ -500,7 +507,8 @@ fn persist_refreshed_tokens(
});
}
/// Lift a CAPTCHA gate and a wrong password out of the generic API error.
/// Lift a CAPTCHA gate, a blocked sign-in and a wrong password out of the
/// generic API error.
///
/// Only a gate that can be solved in an app becomes
/// [`Error::HumanVerification`]; one that wants an e-mail or SMS code is a plain
@@ -512,6 +520,9 @@ fn classify_sign_in_failure(error: ProtonError) -> Error {
{
return Error::HumanVerification(Box::new(challenge));
}
if api.code == ResponseCode::Blocked {
return Error::SignIn(SIGN_IN_BLOCKED.to_owned());
}
if api.http_status == 422 && !api.is_human_verification_required() {
return Error::SignIn(if api.message.is_empty() {
"Proton did not accept that address and password".to_owned()
@@ -642,6 +653,27 @@ mod tests {
assert!(store.resume().expect("resume").is_none());
}
#[test]
fn a_stored_session_unlocks_with_its_passphrases() {
let unlock = stored().unlock();
assert_eq!(unlock.len(), 1);
assert_eq!(unlock.get("key-1"), Some(b"derived".as_slice()));
}
#[test]
fn a_blocked_sign_in_does_not_claim_the_app_is_outdated() {
let error = classify_sign_in_failure(ProtonError::Api(proton_sdk::error::ProtonApiError {
code: ResponseCode::Blocked,
http_status: 422,
message: "This version of the app is no longer supported".to_owned(),
details: None,
}));
assert!(
matches!(&error, Error::SignIn(text) if text == SIGN_IN_BLOCKED),
"{error}"
);
}
#[test]
fn a_stored_session_keeps_its_password_mode() {
let params = stored().resume_parameters();
+207 -4
View File
@@ -1549,7 +1549,9 @@ pub fn from_node(share_id: &str, node: &proton_drive_rs::Node) -> CatalogNode {
/// - grouping folders (`Movies`, `OVA`, `Specials`) are stepped over, so their
/// contents group under the series above them;
/// - whatever the filename claimed as a title, when it differs, is kept as the
/// episode's own name — with the redundant series prefix stripped.
/// episode's own name — with the redundant series prefix stripped;
/// - **a folder of films is one title per film**, not one title: see
/// [`split_films`].
///
/// Folders and non-video files are dropped: a share holds `.nfo` and `.jpg`
/// alongside the video, and a catalog that offers those as episodes is worse
@@ -1562,12 +1564,18 @@ pub fn build_rows(share_id: &str, nodes: &[proton_drive_rs::Node]) -> Vec<Catalo
.map(|node| (node.uid.link_id.as_str(), node))
.collect();
nodes
let mut origins = Vec::new();
let mut rows: Vec<CatalogNode> = nodes
.iter()
.filter(|node| !node.is_folder() && naming::is_video_file(&node.name))
.map(|node| {
let mut row = from_node(share_id, node);
let context = ancestry(node, &by_link);
origins.push(Origin {
own: row.parsed.clone(),
folder: context.title_folder.clone(),
through_container: context.through_container,
});
if let Some(title) = context.title {
// The filename's own title, if it had one and it differs, is the
@@ -1601,7 +1609,75 @@ pub fn build_rows(share_id: &str, nodes: &[proton_drive_rs::Node]) -> Vec<Catalo
}
row
})
.collect()
.collect();
split_films(&mut rows, &origins);
rows
}
/// Where a row's title came from, kept for [`split_films`].
struct Origin {
/// What the filename alone parsed as, before the folder overrode it.
own: ParsedName,
/// The link id of the folder that named the row.
folder: Option<String>,
through_container: bool,
}
/// Give each film in a folder of films its own title.
///
/// `Rebuild of Evangelion/` holding `Evangelion - 1.11 You Are (Not)
/// Alone.mkv` and three more is four films, each its own entry at every
/// provider. Titled by the folder they are one series of four unnumbered
/// files, matched as whichever single film the folder's name reads most like —
/// and no single film is right.
///
/// Only when every file in the folder says so, because the same shape with one
/// file out of place is a series:
///
/// - none is numbered, by its name or by a season folder;
/// - none is under a grouping folder, because `Neon Genesis Evangelion/Movies/`
/// is the series' films, and they belong on its page;
/// - each names itself, differently from the others, and not by the folder's
/// name — `Mushishi - The Green Seat.mkv` under `Mushishi/` is an episode
/// of that show whose number is missing, not a film.
fn split_films(rows: &mut [CatalogNode], origins: &[Origin]) {
use crate::library::title_key;
use std::collections::HashSet;
let mut by_folder: HashMap<&str, Vec<usize>> = HashMap::new();
for (index, origin) in origins.iter().enumerate() {
if let Some(folder) = &origin.folder {
by_folder.entry(folder.as_str()).or_default().push(index);
}
}
for members in by_folder.into_values() {
if members.len() < 2 {
continue;
}
let mut keys = HashSet::new();
let films = members.iter().all(|&index| {
let (row, origin) = (&rows[index], &origins[index]);
let own = &origin.own.title;
!origin.through_container
&& !origin.own.is_episode()
&& origin.own.season.is_none()
&& row.parsed.season.is_none()
&& !own.is_empty()
&& strip_prefix_title(own, &row.parsed.title) == *own
&& !own.eq_ignore_ascii_case(&row.parsed.title)
&& keys.insert(title_key(own))
});
if !films {
continue;
}
for index in members {
let row = &mut rows[index];
let own = &origins[index].own;
row.parsed.title = own.title.clone();
row.parsed.episode_title = own.episode_title.clone();
}
}
}
/// Pair each subtitle file in a crawl with the video it is for.
@@ -1784,6 +1860,10 @@ fn describe_subtitle(rest: &str) -> (Option<String>, Option<String>) {
#[derive(Debug, Default)]
struct Ancestry {
title: Option<String>,
/// The link id of the folder [`Ancestry::title`] came from.
title_folder: Option<String>,
/// Whether a grouping folder sat between the file and that one.
through_container: bool,
season: Option<u32>,
year: Option<u32>,
}
@@ -1822,10 +1902,13 @@ fn ancestry(
match crate::naming::classify_folder(&ancestor.name) {
FolderRole::Season(season) => found.season = found.season.or(Some(season)),
FolderRole::Container => {}
FolderRole::Container => {
found.through_container |= found.title.is_none();
}
FolderRole::Title(parsed) => {
if found.title.is_none() && !parsed.title.is_empty() {
found.title = Some(parsed.title.clone());
found.title_folder = Some(link_id.clone());
found.year = found.year.or(parsed.year);
// `Game of Thrones - Season 1` names both; the season it
// states belongs to the files under it.
@@ -3081,6 +3164,126 @@ mod tests {
assert_eq!(row(&film, "film").parsed.title, "Millennium Actress");
}
/// **What the Rebuild of Evangelion films were matched as.** A folder of
/// four films titled by the folder is one series, matched as a single film
/// that none of the four is. Each names itself, so each is its own title.
#[test]
fn a_folder_of_unnumbered_films_is_one_title_per_film() {
let nodes = vec![
root(),
folder("rebuild", Some("root"), "Rebuild of Evangelion"),
video(
"one",
"rebuild",
"Evangelion - 1.11 You Are (Not) Alone.mkv",
),
video(
"two",
"rebuild",
"Evangelion - 2.22 You Can (Not) Advance..mkv",
),
video(
"three",
"rebuild",
"Evangelion - 3.33 You Can (Not) Redo..mkv",
),
video(
"four",
"rebuild",
"Evangelion - 3.0+1.01 Thrice Upon a Time.mkv",
),
];
let rows = build_rows("share", &nodes);
assert_eq!(
row(&rows, "one").parsed.title,
"Evangelion - 1.11 You Are Alone"
);
assert_eq!(
row(&rows, "four").parsed.title,
"Evangelion - 3.0+1.01 Thrice Upon a Time"
);
for film in &rows {
assert_eq!(film.parsed.episode, None);
assert_eq!(film.parsed.episode_title, None, "a film is not an episode");
}
let library = crate::library::Library::build(rows, &HashMap::new());
assert_eq!(library.titles.len(), 4);
assert!(
library
.titles
.iter()
.all(|title| title.kind == TitleKind::Film)
);
}
/// One numbered file says the folder is a show, and the unnumbered ones are
/// its specials.
#[test]
fn a_folder_with_a_numbered_episode_in_it_is_not_split() {
let nodes = vec![
root(),
folder("show", Some("root"), "Promised Neverland"),
video("e1", "show", "[Group] Yakusoku no Neverland - 01.mkv"),
video("film", "show", "Some Recap Film.mkv"),
video("other", "show", "Another Special.mkv"),
];
let rows = build_rows("share", &nodes);
for file in &rows {
assert_eq!(file.parsed.title, "Promised Neverland");
}
}
/// Films under `Movies/` are the series' films, and stay on its page.
#[test]
fn films_under_a_grouping_folder_stay_with_the_series() {
let nodes = vec![
root(),
folder("eva", Some("root"), "Neon Genesis Evangelion"),
folder("movies", Some("eva"), "Movies"),
video("a", "movies", "Death and Rebirth.mkv"),
video("b", "movies", "The End of Evangelion.mkv"),
];
let rows = build_rows("share", &nodes);
for file in &rows {
assert_eq!(file.parsed.title, "Neon Genesis Evangelion");
}
}
/// Files that repeat the folder's name are that show's episodes with their
/// numbers missing, not films of their own.
#[test]
fn unnumbered_files_named_after_their_folder_stay_one_title() {
let nodes = vec![
root(),
folder("mushi", Some("root"), "Mushishi"),
video("a", "mushi", "Mushishi - The Green Seat.mkv"),
video("b", "mushi", "Mushishi - The Light of the Eyelid.mkv"),
];
let rows = build_rows("share", &nodes);
assert_eq!(row(&rows, "a").parsed.title, "Mushishi");
assert_eq!(
row(&rows, "a").parsed.episode_title.as_deref(),
Some("The Green Seat")
);
}
/// Two files that name themselves the same thing are not two films.
#[test]
fn files_whose_own_names_collide_are_not_split() {
let nodes = vec![
root(),
folder("film", Some("root"), "Akira"),
video("a", "film", "[GroupA] Neo Tokyo.mkv"),
video("b", "film", "Neo.Tokyo.mkv"),
];
let rows = build_rows("share", &nodes);
for file in &rows {
assert_eq!(file.parsed.title, "Akira");
}
}
/// The share root names the *share*, not a series — using it would label
/// every top-level file identically.
#[test]
+11 -2
View File
@@ -85,11 +85,14 @@ impl Error {
}
/// Whether this is the account's session having ended: the refresh token
/// was revoked or expired, or the token lacks a scope only a password
/// sign-in grants. Nothing but signing in again fixes it.
/// was revoked or expired, the token lacks a scope only a password
/// sign-in grants, or the stored key passphrases no longer unlock the
/// account because its mailbox password changed. Nothing but signing in
/// again fixes it.
pub fn is_signed_out(&self) -> bool {
match self {
Self::SignedOut(_) => true,
Self::Drive(proton_sdk::error::ProtonError::KeysLocked) => true,
Self::Drive(proton_sdk::error::ProtonError::Api(api)) => {
api.is_invalid_refresh_token() || api.is_insufficient_scope()
}
@@ -127,4 +130,10 @@ mod tests {
"io: client error (SendRequest): connection closed before message completed"
);
}
#[test]
fn stored_passphrases_that_no_longer_unlock_mean_signed_out() {
let error = Error::Drive(proton_sdk::error::ProtonError::KeysLocked);
assert!(error.is_signed_out());
}
}
+72 -2
View File
@@ -539,6 +539,9 @@ fn find_dash_numbering(text: &str) -> Option<NumberingMatch> {
if is_token_char(tail) && tail != Some(b'v') {
continue;
}
if is_decimal_tail(text, after) {
continue;
}
found = Some(NumberingMatch {
numbering: Numbering {
season: None,
@@ -551,6 +554,24 @@ fn find_dash_numbering(text: &str) -> Option<NumberingMatch> {
found
}
/// Whether the number that ended at `at` goes on as a decimal: `.11` in
/// `Evangelion - 1.11 You Are (Not) Alone`, `.0` in `3.0+1.01`.
///
/// That is a version of a film, not episode 1 of anything, and reading it as
/// one turns a folder of four films into a series of episodes 1, 2, 3 and 3.
/// One or two digits only: `- 05.1080p` is episode 5 and a resolution.
fn is_decimal_tail(text: &str, at: usize) -> bool {
let bytes = text.as_bytes();
if bytes.get(at) != Some(&b'.') {
return false;
}
let digits = bytes[at + 1..]
.iter()
.take_while(|byte| byte.is_ascii_digit())
.count();
(1..=2).contains(&digits) && !is_token_char(bytes.get(at + 1 + digits).copied())
}
/// Step over an `E` / `EP` episode marker and any separator after it.
///
/// Returns `at` unchanged when there is none, so a bare number and a marked one
@@ -630,9 +651,18 @@ fn is_token_start(text: &str, at: usize) -> bool {
/// Normalize the title span: separators to spaces, then trim the debris that
/// sits between the title and whatever followed it.
fn clean_title(raw: &str, year: Option<u32>) -> String {
// A dot between two digits is a decimal point, not a separator: `1.11`
// is the film's name, `1 11` is two numbers.
let bytes = raw.as_bytes();
let mut text: String = raw
.chars()
.map(|c| match c {
.char_indices()
.map(|(at, c)| match c {
'.' if at > 0
&& bytes[at - 1].is_ascii_digit()
&& bytes.get(at + 1).is_some_and(u8::is_ascii_digit) =>
{
'.'
}
'.' | '_' => ' ',
other => other,
})
@@ -856,6 +886,46 @@ mod tests {
);
}
/// **What the four Rebuild of Evangelion films parsed as.** ` - 1.11` read
/// as episode 1, so the folder became a series of episodes 1, 2, 3 and 3.
/// A decimal is a version of the film, and the name keeps it.
#[test]
fn a_decimal_after_the_dash_is_part_of_a_films_name_not_an_episode() {
assert_eq!(
parsed("Evangelion - 1.11 You Are (Not) Alone.mkv"),
("Evangelion - 1.11 You Are Alone".into(), None, None, None)
);
assert_eq!(
parsed("Evangelion - 3.0+1.01 Thrice Upon a Time.mkv"),
(
"Evangelion - 3.0+1.01 Thrice Upon a Time".into(),
None,
None,
None
)
);
}
/// A recap numbered between two episodes is not a second copy of the one
/// before it.
#[test]
fn a_half_episode_is_not_the_episode_before_it() {
assert_eq!(
parsed("[Group] Show Name - 12.5 [1080p].mkv"),
("Show Name - 12.5".into(), None, None, None)
);
}
/// The decimal rule stops at two digits, so a resolution glued on with a
/// dot leaves the episode number alone.
#[test]
fn a_resolution_after_a_dot_does_not_hide_the_episode() {
assert_eq!(
parsed("Show Name - 05.1080p.mkv"),
("Show Name".into(), None, Some(5), None)
);
}
/// A version suffix still names the same episode.
#[test]
fn a_versioned_fansub_episode_keeps_its_number() {
+257
View File
@@ -60,6 +60,211 @@ pub struct PlaybackPrefs {
/// everything at 1.25, and a speed that reset every episode would be a
/// setting nobody could use.
pub speed: f64,
/// How plain subtitles look. Kept with the rest because it is the same
/// kind of choice: made once, for every file after.
pub subtitle_style: SubtitleStyle,
}
/// How subtitles are drawn.
///
/// Every default is mpv's own, so a viewer who never opens the section sees
/// what any mpv shows. Plain (SRT) tracks take all of it. A styled (ASS) track
/// was typeset by somebody, its signs placed and coloured by hand, and painting
/// over that undoes the work — so by default it takes none of this, and moves
/// only to stay clear of the player's controls. All of it reaches a styled
/// track only with [`Self::restyle_styled`].
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(default)]
pub struct SubtitleStyle {
/// Relative to mpv's own size, which is itself relative to the video's
/// height — so one setting reads the same on a phone and a television.
pub scale: f64,
/// A font family name. `None` is mpv's `sans-serif`. A name this device
/// does not have falls back the same way, which is what makes it safe to
/// sync.
pub font: Option<String>,
pub bold: bool,
pub italic: bool,
pub colour: Colour,
pub backdrop: SubtitleBackdrop,
pub outline_colour: Colour,
/// In mpv's scaled pixels, as `sub-outline-size`.
pub outline_size: f64,
/// The box's colour, its alpha the box's opacity. Only with
/// [`SubtitleBackdrop::Box`].
pub box_colour: Colour,
pub shadow_colour: Colour,
/// How far the shadow falls; 0 is none, which is mpv's default.
pub shadow_offset: f64,
/// How soft the edges are, 0–20.
pub blur: f64,
/// Where the line sits, as a percentage of the picture's height from the
/// top: 100 is the bottom edge, mpv's usual place.
pub position: f64,
/// Whether styled (ASS) tracks are drawn in this style too, size and
/// position included. Off by default: it turns signs and karaoke into
/// dialogue-looking text.
pub restyle_styled: bool,
}
impl SubtitleStyle {
/// The family a style with no font of its own is set in: mpv's default,
/// which fontconfig resolves to the system's sans-serif face.
pub const DEFAULT_FONT: &str = "sans-serif";
pub const MIN_SCALE: f64 = 0.5;
pub const MAX_SCALE: f64 = 2.5;
pub const MAX_OUTLINE: f64 = 10.0;
pub const MAX_SHADOW: f64 = 10.0;
pub const MAX_BLUR: f64 = 20.0;
/// The same style with every number brought back into range.
///
/// A hand-edited or synced file can hold anything, and mpv refuses an
/// out-of-range value outright — which would cost the rest of the style.
pub fn sanitized(mut self) -> Self {
let defaults = Self::default();
let clamp = |value: f64, default: f64, min: f64, max: f64| {
if value.is_finite() {
value.clamp(min, max)
} else {
default
}
};
self.scale = clamp(self.scale, defaults.scale, Self::MIN_SCALE, Self::MAX_SCALE);
self.outline_size = clamp(
self.outline_size,
defaults.outline_size,
0.0,
Self::MAX_OUTLINE,
);
self.shadow_offset = clamp(
self.shadow_offset,
defaults.shadow_offset,
0.0,
Self::MAX_SHADOW,
);
self.blur = clamp(self.blur, defaults.blur, 0.0, Self::MAX_BLUR);
self.position = clamp(self.position, defaults.position, 0.0, 100.0);
self.font = self
.font
.map(|font| font.trim().to_owned())
.filter(|font| !font.is_empty());
self
}
}
impl Default for SubtitleStyle {
fn default() -> Self {
Self {
scale: 1.0,
font: None,
bold: false,
italic: false,
colour: Colour::rgba(0xFF, 0xFF, 0xFF, 0xFF),
backdrop: SubtitleBackdrop::Outline,
outline_colour: Colour::rgba(0, 0, 0, 0xFF),
outline_size: 1.65,
// About seventy percent black.
box_colour: Colour::rgba(0, 0, 0, 0xB0),
shadow_colour: Colour::rgba(0, 0, 0, 0xAF),
shadow_offset: 0.0,
blur: 0.0,
position: 100.0,
restyle_styled: false,
}
}
}
/// What keeps the text readable against the picture.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum SubtitleBackdrop {
/// An outline round each letter: mpv's own, and the default.
#[default]
Outline,
/// A box behind each line. Uglier, and the only thing that holds up on
/// snow, sky and white walls.
Box,
}
impl SubtitleBackdrop {
pub const ALL: [Self; 2] = [Self::Outline, Self::Box];
pub fn label(self) -> &'static str {
match self {
Self::Outline => "Outline",
Self::Box => "Box",
}
}
}
/// A colour with opacity, written `#RRGGBBAA` the way CSS writes one.
///
/// Not mpv's order: mpv reads `#AARRGGBB`, which nobody hand-editing a file
/// would guess. [`Self::to_mpv`] does the translation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct Colour {
pub r: u8,
pub g: u8,
pub b: u8,
pub a: u8,
}
impl Colour {
pub const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Self {
Self { r, g, b, a }
}
/// `#RRGGBB` or `#RRGGBBAA`, the `#` optional. Six digits are opaque.
pub fn parse(text: &str) -> Option<Self> {
let hex = text.trim().strip_prefix('#').unwrap_or(text.trim());
if !(hex.len() == 6 || hex.len() == 8) || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
let byte = |at: usize| u8::from_str_radix(&hex[at..at + 2], 16).ok();
let a = if hex.len() == 8 { byte(6)? } else { 0xFF };
Some(Self::rgba(byte(0)?, byte(2)?, byte(4)?, a))
}
/// As mpv's colour options take it.
pub fn to_mpv(self) -> String {
format!("#{:02X}{:02X}{:02X}{:02X}", self.a, self.r, self.g, self.b)
}
pub fn to_array(self) -> [u8; 4] {
[self.r, self.g, self.b, self.a]
}
}
impl From<[u8; 4]> for Colour {
fn from([r, g, b, a]: [u8; 4]) -> Self {
Self::rgba(r, g, b, a)
}
}
impl std::fmt::Display for Colour {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"#{:02X}{:02X}{:02X}{:02X}",
self.r, self.g, self.b, self.a
)
}
}
impl From<Colour> for String {
fn from(colour: Colour) -> Self {
colour.to_string()
}
}
impl TryFrom<String> for Colour {
type Error = String;
fn try_from(text: String) -> std::result::Result<Self, Self::Error> {
Self::parse(&text).ok_or_else(|| format!("not a colour: {text:?}"))
}
}
impl Default for PlaybackPrefs {
@@ -73,6 +278,7 @@ impl Default for PlaybackPrefs {
autoplay_next: true,
auto_skip: false,
speed: 1.0,
subtitle_style: SubtitleStyle::default(),
}
}
}
@@ -93,6 +299,7 @@ impl PlaybackPrefs {
self.speed = self.speed.clamp(MIN_SPEED, MAX_SPEED);
self.audio_language = self.audio_language.filter(|tag| !tag.trim().is_empty());
self.subtitle_language = self.subtitle_language.filter(|tag| !tag.trim().is_empty());
self.subtitle_style = self.subtitle_style.sanitized();
self
}
}
@@ -149,6 +356,16 @@ mod tests {
autoplay_next: false,
auto_skip: true,
speed: 1.5,
subtitle_style: SubtitleStyle {
scale: 1.5,
font: Some("Noto Sans".into()),
italic: true,
colour: Colour::rgba(0xFF, 0xE6, 0x00, 0xFF),
backdrop: SubtitleBackdrop::Box,
box_colour: Colour::rgba(0x10, 0x10, 0x10, 0x80),
restyle_styled: true,
..SubtitleStyle::default()
},
};
save(&dirs, &prefs).unwrap();
assert_eq!(load(&dirs).unwrap(), prefs);
@@ -156,6 +373,46 @@ mod tests {
std::fs::remove_dir_all(&temp).ok();
}
#[test]
fn a_file_from_before_subtitle_styles_loads_with_the_default_style() {
let prefs: PlaybackPrefs =
serde_json::from_str(r#"{"volume": 60.0, "subtitles": true, "speed": 1.0}"#).unwrap();
assert_eq!(prefs.subtitle_style, SubtitleStyle::default());
assert_eq!(prefs.volume, 60.0);
}
#[test]
fn a_colour_is_written_rgba_and_handed_to_mpv_as_argb() {
let colour = Colour::parse("#FFE60080").unwrap();
assert_eq!(colour, Colour::rgba(0xFF, 0xE6, 0x00, 0x80));
assert_eq!(colour.to_string(), "#FFE60080");
assert_eq!(colour.to_mpv(), "#80FFE600");
assert_eq!(
Colour::parse("ffe600"),
Some(Colour::rgba(0xFF, 0xE6, 0, 0xFF))
);
assert_eq!(Colour::parse("#FFE6"), None);
assert_eq!(Colour::parse("#GGGGGG"), None);
}
#[test]
fn a_subtitle_style_out_of_range_is_brought_back_into_it() {
let style = SubtitleStyle {
scale: 40.0,
outline_size: -3.0,
blur: f64::NAN,
position: 400.0,
font: Some(" ".into()),
..SubtitleStyle::default()
}
.sanitized();
assert_eq!(style.scale, SubtitleStyle::MAX_SCALE);
assert_eq!(style.outline_size, 0.0);
assert_eq!(style.blur, 0.0);
assert_eq!(style.position, 100.0);
assert_eq!(style.font, None);
}
#[test]
fn a_volume_no_player_could_honour_is_clamped_rather_than_passed_on() {
let prefs = PlaybackPrefs {
+51
View File
@@ -379,6 +379,12 @@ impl AniList {
/// tokenisation: by dropping the `s` it was holding on to. It is asked for only
/// after the name as written found nothing, which is what keeps it from
/// broadening a search that was already working.
///
/// A film's version number is the same kind of miss. `Evangelion - 1.11 You
/// Are (Not) Alone` is the file of a film AniList calls `Evangelion: 1.0 You
/// Are (Not) Alone`, and `1.11` is not a word of that name — so the last
/// fallback asks without it, and leaves telling the films apart to the scoring,
/// which still sees the whole name.
fn search_terms(name: &str) -> Vec<String> {
let mut terms = vec![name.to_string()];
@@ -386,9 +392,31 @@ fn search_terms(name: &str) -> Vec<String> {
if depossessed != name {
terms.push(depossessed);
}
let unversioned = without_version_numbers(name);
if !unversioned.is_empty() && !terms.contains(&unversioned) {
terms.push(unversioned);
}
terms
}
/// `Evangelion - 1.11 You Are Alone` → `Evangelion - You Are Alone`.
///
/// A version is digits with a dot in them (`1.11`, `3.0+1.01`); a bare number
/// is left alone, because in `Kaijuu 8-gou` or `86` it is the name.
fn without_version_numbers(name: &str) -> String {
name.split(' ')
.filter(|word| {
let versioned = word.contains('.')
&& word.chars().any(|c| c.is_ascii_digit())
&& word
.chars()
.all(|c| c.is_ascii_digit() || matches!(c, '.' | '+'));
!versioned
})
.collect::<Vec<_>>()
.join(" ")
}
/// `Heavens Feel` → `Heaven Feel`.
///
/// Only words long enough to still mean something without it, and only where
@@ -836,6 +864,29 @@ mod tests {
);
}
/// **What three of the four Rebuild films matched as: nothing.** AniList
/// requires every word, and a film's version number is not one of its
/// title's.
#[test]
fn a_films_version_number_is_searched_for_again_without_it() {
assert_eq!(
search_terms("Evangelion - 1.11 You Are Alone"),
vec![
"Evangelion - 1.11 You Are Alone".to_string(),
"Evangelion - You Are Alone".to_string(),
]
);
assert_eq!(
search_terms("Evangelion - 3.0+1.01 Thrice Upon a Time")[1],
"Evangelion - Thrice Upon a Time"
);
assert_eq!(
search_terms("Kaijuu 8-gou"),
vec!["Kaijuu 8-gou"],
"a number that is part of the name stays"
);
}
/// Byte slicing, on names that are not ASCII.
#[test]
fn a_multi_byte_name_is_not_cut_inside_a_character() {
+10 -1
View File
@@ -42,7 +42,7 @@ use libloading::Library;
///
/// EGL leads on a Wayland session and GLX on an X11 one, matching what glutin
/// will have picked — though with `libglvnd` in the way, either order works.
#[cfg(unix)]
#[cfg(all(unix, not(target_os = "macos")))]
fn candidates() -> Vec<&'static str> {
let wayland = std::env::var_os("WAYLAND_DISPLAY").is_some();
if wayland {
@@ -52,6 +52,15 @@ fn candidates() -> Vec<&'static str> {
}
}
/// eframe's context on macOS is CGL, and the framework exports every GL
/// function it implements as a plain symbol — there is no `GetProcAddress` to
/// go through, so the direct lookup in [`GlLoader::resolve`] answers for all of
/// them.
#[cfg(target_os = "macos")]
fn candidates() -> Vec<&'static str> {
vec!["/System/Library/Frameworks/OpenGL.framework/OpenGL"]
}
#[cfg(windows)]
fn candidates() -> Vec<&'static str> {
vec!["opengl32.dll"]
+1
View File
@@ -49,6 +49,7 @@ pub use chapters::{Chapter, ChapterRole, chapter_at, chapter_end, credits_start,
pub use error::{Error, Result};
pub use player::{
EndReason, MAX_VOLUME, Player, PlayerConfig, PlayerEvent, READAHEAD_BLOCKS, VideoOutput,
subtitle_options,
};
pub use registry::{PROTOCOL, StreamHandle, StreamRegistry};
pub use render::VideoRenderer;
+166
View File
@@ -12,6 +12,7 @@ use std::sync::Arc;
use libmpv2::events::{Event, PropertyData};
use libmpv2::{Format, Mpv};
use pstr_core::prefs::{SubtitleBackdrop, SubtitleStyle};
use pstr_stream::VideoStream;
use tokio::runtime::Runtime;
@@ -181,6 +182,8 @@ pub struct PlayerConfig {
/// Whether subtitles are shown at all. Off is a choice a viewer makes once
/// and expects to keep, and no language preference can express it.
pub subtitles: bool,
/// How subtitles look. See [`subtitle_options`].
pub subtitle_style: SubtitleStyle,
/// Raw mpv options, applied last, so anything here wins.
pub options: Vec<(String, String)>,
}
@@ -206,6 +209,7 @@ impl Default for PlayerConfig {
audio_language: None,
subtitle_language: None,
subtitles: true,
subtitle_style: SubtitleStyle::default(),
options: Vec::new(),
}
}
@@ -293,6 +297,9 @@ impl Player {
if !config.subtitles {
init.set_property("sid", "no")?;
}
apply_subtitle_options(&config.subtitle_style, |name, value| {
init.set_property(name, value).map_err(Error::from)
});
for (name, value) in &config.options {
init.set_property(name.as_str(), value.as_str())?;
}
@@ -537,6 +544,18 @@ impl Player {
Ok(())
}
/// Restyle subtitles now, on the line already showing.
pub fn apply_subtitle_style(&self, style: &SubtitleStyle) {
apply_subtitle_options(style, |name, value| self.set_option(name, value));
}
/// Show subtitles `seconds` later (or, negative, earlier) than the file
/// says. For a release whose subtitles were timed against another cut.
pub fn set_subtitle_delay(&self, seconds: f64) -> Result<()> {
self.mpv.set_property("sub-delay", seconds)?;
Ok(())
}
/// Playback speed, where 1.0 is normal. Pitch is corrected, which is mpv's
/// default and what keeps a voice a voice at 1.5×.
pub fn set_speed(&self, speed: f64) -> Result<()> {
@@ -593,6 +612,78 @@ impl Player {
}
}
/// The first option of the block that only makes sense on top of it. See
/// [`apply_subtitle_options`].
const BORDER_STYLE: &str = "sub-border-style";
/// The mpv options that draw `style`, every one of them every time, so that
/// changing a value back to its default while playing lands too.
///
/// `sub-ass-override` is `yes` unless the viewer asked otherwise, so a styled
/// track keeps its own size, fonts and colours. Not mpv's default, `scale`,
/// which hands it `sub-scale` as well. `force` repaints it whole. See
/// [`SubtitleStyle`] for why that is opt-in. `sub-pos` reaches a styled track
/// under `yes` too, so where a styled track sits is the caller's to decide:
/// see `pstr-app`'s `Playback::lift_subtitles`.
/// The border options come last, led by [`BORDER_STYLE`].
pub fn subtitle_options(style: &SubtitleStyle) -> Vec<(&'static str, String)> {
let flag = |on: bool| if on { "yes" } else { "no" }.to_owned();
let mut options = vec![
(
"sub-ass-override",
if style.restyle_styled { "force" } else { "yes" }.to_owned(),
),
("sub-scale", format!("{:.2}", style.scale)),
(
"sub-font",
style
.font
.clone()
.unwrap_or_else(|| SubtitleStyle::DEFAULT_FONT.to_owned()),
),
("sub-bold", flag(style.bold)),
("sub-italic", flag(style.italic)),
("sub-color", style.colour.to_mpv()),
// mpv's name for the shadow's colour, older than the shadow alias.
("sub-back-color", style.shadow_colour.to_mpv()),
("sub-shadow-offset", format!("{:.2}", style.shadow_offset)),
("sub-blur", format!("{:.2}", style.blur)),
("sub-pos", format!("{:.0}", style.position)),
];
match style.backdrop {
SubtitleBackdrop::Outline => options.extend([
(BORDER_STYLE, "outline-and-shadow".to_owned()),
("sub-outline-color", style.outline_colour.to_mpv()),
("sub-outline-size", format!("{:.2}", style.outline_size)),
]),
// `opaque-box` draws the outline as a box hugging each line, so the
// outline's colour and size become the box's colour and margin.
SubtitleBackdrop::Box => options.extend([
(BORDER_STYLE, "opaque-box".to_owned()),
("sub-outline-color", style.box_colour.to_mpv()),
("sub-outline-size", "6".to_owned()),
]),
}
options
}
/// Hand `style` to `set` option by option, best effort.
///
/// An option this libmpv refuses costs that option, not the player:
/// `sub-border-style` is mpv 0.38's, and Ubuntu 24.04 ships 0.37. A refused
/// border style ends the run, though, because what follows it only makes sense
/// on top of it: a box's colour and margin on a plain outline is a fat smear.
fn apply_subtitle_options(style: &SubtitleStyle, mut set: impl FnMut(&str, &str) -> Result<()>) {
for (name, value) in subtitle_options(style) {
if let Err(error) = set(name, &value) {
tracing::warn!("subtitle style {name}={value}: {error}");
if name == BORDER_STYLE {
break;
}
}
}
}
/// mpv's borrowed event to ours.
fn translate(event: Event<'_>) -> PlayerEvent {
match event {
@@ -620,6 +711,81 @@ fn translate(event: Event<'_>) -> PlayerEvent {
mod tests {
use super::*;
fn option<'a>(options: &'a [(&'static str, String)], name: &str) -> Option<&'a str> {
options
.iter()
.find(|(option, _)| *option == name)
.map(|(_, value)| value.as_str())
}
#[test]
fn the_default_subtitle_style_is_what_mpv_would_do_anyway() {
let options = subtitle_options(&SubtitleStyle::default());
// mpv 0.41's own defaults, from `mpv --list-options` — all but
// `sub-ass-override`, which mpv has at `scale`.
for (name, value) in [
("sub-ass-override", "yes"),
("sub-scale", "1.00"),
("sub-font", "sans-serif"),
("sub-bold", "no"),
("sub-italic", "no"),
("sub-color", "#FFFFFFFF"),
("sub-back-color", "#AF000000"),
("sub-shadow-offset", "0.00"),
("sub-blur", "0.00"),
("sub-pos", "100"),
("sub-border-style", "outline-and-shadow"),
("sub-outline-color", "#FF000000"),
("sub-outline-size", "1.65"),
] {
assert_eq!(option(&options, name), Some(value), "{name}");
}
}
#[test]
fn a_boxed_subtitle_style_turns_the_outline_into_a_box_of_its_colour() {
let style = SubtitleStyle {
backdrop: SubtitleBackdrop::Box,
box_colour: pstr_core::prefs::Colour::rgba(0x20, 0x10, 0x00, 0x80),
..SubtitleStyle::default()
};
let options = subtitle_options(&style);
assert_eq!(option(&options, "sub-border-style"), Some("opaque-box"));
assert_eq!(option(&options, "sub-outline-color"), Some("#80201000"));
}
#[test]
fn styled_subtitles_are_repainted_or_resized_only_when_asked() {
// `scale` would hand a styled track the size; `yes` hands it nothing
// but the `sub-ass-*` options, none of which this sets.
let kept = subtitle_options(&SubtitleStyle {
scale: 1.5,
..SubtitleStyle::default()
});
assert_eq!(option(&kept, "sub-ass-override"), Some("yes"));
let repainted = subtitle_options(&SubtitleStyle {
restyle_styled: true,
..SubtitleStyle::default()
});
assert_eq!(option(&repainted, "sub-ass-override"), Some("force"));
}
#[test]
fn a_refused_border_style_skips_what_depends_on_it_and_nothing_before() {
let mut set = Vec::new();
apply_subtitle_options(&SubtitleStyle::default(), |name, _| {
set.push(name.to_owned());
if name == BORDER_STYLE {
Err(Error::NulByte("test"))
} else {
Ok(())
}
});
assert_eq!(set.last().map(String::as_str), Some(BORDER_STYLE));
assert!(set.iter().any(|name| name == "sub-color"));
assert!(!set.iter().any(|name| name == "sub-outline-color"));
}
#[test]
fn every_end_reason_maps_to_something_the_ui_can_act_on() {
use libmpv2::mpv_end_file_reason as raw;
+69
View File
@@ -0,0 +1,69 @@
# Account and sync
Signing in to Proton is optional. Without it, the app plays public share links and keeps
everything on one device. Signing in adds two things:
- **Folders of your own Drive** as shares, with no link to copy.
- **Sync** of your place in every episode, your shares and your settings, across every device
you sign in on.
## Signing in
The **Proton account** section is at the top of the **Shares** page.
1. Enter your Proton address and password, then **Sign in**.
2. If your account has two-factor authentication, enter the code from your authenticator app.
3. If your account has a separate mailbox password, enter it and choose **Unlock**.
Proton sometimes asks to confirm you are human. The app then opens a small window with Proton's
own CAPTCHA page. Solve it, and sign-in continues.
The app keeps a session, not your password. The session goes into the system keyring. **Sign
out** ends it on Proton's side and deletes it here.
Not supported yet:
- **Security keys** (FIDO2). An account whose only second factor is a security key cannot sign
in. Add an authenticator app as a second method in your Proton settings.
- **Email or SMS verification** instead of a CAPTCHA.
## Adding a folder of your Drive
1. Sign in.
2. Under **Add from your Drive**, choose **Browse your Drive**.
3. Open folders until you reach the one that holds your videos.
4. Choose **Add this folder**.
The folder becomes a share like any link: it is crawled, shown in the library and streamed. It is
read through your account, so there is no link or password to store. The same folder has the
same identity on every device, so watch history follows it.
## Sync
When you are signed in, each device keeps a small file in your Drive. You find them under
**Computers** on the Proton Drive website, in a device called `proton-stream`, in the folder
`watch-history`.
**What syncs:**
- Where you stopped in each episode, and which episodes you watched
- Your shares, including their links and passwords (end-to-end encrypted, like every file in
your Drive)
- Settings: playback, appearance and posters and descriptions, including a TMDB key
- Matches you picked by hand, and your audio and subtitle choice for each show
**What stays on each device:** volume and mute, the streaming cache size, text size, Wi-Fi only,
background audio, hardware decoding, window size, and the library's filter and sort order.
**When it syncs:** when the app starts, every 5 minutes while it is open, when you stop playing,
and when it closes. **Sync now** runs it at once. Android also syncs in the background shortly
after you leave the app.
**How conflicts are settled:** each device writes only its own file, and reads everyone else's.
For each episode and each setting, the newest change wins. A device that signs in for the first
time takes the others' state and does not overwrite it with its own defaults.
A device that has not synced for 90 days has its file moved to the Drive trash.
The status line under your address says how the last sync went, for example *Synced 3 min ago ·
2 positions from other devices*. To stop syncing, sign out.
+96
View File
@@ -0,0 +1,96 @@
# Command-line reference
The desktop packages install two programs:
- `proton-stream`, the app
- `pstr`, a command-line tool that does the app's work without a window
Both use the same shares, library, settings and keyring, so a share added with `pstr` shows up in
the app.
## proton-stream
```bash
proton-stream # open the app
proton-stream 'https://drive.proton.me/urls/TOKEN#KEY' # open it with the Add form filled in
```
Only one window runs at a time. A second `proton-stream` brings the open window forward, hands it
any share link it was given, and exits.
A link given as an argument is visible to other users of the computer in the process list while
the command runs, and it may land in your shell history. Pasting it into the window with
**Ctrl+V** does neither.
## pstr
`pstr --help` lists every command, and `pstr <command> --help` explains one. `pstr` never takes a
password or key as an argument; it asks for them.
### Shares
| Command | Does |
|---|---|
| `pstr add --name NAME URL` | Add a public share link. Quote the URL, because of the `#`. |
| `pstr add --name NAME URL --custom-password` | The same, and ask for the link's own password |
| `pstr add-folder --name NAME VOLUME:LINK` | Add a folder of your Drive, by the id `pstr browse` prints |
| `pstr shares` | List the shares and their ids |
| `pstr remove ID` | Remove a share and delete its link and password from the keyring |
### Account
| Command | Does |
|---|---|
| `pstr login ADDRESS` | Sign in. Asks for the password, a two-factor code and a mailbox password as the account needs them. |
| `pstr logout` | Sign out and delete the stored session |
| `pstr account` | Show who is signed in |
| `pstr browse [VOLUME:LINK]` | List your Drive's top-level places, or one folder |
| `pstr sync` | Sync watch history now |
`pstr login` cannot show a CAPTCHA. If Proton asks for one, sign in once in the app instead.
### Library
| Command | Does |
|---|---|
| `pstr crawl [--share ID]` | Read every share, or one, into the library |
| `pstr list [--share ID]` | Print what the library holds |
### Posters and descriptions
| Command | Does |
|---|---|
| `pstr metadata status` | Show whether lookups are on, and which provider |
| `pstr metadata set --on --provider anilist` | Turn lookups on with AniList |
| `pstr metadata set --on --provider tmdb --api-key` | Turn lookups on with TMDB, and ask for the key |
| `pstr metadata set --off` | Turn lookups off, and delete every stored answer |
| `pstr metadata match [--force] [--limit N]` | Look up titles now. `--force` asks again about titles that already have an answer. |
### Testing playback
These two are for finding out which layer is slow or broken.
```bash
pstr bench --file Frieren --verify # measure seek time, throughput and memory, no player
pstr play --file Frieren --disk-cache # play in a plain mpv window
```
| Option | Does |
|---|---|
| `--file TEXT` | The first file whose name or title contains `TEXT` |
| `--share ID` | Look in one share only |
| `--disk-cache` | Keep decrypted blocks on disk, as the app does |
| `--readahead N` | Blocks to fetch ahead of the reader |
| `--ring-mib N` | Memory for blocks, in MiB (128 by default) |
| `--verify` | `bench` only: compare a read against the SDK's own download |
| `--throughput-mib N` | `bench` only: how much to read for the speed test (32 by default) |
| `--start SECONDS` | `play` only: start at this position |
| `--headless` | `play` only: decode with no window and no sound |
| `--for-seconds S` | `play` only: stop after this many seconds |
## Environment variables
| Variable | Does |
|---|---|
| `RUST_LOG` | How much both programs log to the terminal, for example `RUST_LOG=debug` |
| `PSTR_FRAME_CAP` | The app's frame rate limit on Wayland. 60 by default; `0` turns it off. |
+75
View File
@@ -0,0 +1,75 @@
# FAQ
## Is this an official Proton app?
No. It is an unofficial, open-source client written by one developer. Proton AG has not reviewed,
endorsed or supported it. "Proton" and "Proton Drive" are Proton AG's trademarks.
## Do I need a Proton account?
No, not to watch a public share link. You need one to add folders of your own Drive and to sync
your place across devices. See [Account and sync](ACCOUNT_AND_SYNC.md).
## Does it download the whole file before playing?
No. Proton Drive stores a file as blocks that each decrypt on their own, so the app fetches only
the blocks around the point you are watching. A seek fetches the block it lands on. On a
26-minute 1080p episode the first frame takes about 2.3 seconds.
## Does it transcode?
No. The video plays as it is stored, through libmpv. HEVC 10-bit, HDR and ASS subtitles all work,
with hardware decoding where the device has it.
## Subtitles are hard to read. Can I change them?
Yes. In **Settings → Subtitles** you can set the size, position, font, colours, outline, box,
shadow and blur. A **Box** background is easiest to read on bright scenes. Styled subtitles (ASS)
keep the look, size and place their makers gave them, unless you turn on **Restyle styled
subtitles**.
## The subtitles are early or late.
Press **Z** to show them 0.1 s earlier and **X** to show them later, or use **Delay** in the
player's subtitle menu. The delay holds for the file you are watching only.
## Does it provide any videos?
No. It plays what you keep in Proton Drive or what someone shares with you. It has no catalogue,
no search of other people's shares and no content of its own.
## Why are there no posters?
Posters and descriptions are off by default, because looking them up sends your title names to
AniList or TMDB. Turn them on in **Settings → Posters and descriptions**. See
[Privacy](PRIVACY.md).
## A title is matched to the wrong show. How do I fix it?
Open the title and choose **Match…** (or **Change match**). Search for the right entry and pick
it. A match you pick is never replaced, and it syncs to your other devices.
## The episodes of one show appear as separate titles.
The app takes the show's name from its folder. Put every episode of a show in one folder, or in
season folders below it. [How the library reads your
folders](USER_GUIDE.md#how-the-library-reads-your-folders) has examples.
## Can several people share one library?
Yes. Send them the same share link. Each person's app keeps its own watch history; sync only
connects devices that sign in to the same Proton account.
## Is there a macOS version?
Not as a release. The app builds and runs on macOS from source, and `scripts/build.sh` can make a
`.app` and a `.dmg` on a Mac, but no release ships one yet.
## Can I cast to a TV?
Not yet. On an Android TV, install the APK and run the app on the TV itself.
## Where do I report a bug?
Open an issue on [GitHub](https://github.com/narrrl/proton-stream/issues). Say which platform
and version you use, and what you did.
+66
View File
@@ -0,0 +1,66 @@
# Getting started
This page takes you from nothing to a playing episode. It takes a few minutes.
## 1. Install the app
Download the package for your system from the
[latest release](https://github.com/narrrl/proton-stream/releases/latest) and install it.
[Installation](INSTALL.md) has the commands for each platform.
## 2. Add a share
A *share* is a folder the app reads videos from. There are two kinds:
- **A public share link.** Someone sends you a Proton Drive link such as
`https://drive.proton.me/urls/ABC123#xyz`. You need no Proton account for this.
- **A folder of your own Drive.** Sign in to your Proton account, then pick a folder. See
[Account and sync](ACCOUNT_AND_SYNC.md).
To add a public link on the desktop:
1. Copy the whole link, including the part after `#`. That part is the key that decrypts the
share, so the link does not work without it.
2. Open the **Shares** page, or press **Ctrl+V** anywhere outside a text field.
3. Paste the link into **Link**.
4. If the person who shared it set a password of their own, turn on **The link asks for a
password** and type it.
5. Click **Add share**.
The app opens the link to check it before it saves anything. If the link is wrong, it tells you
why and stores nothing.
On Android and iOS, tap **Add share** on the **Shares** tab. On Android you can also share the
link to the app from your browser. [Android and iOS](MOBILE.md) has the details.
## 3. Wait for the library to fill
The app reads the share's folders. This is called a *crawl*. Titles appear in the **Library** as
they are found. A large share takes a minute or two.
The folder layout decides how titles are grouped. Each show should have its own folder:
```text
Sousou no Frieren/
Season 01/
S01E01.mkv
S01E02.mkv
Paprika (2006).mkv
```
A file without episode numbers is shown as a film. [How the library reads your
folders](USER_GUIDE.md#how-the-library-reads-your-folders) has the full rules.
## 4. Press play
Open a title and click **Play**. The episode starts in a few seconds, and you can drag the seek
bar to any point. The app remembers where you stopped, so **Resume** takes you back.
## Next steps
- **Posters and descriptions.** Turn them on in **Settings → Posters and descriptions**. They are
off by default, because the app then sends your title names to AniList or TMDB. See
[Privacy](PRIVACY.md).
- **Your place on every device.** Sign in to Proton on each device, and your position in every
episode follows you. See [Account and sync](ACCOUNT_AND_SYNC.md).
- **Keyboard.** Press **?** on the desktop for the list of shortcuts.
+123
View File
@@ -0,0 +1,123 @@
# Installation
Every [release](https://github.com/narrrl/proton-stream/releases/latest) has packages for Linux
and Windows, an APK for Android and an IPA for iOS, plus a `SHA256SUMS` file to check them
against. The version is part of each file name.
| Platform | File | Needs |
|---|---|---|
| Debian, Ubuntu | `proton-stream_<version>-1_amd64.deb` | x86_64 |
| Fedora | `proton-stream-<version>-1.x86_64.rpm` | x86_64 |
| Other Linux | `proton-stream-<version>-x86_64-unknown-linux-gnu.tar.gz` | x86_64, libmpv 2 |
| Arch Linux | Built from the repository with `makepkg` | |
| Windows | `proton-stream-<version>-x64.msi` or `…-x86_64-windows.zip` | x64 |
| Android, Android TV | `proton-stream-<version>-android.apk` | Android 12 or newer, arm64 or x86_64 |
| iOS, iPadOS | `proton-stream-<version>-ios.ipa` | iOS 17 or newer, SideStore or AltStore |
## Linux
The desktop app needs libmpv, WebKitGTK 4.1 (for the CAPTCHA window when you sign in) and a
Secret Service keyring such as GNOME Keyring or KWallet. The packages pull in everything except
the keyring, which most desktops already have.
### Debian and Ubuntu
Download the `.deb`, then:
```bash
sudo apt install ./proton-stream_*_amd64.deb
```
### Fedora
Download the `.rpm`, then:
```bash
sudo dnf install ./proton-stream-*.x86_64.rpm
```
### Arch Linux
The `PKGBUILD` in `packaging/` builds the checkout it sits in. It needs network access, so cargo
can fetch crates:
```bash
git clone https://github.com/narrrl/proton-stream.git
cd proton-stream/packaging
makepkg -si
```
### Other distributions
Unpack the tarball anywhere. It holds `proton-stream` (the app), `pstr` (the
[command line](CLI.md)) and the icon. Install libmpv 2 and WebKitGTK 4.1 from your
distribution first.
Both packages install:
- `/usr/bin/proton-stream`, the app, listed as **Proton Stream** in your applications menu
- `/usr/bin/pstr`, the command line
## Windows
Download either file from the release:
- **The `.msi` installer** installs to `Program Files\Proton Stream`, adds a Start menu entry
and puts `pstr` on the PATH.
- **The portable `.zip`** runs from any folder. Keep every file in it together: the app does not
start without `libmpv-2.dll` and `WebView2Loader.dll` beside it.
The binaries are not code-signed yet, so SmartScreen may warn the first time. Choose **More
info**, then **Run anyway**. The sign-in window uses the WebView2 runtime that comes with Windows
10 and 11.
## Android and Android TV
1. Download `proton-stream-<version>-android.apk` on the device.
2. Open it. Android asks once to allow installs from your browser or file manager.
3. Install.
The APK is signed, so later versions install over it and keep your library. On Android TV the app
appears in the launcher; installing needs a file manager or `adb install`.
## iOS and iPadOS
The `.ipa` is unsigned. [SideStore](https://sidestore.io) or [AltStore](https://altstore.io)
signs it with your own Apple ID when it installs:
1. Install SideStore or AltStore by following its own guide.
2. Download `proton-stream-<version>-ios.ipa`.
3. Open it with SideStore or AltStore.
A free Apple ID has to refresh the app every 7 days. SideStore and AltStore do that for you.
## Updating
Install the new release over the old one. Your shares, library, watch history and settings stay.
The app does not check for updates by itself; watch the
[releases](https://github.com/narrrl/proton-stream/releases) on GitHub.
## Uninstalling
Remove the package the way you installed it, for example `sudo apt remove proton-stream`.
This leaves your data behind. To remove that too:
1. In the app, remove each share on the **Shares** page. This deletes its link and password
from the keyring and its downloads from the disk.
2. Sign out on the **Shares** page, if you signed in.
3. Delete the app's folders, listed in [Privacy](PRIVACY.md#what-stays-on-your-device).
On Android and iOS, uninstalling the app deletes everything it stored.
## Building from source
Rust 1.96 or newer, plus the libmpv (≥ 2.0) development headers, and WebKitGTK 4.1's on Linux:
```bash
git clone https://github.com/narrrl/proton-stream.git
cd proton-stream
cargo build --release
```
[Development](DEVELOPMENT.md) and `packaging/README.md` have the details, including Windows, the
Android toolchain and iOS builds on macOS.
+8 -2
View File
@@ -160,6 +160,14 @@ same facts, tags and franchise row as the desktop's; *Title names* is in
Settings → Appearance. Android's grid is always covers, so it has no
*Library tiles* choice.
**Folders of films.** `pstr_core::catalog::build_rows` gives each file in a
folder of films its own title, so the four Rebuild films in one folder are
four entries, matched one by one, and the franchise folds them back into one
tile. Only when no file is numbered, none sits under `Movies`/`OVA`, and each
names itself differently from the others and from the folder; anything less
is a series with its specials. A film's version number (`1.11`) is not part of its name on
AniList, so a search that finds nothing is asked again without it.
Not done: TMDB fills no details.
## Phase 3 — reach
@@ -168,7 +176,5 @@ Not done: TMDB fills no details.
machine.
- **Routing by title**: AniList first, then TMDB (with a key) or TVmaze for
whatever is not anime — Game of Thrones in a mostly-anime share.
- **Folders of films** matched per file: four Rebuild films in one folder are
four entries, not one.
- **Skip intro** from AniSkip for files without chapters, and filler flags from
Jikan.
+84
View File
@@ -0,0 +1,84 @@
# Android and iOS
The Android and iOS apps share the desktop app's engine, so a library, its watch history and its
settings behave the same everywhere. This page covers what is different on a phone, a tablet and
a TV. [Installation](INSTALL.md) explains how to install each one.
<table>
<tr>
<td><img src="../images/android-home.png" alt="Home" width="200"></td>
<td><img src="../images/android-library.png" alt="All titles" width="200"></td>
<td><img src="../images/android-title.png" alt="A title page" width="200"></td>
<td><img src="../images/android-episodes.png" alt="Episodes and downloads" width="200"></td>
</tr>
</table>
## Adding a share
Tap **Add share** on the **Shares** tab, paste the link, and add a custom password if the link has
one. The app checks the link before it saves it.
- **Android:** you can also share a link to the app from your browser or a chat app, or open a
`drive.proton.me/urls/…` link directly if you allow the app to open supported links in the
system settings.
- **iOS:** there is no share sheet. Copy the link, then tap **Paste link** in the dialog.
Folders of your own Drive work as on the desktop: sign in on the **Shares** tab, then **Add from
your Drive**. See [Account and sync](ACCOUNT_AND_SYNC.md).
## The player
- Tap to show or hide the controls.
- **Double-tap** the left or right third of the screen to go back or forward 10 seconds. Double-tap
the middle to pause.
- The menu has **Episodes**, **Chapters**, **Playback speed**, the audio and subtitle tracks, and
**Lock to landscape**.
- Sound keeps playing with the screen off or the app in the background, with controls on the lock
screen. Turn off **Background audio** in Settings to stop that.
Picture-in-Picture is not available on either platform.
## Android TV
The app appears in the TV launcher. With the controls hidden:
| Remote | Does |
|---|---|
| Left / right | Back or forward 10 seconds |
| Centre, up or down | Show the controls |
| Play/pause | Pause and play |
There is no separate TV layout yet, and the app has not been tested on a real TV. Reports are
welcome.
## Downloads
Download an episode, a season or a show from its title page, and play it from the **Downloads**
tab without a connection.
- **Android** waits for Wi-Fi unless you turn off **Download on Wi-Fi only**. Downloads continue
with the app closed.
- **iOS** downloads only while the app is open, and for the short time iOS allows after you leave
it. A stopped download resumes where it stopped.
**Delete all offline episodes** in Settings frees the space in one step.
## New episodes
When a share gains episodes of a show, the app sends a notification.
- **Android** checks about every 6 hours, when the device has a network and the battery is not
low. Turn it off with **New episode notifications** in Settings.
- **iOS** asks the system to check every 6 hours or so; iOS decides when it actually runs.
## Where your secrets are kept
- **Android:** in the app's private storage, encrypted with a key in the Android Keystore. If you
change or remove the device's screen lock, Android may delete that key. The app then asks you
to **Re-enter link** for each share.
- **iOS:** in the Keychain, only on this device, and not in backups.
## Requirements
- **Android 12** or newer, on an arm64 or x86_64 device. 32-bit devices are not supported.
- **iOS 17** or newer, on iPhone or iPad.
+69
View File
@@ -0,0 +1,69 @@
# Privacy
proton-stream has no server and no account with its developer. Each app talks to Proton directly,
and to nothing else unless you turn on posters and descriptions. This page lists what goes where.
## What the app sends, and to whom
| To | What | When |
|---|---|---|
| Proton | Requests for the shares you added and, if you signed in, your account's Drive | Always |
| AniList and ani.zip, or TMDB | The names of the titles in your library, and the ids of matched titles | Only with **Posters and descriptions** on |
Nothing else leaves your device. There is no telemetry, no crash reporting and no update check.
**Posters and descriptions** are off by default. When they are on, the provider learns the names
of the titles in your library. It does not learn your files, your watch history or your shares.
Turning them off deletes every stored answer.
## Secrets
- **The part of a share link after `#`** is the key that decrypts the share. The app treats it as
a password.
- **A link's own password**, if it has one.
- **Your Proton session**, if you signed in. The app keeps the session, not your password.
All of these go into the system's credential store, never into a config file:
| Platform | Store |
|---|---|
| Linux | Secret Service (GNOME Keyring, KWallet, KeePassXC) |
| Windows | Credential Manager |
| Android | App storage, encrypted with a key in the Android Keystore |
| iOS | Keychain, this device only |
If you sign in, your shares, with their links and passwords, also sync through your own Drive.
Like every file there, they are end-to-end encrypted. See [Account and sync](ACCOUNT_AND_SYNC.md).
## How the player gets the video
The player is fed through a callback inside the app's own process. There is no local web server,
so there is no port another program on the computer could ask for the decrypted video. The
player is handed an opaque token, not a link, so no secret ends up in its log or window title.
## What stays on your device
| What | Where on Linux |
|---|---|
| Settings and the share list (without secrets) | `~/.config/proton-stream/` |
| The library and watch history (`catalog.db`) and downloads (`offline/`) | `~/.local/share/proton-stream/` |
| Streamed video (`blocks/`), thumbnails and posters | `~/.cache/proton-stream/` |
On Windows the same folders are under `%APPDATA%\narl\proton-stream\` and
`%LOCALAPPDATA%\narl\proton-stream\`. On macOS they are under `~/Library/Application Support/`
and `~/Library/Caches/`, in `io.narl.proton-stream`.
**The streaming cache and downloads hold decrypted video.** Anyone who can read your user's files
can play them. Empty the cache in **Settings → Storage**, and delete downloads on the
**Downloads** page.
The library database holds file names and your watch history, in plain text. It holds no
secrets.
## Other people on the same computer
- A share link given on the command line, as in `proton-stream 'https://…#key'`, is visible in
the process list while the command runs, and may land in your shell history. Paste links into
the window instead.
- Your desktop's media controls are given the title, the episode and a picture already on disk.
They are never given a provider link, so the desktop does not contact a provider by itself.
+41
View File
@@ -0,0 +1,41 @@
# proton-stream documentation
proton-stream turns the videos in your Proton Drive, and the share links people send you, into
a library you can browse and stream. It runs on Linux, Windows, Android, Android TV and iOS.
This is an unofficial client, not a Proton product.
<img src="../images/desktop-home.png" alt="The library in the desktop app" width="820">
## Start here
- [Getting started](GETTING_STARTED.md): install, add your first share, press play.
- [Installation](INSTALL.md): every platform, and how to update and uninstall.
- [FAQ](FAQ.md): short answers to the questions people ask first.
## Using it
- [User guide](USER_GUIDE.md): the library, title pages, the player, downloads, history and
settings.
- [Account and sync](ACCOUNT_AND_SYNC.md): signing in, folders of your own Drive, and keeping
your place on every device.
- [Android and iOS](MOBILE.md): what is different on a phone, a tablet and Android TV.
## Reference
- [Command-line reference](CLI.md): the `pstr` tool and the `proton-stream` launcher.
- [Privacy](PRIVACY.md): what goes where, and what stays on your device.
## When something goes wrong
- [Troubleshooting](TROUBLESHOOTING.md): links that will not add, sign-in problems, playback
problems, and where the logs are.
## Contributing
- [Development](DEVELOPMENT.md): the state of each layer, the build order and the traps.
- [Architecture](ARCHITECTURE.md): the crates, the data flow when an episode plays, and where
secrets live.
- [Testing](TESTING.md), [Metadata](METADATA.md), [Design tokens](DESIGN-TOKENS.md),
[Android development](ANDROID.md) and [iOS development](IOS.md).
Bugs are tracked in [BUGS.md](BUGS.md) in the repository.
+114
View File
@@ -0,0 +1,114 @@
# Troubleshooting
## Adding a share
### "Proton share URL has no #password fragment; copy the full share link"
The link is missing the part after `#`, which is its decryption key. Copy the link again from
where you got it, all of it.
### "This link has a password of its own. Enter it to add the link."
The person who shared it also set a password. Turn on **The link asks for a password** (on a
phone, fill in **Custom password**) and type it.
### "That share is already added."
The link, or the same folder of your Drive, is already on the **Shares** page.
### "Last crawl failed: …"
The share could not be read. The link may have expired or been revoked, or its password
changed. If the password changed, choose **Re-enter link**.
## The keyring
### "share … has no stored credentials; remove and re-add it"
The link and password are gone from the keyring. This happens when a keyring is reset, or on
Android when the screen lock changes. Choose **Re-enter link** on the **Shares** page. Your
library, history and downloads stay.
### "credential store: …" on Linux
The app found no Secret Service. Install and start one, such as GNOME Keyring, KWallet or
KeePassXC with its Secret Service integration, and unlock it.
## Signing in
### "Proton did not accept that address and password"
Check both. Sign in on proton.me to make sure the account works.
### "Proton has blocked sign-ins from this app for now"
Proton's abuse protection stopped the sign-in. Wait a while and try again, or sign in once on
proton.me first.
### "This account's only second factor is a security key"
The app cannot use security keys yet. Add an authenticator app as a second method in your
Proton account settings, then sign in with its code.
### The CAPTCHA window does not open on Linux
The window needs WebKitGTK 4.1. The `.deb`, `.rpm` and Arch packages pull it in; with the
tarball, install it yourself.
### `pstr login` asks for a CAPTCHA
The command line cannot show one. Sign in once in the app.
## Playback
### Green blocks, a black picture or torn frames
Turn off **Hardware decoding** in Settings. It applies from the next file.
### An episode takes long to start
The first seconds of a file are fetched over the network. On a slow connection, start the
episode and give it a moment, or download it first. A second viewing comes from the disk cache.
### No skip button for the opening
The skip button comes from the file's chapter names. A file without named chapters gets none.
### The wrong subtitle track plays
Choose the track in the player. The app remembers it for the rest of the show. Set the
language to start in under **Settings → Playback**.
## Windows
### The app does not start from the portable `.zip`
Keep every file from the archive in one folder. The app needs `libmpv-2.dll` and
`WebView2Loader.dll` next to `proton-stream.exe`.
### SmartScreen warns about the installer
The binaries are not code-signed yet. Choose **More info**, then **Run anyway**.
### A pinned taskbar icon shows a blank picture after an update
Unpin it and pin it again once.
## Linux
### "Not responding" when the window is on another workspace
Fixed. On Wayland the app limits its own frame rate instead of waiting for vsync, which a
compositor withholds from a window it is not showing. Update to the latest release.
## Logs
Start the app from a terminal to see its log:
```bash
RUST_LOG=debug proton-stream
```
The same works for `pstr`. When you
[open an issue](https://github.com/narrrl/proton-stream/issues), include the lines around the
error, but **remove any share link first**: the part after `#` is a key.
+222
View File
@@ -0,0 +1,222 @@
# User guide
This page describes the desktop app. The Android and iOS apps have the same pages as tabs at the
bottom of the screen; [Android and iOS](MOBILE.md) covers what is different there.
The app has five pages, in the bar at the top: **Library**, **History**, **Shares**,
**Downloads** and **Settings**. **Ctrl+1** to **Ctrl+5** open them.
## Library
<img src="../images/desktop-library.png" alt="The whole library, filtered and sorted" width="820">
The library shows every title from every share in one place. Two shares that hold the same show
show it once.
- **The banner** at the top shows the title you watched last, with **Resume** and **More info**.
- **Continue watching** has the episode you stopped in for each show, or the next one when you
finished an episode. To take a show off this row, right-click it and choose **Remove from
Continue watching**.
- **Shelves** such as **Airing now**, **Directed by Satoshi Kon** or **From MADHOUSE** appear when
posters and descriptions are on. The app shows at most four, and only for a director, studio or
genre with at least three titles.
- **All titles** is the full grid. Choose a filter and a sort order above it.
| Filters | Sort orders |
|---|---|
| All, Series, Films, Watching, Not started, Downloaded | A – Z, Recently watched, Recently added, Newest, Highest rated, Most popular |
**Group franchises** folds a series, its sequels and its films into one tile with a **+N** badge.
It is on by default, and needs posters and descriptions to know what belongs together.
**Search** with **Ctrl+F** or **/**. It matches every name a title has: the English one, the
romaji one and the name of its folder.
**Refresh** (or **F5**) reads every share again. The app also does this by itself when a share
has not been read for 6 hours.
### How the library reads your folders
The folder decides which show a file belongs to. The file name gives the season and episode.
| Layout | Read as |
|---|---|
| `Frieren/Season 01/S01E05.mkv` | Frieren, season 1, episode 5 |
| `Frieren/S01E05 - The Hero's Statue.mkv` | The same, with the episode title |
| `Bocchi the Rock/[Group] Bocchi the Rock - 07 [1080p].mkv` | Bocchi the Rock, episode 7 |
| `Spy x Family/Season 2 - 06.mkv` | Spy x Family, season 2, episode 6 |
| `Akira (1988).mkv` | A film, from 1988 |
| `Rebuild of Evangelion/Evangelion - 1.11 You Are (Not) Alone.mkv` and three more | Four films, one title each |
- Season folders can be called `Season 01`, `Season 1`, `S01` or `3rd Season`.
- Folders such as `Specials`, `Extras`, `OVA`, `NCOP` or `Subs` are not taken as a show's name;
the folder above them is.
- An episode title is read only after a dash, as in `S01E01 - Name`.
- A file with no episode number is a film. A folder of such files, each with a different name, is
one title per film.
The app plays `mkv`, `mp4`, `m4v`, `avi`, `mov`, `webm`, `ts`, `m2ts` and most other common video
containers.
## A title's page
Click a title to open its page. **Esc** goes back.
- **Resume S01E03 · 12:04** continues where you stopped. **Start over** plays the episode from
the beginning.
- **Download show** keeps every episode on this device. See [Downloads](#downloads).
- **Match…** opens the matcher, where you choose which AniList or TMDB entry the title is. Use it
when the app guessed wrong or did not guess at all. A match you pick is never replaced.
- **More on AniList** (or TMDB) opens the title's page there.
- Each season has **Mark season watched** and **Download season**.
- Each episode shows a tick when you have watched it. Right-click an episode and choose **Mark
watched up to here** to tick it and every episode before it.
- **In this franchise** lists the other parts of the series, when posters and descriptions are on.
An episode counts as watched once you have seen 90% of it.
## The player
The picture plays inside the app's window. Move the mouse to show the controls.
- **Skip opening** and **Skip ending** appear when the file's chapters mark an opening, an ending
or a preview. Files without chapter names get no skip button. Turn on **Skip openings and
credits** in Settings to skip them without asking.
- **Up next** counts down 10 seconds when the credits start, then plays the next episode. Choose
**Play now**, **Cancel** or **Watch till the end**.
- **Subtitles and audio** are chosen from the buttons at the bottom right. The app remembers your
choice for each show. The subtitle menu also has **Size** and **Position**, which are saved like
the ones in Settings and change styled subtitles only when they are restyled, and **Delay**,
which moves subtitles earlier or later for this file only.
- **Speed** goes from 0.5× to 3×, and stays for the next episode.
### Keyboard
Press **?** anywhere to see this list in the app.
| Key | Anywhere |
|---|---|
| Ctrl+F or / | Search the library |
| F5 or Ctrl+R | Read every share again |
| Ctrl+1 – 5 | Library, History, Shares, Downloads, Settings |
| Ctrl+, | Settings |
| Ctrl+V | Paste a share link to add it |
| Tab or arrows | Move between titles and episodes |
| Enter | Open or play what is highlighted |
| Alt+← or mouse back | Back |
| Key | Playing |
|---|---|
| Space or K | Pause and play |
| ← / → | Back 10 s, forward 30 s |
| ↑ / ↓ | Volume |
| M | Mute |
| N / P | Next and previous episode |
| [ / ] | Slower and faster |
| S | Skip the opening or the credits |
| Z / X | Subtitles 0.1 s earlier and later |
| E | The list of episodes |
| F or double-click | Fullscreen |
| Ctrl+S | Save the frame to `Pictures/proton-stream` |
| Esc | Leave fullscreen, then the player |
Media keys and your desktop's media controls work too.
### Subtitle files beside the video
The app picks up `.srt`, `.ass`, `.ssa` and `.vtt` files next to a video:
```text
Frieren/Season 01/
S01E01.mkv
S01E01.en.srt English
S01E01.en.forced.ass English, "forced"
Subs/
S01E01/
2_English.srt English
```
A `Subs` folder beside the videos works, and so does any subtitle in a folder that holds a single
video. The language comes from the last word in the name that names one.
### Dialogue, not signs and songs
Many anime releases have two subtitle tracks in one language: the full dialogue, and a short
*Signs & Songs* track that only translates on-screen text. When a file would start on the short
track, the app switches to the full one in the same language.
## History
Everything you played, newest first, grouped by day. An entry says **Watched**, **Stopped at
12:04 of 24:00** or **Played**. Removing an entry marks a watched episode unwatched, or forgets
where you stopped in one you had not finished.
## Downloads
A download keeps a full copy of an episode on this device, to play without a connection. Start
one from a title's page: a whole show, a season or a single episode.
The **Downloads** page lists them with **Pause**, **Resume**, **Cancel**, **Retry**, **Play** and
**Delete**. Three run at a time. Downloads do not count against the streaming cache.
## Shares
The **Shares** page lists every share, with what it holds and when it was last read.
- **Crawl** reads the share again.
- **Rename** changes the name shown in the app.
- **Re-enter link** gives the app the link again, for a keyring that lost it or a password that
changed. The library, history and downloads stay.
- **Remove** takes the share's titles out of the library, deletes its downloads and removes its
link and password from the keyring.
The **Proton account** section on this page is where you sign in. See
[Account and sync](ACCOUNT_AND_SYNC.md).
## Settings
**Appearance**
- **Palette:** Proton (the near-black default), Catppuccin Latte, Frappé, Macchiato and Mocha, or
Persona 5.
- **Accent:** Mauve, Pink, Sky, Pink → Sky, Lavender, Blue, Teal, Peach or Red. **Gradient
accent** draws it as a gradient.
- **Text size:** 90% to 150%. This one stays on this computer.
- **Library tiles:** posters or stills. **Title names:** as in the share, English or romaji.
**Playback**
- **Audio language** and **Subtitles:** the language to start in, or the file's own default.
- **Play the next episode** (on by default) and **Skip openings and credits** (off).
- **Hardware decoding** (on). Turn it off if the picture shows green blocks or stays black.
**Subtitles**
How subtitles look. A sample line at the top shows the style on a bright and a dark picture, and
a video that is playing changes at once.
- **Size** and **Position**: how big the line is and how far up the picture it sits.
- **Font**, **Bold** and **Italic**: any font installed on this computer. On Linux the sample
line shows the font too; on Windows and macOS it is drawn in the app's own font, and only the
video uses the one you chose.
- **Text colour**, and a **Background** of **Outline** or **Box**, each with its own colour. A
colour's opacity sets how much of the picture shows through. Choose **Box** if text is hard to
read on bright scenes.
- **Shadow** and **Blur**.
- **Restyle styled subtitles** (off). Plain subtitles (SRT) always take the whole style. Styled
subtitles (ASS) keep the look, size and place their makers gave them unless this is on; they
only move up while the player's controls are showing. Turned on, signs and songs can come out
wrong.
- **Reset** goes back to the default look.
**Storage**
- **Streaming cache:** 1 to 16 GiB, 4 GiB by default. It keeps the parts of videos you streamed,
so watching again needs no network. **Clear the streaming cache** empties it.
**Posters and descriptions**
- Off by default. When it is on, the app sends the names of your titles to the provider you pick:
**AniList** (no key needed) or **TMDB** (needs a free API key). See [Privacy](PRIVACY.md).
- **Match the library** looks up new titles now. **Match everything again** looks up every title,
except those you matched by hand.
Binary file not shown.

After

Width:  |  Height:  |  Size: 653 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 MiB

+39
View File
@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="128" height="128" viewBox="0 0 128 128" fill="none" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="proton-stream">
<defs>
<linearGradient id="ps-face" x1="12" y1="12" x2="116" y2="112" gradientUnits="userSpaceOnUse">
<stop offset="0" stop-color="#A48BFF"/>
<stop offset="0.55" stop-color="#7552FF"/>
<stop offset="1" stop-color="#5B36F2"/>
</linearGradient>
<linearGradient id="ps-glyph" x1="0" y1="36" x2="0" y2="88" gradientUnits="userSpaceOnUse">
<stop offset="0" stop-color="#FFFFFF"/>
<stop offset="1" stop-color="#ECE6FF"/>
</linearGradient>
<!-- The play mark, cut into the blocks a revision is fetched in: each one
decrypts on its own, which is the whole reason this app can seek. -->
<mask id="ps-cut" maskUnits="userSpaceOnUse" x="0" y="0" width="128" height="128">
<path d="M50 41.5v41a6 6 0 0 0 9.1 5.1l34.2-20.5a6 6 0 0 0 0-10.3L59.1 36.4A6 6 0 0 0 50 41.5z" fill="#FFFFFF"/>
<g fill="#000000">
<rect x="63" y="0" width="5.5" height="128"/>
<rect x="78.5" y="0" width="5.5" height="128"/>
</g>
</mask>
</defs>
<!-- base: a rounded tile with a darker lower edge for depth -->
<rect x="12" y="16" width="104" height="100" rx="26" fill="#4424C0"/>
<rect x="12" y="12" width="104" height="100" rx="26" fill="url(#ps-face)"/>
<rect x="12.5" y="12.5" width="103" height="99" rx="25.5" stroke="#FFFFFF" stroke-opacity="0.2"/>
<!-- glyph shadow, then the glyph itself. The mark's box centres on x=73 and
its centroid on x=66; it sits at 70 -> 64, between the two, because the
box centre reads as too far left and the centroid as too far right. The
Android and iOS icons centre it the same way. -->
<g transform="translate(-6 0)">
<g transform="translate(0 3)">
<rect width="128" height="128" fill="#2E1596" fill-opacity="0.3" mask="url(#ps-cut)"/>
</g>
<rect width="128" height="128" fill="url(#ps-glyph)" mask="url(#ps-cut)"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.0 KiB

+1 -1
View File
@@ -14,7 +14,7 @@
# builds from the registry alone.
pkgname=proton-stream
pkgver=1.6.0
pkgver=1.7.0
pkgrel=1
pkgdesc="Netflix-style desktop client for Proton Drive public links: browse and stream a share"
arch=('x86_64')
+9 -4
View File
@@ -26,9 +26,14 @@
<rect x="12" y="12" width="104" height="100" rx="26" fill="url(#ps-face)"/>
<rect x="12.5" y="12.5" width="103" height="99" rx="25.5" stroke="#FFFFFF" stroke-opacity="0.2"/>
<!-- glyph shadow, then the glyph itself -->
<g transform="translate(0 3)">
<rect width="128" height="128" fill="#2E1596" fill-opacity="0.3" mask="url(#ps-cut)"/>
<!-- glyph shadow, then the glyph itself. The mark's box centres on x=73 and
its centroid on x=66; it sits at 70 -> 64, between the two, because the
box centre reads as too far left and the centroid as too far right. The
Android and iOS icons centre it the same way. -->
<g transform="translate(-6 0)">
<g transform="translate(0 3)">
<rect width="128" height="128" fill="#2E1596" fill-opacity="0.3" mask="url(#ps-cut)"/>
</g>
<rect width="128" height="128" fill="url(#ps-glyph)" mask="url(#ps-cut)"/>
</g>
<rect width="128" height="128" fill="url(#ps-glyph)" mask="url(#ps-cut)"/>
</svg>

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 364 KiB

After

Width:  |  Height:  |  Size: 364 KiB

+273
View File
@@ -0,0 +1,273 @@
#!/usr/bin/env bash
# Publish the documentation in docs/ to the GitHub wiki.
#
# The pages in docs/ are the source of truth; the wiki is a generated copy for
# people who look there first. Each run checks every link in docs/, clones the
# wiki, replaces all of its pages with the ones listed in SECTIONS below,
# rewrites links between them to wiki page names and every other repository
# link to an absolute GitHub URL, copies the images they show, writes the
# sidebar and footer, and commits. Nothing is pushed without --push.
#
# --check only checks the links and that every page in docs/ is listed or
# excluded, without touching the wiki. CI runs it for every change to docs/,
# and every push to main that passes it publishes.
#
# GitHub creates the wiki repository only when the first page is saved, so
# create any page once in the web UI before the first run. WIKI_REMOTE
# overrides the remote, which is how the workflow pushes with its token.
#
# usage: scripts/publish-wiki.sh [--check | --push] [WORKDIR]
set -euo pipefail
repo_url="https://github.com/narrrl/proton-stream"
wiki_remote="${WIKI_REMOTE:-git@github.com:narrrl/proton-stream.wiki.git}"
mode=commit
case "${1:-}" in
--check) mode=check; shift ;;
--push) mode=push; shift ;;
esac
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
workdir="${1:-$(mktemp -d)}"
wiki="$workdir/wiki"
if [ "$mode" = check ]; then
wiki="$workdir/check"
mkdir -p "$wiki"
elif [ -d "$wiki/.git" ]; then
git -C "$wiki" pull --ff-only --quiet
else
git clone --quiet "$wiki_remote" "$wiki"
fi
rev="$(git -C "$root" rev-parse --short HEAD)"
version="$(grep -m1 '^version' "$root/Cargo.toml" | cut -d'"' -f2)"
python3 - "$root" "$wiki" "$repo_url" "$version" "$rev" <<'EOF'
import pathlib
import re
import shutil
import sys
root, wiki, repo_url, version, rev = sys.argv[1:]
root = pathlib.Path(root)
wiki = pathlib.Path(wiki)
docs = root / "docs"
HOME = ("README.md", "Home")
# Sidebar sections: docs/ file -> wiki page name, in order.
SECTIONS = [
("Start here", [
("GETTING_STARTED.md", "Getting-Started"),
("INSTALL.md", "Installation"),
("FAQ.md", "FAQ"),
]),
("Using it", [
("USER_GUIDE.md", "User-Guide"),
("ACCOUNT_AND_SYNC.md", "Account-and-Sync"),
("MOBILE.md", "Android-and-iOS"),
]),
("Reference", [
("CLI.md", "Command-Line-Reference"),
("PRIVACY.md", "Privacy"),
]),
("When something goes wrong", [
("TROUBLESHOOTING.md", "Troubleshooting"),
]),
("Contributing", [
("DEVELOPMENT.md", "Development"),
("ARCHITECTURE.md", "Architecture"),
("TESTING.md", "Testing"),
("METADATA.md", "Metadata"),
("DESIGN-TOKENS.md", "Design-Tokens"),
("ANDROID.md", "Android-Development"),
("IOS.md", "iOS-Development"),
]),
]
# Too long or too internal for the wiki; links to them go to GitHub.
EXCLUDED = {"BUGS.md"}
# Files outside docs/ whose links are checked but not published.
CHECKED = ["README.md"]
PAGES = dict([HOME] + [page for _, pages in SECTIONS for page in pages])
images_url = f"https://raw.githubusercontent.com/wiki/{repo_url.removeprefix('https://github.com/')}"
LINK = re.compile(r"(\]\(|src=\")([^)\"\s]+)([)\"])")
FENCE = re.compile(r"^\s*(```|~~~)")
INLINE_CODE = re.compile(r"(`[^`\n]*`)")
HEADING = re.compile(r"^(#{1,6})\s+(.*?)\s*#*\s*$")
EXPLICIT_ID = re.compile(r"<a\s+id=\"([^\"]+)\"")
errors = []
images = set()
def outside_fences(text):
"""Yield (is_prose, chunk) so links in code blocks are left alone."""
chunk, fenced = [], False
for line in text.splitlines(keepends=True):
if FENCE.match(line):
if chunk:
yield not fenced, "".join(chunk)
chunk, fenced = [], not fenced
yield False, line
continue
chunk.append(line)
if chunk:
yield not fenced, "".join(chunk)
def slug(heading):
"""GitHub's anchor for a heading."""
text = re.sub(r"\[([^\]]*)\]\([^)]*\)", r"\1", heading)
return re.sub(r"[^\w\- ]", "", text.lower()).replace(" ", "-")
anchor_cache = {}
def anchors(path):
if path not in anchor_cache:
found, seen = set(), {}
for prose, chunk in outside_fences(path.read_text()):
if not prose:
continue
for line in chunk.splitlines():
found.update(EXPLICIT_ID.findall(line))
m = HEADING.match(line)
if not m:
continue
base = slug(m.group(2))
n = seen.get(base, 0)
seen[base] = n + 1
found.add(base if n == 0 else f"{base}-{n}")
anchor_cache[path] = found
return anchor_cache[path]
def rewrite(source, target):
"""The wiki form of one link in source, recording broken links."""
if re.match(r"^[a-z]+:", target):
return target
path, _, anchor = target.partition("#")
resolved = (source.parent / path).resolve() if path else source
where = f"{source.relative_to(root)}: {target}"
if not resolved.is_relative_to(root) or not resolved.exists():
errors.append(f"{where}: no such file")
return target
if anchor and resolved.suffix == ".md" and anchor not in anchors(resolved):
errors.append(f"{where}: no heading #{anchor}")
relative = resolved.relative_to(root)
anchor = f"#{anchor}" if anchor else ""
if not path:
return anchor
if relative.parent == pathlib.Path("docs") and relative.name in PAGES:
return PAGES[relative.name] + anchor
if relative.parts[0] == "images":
images.add(relative)
return f"{images_url}/{relative}"
kind = "tree" if resolved.is_dir() else "blob"
return f"{repo_url}/{kind}/main/{relative}{anchor}"
def convert(source):
out = []
for prose, chunk in outside_fences(source.read_text()):
if prose:
# Odd pieces are `inline code`, which is left alone too.
pieces = INLINE_CODE.split(chunk)
pieces[::2] = [
LINK.sub(lambda m: m.group(1) + rewrite(source, m.group(2)) + m.group(3), p)
for p in pieces[::2]
]
chunk = "".join(pieces)
out.append(chunk)
return "".join(out)
def title(source):
return (docs / source).read_text().splitlines()[0].lstrip("# ").strip()
def without_title(text):
lines = text.splitlines(keepends=True)
if lines and lines[0].startswith("# "):
lines = lines[1:]
while lines and not lines[0].strip():
lines = lines[1:]
return "".join(lines)
for name in sorted(p.name for p in docs.glob("*.md")):
if name not in PAGES and name not in EXCLUDED:
errors.append(f"docs/{name}: add it to SECTIONS or EXCLUDED in scripts/publish-wiki.sh")
converted = {source: convert(docs / source) for source in PAGES}
published_images = set(images)
for name in CHECKED:
convert(root / name)
if errors:
print("Broken documentation links:", file=sys.stderr)
for error in errors:
print(f" {error}", file=sys.stderr)
sys.exit(1)
# The wiki is generated: anything not written below is stale.
for old in wiki.glob("*.md"):
old.unlink()
shutil.rmtree(wiki / "images", ignore_errors=True)
note = (
"<!-- Generated from docs/ in the repository by scripts/publish-wiki.sh."
" Edit the source there; changes made here are overwritten. -->\n\n"
)
for source, page in PAGES.items():
(wiki / f"{page}.md").write_text(note + without_title(converted[source]))
for image in published_images:
(wiki / image).parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(root / image, wiki / image)
sidebar = ["**[Home](Home)**\n"]
for section, pages in SECTIONS:
sidebar.append(f"\n**{section}**\n\n")
sidebar += [f"- [{title(source)}]({page})\n" for source, page in pages]
sidebar += [
"\n---\n\n",
f"[Releases]({repo_url}/releases) · [Issues]({repo_url}/issues)\n",
]
(wiki / "_Sidebar.md").write_text(note + "".join(sidebar))
(wiki / "_Footer.md").write_text(
note
+ f"Documentation of proton-stream {version}, generated from "
+ f"[`docs/`]({repo_url}/tree/{rev}/docs) at `{rev}`. "
+ f"To change a page, edit it in the [repository]({repo_url}).\n"
)
EOF
if [ "$mode" = check ]; then
echo "Documentation links are fine."
exit 0
fi
cd "$wiki"
git add -A
if git diff --cached --quiet; then
echo "Wiki is already up to date."
exit 0
fi
git commit --quiet -m "Update from docs at $rev"
git show --stat --format='%s' HEAD
if [ "$mode" = push ]; then
git push --quiet
echo "Pushed to the wiki."
else
echo "Committed in $wiki. Review it, then push from there or re-run with --push."
fi